Friday 31 August 2012

There are many situations where you want to get all tables name that contains particular column name using sql query.

Here is query for this.
In this query we want to find column "ProductID" in all tables and get list of that.

SQL Query :
select sysobjects.name, * from syscolumns, sysobjects
where syscolumns.name='ProductID'
and sysobjects.id = syscolumns.id
and (sysobjects.xtype='U' or sysobjects.xtype='S')

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.

Thursday 30 August 2012


Click Here to Download XMLSerializationAndDeserializationApplication.zip

Note : This application contains both serialize and deserialize exmples. Goto File menu and Download after click on download link.

In XML Deserialization you convert XML file data back in to custom class objects.
This is a reverse process of XML Serialization.
In previous example we serialize on object data in to XML now we take this Generated XML file and create class object from that.

This XML Serialization and Deserialization is very useful when communicating between to system where from one system object's data is converted into XML and transmit through network and at receiver end other system receive that xml data and back to converted object using deserialize.
This is useful when both end has different platform. I.e one end has .Net application and other end has JAVA or PHP or anyother patform applicaton.

Here is example for this.
In this example we took XML serialized file "ProductDetails.xml" and deserialize this into object with populating data back.
You can see in the output image that "ProductCategory" object fill from the "ProductDetails.xml" XML File.

