Sunday 18 March 2018

Garbage Collection in C#

What is Garbage Collection and Why We Need It?

When you create any object in C#, CLR (common language runtime) allocates memory for the object from heap. This process is repeated for each newly created object, but there is a limitation to everything, Memory is not un-limited and we need to clean some used space in order to make room for new objects, Here, the concept of garbage collection is introduced, Garbage collector manages allocation and reclaiming of memory. GC (Garbage collector) makes a trip to the heap and collects all objects that are no longer used by the application and then makes them free from memory.

Memory Facts

When any process gets triggered, separate virtual space is assigned to that process, from a physical memory which is the same and used by every process of a system, any program deals with virtual space not with physical memory, GC also deals with the same virtual memory to allocate and de-allocate memory. Basically, there are free-blocks that exist in virtual memory (also known as holes), when any object request for memory allocation manager searches for free-block and assigns memory to the said object.
Virtual memory has three blocks:
  • Free (empty space)
  • Reserved (already allocated)
  • Committed (This block is give-out to physical memory and not available for space allocation)
**You may face out of memory error due to virtual memory full.

How GC Works?

GC works on managed heap, which is nothing but a block of memory to store objects, when garbage collection process is put in motion, it checks for dead objects and the objects which are no longer used, then it compacts the space of live object and tries to free more memory.
Basically, heap is managed by different 'Generations', it stores and handles long-lived and short-lived objects, see the below generations of Heap:
  • 0 Generation (Zero): This generation holds short-lived objects, e.g., Temporary objects. GC initiates garbage collection process frequently in this generation.
  • 1 Generation (One): This generation is the buffer between short-lived and long-lived objects.
  • 2 Generation (Two): This generation holds long-lived objects like a static and global variable, that needs to be persisted for a certain amount of time. Objects which are not collected in generation Zero, are then moved to generation 1, such objects are known as survivors, similarly objects which are not collected in generation One, are then moved to generation 2 and from there onwards objects remain in the same generation.

How GC Decides If Objects Are Live?

GC checks the below information to check if the object is live:
  • It collects all handles of an object that are allocated by user code or by CLR
  • Keeps track of static objects, as they are referenced to some other objects
  • Use stack provided by stack walker and JIT

When GC Gets Triggered?

There are no specific timings for GC to get triggered, GC automatically starts operation on the following conditions:
  1. When virtual memory is running out of space.
  2. When allocated memory is suppressed acceptable threshold (when GC found if the survival rate (living objects) is high, then it increases the threshold allocation).
  3. When we call GC.Collect() method explicitly, as GC runs continuously, we actually do not need to call this method.

What is Managed and Unmanaged Objects/Resources?

 VS 
In simple terms:
Managed objects are created, managed and under scope of CLR, pure .NET code managed by runtime, Anything that lies within .NET scope and under .NET framework classes such as stringintbool variables are referred to as managed code.
UnManaged objects are created outside the control of .NET libraries and are not managed by CLR, example of such unmanaged code is COM objects, file streams, connection objects, Interop objects. (Basically, third party libraries that are referred in .NET code.)

Clean Up Unmanaged Resources

When we create unmanaged objects, GC is unable to clear them and we need to release such objects explicitly when we finished using them. Mostly unmanaged objects are wrapped/hide around operating system resources like file streams, database connections, network related instances, handles to different classes, registries, pointers etc. GC is responsible to track the life time of all managed and unmanaged objects but still GC is not aware of releasing unmanaged resources
There are different ways to cleanup unmanaged resources:
  • Implement IDisposable interface and Dispose method
  • 'using' block is also used to clean unmanaged resources
There are couple of ways to implement Dispose method:
  • Implement Dispose using 'SafeHandle' Class (It is inbuilt abstract class which has 'CriticalFinalizerObject' and 'IDisposable' interface has been implemented)
  • Object.Finalize method to be override (This method is clean unmanaged resources used by particular object before it is destroyed)
Let's see below code to Dispose unmanaged resources:
  • Implement Dispose using 'SafeHandle' Class:
    class clsDispose_safe
        {
            // Take a flag to check if object is already disposed
            bool bDisposed = false;
    
            // Create a object of SafeHandle class
            SafeHandle objSafeHandle = new SafeFileHandle(IntPtr.Zero, true);
    
            // Dispose method (public)
            public void Dispose1()
            {
                Dispose(true);
                GC.SuppressFinalize(this);
            }
    
            // Dispose method (protected)
            protected virtual void Dispose(bool bDispose)
            {
                if (bDisposed)
                    return;
    
                if (bDispose)
                {
                    objSafeHandle.Dispose();
                    // Free any other managed objects here.
                }
    
                // Free any unmanaged objects here.
                //
                bDisposed = true;
            }
        }
  • Implement Dispose using overriding the 'Object.Finalize' method:
    class clsDispose_Fin
        {
            // Flag: Has Dispose already been called?
            bool disposed = false;
    
            // Public implementation of Dispose pattern callable by consumers.
            public void Dispose()
            {
                Dispose1(true);
                GC.SuppressFinalize(this);
            }
    
            // Protected implementation of Dispose pattern.
            protected virtual void Dispose1(bool disposing)
            {
                if (disposed)
                    return;
    
                if (disposing)
                {
                    // Free any other managed objects here.
                    //
                }
    
                // Free any unmanaged objects here.
                //
                disposed = true;
            }
    
            ~clsDispose_Fin()
            {
                Dispose1(false);
            }
        }

