Pages

SPONSORED

Custom Entity Classes

There are too many discussions on multiple sites on why custom entities, custom entites vs data sets etc. In my view every solution has its own advantages and disadvantages. However in this blog, i prefer to discuss on custom entities and i speak in favour of custom entities.

What are custom Entities?
Custom entities are objects, just like some other objects which represent the business domain. They map the data to our application business. If i have to explain in simple .Net terms, custom entities are classes which have properties. This is typically used in n tier architecture.

For example, if we are developing an application on online shopping we can have entity like product which becomes our class. It can have properties like product name, cost, discount, size, weight etc.

'Visual Basic .NET
Public Class Product
#Region "Fields and Properties"
 Private _weight As Integer
 Private _productName As String
 Private _size As Integer
 Public Property Size() As Integer
  Get
   Return _size
  End Get
  Set(ByVal Value As Integer)
    _size = Value
  End Set
 End Property
 Public Property ProductName() As String
  Get
   Return _productName
  End Get
  Set(ByVal Value As String)
   _productName = Value
  End Set
 End Property
 Public Property Weight() As Integer
  Get
   Return _weight
  End Get
  Set(ByVal Value As Integer)
   _weight = Value
  End Set
 End Property
#End Region

#Region "Constructors"
 Public Sub New()
 End Sub
 Public Sub New( name As String, size As Integer, weight as Integer)
  Me.ProductName = name
  Me.Size = size
  Me.Weight = weight
 End Sub
#End Region
End Class

Why Custom Entities?
Custom entities are -

·         Object oriented. DataSets are not object oriented. We cannot add functionality to it. For example, if we need to change the format of some string before displaying on the screen, we will need to do it every time we display. If we use custom entity we can do this in the setter of the corresponding property.
·         More maintainable. Datasets lack abstraction which means they are tightly coupled with data model. If we use them in presentation layer and column definition changes from back end we will need to make changes to all our layers. This makes enhancements and bug fix difficult.
·         Strongly Typed. What i mean is, they are detected during compile time as we will have the entity class defined with us. DataSets are weakly types and any errors in them are detected only during run time.
·         More Secure. If we are sharing our API with any third party developers, it is better we do not expose our underlying structure. Custom Entity hide our data model and show only the business view of it. Hence it is mostly preferred when we have web services. Another point to note here is that the datasets are not optimised on serialization as well.
·         Developer Friendly. Custom Entities will get the help if intellisense and become easier to code. We don’t even need to track the column index or names, all are business friendly.

Decision to use custom entity or datasets should not be based on the theoretical concepts we read. Multiple factors must be considered like memory available, objects created etc. No design can be tagged good or bad. Good design is the one which considers all the functional and non functional aspects around the application.

Dynamic HTML (DHTML)

DHTML, Dynamic HTML sounds like extension to HTML. It isn’t just DHTML; DHTML is not a language, it is a technology. It is collection of JavaScript, CSS and DOM technologies. HTML creates static web pages. Static means the pages remain constant throughout. HTML pages can still be made dynamic with the help of server side scripts or AJAX. However this is on request response basis.

Does this mean that it is possible to create dynamic pages without using request response technique? Yes, using DHML. DHTML helps in creating dynamic pages after that page is fully loaded. It can alter the page when the user is viewing the page. The scripting language associated with it (JavaScript) alters the variables and changes the content on the page and makes it dynamic. DHTML controls HTML codes and commands. This feature of DHML has made it helpful in creating interactive and animated web pages.

Example:
<html>
<head>
<script language="javascript">
function changeText(){
document.getElementById("test").value ="DHTML example..."
}
</script>
</head>
<body>
<input type="button" id="test" value="   Click Here  " onClick="changeText()" />
</body>
</html>


By now you would have realised that this not something new! You have been using it in your day-to-day coding. We generally call it client side coding, it collectively referred as DTHML in technical language.

Ajax is one step ahead of this. It is DHTML plus server side call. Concept still remains the same, we dynamically create pages but with a call to server. I will not get into details of Ajax as it not in scope of this post.

Epoch Time

Epoch time is the number of seconds elapsed since January 1, 1970. This is also called as UNIX time or POSIX time. It is widely used in UNIX operation system.

