Pages

SPONSORED

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

 

Composition and Aggregation

Composition
Composition expresses relationship between objects. It is an association in which one class belongs to a collection. The containing object is responsible for the life time of the object it holds within it. The containing object cannot exist without the main object. It expresses the “has a” relationship among the objects

Example:  Office has a reception, Student has a name, Car has a tyre etc.

Aggregation
It is relationship which is just a reference between objects. The objects are independent of each other.

Example: Chair and person, Chair does not own the person.
Employee and address, address stays even after employee is destroyed.

The table below lists the key differences between composition and aggregation

Composition
Aggregation
Relationship where a part cannot exist without whole
Relationship where a part can exist without whole
Stronger relationship
Weaker relationship
Main object owns the containing objects
Objects are independent of each other
Main object instantiated the containing objects
Objects within the relationship are instantiated independently
Containing objects are destroyed when main object is destroyed
If one object is destroyed other object can survive.




What do you mean by Encapsulation?

As the name suggests Encapsulation means keeping all the objects data is contained together within the object. Data of object here refers to its variables and methods. Object hides the inner implementation from the outside view. Encapsulation controls interactions of objects. It prevents object interaction in unexpected way. This improves code modularity as well as improves application security.
 
Encapsulation Example


Class Product{
private double cost = 0.0;

public void setCost(double cost){
if(cost > 0)
this.cost = cost;
else
throw new Exception("No negative Values for Cost");
}

public int getCost(){
return cost;
}
}

The sample code above shows how the value of cost of the product is controlled. The value of cost can be set only via setCost method which takes care to avoid negative values to be set for the variable.Secure member can be modified in this manner and can be helful to control the code from insecure access.

Access modifiers are keywords used to specify the declared accessibility of a member or a type. The following are access modifiers for C++, C# and Java.
C# and C++
Public: All Objects can access it.
Protected: Access is limited to members of the same class or descendants.
Private: Access is limited to members of the same class.
Internal: Access is limited to the current assembly.
Protected Internal: Access is limited to the current assembly or types derived from the containing class.

The first 3 access levels are available both in C# and C++. But the last 2 are available only in C#.

Java
Public: All Objects can access it.
Protected: Access is limited to members of other classes within the same package or descendants.
Private: Access is limited to members of the same class.
No Modifier: Access is limited to the current package.

Benefits
Maintainability: Encapsulation helps increases the maintainability of the code and reduces the refactoring effort.
Security: It increases security by avoiding objects interaction in unexpected way. This will protect the variables from unaccepted values.

Static Blocks or Static Constructors

As the name suggests static blocks are used to initialise the static fields of the class.

·         These blocks or methods get executed only once for a class.
·         They are executed even before the constructors are executed.
·         The static fields with initializes in declaration will get executed before the  static blocks.
·         They are triggered when any of the following events occur:
o   An instance of the class is created.
o   If any of the static members of the class is accessed.


 The implementation of this is slightly different in Java and C#.

In Java
All blocks that are declared static are executed when a class is loaded. Static blocks in Java do not have a function name.

public class StaticBlockExample {
public static final int abc = 20;
public static final int def;

//Static block to initialise the static variable def
static {
          if(abc == 20)
def = 10;
else
def = 15;
}
//Constructor gets executed after static block is executed
public StaticBlockExample (){}
}


In C#
Static blocks are called as Static Constructors in C#. They are declared using static constructor declarations.

public class StaticBlockExample
{
static int abc = 20;
static int def;

  static StaticBlockExample ()
  {
if(abc == 20)
def = 10;
else
def = 15;
   }
}