Tuesday, 31 July 2012

You can get IP Address of a fully qualified host name. We can Use GetHostEntry method of the System.Net.Dns class. There are multiple IP Addresses for some host name.

Here is Example for this.
In this example we can get IP address of our given host name. We provide "jayeshsorathia.blogspot.com" as a host name. It will return Multiple IP Addresses.
We will also attach another output screen in which we supplied "www.microsoft.com" as a hostname.

C# Examples :
        string strHostName = "jayeshsorathia.blogspot.com";
        //string strHostName = "www.microsoft.com";
        // Get DNS entry of specified host name
        IPAddress[] addresses = Dns.GetHostEntry(strHostName).AddressList;

        // The DNS entry may contains more than one IP addresses.
        // Iterate them and display each along with the type of address (AddressFamily).
        foreach (IPAddress address in addresses)
        {
            Response.Write(string.Format("{0} = {1} ({2})", strHostName, address, address.AddressFamily));
            Response.Write("<br/><br/>");
        }

VB.net Examples :
        Dim strHostName As String = "jayeshsorathia.blogspot.com"
        'string strHostName = "www.microsoft.com";
        ' Get DNS entry of specified host name
        Dim addresses As IPAddress() = Dns.GetHostEntry(strHostName).AddressList

        ' The DNS entry may contains more than one IP addresses.
        ' Iterate them and display each along with the type of address (AddressFamily).
        For Each address As IPAddress In addresses
            Response.Write(String.Format("{0} = {1} ({2})", strHostName, address, address.AddressFamily))
            Response.Write("<br/><br/>")
        Next

Output (jayeshsorathia.blogspot.com)

Output (www.microsoft.com) :

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, 30 July 2012

You can use System.UriBuilder class to build a new well-formed URI.
You can also say create a well-formed URL.
You need to set some property of UriBuilder object's , like Scheme , Port , Host , Path etc....
You can get generated URI using AbsoluteUri Method.
This is very useful article for .Net Beginners.

Here is example for this.
In this example we construct one URI using UriBuilder Class.

C# Examples :
    // Generate a new URI.
    UriBuilder objUri = new UriBuilder();
    objUri.Scheme = "http";
    objUri.Port = 80;
    objUri.Host = "www.microsoft.com";
    objUri.Path = "en-us/default.aspx";

    Response.Write("<b>Genereted URI:</b> " + objUri.Uri.AbsoluteUri);

VB.net Examples :
        ' Generate a new URI.
        Dim objUri As New UriBuilder()
        objUri.Scheme = "http"
        objUri.Port = 80
        objUri.Host = "www.microsoft.com"
        objUri.Path = "en-us/default.aspx"

        Response.Write("<b>Genereted URI:</b> " + objUri.Uri.AbsoluteUri)

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.



Saturday, 28 July 2012

You can update data or records into SQL Server Database tables using SqlCommand Class.
You can use "ExecuteNonQuery" method of SqlCommand Class.
You can update all or particular criteria records using where clause.
This article is very useful for .Net Beginners

Here is example for this.
In this example we update record in "product_master" table. In this table we have two columns. First product_id it's data type is bigint and this is an Identity column, and Second is product_name it's datatype is nvarchar(500). "product_id" is an identity column.
We update product name by it's product_id column, so only one record is updated.
"ExecuteNonQuery" method also returns affected records count as integer. so you can check that records is updated or not and also get how many records are updated.

C# Examples :
        DataTable objTable = new DataTable();
        int intAffectedRecordsCount = 0;
        SqlConnection objConn = new SqlConnection();
        objConn.ConnectionString = @"Data Source=.\SQLEXPRESS;" +
                                   "Initial Catalog=TempDatabase;" +
                                   "User ID=sa;Password=sa;";  

        SqlCommand objcmd = new SqlCommand();
        objcmd.CommandText = "UPDATE product_master SET product_name =@product_name WHERE product_id=@product_id";
        objcmd.Parameters.AddWithValue("@product_name", "Cabinet");
        objcmd.Parameters.AddWithValue("@product_id", 12);
        objcmd.CommandType = CommandType.Text;
        objcmd.Connection = objConn;
        objcmd.Connection.Open();

        intAffectedRecordsCount=objcmd.ExecuteNonQuery();
        Response.Write("<b>Affrected Records Count : </b> " + intAffectedRecordsCount);
        objcmd.Connection.Close();

        objcmd.Dispose();
        objConn.Dispose();

VB.net Examples :
        Dim objTable As New DataTable()
        Dim intAffectedRecordsCount As Integer = 0
        Dim objConn As New SqlConnection()
        objConn.ConnectionString = "Data Source=.\SQLEXPRESS;" & _
                                   "Initial Catalog=TempDatabase;" & _
                                   "User ID=sa;Password=sa;"

        Dim objcmd As New SqlCommand()
        objcmd.CommandText = "UPDATE product_master SET product_name =@product_name WHERE product_id=@product_id"
        objcmd.Parameters.AddWithValue("@product_name", "Cabinet")
        objcmd.Parameters.AddWithValue("@product_id", 12)
        objcmd.CommandType = CommandType.Text
        objcmd.Connection = objConn

        objcmd.Connection.Open()

        intAffectedRecordsCount = objcmd.ExecuteNonQuery()
        Response.Write("<b>Affrected Records Count : </b> " & intAffectedRecordsCount)

        objcmd.Connection.Close()

        objcmd.Dispose()
        objConn.Dispose()