Epoch time is 0 at 00:00:00 1/1/1970. This number is simply increments by 1 every second, without bothering about week, month and year. It is stored as 32 bit unsigned integer and hence can cover 136 years totally. This means it reaches its dead end in year 2038. It causes overflow after that particular date. I read on wiki site that the overflow occurs at one second after 03:14:00 1/19/2038.


Why 1/1/1970?

All this research of representing time in UNIX was carried out in early 1970s. They had to set epoch time as some time in the recent past and hence 1/1/1970 00:00:00 was set as epoch time. The number 0 is also called as epoch.

Epoch time to regular time and vice versa

Now that we know we have something called epoch time and why did it come into existence. The following table shows how to calculate epoch time from regular time and vice versa. We also have ways to calculate current time here.

Regular time to epoch

Java
long epoch = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse("01/01/1970 01:00:00").getTime() / 1000;
VBScript/ASP
DateDiff("s", "01/01/1970 00:00:00", time field)
SQL Server
SELECT DATEDIFF(s, '1970-01-01 00:00:00', time field)



Epoch to regular time

Java
String date = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new java.util.Date (epoch*1000));
VBScript/ASP
DateAdd("s", epoch, "01/01/1970 00:00:00")
SQL Server
DATEADD(s, epoch, '1970-01-01 00:00:00')



Get current time in epoch
Java
long epoch = System.currentTimeMillis()/1000;
Microsoft .NET C#
epoch = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
VBScript/ASP
DateDiff("s", "01/01/1970 00:00:00", Now())
SQL Server
SELECT DATEDIFF(s, '1970-01-01 00:00:00', GETUTCDATE())
JavaScript
Math.round(new Date().getTime()/1000.0) getTime() returns time in milliseconds.


CSS Expressions in IE8 and higher

Microsoft has finally decided to do away with Dynamic properties or CSS Expression from IE version 8. This means that our tricks to make certain conditions work cannot be applied any more in IE versions 8 and above.

Why was it removed?

1.   We have already discussed that it is slow and affects performance in our previous post Expressions in CSS. IE had to get rid of this feature to make the content render and process faster to avoid user inconvenience.
2.   CSS Expressions work only in IE as they are Microsoft proprietary. This makes it difficult for the developers to when it comes to developing pages which needs to be cross browser compatible. Microsoft had to bring in standard compliance.
3.   As we have expressions in css evaluating all the while, it can give way for the ajax hackers by allowing script injection attacks.CSS expressions were removed keeping in mind the security reasons.

Now we will not be able to use expressions via JavaScript as well. The methods getExpression, recalc, removeExpression, setExpression worked on IE 5 and above but is not being recognised on IE8

How do we work on IE8?

Expressions we being written to overcome CSS bugs. IE 8 will be able to interpret the properties to work in standard, interoperable way. Hence we can continue working on IE in the same way we work with other browsers.

This makes IE 8 more standard, faster and secure for the users.

img tag in HTML

img tag is used to display images on html pages.

<img src="Dog-2.jpg" alt="Dog" height="200px" />

The above tag expects that the image is present in the same folder where our html page lies. We can also place the image in separate folder, but in that case we need to specify the path of the image.

alt
The text specified the alt attribute will be displayed in case the browser is not able to display the image specified.

height and width
Specifying the height and width becomes important on displaying an image on the browser. This helps to place the image in the expected position on the screen. If dimensions are not specified it will take the size of original image. This might not fit into our screen design. Moreover the size of the image will also add to our download size. In case we have slow internet connection, this might pose a problem as the page might take longer to load the page and can be frustrating for the user.

src
We have already discussed that the src attribute specifies the path of the image. We can also dynamically specify the path of the image. For example if we are displaying a page having students profile. The image of the student must be that of the logged in student. This can be achieved using JavaScript as follows:

var DogImage = document.getElementById (“imgDog”);
DogImage.src=” Dog-2.jpg”

An img tag with id imgDog must be present on the html page.

src=”” issue
Having src attribute blank for img tag can be bad for your site. When src is blank IE will search for the image in the root folder. Entire root folder will be browsed for the image. When the page is requested, the page gets loaded from the server. As the page renders the browser realises that there is blank src attribute in the image. IT makes another request to the server to fetch the image from the root folder.
This can be problematic. This will increase the traffic as there are 2 requests sent. If your site is rarely access it may not get noticed. However if your site is viewed by large number of users, doubling the traffic for the page for every user will increase the load on the server.

