Wednesday, 26 March 2014

.Net Tips : Fill DataTable from another DataTable using LINQ with C#.Net and VB.Net example

You can fill DataTable from another DataTable using LINQ after doing LINQ operation.

This would be useful in condition like you need to perform some operation on DataTable using LINQ and get back result into another 'DataTable'. Means, you can filter and projection on one DataTable and get result in another DataTable.

We can achieve this by using 'CopyToDataTable' method of LINQ query result variable.

Here is example for this.
In this example we are taking one DataTable which contains product information like ID, name, etc. Now we get only those products which ID is greater than one by LINQ operation on this table and get result in another table using 'CopyToDataTable' method of LINQ query result variable.

C#. Net Example :
    private DataTable GetProducts()
    {
        DataTable dt = new DataTable();
        DataColumn dc;
        DataRow dr;

        dt.TableName = "product";

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

        return dt;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dtProd = GetProducts();
        var obj = (from m in dtProd.AsEnumerable() where m.Field<int>("product_id") > 1 select m);
        DataTable dt = obj.CopyToDataTable();
        Response.Write("a");

    }

VB.Net Examples :
    Private Function GetProducts() As DataTable
        Dim dt As New DataTable()
        Dim dc As DataColumn
        Dim dr As DataRow

        dt.TableName = "product"

        dc = New DataColumn("product_id", Integer.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)

        Return dt
    End Function

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

        Dim dtProd As DataTable = GetProducts()
        Dim obj = (From m In dtProd.AsEnumerable() Where m.Field(Of Integer)("product_id") > 1 Select m)
        Dim dtResult As DataTable = obj.CopyToDataTable()
    End Sub

Output : 
.Net Tips : Fill DataTable from another DataTable using LINQ


Below are the books that you would like :

Tuesday, 4 March 2014

.Net Tips : Create XML file from another XML file with selected Elements using LINQ with C#.Net and VB.Net example

You can create XML file from another file with selected elements from source XML file using LINQ. In this, we query the source XML file using LINQ and write or create new XML file.

Here is example for this. 
In this example we take one "Book.xml" file. In this file we have element like Title, Pages, ISBN and Auther. Now we are querying the "Book.xml" file to get only Title and ISBN of book and create another XML with data that contains only Title and ISBN element.

C#. Net Example :
        XDocument objDoc = XDocument.Load((Server.MapPath("Books.xml")));
        
        var objResults = new XElement("Results",
                         from b in objDoc.Element("Books").Elements("Book")
                         from t in b.Elements("Title")
                         from a in b.Elements("ISBN")
                         select new XElement("Result", t, a));

        StringWriter objSW = new StringWriter();

        //save to XmlWriter
        System.Xml.XmlWriterSettings objSettings = new System.Xml.XmlWriterSettings();
        objSettings.Indent = true;

        XDocument objNewDoc = new XDocument();
        System.Xml.XmlWriter objXMLWriter = System.Xml.XmlWriter.Create(objSW, objSettings);

        objResults.Save(objXMLWriter);
        
        objXMLWriter.Close();
        //Console.WriteLine(objSW.ToString());

        //save to file
        objResults.Save(Server.MapPath("Results.xml"));

VB.Net Examples :
        Dim objDoc As XDocument = XDocument.Load((Server.MapPath("Books.xml")))

        Dim objResults = New XElement("Results",
                                      From b In objDoc.Element("Books").Elements("Book")
                                      From t In b.Elements("Title") From a In b.Elements("ISBN") Select New XElement("Result", t, a))

        Dim objSW As New StringWriter()

        'save to XmlWriter
        Dim objSettings As New System.Xml.XmlWriterSettings()
        objSettings.Indent = True

        Dim objNewDoc As New XDocument()
        Dim objXMLWriter As System.Xml.XmlWriter = System.Xml.XmlWriter.Create(objSW, objSettings)

        objResults.Save(objXMLWriter)

        objXMLWriter.Close()
        'Console.WriteLine(objSW.ToString());

        'save to file
        objResults.Save(Server.MapPath("Results.xml"))

Output :


Below are the books that you would like :

Wednesday, 12 February 2014

.Net Tips : Convert DataTable object to list of class object using LINQ with C#.Net and VB.Net example

You can fill List of object from DataTable using LINQ. There are many situations where you need to get data from DB into data table and after that from data table to proper class object. We can do this easily with LINQ.

Here is example for this.
In this example we take one DataTable object which contains two columns 'product_id' and 'product_name'. This DataTable has many rows. Now we want to convert DataTable object into list of class object. We have one Class 'clsProduct' which has two property 'product_id' and 'product_name'. Now we transform DataTable object data in to list of clsProduct class object using LINQ.

Friday, 24 January 2014

MVC Tips : Implement IValidatableObject Interface for custom validation in ASP.Net MVC 4

Click Here to Download ImplementIValidateObjectInterfaceInMVC.zip Example.

We can validate model itself by implementing IValidatableObject Interface. For validation you need to implement 'Validate' method of IValidatableObject Interface.

Here is some difference from the attribute validation version.
  • In this for validation method is 'Validate' instead of 'IsValid' and also return type and parameter is different.
  • The return type for Validate is an IEnumerable<ValidationResult>, because the logic inside this method is validating the entire model and might need to return more than a single validation error.
  • No parameter is passed to Validate because you  can directly access model properties because this Validate method is inside model.

Here is example for this.

Thursday, 16 January 2014

.Net Tips : Attach and Raise events on XML document object with C#.Net and VB.Net example

You can attach events like 'onChanging' and 'onChanged' events on XML document object. These events raise when you 'ADD' or 'REMOVE' XML element from XML Document object.

First 'onChanging' event raise after that 'onChanged' event raise. In this event we get 'XObjectChangeEventArgs' class object. This object give us property like 'ObjectChange'. In this property we can know that which method is performed.

When we call 'Add' method we get 'Add' value in 'ObjectChange' property and when we call 'Remove' method we get 'Remove' value in 'ObjectChange' property.

Here is example on this.

Wednesday, 1 January 2014

MVC Tips : Custom Annotation validation in ASP.Net MVC 4

Click Here to Download CustomAnnotationInMVC.zip Example.

You can write your own custom annotations in MVC 4.
Here we can do custom validation using custom annotations. Custom annotations validation derive from the ValidationAttribute base class. This base class available in 'System.ComponentModel.DataAnnotations' namespace. ValidationAttribute class is abstract class.

For custom validation you need to write your own class and inherit ValidationAttribute class. After that, you need to override IsValid Method. IsValid Method has two parameters 'Value' and 'ValidationContext'.

  • Value : Which contains your data, which is going to validate.
  • ValidationContext : This parameter is very important. This content information like model object instance, model type friendly display name and other information
In this method you write your own logic for validate data and return result. If value is validate at that time you need to return this 'ValidationResult.Success' else you return result like 'return new ValidationResult(your custom error message)'

Friday, 20 December 2013

C# Tips : Validate or Verify XML File Data using LINQ and REGEX with C#.Net and VB.Net example

You can validate the data of XML file and identify XML elements which are failed to validate. We can easily achieve this using LINQ.

Here is example for this.
In this example we take one 'customer.xml' file. In this file we have 'name' and 'phone' element. We need to validate phone number with REGEX and display it's validate result either it is true or false.