Updated JavaScript

16-August-2012

When you update JavaScript or CSS files that are already cached in users’ browsers, most likely many users won’t get that for some time because of the caching at the browser. You need some way to force browser to download the latest files. There’s no way to do that effectively across all browsers from the web server by manipulating cache headers unless you change the file name or you change the URL of the files.  I found a way to do his. Every time file is updated it creates a duplicate copy of the existing file with new name and linked it with the .aspx page. So when user requests the page, new file is downloaded in his computer. He needs not to clear chase.

protected void Page_Load(object sender, EventArgs e)

{

//Adding dynamically in Head tag with new file name if the file is new.

FindControl(“tagHead”).Controls.Add(new LiteralControl(“<script type=’text/javascript’ src=’Scripts/” + NewFileName(“~/Scripts/JScriptOld.js”) + “‘></script>”));

}

//Checks the file if new create copy with new name and returns the new file name.

public string NewFileName(string FileNameWithPath)

{

string FileWithPath = Server.MapPath(FileNameWithPath);

FileInfo FI = new FileInfo(FileWithPath);

String FileName = DateTime.Now.Ticks.ToString() + FI.Extension;

String[] FileLines = File.ReadLines(FileWithPath).ToArray();

//Check existing file is new

if (FileLines[FileLines.Length – 2].ToString() != “//Added//”)

using (StreamWriter sw = File.AppendText(FileWithPath))

{

//Adding Lines to Existing File

sw.WriteLine(“//Added//”);

sw.WriteLine(“//” + FileName + “//”);

//Create a copy of existing file with another name.

String[] str = FileNameWithPath.Split(‘/’);

File.Copy(FileWithPath, Server.MapPath(FileNameWithPath.Replace(str[str.Length – 1], FileName)));

}

else

FileName = FileLines[FileLines.Length – 1].ToString().Replace(“//”, “”);

return FileName;

}

Entity Framework

29-November-2010

What is an Entity?

Entities are instances of EntityTypes; they represent the individual instances of the objects (such as candidates, opening) to which the information pertains. The identity of an entity is defined by the entity type it is an instance of; in that sense an entity type defines the class an entity belongs to and also defines what properties an entity will have. Properties describe some aspect of the entity by giving it a name and a type. The properties of an entity type in ADO.NET Entity Framework are fully typed, and are fully compatible with the type system used in a DBMS system, as well as the Common Type System of the .NET Framework.

What is Entity Framework?
The ADO.NET Entity Framework enables developers to create data access applications by programming against a conceptual application model instead of programming directly against a relational storage schema. The goal is to decrease the amount of code and maintenance required for data-oriented applications. Entity Framework applications provide the following benefits:

• Applications can work in terms of a more application-centric conceptual model, including types with inheritance, complex members, and relationships.

• Applications are freed from hard-coded dependencies on a particular data engine or storage schema.

• Mappings between the conceptual model and the storage-specific schema can change without changing the application code.

• Developers can work with a consistent application object model that can be mapped to various storage schemas, possibly implemented in different database management systems.

• Language-integrated query (LINQ) support provides compile-time syntax validation for queries against a conceptual model.

ADO.NET Entity Framework abstracts the relational (logical) schema of the data that is stored in a database and presents its conceptual schema to the application. For example, in the database, entries about a candidate and their information can be stored in the Candidates table, their opening in the Openings table and their contact information in yet another Contacts table. For an application to deal with this database, it has to know which information is in which table, i.e., the relational schema of the data is hard-coded into the application.

The disadvantage of this approach is that if this schema is changed the application is not shielded from the change. Also, the application has to perform SQL joins to traverse the relationships of the data elements in order to find related data. For example, to find the opening of a certain candidate, the candidate needs to be selected from the Candidates table, the Candidates table needs to be joined with the Opening table, and the joined tables need to be queried for the opening that are linked to the candidate.

This model of traversing relationships between items is very different from the model used in object-oriented programming languages, where the relationships of an object’s features are exposed as Properties of the object and accessing the property traverses the relationship. Also, using SQL queries expressed as strings, only to have it processed by the database, keeps the programming language from making any guarantees about the operation and from providing compile time type information.

The mapping of logical schema into the physical schema that defines how the data is structured and stored on the disk is the job of the database system and client side data access mechanisms are shielded from it as the database exposes the data in the way specified by its logical schema.

Why we should use Custom Entities instead of Dataset?
In order to use a Dataset inside the presentation layer, we need to have knowledge about data structures (i.e. tables, columns and rows hosted by the Dataset), so we don’t have real abstraction from the data layer. Anyway a Dataset makes easier to develop data binding code.
Custom Entities are usually slim, from an XmlSerialization point of view, and there are also tools, like System.Xml.Serialization attributes, to make it even slimmer.
We’ve to pay the due to fill the entities with our data, being careful of not building monster with multiple heads, with GB and GB of RAM filled with data that should be kept inside the DBMS engine. Remember that custom entities are the containers of small instance data and not a replacement for your DBMS, like Dataset.
Custom entities provide the means to expose real data in easy-to-access APIs without forcing every data model to fit in the relational model. Like it or not, in the real world all data is rarely entirely relational. By using Datasets, you render data with some approximation, albeit without loss of information.
Custom entities supply strong typing and more compact, faster objects. At the same time, they are abstract enough to require no changes to the DAL if the underlying database schema changes. Being custom classes, they enable you to incorporate information aggregated from multiple sources and represent free-form and hierarchical data. A custom class can be marked as serializable and serialized through any super-optimized algorithm.

Dataset Custom Entities
Built-in support for concurrency Yes To be added
Data Relationship Yes No
Serialization Inefficient in .NET Framework 1.x To be added
NULL values No To be added
Schema abstraction Yes Yes
Strong typing No Yes
Support for hierarchical data Yes, but through a relational API Yes
Free-form data No Yes
Custom behavior No Yes
Ease of development Yes No, but can be improved through code generation
.NET data binding Yes To be added; requires the implementation of several additional interfaces
Interfacing with Web services Costly, unless knowledge of the object is assumed on the client Yes
XML integration Yes To be added
Expression language Yes To be added
Data aggregation Yes To be added
Why do we need interfaces?
Interfaces are a very logical way of grouping objects in terms of behavior. When multiple developers start building a large scale ASP.NET application, the site’s design often suffers from two common problems:
1. Quality control
2. Flexibility
One reason quality control suffers is because it is natural for developers to give the functionality of their components different method names. For example three developers creating similar components may opt to name related functions with different names. Second, flexibility will suffer unless there is a convenient way to reference dynamically called components. For example, imagine a particular ASP.NET page loads a set of User Controls specified through querystring values. Once these controls have been loaded, they each might have differently named methods or properties that need to be called / set. With a gaggle of different User Controls that could be loaded, and each with different method and property names, the page’s source code will quickly become unreadable.
It is possible, though, to solve these quality control and flexibility issues through the use of .NET interfaces.
During the process of designing an application using OOP Paradigm, the application will be designed as a set of classes indicating how objects will be created each with specific status and behavior, as well as defining the ways of interaction between those objects. By this way, almost every class indicates a type (an abstracted data type in a more specific manner).
Interfaces also enhance abstraction which is a core principal of OOP; design patterns like the factory pattern make a perfect use of interfaces through abstracting objects to know which implementation of a certain object type is provided. Interfaces make it very flexible to change implementations of services especially in multilayer applications.
Another benefit of interfaces shows up during the development of large projects by large teams, at which the interface acts as a specification for developers with the set of methods they need to implement in classes of a certain type.
Why “Microsoft Data Access Application Block”?
The Data Access Application Block is a Microsoft .NET Framework component that contains optimized data access code that can help you do the following:

• Call stored procedures.

• Issue SQL text commands against a SQL Server database.
The Enterprise Library Data Access Application Block simplifies development tasks that implement common data access functionality. Applications can use the application block in a variety of situations, such as reading data for display, obtaining data to pass through application layers, and submitting changed data back to the database system. The application block includes support for both stored procedures and in-line SQL, and common housekeeping tasks such as managing connections and creating and caching parameters are encapsulated in the application block’s methods. In other words, the Data Access Application Block provides access to the most frequently used features of ADO.NET.
The application block also facilitates the development of portable application code, allowing the code to remain uniform across multiple database servers, including Microsoft SQL Server, Oracle, and DB2. It does so by using an abstract base class that defines a common interface and provides much of the implementation for the data access methods, Applications written for one type of database such as SQL Server look the same as applications written for another type of database, such as Oracle. By using the Data Access Application Block and by following the guidelines in this document, your code remains mostly portable.

The Data Access Application Block has the following features:

• It reduces the need to write boilerplate code to perform standard tasks.

• It helps maintain consistent data access practices, both in an application and across the enterprise.

• It reduces difficulties in changing the physical database target.

• It relieves developers from learning different programming models for different types of databases.

• It reduces the amount of code that needs to be rewritten when porting applications to different types of databases.

Page Pre Initializing

Page_PreInit

Check the IsPostBack property to determine whether this is the first time the page is being processed. Create or re-create dynamic controls. Set a master page dynamically. Set the Theme property dynamically.

Page Initialization

Page_Init

Raised after all controls have been initialized. Use this event to read or initialize control properties.

Page Initialization Completed

Page_InitComplete

Use this event for processing tasks that require all initialization be complete.

View State Loading

LoadViewState

The view state of the control posted by the client is reloaded into the new instance of the control.

Page before Load

OnPreLoad

Use this event if you need to perform processing on your page or control before the Load event.

Page Loading

OnLoad

The Page calls the OnLoad event method on the Page, then recursively does the same for each child control, which does the same for each of its child controls until the page and all controls are loaded.
Use the OnLoad event method to set properties in controls and establish database connections.

Page Load

Page_Load

This is not an event instead, at this stage of processing, the OnLoad event calls the Page_Load method.

Loading the postback data

LoadPostData

The server searches any data corresponding to the control that is loaded in the data posted by the client.

PostBack Event Handling

RaisePostBackEvent

Notifies the server control that caused the postback that it should handle an incoming postback event.

Control Event

Page Load Completed

LoadComplete

Use this event for tasks that require that all other controls on the page be loaded.

PreRendering

Page_PreRender

The PreRender event occurs for each control on the page. Use the event to make final changes to the contents of the page or its controls.

PreRendering Completed

OnPreRenderComplete

The OnPreRenderComplete method is called when the prerendering stage of the page life cycle is complete. At this stage of the page life cycle, all controls are created and the page is ready to render the output.

Saving ViewState

SaveViewState

Before this event occurs, ViewState has been saved for the page and for all controls. Any changes to the page or controls at this point will be ignored.
Use this event perform tasks that require view state to be saved, but that do not make any changes to controls.

Saving ViewState Completed

OnSaveStateComplete

The OnSaveStateComplete method is called when the state information for the control has been written to the persistence medium for the page.

Creating HTML

CreateHtmlTextWriter

The CreateHtmlTextWriter method creates a TextWriter through the browser property of the request object associated with the page request.

Rendering

Page_Render

This is not an event instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control’s markup that is sent to the browser.

Page Unload

OnUnload

Fires immediately before the object is unloaded from the servers memory.

Unloading

Page_UnLoad

This event occurs for each control and then for the page. In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.
For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.

.Net Code Execution

5-July-2009

How the .Net code is Executes.

The program written in .net environment is compiled twice.

The first compilation is done from the original language to a "common intermediate language&quo (CIL). This is what actually goes "in" an assembly.

When a compiler produces MSIL, it also produces metadata. Metadata describes the types in your code, including the definition of each type, the signatures of each type’s members, the members that your code references, and other data that the runtime uses at execution time. The MSIL and metadata are contained in a portable executable (PE) file that is based on and extends the published Microsoft PE and common object file format (COFF) used historically for executable content. The presence of metadata in the file along with the MSIL enables your code to describe itself, which means that there is no need for type libraries or Interface Definition Language (IDL). The runtime locates and extracts the metadata from the file as needed during execution.

The second compilation is done from the CIL to machine code. This compilation is usually performed automatically by the "just-in-time" (JIT) compiler. It is also possible to use the Native Image Generator (ngen) utility to create the machine code in advance of runtime.

As part of compiling MSIL to native code, the MSIL code must pass a verification process unless an administrator has established a security policy that allows the code to bypass verification. Verification examines MSIL and metadata to find out whether the code is type safe, which means that it only accesses the memory locations it is authorized to access. Type safety helps isolate objects from each other and therefore helps protect them from inadvertent or malicious corruption. It also provides assurance that security restrictions on code can be reliably enforced.

Executes

 

The whole step is elaborated below and explains this process in a diagrammatic manner:

  1. The programmer writes the source code using C# language conventions.
  2. The source code is then compiled using a C# Compiler (csc.exe).
  3. The compiler then converts the source code into an Intermediate Language. The Intermediate Language can be either an executable (exe) or a Dynamic Link Library (DLL). Since the Intermediate Language is generated by the C# compiler, it is called as Managed Code. Managed Code can be executed only on a .NET aware Platform. (Where the .Net Framework is already install.)
  4. The compiled file unit is then executed using the C# Interpreter. Upon execution, the code is checked for type safety. Moreover, the Just In Time (JIT) compiler compiles the unit into Managed Native Code and finally Common Language Runtime (CLR) produces the final output.
  5. The final unit can be executed on any system having Common Language Runtime installed on it. The C# Compiler and Interpreter will be installed at the time of installing the .NET Framework Software Development Kit (SDK).

In Microsoft .NET there are three types of JIT compilers:

Pre-JIT: Pre-JIT compiles complete source code into native code in a single compilation cycle. This is done at the time of deployment of the application.

Econo-JIT: Econo-JIT compiles only those methods that are called at runtime.However, these compiled methods are removed when they are not required.

Normal-JIT: Normal-JIT compiles only those methods that are called at runtime. These methods are compiled the first time they are called, and they are stored in the cache. When the same methods are called again, the compiled code from cache is used for execution.

This is my first post. This article won’t be the definitive guide of Object oriented Programming System an entire book could easily be devoted to that. Instead, think of this as a good place to start. Good for those how had already know about OOPS. If you get sometime wrong / new please comment me.

Basics of Object Oriented Programming System

What is Opps?
Oops is a problem solving technique.

What is Class?
Class is a description of an Object.

What is an Object?
An Object is an entity that has attribute, behavior and identity of a class.

What is the relation between Class and Object?
Class is the defection, while Object is an instance of the Class created.

What is Encapsulation?
Encapsulation is the localization or hiding of information and processes within an object. Because objects encapsulate both data and processes, the user of an object can view the object as a black box that provides services. Instance variables and methods can be added, deleted, or changed, but as long as the services provided by the object remain the same, code that uses the object can continue to use it without being rewritten.

public class TestMain
{
    private string _Name = string.Empty;

    public string Name
    {
        get
        {
            return _Name;
        }
        set
        {
            _Name = value;
        }
    }
}

Like the above way we can protect the private data from the outside world. In the above example we can’t access the private data Name from an object instance. We manipulate the data only using the property.

What is Polymorphism?
Through inheritance, a class can be used as more than one type; it can be used as its own type, any base types, or any interface type if it implements interfaces. This is called polymorphism. In C#, every type is polymorphic. Types can be used as their own type or as an object instance, because any type automatically treats Object as a base type.

public class BaseClass
{
    public virtual void DoWork() { }
    public virtual int WorkProperty
    {
        get { return 0; }
    }
}
public class DerivedClass : BaseClass
{
    public override void DoWork() { }
    public override int WorkProperty
    {
        get { return 0; }
    }
}

 

DerivedClass B = new DerivedClass();
B.DoWork();  // Calls the new method.
 
BaseClass A = (BaseClass)B;
A.DoWork();  // Also calls the new method.

 

What is Access Modifiers?
Access modifiers are keywords used to specify the declared accessibility of a member or a type. They are …….

  1. Public
  2. Private
  3. Protected
  4. Internal
  5. Protected Internal.

 

Public: All members have access in the classes.
Private: Only members of class have access.
Protected: All members in current class and in derived class can access the variables.
Internal: Only members in current project have access to the element.
Protected Internal: All members of the current project and all members in derived class can access the variables.

What is Properties?
Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields.

Public Int32 ID
    {
        get { return _ID;  }
        set { _ID = value; }
    }

Read Only Property

Public Int32 ID
    {
        get { return _ID;  }
    }
Write Only Property

Public Int32 ID
    {
        set { _ID = value; }
    }

 

What is Implementation Inheritance?
When a class is derived from another class such that it inherits all the members of the base type it is Implementation Inheritance.

What is Interface Inheritance?
When a type (class or a structure) inherits only the signatures of the functions from another type it is Interface Inheritance.

What is Abstract class?
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but doesn’t contain implementation. Abstract classes can’t be instantiated, and require subclasses to provide implementations for the abstract methods. This class must be inherited. This class is mostly used as a base class.

Abstract Class

public abstract class TestAbstract
{
    public abstract int AddNumber(int One, int two);

    public virtual int AddTwoNumber(int One, int two)
    {
        int Result = One + two;
        return Result;
    }
}

Child Class

public class TestMain:TestAbstract
{
    public override int AddNumber(int One, int two)
    {
        int Result = One + two;
        return Result;
    }

    public override int AddTwoNumber(int One, int two)
    {
        int Result = One +two;
        return Result;
    }

}

What is Virtual function?
A virtual function is a function whose behavior can be overridden within an inheriting class by a function with the same signature. A base class must provide the virtual modifier for any virtual method, and derived classes must provide the override modifier for any override method inherited from a base class.
Virtual methods allow subclasses to provide their own implementation of that method using the override keyword.

What is Abstract  function?
Abstract functions in a class contain no method body, and are implicitly virtual function. Abstract function-modifier exists only to provide a uniform syntactical style.

Neither abstract nor virtual can be declared private, since it would defeat the purpose, and subclasses must override them using the same method signature. If a class has any abstract methods, then it must tag itself as abstract, and no instances of it can be created.

What is Interface?
An interface is a reference type containing only abstract members. These can be events, indexers, methods or properties, but only the member declarations. A class implementing an interface must provide the implementation of the interface members. An interface cannot contain constants, constructors, data fields, destructors, static members or other interfaces. Interface member declarations are implicitly public.

Interface
public interface TestInterface
{
    Int32 ID
    {
        get;
        set;
    }

    String Name
    {
        get;
        set;
    }

    string Address
    {
        get;
        set;
    }

    bool Add();

    bool Update();

    bool Delete();
}

Class
public class Employee : TestInterface
{
    public int ID
    {
        get
        {
            //Implement………
        }
        set
        {
            //Implement………
        }
    }

    public string Name
    {
        get
        {
            //Implement………
        }
        set
        {
            //Implement………
        }
    }

    public string Address
    {
        get
        {
            //Implement………
        }
        set
        {
            //Implement………
        }
    }

    public bool Add()
    {
        //Implement………
    }

    public bool Update()
    {
        //Implement………
    }

    public bool Delete()
    {
        //Implement………
    }
}

 

When a class or structure is said to inherit an interface, it means that the class or structure provides an implementation for all of the members defined by the interface. The interface itself provides no functionality that a class or structure can inherit in the way that base class functionality can be inherited. However, if a base class implements an interface, the derived class inherits that implementation. A class or structure can inherit more than one interface. When a class or structure inherits an interface, it inherits only the method names and signatures, because the interface itself contains no implementations.

Interface versus Abstract Class.
 
An Interface cannot implement methods.
An abstract class can implement methods.
An Interface can only inherit from another Interface.
An abstract class can inherit from a class and one or more interfaces.
An Interface cannot contain fields.
An abstract class can contain fields.
An Interface can contain property definitions.
An abstract class can implement a property.
An Interface cannot contain constructors or destructors.
An abstract class can contain constructors or destructors.
An Interface can be inherited from by structures.
An abstract class cannot be inherited from by structures.
An Interface can support multiple inheritances.
An abstract class cannot support multiple inheritances.

 

What is Sealed Class?
A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class. Sealed classes prevent derivation.

What is Sealed Methods?
A class member, method, field, property, or event, on a derived class that is overriding a virtual member of the base class can declare that member as sealed. This negates the virtual aspect of the member for any further derived class. This is accomplished by putting the sealed keyword before the override keyword in the class member declaration.

public sealed override int AddTwoNumber(int One, int two)
    {
        int Result = One +two;
        return Result;
    }

What is Function Overloading?
Function overloading is the practice of declaring the same function with different signatures. The same function name will be used with different number of parameters and parameters of different type. But overloading of functions with different return types is not allowed.

public Int32 AddTwoNumber(Int16 One, Int16 Two)

public Int32 AddTwoNumber(Int32 One, Int32 Two)

 

What is function overriding?
If a base class is declared as virtual and derived class is declared as virtual. This redefinition of virtual in derived class is known as Function overriding. Both functions have same parameters.

public virtual int AddNumber(int One, int two)

public override int AddNumber(int One, int two)

What is Class Constructor?
A constructor is a special function which can be included in a class. It is unusual as a function because it is never specifically called, the same way that other functions are. A constructor function is called automatically when the class variable is declared. It is used to set up the class variable with sensible values in the member variables. There is more then one Constructor in a class within a class with different parameters.

public Class ABC
{
public ABC()
{
//Implement………

}
public ABC(string xyz)
{
                        //Implement………
}
}

What is Class Destructor?
Destructor is a special function that is called whenever a class variable is destroyed. A destructor is declared as having the same name as the function, except that the name is preceded by the ~ symbol before it. Apart from that symbol, the declaration of a destructor would be indistinguishable from a constructor. There is always one destructor in a class.

public Class ABC
{
public ABC()
{
//Implement………

}
public ~ABC()
{
                        //Implement………
}
}

What is Delegate?
A delegate is a function pointer. A delegate allows encapsulating a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked. Delegates are multicasting which means that they can point to more than one function at a time.

What is Event?
An event is a mechanism via which a class can notify its clients when something happens. For example when you click a button, a button-click-event notification is sent to the hosting the button. Events are declared using delegates.

What is Generic Class?
Generic classes encapsulate operations that are not specific to a particular data type. The most common use for generic classes is with collections like linked lists, hash tables, stacks, queues, trees, and so on. Operations such as adding and removing items from the collection are performed in basically the same way regardless of the type of data being stored.