The same effect is observed if src attribute is left blank via JavaScript.

var DogImage = document.getElementById (“imgDog”);
DogImage.src=””
In such cases we need to have img tag without specifying the src tag as shown below.

<img alt=”DOG” />

All we can do is make sure that you don’t leave the src attribute blank in any case. Just adjust you logic keeping this in mind to implement the requirements.

I recently read in some article that this issue has been addressed in HTML5. Hopefully we will not have any such issues in future.

Expressions in CSS

CSS Expressions, also called Dynamic properties are used to assign CSS code with calculated and dynamic values. CSS Expressions are JavaScript embedded within CSS. They are completely JavaScript dependent. Values are assigned to CSS code through JavaScript calculations during run time.  

<DIV ID="myDiv"
  STYLE="left:expression(document.body.clientWidth/2-oDiv.offsetWidth/2);
         top:expression(document.body.clientHeight/2-oDiv.offsetHeight/2)">
My text goes here...
</DIV>

Is it really good?
We just discussed that expressions are JavaScript dependent. This means that it required the browser to keep JavaScript enabled on running the pages using expressions. Expressions will not be functional if JavaScript is disabled.

We may feel that expressions are calculated once when the control loads or at event where we have implemented it to be fired. That is not true. Expressions are evaluated consistently when we are on the web page. Even a simple operation like scroll, hover over the control etc will cause the expression evaluation.This is easily observed if expressions are used to freeze data grid headers in aspx pages. Each time you scroll you can observe a shake on the header. This makes use of most of our client resources. Next time if you notice any slowdown in your browser and not able to find any reason, look for expressions.

Then why do developers use this?
Internet Explorer version 7 and below are not fully compliant with cascading style sheets (CSS) and hence we had to go with alternate and easy way of using expressions in CSS.

Is there any alternate for IE7 and below?
JavaScript can be used directly in most of the cases instead of CSS expressions. The above example can be implemented in JavaScript as given below –

window.onload = setWidth;

Function setWidth(){
document.getElemenById(“myDiv”).style.left = body.clientWidth/2-oDiv.offsetWidth/2;
document.getElemenById(“myDiv”).style.top = document.body.clientHeight/2-oDiv.offsetHeight/2;
}


CSS Expressions are no longer supported in IE8. However it can be made to work by running Internet Explorer in IE7 mode or below. We know that expressions in CSS hit performance. Despite that sometimes we will need to end up going for it. However before writing expressions just remember that they affect performance and are less reliable. Always consider JavaScript instead.

Abstract class and Interface

Abstract Class
Abstract class is a class which cannot be instantiated. We need to inherit this class and then instantiate the child class. Abstract class always acts as base class and contains one or more abstract or non abstract methods. An abstract method is a method that has only definition but not implementation. The child class must provide the definition for all the abstract method of its parent. However if it does not provide the implementation then the child class too must be declared abstract.

Static, Value Types & interface doesn't support abstract modifiers. Static members cannot be abstract. Classes with abstract member must also be abstract.

Example
Consider implementing the shapes available under Insert > Shape option of a word document. Some of the properties like fill, border, line style etc are common among all shapes. However other properties must be implemented separately.


We create an abstract class Shape. It is declared abstract as we do not intend to instantiate as shape in general makes no sense. Then create sub classes rectangle, triangle, circle etc.

Interface
Interfaces are used to separate implementation and definitions. It comes to use when the implementations need to be interchangeable and also in cases where the implementation changes frequently.

Interfaces define a generic template and just have method declaration and might contain properties. These method declarations are implicitly public and abstract. Interfaces cannot be instantiated. Interfaces can inherit other interfaces.

A class can implement the interface and implement the methods as per requirement. Each class which implements the interface can implement the method in its own way and can reflect the expected behaviour as per requirement.

In case the class does not implement all the methods from the interface then the class must be declared abstract. This class must be further extended to sub class and implementation must be provided in that sub class. This sub class can be later instantiated and put into use.

Interface definition
public interface Shape
{
//Can have any function which a shape required to be implemented
function area();
}

Implementing the interface
public circle implements shape
{
//Implement the area as required for circle
Function area()
{
                    //calculate area of circle
}
}


The below link has detailed explanation on when to use abstract class and interfaces