Sunday, 31 August 2014

Store Procedure Code In C#....

               Store Procedure Code In C#.... 
                                               In ASPX.CS
protected void btn_login_Click(object sender, EventArgs e)
        {
            SqlConnection cn = null;
            SqlCommand cmd = null;
            SqlDataReader dr = null;

            try
            {
                //////////////make connection///////////////
                cn = new SqlConnection(@"Data Source=UDAYKOTHARI-PC\SQLEXPRESS;Initial Catalog=DB_LOGIN;Integrated Security=True");

                //////////get connection string///////////

                /////////open cn/////////
                cn.Open();

                /////login logic///////////
                cmd = new SqlCommand("DB_LOGIN",cn);
                cmd.CommandType = CommandType.StoredProcedure;
                    //"SELECT COUNT (*) AS [RF] FROM dbo.tbl_login WHERE @username=username AND @password=password";
                cmd.Parameters.AddWithValue("@username",txt_username.Text);
                cmd.Parameters.AddWithValue("@password", txt_password.Text);

                cmd.Parameters.Add("@cn", SqlDbType.Int);//("@password", SqlDbType.VarChar, 50);
                cmd.Parameters["@cn"].Direction = ParameterDirection.Output;

                cmd.ExecuteNonQuery();
                //cmd.Connection = cn;
                //////////execute query////////////
                //dr = cmd.ExecuteReader();
                //if (dr.Read())
                //{
                    if (Convert.ToInt32( cmd.Parameters["@cn"].Value)>0)
                    {
                        Response.Redirect("Forgetpassword.aspx");
                    }
                    else
                    {
                        
                        Response.Write("INVALID LOGIN");
                    }
                
            }
            catch (Exception adoError)
            {
                Response.Write(adoError.ToString());
            }
            finally
            {
                //dr.Close();
                cmd.Dispose();
                cn.Close();
            }

        }

             Logic In Store Procedure

