Tuesday, June 23, 2015

Events in ASP.NET Program

Events

ASP.NET is an event-driven way of making web applications. With PHP and Classic ASP, you have one file, which is executed line after line, from start to end. However, ASP.NET is very different. Here we have events, which are either activated by the user in one way or another. In the previous example, we used the Page_Load method. Actually, this is an event, which the Page class calls when the page is loaded. We will use the same technique in the next example, where we will add a couple of controls to our simple hello world example. To make it a bit more interesting, we will change the "world" word with something defined by the user. Have a look at this codelisting, where we add two new controls: A Button control and a TextBox control.

<form id="form1" runat="server">
<div>
    <asp:Label runat="server" id="HelloWorldLabel"></asp:Label>
    <br /><br />
    <asp:TextBox runat="server" id="TextInput" /> 
    <asp:Button runat="server" id="GreetButton" text="Say Hello!" />
</div>
</form>
As you can see, we now have the 2 new controls added, but they really can't do much at the moment. You can run the example if you wish to check this out for your self - if you click the button, the page is simply reloaded. Let's change that, and let's start by doing it the easy way. VWD comes with a WYSIWYG editor, and while I hardly ever use it my self, it does make some things easier, like creating events. So, click the Design button in the bottom of VWD. Now you will see a visual representation of our page. We wish to add a Click event to the button, and this is very simply - just doubleclick the GreetButton, and you will be taken to the CodeBehind file of our page. As you can see, a fine new method has been added, called GreetButton_Click. If you have a look at the Default.aspx file (you need to go from Design view to Source view), you will see that an attribute has been added to our Button control, telling which method to call when the button is clicked. All this work done with a simple doubleclick. 

Now lets add some code to our new event. We wish to use the text from the TextBox, on our good old Label with the "Hello, world!" text. This is also very simple, and all it requires is a single line of code:


HelloWorldLabel.Text = "Hello, " + TextInput.Text;
Run the project again (F6), and you will see the our old page with a couple of new controls. The "Hello, world!" text is still there, because we set it in the Page_Load event. Now try entering a name in the textbox, and press the button. Voila, the text is changed, and we have just used our first control event. Notice how we can add code which is not necessarily called unless the user performs a specific task. This is different from the good old Classic ASP/PHP approach, but you will soon get used to it, and you will probably also come to like it a lot! 

Sunday, June 21, 2015

Twitter Bootstrap Pages




Twitter Bootstrap 20 Static Content Pages developed for a Greenfield project



I designed 20 static pages in MVC3 using HTML, Twitter Bootstrap CSS, JQuery. The gradient color combination and the entire flow looks like the site: 

1. http://www.microsoft.com/expression

2. http://demos.kendoui.com/web/datasource/remote-data.html







Add Article
I designed this page using twitter bootstrap css.





Add Note

When the 'Add Note' button is clicked a modal dialog appears where you can add data.



Add Profile
In this page I added 3 information widgets and a ListView with gradient background.




Add Service
In this page when 'Add Service' button is clicked, a modal dialog appears where you can add data. This data will be stored in SQL Server.



Add User
This page is designed to add details of the new users. The dropdown list and textboxes are designed to give a professional look.



Blog Details
This page is designed to display the details of the article. Here rich textbox is added where you can style your text. Also I added a Info widget on this page.





Blog Main
This page is designed blog summary in a table.





Contact Us





Manger Users
Twitter Bootstrap JQuery datatable added on this page with table paging, Add User and Search buttons.





Modal Generic Document Viewer 1
This page has a button which when clicked opens a modal dialog with image slideshow





Modal Generic Document Viewer 2
Image slide show in modal dialog. There are 4 buttons at the bottom for Downloading the image, Slideshow of all the images, display next image and previous image.




My Notifications
Here twitter bootstrap jquery datatable is used with pagination.




Partner Registration
This page displays textboxes, dropdown lists with Info widgets. I designed this page keeping in mind that the look and feel and the flow of the entire project should be same.





Profile Details
In this page the critical part was to create a list view similar to http://demos.kendoui.com/web/datasource/remote-data.html
Here the ListView should be with pagination instead of scrolling. I used JQuery for pagination of ListView.




Report
This page is designed with Info widgets and alerts using twitter bootstrap css.





Search
Simple search page with professional look and feel.




Search Result
In this page ListView with gradient background color is created. This ListView is with pagination and a search button.


Service Reports
This page contains an Info widget and a simple JQuery datatable with pagination




Update Service
For the page the requirement was that the textarea for 'Peer Note' should be re-sizable with fixed width and resize height. Usually when we expand a textarea the width and height both increase/decrease. I used CSS style to fix the width and resize the height of the textarea




