Showing posts with label IO. Show all posts
Showing posts with label IO. Show all posts

Monday, 24 September 2012

Click Here to Download ProcessRSSorATOMFeed.zip

You can process the content of an Atom 1.0 or RSS 2.0 feed to extract or get details of the feed. .Net framework provide classes to parse the feed data.
We are using System.ServiceModel.Syndication.SyndicationFeedFormatter and System.ServiceModel.Syndication.SyndicationFeed classes.

The SyndicationFeedItem  and SyndicationFeed classes gives a generic abstraction of Atom 1.0 and RSS 2.0 feeds and feed items, and provide a common interface to simplify the processing of both feed types. The Rss20FeedFormatter class allows to create a SyndicationFeed object from an RSS 2.0 feed, and the Atom10FeedFormatter class provides support for Atom 1.0 feeds. Both classes are available in the System.ServiceModel.Syndication namespace.
We are using "ReadFrom" method and "Feed" property of these classes.

Here is example for this.
In this example we read the feed and display it's details.

C# Examples :
        Uri objFeedUrl = null;
        string strUrl = "http://jayeshsorathia.blogspot.com/rss.xml";
        if (strUrl.Length == 0 || String.IsNullOrEmpty(strUrl) || !Uri.TryCreate(strUrl, UriKind.RelativeOrAbsolute, out objFeedUrl))
        {
            Response.Write("Invalid feed.");
            return;
        }

        // Create the web request.
        WebRequest objReqFeed = WebRequest.Create(objFeedUrl);

        // Get the data from the feed.
        WebResponse objResFeed = objReqFeed.GetResponse();

        
        SyndicationFeedFormatter objFeedFormatter = null;

        XElement feed = XElement.Load(objResFeed.GetResponseStream());

        // Check for the feed type
        if (feed.Name.LocalName == "rss")
        {
            objFeedFormatter = new Rss20FeedFormatter();
        }
        else if (feed.Name.LocalName == "feed")
        {
            objFeedFormatter = new Atom10FeedFormatter();
        }
        else
        {
            Response.Write("Unsupported feed type: " + feed.Name.LocalName);
            return;
        }

        // Read the feed data into the formatter.
        objFeedFormatter.ReadFrom(feed.CreateReader());

        // Display feed Details

        Response.Write("<b>Feed Title : </b>" + objFeedFormatter.Feed.Title.Text);
        Response.Write("<br/><br/>");
        Response.Write("<b>Feed Description : </b>" + objFeedFormatter.Feed.Description.Text);
        Response.Write("<br/><br/>");
        Response.Write("<b>Items in the Feed : </b>");
        Response.Write("<br/><br/>");
        
        foreach (var objItem in objFeedFormatter.Feed.Items)
        {
            Response.Write("<b>Title : </b> " + objItem.Title.Text);
            if (objItem.Summary != null)
            {
                Response.Write("<br/><b>Summary : </b>" + objItem.Summary.Text);
            }

            Response.Write("<br/><b>Publish Date : </b>" + objItem.PublishDate);
            Response.Write("<br/><br/>");
        }

VB.net Examples :
        Dim objFeedUrl As Uri = Nothing
        Dim strUrl As String = "http://jayeshsorathia.blogspot.com/rss.xml"
        If strUrl.Length = 0 Or String.IsNullOrEmpty(strUrl) Or Not Uri.TryCreate(strUrl, UriKind.RelativeOrAbsolute, objFeedUrl) Then
            Response.Write("Invalid feed.")
            Return
        End If

        ' Create the web request.
        Dim objReqFeed As WebRequest = WebRequest.Create(objFeedUrl)

        ' Get the data from the feed.
        Dim objResFeed As WebResponse = objReqFeed.GetResponse()


        Dim objFeedFormatter As SyndicationFeedFormatter = Nothing

        Dim feed As XElement = XElement.Load(objResFeed.GetResponseStream())

        ' Check for the feed type
        If feed.Name.LocalName = "rss" Then
            objFeedFormatter = New Rss20FeedFormatter()
        ElseIf feed.Name.LocalName = "feed" Then
            objFeedFormatter = New Atom10FeedFormatter()
        Else
            Response.Write("Unsupported feed type: " & feed.Name.LocalName)
            Return
        End If

        ' Read the feed data into the formatter.
        objFeedFormatter.ReadFrom(feed.CreateReader())

        ' Display feed Details

        Response.Write("<b>Feed Title : </b>" & objFeedFormatter.Feed.Title.Text)
        Response.Write("<br/><br/>")
        Response.Write("<b>Feed Description : </b>" & objFeedFormatter.Feed.Description.Text)
        Response.Write("<br/><br/>")
        Response.Write("<b>Items in the Feed : </b>")
        Response.Write("<br/><br/>")

        Dim objItem As SyndicationItem
        For Each objItem In objFeedFormatter.Feed.Items
            Response.Write("<b>Title : </b> " & objItem.Title.Text)
            If Not objItem.Summary Is Nothing Then
                Response.Write("<br/><b>Summary : </b>" & objItem.Summary.Text)
            End If

            Response.Write("<br/><b>Publish Date : </b>" & objItem.PublishDate.ToString())
            Response.Write("<br/><br/>")
        Next

