Friday 29 June 2012

You can determine that the current operating system is 64 bit OS or not.
In .NET Framework 4 there is one function Is64BitOperatingSystem  is available to check that  current operating system is a 64-bit operating system.
This function available in Environment class of System namespace.
This function return true if OS is 64 bit else return false.

Here is example :
This example is in both C# .Net Programming and VB.Net Programming.

C# Example :
        if (System.Environment.Is64BitOperatingSystem == true)
        {
            Response.Write("This is 64 Bit Operating System.");
        }
        else
        {
            Response.Write("This is not 64 Bit Operating System.");
        }

VB.net Example :
        If System.Environment.Is64BitOperatingSystem = True Then
            Response.Write("This is 64 Bit Operating System.")
        Else
            Response.Write("This is not 64 Bit Operating System.")
        End If

This type of C# Tips is very useful in day to day programming life.

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.



Thursday 28 June 2012

In .NET Framework 4 there is enhancement System.Guid structure, These includes new TryParse and TryParseExact methods. Using these methods you can validate GUID string.
GUID means a globally unique identifier (GUID). GUID is a structure and it's namespace is System.Guid. A GUID is a 128-bit integer this can be used in all computers and networks wherever a unique identifier is required. This identifier has a very less probability of being duplicated.


Here is example for this.
In this example we create new guid object and also take one string variable which has invalid guid. After that we use TryParse method to validate that both variable has valid guid format or not. By running example you can see that string variable has not valid guid format and it gives message of "InValid guid". If string variable has valid guid than this will return true in TryParse method.


C# Example :
        //Generate New GUID
        Guid objGuid = Guid.NewGuid();
        //Take invalid guid format
        string strGUID = "aaa-a-a-a-a";

        Guid newGuid;

        if (Guid.TryParse(objGuid.ToString(), out newGuid) == true)
        {
            Response.Write(string.Format("<br/>{0} is Valid GUID.", objGuid.ToString()));
        }
        else
        {
            Response.Write(string.Format("<br/>{0} is InValid GUID.", objGuid.ToString()));
        }

        
        Guid newTmpGuid;

        if (Guid.TryParse(strGUID, out newTmpGuid) == true)
        {
            Response.Write(string.Format("<br/>{0} is Valid GUID.", strGUID));
        }
        else
        {
            Response.Write(string.Format("<br/>{0} is InValid GUID.", strGUID));
        }

VB.net Example :
        'Generate New GUID
        Dim objGuid As Guid = Guid.NewGuid()
        'Take invalid guid format
        Dim strGUID As String = "aaa-a-a-a-a"

        Dim newGuid As Guid

        If Guid.TryParse(objGuid.ToString(), newGuid) = True Then
            Response.Write(String.Format("<br/>{0} is Valid GUID.", objGuid.ToString()))
        Else
            Response.Write(String.Format("<br/>{0} is InValid GUID.", objGuid.ToString()))
        End If


        Dim newTmpGuid As Guid

        If Guid.TryParse(strGUID, newTmpGuid) = True Then
            Response.Write(String.Format("<br/>{0} is Valid GUID.", strGUID))
        Else
            Response.Write(String.Format("<br/>{0} is InValid GUID.", strGUID))
        End If

Output :

This type of C# Tips is very useful in day to day programming life.

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.




Wednesday 27 June 2012

You can set and get textbox value programmatically using C# and VB.Net. Every .Net Beginners needs to know this.
You can use "Text"  property of textbox to set and get value of textbox.

Here is example of this.
This example is in both C# .Net Programming and VB.Net Programming.
In this example we have one textbox it's id is "txtProductName".

ASPX Code : 
        <asp:TextBox runat="server" ID="txtProductName"></asp:TextBox>
        <br />
        <asp:Label runat="server" ID="lblProductName"></asp:Label>


C# Example :
        //Set textbox value
        txtProductName.Text = "ASP.net book";

        //Get textbox value and display in label
        lblProductName.Text = "Product Name : " + txtProductName.Text.Trim();

VB.net Example :
        ''Set textbox value
        txtProductName.Text = "ASP.net book"

        ''Get textbox value and display in label
        lblProductName.Text = "Product Name : " + txtProductName.Text.Trim()

Output : 



You can use Text.Trim() method to remove extra whitespace from left and rights side of text.

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.


In .NET Framework 4 there is enhancement in TimeSpan Class, These include new overloads of the ToString , TryParse and Parse methods, and also introduce new methods like TryParseExact  and ParseExact.
Using time span class you get time span interval between two dates, this timespan gets in days , hour , minute , seconds and milliseconds format. .Net Beginners very much like this type of example.

Here is example of this.
In this example we take Departure and Arrival dates and we get total travel time span.

C# Example :
 DateTime objDepartureDt = new DateTime(2012, 6, 1, 5, 42, 0);
 DateTime objArrivalDt = new DateTime(2012, 6, 2, 11, 17, 0);
 TimeSpan objTravelTimeTS = objArrivalDt - objDepartureDt;

 Response.Write(string.Format("<b>TimeSpan :</b> {0} - {1} = <b> {2} </b>", objArrivalDt, objDepartureDt, objTravelTimeTS));

 Response.Write("<br/><br/>");
 Response.Write("<b>Interval details</b>");
 Response.Write("<br/>Days : " + objTravelTimeTS.Days);
 Response.Write("<br/>Hours : " + objTravelTimeTS.Hours);
 Response.Write("<br/>Minutes : " + objTravelTimeTS.Minutes);
 Response.Write("<br/>Second : " + objTravelTimeTS.Seconds);
 Response.Write("<br/>Milliseconds : " + objTravelTimeTS.Milliseconds);

VB.net Example :
 Dim objDepartureDt As New DateTime(2012, 6, 1, 5, 42, 0)
 Dim objArrivalDt As New DateTime(2012, 6, 2, 11, 17, 0)
 Dim objTravelTimeTS As TimeSpan = objArrivalDt - objDepartureDt

 Response.Write(String.Format("<b>TimeSpan :</b> {0} - {1} = <b> {2} </b>", objArrivalDt, objDepartureDt, objTravelTimeTS))

 Response.Write("<br/><br/>")
 Response.Write("<b>Interval details</b>")
 Response.Write("<br/>Days : " & objTravelTimeTS.Days)
 Response.Write("<br/>Hours : " & objTravelTimeTS.Hours)
 Response.Write("<br/>Minutes : " & objTravelTimeTS.Minutes)
 Response.Write("<br/>Second : " & objTravelTimeTS.Seconds)
 Response.Write("<br/>Milliseconds : " & objTravelTimeTS.Milliseconds)