Output :


Learn other ADO.Net Examples over here. Click Here...

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


 

Friday, 27 July 2012

You can get list of all files in particular directory or folder and it's all sub directories.
.NET Framework 4 allow to enumerate directories and files using methods that returns enumerable collections. There is a also a methods of get enumerable collections for DirectoryInfo , FileSystemInfo and FileInfo objects.
Earlier version of .Net framework provide only array of these collections.
Performance wise enumerable collection is better than arrays.

We are using .NET Framework 4 feature in this example.

We are Using "EnumerateFiles" Method of "Directory" class for get all files in directory.
We are using LINQ query to get list.
For this you have to use System.Collections.Generic and System.IO namespaces.

Here is example for this.
In this example we get list of files name from given directory.
In output you can see that there is a sub folder "New Folder" in "Imp" folder. You can also get this sub folder's file in list.

C# Example :
        var lstFiles = from tmpFile in Directory.EnumerateFiles(@"D:\Imp\","*.*", SearchOption.AllDirectories)
                    select new
                    {
                        File = tmpFile
                    };

        Response.Write("<br/><b>File Paths:</b>");
        foreach (var objFile in lstFiles)
        {
            Response.Write(string.Format( "<br/>{0}", objFile.File));
        }

        Response.Write(string.Format("<br/><br/><b>Total {0} files found.</b>", lstFiles.Count().ToString()));

VB.net Example :
        Dim lstFiles = From tmpFile In Directory.EnumerateFiles("D:\Imp\", "*.*", SearchOption.AllDirectories)
                       Select New With { _
                           Key .File = tmpFile _
                        }

        Response.Write("<br/><b>File Paths:</b>")
        For Each objFile In lstFiles
            Response.Write(String.Format("<br/>{0}", objFile.File))
        Next

        Response.Write(String.Format("<br/><br/><b>Total {0} files found.</b>", lstFiles.Count().ToString()))

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.

Thursday, 26 July 2012

You can insert data or records in to SQL Server Database tables using SqlCommand Class.
You can use "ExecuteNonQuery" method of SqlCommand Class.
This article is very useful for .Net Beginners.

Here is example for this.
In this example we insert record in "product_master" table. In this table we have two columns. First product_id it's data type is bigint and this is an Identity column, and Second is product_name it's datatype is nvarchar(500).
"product_id" is an identity column so we did not provide this column in Insert query, this column automatically generate new identical number and stored. so we only insert product_name data in INSERT query.


C# Examples :
        SqlConnection objConn = new SqlConnection();
        objConn.ConnectionString = @"Data Source=.\SQLEXPRESS;" +
                                   "Initial Catalog=TempDatabase;" +
                                   "User ID=sa;Password=sa;";  

        SqlCommand objcmd = new SqlCommand();
        objcmd.CommandText = "Insert INTO product_master(product_name) values(@product_name)";
        objcmd.Parameters.AddWithValue("@product_name", "Cabinet");
        objcmd.CommandType = CommandType.Text;
        objcmd.Connection = objConn;
        objcmd.Connection.Open();

        objcmd.ExecuteNonQuery();
        objcmd.Connection.Close();

        objcmd.Dispose();
        objConn.Dispose();

VB.net Examples :
        Dim objConn As New SqlConnection()
        objConn.ConnectionString = "Data Source=.\SQLEXPRESS;" & _
                                   "Initial Catalog=TempDatabase;" & _
                                   "User ID=sa;Password=sa;"

        Dim objcmd As New SqlCommand()
        objcmd.CommandText = "Insert INTO product_master(product_name) values(@product_name)"
        objcmd.Parameters.AddWithValue("@product_name", "Cabinet")
        objcmd.CommandType = CommandType.Text
        objcmd.Connection = objConn

        objcmd.Connection.Open()

        objcmd.ExecuteNonQuery()
        objcmd.Connection.Close()

        objcmd.Dispose()
        objConn.Dispose()

Learn other ADO.Net Examples over here. Click Here...

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


Tuesday, 24 July 2012

You can get Intersect of two LINQ query or Results.
Intersect means find common records between two LINQ results.
You can also say find duplicate records from two LINQ query or Results.
In this example we find duplicate records from two DataTable using LINQ.

Here is example of this.

In this example we execute two different LINQ Query on DataTable and find two different results object.
After that we find common records from these two results.

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

        dc = new DataColumn("product_id",long.MaxValue.GetType());
        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);

        dr = dt.NewRow();
        dr["product_id"] = 4;
        dr["product_name"] = "LCD";
        dt.Rows.Add(dr);

        ds.Tables.Add(dt);

        IEnumerable<DataRow> objResult1 = from tbl in dt.AsEnumerable()
                                       where tbl.Field<long>(0) >=3
                                       select tbl;

        Response.Write("<b>Query Results 1</b>");
        foreach (DataRow row in objResult1)
        {
            Response.Write(string.Format("<br/>Product ID: {0} ,  Product Name: {1}", row.Field<long>(0), row.Field<string>(1)));
        }

        IEnumerable<DataRow> objResult2 = from tbl in ds.Tables[0].AsEnumerable()
                                       let product_name = tbl.Field<string>(1)
                                       where product_name.StartsWith("Key")
                                       || product_name.StartsWith("Mo")
                                       select tbl;

        Response.Write("<br/><br/><b>Query Results 2</b>");
        foreach (DataRow row in objResult2)
        {
            Response.Write(string.Format("<br/>Product ID: {0} ,  Product Name: {1}", row.Field<long>(0), row.Field<string>(1)));
        }


        IEnumerable<DataRow> objIntersectResult = objResult1.Intersect(objResult2);

        Response.Write("<br/><br/><b>Intersect Query Results</b>");
        foreach (DataRow row in objIntersectResult)
        {
            Response.Write(string.Format("<br/>Product ID: {0} ,  Product Name: {1}", row.Field<long>(0), row.Field<string>(1)));
        }
        Response.Write("<br/><br/>");

VB.net Examples :
        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", Long.MaxValue.GetType())
        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)

        dr = dt.NewRow()
        dr("product_id") = 4
        dr("product_name") = "LCD"
        dt.Rows.Add(dr)

        ds.Tables.Add(dt)

        Dim objResult1 As IEnumerable(Of DataRow) = From tbl In dt.AsEnumerable()
                                      Where tbl.Field(Of Long)(0) >= 3
                                      Select tbl

        Response.Write("<b>Query Results 1</b>")
        For Each row As DataRow In objResult1
            Response.Write(String.Format("<br/>Product ID: {0} ,  Product Name: {1}", row.Field(Of Long)(0), row.Field(Of String)(1)))
        Next

        Dim objResult2 As IEnumerable(Of DataRow) = From tbl In ds.Tables(0).AsEnumerable()
                                    Let product_name = tbl.Field(Of String)(1)
                                    Where product_name.StartsWith("Key") Or product_name.StartsWith("Mo")
                                    Select tbl

        Response.Write("<br/><br/><b>Query Results 2</b>")
        For Each row As DataRow In objResult2
            Response.Write(String.Format("<br/>Product ID: {0} ,  Product Name: {1}", row.Field(Of Long)(0), row.Field(Of String)(1)))
        Next

        Dim objIntersectResult As IEnumerable(Of DataRow) = objResult1.Intersect(objResult2)

        Response.Write("<br/><br/><b>Intersect Query Results</b>")
        For Each row As DataRow In objIntersectResult
            Response.Write(String.Format("<br/>Product ID: {0} ,  Product Name: {1}", row.Field(Of Long)(0), row.Field(Of String)(1)))
        Next
        Response.Write("<br/><br/>")

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.




