Saturday, October 30, 2010

Garbage Collection

The .NET Framework's garbage collector manages release of memory for your application. Each time you create a new object, the common language runtime allocates memory for the object from the managed heap. If there is no memory for new object garbage collector run automatically in order to free some memory. You can do it forcefully by calling System.GC.Collect() method.

When the garbage collector performs a collection, it checks for objects in the managed heap that are no longer being used by the application and performs the necessary operations to reclaim their memory.

If we manage memory ourselves we face mostly two issue:
1) Memory Leak :- If you allocate some memory and forget to release it , it is memory leak.

2) Dangling Pointer :- If you assign a memory location to two pointers and free to one, than second pointer is said dangling pointer since it is pointing to memory that is already released.

Which object is eligible for Garbage Collection:

void main()
{
Sum();
int iTotal = 0;
}

void Sum()
{

CSum objCSum = new CSum();

int iTotal = C.FirstNumber + C.SecondNumber;

Console.WriteLine(“Total is “ + iTotal);
}

When control comes to line “int iTotal = 0; than there is no way to access object objCSum created in Sum function. So this object is eligible for Garbage Collection, You can say if an object goes out of scope than this object is eligible for garbage collection.

How Garbage Collector Works :- When we run a program a bunch of memory allocated to that program. All memory required for objects of this program allocated from this bunch.This bunch of memory divided in three parts which are called Generation0, Generation1 and Generation2. respectively.
Generation0 has smaller size, Generation1 has medium size and Generation2 has large size.

When we create a object using new it searches space in first part if it is find allocated else garbage collector to run for generation0 to get the space for new object.If it is an heavy object means need more bytes than generation 0 has than it takes the memory in generation1.

Garbage collection is a two step process.
1) Mark :- In first step Garbage collection mark the object which are eligilble for Garbage collection.
2) Compact :- In second step garbage collection run and free the memory occupied by marked object.

If garbage collector free the object from middle than there will be blank memory in the middle. But memory should be compact all freed space should be in last. Garbage collector do one task here shift all remaining object to generation1. And now generation 0 is again empty for new object.

If all generations are filled than MemoryOutofRange exception will be thrown..

Grabage Collector class and methods:- System.GC class represent the Garbage Collector.

Collect(..) :- This method is used to force Garbage Colelcttion for all generation or for a specific.

public static void Colelct()
public static void Colelct(int iGeneration);

GetTotalMemory(boolean IsWait) :- Returns the total number of bytes allocated in managed heap. If IsWait is true it waits for garbage collector to finish.

KeepAlive(object obj):- Extend the life time of an object passed to it as a parameter.

SuppressFinalize:- Suppress the finalize method if there is no need of it.

GetGeneraion(object obj):- Returns the current generation of an object.

ReRegisterRorFinalize :- Reregister an object for finalization. Means make it eligible for finalization.

WaitForPendingFinalizers() :- This method block the current thread till the execuation of all the pending finalizers over.

Destructor :- If we have opened some file or a database connection that all the work of closing the file or closing the connection get done in destructor. In C++ distructor called when we free memory. In C++ we release memory explicitly (by calling free objCSum). But in dot net we don’t do it explicitly it is garbage collection responsibility to free it and no one know it when it will do it.So there is no concept of destructor in dot net. When we write a desturctor in C#, C# compiler internally replace it by Finalize method. In Vb.Net we have Finalize method in place of Destructor in C#.

Dispose :- All the work that we do in destructor we do here in Dispose method. We have to call this method explicitly, dot net runtime does not know about this method.There is a IDiposable interface in dot net which contain only one method Dispose.We can implement this interface if we want Dispose method strictly.
Name does not matter you can write any custom method name ClearRes(). But there is a benefit to implement IDisposable and use Dispose method instead of any other method when we use using keyword it automatically call Dispose method for that object.

CSum objCSum = new CSum();
using (objCSum)
{
objSum.Sum();
} // here it will Dispose method

//This is equivalent to try finally. If any error occurs between using block, finally always called. And inside finally  object destructor will be called.

To ensure that Dispose called at least once you can call it in Finalize method.But there is no guarantee that GC will call Finalize method on all objects which implements methods.If you have called Dispose method explicitly and written a calling in Finalize too then you can suppress the Finalize method by calling
GC.SuppressFinalize().

Sunday, October 24, 2010

Difference Between Abstract Class and Interface

What is an Abstract Class?
An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.

What is an Interface?
An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn�t support multiple inheritance, interfaces are used to implement multiple inheritance.

1)An Abstract Class can contain default Implementation(some non abstract methods), where as an Interface should not contain any implementation at all.When a class inherits from an abstract, the derived class must implement all the abstract methods declared in the base class. an abstract class can inherit from another non-abstract class.

