Saturday, 6 July 2013

Threading in C#

A C# client program (Console, WPF, or Windows Forms) starts in a single thread created automatically by the CLR and operating system (the “main” thread)


All examples assume the following namespaces are imported: 

using System; 
using System.Threading; 

class ThreadTest
{
     static void Main()
     {
 
         Thread t = new Thread (Write);        //  a new thread 
         t.Start();                                           //   running Write() 

         // Simultaneously, do something on the main thread.       
         for (int i = 0; i < 1000; i++)
             Console.Write ("x");

     }
     static void Write()
     {
         for (int i = 0; i < 1000; i++) Console.Write ("y");
     }
}

Output : 
xxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyy
yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
yyyyyyyyyyyyyxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx


Properties of a Thread

  • Thread.CurrentThread -> Static method gives the reference of the thread object which is executing the current code.
  • Name           -> Read/Write Property used to get and set the name of a thread
  • ThreadState -> Property used to check the state of a thread.
  • Priority        -> Property used to check for the priority level of a thread.
  • IsAlive         -> Returns a Boolean value stating whether the thread is alive or not.
  • IsBackground -> Returns a Boolean value stating the running in background or foreground.

PriorityLevels of Thread

  • Highest
  • AboveNormal
  • Normal
  • BelowNormal
  • Lowest

Difference between Var and Dynamic keyword

In this article i am going to Discuss about difference between var and dynamic keyword

Var Keyword 
 
   












1.     It is introduced in C# 3.0 version
2.     The variable type is decided at compile time itself by compiler. when we mouse over the variable it will tell the data type.
3.     Variable should initialize at the declaration itself.
               var number 10 is correct.   
               var number;     not correct error ; 
           Implicitly-typed local variables must be initialized (CS0818) 
      4.  var can't be used as type in method parameter
5.     This  is statically typed.
6.     Errors caught at compile time.
7.     We can’t reassign the value of variable to another data type, because compiler already knows what kind of data type is declared.
  var  obj=1; 
  var  obj=”name”;   Error because already it defined as int type by compiler. 


Dynamic Keyword




      1.      It is introduced in C# 4.0
      2.      This is dynamically typed. Decides the type of variable at runtime by compiler.
      3.      No needs of initialize at declare time.
e.g., dynamic str; 
§  str =”I am a string”;  //Works fine and compiles
§  str=2;                  //Works fine and compiles
       4.      Error caught at runtime.
       5.      No intellisense.
       6.   dynamic should be used as a type in method parameter
               public void dyn(dynamic dd)
        {
            dynamic add;
            add="sample";
            add=3;
        }






Implicit and Explicit Conversion in C#

In C# Language , There is concept called Type Conversions, Which will convert one type to another.

In that there are two types of Conversions
1. Implicit Conversion
2. Explicit Conversion

Implicit Conversion : 
Conversion between types can be achieved automatically is known as Implicit
 For Ex :  

        byte value1 = 10;
        byte value2 = 23;
        long  total    = value1 + value2;

Here in this example, we don't need to specify data type for the target type, internally it will convert that is implicit. value1 , value2 are byte when adding we assign the value to a variable total which is long data type.
Internally it converts the result value into long data type.

Explicit Conversion :
Conversion between types can be done Manually instead of automatically
For Ex:
        
        long val = 3000;
        int a = (int) val;       /*  valid cast . The Maximum int is 2147483647  */

In this above example, we can see that val is long data type now it is assign to int type with explicitly specify 
to which data type we have to convert . If we misses this explicit convert C# Compiler throws error.

Let we see in coding How it is works like this Implicit and Explicit conversion 

Here we take three class  Rupees Dollar  ,Euro     

Rupees can be convert to Euro or Dollar   Implicit
Dollar   can be convert to Rupees Implicit and Euro as Explicit
Euro     can be convert to Rupees or Dollar   Implicit

From the below code 20 is pass as a parameter to rupees, then it is implicitly converted to Dollar and 
Euro

/***********************************************************************/

     Rupees rup  =  new Rupees(20);
     Dollar   rdrl  =  rup;
     Euro     reur  =  rup;

   class Rupees     {
        public decimal Value{set;get;}
    
    
        public Rupees(decimal value)
        {
            this.Value = value;
        }
    
       /* Rupees can be implicitly converted to Euro */
        public static implicit operator Euro(Rupees cur)
        {        
            return new Euro(cur.Value/100 );
        }
         
        /* Rupees can be implicitly converted to Dollar */
        public static implicit operator Dollar(Rupees cur)
        {
            return new Dollar(cur.Value/50);
        }
    }
