Friday, December 31, 2010

Simple LINQ to SQL in C#

This article provides an introduction to employing LINQ to SQL within a Windows Forms application; the article will address the incorporation of LINQ to SQL into a win forms project, how to use LINQ to SQL to select, insert, update, and delete data, and how to use LINQ to SQL to execute stored procedures.  Select query examples will demonstrate ordering, filtering, aggregation, returning typed lists, returning single objects and values, and how to query across entity sets (which are essentially related tables associated by foreign keys).

Figure 1:  Application Main Form
The demonstration project included with the article is a simple win forms application; this example contains a datagridview control and a menu; the menu is used to execute each example query contained in the demonstration.
The application provides the following functionality:
  • Return Full Tables
  • Return Typed Lists
  • Return Single Typed Values
  • Insert Data
  • Update Data
  • Delete Data
  • Execute Stored Procedures
  • Select Filtered Lists
  • Select Ordered Lists
  • Perform Aggregate Functions
There is a great deal more that one can do with LINQ to SQL that is not contained in this demonstration however, the demonstration was geared towards the mechanics of performing the most typical types of queries that might be required within a data driven application.
LINQ to SQL Statements
This section will discuss some of the common techniques used in LINQ to SQL statement construction.  In a nutshell, LINQ to SQL provides the developer with the means to conduct queries against a relational database through a LINQ to SQL database model and related data context.  

http://www.c-sharpcorner.com/UploadFile/scottlysle/L2SinCS06022008035847AM/L2SinCS.aspx

Thursday, December 30, 2010

Introducing LINQ

Introducing LINQ is the first part of a series of articles on Language Integrated Query (LINQ). This series will cover the core essentials of LINQ and its use with other technologies like ASP.NET, Win Forms and WPF.
This and the forthcoming articles are designed to be a comprehensive tutorial on LINQ, having completed the series you will have a thorough understanding of LINQ and C# 3.0.
All code in the series will use the latest publicly available CTP at the time of writing.