Output : 



There are also a properties like TotalDays, TotalHours, TotalMinutes, TotalSeconds and TotalMilliseconds. Using these properties you can get time span in specific values.

This type of C# Tips is very useful in day to day programming life.

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.



Tuesday 26 June 2012

The .NET Framework 4 introduce the System.Tuple class for creating tuple objects that contain structured data. It also provides generic tuple classes to support tuples that have from one to eight components . To support tuple objects that have more than 8 components, there is a generic tuple class with seven type parameters and an eighth parameter of any tuple type. Tuple Class provides static methods for creating tuple objects.You can store upto eight types of value in one tuple object. This tuple object may useful for .Net Beginners to .Net Expert Level people.

Here is table for this.

Name Description
Create(T1) Creates a new 1-tuple, or singleton.
Create(T1, T2) Creates a new 2-tuple, or pair.
Create(T1, T2, T3) Creates a new 3-tuple, or triple.
Create(T1, T2, T3, T4) Creates a new 4-tuple, or quadruple.
Create(T1, T2, T3, T4, T5) Creates a new 5-tuple, or quintuple.
Create(T1, T2, T3, T4, T5, T6) Creates a new 6-tuple, or sextuple.
Create(T1, T2, T3, T4, T5, T6, T7) Creates a new 7-tuple, or septuple.
Create(T1, T2, T3, T4, T5, T6, T7, T8) Creates a new 8-tuple, or octuple.