'using' Statement

using statement ensures object dispose, in short, it gives a comfort way of use of IDisposable objects. When an Object goes out of scope, Dispose method will get called automatically, basically using block does the same thing as 'TRY...FINALLY' block. To demonstrate it, create a class with IDisposable implementation (it should have Dispose() method), 'using' statement calls 'dispose' method even if exception occurs.
See the below snippet:
class testClass : IDisposable
{
    public void Dispose()
    {
        // Dispose objects here
  // clean resources
  Console.WriteLine(0);
    }
}

//call class
class Program
{
    static void Main()
    {
        // Use using statement with class that implements Dispose.
  using (testClass objClass = new testClass())
  {
       Console.WriteLine(1);
 }
  Console.WriteLine(2);
    }
}

//output
1
0
2

//it is same as below TRY...Finally code
{
    clsDispose_Fin objClass = new clsDispose_Fin();
    try
    {
        //code goes here 
    }
    finally
    {
        if (objClass != null)
        ((IDisposable)objClass).Dispose();
    }
}
In the above sample after printing 1, using block gets end and calls Dispose method and then call statement after using.

Re-view

  • Garbage collector manages allocation and reclaim of memory.
  • GC works on managed heap, which is nothing but a block of memory to store objects.
  • There is no specific timings for GC to get triggered, GC automatically start operation.
  • Managed objects are created, managed and under scope of CLR.
  • Unmanaged objects are wrapped around operating system resources like file streams, database connections, network related instances, handles to different classes, registries, pointers, etc.
  • Unmanaged resources can be cleaned-up using 'Dispose' method and 'using' statement.

Tuesday 1 October 2013

What is WCF ?

Windows Communication Foundation (Code named Indigo) is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is the latest service oriented technology; Interoperability is the fundamental characteristics of WCF. It is unified programming model provided in .Net Framework 3.0. WCF is a combined features of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication.

Sunday 29 September 2013

ASP.Net Page Life Cycle Events:



At each stage of the page life cycle, the page raises some events, which could be coded. An event handler is basically a function or subroutine, bound to the event, using declarative attributes like Onclick or handle.

Following are the page life cycle events:


PreInit . PreInit is the first event in page life cycle. It checks the IsPostBack property and determines whether the page is a postback. It sets the themes and master pages, creates dynamic controls and gets and sets profile property values. This event can be handled by overloading the OnPreInit method or creating a Page_PreInit handler.


Init . Init event initializes the control property and the control tree is built. This event can be handled by overloading the OnInit method or creating a Page_Init handler.


InitComplete . InitComplete event allows tracking of view state. All the controls turn on view-state tracking.


LoadViewState . LoadViewState event allows loading view state information into the controls.


LoadPostData . during this phase, the contents of all the input fields defined with the <form> tag are processed.


PreLoad . PreLoad occurs before the post back data is loaded in the controls. This event can be handled by overloading the OnPreLoad method or creating a Page_PreLoad handler.


Load . the Load event is raised for the page first and then recursively for all child controls. The controls in the control tree are created. This event can be handled by overloading the OnLoad method or creating a Page_Load handler.


LoadComplete . the loading process is completed, control event handlers are run and page validation takes place. This event can be handled by overloading the OnLoadComplete method or creating a Page_LoadComplete handler.


PreRender . the PreRender event occurs just before the output is rendered. By handling this event, pages and controls can perform any updates before the output is rendered.


PreRenderComplete . as the PreRender event is recursively fired for all child controls, this event ensures the completion of the pre-rendering phase.


SaveStateComplete . state of control on the page is saved. Personalization, control state and view state information is saved. The HTML markup is generated. This stage can be handled by overriding the Render method or creating a Page_Render handler.


UnLoad . the UnLoad phase is the last phase of the page life cycle. It raises the UnLoad event for all controls recursively and lastly for the page itself. Final cleanup is done and all resources and references, such as database connections, are freed. This event can be handled by modifying the OnUnLoad method or creating a Page_UnLoad handler.

ASP.Net Page Life Cycle



When a page is requested, it is loaded into the server memory, processed and sent to the browser. Then it is unloaded from the memory. At each of this steps, methods and events are available, which could be overridden according to the need of the application. In other words, you can write your own code to override the default code.

The Page class creates a hierarchical tree of all the controls on the page. All the components on the page, except the directives are part of this control tree. You can see the control tree by adding trace= "true" to the Page directive. We will cover page directives and tracing under 'directives' and 'error handling'.

The page life cycle phases are:


Initialization


Instantiation of the controls on the page


Restoration and maintenance of the state


Execution of the event handler codes


Page rendering