Introducing LINQ Series

  • Part 1 In this part you will learn how to the query in-memory collections.
  • Part 2 In this part we will look at querying relational data.
  • Part 3 In this part we will look a little more at what entities are, as well as taking a closer look at the key types we can use and their application .
  • Part 4 In this part of the series we will use LINQ, ASP.NET and ASP.NET AJAX to replicate the to-do list that Scott Guthrie created a while back to show off the features of ASP.NET AJAX.
  • Part 5 In this part of the series I will explain the DataContext class in depth through a series of examples and explanations.

  • Read More : http://dotnetslackers.com/articles/csharp/IntroducingLINQ1.aspx

    Friday, December 10, 2010

    Optimized Paging and Sorting in ASP.NET GridView

    Introduction

    Paging and sorting are most commonly used features of ASP.NET GridView. And it is very easy to use/implement these features in GridView with small chunk of lines. In this article I am going to demonstrate what are the performance drawbacks of using conventional way to page and sort your GridView and then I will demonstrate 'An Optimized way to implement Paging and Sorting'.

    What are conventional steps for Paging and Sorting?

    Usually we perform the following steps to enable paging and sorting in our GridView.
    1. Set AllowPaging and AllowSorting Properties of GridView to True to enable paging and sorting respectively e.g
    view sourceprint?
    1.<asp:GridView ID="GridView1" runat="server" AllowPaging="true" AllowSorting="true"  >
    2. </asp:GridView>
    2. Set the PageSize property to mention how many records will be display on each page.
    3. Set the SortExpression property of each column. By default each Data Bound columns has the bounded column name as default value for the SortExpression property.
    4. Handle PageIndexChanging and Sorting Events of GridView to respond to paging and sorting actions respectively, like so:
    view sourceprint?
    01.<asp:GridView ID="GridView1" runat="server" AllowPaging="true"
    02.            AllowSorting="true" onpageindexchanging="GridView1_PageIndexChanging"
    03.            onsorting="GridView1_Sorting"  >
    04.        </asp:GridView>
    05. protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    06.{
    07.}
    08.protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    09.{
    10.}
    5. Put some logic in the event handlers to do their jobs
    5a. In the PageIndexChanging Event Handler method, we usually get the data from database or somewhere from the Cache and rebind our Grid with that data. After rebinding we change the PageIndex property of the GridView to a new page index to display the page that was selected by the user.
    view sourceprint?
    1.protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    2. {
    3.     GridView1.DataSource = GetData(); // GetData() is a method that will get Data from Database/Cache/Session to display in Grid.
    4.     GridView1.DataBind();
    5.     GridView1.PageIndex = e.NewPageIndex;
    6. }
    5b. In the Sorting event handler method, we get the sorted data according to the sort expression from our data source (data source could be database/cache/session etc) and then rebind the Grid to display the sorted records.
    And that's it.

    Drawbacks

    In conventional way of paging and sorting we get complete set of data instead of getting only the portion of data that is required to display on current/requested page. As you can see on each pageIndexChanging call we are getting all the data from our data source and then binding it to the GridView. Ideally we should get only the data that we need to display on the requested page.

    Hmmm...Sounds good but HOW??

    The question that may arise in your mind could be "It seems good in theory that we should only get the required data, but practically if we bind only one page of data with GridView then it would assume that this is the only data that it needs to display. So how does the GridView even display page numbers and total records count? It is a genuine question, so let's try to answer!

    An Optimized Way to implement Paging and Sorting

    As in the start of this article, we discuss the conventional 5 steps to implement paging and sorting in ASP.NET GridView . In this solution we will use the first 3 steps as described above, and perform the 4th and 5th steps by ourselves. We will use an ObjectDataSource that will perform these steps for us in an optimized way.

    http://dotnetslackers.com/articles/gridview/Optimized-Paging-and-Sorting-in-ASP-NET-GridView.aspx

    Multi File Upload Using JQuery!

    Herewith I have explained and given the code for multiple file upload using jquery.
    We know all the normal upload functionality. But someone of us wants the multiple file upload in .NET. Here jquery makes that very easy.
    We just use the same asp:fileupload control. If you want to accept only jpg,png only you no need to go for a customvalidator tocheck the file extension. You just add the accept="jpg|png". Thats it. It allows only files which has the extension of above.
    Ok let us see the code below,

    HEAD SECTION:
    <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
    <script src="Scripts/jquery.MultiFile.js" type="text/javascript"></script>
     
    BODY TAG:
    <div>

    <asp:FileUpload ID="fupImage" runat="server" class="multi" accept="" />
    <br />
    <asp:Button ID="btnUpload" runat="server" Text="Upload All" OnClick="btnUpload_Click" />
    </div>

    Thats it about in the UI page(aspx).
    Let us see the code behind page,

    the following code should be inside in the upload button event,

    try

    {
    // Get the HttpFileCollection
    HttpFileCollection hfc = Request.Files;
    Guid newid = new Guid();
    newid = System.Guid.NewGuid();
    for (int i = 0; i < hfc.Count; i++)
    {
    HttpPostedFile hpf = hfc[i];
    if (hpf.ContentLength > 0)
    {
    hpf.SaveAs(Server.MapPath("Files") + "\\" +
    System.IO.Path.GetFileName(newid + hpf.FileName));
    Response.Write("Uploaded Successfully <br/>");
    }
    }
    }
    catch (Exception ex)
    {
    // ERROR OCCURED
    }

    http://dotnetworldblog.blogspot.com/2010/04/multi-file-upload-using-jquery.html

    Light Weight PopUp

    Here we have a javascript and CSS code to create a light weight popups
    on Code Behind
    <div>
    <input id="Button1" type="button" value="Click To Popup" onclick="ShowDiv('DivOrderSearch','DivLayer')" />
    </div>
      <div id="DivLayer" class="DialogueBackground">
    </div>
    <div id="DivOrderSearch" style="width: 400px; height: 300px; background-color: #D9E0E6;"
      class="Dialogue">
      <div class="DialogueTitle">
    Popup Sample
    </div>
      <div class="DialogueImg" onclick="HideDiv('DivOrderSearch');" title="Close">
    </div>
    <div style="padding: 10px;">
    Hello World
    </div>
    </div>

    Add javascripts

    function HideDiv(PopUpDiv) {
    var DivPopUp = document.getElementById(PopUpDiv);
    var DivLayer = document.getElementById('DivLayer');
    DivPopUp.style.display = "none";
    DivLayer.style.width = "0%";
    }
    function ShowDiv(PopUpDiv, LayerDiv) {
    var DivPopUp = document.getElementById(PopUpDiv);
    var DivLayer = document.getElementById(LayerDiv);
    DivPopUp.style.display = "block";
    DivLayer.style.width = "100%";
    DivPopUp.style.top = document.documentElement.clientHeight / 2 - DivPopUp.style.height.replace('px', '') / 2 + 'px';
    DivPopUp.style.left = document.body.offsetWidth / 2 - DivPopUp.style.width.replace('px', '') / 2 + 'px';
    return false;
    }

    Few Css Classes

    .DialogueBackground
    {
    background-color: Gray;
    filter: alpha(opacity=50);
    opacity: 0.50;
    position: fixed;
    left: 0;
    top: 0;
    width: 0%;
    height: 100%;
    }

    .Dialogue
    {
    background-color: White;
    display: none;
    z-index: 2;
    border: 1px solid Black;
    position: fixed;
    text-align: center;
    }
    .DialogueImg
    {
    height: 30px;
    position: absolute;
    width: 27px;
    float: right;
    background-image: url(../images/closebox.png);
    cursor: pointer;
    right: -15px;
    top: -15px;
    background-repeat: no-repeat;
    border: 0;
    }
    .DialogueTitle
    {
    font-size: small;
    font-weight: bolder;
    padding: auto;
    height: 25px;
    color: #ffffff;
    position: relative;
    background: url(../images/app_tab2.jpg) repeat-x;
    top: 0px;
    }

    Export to PDF file in ASP.Net – Gridview to PDF, ASPX Page Content to PDF

    Creating data driven application is one of the most commonly done task in our day today application development. In these applications, reporting and generating reports in various formats is one of the repeated requirements we will get. Read the article Export to Excel in ASP.Net 2.0 – Gridview to Excel, DataTable to Excel which discusses some handful of techniques to export the data to excel file. Apart from excel reports, generating PDF report is one of the most common reporting requirement we will get in data driven application. Exporting data to PDF format is not a straight forward task like we do for excel file generation. To do this, we have to employ some 3rd party component or develop a component ourselves by understanding the PDF file standards.

    Since, developing a component ourselves is complicated and time consuming task we can try using any free 3rd party component available in the market. In this article, we will try using one of most widely used PDF generation component called iTextSharp or iText PDF component.

    According to iText PDF official site,
    iText is a library that allows you to generate PDF files on the fly.
    iText is an ideal library for developers looking to enhance web- and other applications with dynamic PDF document generation and/or manipulation.

    In this article, we will see about,
    1.      Simple PDF generation from an in-memory string or HTML string
    2.      Export Page Content to PDF
    3.      Export GridView control to PDF

    Steps
    1.      Open Visual Studio 2008, Click File >Website and choose ASP.Net Website.
    2.      Select a language of your choice. I have selected C#. You can name your website as per your need.
    3.      Download the iText PDF component from the official site (or from here) and add it to your project through add reference dialog box.

    http://www.codedigest.com/Articles/ASPNET/344_Export_to_PDF_file_in_ASPNet-Gridview_to_PDF_ASPX_Page_Content_to_PDF.aspx

    ASP.NET Application Folder

    http://www.codeproject.com/KB/aspnet/AspNetAppFolder.aspxOverview - ASP.NET Application Folders

    ASP.NET 2.0 uses a file-based approach. That means, all class files, resource files, data files and folders are maintained in a hierarchical structure. If we are working with ASP.NET 2.0, we can add files and folders using the Add Items option. If we look at a sample application hierarchy, it will look like the following figure.
    beginn1.jpg
    We can add as many as files and folders as we like (according to our requirements) within our solutions,and it won't be necessary to recompile them each and every time they are added. It is ASP.NET'stask to dynamically compile them when required. So, what ASP.NET 2.0 does is, it uses a predefined folder structure containing the files (classes, images, resources, etc.), to compile them dynamically and we can access those files throughout the application. ASP.NET also provides special folders to maintain files and resources. Let's see the advantages of using these folders.

    Advantages of ASP.NET Application Folders

    Following are the main advantages of use of ASP.NET's Application Folders
    • We can maintain resources (classes, images, code, databases, themes) in an organized manner, which allows us to develop and maintain sites easily
    • All files and folders are accessible through the application
    • We can add as many files as required
    • Files are compiled dynamically when required 

    http://www.codeproject.com/KB/aspnet/AspNetAppFolder.aspxhttp://www.codeproject.com/KB/aspnet/AspNetAppFolder.aspx