Output : 
Read the Content of an Atom or RSS Feed output
(To view original image , click on image)

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

Download Sample Application. Download...

Binary Deserialization is a reverse process of Binary Serialization.
In Binary Deserialization we fetch binary file that generated from Binary Serialization and get back orignal object.
In previous example we serialize one list object using binary serialization and store in file.

Here is example for this.
In this example we take binary serialized file and generate list object from that with data.
You can see in the output image that "booklist" object fill from the "books.bin" binary file.

C# Examples :
    [Serializable]
    public class Books
    {
        public string Title { get; set; }
        public string ISBN { get; set; }
        public DateTime ReleaseDate { get; set; }
        public int Pages { get; set; }
        public int PublisherId { get; set; }
    }
       
   
    protected void Page_Load(object sender, EventArgs e)
    {
        //Read Binary Serialized File
        System.IO.FileStream objFS = System.IO.File.OpenRead(Server.MapPath("books.bin"));
        BinaryFormatter objBF = new BinaryFormatter();
        // Deserialize File stream into object
        var bookslist = objBF.Deserialize(objFS);

    }
VB.net Examples :
    <Serializable()> _
    Public Class Books
        Public Property Title() As String
        Public Property ISBN As String
        Public Property ReleaseDate As Date
        Public Property Pages As Integer
        Public Property PublisherId As Integer
    End Class

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

        ''Read Binary Serialized File
        Dim objFS As System.IO.FileStream = System.IO.File.OpenRead(Server.MapPath("books.bin"))
        Dim objBF As New BinaryFormatter()
        '' Deserialize File stream into object
        Dim bookslist = objBF.Deserialize(objFS)
    End Sub

Output : 

(To view original image , click on image)


Click Here to view "Serialize object and store in file using Binary Serialization 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.



Monday, 10 September 2012

 Download Sample Application. Download...

There is a need to serialize object and store into a file, and then deserialize when required.
For Binary Serialization we are using "BinaryFormatter" class which is available in "System.Runtime.Serialization.Formatters.Binary" namespace.
"BinaryFormatter" class produce a binary data of serialized object. If you want to serialize custom class object for that you have to declare that class as serializable and add "[Serializable]" attribute on that class name.

Here is example for this.
In this example we take one class name "Books" and generate books list object and do binary serialize of that list and store in "Books.bin" file. You can give any extension of that generated file name. The generated file is in binary so not easy to understand.


C# Examples :
    [Serializable]
    public class Books
    {
        public string Title { get; set; }
        public string ISBN { get; set; }
        public DateTime ReleaseDate { get; set; }
        public int Pages { get; set; }
        public int PublisherId { get; set; }
    }

    public List<Books> GetBooksList()
    {
        return new List<Books> {
                        new Books { Title="ASP.NET",ISBN="asp1",ReleaseDate= DateTime.Parse( "11/11/2010") ,Pages=200,PublisherId=1},
                        new Books { Title="C#.NET",ISBN="c#2",ReleaseDate= DateTime.Parse( "10/11/2010") ,Pages=500,PublisherId=1},
                        new Books { Title="VB.NET",ISBN="vb3",ReleaseDate= DateTime.Parse( "5/5/2009") ,Pages=400,PublisherId=1},
                        new Books { Title="SQL Server",ISBN="sql4",ReleaseDate= DateTime.Parse( "6/9/2010"),Pages=300,PublisherId=2 },
                        new Books { Title="JAVA",ISBN="java5",ReleaseDate= DateTime.Parse( "8/5/2011"),Pages=400,PublisherId=3 },
                        new Books { Title="HTML",ISBN="html6",ReleaseDate= DateTime.Parse( "9/5/2011"),Pages=400 }
        
        };

    }

    private void BinarySerialization(System.Collections.Generic.List<Books> bookslist)
    {
        BinaryFormatter objBF = new BinaryFormatter();
        System.IO.FileStream objFS = System.IO.File.Create(Server.MapPath("books.bin"));
        objBF.Serialize(objFS, bookslist);
        objBF = null;
        objFS.Close();
        objFS = null;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Collections.Generic.List<Books> bookslist = GetBooksList();
        BinarySerialization(bookslist);
    }