/***********************************************************************/


/***********************************************************************/
Here Dollar is convert to Euro Explicitly 

     Dollar    dlr    =  new Dollar(4);
     Euro      deur =  (Euro)dlr;
     Rupees drup =  dlr;

class Dollar
    {
        public decimal Value{set;get;}
    
    
        public Dollar(decimal value)
        {
            this.Value = value;
        }
    
        /* Dollar can be implicitly converted to Rupees */
        public static implicit operator Rupees(Dollar cur)
        {        
            return new Rupees(cur.Value*50);
        }
            
        /* Dollar can be implicitly converted to Euro */
        public static explicit operator Euro(Dollar cur)
        {
            return new Euro(cur.Value/2);
        }
    }
 /***********************************************************************/   

/***********************************************************************/
In the below code Euro is implicitly convert to rupees and Explicitly to Dollar

     Euro      eur   =   new Euro(2);
     Rupees erup =   eur;
     Dollar   edlr  =   (Dollar)eur;

class Euro
    {
        public decimal Value{set;get;}
    
        public Euro(decimal value)
        {
            this.Value = value;
        }
    
        /* Euro can be implicitly converted to Rupees */
        public static implicit operator Rupees(Euro cur)
        {        
            return new Rupees(cur.Value*100);
        }

      /* Euro can be implicitly converted to Dollar */
        public static implicit operator Dollar(Euro cur)
        {
            return new Dollar(cur.Value*2);
        }
    }
 /***********************************************************************/
public static void Main(string[] args)
{
            Rupees r     = new Rupees(20);
            Dollar   rdrl = r;
            Euro     reur = r;
            Console.WriteLine("Rupees = {0} \tDollar = {1} \tEuro = {2}",r.Value,rdrl.Value,reur.Value);
        
            Dollar  dlr    =   new Dollar(4);
            Euro    deur  =   (Euro)dlr;
            Rupees drup=   dlr;
            Console.WriteLine("Dollar = {0} \tEuro = {1} \tRupees = {2}",dlr.Value,deur.Value,drup.Value);
        
            Euro      eur   = new Euro(2);
            Rupees erup = eur;
            Dollar    edlr = (Dollar )eur;
            Console.WriteLine("Euro = {0} \tRupees = {1} \tDollar = {2}",eur.Value,erup.Value,edlr.Value);
        
            Console.WriteLine();
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
  }

Following is the ouput :                 





The full source code for Type Conversion  Code.

namespace TypeConversion
{
    class Dollar
    {
        public decimal Value{set;get;}
    
    
        public Dollar(decimal value)
        {
            this.Value = value;
        }
    
    
        public static implicit operator Rupees(Dollar cur)
        {        
            return new Rupees(cur.Value*50);
        }
        
        public static explicit operator Euro(Dollar cur)
        {
            return new Euro(cur.Value/2);
        }
    }

    class Euro
    {
        public decimal Value{set;get;}
    
        public Euro(decimal value)
        {
            this.Value = value;
        }
    
        public static implicit operator Rupees(Euro cur)
        {        
            return new Rupees(cur.Value*100);
        }
        
        public static implicit operator Dollar(Euro cur)
        {
            return new Dollar(cur.Value*2);
        }
    }

    class Rupees
    {
        public decimal Value{set;get;}
    
    
        public Rupees(decimal value)
        {
            this.Value = value;
        }
    
        public static implicit operator Euro(Rupees cur)
        {        
            return new Euro(cur.Value/100 );
        }
        
        public static implicit operator Dollar(Rupees cur)
        {
            return new Dollar(cur.Value/50);
        }
    }