USE [DB_LOGIN]
GO
/****** Object:  StoredProcedure [dbo].[DB_LOGIN]    Script Date: 09/01/2014 11:58:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[DB_LOGIN] 
-- Add the parameters for the stored procedure here
(@username varchar(50),@password varchar(50),@cn int output)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

    -- Insert statements for procedure here
SELECT @cn=COUNT (*) 
FROM dbo.tbl_login
WHERE username=@username AND password=@password

if(@cn=1)
begin
return 1;
end
else
begin 
return 0;
end



--return @cn;


END

Saturday, 16 August 2014

Register Page Using Standard Controls in the .NET Framework 4.0

Register Page Using Standard Controls in the                       .NET Framework 4.0

                             Register.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="REGISTER.aspx.cs" Inherits="using_standard_control.REGISTER" %>

<!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></title>
</head>
<body background=abstract-orange-background-wallpaper.jpg>
    <%--//////////////////give bachground image here/////////////////--%>
    
    <form id="form1" runat="server">
    <%--//////////////////heading of page////////////////--%>
    <div align=center><h1><font color=navy>  
        Registration Form Page </font></h1></div>
        <hr>
        <br />
        <div align=center>
    &nbsp;&nbsp;&nbsp;&nbsp;<img src="WEB-hdr-REGISTRATION.jpg" align="middle" height="100" width="600" />
    </div>
        <br>
        <%--/////////////////registration form attrubutes starts from here///////////////////--%>
    <p align=center>
        First Name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:TextBox ID="txt_firstname" runat="server" Width="353px" 
            BorderStyle="Solid"></asp:TextBox>
    </p>
    <p align=center>
        Last Name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:TextBox ID="txt_lastname" runat="server" Width="353px" BorderStyle="Solid"></asp:TextBox>
    </p>
    <p align=center>
        Username&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:TextBox ID="txt_username" runat="server" Width="354px" BorderStyle="Solid"></asp:TextBox>
    </p>
    <p align=center>
        Password&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:TextBox ID="txt_password" runat="server" Width="361px" BorderStyle="Solid" 
            style="margin-left: 0px" TextMode="Password"></asp:TextBox>
    </p>
    <p align=center>
        &nbsp;&nbsp;&nbsp;&nbsp; Gender&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:RadioButton ID="btn_male" runat="server" BorderColor="Red" 
            GroupName="gender" />
        Male&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:RadioButton ID="btn_female" runat="server" BorderColor="Red" 
            GroupName="gender" />
        Female</p>
    <p align=center>
        Profile Picture &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 
        <asp:FileUpload ID="FileUpload1" runat="server" Height="34px" Width="258px" 
            style="margin-left: 0px" />
    </p>
    <p align=center>
        <asp:Button ID="btn_register" runat="server" Text="Register" Width="180px" 
            BackColor="#FF5BAD" BorderStyle="Solid" Height="37px" />
    </p>
    </form>
</body>
</html>

                    Register.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace using_standard_control
{
    public partial class REGISTER : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btn_register_Click(object sender, EventArgs e)
        {
            ///////////////////code for uploading images/////////////////
            if (FileUpload1.HasFile)
            {
                FileUpload1.SaveAs("D:"+ FileUpload1.FileName.ToString());
            }
            else
            {
               label_fileupload.Text= "Please Browse the file first.....";
            }
        }
        
    }

}



Login Page Using Standard Control Tools From .NET Framework 4.0

Login Page Using Standard Control Tools                       From .NET Framework 4.0


                                              Login.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="LOGIN.aspx.cs" Inherits="using_standard_control.LOGIN" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div align=center>
    <h1><font color=navy>       Login page </font></h1></div>
    <hr>
    <br>
    <br>
   <%-- //////////////////////////Username text box////////////////////--%>
    <p align=center>
        <font color=maroon>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; UserName&nbsp;&nbsp;&nbsp;
        <asp:TextBox ID="txt_username" runat="server" Width="268px" BackColor="#BFD5D5" 
            Height="29px" ontextchanged="txt_username_TextChanged"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
            ErrorMessage="Enter Valid Username" ControlToValidate="txt_username"></asp:RequiredFieldValidator>
        </font>
    </p>
    <%--//////////////////////////////Password text box ///////////////////--%>
    <p align=center>
        <font color=maroon>Password&nbsp;&nbsp;&nbsp; &nbsp;<asp:TextBox 
            ID="txt_password" runat="server" Width="267px" BackColor="#BFD5D5" 
            Height="32px" TextMode="Password" ontextchanged="txt_password_TextChanged"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
            ErrorMessage="Wrong Password" ControlToValidate="txt_password"></asp:RequiredFieldValidator>
        </font>
    </p>
    <%--///////////////login button/////////////--%>
    <p align=center>
        &nbsp;
        <asp:Button ID="btn_login" runat="server" BackColor="White" BorderColor="Red" 
            BorderStyle="Solid" ForeColor="#AA600D" Text="Login" Width="158px" 
            Height="45px" onclick="btn_login_Click" />
    </p>
    </form>
</body>
</html>

                        Login.aspx.cs

   In the .aspx.cs file we write the business logic for any webpage.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace using_standard_control
{
    public partial class LOGIN : System.Web.UI.Page
    {
        
       protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void txt_username_TextChanged(object sender, EventArgs e)
        {
            
            }

        protected void txt_password_TextChanged(object sender, EventArgs e)
        {

        }

        protected void btn_login_Click(object sender, EventArgs e)
        {
            if (txt_username.Text.Equals("Compulink") && txt_password.Text.Equals("12345"))
            {
                Response.Redirect("REGISTER.aspx");
            }
            else {
                Response.Write("ERROR while login");
            }
        }
    }
}



Friday, 8 August 2014

Technical Test Paper 4 on C# with MCQ's

     Technical Test Paper 4 with MCQ's

(Serialization,Exception Handling,Reflection)

1.Select whichamong is NOT an exception?
a)stackOverflow
b)arithmeticOverflow or underflow
c)Incorrect Arithmetic Expression
d)All of the above mentioned

Ans:- c) Incorrect Arithmatic Expression

2.Select which among is NOT considered as .NET Exception class?
a)Exception
b)StackUnderflowException
c)File Found Exception
d)Divide By Zero Exception

Ans:- c) File Found Exception

3.Select the statements which describes correctly usage of exception handling over conventional error handling approaches?
a.As errors can be ingnored but exception cannot be ignored
b)Exception handling allows seperation of progaram's logic from error handling logic making software more reliable and maintainable.
c)try-catch-finally structure allows guaranteed cleanup in event of errors under all circumstances
d) All of the above mentionaed

Ans:- d) All of the above mentionaed

4.Select the correct statement about an Exception?
a)It occurs during loading of program
b)It occurs during Just-In-Time compilation
c)It occurs at run-time
d)all of the above mentioned

Ans:- c) It occures at run time.

5.Which of these keywords is used to manually throw an exception?
a)try
b)finally
c)throw
d)catch

Ans:-throw

6.Choose the correct for given set of code:
 class program
 {
     static void main(String []args)
     {
         int i=5;
         int v=40;
         int[]p=new int[4];
      try
       {
         p[i]=v;
        }
      catch(IndexOutOfRangeException e)
       {
         Console.WriteLine("Index out of bounds");
       }
         Console.WriteLine("Remaining program");
       }
  }


a)value 40 will be assigned to a[ 5 ]:
b)The output will be:
    Index out of bounds
    Remaining program
c) The output will be:
    Remaining program
d) None of the above mentioned

Ans:-   Index out of bounds
           Remaining program

7.Which is correct satement about exception handling in C#.NET?

a)finally clause is used to perform cleanup operatinos of closing network and database connections
b)a program can contain multiple finally clauses
c)The statements in final clause will get executed no matter whether an exception occurs or not
d)All of the above mentioned

Ans:- a & b

8.Coose the correct output for given set of code:
static void main(string[]args)
{
  try
   {
     Console.WriteLine("csharp"+""+1/Convert.ToInt32(0));
    }
  catch(ArithmeticException e)
   {
         Console.WriteLine("Java");
   }
 Console.ReadLine();
}

a)csharp
b)java
c)Run time error
d)csharp 0

Ans:- java


9.Which feature enables to obtain information about use and capabilities of runtime?

a)Runtime type ID
b)Reflection
c)Attributes
d)None of the mentionaed

Ans:- Reflection

10.Choose the namespace which consists of classes that are part of .NET Reflection API:

a)System.Text
b)Syatem.Name
c)Syatem.Reflection
d)None of the mentioned

  Ans:-System .Reflection

11.Choose the correct statement about System.Type namespace:

a)Core the reflection subsystem as encapsulates a type
b)Consist of many methods and properties taht can be obtain information about a type at run-time
c)Both a&b
d)Only b

Ans:- c) Both a&b

12.Choose the class From which the namespace 'System.Type' is derived:

a)Systems.Reflection
b)System.Reflection.MemberInfo
c) Both a&b
d)None of the mentioned

Ans:-b)System.Reflection.MemberInfo

13.What does the following deceleration specifies?
a)Returns an array of MethodInfo object
b)Returns a list of the public methods supported by the type by using Getmethods( )
c)Both a&b
d)None of the mentioned

Ans:-1.Returns an array of MethodInfo objects.
           2.Return a list of public methods supported by type using Getmethods( )

14.Explain Serialization and Deserialization in C#? 
Ans:-
  • Serialization:-It is the process of converting an object into stream of bytes.
  • Deserialization:-Deserialization is the process of converting stream of bytes into object.
  • There are 2 types of serialization.
           1. Binary Serialization.
           2. XML Serialization.


  • We need to use namespace:
             1. System.Runtime.Serialization
             2.System.Runtime.Serialization.

  • If we have to use string data, then there is no need  of serializable.
  • It is used in case of complex data.
Program :- To store object in file and

read it using serialization.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Serialization_eg

{

class Program

{

static void Main(string[] args)

{

//Serialization

FileStream fs = new

FileStream("C:\\SDemo.txt",

FileMode.Create);

BinaryFormatter obj = new

BinaryFormatter();

obj.Serialize(fs, DateTime.Now);

fs.Close();

//DeSerialization

FileStream fs = new

FileStream("C:\\SDemo.txt",

FileMode.Open);

BinaryFormatter obj = new

BinaryFormatter();

DateTime dt =

(DateTime)(obj.Deserialize(fs));

Console.WriteLine(dt.Date);

}

}

}

Program :- To Serialize Our Own Class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace Serialize_own_class


[Serializable]


class Product
{

public string Name;
public double Price;
public int Quantity;
public double Total;
public Product(string n, double p, int q)
{


Name = n;
Price = p;
Quantity = q;
Total = Price + Quantity;
}

}

class Program
{
static void Main(string[] args)
{

// Serialization\\\\\\\\\

Product p = new Product("Comp", 1000, 5);

FileStream fs = new FileStream("C:\\SerDemo.txt",
FileMode.Create);

BinaryFormatter obj = new BinaryFormatter();

obj.Serialize(fs, p);
fs.Close();

//Deserialization\\\\\\

FileStream fs = new
FileStream("C:\\SerDemo.txt", FileMode.Open);

BinaryFormatter obj = new
BinaryFormatter();

Product p = (Product)
obj.Deserialize(fs);

Console.WriteLine(p.Name);
Console.WriteLine(p.Quantity);
Console.WriteLine(p.Total);
fs.Close();

  }
}
  • If we don’t want particular variable to be serialized then use [NonSerialized] .
  • IDeserialization CallBack is a method. It should be written in front of class name.
  • If we want to implement it, then  
\\\\\\\\\\\\\\\\\\\\\\useOnDeserialization\\\\\\\\\\\\

Program :- To make use of NonSerialize.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
usingSystem.Runtime.Serialization.Formatters.Binary;

namespace Serialize_Nonserialize

[Serializable]

class Product : IDeserializationCallback
//class Product
{

public string Name;
public double Price;
public int Quantity;


[NonSerialized]

public double Total;
public Product(string n, double p, int q)
{
Price = p;
Quantity = q;
}
public void OnDeserialization(object sender)
{
Total = Price * Quantity;
}
}

class Program
{
static void Main(string[] args)
{

\\\\\\\\\\\// Serialization\\\\\\\\\\\

Product p = new Product("Comp", 1000, 5);
FileStream fs = new
BinaryFormatter obj = new BinaryFormatter();
obj.Serialize(fs, p);
fs.Close();

\\\\\\\\\\\\\//Deserialization\\\\\\\\\\\\\\

FileStream fs = new
BinaryFormatter obj = new BinaryFormatter();
Product p = (Product)obj.Deserialize(fs);
Console.WriteLine(p.Name);
Console.WriteLine(p.Quantity);
Console.WriteLine(p.Total);
fs.Close();
        }
     }
}









Tuesday, 5 August 2014

Examples on Types of Exception Handling

    Examples on Types of Exception Handling

1)Example of SystemIO.IOException:-

using System;
using System.IO;

class Program
{
    static void Main(String[] args)
    {
        try
        {
            File.Open("C:\\anuragdhamal\\new.txt", FileMode.Open);
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("Not found");
        }
        catch (IOException)
        {
            Console.WriteLine("IO");
        }

    }
}

output:
IO
Press Any Key To Countinue....

2) Example Of System.IndexOutofRange:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication5_IndexOutOfRangeExc
{

    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = new int[2];
            try
            {
                numbers[0] = 11;
                numbers[1] = 21;
                //  numbers[2] = 24; // here if we uncomment this line then exception is gets raised

                foreach (int i in numbers)
                    Console.WriteLine(i);
            }
            catch (IndexOutOfRangeException ex)
            {
                Console.WriteLine("An index out of range! occure" + ex);
                Console.WriteLine("HelpLink = {0}", ex.HelpLink);
                Console.WriteLine("Message = {0}", ex.Message);
                Console.WriteLine("Source = {0}", ex.Source);
                Console.WriteLine("StackTrace = {0}", ex.StackTrace);
            }

            finally
            {
                Console.WriteLine("Task completed");
            }
            Console.ReadLine();

        }
    }
}

Output:-
11
21
Task Complete

3)Example Of SystemArrayTypeMismatchException:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication5_ArrayTypeMismatchExc
{
    class Class1
    {
        static void Main(string[] args)
        {
            string[] names = { "Anurag", "Dhamal", "compulink" };
            object[] objs = (object[])names;
            try
            {
                objs[2] = "Academy";
                foreach (object Name in objs)
                {
                    Console.WriteLine(Name);
                }
            }
            catch (ArrayTypeMismatchException e1)
            {
                // Not reached; "Academy" is of the correct type.
                System.Console.WriteLine("Exception Thrown.");
            }
            try
            {
                Object obj = (Object)13;
                objs[2] = obj;
            }
            catch (ArrayTypeMismatchException e2)
            {
                Console.WriteLine(e2.Message);
                // Always reached, 13 is not a string.
                Console.WriteLine("New element is not of the correct type.");
            }
            // Set objs to an array of objects instead of
            // an array of strings.
            objs = new Object[3];
            try
            {
                objs[0] = (Object)"Shirwal";
                objs[1] = (Object)8;
                objs[2] = (Object)12.12;
                foreach (object element in objs)
                {
                    Console.WriteLine(element);
                }
            }
            catch (ArrayTypeMismatchException)
            {
                // ArrayTypeMismatchException is not thrown this time.
                System.Console.WriteLine("Exception Thrown.");
            }
            Console.ReadLine();
        }
    }
}
output:-









Exception Handling

                              Exception handling

  • C# exceptions are represented by classes. 
  • The exception classes in C# are mainly directly or indirectly derived from the System.Exception class. 
  • Some of the exception classes derived from the System. System.ApplicationException and System.SystemException classes.
The System.ApplicationException class supports exceptions generated by application programs. So the exceptions defined by the programmers should derive from this class. The System.SystemException class is the base class for all predefined system exception.
The following table provides some of the predefined exception classes derived from the Sytem.SystemException class:
Exception ClassDescription
System.IO.IOExceptionHandles I/O errors.
System.IndexOutOfRangeExceptionHandles errors generated when a method refers to an array index out of range.
System.ArrayTypeMismatchExceptionHandles errors generated when type is mismatched with the array type.
System.NullReferenceExceptionHandles errors generated from deferencing a null object.
System.DivideByZeroExceptionHandles errors generated from dividing a dividend with zero.
System.InvalidCastExceptionHandles errors generated during typecasting.
System.OutOfMemoryExceptionHandles errors generated from insufficient free memory.
System.StackOverflowExceptionHandles errors generated from stack overflow.


Saturday, 2 August 2014

Technical Test No.2 On C# (Paper with Quation And Answer)

               Technical Test Paper 2

             (File system,collection,Generic,Treading) 

  Q . 1) In which collection is the Input / Output based on key?
   Ans:-    HashTable
                SortedList


 Q. 2)In a HashTable key can not be NULL,but Value can be.
   Ans:-  True

 Q. 3) Which of The following statements are correct about the C#.NET code snippet given ?
     Stack s=new Stack();
                   s.Push("Hello");
                   s.Push(8.2);
                   s.Push(5);
                   s.Push('b');
                   s.Push(true);

 Ans:-  This is perfectly workable code.

 Q. 4) A HashTable t maintains a collection of names of states and capital city of each state.Which  is correct way to find out
wheatther " Kerla '' state is present in this collection or not?


Ans:- t.ContainsKey("Kerla");

Q. 5) Suppose value of the Capacity property of ArrayList Collection is set to 4.What will be the capacity  of the collection on adding fifth element  to it?

Ans:- 8

Q. 6) Which of the following statement are correct about Collection Classes  available in network class  library

Ans:-They use efficient algorithms to manage the collection,thereby improving the performance of the  program.

Q. 7) What is advantages of generics?

Ans:- Generic Provide type safety without the overhead of multiple imlementation.

Q.8) Which are the classes are present in system.Collection.Generic namespaces?
Ans:-   Stack
           SortedDictionary

Q. 9) Trace the output

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApplication4
{
    class Program
    {
        public static void CallToChildThread()
        {
            Console.WriteLine(" child thread starts");
            int sleepfor = 5000;
            Console.WriteLine("Child thread paused for {0} seconds",sleepfor/1000);
            Thread.Sleep(5000);
            Console.WriteLine("child thread resumes");
        }

        static void Main(String[] args)
        {
            ThreadStart childref = new ThreadStart(CallToChildThread );
            Console.WriteLine("In main: creating the child thread");
            Thread childthread = new Thread(childref );
            childthread.Start();
            Console.ReadKey();
        }
    }
}


Ans:-o/p:-
            In main: creating the child thread
            child thread starts
            Child thread paused for 5 seconds
            child thread resumes

 
Q.10) Explain Thread LifeCycle .
Ans:------
    
A thread is defined as the execution path of a program. Each thread defines a unique flow of control. If your application involves complicated and time consuming operations then it is often helpful to set different execution paths or threads, with each thread performing a particular job.
Threads are lightweight processes. One common example of use of thread is implementation of concurrent programming by modern operating systems. Use of threads saves wastage of CPU cycle and increase efficiency of an application.

So far we have written programs where a single thread runs as a single process which is the running instance of the application. However, this way the application can perform one job at a time. To make it execute more than one task at a time, it could be divided into smaller threads.

 The life cycle of a thread starts when an object of the System.Threading.Thread class is created and ends when the thread is terminated or completes execution.
Following are the various states in the life cycle of a thread:
  • The Unstarted State: it is the situation when the instance of the thread is created but the Start method has not been called.
  • The Ready State: it is the situation when the thread is ready to run and waiting CPU cycle.
  • The Not Runnable State: a thread is not runnable, when:
    • Sleep method has been called
    • Wait method has been called
    • Blocked by I/O operations
  • The Dead State: it is the situation when the thread has completed execution or has been aborted.

11. Discuss File System in Detail.

ANS :
FileStream typical use
This is typical code when opening file using FileStream. It's important to always close the stream. If you don't close the stream it can take a minute to be file again accessible (it will wait to garbage collector to free the FileStream instance and close the file).

[C#] Open existing file for read and write.
FileStream fileStream = new FileStream(@"c:\file.txt", FileMode.Open);

[C#] Open existing file for reading.
FileStream fileStream = new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Read);

[C#] Open existing file for writing.
FileStream fileStream = new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Write);

[C#] Open file for writing (with seek to end), if the file doesn't exist create it.
FileStream fileStream = new FileStream(@"c:\file.txt", FileMode.Append);

[C#] Create new file and open it for read and write, if the file exists overwrite it.
FileStream fileStream = new FileStream(@"c:\file.txt", FileMode.Create);

[C#] Create new file and open it for read and write, if the file exists throw exception.
FileStream fileStream = new FileStream(@"c:\file.txt", FileMode.CreateNew);
Example;
         

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";
        if (!File.Exists(path))
        {
            // Create a file to write to.
            using (StreamWriter sw = File.CreateText(path))
            {
                sw.WriteLine("Hello");
                sw.WriteLine("And");
                sw.WriteLine("Welcome");
            }
        }

        // Open the file to read from.
        using (StreamReader sr = File.OpenText(path))
        {
            string s = "";
            while ((s = sr.ReadLine()) != null)
            {
                Console.WriteLine(s);
            }
        }
    }
}