Understanding the page cycle helps in writing codes for making some specific thing happen at any stage of the page life cycle. It also helps in writing custom controls and initializing them at right time, populate their properties with view-state data and run control behavior code.

Following are the different stages of an ASP.Net page:


Page request . when ASP.Net gets a page request, it decides whether to parse and compile the page or there would be a cached version of the page; accordingly the response is sent


Starting of page life cycle . at this stage, the Request and Response objects are set. If the request is an old request or post back, the IsPostBack property of the page is set to true. The UICulture property of the page is also set.


Page initialization . at this stage, the controls on the page are assigned unique ID by setting the UniqueID property and themes are applied. For a new request postback data is loaded and the control properties are restored to the view-state values.


Page load . at this stage, control properties are set using the view state and control state values.


Validation . Validate method of the validation control is called and if it runs successfully, the IsValid property of the page is set to true.


Postback event handling . if the request is a postback (old request), the related event handler is called.


Page rendering . at this stage, view state for the page and all controls are saved. The page calls the Render method for each control and the output of rendering is written to the OutputStream class of the Page's Response property.


Unload . the rendered page is sent to the client and page properties, such as Response and Request are unloaded and all cleanup done.

Saturday 28 September 2013

Differance between Web Application and Web site creation in Asp.Net

Area
Web application projects
Web site projects
Project file structure
A Visual Studio project file (.csproj or .vbproj) stores information about the project, such as the list of files that are included in the project, and any project-to-project references.
There is no project file (.csproj or .vbproj). All the files in a folder structure are automatically included in the site.
Compilation
·    You explicitly compile the source code on the computer that is used for development or source control.
·    By default, compilation of code files (excluding .aspx and .ascx files) produces a single assembly.
·    The source code is typically compiled dynamically (automatically) by ASP.NET on the server the first time a request is received after the site has been installed or updated.
You can precompile the site (compile in advance on a development computer or on the server).
·    By default, compilation produces multiple assemblies.
Namespaces
Explicit namespaces are added to pages, controls, and classes by default.
Explicit namespaces are not added to pages, controls, and classes by default, but you can add them manually.
Deployment
·    You copy the assembly to a server. The assembly is produced by compiling the application.
·    Visual Studio provides tools that integrate with Web Deploy (the IIS web deployment tool) to automate many deployment tasks.
·    You copy the application source files to a computer that has IIS installed on it.
·    If you precompile the site on a development computer, you copy the assemblies produced by compilation to the IIS server.
·    Visual Studio provides tools that integrate with Web Deploy (the IIS web deployment tool) to automate many deployment tasks.

Refine Hours and Min from user give value

Hi All,

Today I am going to give a method by the help of which you can get hours and mins as integer if user willl give in different formate like, (1 hr 10 min or 1hr or 1:10 hour...)



public void getEventHourAndMinuteValues(string eventDuration, out int hour, out int minutes)
        {
            hour = 0;
            minutes = 0;

            try
            {
                if (eventDuration != string.Empty)
                {
                label1:
                    string[] duration = eventDuration.Split(new char[] { ':','.' });
                    if (IsValidTime(eventDuration))
                    {
                        if (duration.Length > 1)
                        {
                            hour = Convert.ToInt32(duration[0]);
                            minutes = Convert.ToInt32(duration[1]);
                        }
                        else
                        {
                            hour = Convert.ToInt32(duration[0]);
                        }
                    }
                    else
                    {
                        string pattern = @"(hour|HRs|hr|hrs|hr's|HOUR|HR)";
                        string minPattern = @"(minutes|mins|min's|Minutes|MINUTES)";
                        if (duration.Length > 1)
                        {
                            duration[0] = Regex.Replace(duration[0], @"\s+", string.Empty); //removing whitespace
                            duration[1] = Regex.Replace(duration[1], @"\s+", string.Empty);
                            hour = Convert.ToInt32(Regex.Replace(duration[0], pattern, string.Empty));
                            minutes = Convert.ToInt32(Regex.Replace(duration[1], minPattern, string.Empty));
                        }
                        else
                        {
                            //duration[0] = Regex.Replace(duration[0], @"\s+", string.Empty); //removing whitespace
                            try
                            {
                                hour = Convert.ToInt32(Regex.Replace(duration[0], pattern, string.Empty));
                            }
                            catch
                            {
                                hour = 1;
                                //eventDuration = Regex.Replace(duration[0], pattern, ":");
                                //eventDuration = Regex.Replace(eventDuration, minPattern, string.Empty);
                                //eventDuration = Regex.Replace(eventDuration, @"\s+", string.Empty); //removing whitespace
                                ////goto label1;
                            }
                        }

                    }
                }
                else
                {
                    hour = 1;
                }

            }
            catch (Exception ex)
            {
                hour = 1;
            }

        } 

Friday 27 September 2013

Check Valid Time Method

public bool IsValidTime(string thetime)
        {
            Regex checktime = new Regex(@"^(20|21|22|23|[01]d|d)(([:][0-5]d){1,2})$");
            return checktime.IsMatch(thetime);
        }