    class Program
    {
        public static void Main(string[] args)
        {
            Rupees r=new Rupees(20);
            Dollar rdrl=r;
            Euro reur=r;
            Console.WriteLine("Rupees = {0} \tDollar = {1} \tEuro = {2}",r.Value,rdrl.Value,reur.Value);
            
            Dollar dlr =new Dollar(4);
            Euro deur=(Euro)dlr;
            Rupees drup=dlr;
            Console.WriteLine("Dollar = {0} \tEuro = {1} \tRupees = {2}",dlr.Value,deur.Value,drup.Value);
            
            Euro eur=new Euro(2);
            Rupees erup=eur;
            Dollar edlr=(Dollar)eur;
            Console.WriteLine("Euro = {0} \tRupees = {1} \tDollar = {2}",eur.Value,erup.Value,edlr.Value);
            
             Console.WriteLine();
             Console.Write("Press any key to continue . . . ");
             Console.ReadKey(true);
        }
    }
}


This article will make a Clear understanding of Implicit and Explicit type conversion.














Windows, Mac OSx , Linux

Operating Systems of various companies written in Various Languages.
  • Windows: C++, kernel is in C , some part are in c#
  • Mac: Objective C, kernel is in C (IO PnP subsystem is Embedded C++)
  • Linux: Most things are in C, many userland apps are in Python, KDE is all C++
What is a Kernel ?
Kernel is a Computer Program which manages the input and output of a software . It is designed for Transferring a  software instructions to data instructions. This is the central core of computer operating system.
Difference between the C and Objective C:
C language is the low level language which is close to the assembly language, Objective C is the little higher layer it is superset of C. Objective C have the Object Oriented Layer in Top of C Language.
Web Hosting :
Hardware
  •  The amount of resources need for Linux is less than Windows and Mac
  •  Linux can run in low end hardware.
  •  Mac and Windows need High end hardware.
Mac Hosting
  • Sofware is secured.
  • Data never be hacked.
  • Mac hosts run Apache servers similar to Linux which allows for basic web code plus software like WordPress, vBulletin, and cPanel to run smoothly.

 Linux Hosting

  • The biggest benefit to using Linux hosting opposed to Mac hosting is the cost. No,
  • you will save money.
  • High Level security.
  • Linux runs on Apache servers and can run basic web code, WordPress, forum software, etc.
Windows Hosting
  • Windows servers can run applications like WordPress and vBulletin, it will often be slow or choppy.
  • Windows hosting can run applications that use ASP, .NET, Microsoft Access, or MSSQL databases.
  •  These web applications that will not run on Linux or Mac servers.

Solution for Thread being Aborted, Call a long running Webservice using SoapRequest from asp.net page and Usage of Health Monitoring system

Sometimes we had to face a problem thread being aborted while long running web service  which is call from a website through soap request.

Why this error is raising while doing a long running process in ASP.Net 2.0 , Answer from the Microsoft is IIS is not designed for a long running process.

 What makes the running thread to be Aborted in ASP.Net ?
  • while any error is raised in your application, if there is no catch block, because of  UnHandledException Thread is begin Aborted abruptly.
  • RoundRobin Request Makes AppDomain to ReCycle.
  • After a IdleTime Out ApplicationPool Automatically Recycles (If there is no more request is received for asp.net page from client more than IdleTimeOut minutes)
   If Recycle  is done by Application Pool, then following are the Reasons 

IIS may have recycled the application pool for whatever reason.

IIS may have restarted

Some settings on the server that limits asp.net execution time.


  To Avoid the thread Being Aborted , if it process by Application pool, Increase the Execution Time Out of Web  Service

Change the web.config file and setting in IIS.

Increase the executionTimeOut and application pool ideal time out.


Timeout in Debug mode
          Default script timeout on IIS is only 90 seconds. When you start web application in debug mode it is 300 000 seconds (almost a year). So, timeout errors are visible only when running release code.

Change server timeout in Web.config

              If you want to have an option to change server timeout value later, after code is compiled, one of easy ways is to change it as parameter through a web.config. You can set server timeout with code like this:    Default executionTimeout is 90 seconds.

<configuration>
   <system.web>
      <httpRuntime maxRequestLength="4000" executionTimeout="45" />
   </system.web>
</configuration>


Change Application Pool Ideal Timeout
  1. Open IIS Manager.type inetmgr in run
  2. In the Connections pane, expand the server node and click Application Pools.
  3. On the Application Pools page, select the application pool for which you want to specify idle time-out settings, and then click Advanced Settings in the Actionspane.
  4. In the Idle Time-out (minutes) box, type a number of minutes, and then click OK.