Monday, 23 July 2012

.NET Framework 4 introduce new "CopyTo" method of Stream Class of System.IO namespace. Using this method we can copy one stream to another stream of different stream class.
You can also say that write content or data of one stream to another stream.

Here is example of this.
In this example we copy FileStream content to MemoryStream. We first create file stream object and print it's length after that we copy filestream object to memorystrem object and print it's length. You can see output in below image.

C# Example :
        FileStream objFileStream = File.Open(Server.MapPath("TextFile.txt"), FileMode.Open);
        Response.Write(string.Format("FileStream Content length: {0}", objFileStream.Length.ToString()));

        MemoryStream objMemoryStream = new MemoryStream();

        // Copy File Stream to Memory Stream using CopyTo method
        objFileStream.CopyTo(objMemoryStream);
        Response.Write("<br/><br/>");
        Response.Write(string.Format("MemoryStream Content length: {0}", objMemoryStream.Length.ToString()));
        Response.Write("<br/><br/>");

VB.net Example :
        Dim objFileStream As FileStream = File.Open(Server.MapPath("TextFile.txt"), FileMode.Open)
        Response.Write(String.Format("FileStream Content length: {0}", objFileStream.Length.ToString()))

        Dim objMemoryStream As New MemoryStream()

        ' Copy File Stream to Memory Stream using CopyTo method
        objFileStream.CopyTo(objMemoryStream)
        Response.Write("<br/><br/>")
        Response.Write(String.Format("MemoryStream Content length: {0}", objMemoryStream.Length.ToString()))
        Response.Write("<br/><br/>")
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.


Saturday, 21 July 2012

Options :

A. Preinit
B. Init
C. Render
D. PreRender
E. PreLoad


Please give your answer in comment.
 
Correct Answer is : A. Preinit

Note : Correct answer will be given after one week.

As a .Net Beginners you must know how to set textbox width.
You can set "width" property of TextBox control to set width.
You can set "width" property in Pixel or Percentage wise.

Here is Example for this.
In this example we are setting different width in pixel as well as percentage.

ASPX Code :
<asp:TextBox runat="server" ID="txt1"></asp:TextBox>
<asp:TextBox runat="server" ID="TextBox1" Width="10px"></asp:TextBox>
<asp:TextBox runat="server" ID="TextBox2" Width="20px"></asp:TextBox>
<asp:TextBox runat="server" ID="TextBox3" Width="200px"></asp:TextBox>
<asp:TextBox runat="server" ID="TextBox4"  Width="20%"></asp:TextBox>
<asp:TextBox runat="server" ID="TextBox5" Width="100%"></asp:TextBox>