Add Parcel
A simple page with professional look and feel and gradient color combination look like the site http://www.microsoft.com/expression/






Edit Profile
The color combination and the flow of  the page look like the site http://www.microsoft.com/expression/




























Monday, June 8, 2015

Sutra1

Sutra 1 - Ekadhikena Purvena

Meaning: By one more than the one before

Examples:

Square of numbers ending with 5 :

1) 255
= 2 X 3 | 52
= 6 | 25
Answer = 625

    Vedic Maths (Index)

    Vedic Maths Tutorials

    Brief History

    16 Sutras

    Sutra 2 - Nikhilam Navastascaramam Dasatah
    Sutra 3 - Urdhva-Tiryagbhyam
    Sutra 4 - Paravartya Yojayet
    Sutra 5 - Shunyam Samyasamuchchaye
    Sutra 6 - Aanyarupaye Sunyamanyat
    Sutra 7 - Sankalana-Vyavakalanabhyam
    Sutra 8 - Purna Puranabhyam
    Sutra 9 - Chalana-Kalanabhyam
    Sutra 10 - Yavadunam
    Sutra 11 - Vyasti Samastih
    Sutra 12 - Sesanyankena Caramena
    Sutra 13 - Sopantyadyamantyam
    Sutra 14 - Ekanyunena Purvena
    Sutra 15 - Gunitasamuchchaya
    Sutra 16 - Gunakasamuchchaye

    16 Sub-Sutras

    Sutra 1 - Anurupyena
    Sutra 2 - Sisyate Sesasmjnah
    Sutra 3 - Adyamadye Nantyamantyna
    Sutra 4 - Kevalaih Saptakam Gunyat
    Sutra 5 - Vestanam
    Sutra 6 - Yavadunam Tavadunam
    Sutra 7 - Yavadunam Tavadunikritya Vargancha Yojayet
    Sutra 8 - Antyayordashake 'pi'
    Sutra 9 - Antyayoreva
    Sutra 10 - Samuchchaya Gunitah
    Sutra 11 - Lopanasthapanabhayam
    Sutra 12 - Vilokanam
    Sutra 13 - Gunita Samuchchaya Samuchchaya Gunitah
    Sutra 14 - Dhvajanka
    Sutra 15 - Dwandwa Yoga
    Sutra 16 - Sudha

      Developer Links

      Sunday, June 7, 2015

      Creating First Website


      Introduction

      In VisualStudio, Open the File menu and select "New Web Site". You will be presented with the following dialog: 



      You need to select "ASP.NET Web Site", if it's not already selected. You should also name your new site. This is done by entering a name in the Location box. This text box is probably already filled for you, with the last part being something like "Website1". You can choose to accept this, as well as the location of the project, or you can enter a new one. I have created a folder, "My Websites", and within this folder, I would like to create the new project with the name of "WebSite1". For now, this is less important, but later on you might wish to gather all your projects in a specific folder. 

      This tutorial will focus on the C# language. Once again, no knowledge of this is required, so if you already know another .NET language, you will get to learn some C# with this tutorial as well. Select C# in the Language dropdown. Now, click the Ok button to create this new website. 

      VisualStudio2012 will create a very basic website for you, consisting only of a Default.aspx file (and it's partner, the Default.aspx.cs file) and an App_Data folder. We will only use the Default.aspx for this first example. Move on to the next chapter, for the obligatory "Hello, world!" example. 




      Next Chapter:

      News 8 June 2015

      News 7 June 2015

      aspnet introduction

      Introduction

      ASP.NET is a development framework for building web pages and web sites with HTML, CSS, JavaScript and server scripting.
      ASP.NET supports three different development models:
      1. Web Pages,

      2. MVC (Model View Controller), and 

      3.Web Forms
      ASP.NET is a programming framework developed by Microsoft
      for building powerful Web applications.

      Language Support

      ASP.NET has built-in support for three languages: Visual
      Basic (VB), C#, and Jscript.

      Web Forms

      ASP.NET Forms gives you the ability to create Web pages on
      the .NEST platform.

      Web Controls

      Standard Web Controls

      Label

      default.aspx
      protected void Button1_Click(object sender, EventArgs e)
          {
              if (TextBox1.Text != "")
              {
                  Response.Redirect("Page1.aspx?cname=" + TextBox1.Text);
              }
              else
              {
                  Label2.Text = "Please enter text in textbox";
              }
          }
      Page1.aspx
      protected void Page_Load(object sender, EventArgs e)
          {
              Label1.Text = Request.Params["cname"];
          }

      Saturday, June 6, 2015

      Multi-Threading

      MULTITHREADING

      Multithreading allows an application to divide tasks such that they work independently of each other to make the most efficient use of the processor and the user’s time. Threading is not always the right choice for all applications as they sometimes slows down the processing speed of the application.

      Thread

      Every application runs with at least one thread. A thread is nothing more than a process. On the computer, a thread is a process moving through time. The process performs sets of sequential steps, each step executing a line of code. The steps are sequential and take a given amount of time. The time it takes to complete a series of steps is the sum of the time it takes to perform each programming step.

      Multithreading applications

      For a long time, most programming applications were single threaded. That means there was only thread in the entire application. You could never do computation A until completing computation B. A multithreaded application allows you to run several threads, each thread running in its own process. So theoretically you can run computation A in one thread, and at the same time Computation B in another thread. At the same time you could run computation C, D in their own threads. Hence computation A, B, C and D would run concurrently. Theoretically, if all four computations took about the same time, you could finish you program in a quarter of the time it takes to run a single thread. 

      ThreadStart() and Thread() class

      using System.Threading;
      public class dummy
      {
      public static void prt()
      {
      System.Console.WriteLine("Hi");
      }
      }
      public class thread
      {
      public static void Main()
      {
      ThreadStart ts = new ThreadStart(dummy.prt);
      Thread t = new Thread(ts);
      System.Console.WriteLine("Before Start");
      t.Start();
      }
      }

      Start() method

      using System.Threading;
      public class dummy
      {
      public void prt()
      {
      System.Console.WriteLine("Hi");
      }
      }
      public class thread
      {
      public static void Main()
      {
      dummy obj = new dummy();
      Thread t = new Thread (new ThreadStart(obj.prt));
      t.Start();
      }
      }

      2 threads running

      using System.Threading;
      public class dummy
      {
      public void prt()
      {
      for (int i=0; i<=3; i++) { System.Console.WriteLine(i + " "); } } public void disp() { for(int i= 0; i<=3; i++) { System.Console.WriteLine(i + "..."); } } } public class thread { public static void Main() { dummy obj = new dummy(); Thread t = new Thread (new ThreadStart(obj.prt)); Thread t1 = new Thread(new ThreadStart(obj.prt)); t.Start(); t1.Start(); } }

      Sleep() method

      using System.Threading;
      public class dummy
      {
      public void prt()
      {
      for (int i=0; i<=3; i++) { System.Console.WriteLine(i + " "); Thread.Sleep(500); } } public void disp() { for(int i= 0; i<=3; i++) { System.Console.WriteLine(i + "..."); Thread.Sleep(500); } } } public class thread { public static void Main() { dummy obj = new dummy(); Thread t = new Thread (new ThreadStart(obj.prt)); Thread t1 = new Thread(new ThreadStart(obj.prt)); t.Start(); t1.Start(); } }

      Name property

      using System.Threading;
      public class dummy
      {
      public void prt()
      {
      for (int i=0; i<=3; i++) { Thread t2 = Thread.CurrentThread; System.Console.WriteLine(i + "," + t2.Name + " "); Thread.Sleep(500); } } } public class thread { public static void Main() { dummy obj = new dummy(); Thread t = new Thread (new ThreadStart(obj.prt)); Thread t1 = new Thread(new ThreadStart(obj.prt)); t.Name = "One"; t1.Name = "Two"; t.Start(); t1.Start(); } }

      Abort(), IsAlive() methods

      using System.Threading;
      public class dummy
      {
      public void prt()
      {
      System.Console.WriteLine("Hi!");
      Thread.Sleep(10);
      }
      }
      public class thread
      {
      public static void Main()
      {
      dummy obj = new dummy();
      Thread t = new Thread (new ThreadStart(obj.prt));
      System.Console.WriteLine(t.IsAlive);
      t.Start();
      System.Console.WriteLine(t.IsAlive);
      t.Abort();
      System.Console.WriteLine(t.IsAlive);
      }
      }

      Running a thread till it is alive

      Example 1
      using System.Threading;
      public class dummy
      {
      public void prt()
      {
      System.Console.WriteLine("Hi!");
      }
      }
      public class thread
      {
      public static void Main()
      {
      dummy obj = new dummy();
      Thread t = new Thread (new ThreadStart(obj.prt));
      t.Start();
      while (!t.IsAlive)
      System.Console.WriteLine("Hi");
      }
      }
      Example 2
      using System.Threading;
      public class dummy
      {
      public void prt()
      {
      for (int i=0; i<=3; i++) System.Console.WriteLine("Hi!" + i + " "); } } public class thread { public static void Main() { dummy obj = new dummy(); Thread t = new Thread (new ThreadStart(obj.prt)); t.Start(); System.Console.WriteLine("Over"); } }

      Thread: Start(), Join()

      Example 1
      using System.Threading;
      public class dummy
      {
      public void prt()
      {
      for (int i=0; i<=3; i++) System.Console.WriteLine("Hi!" + i + " "); } } public class thread { public static void Main() { dummy obj = new dummy(); Thread t = new Thread (new ThreadStart(obj.prt)); t.Start(); t.Join(); System.Console.WriteLine("Over"); } }
      Example 2
      using System.Threading;
      public class dummy
      {
      public void prt()
      {
      for ( ; ; ) ;
      }
      }
      public class thread
      {
      public static void Main()
      {
      dummy obj = new dummy();
      Thread t = new Thread (new ThreadStart(obj.prt));
      t.Start();
      bool b = t.Join(10000);
      System.Console.WriteLine("Over " + b) ;
      }
      }
      Example 3
      using System.Threading;
      public class dummy
      {
      public void prt()
      {
      System.Console.WriteLine("function running");
      }
      }
      public class thread
      {
      public static void Main()
      {
      dummy obj = new dummy();
      Thread t = new Thread (new ThreadStart(obj.prt));
      t.Start();
      Thread.Sleep(200);
      t.Abort();
      System.Console.WriteLine("Over ") ;
      Thread.Sleep(200);
      try
      {
      t.Start();
      }
      catch(ThreadStateException e)
      {
      System.Console.WriteLine("In Exception " + e);
      }
      }
      }

      ApartmentState

      using System.Threading;
      public class dummy
      {
      public void prt()
      {
      System.Console.WriteLine("function running");
      }
      }
      public class thread
      {
      public static void Main()
      {
      dummy obj = new dummy();
      Thread t = new Thread (new ThreadStart(obj.prt));
      System.Console.WriteLine(t.ApartmentState);
      t.ApartmentState = ApartmentState.STA;
      t.Start();
      System.Console.WriteLine(t.ApartmentState);
      }
      }

      IsBackground property

      using System.Threading;
      public class dummy
      {
      public void prt()
      {
      System.Console.WriteLine( "prt() " + Thread.CurrentThread.IsBackground);
      }
      }
      public class thread
      {
      public static void Main()
      {
      dummy obj = new dummy();
      Thread t = new Thread (new ThreadStart(obj.prt));
      System.Console.WriteLine("Main " + Thread.CurrentThread.IsBackground);
      t.Start();
      }
      }

      Creating a background thread

      using System.Threading;
      public class dummy
      {
      public void prt()
      {
      for(int i=0; i<=100; i++) { System.Console.WriteLine( "prt() " + i); Thread.Sleep(100); } } } public class thread { public static void Main() { dummy obj = new dummy(); Thread t = new Thread (new ThreadStart(obj.prt)); System.Console.WriteLine("Main " + Thread.CurrentThread.IsBackground); t.IsBackground = true; t.Start(); Thread.Sleep(100); } }

      ThreadPriority enum

      Example 1
      using System.Threading;
      public class dummy
      {
      public void prt()
      {
      for(int i=0; i<=10; i++) { System.Console.WriteLine(i + " "); Thread.Sleep(100); } } public void display() { for(int i=0; i<=10; i++) { System.Console.WriteLine(i + "..."); Thread.Sleep(100); } } } public class thread { public static void Main() { dummy obj = new dummy(); Thread t = new Thread (new ThreadStart(obj.prt)); Thread t1 = new Thread(new ThreadStart(obj.display)); System.Console.WriteLine(t.Priority); t.Priority = ThreadPriority.Highest; t1.Priority = ThreadPriority.Lowest; t.Start(); t1.Start(); } }
      Example 2
      using System.Threading;
      public class dummy
      {
      public void prt()
      {
      try
      {
      System.Console.WriteLine("in prt()");
      for(; ; );
      }
      catch (System.Exception e)
      {
      System.Console.WriteLine("In abc Exception " + e.ToString());
      }
      finally
      {
      System.Console.WriteLine("in abc Finally");
      }
      }
      }

      public class thread
      {
      public static void Main()
      {
      dummy obj = new dummy();
      Thread t = new Thread (new ThreadStart(obj.prt));
      t.Start();
      Thread.Sleep(10);
      t.Abort();
      }
      }
      Example 3: 

      using System.Threading;
      public class dummy
      {
      public void prt()
      {
      try
      {
      System.Console.WriteLine("in prt()");
      for(; ; );
      }
      catch (System.Exception e)
      {
      System.Console.WriteLine("In abc Exception " + e.ToString());
      }
      finally
      {
      System.Console.WriteLine("in abc Finally");
      }
      }
      }
      public class thread
      {
      public static void Main()
      {
      dummy obj = new dummy();
      Thread t = new Thread (new ThreadStart(obj.prt));
      t.Abort();
      t.Start();
      }
      }

      Suspend(), Resume() methods using System.Threading;

      public class dummy
      {
      public void prt()
      {
      for(int i=1; i<=10; i++) { System.Console.Write(i + " "); Thread.Sleep(100); } } } public class thread { public static void Main() { dummy obj = new dummy(); Thread t = new Thread (new ThreadStart(obj.prt)); t.Start(); Thread.Sleep(10); t.Suspend(); System.Console.WriteLine("\n After Suspend"); Thread.Sleep(10); System.Console.WriteLine("Before Resume"); t.Resume(); } }

      Mutex

      When two or more threads need to access a shared resource at the same time, the system needs to be in synchronization mechanism to ensure that only one thread at a time uses the resource. Mutex is a synchronization primitive that grants exclusive access to the shared resource to only one thread. If a thread acquires a mutex, the second thread that wants to acquire that mutex is suspended until the first thread releases the mutex. using System;
      using System.Threading;
      class Test
      {
      private static Mutex mut = new Mutex();
      private const int numIterations = 1;
      private const int numThreads = 3;
      static void Main()
      {
      for (int i = 0; i < numThreads; i++) { Thread myThread = new Thread(new ThreadStart(MyThreadProc)); myThread.Name = String.Format("Thread{0}", i + 1); myThread.Start(); } } private static void MyThreadProc() { for (int i = 0; i < numIterations; i++) { UseResource(); } } private static void UseResource() { mut.WaitOne(); Console.WriteLine("{0} has entered the protected area",Thread.CurrentThread.Name); Thread.Sleep(500); Console.WriteLine("{0} is leaving the protected area\r\n",Thread.CurrentThread.Name); mut.ReleaseMutex(); } }

      Mutex - Infinite wait

      using System.Threading;
      public class thread
      {
      static Mutex m;
      public static void Main()
      {
      m = new Mutex(true, "aptech");
      thread obj = new thread();
      Thread t = new Thread(new ThreadStart(thread.prt));
      t.Start();
      }
      public static void prt()
      {
      System.Console.WriteLine("thread start");
      m.WaitOne();
      System.Console.WriteLine("thread end");
      }
      }
      Mutexes using System.Threading;
      public class thread
      {
      static Mutex m;
      public static void Main()
      {
      m = new Mutex(false, "aptech");
      thread obj = new thread();
      System.Console.WriteLine("thread start");
      m.WaitOne();
      System.Console.WriteLine("thread end");
      }
      }

      Locking

      using System;
      using System.Threading;
      class threadSafety
      {
      public static object Compute = new object();
      public static int ValOne, ValTwo;
      static void Divide()
      {
      ValOne = 45;
      ValTwo = 8;
      lock (Compute)
      {
      if (ValOne != 0)
      Console.WriteLine(ValOne / ValTwo);
      ValTwo = 0;
      }
      }
      public static void Main()
      {
      Divide();
      }
      }

      First ASP.NET Program - Hello World


      Hello World! Program



      Let us see how you can say hello to the world from ASP.NET. Open the Default.aspx (if it's not already opened) by doubleclicking it in the Solution Explorer. It already contains a bunch of HTML markup, as well as some stuff you probably won't recognize, like the Page directive in the top, or the runat attribute on the form tag. This will all be explained later, but for now, we want to see some working code. 

      First of all, we will add a Label control to the page. A Label control is some what simple, since it's just used to hold a piece of text. Add the following piece of HTML-looking code somewhere between the set of <form> tags:
      <asp:Label runat="server" id="HelloWorldLabel"></asp:Label>
      
      Secondly, add this script block somewhere on the page, preferably below the Page directive in the top:
      <% HelloWorldLabel.Text =   "Hello,  world!"; %>
      

      If you haven't worked with ASP.NET before, I'm sure there's a bunch of things that you're wondering about now, but as I said, this is all about seeing some results right now. To see the page in action, use Debug -> Start Without Debugging, or simply press F6. VWD will now compile your project, and launch the page you're working on in your default browser. The page will simply have a piece of text which says "Hello, world!" - congratulations, you have just created your first ASP.NET website! Here is the complete code:

      <% HelloWorldLabel.Text = "Hello, world!"; %> <!
      DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      <html xmlns="http://www.w3.org/1999/xhtml" > 
      <head runat="server"> <title>Untitled Page</title>
      </head> 
      <body>
      <form id="form1" runat="server"> 
       <div>
        <asp:Label runat="server" id="HelloWorldLabel"></asp:Label> 
       </div>
      </form>
      </body> 
      </html>

      Friday, June 5, 2015

      NANT

      NANT

      Nant Definition

      NAnt is a console-based tool which allows arbitrary tasks to be grouped, arranged in sequences, and executed in a way that honors declared dependencies.
      Although primarily intended for compiling and deploying applications, it can be used for many other tasks.

      Use Of Nant

      NAnt doesn't dictate how you do anything or what procedures and standards you follow.
      But whatever you do, NAnt will allow you to do it more consistently and more quickly.
      It also allows you to integrate different activities into your build/deployment process, such as document generation, unit testing, logging and notification. Finally, it can reduce downtime in disaster recovery scenarios by giving you a way to rebuild, redeploy and reconfigure applications quickly.

      Advantages Of Nant

      • It's free
      • Open architecture - several extension mechanisms
      • On-line community of users and developers
      • Under active development
      • Small footprint - no registry or GAC usage, simple "xcopy" install
      • Declarative programming model - can reduce logic errors

      Disadvantages Of Nant

      • No vendor support - must rely on kindness of strangers
      • Requires familiarity with XML
      • No GUI - console, command lines and config files not "user friendly"
      • Volatile - frequent releases - technically still beta
      • Not transactional - you must code rollback logic yourself

      Exception Handling In C Sharp

      Exception Handing

      Exception handling is of 2 types:
      • System-level exceptions
      • Application-level exceptions
      System-level exceptions are the exceptions thrown by the system. These exceptions are thrown by the CLR. E.g. exception thrown due to failure in database connection or network connection.

      Application-level exceptions are thrown by user-created applications. E.g. exceptions thrown due to arithmetic operations or referencing any null object.

      InvalidCastException Class 


      using System;
      class InvalidCastError
      {
          static void Main(string[] args)
          {
              try
              {
                  float numOne = 3.14F;
                  Object obj = numOne;
                  int result = (int)obj;
                  Console.WriteLine("Value of numOne = {0}", result);
              }
              catch (InvalidCastException objEx)
              {
                  Console.WriteLine("Message : {0} ", objEx.Message);
                  Console.WriteLine("Error: {0}", objEx);
              }
              catch (Exception ex)
              {
                  Console.WriteLine(ex);
              }
          }
      }

      ArrayTypeMismatchException Class


      using System;
      class ArrayMisMatch
      {
          static void Main(string[] args)
          {
              string[] names = { "James""Jack""Peter" };
              int[] id = { 10, 11, 12 };
              double[] salary = { 1000, 2000, 3000 };
              float[] bonus = new float[3];
              try
              {
                  salary.CopyTo(bonus, 0);
              }
              catch (ArrayTypeMismatchException objType)
              {
                  Console.WriteLine("Error: {0}", objType);
              }
              catch (Exception objEx)
              {
                  Console.WriteLine("Error : {0}", objEx);
              }
          }
      }

      NullReferenceException Class


      using System;
      class Employee
      {
          private string _empName;
          private int _empID;
          public Employee()
          {
              _empName = "David";
              _empID = 101;
          }
          static void Main(string[] args)
          {
              Employee objEmployee = new Employee();
              Employee objEmp = objEmployee;
              objEmployee = null;
              try
              {
                  Console.WriteLine("Employee Name: " + objEmployee._empName);
                  Console.WriteLine("Employee ID: " + objEmployee._empID);
              }
              catch (NullReferenceException objNull)
              {
                  Console.WriteLine("Error: {0}", objNull);
              }
              catch (Exception objEx)
              {
                  Console.WriteLine("Error : {0}", objEx);
              }
          }
      }

      Public Methods of System.Exception Class


      using System;
      class ExceptionMethods
      {
          static void Main(string[] args)
          {
              byte numOne = 200;
              byte numTwo = 5, result = 0;
              try
              {
                  result = checked((byte)(numOne * numTwo));
                  Console.WriteLine("Result = {0}", result);
              }
              catch (Exception objEx)
              {
                  Console.WriteLine("Error  Description : {0}", objEx.ToString());
                  Console.WriteLine("Exception : {0}", objEx.GetType());
              }
          }
      }

      Public Properties Of System.Exception class


      using System;
      class ExceptionMethods
      {
          static void Main(string[] args)
          {
              byte numOne = 200;
              byte numTwo = 5, result = 0;
              try
              {
                  result = checked((byte)(numOne * numTwo));
                  Console.WriteLine("Result = {0}", result);
              }
              catch (OverflowException objEx)
              {
                  Console.WriteLine("Message : {0}", objEx.Message);
                  Console.WriteLine("Source : {0}", objEx.Source);
                  Console.WriteLine("TargetSite : {0}", objEx.TargetSite);
                  Console.WriteLine("StackTrace : {0}", objEx.StackTrace);
              }
              catch (Exception objEx)
              {
                  Console.WriteLine("Error  : {0}", objEx.ToString());
              }
          }
      }

      Finally Keyword


      using System;
      class InvalidCastError
      {
          static void Main(string[] args)
          {
              try
              {
                  float numOne = 3.14F;           
                  Console.WriteLine("Value of numOne = {0}", numOne);
              }
              catch (InvalidCastException objEx)
              {
                  Console.WriteLine("Message : {0} ", objEx.Message);
                  Console.WriteLine("Error: {0}", objEx);
              }
              catch (Exception ex)
              {
                  Console.WriteLine(ex);
              }
              finally
              {
                  Console.WriteLine("End of program");
              }
          }
      }

      Throw keyword - ArgumentNullException()


      using System;
      using System.Collections.Generic;
      using System.Text;
      namespace ConsoleApplication4
      {
          class Program
          {
              static void thro(string name)
              {
                  if (name == null)
                      throw new ArgumentNullException();
                  else
                 
                      Console.WriteLine(name);           
              }
              static void Main(string[] args)
              {
                  try
                  {
                      string name;
                      name = null;
                      thro(name);
                  }
                  catch (ArgumentNullException ex)
                  {
                      System.Console.WriteLine(ex);
                  }
              }
          }
      }

      Nested try catch


      using System;
      using System.Collections.Generic;
      using System.Text;
      namespace ConsoleApplication4
      {
          class Program
          {       
              static void Main(string[] args)
              {
                  string[] names = { "John""James" };
                  int numOne = 0;
                  int result;
                  try
                  {
                      try
                      {
                          result = 133/numOne;
                      }
                      catch(ArithmeticException ae)
                      {
                          System.Console.WriteLine(ae);
                      }
                      names[2] = "aptech";
                  }
                  catch(IndexOutOfRangeException ie)
                  {
                      System.Console.WriteLine();
                      System.Console.WriteLine(ie);
                  }
              }
          }
      }

      User defined exception

      Example 1
      using System;
      using System.Collections.Generic;
      using System.Text;
      namespace ConsoleApplication4
      {
          class Program : Exception
          {
              public Program()
              {
                  Console.WriteLine("Age should be between 17 and 100");
              }       
          }
          class handleExp
          {
              public static void Main()
              {
                  int val;
                  val = Int32.Parse(Console.ReadLine());
                  try
                  {
                      if (val < 17 || val > 100)
                      {
                          throw new Program();
                      }
                      else
                      {
                          Console.WriteLine("welcome to polling booth");
                      }

                  }
                  catch (Program obj)
                  {
                      Console.WriteLine(obj.Message);
                  }               
              }
          }
      }

      Example 2

      using System;
      using System.Collections.Generic;
      using System.Text;
      namespace ConsoleApplication4
      {
          class Program : Exception
          {
              public Program(string msg): base(msg)
              {
                  Console.WriteLine("Constructor invoked");
              }
          }
          class handleExp
          {
              public static void Main()
              {
                  int value;
                  try
                  {
                      value = Int32.Parse(Console.ReadLine());
                      if (value < 10 || value > 100)
                          throw new Program("this exception is going to be thrown by the program");
                      else
                          Console.WriteLine(value);

                  }
                  catch (Program obj)
                  {
                      Console.WriteLine(obj.Message);
                  }
              }
          }
      }

      Tester-Doer Pattern


      using System;
      using System.Collections.Generic;
      using System.Text;
      namespace ConsoleApplication4
      {
          class NumberDoer
          {
              public void Process(int numOne, int numTwo)
              {
                  try
                  {
                      if (numTwo == 0)
                      {
                          throw new DivideByZeroException("Value of divisor is zero");
                      }
                      else
                      {
                          Console.WriteLine("Quotient: " + (numOne / numTwo));
                          Console.WriteLine("Remainder: " + (numOne % numTwo));
                      }
                  } catch (DivideByZeroException objDivide)
                  {
                      Console.WriteLine("Error {0}: " + objDivide);
                  }
              }
          }
          class handleExp
          {
              NumberDoer objDoer = new NumberDoer();
              public void AcceptDetails()
              {
                  int dividend = 0;
                  int divisor = 0;
                  Console.WriteLine("Enter the value of dividend");
                  try
                  {
                      dividend = Convert.ToInt32(Console.ReadLine());
                  }
                  catch (FormatException objForm)
                  {
                      Console.WriteLine("Error : {0}" + objForm);
                  }

                  Console.WriteLine("Enter the value of divisor:");

                  try
                  {
                      divisor = Convert.ToInt32(Console.ReadLine());
                  }
                  catch (FormatException objFormat)
                  {
                      Console.WriteLine("Error: {0}" + objFormat);
                  }

                  if ((dividend > 0) || (divisor > 0))
                  {
                      objDoer.Process(dividend, divisor);
                  }
                  else
                  {
                      Console.WriteLine("Invalid Input");
                  }
              }
              public static void Main()
              {
                  handleExp objTester = new handleExp();
                  objTester.AcceptDetails();                     
              }
          }
      }

      TryParse Pattern


      using System;
      using System.Collections.Generic;
      using System.Text;
      namespace ConsoleApplication4
      {
          class Product
          {
              private int _quantity;
              private float _price;
              private double _sales;
              string _productName;
              public Product()
              {
                  _productName = "Motherboard";
              }
              public void AcceptDetails()
              {
                  Console.WriteLine("Enter the number of " + _productName + " sold");
                  try
                  {
                      _quantity = Int32.Parse(Console.ReadLine());
                  }
                  catch (FormatException objFormat)
                  {
                      Console.WriteLine("Error {0}: " + objFormat);
                      return;
                  }
                  Console.WriteLine("Enter the price of the product");
                  if (float.TryParse((Console.ReadLine()), out _price) == true)
                  {
                      _sales = _price * _quantity;
                  }
                  else
                  {
                      Console.WriteLine("Invalid price inserted");
                  }
                  Console.WriteLine("Product Name: " + _productName);
                  Console.WriteLine("Product Price: " + _price);
                  Console.WriteLine("Quantity sold: " + _quantity);
                  Console.WriteLine("Total Sale Value: " + _sales);
              }
              static void Main(string[] args)
              {
                  Product objGoods = new Product(); objGoods.AcceptDetails();
              }
          }

      }

      System.TypeInitializationException Class


      using System;
      class TypeInitError
      {
          static TypeInitError()
          {
              throw new ApplicationException("This program throws TypeInitializationException error.");
          }
          static void Main(string[] args)
          {
              try
              {
                  TypeInitError objType = new TypeInitError();
              }
              catch (System.TypeInitializationException objEx)
              {
                  Console.WriteLine("ERROR: {0}", objEx);
              }
              catch (Exception objEx)
              {
                  Console.WriteLine("Error : {0}", objEx);
              }
          }
      }

      The throw statement


      using System;
      class RethrowException
      {
          static void Main(string[] args)
          {
              string[] customerNames = new string[3];
              int[] age = new int[3];
              try
              {
                  try
                  {
                      for (int i = 0; i < customerNames.Length; i++)
                      {
                          Console.WriteLine("Enter the name of the  customer: ");
                          customerNames[i] = Console.ReadLine();
                          Console.Write("Enter the age of the Customer:");
                          age[i] = Convert.ToInt32(Console.ReadLine());
                      }
                  }
                  catch (FormatException objEx)
                  {
                      Console.WriteLine("Invalid input");
                      //throw;
                  }
              }
              catch (Exception objEx)
              {
                  Console.WriteLine("Error thrown by the inner catch block  caught in the outer catch block");
              }
          }
      }

      Custom Exception


      using System;
      class NewCustom : Exception
      {
          public NewCustom(string msg) : base(msg)
          {
          }
          static void Main(string[] args)
          {
              int dividend = 133;
              int divisor;
              int result = 0;
              Console.WriteLine("Enter the value of divisor");
              try
              {
                  divisor = Convert.ToInt32(Console.ReadLine());
                  if (divisor == 0)
                  {
                      throw new NewCustom("Zero not allowed here");
                  }
                  if (divisor < 0)
                  {
                      throw new NewCustom("Please enter a positive number");
                  }
                  Console.WriteLine("You entered: " + divisor.ToString());
                  result = dividend / divisor;
              }
              catch (NewCustom objEx)
              {
                  Console.WriteLine("Error :" + objEx.Message);
              }
              Console.WriteLine("Result of division: " + result);
          }