Problem with application restart when running long tasks in ASP.NET

when work with long running tasks. Application could restart because of different outside reasons, and then your long operation is stopped too. The reason can be
  • Change in global.asax file
  • Change in web.config file
  • Change in machine.config file
  • Change in content of bin folder 
  • Add a new folder inside App folder
  • Even some antivirus also reason

    Health Monitoring 
          How we can find out which makes the Thread being Aborted for ASP.Net ?

Health Monitoring : Health Monitoring is the One of the Framework that is forgotten by Asp.Net Developers. It Provides great Monitoring features in Diagnose Failing Application and systems. Asp.Net Errors are placed in system event logs.

To Enable that Change in Master Web.Config file which is placed in Dotnet framework installation directory %WINDIR%\Microsoft.NET\Framework\version\CONFIG . From the Config file we removed some 
markup to show clearly.

 <configuration>
  <system.web>
  <healthMonitoring>
  <eventMappings>
    <add name="All Errors" type="System.Web.Management.WebBaseErrorEvent,System.Web,Version=2.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a" startEventCode="0" endEventCode="2147483647"/>
    <add name="Failure Audits" type="System.Web.Management.WebFailureAuditEvent,System.Web,Version=2.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a" startEventCode="0" endEventCode="2147483647"/>
  </eventMappings>

  <providers>
    <add name="EventLogProvider" type="System.Web.Management.EventLogWebEventProvider,System.Web,Version=2.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a"/>
    <add connectionStringName="LocalSqlServer" maxEventDetailsLength="1073741823" buffer="false" bufferMode="Notification" name="SqlWebEventProvider" type="System.Web.Management.SqlWebEventProvider,System.Web,Version=2.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a"/>
  </providers>

  <rules>
  <add name="All Errors Default" eventName="All Errors" provider="EventLogProvider" profile="Default" minInstances="1" maxLimit="Infinite" minInterval="00:01:00" custom=""/>
 <add name="Failure Audits Default" eventName="Failure Audits" provider="EventLogProvider" profile="Default" minInstances="1" maxLimit="Infinite" minInterval="00:01:00" custom=""/>
  </rules>
  </healthMonitoring>
  </system.web>
</configuration>
 

Health Monitoring :
1. Monitor the health and performance of the application.
2. Diagnose the application or system failures.
3. appraise significant events during the life cycle of an application.
4. Monitor live ASP.NET applications, individually or across a Web farm.
5. Log events that do not necessarily relate to errors in an ASP.NET application.

the <eventMappings> element assigns the human-friendly name "All Errors" to  the health monitoring events of type WebBaseErrorEvent and the name "Failure Audits" to health monitoring events of type WebFailureAuditEvent

The <providers> element defines the log sources,The first <add> element defines the "EventLogProvider" provider, which logs the specified health monitoring events using the EventLogWebEventProvider class. The EventLogWebEventProvider class logs the event to the Windows Event Log. The second <add> element defines the "SqlWebEventProvider" provider, which logs events to a Microsoft SQL Server database via the SqlWebEventProvider class. The "SqlWebEventProvider" configuration specifies the database's connection string (connectionStringName) among other configuration options.

The <rules> element maps the events specified in the <eventMappings> element to log sources in the<providers> element. By default, ASP.NET web applications log all unhandled exceptions and audit failures to the Windows Event Log.


Now change the Web.Config file in your Asp.Net Application
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0">
    </compilation>

    <healthMonitoring enabled="true" heartbeatInterval="120">
      <rules>
        <add name="Heartbeats Default" eventName="Heartbeats" provider="EventLogProvider"
              profile="Default" />
        <add name="Application Lifetime Events Default" 
              eventName="Application Lifetime Events" 
              provider="EventLogProvider"
              profile="Default" />
        <add name="Request Processing Events Default" 
              eventName="Request Processing Events" 
              provider="EventLogProvider"
              profile="Default" />
      </rules>
    </healthMonitoring>
  </system.web>
</configuration>
After deploy the application , when we launch the application we can see the event log with codes 1001 , 1002 gives information about application start up and shut down. code 1005 traced every 120 seconds (hearbeatinterval = 120).
From this log we can say whether our application is consuming to much memory or queuedin user request.
From This article we can find the various possibilities of Thread Aborting for a long running task,
And Process of Health Monitoring