Output :
(To view original image , click on image)

Here in output we made slightly changes we display textbox with it's actual html tag, so you can easily differentiate it's width.


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



Friday, 20 July 2012

You can also fill DataTable with DataReader with the help of "Load" method of DataTable.
This is very useful for .Net Beginners.
We can do this using ExecuteReader method of SqlCommand class.

Here is example of this.
In this example we get  all product_master table records and fill in data table object.
Here we do not close connection manually because we specify "CommandBehavior.CloseConnection" this behavior. This will automatically close connection after executing ExecuteReader command.

ASPX Code :
 <asp:GridView ID="gvProducts" runat="server">
 </asp:GridView>


C# Examples :
        //Create Data Table object, That hold records
        DataTable objTable = new DataTable();

        SqlConnection objConn = new SqlConnection();
        objConn.ConnectionString = @"Data Source=.\SQLEXPRESS;" +
                                   "Initial Catalog=TempDatabase;" +
                                   "User ID=sa;Password=sa;";  

        SqlCommand objcmd = new SqlCommand();
        objcmd.CommandText = "SELECT  * FROM product_master";
        objcmd.CommandType = CommandType.Text;
        objcmd.Connection = objConn;
        objcmd.Connection.Open();

        //Get sql data reader object
        SqlDataReader objReader= objcmd.ExecuteReader(CommandBehavior.CloseConnection);

        //Load SqlDataReder object into DataTable object
        objTable.Load(objReader);
                
        gvProducts.DataSource = objTable.DefaultView;
        gvProducts.DataBind();

        
        objcmd.Dispose();
        objConn.Dispose();

VB.net Example :
       'Create Data Table object, That hold records
        Dim objTable As New DataTable()

        Dim objConn As New SqlConnection()
        objConn.ConnectionString = "Data Source=.\SQLEXPRESS;" & _
                                   "Initial Catalog=TempDatabase;" & _
                                   "User ID=sa;Password=sa;"

        Dim objcmd As New SqlCommand()
        objcmd.CommandText = "SELECT  * FROM product_master"
        objcmd.CommandType = CommandType.Text
        objcmd.Connection = objConn
        objcmd.Connection.Open()

        'Get sql data reader object
        Dim objReader As SqlDataReader = objcmd.ExecuteReader(CommandBehavior.CloseConnection)

        'Load SqlDataReder object into DataTable object
        objTable.Load(objReader)

        gvProducts.DataSource = objTable.DefaultView
        gvProducts.DataBind()


        objcmd.Dispose()
        objConn.Dispose()

You can also get a DataTableReader from DataTable object, You can do this with the help of CreateDataReader method of Data Table class.

Output :



Thursday, 19 July 2012

You can create a XML File using XMLWriter class.
XMLWriter class available in System.XML namespace.
This will give proper indentation and create Well formed XML File.

Here is example for this.
In this example we create BookList.xml file with different Elements and Attributes.

C# Example :
        XmlWriterSettings objSetting = new XmlWriterSettings();
        objSetting.Indent = true;
        objSetting.NewLineOnAttributes = true;
        
        System.Text.StringBuilder sb = new System.Text.StringBuilder();


        using (XmlWriter objWriter = XmlWriter.Create(sb, objSetting))
        {
            //Note the artificial, but useful, indenting
            objWriter.WriteStartDocument();

            objWriter.WriteStartElement("books");

            ////////Start Book Element///////
            
            objWriter.WriteStartElement("book");

            objWriter.WriteStartAttribute("ISBN");
            objWriter.WriteValue("asp1");
            objWriter.WriteEndAttribute();

            objWriter.WriteStartElement("Title");
            objWriter.WriteValue("ASP.NET");
            objWriter.WriteEndElement();

            objWriter.WriteElementString("ReleaseDate", "11/11/2010");

            objWriter.WriteStartElement("Pages");
            objWriter.WriteValue(200);
            objWriter.WriteEndElement(); //price

            objWriter.WriteEndElement(); //book
            ////////End Book Element///////


            ////////Another Element

            ////////Start Book Element///////
            
            objWriter.WriteStartElement("book");

            objWriter.WriteStartAttribute("ISBN");
            objWriter.WriteValue("c#2");
            objWriter.WriteEndAttribute();

            objWriter.WriteStartElement("Title");
            objWriter.WriteValue("C#.NET");
            objWriter.WriteEndElement();

            objWriter.WriteElementString("ReleaseDate", "10/11/2010");

            objWriter.WriteStartElement("Pages");
            objWriter.WriteValue(500);
            objWriter.WriteEndElement(); 

            objWriter.WriteEndElement(); //book
            ////////End Book Element///////


            
            objWriter.WriteEndElement(); //books
            objWriter.WriteEndDocument();
            
        }

        File.WriteAllText(Server.MapPath("BooksList.xml"), sb.ToString());