Tuples are mostly use for following ways.
  • Return multiple values from a method without using out parameters (in C#) or ByRef parameters (in Visual Basic). 
  • Easy access of the data. 
  • To pass multiple values to a method through a single parameter. 
  • Store multiple values in sing object.

Here is example of this.
In this example we take four values in tuple , first is firstname , second is lastname , third is salary , and forth is mobilenumber. We can store this four values in single object. This is the benefit of tuple class.

C# Example :
 var objTupe = new System.Tuple<string, string, double, long>("Mike","Anderson",29000,9999999999);
 Response.Write("Item1 : " + objTupe.Item1);
 Response.Write("<br/>Item2 : " + objTupe.Item2);
 Response.Write("<br/>Item3 : " + objTupe.Item3);
 Response.Write("<br/>Item4 : " + objTupe.Item4);

VB.net Example :
 Dim objTupe = New System.Tuple(Of String, String, Double, Long)("Mike", "Anderson", 29000, 9999999999L)
 Response.Write("Item1 : " & objTupe.Item1)
 Response.Write("<br/>Item2 : " & objTupe.Item2)
 Response.Write("<br/>Item3 : " & objTupe.Item3)
 Response.Write("<br/>Item4 : " & objTupe.Item4)

Output :



You can access the individual tuple value by using tuple object's property like Item1 ,Item2 , Item3 , Item4 etc... These property available depends on how many parameters you taken in tuple object at object creation time , we took 4 parameters so we got these 4 properties.

This type of C# Tips is very useful in day to day programming life.

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.


Monday 25 June 2012

 This is very useful article for .Net Beginners Who want to querying database server using programming .
You can create a command object appropriate to the type of database that you use. All command objects implement the System.Data.IDbCommand interface. Configure the command object by setting its CommandType and CommandText properties. Execute the command using the ExecuteNonQuery, ExecuteReader, or ExecuteScalar method, depending on the type of command and its expected results.

The IDbCommand interface represents a database command, and each data provider includes a unique implementation.
Here is the list of IDbCommand implementations for some standard data providers:
  • System.Data.SqlClient.SqlCommand
  • System.Data.Odbc.OdbcCommand
  • System.Data.OleDb.OleDbCommand
  • System.Data.OracleClient.OracleCommand
  • System.Data.SqlServerCe.SqlCeCommand


To execute a command on a database, you must have an open connection and a properly configured command object appropriate to the type of database you are accessing.

Here are some common command object properties.
Property Description
CommandText Command text contains SQL command or stored procedure name to execute. The content of the CommandText property must be compatible with the value you specify in the CommandType property.
CommandTimeout An integer that specifies the number of seconds to wait for the command to return before timing out and raising an exception. Defaults is 30 seconds.
CommandType A value of the System.Data.CommandType enumeration that specifies the type of command represented by the command object.For stored procedure you specify StoredProcedure and when you want to execute a SQL text command than you specify Text value. If you are using the OLE DB data provider, you can specify TableDirect when you want to return the entire contents of one or more tables.
Connection An IDbConnection instance that provides the connection to the database on which you will execute the command. If you create the command using the IDbConnection.CreateCommand method, this property will be automatically set to the IDbConnection instance from which you created the command. You can also create connection object of specific connection class like SQLConnection.
Parameters A System.Data.IDataParameterCollection instance containing the set of parameters to substitute into the command.
Transaction A System.Data.IDbTransaction instance representing the transaction into which to enlist the command.


Once you have configured your command object details, you can execute it in a various ways, depending on the nature of the command, the type of data returned by the command, and the format in which you want to process the data.

  • To execute a command that does not return database data Like INSERT, DELETE, or CREATE TABLE etc.. , call ExecuteNonQuery. For the INSERT, UPDATE and DELETE commands, the ExecuteNonQuery method returns an int that specifies the number of rows affected by the command. For other commands, like CREATE TABLE, ExecuteNonQuery returns the value -1.
  • To execute a command that returns a result set, such as a SELECT statement or stored procedure, use the ExecuteReader or other DataAdapter method. ExecuteReader returns an IDataReader instance through which you have access to the result data. Most data providers also allow you to execute multiple SQL commands in a single call to the ExecuteReader method. 
  • If you want to execute a query but only need the value from the first column of the first row of result data, use the ExecuteScalar method. The value is returned as an object reference that you must cast to the correct type.


Here are example of ExecuteNonQuery , ExecuteReader and ExecuteScalar Methods.

C# Example :
    public void ExecuteNonQueryOnDatabase(IDbConnection objCon)
    {
        // Create and configure a new command.
        IDbCommand objCom = objCon.CreateCommand();
        objCom.CommandType = CommandType.Text;
        /////Create Update command for update product name of product_id = 8
        objCom.CommandText = "UPDATE product_master SET product_name = 'KeyBoard'" +
        " WHERE Product_id = 8";
        // Execute the command and process the result.
        int result = objCom.ExecuteNonQuery();
        if (result == 1)
        {
            Response.Write("Product title updated.");
        }
        else
        {
             Response.Write("Product title not updated.");
        }
    }
    public void ExecuteReaderOnDatabase(IDbConnection objCon)
    {
        // Create and configure a new command.
        IDbCommand objCom = objCon.CreateCommand();
        objCom.CommandType = CommandType.StoredProcedure;
        objCom.CommandText = "SP_GET_ALL_PRODUCTS";
      

        // Execute the command and process the results using reader.
        using (IDataReader reader = objCom.ExecuteReader())
        {
            Response.Write("Get All Products.");
            while (reader.Read())
            {
                // Display the product details.
                 Response.Write(reader["product_id"] + " = " + reader["product_name"]);
            }
        }
    }
    public  void ExecuteScalarOnDatabase(IDbConnection objCon)
    {
        // Create and configure a new command.
        IDbCommand objCom = objCon.CreateCommand();
        objCom.CommandType = CommandType.Text;
        objCom.CommandText = "SELECT COUNT(*) FROM product_master";
        // Execute the command and cast the result.
        int result = (int)objCom.ExecuteScalar();
         Response.Write("Product count = " + result);
    }
    protected void Page_Load(object sender, EventArgs e)
    {

        // Create a new SqlConnection object.
        using (SqlConnection objCon = new SqlConnection())
        {
            // Configure the SqlConnection object's connection string.
            objCon.ConnectionString =@"Data Source=.\SQLEXPRESS;" + // SQL Server instance , You can also set remote database
                                         "Initial Catalog=TempDatabase;" + // the sample TempDatabase DB
                                         "User ID=sa;Password=sa;";  //Set Credential
                                 
            // Open the database connection and execute the example
            // commands through the connection.
            objCon.Open();
            ExecuteNonQueryOnDatabase(objCon);
            Response.Write(Environment.NewLine);
            ExecuteReaderOnDatabase(objCon);
            Response.Write(Environment.NewLine);
            ExecuteScalarOnDatabase(objCon);
        };
    }

VB.net Example :
    Public Sub ExecuteNonQueryOnDatabase(ByVal objCon As IDbConnection)
        ' Create and configure a new command.
        Dim objCom As IDbCommand = objCon.CreateCommand()
        objCom.CommandType = CommandType.Text
        ''''Create Update command for update product name of product_id = 8
        objCom.CommandText = "UPDATE product_master SET product_name = 'KeyBoard'" & " WHERE Product_id = 8"
        ' Execute the command and process the result.
        Dim result As Integer = objCom.ExecuteNonQuery()
        If result = 1 Then
            Response.Write("Product title updated.")
        Else
            Response.Write("Product title not updated.")
        End If
    End Sub
    Public Sub ExecuteReaderOnDatabase(ByVal objCon As IDbConnection)
        ' Create and configure a new command.
        Dim objCom As IDbCommand = objCon.CreateCommand()
        objCom.CommandType = CommandType.StoredProcedure
        objCom.CommandText = "SP_GET_ALL_PRODUCTS"

        ' Execute the command and process the results using reader.
        Using reader As IDataReader = objCom.ExecuteReader()
            Response.Write("Get All Products.")
            While reader.Read()
                ' Display the product details.
                Response.Write(reader("product_id") + " = " + reader("product_name"))
            End While
        End Using
    End Sub
    Public Sub ExecuteScalarOnDatabase(ByVal objCon As IDbConnection)
        ' Create and configure a new command.
        Dim objCom As IDbCommand = objCon.CreateCommand()
        objCom.CommandType = CommandType.Text
        objCom.CommandText = "SELECT COUNT(*) FROM product_master"
        ' Execute the command and cast the result.
        Dim result As Integer = CInt(objCom.ExecuteScalar())
        Response.Write("Product count = " & result)
    End Sub


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ' Create a new SqlConnection object.
        Using objCon As New SqlConnection()
            ' Configure the SqlConnection object's connection string.
            ' SQL Server instance , You can also set remote database
            ' the sample TempDatabase DB
            objCon.ConnectionString = "Data Source=.\SQLEXPRESS;" & _
                "Initial Catalog=TempDatabase;" & _
                "User ID=sa;Password=sa;" 
            objCon.Open()
            ExecuteNonQueryOnDatabase(objCon)
            Response.Write(Environment.NewLine)
            ExecuteReaderOnDatabase(objCon)
            Response.Write(Environment.NewLine)
            ExecuteScalarOnDatabase(objCon)
        End Using

    End Sub


In this article we are using both Text and StoredProcedure as command type. 

Note : Give Us your valuable feedback in comments. Give your suggestions in articles so we can update our articles accordingly that.


Saturday 23 June 2012

As a .Net beginners you need to know about how and where to store database connection string and how to retrieve this database connection string.
Store database connection string in Web.Config file is a good way.
In Web.Config file there is "<configuration>" section , In this section there is "<connectionStrings>" section. In this section you can add your connection string. You can add connection string using add tag.

Here are sample example of web.config file in which we store connection string.

Web.Config file :
<configuration>
    <connectionStrings>
        <add name="NorthWindConnectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;;User ID=sa;Password=sa;" providerName="System.Data.SqlClient"/>
    </connectionStrings>
</configuration>

In this we can set the connection string name and connection string values and provider name. In this example we set name as "NorthWindConnectionString" and provider as "System.Data.SqlClient" for SQL Sever. You can set different provider for different database servers ie ORACLE , SYBASE etc...

Now we are retrivieing this stored database connection string in our code. The easiest way to read this connection string is to use the ConnectionStrings property of the System.Configuration.ConfigurationManager class. Specify the name of the connection string you want as the property index will return a System.Configuration.ConnectionStringSettings object. You can use ConnectionString property of System.Configuration.ConnectionStringSettings object.

Here are example of read database connection string from web.config into server side code.

C# Example :
        System.Configuration.ConnectionStringSettings objConnSetting= System.Configuration.ConfigurationManager.ConnectionStrings["NorthWindConnectionString"];
        string conString = objConnSetting.ConnectionString;
        SqlConnection objConn = new SqlConnection();
        objConn.ConnectionString = objConnSetting.ConnectionString;
        objConn.Open();
        /////Do you database stuff
        objConn.Close();

VB.net Example :
        Dim objConnSetting As System.Configuration.ConnectionStringSettings = System.Configuration.ConfigurationManager.ConnectionStrings("NorthWindConnectionString")
        Dim conString As String = objConnSetting.ConnectionString

        Dim objConn As New SqlConnection()
        objConn.ConnectionString = objConnSetting.ConnectionString
        objConn.Open()
        ''''Do you database stuff
        objConn.Close()

Friday 22 June 2012

.Net 4.0 Framework provide Optional and Named Parameters in C# also. Previously it was supported in VB.Net.
Now you do not need to write unnecessary overload methods , With the help of the Optional method you can achieve this.

Here is example of this.

C# Example :
    void DisplayString(int id, string title = "Information", string message = "No Message")
    {
        Response.Write("ID : " +  Convert.ToString( id));
        Response.Write("<br/>Title : " + title);
        Response.Write("<br/>Message : " + message);

    }
    protected void Page_Load(object sender, EventArgs e)
    {
        DisplayString(10, message: "Hi");
    }

In this example we create one method name "DisplayString" this methods has three parameters , First is Id , Second is Title , This parameter has default value "Information" and Third parameter message , This parameter has also default value "No Message". Now if we called this method with this parameters:

DisplayString(10, message: "Hi"); 

It will display output like this.
Output : 


In this output we pass id as 10 , we do not pass second argument so it takes its default value "Information" , and as second parameter we set name of parameter message , so this parameter property do not take it's default values , it takes pass value "Hi".




Thursday 21 June 2012

You can create database connection string using ConnectionStringBuilder class.
You can use the System.Data.Common.DbConnectionStringBuilder class or one of its strongly typed subclasses that form part of an ADO.NET data provider.
Here is the list of available DbConnectionStringBuilder implementations for standard data providers:
  • System.Data.Odbc.OdbcConnectionStringBuilder
  • System.Data.OleDb.OleDbConnectionStringBuilder
  • System.Data.OracleClient.OracleConnectionStringBuilder
  • System.Data.SqlClient.SqlConnectionStringBuilder
Each of these classes exposes properties for getting and setting the parameters for a connection string . To parse an existing connection string, pass it as an argument when creating the DbConnectionStringBuilder derived class, or set the ConnectionString property. If this string contains a keyword not supported by the type of connection, an ArgumentException will be thrown.

Here is example of this.
In this example we parse one connection string using SqlConnectionStringBuilder class and also we create other connection programmatically by setting SqlConnectionStringBuilder object's properties.

C# Example :
        string conString = @"Data Source=.\sqlexpress;" +
                            "Database=Northwind;Integrated Security=SSPI;" +
                            "Min Pool Size=5;Max Pool Size=15;Connection Reset=True;" +
                            "Connection Lifetime=600;";
        // Parse the SQL Server connection string and display it's properties
        
        SqlConnectionStringBuilder objSB1 = new SqlConnectionStringBuilder(conString);
        Response.Write("<b>Parsed SQL Connection String Parameters:</b>");
        Response.Write(" <br/>  Database Source = " + objSB1.DataSource);
        Response.Write(" <br/>  Database = " + objSB1.InitialCatalog);
        Response.Write(" <br/>  Use Integrated Security = " + objSB1.IntegratedSecurity);
        Response.Write(" <br/>  Min Pool Size = " + objSB1.MinPoolSize);
        Response.Write(" <br/>  Max Pool Size = " + objSB1.MaxPoolSize);
        Response.Write(" <br/>  Lifetime = " + objSB1.LoadBalanceTimeout);

        // Set properties of string builder object and display whole connection string using ConnectionString property.
        SqlConnectionStringBuilder objSB2 =new SqlConnectionStringBuilder(conString);
        objSB2.DataSource = @".\sqlexpress";
        objSB2.InitialCatalog = "Northwind";
        objSB2.IntegratedSecurity = true;
        objSB2.MinPoolSize = 5;
        objSB2.MaxPoolSize = 15;
        objSB2.LoadBalanceTimeout = 600;
        Response.Write(Environment.NewLine);
        Response.Write("<br/><br/><b>Constructed connection string:</b>");
        Response.Write(" <br/>  " + objSB2.ConnectionString);

VB.net Example :
        Dim conString As String = "Data Source=.\sqlexpress;" & _
                                "Database=Northwind;Integrated Security=SSPI;" & _
                                "Min Pool Size=5;Max Pool Size=15;Connection Reset=True;" & _
                                "Connection Lifetime=600;"

        ' Parse the SQL Server connection string and display it's properties
        Dim objSB1 As New SqlConnectionStringBuilder(conString)
        Response.Write("<b>Parsed SQL Connection String Parameters:</b>")
        Response.Write(" <br/>  Database Source = " + objSB1.DataSource)
        Response.Write(" <br/>  Database = " + objSB1.InitialCatalog)
        Response.Write(" <br/>  Use Integrated Security = " + objSB1.IntegratedSecurity)
        Response.Write(" <br/>  Min Pool Size = " + objSB1.MinPoolSize)
        Response.Write(" <br/>  Max Pool Size = " + objSB1.MaxPoolSize)
        Response.Write(" <br/>  Lifetime = " + objSB1.LoadBalanceTimeout)

        ' Set properties of string builder object and display whole connection string using ConnectionString property.
        Dim objSB2 As New SqlConnectionStringBuilder(conString)
        objSB2.DataSource = ".\sqlexpress"
        objSB2.InitialCatalog = "Northwind"
        objSB2.IntegratedSecurity = True
        objSB2.MinPoolSize = 5
        objSB2.MaxPoolSize = 15
        objSB2.LoadBalanceTimeout = 600
        Response.Write(Environment.NewLine)
        Response.Write("<br/><br/><b>Constructed connection string:</b>")
        Response.Write(" <br/>  " + objSB2.ConnectionString)

After the connection builder object build you get whole connection string using ConnectionString property and set this connection to SQLConnection object to connect to the database.


Wednesday 20 June 2012

You need to open a connection to a database on regular bases for database operations.
For that you need to create a connection object.
The IDbConnection interface represents a database connection, and each data provider implement interface uniquely.
Here is the list of some IDbConnection implementations for standard data providers:
  • System.Data.SqlClient.SqlConnection
  • System.Data.SqlServerCe.SqlCeConnection
  • System.Data.Odbc.OdbcConnection
  • System.Data.OleDb.OleDbConnection
  • System.Data.OracleClient.OracleConnection

You need to configure a connection string property of connection object.
You need to provide certain things in connection string property like , Server address , authentication details etc...
Different data providers has different methodology.

Here is example of this.
In this example we connect to SQL Server using SqlConnection class , this class is available in System.Data.SqlClient namespace, and display SQL Server Information. After the utilization of open connection you must have to close this connection using Close method otherwise the connection remain open.

C# Example :
        SqlConnection con = new SqlConnection();
        con.ConnectionString =
                                @"Data Source=.\SQLEXPRESS;" + // SQL Server instance , You can also set remote database
                                 "Initial Catalog=Northwind;" + // the sample Northwind DB
                                 "User ID=sa;Password=sa;";  //Set Credential
                                 
        // Open the database connection.
        con.Open();

        if (con.State == ConnectionState.Open) //Check database connection state
        {
            Response.Write("<b>SqlConnection Information:</b>");
            Response.Write(" <br/> Connection State = " + con.State);
            Response.Write("<br/> Connection String = " + con.ConnectionString);
            Response.Write("<br/> Database Source = " + con.DataSource);
            Response.Write("<br/> Database = " + con.Database);
            Response.Write("<br/> Server Version = " + con.ServerVersion);
            Response.Write("<br/> Workstation Id = " + con.WorkstationId);
            Response.Write("<br/> Timeout = " + con.ConnectionTimeout);
            Response.Write("<br/> Packet Size = " + con.PacketSize);
        }
        else
        {
            Response.Write("SqlConnection failed to open.");
            Response.Write(" Connection State = " + con.State);
        }
        con.Close();
        con.Dispose();

VB.net Example :
        Dim con As New SqlConnection()
        
        con.ConnectionString = "Data Source=.\SQLEXPRESS;" & _
                               "Initial Catalog=Northwind;" & _
                               "User ID=sa;Password=ibmx206;"

        ' Open the database connection.
        con.Open()

        If con.State = ConnectionState.Open Then 'Check database connection state
            Response.Write("SqlConnection Information:")
            Response.Write(" <br/> Connection State = " & con.State)
            Response.Write("<br/> Connection String = " & con.ConnectionString)
            Response.Write("<br/> Database Source = " & con.DataSource)
            Response.Write("<br/> Database = " & con.Database)
            Response.Write("<br/> Server Version = " & con.ServerVersion)
            Response.Write("<br/> Workstation Id = " & con.WorkstationId)
            Response.Write("<br/> Timeout = " & con.ConnectionTimeout)
            Response.Write("<br/> Packet Size = " & con.PacketSize)
        Else
            Response.Write("SqlConnection failed to open.")
            Response.Write(" Connection State = " & con.State)
        End If
        con.Close()
        con.Dispose()

Here is output of this code.
Output : 


(To view original image , click on image)


Tuesday 19 June 2012

You can open a file in read mode and get FileStream Object for reading a stream.
After getting FileStream object you can read data using "Read" and "ReadByte" methods.
You can open any file i.e Text , Image , doc etc..
After reading the file you need to close the FileStream Object.

Here are example for this.
In this example we open two different "Text" and "Image" format files.

C# Example :
    // Get a filestream for reading a Text file
    System.IO.FileStream objFileStreamTxt = System.IO.File.OpenRead(MapPath("TextFile.txt"));
    objFileStreamTxt.Close();

    // Get a filestream for reading a Image file
    System.IO.FileStream objFileStreamImg = System.IO.File.OpenRead(MapPath("computer.jpg"));
    objFileStreamImg.Close();

VB.net Example :
        ' Get a filestream for reading a Text file
        Dim objFileStreamTxt As System.IO.FileStream = System.IO.File.OpenRead(MapPath("TextFile.txt"))
        objFileStreamTxt.Close()

        ' Get a filestream for reading a Image file
        Dim objFileStreamImg As System.IO.FileStream = System.IO.File.OpenRead(MapPath("computer.jpg"))
        objFileStreamImg.Close()

Here is example of how to read FileStream object using "Read" method. Click Here...

This is very useful .Net Tips which is use in day to day programming life.

You can read file byte data using "Read" Method of FileStream class and get bytes array. You can also say that read bytes array from FileStream object or read bytes array from FILE.

Here are example of this.
In this example We get FileStream of file and read it's byte data , byte data are store in Byte array.
You can also say that this approach is as chunk by chunk reading.

C# Example :
    // Get a filestream for reading a Text file
    System.IO.FileStream objFileStreamTxt = System.IO.File.OpenRead(MapPath("TextFile.txt"));

    // Set buffer length
    int intBufferLength = 16 * 1024;
    byte[] objBuffer = new byte[intBufferLength];

    int len = 0;

    while ((len = objFileStreamTxt.Read(objBuffer, 0, intBufferLength)) != 0)
    {
        // Here objBuffer object has bytes value, Which you can use to write into other stream or other use
        // Here objBuffer object contains intBufferLength length data
    }

    objFileStreamTxt.Close();

VB.net Example :
        ' Get a filestream for reading a Text file
        Dim objFileStreamTxt As System.IO.FileStream = System.IO.File.OpenRead(MapPath("TextFile.txt"))

        ' Set buffer length
        Dim intBufferLength As Integer = 16 * 1024
        Dim objBuffer As Byte() = New Byte(intBufferLength - 1) {}

        Dim len As Integer = 0
        len = objFileStreamTxt.Read(objBuffer, 0, intBufferLength)
        While len <> 0
            ' Here objBuffer object has bytes value, Which you can use to write into other stream or other use
            ' Here objBuffer object contains intBufferLength length data
            len = objFileStreamTxt.Read(objBuffer, 0, intBufferLength)
        End While

        objFileStreamTxt.Close()

In this example we read bytes array chunk by chunk , but If you want to get all bytes value whithout using loop than use this code.

C# Example (Without Loop) :
    System.IO.FileStream objFileStreamTmp = System.IO.File.OpenRead(MapPath("TextFile.txt"));
    byte[] objBufferTmp = new byte[objFileStreamTmp.Length];
    len = objFileStreamTmp.Read(objBufferTmp, 0, objBufferTmp.Length);

    objFileStreamTmp.Close();

VB.net Example (Without Loop) :
        Dim objFileStreamTmp As System.IO.FileStream = System.IO.File.OpenRead(MapPath("TextFile.txt"))
        Dim objBufferTmp As Byte() = New Byte(objFileStreamTmp.Length - 1) {}
        len = objFileStreamTmp.Read(objBufferTmp, 0, objBufferTmp.Length)

        objFileStreamTmp.Close()

Note : The chunk by chunk means looping approach is very good when you open a large file. Because if you open a large file in one statement it may gives Memory related errors.

This is very useful .Net Tips which is use in day to day programming life.


Monday 18 June 2012

You can seen that XML is now every where to exchange data between multiple system and platform.
Here are sample query which retrieve XML of particular Table's data.
XML support is available on SQL Server 2000 with SQLXML 3.0 and its XML extensions, and There are in built  native XML data type support in SQLServer 2005 and 2008. 

With the help of FOR XML AUTO clause you can get XML of table's data.

Here are sample queries.

SQL Query :
SELECT * FROM product_master FOR XML AUTO 

XML AUTO returns XML fragments it does not returns a full XML document with a document element. Each row in the database becomes one element and each column in the database becomes one attribute on the element. You can see that each element in the result set is name product_master because the select clause is from product_master table.

Output XML File :
<product_master product_id="1" product_name="LCD" />
<product_master product_id="2" product_name="Processor" />
<product_master product_id="3" product_name="Cabinet" />
<product_master product_id="4" product_name="Headphone" />
<product_master product_id="5" product_name="USB" />

If you want result in Element and you also want "Product" as main element. So you have to use ELEMENT Query. Here is element Query.

SQL Query :
select * from product_master as Product FOR XML AUTO , ELEMENTS

In FOR XML AUTO , ELEMENTS return XML with a document element.

 Output XML File :
<Product>
  <product_id>1</product_id>
  <product_name>LCD</product_name>
</Product>
<Product>
  <product_id>2</product_id>
  <product_name>Processor</product_name>
</Product>
<Product>
  <product_id>3</product_id>
  <product_name>Cabinet</product_name>
</Product>
<Product>
  <product_id>4</product_id>
  <product_name>Headphone</product_name>
</Product>
<Product>
  <product_id>5</product_id>
  <product_name>USB</product_name>
</Product>

In Previous queries Return XML does not have Root Element. If you want XML structure like Root Element after that child elements.

SQL Query :
select * from product_master as Products FOR XML PATH ('Product'), TYPE, ROOT ('Products') 

In this query we are using PATH and ROOT element to make a full XML document.

Output XML File : 
<Products>
  <Product>
    <product_id>1</product_id>
    <product_name>LCD</product_name>
  </Product>
  <Product>
    <product_id>2</product_id>
    <product_name>Processor</product_name>
  </Product>
  <Product>
    <product_id>3</product_id>
    <product_name>Cabinet</product_name>
  </Product>
  <Product>
    <product_id>4</product_id>
    <product_name>Headphone</product_name>
  </Product>
  <Product>
    <product_id>5</product_id>
    <product_name>USB</product_name>
  </Product>
</Products>

In above all queries you can also use INNER JOIN , OUTER JOIN and other any type of select queries.

If you know any other way to implement this solution, Insert that in comment so I can add in this blog.

Saturday 16 June 2012

There is a very quick way in .Net to read the entire file and return a string of data.
We are using ReadAllText method of File class.
Here are sample example of this.
In this example we read the whole file in one statement and return it's string of data.
These examples are in both C# and VB.Net .

C# Example :
 // Read the entire file and returns a string of data
 string strData = System.IO.File.ReadAllText(MapPath("TextFile.txt"));

VB.net Example :
'' Read the entire file and returns a string of data
Dim strData As String = System.IO.File.ReadAllText(MapPath("TextFile.txt"))

This is very useful .Net Tips which is use in day to day programming life.


Friday 15 June 2012

You can also query the array variables using LINQ.
Here are sample example for this.
In this example there is an array of integer values which contains various number, Now we want to get numbers in array which is greater then 5.
We can do this without FOR loop.

There are two possible way to do this. One is using LINQ Query and Second is Using Predicate.

VB.net Example using LINQ Query :
Dim arrayNumbers As Integer() = {1, 2, 5, 9, 10, 1, 0, 9, 5, 6, 4, 3, 2}
Dim selectedNumber As Integer() = (From an In arrayNumbers Where an > 5 Select an).ToArray()

VB.net Example using Predicate :
Dim arrayNumbers As Integer() = {1, 2, 5, 9, 10, 1, 0, 9, 5, 6, 4, 3, 2}
Dim selectedNumberLambda As Integer() = arrayNumbers.Where(Function(o) o > 5).ToArray()

Thursday 14 June 2012

There is a very quick way to open text file and appends data into that file.
There are two methods to appends text files AppendAllText and AppendAllLines.
These methods open a file. Appends data to the files , and then close the file. If file does not exist, These methods create the files , appends the data and close the file.

If you do not want append the data but you want overwrite the data of file you can also do this with the help of WriteAllText and WriteAllLines Methods.
These methods create the file and write data in file, If file is already exists than this will overwrite data.

Here are sample example of this.
In this example For append we are using AppendAllText method for directly append sample string.
and  AppendAllLines method to append IEnumerable of strings.
For write we are using WriteAllText method to write data in file and WriteAllLines method to write IEnumerable of strings.

C# Example :
    string strData = "This is sample string.";

    string[] lineNumbers = (from line in System.IO.File.ReadLines(MapPath("TextFile.txt"))
                            where line.Contains("sample")
                            select line).ToArray();

    // Appends the string of data to a file
    System.IO.File.AppendAllText(MapPath("TextFile1.txt"), strData);
    //Appends the IEnumerable of strings to a text file
    System.IO.File.AppendAllLines(MapPath("TextFile1.txt"), lineNumbers);

    // Writes the string of data to a file
    System.IO.File.WriteAllText(MapPath("TextFile2.txt"), strData);

    // Writes an IEnumerable of strings to a text file
    System.IO.File.WriteAllLines(MapPath("TextFile2.txt"), lineNumbers);

VB.net Example :
        Dim strData As String = "This is sample string."

        Dim lineNumbers As String() = (From line In System.IO.File.ReadLines(MapPath("TextFile.txt"))
                                      Where line.Contains("sample")
                                      Select line).ToArray()

        ' Appends the string of data to a file
        System.IO.File.AppendAllText(MapPath("TextFile1.txt"), strData)
        'Appends the IEnumerable of strings to a text file
        System.IO.File.AppendAllLines(MapPath("TextFile1.txt"), lineNumbers)

        ' Writes the string of data to a file
        System.IO.File.WriteAllText(MapPath("TextFile2.txt"), strData)

        ' Writes an IEnumerable of strings to a text file
        System.IO.File.WriteAllLines(MapPath("TextFile2.txt"), lineNumbers)

This is very useful .Net Tips which is use in day to day programming life.


Wednesday 13 June 2012

.Net framework provide the System.IO.Compression.GZipStream or System.IO.Compression.DeflateStream to compress or decompress data.
Both GZipStream and DeflateStream classes allow you to use GZIP and Deflate compression algorithms to compress or decompress data.

Here are sample examples with GZipStream class.
The sample examples there are two methods one is CompressData and other is DCompressData.
In CompressData method we create a new file and uses the GZipStream class to write compressed file to it and close that file .
In DCompressData method we open that compressed file in read mode and decompressed the file and save.
In this sample you have to provide the file path which file you want to compress and also provide file path where the compressed file stored.
In this example we store both files in application root directory.

This examples are in both C# and VB.Net .

C# Example :
    protected void Page_Load(object sender, EventArgs e)
    {

        CompressData();
        DCompressData();
             
    }
    void CompressData()
    {
        // Create the compression stream.
        GZipStream objGZipOut = new GZipStream(File.OpenWrite(Server.MapPath("compressed_data.gzip")), CompressionMode.Compress);
        
        int intBufferLength = 16 * 1024;
        byte[] objBuffer = new byte[intBufferLength];

        // Get File Stream Object
        System.IO.FileStream objFileStream = System.IO.File.Open(MapPath("TextFile.txt"), System.IO.FileMode.Open);
        int len = 0;

        while ((len = objFileStream.Read(objBuffer, 0, intBufferLength)) != 0)
        {
            // Write file Content 
            objGZipOut.Write(objBuffer, 0, len);

        }
        objFileStream.Close();
        objGZipOut.Close();
       
    }
    void DCompressData()
    {
        // Open the same gzip file to decompress
        GZipStream objGZipIn = new GZipStream(File.OpenRead(Server.MapPath("compressed_data.gzip")), CompressionMode.Decompress);

        // Get stream reader of the gzip file.
        StreamReader objReader = new StreamReader(objGZipIn);
       
        byte[] buffer = new byte[16 * 1024];
        int len = 0;
        FileStream objFS = new FileStream(Server.MapPath("compressed_data.txt"), FileMode.Create, FileAccess.Write, FileShare.Read);
        while ((len = objReader.BaseStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            objFS.Write(buffer, 0, len);
        }
        objFS.Close();
        objReader.Close();
        objGZipIn.Close();
       
    }


VB.net Example :
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        CompressData()
        DCompressData()
    End Sub
    Private Sub CompressData()
        ' Create the compression stream.
        Dim objGZipOut As New GZipStream(File.OpenWrite(Server.MapPath("compressed_data.gzip")), CompressionMode.Compress)

        Dim intBufferLength As Integer = 16 * 1  '1024
        Dim objBuffer As Byte() = New Byte(intBufferLength - 1) {}

        ' Get File Stream Object
        Dim objFileStream As System.IO.FileStream = System.IO.File.Open(MapPath("TextFile.txt"), System.IO.FileMode.Open)
        Dim len As Integer = 0
        len = objFileStream.Read(objBuffer, 0, intBufferLength)
        While len <> 0
            ' Write file Content 
            objGZipOut.Write(objBuffer, 0, len)
            len = objFileStream.Read(objBuffer, 0, intBufferLength)
        End While

        objFileStream.Close()
        objGZipOut.Close()

    End Sub
    Private Sub DCompressData()
        ' Open the same gzip file to decompress
        Dim objGZipIn As New GZipStream(File.OpenRead(Server.MapPath("compressed_data.gzip")), CompressionMode.Decompress)

        ' Get stream reader of the gzip file.
        Dim objReader As New StreamReader(objGZipIn)

        Dim buffer As Byte() = New Byte(16 * 1024 - 1) {}
        Dim len As Integer = 0
        Dim objFS As New FileStream(Server.MapPath("compressed_data.txt"), FileMode.Create, FileAccess.Write, FileShare.Read)
        len = objReader.BaseStream.Read(buffer, 0, buffer.Length)
        While len <> 0
            objFS.Write(buffer, 0, len)
            len = objReader.BaseStream.Read(buffer, 0, buffer.Length)
        End While
        
        objFS.Close()
        objReader.Close()
        objGZipIn.Close()

    End Sub

You can also provide other data like simple string to compress data , for that you have to use stream writer and use it's WriteLine method.

In this example we provide "TextFile.txt" text file. Size of this text file is 3 kb.
After the compressing new file "compressed_data.gzip" generated and it's size is 1 kb.

Output :

Before compression 



After compression 



Tuesday 12 June 2012

You can also query the text file using LINQ .
Here are example for this.
In this example we can get specific lines which has matching word given by us.
After the LINQ query is executed you need to close file otherwise it gives error on next attempt to access of file.

C# Example :
string[] lineNumbers = (from line in
                        System.IO.File.ReadLines(MapPath(
                        where line.Contains("sample")
                        select line).ToArray();

System.IO.File.OpenText(MapPath("TextFile.txt")).Close();

VB.net Example :
Dim lineNumbers As String() = (From line In
                              System.IO.File.ReadLines(MapPath("TextFile.txt"))
                              Where line.Contains("sample")
                              Select line).ToArray()

System.IO.File.OpenText(MapPath("TextFile.txt")).Close()

Monday 11 June 2012

You are able to get stream reader of a file and work on stream reader.
After getting Stream Reader and completing work on stream reader you have to close SteramReader using Close method. to avoid any file open errors.

Here are example for this.

C# Example :
System.IO.StreamReader objStreamReader = System.IO.File.OpenText(MapPath("TextFile.txt"));
objStreamReader.Close();

VB.net Example :
Dim objStreamReader As System.IO.StreamReader = System.IO.File.OpenText(MapPath("TextFile.txt"))
objStreamReader.Close()

Here in below image you can see that after FileStream Object is filled it's properties are set.

Output :

Are you having a problem of store Unicode data in database table and it will display  "??????"  ?
Here are solution for that.
SQL Server supports Unicode data in nchar, nvarchar and ntext datatypes.
If you are inserting unicode data as regular data at that time sql does not store unicode characters it store "??????" (Question marks) in also display this "??????".
If you want to store Unicode data you need to specify 'N' ahead of data.

Here are sample example for this.
Let's we have one table "product_master" and we have one column "product_name" and it's data type "nvarchar(500)".
Now we want store one record in that without 'N' .

SQL Query without 'N'
insert into product_master(product_name) values('कंप्यूटर')
select * from product_master

Output :


Now we want store one record in that with 'N' .

SQL Query With 'N'
insert into product_master(product_name) values(N'कंप्यूटर')
select * from product_master

Output :

 

Saturday 9 June 2012

Using LINQ you are able to fin common values amoung two arrays.
There is a one method "Intersect" in LINQ to get intersect values.
Here are sample example for this.
In this example we have two arrays of integer and find common values of that arrays.

C# Example :
        int[] arrayNumbersA = { 5, 0, 9, 10, 50, 6, 4, 3, 1 };
        int[] arrayNumbersB = { 10, 11, 51, 1, 0 };

        int[] arrayCommon = arrayNumbersA.Intersect(arrayNumbersB).ToArray(); ;

        Response.Write("<b>Common values :</b><br/>");
        foreach (var intValue in arrayCommon)
        {
            Response.Write(intValue);
            Response.Write("<br/>");
        }
        Response.Write("<br/>");
        Response.Write("<br/>");

VB.net Example :
        Dim arrayNumbersA() As Integer = {5, 0, 9, 10, 50, 6, 4, 3, 1}
        Dim arrayNumbersB() As Integer = {10, 11, 51, 1, 0}

        Dim arrayCommon() As Integer = arrayNumbersA.Intersect(arrayNumbersB).ToArray()

        Response.Write("<b>Common values :</b><br/>")
        For Each intValue As Integer In arrayCommon
            Response.Write(intValue)
            Response.Write("<br/>")
        Next
        Response.Write("<br/>")
        Response.Write("<br/>")
Output :
You can also use other data types like string , decimal , double etc...

Friday 8 June 2012

You can get the FileStream of a file by opening a file using File Class.
After get FileStream and completing work on file stream you have to close FileSteram using Close method. to avoid any file open errors.

Here are example for this.
C# Example :
System.IO.FileStream stream1 = System.IO.File.Open(MapPath("TextFile.txt"), System.IO.FileMode.Open);
stream1.Close();

VB.net Example :
Dim stream1 As System.IO.FileStream = System.IO.File.Open(MapPath("TextFile.txt"), System.IO.FileMode.Open)
stream1.Close()

Here in below image you can see that after FileStream Object is filled it's properties are set.

Output :

You can generate XML file from Dataset very easily.
Here are sample example for this.
In this example we have one dataset name "products" and one table inside dataset name "product".
We populate some records in table and generate xml from that and save this XML file using StreamWriter.

C# Example :
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        DataColumn dc;
        DataRow dr;
        ds.DataSetName = "products";
        dt.TableName = "product";

        dc = new DataColumn("product_id");
        dt.Columns.Add(dc);

        dc = new DataColumn("product_name");
        dt.Columns.Add(dc);

        dr = dt.NewRow();
        dr["product_id"] = 1;
        dr["product_name"] = "Monitor";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["product_id"] = 2;
        dr["product_name"] = "Mouse";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["product_id"] = 3;
        dr["product_name"] = "KeyBoard";
        dt.Rows.Add(dr);

        ds.Tables.Add(dt);
        string strXML= ds.GetXml();

        System.IO.StreamWriter sw = new System.IO.StreamWriter(Server.MapPath("datasetxml.xml"));
        sw.WriteLine(strXML);
        sw.Close();

VB.net Example :
        Dim ds As New DataSet()
        Dim dt As New DataTable()
        Dim dc As DataColumn
        Dim dr As DataRow
        ds.DataSetName = "products"
        dt.TableName = "product"

        dc = New DataColumn("product_id")
        dt.Columns.Add(dc)

        dc = New DataColumn("product_name")
        dt.Columns.Add(dc)

        dr = dt.NewRow()
        dr("product_id") = 1
        dr("product_name") = "Monitor"
        dt.Rows.Add(dr)

        dr = dt.NewRow()
        dr("product_id") = 2
        dr("product_name") = "Mouse"
        dt.Rows.Add(dr)

        dr = dt.NewRow()
        dr("product_id") = 3
        dr("product_name") = "KeyBoard"
        dt.Rows.Add(dr)

        ds.Tables.Add(dt)
        Dim strXML As String = ds.GetXml()

        Dim sw As New System.IO.StreamWriter(Server.MapPath("datasetxml.xml"))
        sw.WriteLine(strXML)
        sw.Close()

Output :
<products>
  <product>
    <product_id>1</product_id>
    <product_name>Monitor</product_name>
  </product>
  <product>
    <product_id>2</product_id>
    <product_name>Mouse</product_name>
  </product>
  <product>
    <product_id>3</product_id>
    <product_name>KeyBoard</product_name>
  </product>
</products>