Horizontal Nav

Showing posts with label C# Programming. Show all posts
Showing posts with label C# Programming. Show all posts

Tuesday, 15 July 2014

C# SqlDataReader

SqlDataReader reads database rows one-by-one. It reads in forward order from an SQL database. The SqlDataReader type can be used in a loop to read multiple rows from an SQL database. It provides good performance and strong typing.


Example

Preliminary steps are required before using SqlDataReader on a database table. These steps require configuration on your part. You must target the correct database with a custom connection string and also target the proper table.

To begin, you can create a new SqlConnection and open it. Then you can create a new SqlCommand and call its ExecuteReader method, assigning the reference it returns to an SqlDataReader.

Program that uses SqlDataReader with SqlClient: C#
using System;

using System.Data.SqlClient;
class Program

{

    static void Main()

    {

       //

       // You need to access the project's connection string here.

       //



       string connectionString = ConsoleApplication1.Properties.Settings.Default.ConnectionString;
       //

       // Create new SqlConnection object.

       //
       using (SqlConnection connection = new SqlConnection(connectionString))

       {

           connection.Open();
           //

           // Create new SqlCommand object.

           //
           using (SqlCommand command = new SqlCommand("SELECT * FROM Dogs1", connection))

           {
              //

              // Invoke ExecuteReader method.

              //
              SqlDataReader reader = command.ExecuteReader();

              while (reader.Read())

              {

                  int weight = reader.GetInt32(0);    // Weight int

                  string name = reader.GetString(1);  // Name string

                  string breed = reader.GetString(2); // Breed string
                  //

                  // Write the values read from the database to the screen.

                  //
                  Console.WriteLine("Weight = {0}, Name = {1}, Breed = {2}",weight, name, breed);

              }

           }

       }

    }

}
Output
Weight = 57, Name = Koko, Breed = Shar Pei
Weight = 130, Name = Fido, Breed = Bullmastiff
Weight = 93, Name = Alex, Breed = Anatolian Shepherd Dog
Weight = 25, Name = Charles, Breed = Cavalier King Charles Spaniel
Weight = 7, Name = Candy, Breed = Yorkshire Terrier

Access connection string. Main() first accesses a project-specific ConnectionString. Your project will have its own ConnectionString, which can be generated through the Add Data Source menu item in Visual Studio.

Tip:You must always create a new SqlConnection before using the SqlDataReader code here.

Note:SqlConnection objects use an advanced optimization called connection pooling.

So:Creating these new objects will probably not have a highly adverse affect on overall program performance.

Next, you must create a new SqlCommand object with an SQL text query as its first parameter, and the SqlConnection object reference as its second parameter. This program does not use a stored procedure, which may reduce performance.

Note:The text "SELECT * FROM Dogs1" simply selects all rows from a table called Dogs1 in the database.

Finally, the program creates a new SqlDataReader object from the result of the ExecuteReader() method. The while-loop continues iterating through its loop body as long as the Read() method does not return false.

Tip:This makes it possible to query the SqlDataReader for integers, strings and other types with the GetInt32 and GetString methods.

SqlDataAdapter

A more object-oriented approach to database table reading can be achieved by using DataTables. You can directly populate a DataTable with the data from an SQL database table using the SqlDataAdapter class.

Warning:This approach is slower if you are dealing with vast amounts of data, because all of it must be stored in memory at once.

Summary

We saw the SqlDataReader class. It provides an excellent way to query rows one-by-one from your database tables. It does not require the usage of a DataTable, which can improve performance and decrease memory usage in certain cases.

Tip:Using SqlDataReader is an easy way to print all rows from a table. It is efficient and worth knowing.

C# SqlConnection

The SqlConnection class handles database connections. It initiates a connection to your SQL database. This class is best used in a using resource acquisition statement. We call Open to query the database with SqlCommand.




Example

We emphasize the usage of SqlConnection in a "using" resource acquisition statement. The SqlConnection has a constructor that requires a string reference pointing to the connection string character data.

This connection string is often autogenerated for you by the dialogs in Visual Studio, and sometimes is provided by your hosting company or department. You must include the SqlConnection code before you can perform a database query.

Program that uses SqlConnection: C#
using System;

using System.Data.SqlClient;
class Program

{

    static void Main()

    {
      //

      // First access the connection string.

      // ... This may be autogenerated in Visual Studio.

      //
      string connectionString = ConsoleApplication1.Properties.Settings.Default.ConnectionString;
      //

      // In a using statement, acquire the SqlConnection as a resource.

      //
      using (SqlConnection con = new SqlConnection(connectionString))

      {
          //

          // Open the SqlConnection.

          //
          con.Open();
          //

          // The following code uses an SqlCommand based on the SqlConnection.

          //
          using (SqlCommand command = new SqlCommand("SELECT TOP 2 * FROM Dogs1", con))
          using (SqlDataReader reader = command.ExecuteReader())

          {

             while (reader.Read())

             {

                 Console.WriteLine("{0} {1} {2}",

                   reader.GetInt32(0), reader.GetString(1), reader.GetString(2));
             }

          }

      }

    }

}
 