2)There is no difference in the functionality of these two.The only difference is that a class cannot extend an abstract class if it already is extending some other class.An interface on the other hand can be implemented in any situation which makes them very powerful.Also user defined exceptions can be defined within an interface itself which is not the case with an abstract class.

3)Abstract class contatins one or more abstract methods. where Interface contains all abstract methods and final declarations.

4)Abstract classes are useful in a situation that Some general methods should be implemented and specialization behaviour should be implemented by child classes. Interafaces are useful in a situation that all properties should be implemented we can use this scenario

5)Interface must always have by default public and abstract methods while abstract class can have non abstract methods.

6)All the variables in interface are by default public static constant while in abstract class you may have instant variables.

7)Interfaces are slow as it requires extra indirection to find corresponding method in the actual class. Abstract classes are fast.

8)Accessibility modifier(Public/Private/internal) is allowed for abstract class. Interface doesn't allow accessibility modifier.

9)Interface come in inheritance chain but abstract class does not come. (Please test not confirmed.)

10)An abstract class can contain fields, constructors, or destructors and implement properties. An interface can not contain fields, constructors, or destructors and it has only the property's signature but no implementation.

11)You can prevent not required method to override in Abstract class, but not in Interface.

12)Abstract classes can inherit interfaces while interfaces cannot inherit abstract classes.

13)An abstract class may or may not have abstract method,but it is useless without abstract method,so an abstract class should have atleast single abstract method. While in case of an interface it is hardcode that an interface can have only the abstract methods with it.

14)We can't create object of abstract class.

15)We can't make method body with abstract method.

16)Abstract classes can inherit interfaces while interfaces cannot inherit abstract classes And abstract class can implement more than one interface.

Which is better interface or abstract class?
Obvious abstract class is better as it is fast in comparison of interface. And you can define your method also here.We use interface only in compel where we can not use abstract class we use interface[In case if class is already inherited with some other class like form.].

Why interface is slow in comparison of abstract class?
In Java's early days, there was a technical reason for the difference. Do you know what a "virtual table" or "vtbl" is? Basically, a simple vtbl could be used for directly inherited methods, and so the JVM just had to look at two pointers to find the code for a method inherited from an abstract class -- that's relatively fast. But since any class can implement any number of interfaces, finding the code that implements an interface method would involve following a pointer to a table of interfaces implemented by a class, then searching through the table to find a vtbl for the implementation of that interface, and then finding the method pointer in the table. That's obviously a lot more work, so calling an interface method used to be measurably slower.

These days, JVMs are a lot smarter, and most of this sort of lookup is done during dynamic compilation, so the runtime differences are small or nonexistent.

Delegates and Event

Event :-
An event is a message sent by an object to signal the occurrence of an action. The action could be caused by user interaction, such as a mouse click, or it could be triggered by some other program logic. The object that raises the event is called the event sender. The object that captures the event and responds to it is called the event receiver.

In event communication, the event sender class does not know which object or method will receive (handle) the events it raises. What is needed is an intermediary (or pointer-like mechanism) between the source and the receiver. The .NET Framework defines a special type (Delegate) that provides the functionality of a function pointer.

A delegate is a class that can hold a reference to a method. Unlike other classes, a delegate class has a signature, and it can hold references only to methods that match its signature. A delegate is thus equivalent to a type-safe function pointer or a callback.

How to declare delegates and events :-

private delegate void dlgAction();

private event dlgAction m_evnt = null;

Events are variables of type delegates

Difference between Template Filed and Bound Field

Use bound field to simply display the db column, use template to do something more fancy such as concatonate 2 db columns as 1 gridview column or add some text to the grid that doesn't come from the db.

The BoundField displays the value of specified DataSource field as text.
By using bound field we can bind the data directly by using header text and datafield without using any controls.
Headertext : We can specify header for the data
Datafield : Its the field which gets the data from dataset.

The TemplateField allows for a mix of HTML markup, Web controls, and data-binding syntax.
We can define our own asp.net controls in template field.

I want to have 2 columns in my grid that represent 2 columns in my db.
First name and surname so I have....
<asp:BoundField DataField="FirstName"/>
<asp:BoundField DataField="SurName" />'

But if you want to string them together you could have....

<asp:TemplateField HeaderText="Name"/>
<Itemtemplate>
eval("FirstName") + " " + eval("surname")
</ItemTemplate>
</asp:TemplateField>

so basically you convert a bound field to a template column when you want more than out of the box functionality for the column.
Template columns also come with a edit template tag which offers you more than the standard editing of that gridview row is desired... e.g when in edit mode put a drop down list in this row for me to select from - possibilities are endless

We can use CommandName property in Tamplate Filed but not in Bound Field.

Window Authentication

