Thursday, August 30, 2012

LINQ to Object Examples

LINQ: Language Integrated Query


you’ll need to persist objects to a database, query the database and load the results back into objects. The problem is that in
most cases, at least with relational databases, there is a gap between your programming language and the database. Good attempts have been made to provide object-oriented databases, which would be closer to object-oriented platforms and imperative programming languages like C# and VB.NET. However, after all these years, relational databases are still pervasive and you still have to struggle with data-access and persistence in all of your programs.The original motivation behind LINQ was to address the impedance mismatch between programming languages and databases. With LINQ, Microsoft’s intention was to provide a solution for the problem of  object-relational mapping, as well as simplify the interaction between objects and data sources. 

LINQ eventually evolved into a general-purpose language-integrated querying toolset. This toolset can be used to
access data coming from in-memory objects (LINQ to Objects), databases (LINQ to SQL), XML documents (LINQ to XML), a file-system, or from any other source.

Examples


 Response.Write("<h2>LINQ to Object</h2>");

        int[] numbers = { 5,6,7,8,3,4,9,1,2,0 };

        var no= from n in numbers
                    group n by n % 2 into g 
                    select new { Reminder=g.Key ,Number=g   };
        foreach (var g in no)
        {
            string s = string.Format("<br/>no of remainder of {0} when divided by 2:", g.Reminder);
            Response.Write(s);
            
            foreach (var n in g.Number)
            {
                Response.Write("<br/>"+n);
            }
        }
        /*
     OUTPUT
      no of remainder of 1 when divided by 2:
     5
     7
     3
     9
     1
      no of remainder of 0 when divided by 2:
     6
     8
     4
     2
     0
        */
        // for word lenth
        Response.Write("<h3>find length of word</h3>");
  string[] word = { "ABCD","EFG","HIJKL","MN","OPQRST","UVWXYZ"};

        var len = from words in word

                 // where words.Length <= 5
                 orderby words.Length ascending
                  select words;
        foreach (var leng in len)
        {
            Response.Write("<br/>" + leng + " >>Length :" + leng.Length);
        }
              
          /*
           OUTPUT
        find length of word
        MN >>Length :2
        EFG >>Length :3
        ABCD >>Length :4
        HIJKL >>Length :5
        OPQRST >>Length :6
        UVWXYZ >>Length :6
           */
                      
        //find even no

        Response.Write("<h3>find even number</h3>");

        int[] number = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15 };

        var ev = from even in number
                 where even % 2 == 0
                 orderby even descending
                 select even;
        Response.Write("Even Number<br/>");
        foreach (var evn in ev)
        {
            Response.Write(evn+"<br/>");
        }

        /*
         OUTPUT
      find even number
      Even Number
    12
    10
    8
    6
    4
    2
       */    

Friday, August 17, 2012

Split and Merge File Example in asp.net

In this example i am showing how to split the file size into more than one file.
(Example: suppose file size is of 200byte and i want to split this file into 2 part 100byte each and save them)

in .aspx page
 <asp:FileUpload ID="FileUpload1" runat="server" />
 <asp:Button ID="btnupload" runat="server" Text="find Byte"
          onclick="btnupload_Click" />
 </p>
 <p>
  No to split :
 <asp:TextBox ID="txtsayno" runat="server"></asp:TextBox>
 </p>
 <p>
 <asp:Button ID="btnsplit" runat="server" onclick="btnsplit_Click" Text="Split" />
 </p>
 
 
in .cs page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
    FileInfo info;
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnupload_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile && FileUpload1.FileContent.Length > 0)
        { FileUpload1.PostedFile.SaveAs(

Server.MapPath("file/"+FileUpload1.FileName));
         info=new FileInfo(Server.MapPath("file/"+FileUpload1.FileName));
         Session["filename"] = "file/" + FileUpload1.FileName;
            long fileinByte=info.Length;
            Response.Write(fileinByte);
        }
    }
    protected void btnsplit_Click(object sender, EventArgs e)
    {
        flename = new string[100];
        string file = Server.MapPath(Session["filename"].ToString());
        info = new FileInfo(file);

        FileStream fs = new FileStream(file,FileMode.Open,FileAccess.Read);
       int no=Convert.ToInt32(txtsayno.Text);
        int size=Convert.ToInt32(info.Length / no);
        for (int i=0;i<no;i++)
        {
         
        string basename = Path.GetFileNameWithoutExtension(file);
        string ex = Path.GetExtension(file);
        Session["extension"] = ex;
        FileStream outputFile = new FileStream(Path.GetDirectoryName(file) + "\\" + basename + "." + i.ToString().PadLeft(5, Convert.ToChar("0")) + ex + ".tmp", FileMode.Create, FileAccess.Write);
       flename[i] = basename + "." + i.ToString().PadLeft(5, Convert.ToChar("0")) + ex + ".tmp";
       string mergeFolder = Path.GetDirectoryName(file);
                    int bytesRead = 0;
                    byte[] buffer = new byte[size];
                    if ((bytesRead = fs.Read(buffer, 0, size)) > 0)
                    {
                        outputFile.Write(buffer, 0, bytesRead);
                    }
                    outputFile.Close();
                }
                fs.Close();             
        }

    }

To view Merge Example Click: Merge File

Thursday, August 2, 2012

Client Callbacks Example in Asp.net

Client callbacks : Rather than posting back the entire page, your custom control can send a request to the server to get just the additional information it needs.

Example:                                                        On Click of Button show Alert box with text value.

 in .aspx page                                                             <script type="text/javascript">
        function ss() {
            var va = document.forms[0].Text1.value;
            UseCallback(va, "");
      
    
        }
        function show(Text1, context) {
            alert(Text1);
      
        }
    </script> 
      <asp:Panel ID="Panel2" runat="server">
      <input id="Text1" type="text" runat="server" />
      <input id="Button1" type="button" value="button" onclick="ss()"/>
        </asp:Panel>

   in .cs page                              
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
  
 public partial class _Default: System.Web.UI.Page, System.Web.UI.ICallbackEventHandler
{
  protected void Page_Load(object sender, EventArgs e)
    {
        string cref = Page.ClientScript.GetCallbackEventReference(this, "arg", "show", "context");
        string cscript = "function UseCallback(arg,context)" +
            "{" + cref + ";" + "}";
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "UseCallback", cscript, true);
    } 
  public string GetCallbackResult()
    {
        return aa;
    }
    public void RaiseCallbackEvent(string eventArgument)
    {
        aa = eventArgument;
    } 
}
OutPut