C# Examples :
    [XmlRoot("productCategory")]
    public class ProductCategory
    {
        [XmlElement("categoryName")]
        public string CategoryName;

        [XmlElement("categoryDescription")]
        public string CategoryDescription;
        [XmlElement(ElementName = "launchDate", DataType = "date")]
        public DateTime LaunchDate;
        [XmlArray("products")]
        [XmlArrayItem("product")]
        public Product[] Products;
        public ProductCategory()
        {
            // Default constructor for deserialization.
        }
        public ProductCategory(string categoryName, string categoryDescription, DateTime launchDate)
        {
            this.CategoryName = categoryName;
            this.CategoryDescription = categoryDescription;
            this.LaunchDate = launchDate;
        }
    }
    public class Product
    {
        [XmlElement("productName")]
        public string ProductName;
        [XmlElement("productWeight")]
        public decimal ProductWeight;
        [XmlElement("productPrice")]
        public decimal ProductPrice;
                
        [XmlAttributeAttribute(AttributeName = "id")]
        public int Id;
        public Product()
        {

        }
        public Product(int productId, string productName, decimal productWeight , decimal productPrice)
        {
            this.Id =  productId;
            this.ProductName = productName;
            this.ProductWeight = productWeight;
            this.ProductPrice = productPrice;
            
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {

        ProductCategory objCategory;
        XmlSerializer objXMLSerializer = new XmlSerializer(typeof(ProductCategory));
        FileStream objFS = new FileStream(Server.MapPath("ProductDetails.xml"), FileMode.Open);
        objCategory = (ProductCategory)objXMLSerializer.Deserialize(objFS);
        objFS.Close();

    }

VB.net Examples :
    <XmlRoot("productCategory")> _
    Public Class ProductCategory
        <XmlElement("categoryName")> _
        Public CategoryName As String

        <XmlElement("categoryDescription")> _
        Public CategoryDescription As String
        <XmlElement(ElementName:="launchDate", DataType:="date")> _
        Public LaunchDate As DateTime
        <XmlArray("products")> _
        <XmlArrayItem("product")> _
        Public Products() As Product
        Public Sub New()

        End Sub
        Public Sub New(ByVal categoryName As String, ByVal categoryDescription As String, ByVal launchDate As DateTime)
            Me.CategoryName = categoryName
            Me.CategoryDescription = categoryDescription
            Me.LaunchDate = launchDate
        End Sub
    End Class
    Public Class Product
        <XmlElement("productName")> _
        Public ProductName As String
        <XmlElement("productWeight")> _
        Public ProductWeight As Decimal
        <XmlElement("productPrice")> _
        Public ProductPrice As Decimal

        <XmlAttributeAttribute(AttributeName:="id")> _
        Public Id As Integer
        Public Sub New()

        End Sub
        Public Sub New(ByVal productId As Integer, ByVal productName As String, ByVal productWeight As Decimal, ByVal productPrice As Decimal)
            Me.Id = productId
            Me.ProductName = productName
            Me.ProductWeight = productWeight
            Me.ProductPrice = productPrice

        End Sub
    End Class
  
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim objCategory As New ProductCategory
        Dim objXMLSerializer As New XmlSerializer(Type.GetType(objCategory.ToString()))
        Dim objFS As FileStream = New FileStream(Server.MapPath("ProductDetails.xml"), FileMode.Open)
        objCategory = objXMLSerializer.Deserialize(objFS)
        objFS.Close()
    End Sub

XML File ("ProductDetails.xml") :
<?xml version="1.0"?>
<productCategory xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <categoryName>Category 1</categoryName>
  <categoryDescription>Category for sports</categoryDescription>
  <launchDate>2012-08-29</launchDate>
  <products>
    <product id="1">
      <productName>Bat</productName>
      <productWeight>2</productWeight>
      <productPrice>20.39</productPrice>
    </product>
    <product id="2">
      <productName>Ball</productName>
      <productWeight>1</productWeight>
      <productPrice>2.90</productPrice>
    </product>
    <product id="3">
      <productName>Stumps</productName>
      <productWeight>3</productWeight>
      <productPrice>50.70</productPrice>
    </product>
  </products>
</productCategory>

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

Click Here to view "XML Serialization of Class Objects with C# Examples and VB.Net Examples". Click Here...

This is very useful .Net Tips.

For Beginning .Net articles. Click Here...

To learn more regarding XML. Click Here...

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



Wednesday 29 August 2012

Click Here to Download XMLSerializationAndDeserializationApplication.zip

Note : This application contains both serialize and deserialize exmples. Goto File menu and Download after click on download link.

There is a need where you want objects data into XML format.
You can achieve this using XML Serialization.
Using XML Serialization you can convert custom objects data into XML and XML into custom objects.
We are using "XmlSerializer" class available in "System.Xml.Serialization" namespace.
There is some prerequisite for custom object class that need to know.

  • The classes that are going to serialize must have a default zero-argument constructor. XmlSerializer use this constructor at a time of creating the new object during deserialization process.
  • XmlSerializer serializes only public variables and properties.
  • All class properties must be readable and writable. Because XmlSerializer uses the property to retrieve information and the property to restore the data after deserialization.

To use XML serialization, you must do mark up data objects with attributes that indicate the desired XML mapping. These attributes are available in the System.Xml.Serialization namespace.
  • XmlRoot indicate the name of the root element of the XML file. By default, XmlSerializer will use the name of the class. This attribute apply to the class declaration.  
  • XmlElement indicates the element name that use for a property or public variable. By default, XmlSerializer will use the name of the property or public variable.
  • XmlAttribute indicate that a property or public variable serialized as an attribute.
  • XmlIgnore indicate that a property or public variable should not be serialized in serialization process.
  • XmlEnum indicate that the text that should be used at the time of serializing enumerated values.

Here is example for this.
In this example we serialize object into XML.
We are taking two classes "ProductCategory" and "Product". We create object of this class fill some data and generate xml using XMLSerialization.

C# Examples :
    [XmlRoot("productCategory")]
    public class ProductCategory
    {
        [XmlElement("categoryName")]
        public string CategoryName;

        [XmlElement("categoryDescription")]
        public string CategoryDescription;
        [XmlElement(ElementName = "launchDate", DataType = "date")]
        public DateTime LaunchDate;
        [XmlArray("products")]
        [XmlArrayItem("product")]
        public Product[] Products;
        public ProductCategory()
        {

        }
        public ProductCategory(string categoryName, string categoryDescription, DateTime launchDate)
        {
            this.CategoryName = categoryName;
            this.CategoryDescription = categoryDescription;
            this.LaunchDate = launchDate;
        }
    }
    public class Product
    {
        [XmlElement("productName")]
        public string ProductName;
        [XmlElement("productWeight")]
        public decimal ProductWeight;
        [XmlElement("productPrice")]
        public decimal ProductPrice;
                
        [XmlAttributeAttribute(AttributeName = "id")]
        public int Id;
        public Product()
        {
            // Default constructor for serialization.
        }
        public Product(int productId, string productName, decimal productWeight , decimal productPrice)
        {
            this.Id =  productId;
            this.ProductName = productName;
            this.ProductWeight = productWeight;
            this.ProductPrice = productPrice;
            
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {

        // Create the product catalog.
        
        ProductCategory objCategory = new ProductCategory("Category 1", "Category for sports", DateTime.Now);
        Product[] lstProducts = new Product[3];
        lstProducts[0] = new Product(1,"Bat", 2, 20.39m);
        lstProducts[1] = new Product(2,"Ball", 1, 2.90m);
        lstProducts[2] = new Product(3,"Stumps", 3, 50.70m);
        objCategory.Products = lstProducts;
        XmlSerializer objXMLSerializer = new XmlSerializer(typeof(ProductCategory));
        FileStream objFS = new FileStream( Server.MapPath( "ProductDetails.xml"), FileMode.Create);
        objXMLSerializer.Serialize(objFS, objCategory);
        objFS.Close();
    }

VB.net Examples :
    <XmlRoot("productCategory")> _
    Public Class ProductCategory
        <XmlElement("categoryName")> _
        Public CategoryName As String

        <XmlElement("categoryDescription")> _
        Public CategoryDescription As String
        <XmlElement(ElementName:="launchDate", DataType:="date")> _
        Public LaunchDate As DateTime
        <XmlArray("products")> _
        <XmlArrayItem("product")> _
        Public Products() As Product
        Public Sub New()

        End Sub
        Public Sub New(ByVal categoryName As String, ByVal categoryDescription As String, ByVal launchDate As DateTime)
            Me.CategoryName = categoryName
            Me.CategoryDescription = categoryDescription
            Me.LaunchDate = launchDate
        End Sub
    End Class
    Public Class Product
        <XmlElement("productName")> _
        Public ProductName As String
        <XmlElement("productWeight")> _
        Public ProductWeight As Decimal
        <XmlElement("productPrice")> _
        Public ProductPrice As Decimal

        <XmlAttributeAttribute(AttributeName:="id")> _
        Public Id As Integer
        Public Sub New()

        End Sub
        Public Sub New(ByVal productId As Integer, ByVal productName As String, ByVal productWeight As Decimal, ByVal productPrice As Decimal)
            Me.Id = productId
            Me.ProductName = productName
            Me.ProductWeight = productWeight
            Me.ProductPrice = productPrice

        End Sub
    End Class


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim objCategory As ProductCategory = New ProductCategory("Category 1", "Category for sports", DateTime.Now)
        Dim lstProducts() As Product = New Product(2) {}
        lstProducts(0) = New Product(1, "Bat", 2, 20.39)
        lstProducts(1) = New Product(2, "Ball", 1, 2.9)
        lstProducts(2) = New Product(3, "Stumps", 3, 50.7)
        objCategory.Products = lstProducts
        Dim objXMLSerializer As XmlSerializer = New XmlSerializer(Type.GetType(objCategory.ToString()))
        Dim objFS As FileStream = New FileStream(Server.MapPath("ProductDetails.xml"), FileMode.Create)
        objXMLSerializer.Serialize(objFS, objCategory)
        objFS.Close()

    End Sub

Output XML File ("ProductDetails.xml") :
<?xml version="1.0"?>
<productCategory xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <categoryName>Category 1</categoryName>
  <categoryDescription>Category for sports</categoryDescription>
  <launchDate>2012-08-29</launchDate>
  <products>
    <product id="1">
      <productName>Bat</productName>
      <productWeight>2</productWeight>
      <productPrice>20.39</productPrice>
    </product>
    <product id="2">
      <productName>Ball</productName>
      <productWeight>1</productWeight>
      <productPrice>2.90</productPrice>
    </product>
    <product id="3">
      <productName>Stumps</productName>
      <productWeight>3</productWeight>
      <productPrice>50.70</productPrice>
    </product>
  </products>
</productCategory>

Click Here to View "XML Deserialization with C# Examples and VB.Net Examples". Click Here...

This is very useful .Net Tips.

For Beginning .Net articles. Click Here...

To learn more regarding XML. 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 28 August 2012

There is a need in application to upload a file and store into SQL Server Database table.
You can do this very simple way.
File is stored in sql server as binary data. You need to set "varbinary" data type of the column in which you want to store file. You need to take "varbinary(MAX)" data type.

Here is example for this.
In this example we take one "product_master" table. This tables contains columns like "product_id" , "product_name", "product_document_filename" and "product_document".
This "product_document" column store whole file as binary. so that we need to set it's datatype ""varbinary(MAX)". We are inserting uploaded file name in "product_document_filename" column whose datatype is nvarchar(1000).
In this example we take product name as textbox and for Upload file we take FileUpload control.

ASPX Code :
        <table>
            <tr>
                <td>
                    Product Title :
                </td>
                <td>
                    <asp:TextBox runat="server" ID="txtProductTitle"  ></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Product Document :
                </td>
                <td>
                    <asp:FileUpload runat="server" ID="fuDocument" />
                </td>
            </tr>
        </table>
        <asp:Button runat="server" ID="btnSave" Text="Save" onclick="btnSave_Click" />

C# Examples :
    protected void btnSave_Click(object sender, EventArgs e)
    {
        SqlCommand objCmd = new SqlCommand();
        SqlConnection objConn = new SqlConnection();
        objConn.ConnectionString = @"Data Source=.\SQLEXPRESS;" +
                                   "Initial Catalog=TempDatabase;" +
                                   "User ID=sa;Password=sa;";

        objConn.Open();
        objCmd.Connection = objConn;

        objCmd.CommandText = "insert into product_master(product_name,product_document_filename,product_document) values(@product_name,@product_document_filename,@product_document)";
        objCmd.Parameters.AddWithValue("@product_name", txtProductTitle.Text.Trim());

        if (fuDocument.HasFile == true)
        {
            objCmd.Parameters.AddWithValue("@product_document_filename", fuDocument.FileName);
            objCmd.Parameters.AddWithValue("@product_document", fuDocument.FileBytes);
        }
        else
        {
            objCmd.Parameters.AddWithValue("@product_document_filename", DBNull.Value);
            objCmd.Parameters.AddWithValue("@product_document", DBNull.Value);
        }
        objCmd.ExecuteNonQuery();
        objConn.Close();
    }

VB.net Examples :
    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
        Dim objCmd As New SqlCommand()
        Dim objConn As New SqlConnection()
        objConn.ConnectionString = "Data Source=.\SQLEXPRESS;" & "Initial Catalog=TempDatabase;" & "User ID=sa;Password=sa;"

        objConn.Open()
        objCmd.Connection = objConn

        objCmd.CommandText = "insert into product_master(product_name,product_document_filename,product_document) values(@product_name,@product_document_filename,@product_document)"
        objCmd.Parameters.AddWithValue("@product_name", txtProductTitle.Text.Trim())

        If fuDocument.HasFile = True Then
            objCmd.Parameters.AddWithValue("@product_document_filename", fuDocument.FileName)
            objCmd.Parameters.AddWithValue("@product_document", fuDocument.FileBytes)
        Else
            objCmd.Parameters.AddWithValue("@product_document_filename", DBNull.Value)
            objCmd.Parameters.AddWithValue("@product_document", DBNull.Value)
        End If
        objCmd.ExecuteNonQuery()
        objConn.Close()
    End Sub

Output (Database Table Structure) : 


Output (Create Product Screen) : 


Output (Inserted Product Details in Table) : 


This is very useful .Net Tips.

For Beginning .Net articles. Click Here...

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.




Monday 27 August 2012

There is always a need to parse and create valid URL.
We can achieve this using "Uri" class's "TryCreate" method.

Here is example for this.
In this example we take on URL string and parse that and create URI object from that.
If URL format in invalid than URL is not parsed and URI object is not created.
This method try to possible all way to create URI object.

If you do not specify "Scheme" in URL string than also this method create object but if you access "Scheme" property of this created object it will return error, so you need to handle this error. This is same for other properties also.


C# Examples :
        string strUri = "http://www.microsoft./en-us/default.aspx";
        Uri objUri = null;
        // Safely parse the url
        if (Uri.TryCreate(strUri, UriKind.RelativeOrAbsolute, out objUri))
        {
            Response.Write("<b>Parsed URI : </b>" + objUri.OriginalString);
            Response.Write("<br/><b>Scheme : </b>" + objUri.Scheme);
            Response.Write("<br/><b>Host : </b>" + objUri.Host);
            Response.Write("<br/><b>Port : </b>" + objUri.Port);
            Response.Write("<br/><b>Path and Query : </b>" + objUri.PathAndQuery);
        }

VB.net Examples :
        Dim strUri As String = "http://www.microsoft./en-us/default.aspx"
        Dim objUri As Uri
        '' Parse the url
        If (Uri.TryCreate(strUri, UriKind.RelativeOrAbsolute, objUri)) Then
            Response.Write("<b>Parsed URI : </b>" & objUri.OriginalString)
            Response.Write("<br/><b>Scheme : </b>" & objUri.Scheme)
            Response.Write("<br/><b>Host : </b>" & objUri.Host)
            Response.Write("<br/><b>Port : </b>" & objUri.Port)
            Response.Write("<br/><b>Path and Query : </b>" & objUri.PathAndQuery)
        End If

Output :

Click Here to view Examples of "Create a well formed URI using UriBuilder class with C# Examples and VB.Net Examples ". Click Here...

This type of .Net 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 25 August 2012

You can make textbox disabled. Means do not allow enter or change text into textbox.
You can do this with the help of "Enabled" property. You need to set Enabled=false to make text box disabled.
By default text box is enabled.

Here is example for this.
In this example we have one text box and we make that textbox disabled.
You can set this property from aspx side or from Coding side.

ASPX Code:
<asp:TextBox runat="server" ID="txtProductTitle" Text="Keyboard" Enabled="false" ></asp:TextBox>

Output : 




This is very useful articles for Beginning .Net .

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.



Friday 24 August 2012

There are situation in multi line textbox where you want to wrapping text in textbox and sometimes you not want to wrap text , that text type as it is.
We can achieve this using "Wrap" property. By Default it is true.

In textbox Wrapping means if you entered text more than width of the textbox it will automatically set cursor into next line. In unwrapping if you entered text more than width of the textbox there is one horizontal scrollbar appear below the textbox and your line is continued.

Here is example for this.
In this example you can see that we take two text boxes one is "Product Description" and Second is "Product Meta Description". And both this text boxes are multiline textbox.
In "Product Description" textbox we allow warp text in this textbox.
And in "Product Meta Description" textbox we do not allow wraping in text.

You can see in output that in "Product Description" textbox new line created without pressing enter or return key. In "Product Meta Description" textbox scrollbar is appear when entered more data.

ASPX Code :
        <table>
            <tr>
                <td>
                    Product Description :
                </td>
                <td>
                    <asp:TextBox runat="server" ID="txtProductDescription" TextMode="MultiLine" Wrap="true"
                        Height="120px" Width="250px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Product Meta Description :
                </td>
                <td>
                    <asp:TextBox runat="server" ID="txtProductMetaDescription" TextMode="MultiLine" Wrap="false"
                        Height="120px" Width="250px"></asp:TextBox>
                </td>
            </tr>
        </table>

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

Here is example for set Maximum characters length of multi line textbox. Click Here...
 
For Beginning .Net articles. Click Here...
 
Here 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 23 August 2012

 Click Here to Download TextBoxMaximumLengthApplication.zip

There is always a need of application to set maximum length allowed in textbox.
In this article we demonstrate both single line textbox and multi line textbox max length validation. 
There is a different way to set maximum characters allowed for single line textbox and multiline textbox.
You can set "MaxLength" property for single line textbox.

 For multiline textbox "MaxLength" does not supported.

So for Multi Line textbox we need some tricky approch. We can use javascript , JQuery or server side checking. Here we are going to use .Net Validator controls. We are using "RegularExpressionValidator" control.

Here is example for this.

In this example we are taking two textbox one is for ProdutTitle which is singleline textbox and other is for ProductDescription which is MultiLine textbox. For ProductTitle we are using MaxLength property to set maximum allowed characters. Which is 20 characters.
For ProductDescription we are using "RegularExpressionValidator" control to set maximum allowed characters. Which is 50 characters.
We are using Regex expression for validation.
The "RegularExpressionValidator" control display error message after typing in textbox focus or cursor moved out from textbox.
You can also make server side validation check for regular expression validation using "Page.Validate()" Method and "Page.IsValid" property.

In output you can see that if more than maximum allowed characters type in textbox it will give error message. You can also make you customize message.


ASPX Code:
        <table>
            <tr>
                <td>
                    Product Title :
                </td>
                <td>
                    <asp:TextBox runat="server" ID="txtProductTitle" MaxLength="20" ></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Product Description :
                </td>
                <td>
                    <asp:TextBox runat="server" ID="txtProductDescription"  TextMode="MultiLine"></asp:TextBox>
                    <asp:RegularExpressionValidator runat="server" ID="REVProductDescription" ControlToValidate="txtProductDescription"
                        ValidationExpression="^[\s\S]{0,50}$" style="color:Red;font-weight:bold" ErrorMessage="Please enter a maximum of 50 characters"
                        Display="Dynamic"></asp:RegularExpressionValidator>
                </td>
            </tr>
        </table>

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

For Beginning .Net articles. Click Here...
 
Here 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.



Wednesday 22 August 2012

You can write or insert entry into the Windows event log using the static methods of the EventLog class, or  also you can create an EventLog object.
But you must decide in which event source you want to write your log entry.The event source is a string that uniquely identifies your application.

By default, there is three event log sources Application, System, and Security. Normally you will write into the Application event source, but you also specify you custom log. You do not need to explicitly create a custom log but when you register an event source against a log, if the specified log doesn’t exist, it’s created automatically.

You can also set type of log entry i.e Error, FailureAudit, Information,SuccessAudit, and Warning. Which you need to set in EventLog class's method.

Here is example for this
In this example we write one event entry in "Application" log section in windows event log.
We are using "EventLog.WriteEntry" Method.

C# Examples :
        // Write an event into the event log.
        EventLog.WriteEntry("Application",
                            "A simple demo event.", // Event entry message
                            EventLogEntryType.Information, // Type of Event
                            1,
                            0,
                            System.Text.Encoding.Default.GetBytes("Hi , This is simple event log entry") // Event data
                            );

VB.net Examples :
        '' Write an event into the event log.
        EventLog.WriteEntry("Application",
                            "A simple demo event.",
                            EventLogEntryType.Information,
                            1,
                            0,
                            System.Text.Encoding.Default.GetBytes("Hi , This is simple event log entry")
                            )

Output :

(To view original image , click on image)


You can also create an event source using this method "EventLog.CreateEventSource".

NOTE : You must have administrator privileges to create an event source.

Here is an example of Read Event Logs Entry and Display. Click Here...
 
This is very useful .Net Tips.

For Beginning .Net articles. 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 21 August 2012

For security purpose there is a need to convert plain string in cryptographic string or encrypt password, so hackers did not understand the password.
You can create cryptographic string using seven different algorithms that provided in .Net Framework.
This is mainly use in encrypt a password and store.
This encrypted password is do not convert back to original string.

Now if you want to compare password for authentication at that time you need to encrypt entered password at that time of login and check that encrypted string with already stored encrypted string.
Same input string generate same encrypted hash code.

Here is example for this.
In this Example we use MD5 algorithm. Means Encrypt password using MD5 algorithm.

C# Example :
        string strPassword = "thisisdemo";
        string strAlgorigthm = "MD5";
        //You can also specify these algorights RIPEMD160 or RIPEMD-160 ,SHA or SHA1 ,
        //SHA256 or SHA-256 ,SHA384 or SHA-384,SHA512 or SHA-512
        //SHA1Managed algorithm you must be instantiated directly like this "objAlg = new SHA1Managed()"

        HashAlgorithm objAlg = null;
        objAlg = HashAlgorithm.Create(strAlgorigthm);

        // Convert string to bytes
        byte[] objData = System.Text.Encoding.Default.GetBytes(strPassword);

        // Generate the hash code of password
        byte[] objHashBytes = objAlg.ComputeHash(objData);

        Response.Write("<b>Hash Code : </b>");
        Response.Write(BitConverter.ToString(objHashBytes));

VB.net Example :
        Dim strPassword As String = "thisisdemo"
        Dim strAlgorigthm As String = "MD5"
        'You can also specify these algorights RIPEMD160 or RIPEMD-160 ,SHA or SHA1 ,
        'SHA256 or SHA-256 ,SHA384 or SHA-384,SHA512 or SHA-512
        'SHA1Managed algorithm you must be instantiated directly like this "objAlg = new SHA1Managed()"

        Dim objAlg As HashAlgorithm = Nothing
        objAlg = HashAlgorithm.Create(strAlgorigthm)

        ' Convert string to bytes
        Dim objData As Byte() = System.Text.Encoding.[Default].GetBytes(strPassword)

        ' Generate the hash code of password
        Dim objHashBytes As Byte() = objAlg.ComputeHash(objData)

        Response.Write("<b>Hash Code : </b>")
        Response.Write(BitConverter.ToString(objHashBytes))

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

You can also use other algorithms like RIPEMD160 or RIPEMD-160 ,SHA or SHA1 ,SHA256 or SHA-256 ,SHA384 or SHA-384,SHA512 or SHA-512.

Here is details of hashing algorithms available in .Net Framework. Click Here...


Only SHA1Managed algorithm can not be implemented using the factory approach.
It must be instantiated directly like this "hashAlg = new SHA1Managed()".

This is very useful .Net Tips.

For Beginning .Net articles. Click Here...

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

Monday 20 August 2012

Hashing algorithms are one way cryptographic functions that accept plain text of any length and generate a numeric value. These are one-way because it’s almost impossible to get the original plain text from the hash code. Hashing algorithms are useful for encrypt the password.

Use the same hashing algorithm to a specific text always generates the same hash code. This makes hash codes useful for check if two blocks of plain text are the same.
Generating hash codes in the .NET Framework is possbile.

The abstract class "HashAlgorithm" provides a base from which all hashing algorithm implementations.
The .NET Framework has the seven hashing algorithm implementations.
This class is in the System.Security.Cryptography namespace.

Here is list of Algorithms. 

Algorithm Name Class Name Hash Code Size (in Bits)
MD5 MD5CryptoServiceProvider 128
RIPEMD160 or RIPEMD-160    RIPEMD160Managed 160
SHA or SHA1 SHA1CryptoServiceProvider   160
SHA1Managed SHA1Managed 160
SHA256 or SHA-256 SHA256Managed 256
SHA384 or SHA-384 SHA384Managed 384
SHA512 or SHA-512 SHA512Managed 512

Visit this link for C# Examples and VB.net Example on Hashing Algorithm Implementation. Click Here...

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

Saturday 18 August 2012

As a .Net Beginners you must know how to make textbox readonly.

You can make textbox read only. Means do not allow type text in textbox and also is there is any text predefined in that you are not able to change that text.
You can do this with the help of "ReadOnly" property. You can set ReadOnly=true to make textbox read only.
By default text box is not readonly.

Here is example for this.
In this example we have one text box and we make that textbox readonly.
You can set this property from aspx side or from Coding side.
In this example we are showing from both side

ASPX Code:
<asp:TextBox runat="server" ID="txtProductName" Text="Keyboard"  ></asp:TextBox>

C# Examples :
txtProductName.ReadOnly = true;

VB.net Examples :
txtProductName.ReadOnly = True

Output : 


You can use Either aspx side or Coding side approach.

This is very useful articles for Beginning .Net .

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.


Friday 17 August 2012

When error occurred in .Net application Asp.Net page display it's default error page with the source code and line number of the error. This approach is not good it has some issues like.
  1. If source code and the error messages are displayed to a hacker it could damage application.
  2. And this message do not able to understand normal users.
There is a solution for this in ASP.Net. You can make settings in Web.Config file using "<customErrors>" section.

Syntax :
<customErrors defaultRedirect="[url]" mode="[on/off/remote]">
<error statusCode="[statuscode]" redirect="[url]" />
</customErrors>
  • defaultRedirect : Specifies URL to which page should be redirected if an error occurs. This setting is optional.
  • mode : Specifies the status of the custom errors is enabled, disabled, or shown only to remote machines. The values are On, Off, and RemoteOnly. "On" means that the custom errors are enabled. "Off" means that the custom errors are disabled. "RemoteOnly" means that the custom errors are shown only to remote clients. 
  • customErrors : The "<customErrors>" section has multiple <error> sub-elements that are used to define custom errors. Each <error> sub-element can has a statusCode attribute and a URL.

Here is example for this.
In this example we forcefully raise error from code and after error raise page is redirected to our custom "ErrorPage.aspx". In this example we raise error using numeric value divide by zero.
Here you have to add one aspx page into your .net application.
We specify settings in "web.config" file.
You have to put  "<customErrors>" section in  "<system.web>" section.

Web.Config :
<customErrors defaultRedirect="ErrorPage.aspx" mode="On">
</customErrors>

C# Examples :
        int a=1;
        int b = 0;
        a = a / b;

VB.net Examples :
        Dim a As Integer = 1
        Dim b As Integer = 0
        a = a / b
Output :
(To view original image , click on image)

If you do not handle error, error message display on screen. You can see in below screen shot.

.

 (To view original image , click on image)

This is very useful articles for Beginning .Net .

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 16 August 2012

This error occurred due to cast or convert or assign NULL value cell of data row or data table.

Error Reason :

Here is example for this.
We have datatable. This data table contains value of cusutomers, thsi data table has three columns.
Columns are customer_id, customer_firstname and customer_lastname.
Sometimes customer_lastname column has DBNULL value and we directly assign this value to string variable at that time this error occured.

Something like this.
dtCustomer.rows[0]["customer_lastname "]  has DBNULL value. and we are assigning this value to variable like this.


C# Examples :
string strCustomerLastName = dtCustomer.Rows[0]["customer_lastname "].ToString();

VB.net Examples :
Dim strCustomerLastName As String = dtCustomer.Rows(0)("customer_lastname ").ToString()

At this time this error occured.

Solution :

Before assigning or converting this DBNULL value we have make check for this.
We can make check with "System.DBNull.Value" value. We compare both "cell" and "System.DBNull.Value" value if both are same so we do not assign or convert that value. We simply use default value.

Here is Example for this.


C# Examples :
        string strCustomerLastName=string.Empty;
        if(dtCustomer.Rows[0]["customer_lastname "] != System.DBNull.Value)
        {
            strCustomerLastName = dtCustomer.Rows[0]["customer_lastname "].ToString();
        }

VB.net Examples :
        Dim strCustomerLastName As String = String.Empty
        If (dtCustomer.Rows(0)("customer_lastname ") IsNot System.DBNull.Value) Then
            strCustomerLastName = dtCustomer.Rows(0)("customer_lastname ").ToString()
        End If

This is very useful articles for Beginning .Net .

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 9 August 2012

You are able to reading event log from .Net application.
We are using "EventLog" class of "System.Diagnostics" namespace.
There are three categories of event log available Application, Security and System.

Here is example for this.
In this example we take one combobox, this combobox contains three values "Application", "Security" and "System". You can select any one category to read event log and display it's result in grid.

ASPX Code : 
        <asp:DropDownList runat="server" ID="cboEventLog">
            <asp:ListItem Text="Application" Value="Application"></asp:ListItem>
            <asp:ListItem Text="Security" Value="Security"></asp:ListItem>
            <asp:ListItem Text="System" Value="System"></asp:ListItem>
        </asp:DropDownList>
        <asp:Button runat="server" ID="btnGetEventLog" Text="Get Event Log" OnClick="btnGetEventLog_Click" />
        <br /><br />
        <asp:GridView ID="gvEventLog" runat="server" AllowPaging="true" PageSize="5" Width="100px" >
        </asp:GridView>

C# Examples :
        EventLog objEL = new EventLog();
        objEL.Source = cboEventLog.SelectedItem.Text;
        gvEventLog.DataSource = objEL.Entries;
        gvEventLog.DataBind();

VB.net Examples :
        Dim objEL As New EventLog()
        objEL.Source = cboEventLog.SelectedItem.Text
        gvEventLog.DataSource = objEL.Entries
        gvEventLog.DataBind()

Output :

(To view original image , click on image)

Here is an example of write or insert event log entry into windows event log. Click Here...

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 8 August 2012

Every ASP.NET server includes a number of configuration files, such as the machine.config , web.config file. This file is installed as a default .NET Framework installation. You can find "machine.config" file and and other server-specific configuration files in "C:\Windows\Microsoft.NET\Framework\v4.xxxxxx" folder. They have the default settings for ASP.NET Web applications on the server.

List of the server-wide configuration files :
  • machine.config
  • machine.config.comments
  • machine.config.default
  • web.config
  • web.config.comments
  • web.config.default
  • web_hightrust.config
  • web_hightrust.config.default
  • web_lowtrust.config
  • web_lowtrust.config.default
  • web_mediumtrust.config
  • web_mediumtrust.config.default
  • web_minimaltrust.config
  • web_minimaltrust.config.default

.Net Framework install machine.config , machine.config.default and machine.config.comments files.
The machine.config.default file is a backup of the machine.config file.
If you want to the factory setting of machine.config file, you simply copy the settings from the machine.config.default to the machine.config file.

The machine.config.comments file contains a description for each configuration section and explicit settings for the most commonly used values. machine.config.default and machine.config.comment files are not used by the .NET Framework runtime, they are installed in case you want to revert to default factory settings.

You can find a root - level web.config file within the same CONFIG folder as the machine.config.

By default, ASP.NET Web applications run under a full trust setting. You can see this setting at the <securityPolicy> and <trust> sections in the root - level web.config file.

Note : Let us know if any additional things you know about this topic. We will update our article accordingly that.


Tuesday 7 August 2012

You can get processors count on your machine.
We are using "ProcessorCount" property of "System.Environment" class.

Here is example for this.
In this example we display Processor count on screen

C# Examples :
Response.Write("<b>Number of Processor :</b> " + Environment.ProcessorCount);

VB.net Examples :
Response.Write("<b>Number of Processor :</b> " & Environment.ProcessorCount)

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.