Window Authentication
Authentication is a process of identifying a user, while authorization is the process of determining if an authenticated user has access to the resource(s) they requested. Typically, authentication is achieved by the user sharing credentials that somehow verify the user's identity.

Whenever a user logs on to an application, the user is first authenticated and then authorized. With ASP.NET Web applications, the users requesting a page are, by default, anonymous. There are different techniques available for determining the identity of an anonymous user. Realize, however, that, by default, Web applications allow for anonymous access.

Understanding how ASP.NET and IIS Handle Authentication and Authorization
ASP.NET is not a stand-alone product - rather, it is utilized from IIS. When a request comes in for an ASP.NET Web page, the request is sent to the Web server software (IIS), which performs authentication and authorization. Depending on the settings in IIS and the user accessing the site, these checks might pass or they might not. If the user is not authenticated, or does not have access, there request will be stopped and an appropriate message will be returned. If, however, the request passes IIS's authentication and authorization, the request will be handed off to the ASP.NET engine, which can impose its own authentication and authorization schemes.

The following shows the sequence of authentication and authorization actions performed by IIS and ASP.NET on an incoming request.
1. The incoming request is first checked by IIS. If the IP address from where the request is sought is not allowed access to the domain, IIS denies the request.
2. IIS allows anonymous access by default and hence requests are automatically authenticated. However, this can be overridden for each application within IIS. Next in the sequence IIS performs this authentication, if it has been configured to do so.
3. The authenticated user request is passed to ASP.NET.
4. ASP.NET checks whether Impersonation is enabled or not. By default impersonation is not enabled in ASP .NET. Generally, some applications require impersonation for ASP compatibility and Windows server authentication. (By default, the ASP.NET engine operates under the ASPNET user account. Impersonation is a means by which you can have the ASP.NET engine operates under the authenticated user's user account. For more information refer to INFO: Implementing Impersonation in an ASP.NET Application.)
○ If impersonation is enabled, ASP.NET executes with the identity of the entity on behalf of which it is performing executing the task.
○ If impersonation is not enabled, the application runs with the privileges of the ASPNET user account.
5. Finally, the identity that has been authenticated and checked for in the previous steps is used to request resources from the OS. ASP.NET uses two forms of authorization:
○ FileAuthorization - relies on NTFS file permissions for granting access.
○ UrlAuthorization - in the Web.config file you can specify the authorization rules for various directories or files using the element.
6. If access is granted (successful authorization), ASP .NET returns the user's request through IIS.
Authentication Providers
ASP.NET provides three ways to authenticate a user:
● Windows authentication,
● Forms authentication, and
● Passport authentication
It is the job of the authentication provider to verify the credentials of the user and decide whether a particular request should be considered authenticated or not. The authentication scheme an ASP.NET Web application uses can be configured in its Web.config file.

4. Where is �Windows Authentication� applicable?
Since �Windows Authentication� uses the credentials of Windows users, it can be used only for an intranet application. In an intra-net application, the administrator has full control over the network users. The application can be designed in such a way that, it can display all the �Active Directory� users, so that the administrator of the application can configure the users authentication for the application. Integrated Windows authentication is best suited for an intranet environment, where both user and Web server computers are in the same domain, and where administrators can ensure that every user has Microsoft Internet Explorer, version 2.0 or later


Windows authentication and IIS
If you select windows authentication for your ASP.NET application, you also have to configure authentication within IIS. This is because IIS provides Windows authentication. IIS gives you a choice for four different authentication methods:
Anonymous, basic, digest, and windows integrated
If you select anonymous authentication, IIS doesn't perform any authentication, Any one is allowed to access the ASP.NET application.
If you select basic authentication, users must provide a windows username and password to connect. How ever this information is sent over the network in clear text, which makes basic authentication very much insecure over the internet.
If you select digest authentication, users must still provide a windows user name and password to connect. However the password is hashed before it is sent across the network. Digest authentication requires that all users be running Internet Explorer 5 or later and that windows accounts to stored in active directory.
If you select windows integrated authentication, passwords never cross the network. Users must still have a username and password, but the application uses either the Kerberos or challenge/response protocols authenticate the user. Windows-integrated authentication requires that all users be running internet explorer 3.01 or later Kerberos is a network authentication protocol. It is designed to provide strong authentication for client/server applications by using secret-key cryptography. Kerberos is a solution to network security problems. It provides the tools of authentication and strong cryptography over the network to help to secure information in systems across entire enterprise

Saturday, October 2, 2010

Watan

Watan ki fiker ker nadan
Musibat aane wali hai
Teri barbadyo ke mashware hain
Aasmano me
Na samjhoge to mit jaoge
e mere watan ke logo
Tumhari dastan tak bhi na hogi
Dastano me



..............By Iqbal

Followers

Link