VB.net Examples :
    <Serializable()> _
    Public Class Books
        Public Property Title() As String
        Public Property ISBN As String
        Public Property ReleaseDate As Date
        Public Property Pages As Integer
        Public Property PublisherId As Integer
    End Class

    Public Function GetBooksList() As List(Of Books)
        Dim lstBooks As New List(Of Books) From { _
                                New Books With {.Title = "ASP.NET", .ISBN = "asp1", .ReleaseDate = DateTime.Parse("11/11/2010"), .Pages = 200, .PublisherId = 1}, _
                                New Books With {.Title = "C#.NET", .ISBN = "c#2", .ReleaseDate = DateTime.Parse("10/11/2010"), .Pages = 500, .PublisherId = 1}, _
                                New Books With {.Title = "VB.NET", .ISBN = "vb3", .ReleaseDate = DateTime.Parse("5/5/2009"), .Pages = 400, .PublisherId = 1}, _
                                New Books With {.Title = "SQL Server", .ISBN = "sql4", .ReleaseDate = DateTime.Parse("6/9/2010"), .Pages = 300, .PublisherId = 2}, _
                                New Books With {.Title = "JAVA", .ISBN = "java5", .ReleaseDate = DateTime.Parse("8/5/2011"), .Pages = 400, .PublisherId = 3}, _
                                New Books With {.Title = "HTML", .ISBN = "html6", .ReleaseDate = DateTime.Parse("9/5/2011"), .Pages = 400}}

        Return lstBooks
    End Function

    Private Sub BinarySerialization(ByVal bookslist As System.Collections.Generic.List(Of Books))
        Dim objBF As New BinaryFormatter()
        Dim objFS As System.IO.FileStream = System.IO.File.Create(Server.MapPath("books.bin"))
        objBF.Serialize(objFS, bookslist)
        objBF = Nothing
        objFS.Close()
        objFS = Nothing
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim bookslist As System.Collections.Generic.List(Of Books) = GetBooksList()
        BinarySerialization(bookslist)
    End Sub

Output : 

(To view original image , click on image)


Click Here to view "Binary Deserialization with C# Examples and VB.Net Examples". 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.




Monday, 3 September 2012

You can retrieve stored file from SQL Server Database Table and store as physical file in hard drive.
In earlier example we stored file into SQL Server Database table.

Here is example for this.
In this example we retrieved stored file from database record and store as physical file in hard drive.
We retrieved "product_document" column data and stored.

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

        objConn.Open();
        objCmd.Connection = objConn;
        objCmd.CommandText = "select * from product_master where product_id=15";
        objAdapt.SelectCommand = objCmd;
        objAdapt.Fill(Ods);
        objConn.Close();
        string strFileName = Convert.ToString(Ods.Tables[0].Rows[0]["product_document_filename"]);
        Byte[] objByte = (Byte[])Ods.Tables[0].Rows[0]["product_document"];

        System.IO.File.WriteAllBytes(Server.MapPath("") + "/" + strFileName, objByte);

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

        objConn.Open()
        objCmd.Connection = objConn
        objCmd.CommandText = "select * from product_master where product_id=15"
        objAdapt.SelectCommand = objCmd
        objAdapt.Fill(Ods)
        objConn.Close()
        Dim strFileName As String = Convert.ToString(Ods.Tables(0).Rows(0)("product_document_filename"))
        Dim objByte As [Byte]() = DirectCast(Ods.Tables(0).Rows(0)("product_document"), [Byte]())

        System.IO.File.WriteAllBytes(Server.MapPath("") & "/" & strFileName, objByte)

Click here to view "Insert or Save file into SQL Server Database Table with C# Examples and VB.Net Examples" article. Click Here...

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.



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.




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.

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.


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.


Tuesday, 19 June 2012

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

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

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

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

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

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

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

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

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

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

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

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

    int len = 0;

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

    objFileStreamTxt.Close();

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

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

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

        objFileStreamTxt.Close()

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

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

    objFileStreamTmp.Close();

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

        objFileStreamTmp.Close()

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

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


Saturday, 16 June 2012

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

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

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

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


Thursday, 14 June 2012

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

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

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

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

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

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

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

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

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

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

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

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

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

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