Output
57 Koko Shar Pei
130 Fido Bullmastiff
This program will not work unless you change the connection string reference to point to a correct one in your environment. To create a connection string to a database, go to the Visual Studio Data menu and select Add New Data Source.

Also:The program assumes the name of an SQL table that will not be present in most databases.

Using statement. The purpose of the using statement in the C# language is to provide a simpler way to specify when the unmanaged resource is needed by your program, and when it is no longer needed.

Internally:The language can transform the using statement into a try-finally statement that calls the Dispose method.

Open method call. The using statement creates a read-only variable of type SqlConnection. You need to actually call the Open method on the SqlConnection instance before using it in an actual SqlCommand.

And:The SqlConnection is passed as the parameter to the SqlCommand. In this way we specify that the SqlCommand "uses" the SqlConnection.

For the example to work correctly, it would need to find the specified SQL table. The specified connection string must be correct. This site contains a more through overview and tutorial of SqlConnection and its supporting constructs.


In the annotated C# language specification, we are advised to use the “using” statement when creating any object that implements the interface IDisposable. Even if the interface does nothing, it is safest to always call it if it exists.

Specification

Note: Many examples of SqlConnection and SqlCommand do not use the using statement reliably, including the one on MSDN.

Summary

We looked at database code. We stressed the proper usage of the SqlConnection class and the resource acquisition pattern. The SqlConnection is required for correctly using other SQL objects such as SqlCommand and SqlDataReader.


Tuesday, 24 June 2014

Difference Between DataReader, DataSet, DataAdapter and DataTable in C#

DataReader
DataReader is used to read the data from database and it is a read and forward only connection oriented architecture during fetch the data from database. DataReader will fetch the data very fast when compared with dataset. Generally we will use ExecuteReader object to bind data to datareader.
To bind DataReader data to GridView we need to write the code like as shown below:

Protected void BindGridview()
{
using (SqlConnection conn = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
SqlDataReader sdr = cmd.ExecuteReader();
gvUserInfo.DataSource = sdr;
gvUserInfo.DataBind();
conn.Close();
}
}
  • Holds the connection open until you are finished (don't forget to close it!).
  • Can typically only be iterated over once
  • Is not as useful for updating back to the database
DataSet
DataSet is a disconnected orient architecture that means there is no need of active connections during work with datasets and it is a collection of DataTables and relations between tables. It is used to hold multiple tables with data. You can select data form tables, create views based on table and ask child rows over relations. Also DataSet provides you with rich features like saving data as XML and loading XML data.
protected void BindGridview()
{
    SqlConnection conn = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test");
    conn.Open();
    SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    gvUserInfo.DataSource = ds;
    gvUserInfo.DataBind();
}

DataAdapter
DataAdapter will acts as a Bridge between DataSet and database. This dataadapter object is used to read the data from database and bind that data to dataset. Dataadapter is a disconnected oriented architecture. Check below sample code to see how to use DataAdapter in code:
protected void BindGridview()
{
    SqlConnection con = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test");
    conn.Open();
    SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    gvUserInfo.DataSource = ds;
    gvUserInfo.DataBind();
}
  • Lets you close the connection as soon it's done loading data, and may even close it for you automatically
  • All of the results are available in memory
  • You can iterate over it as many times as you need, or even look up a specific record by index
  • Has some built-in faculties for updating back to the database.
DataTable 

DataTable represents a single table in the database. It has rows and columns. There is no much difference between dataset and datatable, dataset is simply the collection of datatables.

protected void BindGridview()
{
     SqlConnection con = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test");
     conn.Open();
     SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
     SqlDataAdapter sda = new SqlDataAdapter(cmd);
     DataTable dt = new DataTable();
     da.Fill(dt);
     gridview1.DataSource = dt;
     gvidview1.DataBind();

}

Thursday, 5 June 2014

StringBuilder Class in C#

Most of the programmer use string, as they are easy to use and provides effective interaction with the user. Every time we manipulate a string object we get a new string object created. 

String is immutable means that once it has been created, a string cannot be changed. No characters can be added or removed from it, nor can its length be changed.

The String object is immutable while StringBuilder object is mutable. Both String and StringBuilder are reference type. But String acts like a value type.
StringBuilder is located in the System.Text namespace. 

The following table lists the methods you can use to modify the contents of a StringBuilder.



The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. Using the StringBuilder class can boost performance when concatenating many strings together in a loop.


Method
Description
StringBuilder.Append
Appends information to the end of the current StringBuilder.
StringBuilder.AppendFormat
Replaces a format specifier passed in a string with formatted text.
StringBuilder.Insert
Inserts a string or object into the specified index of the current StringBuilder.
StringBuilder.Remove
Removes a specified number of characters from the current StringBuilder.
StringBuilder.Replace
Replaces a specified character at a specified index.

Program to explain StringBuilder Class

using System;
using System.Text;
namespace StringBuilder_example
{
    class Program
    {
        static void Main(string[] args)
        {
            StringBuilder sbstr = new StringBuilder("We are the world");
            Console.WriteLine(sbstr);           
            sbstr.Append(" we are the people");
            Console.WriteLine(sbstr);
            float currency=3400.50f;
            sbstr.AppendFormat(" Our individual salary : {0:C}. ", currency);
            Console.WriteLine(sbstr);
            sbstr.Insert(11, "people of ");
            Console.WriteLine(sbstr);
            sbstr.Remove(11, 10);
            Console.WriteLine(sbstr);

            sbstr.Replace("world", "Indian");
            Console.WriteLine(sbstr);

            Console.ReadKey();
        }
    }
}


Output of above program


Difference between String and StringBuilder class


String
StringBuilder
System.String is immutable
System.StringBuilder is mutable
Concatenation is used to combine two strings
Append method is used.
The first string is combined to the other string by creating a new copy in the memory as a string object, and then the old string is deleted
Insertion is done on the existing string.
String is efficient for small string manipulation
StringBuilder is more efficient in case large amounts of string manipulations have to be performed



Conclusion

I hope that this article would have helped you in understanding StringBuilder Class in C#. StringBuilder can improve the performance of your application.

Friday, 28 June 2013

C# Enum


Enums store special values. They make programs simpler. If you place constants directly where used, your C# program becomes complex. It becomes hard to change. Enums instead keep these magic constants in a distinct type.

Example

In this first example, we see an enum type that indicates the importance of something. An enum type internally contains an enumerator list. We use enums when we want readable code that uses constants. 
An enum type is a distinct value type that declares a set of named constants.
Hejlsberg et al., p. 585
Program that uses enums: C#

using System;
class Program
{
    enum Importance
    {
None,
Trivial,
Regular,
Important,
Critical
    };

    static void Main()
    {
// 1.
Importance value = Importance.Critical;

// 2.
if (value == Importance.Trivial)
{
   Console.WriteLine("Not true");
}
else if (value == Importance.Critical)
{
   Console.WriteLine("True");
}
    }
}

Output
True


We see a new variable with the identifier "value" is of the Importance type. It is initialized to Importance.Critical in part 1. At part 2, the variable is tested against other enum constants.

Tip:Enums can be used with IntelliSense in Visual Studio. Visual Studio will guess the value you are typing.
So:You can simply press tab and select the enum type you want. This is an advantage to using enum types.

Saturday, 15 June 2013

Difference Between Parameter and Argument

Parameter
Parameter is a variable in the declaration of function.
int add(int x,int y)
{
return x+y;
}
In this example int x,int y are parameters.
Argument
Argument is the actual value of this variable that gets passed to function.
E.g.
int result;
result=add(1,2);

In this example 1,2 are arguments.

Friday, 10 February 2012

What is delegate in C#?


Basically it is similar like the old "C" age function pointer, where functions can be assigned like a variable and called in the run time based on dynamic conditions. C# delegate is the smarter version of function pointer which helps software architects a lot, especially while utilizing design patterns.

At first, a delegate is defined with a specific signature (return type, parameter type and order etc). To invoke a delegate object, one or more methods are required with the EXACT same signature. A delegate object is first created similar like a class object created. The delegate object will basically hold a reference of a function. The function will then can be called via the delegate object.

Sounds easy? If not lets have a look in the code snippets below.

1. Defining the delegate

public delegate int Calculate (int value1, int value2);

 2. Creating methods which will be assigned to delegate object

//a method, that will be assigned to delegate objects
//having the EXACT signature of the delegate

public int add(int value1, int value2)
{    return value1 + value2;            }

//a method, that will be assigned to delegate objects
//having the EXACT signature of the delegate
public int sub( int value1, int value2)
{    return value1 - value2;            }

 3. Creating the delegate object and assigning methods to those delegate objects

//creating the class which contains the methods
//that will be assigned to delegate objects
MyClass mc = new MyClass();
//creating delegate objects and assigning appropriate methods
//having the EXACT signature of the delegate
Calculate add = new Calculate(mc.add);
Calculate sub = new Calculate(mc.sub);

 4. Calling the methods via delegate objects

//using the delegate objects to call the assigned methods
Console.WriteLine("Adding two values: " + add(10, 6));
Console.WriteLine("Subtracting two values: " + sub(10,4));