VB.net Example :
        Dim objSetting As New XmlWriterSettings()
        objSetting.Indent = True
        objSetting.NewLineOnAttributes = True

        Dim sb As New System.Text.StringBuilder()


        Using objWriter As XmlWriter = XmlWriter.Create(sb, objSetting)
            'Note the artificial, but useful, indenting
            objWriter.WriteStartDocument()

            objWriter.WriteStartElement("books")

            ''''Start Book Element

            objWriter.WriteStartElement("book")

            objWriter.WriteStartAttribute("ISBN")
            objWriter.WriteValue("asp1")
            objWriter.WriteEndAttribute()

            objWriter.WriteStartElement("Title")
            objWriter.WriteValue("ASP.NET")
            objWriter.WriteEndElement()

            objWriter.WriteElementString("ReleaseDate", "11/11/2010")

            objWriter.WriteStartElement("Pages")
            objWriter.WriteValue(200)
            objWriter.WriteEndElement()
            objWriter.WriteEndElement() 'book
            ''''End Book Element

            ''''Another Element

            ''''Start Book Element

            objWriter.WriteStartElement("book")

            objWriter.WriteStartAttribute("ISBN")
            objWriter.WriteValue("c#2")
            objWriter.WriteEndAttribute()

            objWriter.WriteStartElement("Title")
            objWriter.WriteValue("C#.NET")
            objWriter.WriteEndElement()

            objWriter.WriteElementString("ReleaseDate", "10/11/2010")

            objWriter.WriteStartElement("Pages")
            objWriter.WriteValue(500)
            objWriter.WriteEndElement()
            objWriter.WriteEndElement() 'book
            ''''End Book Element


            objWriter.WriteEndElement() 'books

            objWriter.WriteEndDocument()
        End Using

        File.WriteAllText(Server.MapPath("BooksList.xml"), sb.ToString())

Output (Generated XML) :

<?xml version="1.0" encoding="utf-16"?>
<books>
  <book
    ISBN="asp1">
    <Title>ASP.NET</Title>
    <ReleaseDate>11/11/2010</ReleaseDate>
    <Pages>200</Pages>
  </book>
  <book
    ISBN="c#2">
    <Title>C#.NET</Title>
    <ReleaseDate>10/11/2010</ReleaseDate>
    <Pages>500</Pages>
  </book>
</books>

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



Wednesday, 18 July 2012

This is very useful post for .Net Beginners. Every .Net Developer use this in their application.
We can fill data table using SqlDataAdapter by execute sql query.
SqlDataAdapter is also use for execute standard INSERT, UPDATE, and DELETE statements.
SelectCommand , InsertCommand , UpdateCommand and DeleteCommand are the some very useful properties of SqlDataAdapter.
SqlDataAdapter is use for fill disconnected data table.
This is an ADO.Net .

Here is example.
In this example we execute select query of product_master table to get all records and fill in data table.

ASPX Code :
 <asp:GridView ID="gvProducts" runat="server">
 </asp:GridView>


C# Examples :
        //Create Data Table object, That hold records
        DataTable objTable = new DataTable();

        SqlConnection objConn = new SqlConnection();
        objConn.ConnectionString = @"Data Source=.\SQLEXPRESS;" +
                                   "Initial Catalog=TempDatabase;" +
                                   "User ID=sa;Password=sa;";  

        SqlCommand objcmd = new SqlCommand();
        objcmd.CommandText = "SELECT  * FROM product_master";
        objcmd.CommandType = CommandType.Text;
        objcmd.Connection = objConn;

        //Create Data Adapter object
        SqlDataAdapter objAdapt = new SqlDataAdapter();
        objAdapt.SelectCommand = objcmd;

        //Fill Data Table with return result of sql query
        objAdapt.Fill(objTable);

        gvProducts.DataSource = objTable.DefaultView;
        gvProducts.DataBind();

        objAdapt.Dispose();
        objcmd.Dispose();
        objConn.Dispose();

VB.net Example :
        'Create Data Table object, That hold records
        Dim objTable As New DataTable()

        Dim objConn As New SqlConnection()
        objConn.ConnectionString = "Data Source=.\SQLEXPRESS;" & _
                                    "Initial Catalog=TempDatabase;" & _
                                    "User ID=sa;Password=sa;"

        Dim objcmd As New SqlCommand()
        objcmd.CommandText = "SELECT  * FROM product_master"
        objcmd.CommandType = CommandType.Text
        objcmd.Connection = objConn

        'Create Data Adapter object
        Dim objAdapt As New SqlDataAdapter()
        objAdapt.SelectCommand = objcmd

        'Fill Data Table with return result of sql query
        objAdapt.Fill(objTable)

        gvProducts.DataSource = objTable.DefaultView
        gvProducts.DataBind()

        objAdapt.Dispose()
        objcmd.Dispose()
        objConn.Dispose()

Output :


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



Tuesday, 17 July 2012

You can get System Folder path using code using "System.Environment" Class.
We are using  Static / Shared "GetFolderPath" method of Environment Class.

Here is examples of this.
In this example we get system folder path and display on screen.

C# Examples :
 string strSystemPath = Environment.GetFolderPath(Environment.SpecialFolder.System);
 Response.Write("<b>System Folder Path :</b> " + strSystemPath);

VB.net Example :
 Dim strSystemPath As String = Environment.GetFolderPath(Environment.SpecialFolder.System)
 Response.Write("System Folder Path:" + strSystemPath)

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.


Monday, 16 July 2012

You can get current database name using In Built SQL function "DB_NAME()".

SQL Query :
SELECT DB_NAME() AS DataBaseName

Output :


This is the very useful SQL Server Scripts.

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

Saturday, 14 July 2012

There is a situation where you need to focus on text box after page is loaded.
This is the best user friendly concept.

You can do this with two ways.
First use .Focus() method of TextBox Control.
Second use Page.SetFocus method.

Here is example for this.

C# Example :
 //Use Focus method of textbox
 txtProductName.Focus();

 //Use SetFocus method of Page
 Page.SetFocus(txtProductName);

VB.net Example :
''Use Focus method of textbox
txtProductName.Focus()

''Use SetFocus method of Page
Page.SetFocus(txtProductName)

 You can use anyone method from above. Do not use both method at a time.

This article is very useful for .Net Beginners.


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




Friday, 13 July 2012

Hash code of a file is useful for check that file contents is changed over the time or not. First time you calculate hash code of a file and store , after some time period you again calculate hash code of a file and compare with stored hash code, If hash code is changed that means contents of the file is changed.

You can create a cryptographic hash code of the file using the ComputeHash method of the System.Security.Cryptography.HashAlgorithm class. Store calculated hash code for future comparison against newly calculated hash code of the same file. Hashing algorithm will generate a very different hash code even if the file has been changed slightly, and the chances of two different files resulting in the same hash code are very small.

Here is example of this.
In this example we are calculating hash code of a file.
We are calculating hash code using "SHA1" Hashing algorithm.
If you calculate hash code of same file using another hashing algorithm like "MD5" or "RIPEMD-160" it will produce different hash code.

C# Example :
        string strFile = Server.MapPath("TextFile.txt");
        using (HashAlgorithm objHashAlg = HashAlgorithm.Create("SHA1"))
        {
            
            using (Stream objFile = new FileStream(strFile, FileMode.Open, FileAccess.Read))
            {
                // Calculate the hash code of the file.
                byte[] objHash = objHashAlg.ComputeHash(objFile);
                
                Response.Write("<b>Calculated Hash Code :</b> "+ BitConverter.ToString(objHash));
            }
            
        }

VB.net Example :
        Dim strFile As String = Server.MapPath("TextFile.txt")
        Using objHashAlg As HashAlgorithm = HashAlgorithm.Create("SHA1")

            Using objFile As Stream = New FileStream(strFile, FileMode.Open, FileAccess.Read)
                ' Calculate the hash code of the file.
                Dim objHash As Byte() = objHashAlg.ComputeHash(objFile)

                Response.Write("<b>Calculated Hash Code :</b> " & BitConverter.ToString(objHash))

            End Using
        End Using

Output : 
(To view original image , click on image)

This is very useful .Net Tips.

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


Thursday, 12 July 2012

Ping message is sent using the ICMP using System.Net.NetworkInformation.Ping class.
Ping Message passing a test packet to specific IP Address, and requests the remote device respond by send back the packet.
In Ping Message a byte array of up to 65,500 data bytes that is sent with the ping request and that should be returned back in the response.
You can send ping using "send" method of Ping class. In the reply of the send method will return a System.Net.NetworkInformation.PingReply object. The Status property of the PingReply object will contain a value of the Status of the ping request.The most common values will be Success and TimedOut. You can set TimeOut value in Send method in milliseconds.
If you sepcify Invalid host or Ping request did not found given host at that time Send method raise Exception "An exception occurred during a Ping request." .You need to handle this exception in Try Catch block.

Here is example of this.
In this example we sent ping to specific IP Address or Website and display it's result on screen.
We send ping request to "www.google.com" and it's success message on screen with it's IP address and time taken by ping request.

ASPX Code :
<asp:TextBox runat="server" ID="txtURL"></asp:TextBox>
<asp:Button runat="server" ID="btnPing" Text="Ping" onclick="btnPing_Click" />
<br />
<b>Status : </b><asp:Label runat="server" ID="lblProductName"></asp:Label>

C# Examples :
    protected void btnPing_Click(object sender, EventArgs e)
    {
        Ping objPing = new Ping();
        
        try
        {
            PingReply objReply = objPing.Send(txtURL.Text, 1000);

            if (objReply.Status == IPStatus.Success)
            {
                lblProductName.Text = string.Format("<b>Success</b> - IP Address:{0} Time:{1}ms", objReply.Address, objReply.RoundtripTime);
            }
            else
            {
                lblProductName.Text = objReply.Status.ToString();
            }
        }
        catch (Exception ex)
        {
            lblProductName.Text = ex.Message;
        }
        
    }
VB.net Examples :
    Protected Sub btnPing_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim objPing As New Ping()

        Try
            Dim objReply As PingReply = objPing.Send(txtURL.Text, 1000)

            If objReply.Status = IPStatus.Success Then
                lblProductName.Text = String.Format("<b>Success</b> - IP Address:{0} Time:{1}ms", objReply.Address, objReply.RoundtripTime)
            Else
                lblProductName.Text = objReply.Status.ToString()
            End If
        Catch ex As Exception
            lblProductName.Text = ex.Message
        End Try
    End Sub

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, 11 July 2012

You can execute LINQ query on DataTable Or Specific table on DataSet with the help of the AsEnumerable.

Here is example for this.
In this example we create one datatable and dataset , You can also fill dataset directly from DataAdapter, and we run LINQ query on this datatable to filter results.
The first query is for get records which ID is less than or equal to 2.
The second query is for get records which name starts with "Key" and "Mo".
You can also perform all LINQ queries on datatable and dataset.

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

        dc = new DataColumn("product_id",long.MaxValue.GetType());
        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);

        dr = dt.NewRow();
        dr["product_id"] = 4;
        dr["product_name"] = "LCD";
        dt.Rows.Add(dr);

        ds.Tables.Add(dt);

        IEnumerable<DataRow> objResult1 = from tbl in dt.AsEnumerable()
                                       where tbl.Field<long>(0) <= 2
                                       select tbl;

        Response.Write("<b>Query Results 1</b>");
        foreach (DataRow row in objResult1)
        {
            Response.Write(string.Format("<br/>Product ID: {0} ,  Product Name: {1}", row.Field<long>(0), row.Field<string>(1)));
        }

        IEnumerable<DataRow> objResult2 = from tbl in ds.Tables[0].AsEnumerable()
                                       let product_name = tbl.Field<string>(1)
                                       where product_name.StartsWith("Key")
                                       || product_name.StartsWith("Mo")
                                       select tbl;

        Response.Write("<br/><br/><b>Query Results 2</b>");
        foreach (DataRow row in objResult2)
        {
            Response.Write(string.Format("<br/>Product ID: {0} ,  Product Name: {1}", row.Field<long>(0), row.Field<string>(1)));
        }
VB.net Examples :
        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", Long.MaxValue.GetType())
        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)

        dr = dt.NewRow()
        dr("product_id") = 4
        dr("product_name") = "LCD"
        dt.Rows.Add(dr)

        ds.Tables.Add(dt)

        Dim objResult1 As IEnumerable(Of DataRow) = From tbl In dt.AsEnumerable()
                                      Where tbl.Field(Of Long)(0) <= 2
                                      Select tbl

        Response.Write("<b>Query Results 1</b>")
        For Each row As DataRow In objResult1
            Response.Write(String.Format("<br/>Product ID: {0} ,  Product Name: {1}", row.Field(Of Long)(0), row.Field(Of String)(1)))
        Next

        Dim objResult2 As IEnumerable(Of DataRow) = From tbl In ds.Tables(0).AsEnumerable()
                                    Let product_name = tbl.Field(Of String)(1)
                                    Where product_name.StartsWith("Key") Or product_name.StartsWith("Mo")
                                    Select tbl

        Response.Write("<br/><br/><b>Query Results 2</b>")
        For Each row As DataRow In objResult2
            Response.Write(String.Format("<br/>Product ID: {0} ,  Product Name: {1}", row.Field(Of Long)(0), row.Field(Of String)(1)))
        Next

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.




Tuesday, 10 July 2012

You can check that your current application uses in 64 bit process or not.
In  .NET Framework 4 there is one function Is64BitProcessis available to check that current application uses in 64 bit process or not.
This function available in Environment class of System namespace.
This function return true if process 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.Is64BitProcess == true)
        {
            Response.Write("This is 64 Bit Process.");
        }
        else
        {
            Response.Write("This is not 64 Bit Process.");
        }

VB.net Example :
        If System.Environment.Is64BitProcess = True Then
            Response.Write("This is 64 Bit Process.")
        Else
            Response.Write("This is not 64 Bit Process.")
        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.

Monday, 9 July 2012

Options :

A. asp:AjaxManager
B. asp:PageManager
C. asp:ScriptManager
D. asp:ClientScriptManager

Correct Answer is : C. asp:ScriptManager

Please give your answer in comment.

Note : Correct answer will be given after one week.

 

If you need to process the records one by one or iterate the records from database table for that you need to use IDataReader instance. There are various implementation of IDataReader class. We are using System.Data.SqlClient.SqlDataReader class to iterate the records.
The IDataReader interface extends the System.Data.IDataRecord interface. These interfaces declare the functionality to access both the data and the structure of the data contained in the result set.

Here is the example.
In this example we execute two select queries first query is for to get product details and display it's records on screen, and second query is for get employee_master details and display it's table's metadata details on screen.

C# Examples :
        // Create a new SqlConnection object.
        using (SqlConnection objCon = new SqlConnection())
        {
            // Configure the SqlConnection object's connection string.
            objCon.ConnectionString =@"Data Source=JAYESH-PC\SQLEXPRESS;" + 
                                     "Initial Catalog=TempDatabase;" +  
                                     "User ID=sa;Password=ibmx206;";  
            using (SqlCommand objCommand = objCon.CreateCommand())
            {
                objCommand.CommandType = CommandType.Text;
                objCommand.CommandText = "SELECT product_id,product_name FROM product_master " +
                " ORDER BY product_name;SELECT * FROM employee_master";
                
                objCon.Open();
                // Execute the command and obtain a SqlReader.
                using (SqlDataReader objReader = objCommand.ExecuteReader())
                {
                    // Process the first set of results and display the
                    // content of the result set.
                    Response.Write("Prodct details (By Product Name).");

                    while (objReader.Read())
                    {
                        Response.Write(string.Format(" <br/> {0} - {1} ",
                        objReader["product_id"], // Use string index
                        objReader[1])); // Use ordinal index
                    }
                    Response.Write("<br/><br/>");
                    // Process the second set of results and display 
                    objReader.NextResult();
                    Response.Write("Employee Details.");
                    for (int field = 0; field < objReader.FieldCount; field++)
                    {
                        Response.Write(string.Format("<br/><b> Column Name:</b>{0}   <b>Data Type:</b>{1}",
                        objReader.GetName(field),
                        objReader.GetDataTypeName(field)));
                    }
                }
            }
        }

VB.net Examples :
        ' Create a new SqlConnection object.
        Using objCon As New SqlConnection()
            ' Configure the SqlConnection object's connection string.
            objCon.ConnectionString = "Data Source=JAYESH-PC\SQLEXPRESS;" & "Initial Catalog=TempDatabase;" & "User ID=sa;Password=ibmx206;"
            Using objCommand As SqlCommand = objCon.CreateCommand()
                objCommand.CommandType = CommandType.Text
                objCommand.CommandText = "SELECT product_id,product_name FROM product_master " & " ORDER BY product_name;SELECT * FROM employee_master"

                objCon.Open()
                ' Execute the command and obtain a SqlReader.
                Using objReader As SqlDataReader = objCommand.ExecuteReader()
                    ' Process the first set of results and display the
                    ' content of the result set.
                    Response.Write("Prodct details (By Product Name).")

                    While objReader.Read()
                        ' Use string index
                        ' Use ordinal index
                        Response.Write(String.Format(" <br/> {0} - {1} ", objReader("product_id"), objReader(1)))
                    End While
                    Response.Write("<br/><br/>")
                    ' Process the second set of results and display 
                    objReader.NextResult()
                    Response.Write("Employee Details.")
                    For field As Integer = 0 To objReader.FieldCount - 1
                        Response.Write(String.Format("<br/><b> Column Name:</b>{0}   <b>Data Type:</b>{1}", objReader.GetName(field), objReader.GetDataTypeName(field)))
                    Next
                End Using
            End Using
        End Using

Output :

You can access the SqlDataReder objects data using Field name, ordinal index and typed data methods. The typed data contains various methods like GetBoolean, GetByte, GetBytes, GetChar, GetChars, GetDateTime, GetDecimal, GetDouble, GetFloat, GetGuid, GetInt16, GetInt32, GetInt64, GetString, GetValue, and GetValues. Each of the these methods takes an integer argument that identifies the zero-based index of the column from which the data should be returned.

After the use of the data reader, you must have to call its Close method so that you can use the database connection again. IDataReader extends System.IDisposable interface, so that each data reader class implements the Dispose method. Dispose automatically calls Close method.

This article is very useful for .Net Beginners.

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


Saturday, 7 July 2012

You can submit a page when textbox value changed.
For that you need to take asp textbox control and set it's AutoPostBack property to true and handle it's ontextchanged event.

This article is very useful for .Net Beginners.

Here is example of this.
In this example we set autopostback=true and handle textbox change event. And on server side we handle change event and set textbox value to label control.

C# ASPX Code : 
<asp:TextBox runat="server" ID="txtProductName" AutoPostBack="true" ontextchanged="txtProductName_TextChanged"></asp:TextBox>
<br />
<asp:Label runat="server" ID="lblProductName"></asp:Label>

C# Example :
    protected void txtProductName_TextChanged(object sender, EventArgs e)
    {
        lblProductName.Text = txtProductName.Text;
    }

VB.Net ASPX Code :
<asp:TextBox runat="server" AutoPostBack="true" ID="txtProductName"></asp:TextBox>
<br />
<asp:Label runat="server" ID="lblProductName"></asp:Label>

VB.net Example :
    Protected Sub txtProductName_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles txtProductName.TextChanged
        lblProductName.Text = txtProductName.Text
    End Sub

In Vb.Net we are using handle keyword to handle event.So that we do not set ontextchanged property.
You can also set ontextchanged property as we do in C# Example. In this case you need to remove that Handle from server side code. Otherwise textchanged event call two times.

Output : 


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


You need this password textbox where you would like you insert username and password from website users. With the help of this password textbox inputed password character is not see on textbox , it will display astrik "*" or other special characters.
This is very useful article for .Net Beginners.

Here is example for this.
In this example we take two textbox one is for username and second is for password. Username password is normal textbox and password textbox is special password type textbox. There is a "TextMode"  property of textbox , you canse this property as "password" like this TextMode="Password" , by doing this your textbox is converted to password type textbox.

ASPX Code : 
        <table>
            <tr>
                <td>
                    User Name :
                </td>
                <td>
                    <asp:TextBox runat="server" ID="txtUserName"></asp:TextBox></td>
            </tr>
            <tr>
                <td>
                    Password :</td>
                <td>
                    <asp:TextBox runat="server" ID="txtPassword" TextMode="Password"></asp:TextBox></td>
            </tr>
        </table>

Output : 

You can see in the output image, In password textbox you did not see password in plain text , this will display in special characters.

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