Pages

Ruchi Tech

Sunday, 29 July 2012

Entity Framework


What is Entity Framework ?


  • Entity Framework based on ORM (object relation mapping).
  • Entity Framework enables developers to work with relational data, eliminate the need for most of the data access plumbing code that developers usually need to write.
  • It uses LINQ (Language Integrated Query) to retrieve and manipulate data as strongly typed objects.

 

Advantages


  • One common syntax "LINQ" for all object queries.
  • Fast
  • Easy to implement.
  • Less coding required.

Now, take an example for How to use it:

Insertion, Updation and Deletion with Entity Framework


Step:1 First, create a ASP.Net empty web application named "WebAppEntity". Right click on solution, add new item > add ADO.NET Data Entity Model named it as "BusinessObjects.edmx"




Now check your Web.config file, it will create connection string automatically. And check your BusinessObjects.designer.cs also, It looks like:

















Open/Expand Contexts,































Step:2 File > Add > New Project > ASP.NET Empty Web Application named "Entity Framework".

  • Copy connection string of "WebApp Entity Web.config file" to "Entity Framework Web.config file".

  • Add two "Web Refrences" in "Entity Framework"
                       1. Projects > "WebAppEntity"
                       2. System.Web.Entity

  • Create a aspx page named "EntityFirst.aspx" for create, update and delete the records.

Now, Solution looks like:



Step:3 Now Add a code into "EntityFirst.aspx" and  "EntityFirst.aspx.cs"     

Add three button for save, update and delete in EntityFirst.aspx like:

<asp:Button ID="btnsave" runat="server" Text="Save" OnClick="btnsave_Click" />
<asp:Button ID="btnupdate" runat="server" Text="Update" OnClick="btnupdate_Click" />
<asp:Button ID="btndelete" runat="server" Text="Delete" OnClick="btndelete_Click" />


Now, add code in code behind like:

using  WebAppEntity;


LeadManagementTestEntities LeadDB = new LeadManagementTestEntities();

protected void btnsave_Click(object sender, EventArgs e)
{
aaa objaa = new aaa();
objaa.user = "Name";
objaa.city = "Gurgaon";
objaa.designation = "Software Engineer";
LeadDB.aaas.AddObject(objaa);
LeadDB.SaveChanges();
lblmsg.Text =
"Record saved successfully";
}

protected void btnupdate_Click(object sender, EventArgs e)
{
aaa objaa = LeadDB.aaas.SingleOrDefault(p => p.user == "Ruchi");
objaa.city = "Delhi";
LeadDB.SaveChanges();
lblmsg.Text =
"Record updated successfully";
}

protected void btndelete_Click(object sender, EventArgs e)
{
aaa objaa = LeadDB.aaas.SingleOrDefault(p => p.user == "Name");
LeadDB.aaas.DeleteObject(objaa);
LeadDB.SaveChanges();
lblmsg.Text =
"Record deleted successfully";

}



Now, we are done. Run the application and test it.

Sunday, 22 July 2012

How to create RDLC Report in C#

RDLC - Report Definition Language Client-Side

Step 1: In Solution Explorer - right click on add select new item. Select Report wizard with name like "report1.rdlc".




Step 2: In Solution Explorer - right click on add select new item. Select DataSet.



DataSet designer window is display. Right click on it and add Table Adapter.



Now Table Adapter Configuration window is display. Click on New Connection



Add Connection window is display. Now
  • Server Name- Fill your server name
  • Log on to the Server - Click on "Use SQL Server Authentication" and fill your username and password.
  • Connect to a database - select your database name.
  • Test Connection - click on it. If test connection is succeeded, then click on OK.
Click Next then select use SQL statements radio button and click next.

 
Click on Query Builder and add Table and close. There is an option of Execute Query. So use that to execute your query.

Finally, connection string is added on app.config file.

Step 3: Now, on your report1.rdlc, add datasource then Arrange Fields window is display then Drag and drop fields accordingly


Click Next and see the preview . Choose layout and style accordingly. And then click on finish.

Step 4: Add a Window Form, Form the toolbox select reporting and add Report Viewer on it.



Choose Report - Add your report "report1.rlc"
Choose Data Source - Add data source

then click on next and finish.

Now Run your application.

Sunday, 15 July 2012

Move DataGrid Row Up/Down with Sorting

Create two buttons "one for UP" and "one for DOWN" in the datagrid then you can easily move row up and down by using the below code.

Add code in Default.aspx page:


 <asp:DataGrid ID="dgrdAdmin" runat="server" OnItemCommand="dgrdAdmin_ItemCommand"
     AllowSorting="true">
     <Columns>
        <asp:BoundColumn DataField="id" Visible="false"></asp:BoundColumn>
           <asp:TemplateColumn>
              <ItemTemplate>
                 <asp:ImageButton ID="imgbtnUP" runat="server" CommandName="Up" />
                  <asp:ImageButton ID="imgbtnDown" runat="server" CommandName="Down" />
             </ItemTemplate>
          </asp:TemplateColumn>
      </Columns>
  </asp:DataGrid>

Now, Add code in Default.aspx.cs


 private int GetMaxSortOrder()
   {
      int max = 0;
      DataTable dt = new DataTable();
      SqlConnection conn = new SqlConnection("Your_Connection_String");
      SqlCommand cmd = new SqlCommand("SELECT MAX(SORTORDER) FROM Your_Admin_Table");
      conn.Open();
      SqlDataAdapter sqad = new SqlDataAdapter(cmd);
      sqad.Fill(dt);
      if (dt.Rows.Count > 0)
      {
          if (dt.Rows[0][0].ToString() != "")
          max = Convert.ToInt32(dt.Rows[0][0]);
      }
    return max;
    }


protected void dgrdAdmin_ItemCommand(object sender, DataGridCommandEventArgs e)
{
   if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
     {
       if (e.CommandName.Equals("Up"))
       {
          int SortOrder = 0;
          SqlConnection conn = new SqlConnection("Your_Connection_String");
           if (e.Item.Cells[10].Text != "")
            {
              SortOrder = Convert.ToInt32(e.Item.Cells[10].Text);
              if (SortOrder == 0)
                {
                  DataTable dt = new DataTable();
                  SqlCommand cmd = new SqlCommand("SELECT id FROM Your_ADMIN_Table");
                  conn.Open();
                  SqlDataAdapter sqad = new SqlDataAdapter(cmd);
                  sqad.Fill(dt);
                  if (dt.Rows.Count > 0)
                  {
                    int count = 0;
                    foreach (DataRow dr in dt.Rows)
                    {
                     count++;
                     SqlCommand cmdUp = new SqlCommand("UPDATE Your_ADMIN_Table SET 
                                        SortOrder='" + count + "' WHERE id='" + dr["id"].ToString() + "'");
                     cmdUp.ExecuteNonQuery();
                    }
                  }
                   // bind your grid
                   return;
               }
            }
           if (SortOrder == GetMaxSortOrder() || SortOrder > GetMaxSortOrder())
           return;
           SqlCommand cmd2 = new SqlCommand("UPDATE Your_ADMIN_Table SET 
              SortOrder='" + SortOrder + "' WHERE SortOrder='" + (SortOrder + 1) + "'");
           cmd2.ExecuteNonQuery();
           SqlCommand cmd3 = new SqlCommand("UPDATE Your_ADMIN_Table SET 
           SortOrder='" + (SortOrder + 1) + "' WHERE id='" + e.Item.Cells[1].Text + "' AND 
                                          SortOrder='" + SortOrder + "'");
           cmd3.ExecuteNonQuery();
           dgrdAdmin.DataSource = // Bind data in datagrid
           dgrdAdmin.DataBind();
         }
        if (e.CommandName.Equals("Down"))
        {
          SqlConnection conn = new SqlConnection("Your_Connection_String");
          int SortOrder = 0;
          if (e.Item.Cells[10].Text != "")
           {
             SortOrder = Convert.ToInt32(e.Item.Cells[10].Text);
             if (SortOrder == 0)
             {
               DataTable dt = new DataTable();
               SqlCommand cmd = new SqlCommand("SELECT id FROM Your_ADMIN_Table");
               conn.Open();
               SqlDataAdapter sqad = new SqlDataAdapter(cmd);
               if (dt.Rows.Count > 0)
               {
                 int count = 0;
                 foreach (DataRow dr in dt.Rows)
                 {
                   count++;
                   SqlCommand cmdDown = new SqlCommand("UPDATE Your_ADMIN_Table SET 
                                           SortOrder='" + count + "' WHERE id='" + dr["id"].ToString() + "'");
                   cmdDown.ExecuteNonQuery();
                  }
               }
              // bind your grid
                 return;
           }
       }
        if (SortOrder == 0)
        return;
       SqlCommand cmd1 = new SqlCommand("UPDATE Your_ADMIN_Table SET SortOrder=
                                     " + SortOrder + "' WHERE SortOrder='" + (SortOrder - 1) + "'");
       cmd1.ExecuteNonQuery();
       SqlCommand cmd2 = new SqlCommand("UPDATE Your_ADMIN_Table SET SortOrder=
                                       '" + (SortOrder - 1) + "' WHERE id='" + e.Item.Cells[1].Text + "' 
                                        AND SortOrder='" + SortOrder + "'");
       cmd2.ExecuteNonQuery();
       dgrdAdmin.DataSource = // Bind data in datagrid
       dgrdAdmin.DataBind();
       }
    }
}

Now you can easily move your datagrid row up and down with sorting.

Monday, 9 July 2012

Resize Images Using JQuery


Write a JQuery function for Image Resizing:


$(document).ready(function(){     $('imgresize').each(function(){         var maxWidth = 500;         var ratio = 0;         var img = $(this);         if(img.width() > maxWidth){             ratio = img.height() / img.width();             img.attr('width', maxWidth);             img.attr('height', (maxWidth*ratio));           }     }); });

This script simply resize your image.

Sunday, 1 July 2012

Upload and Crop Image with JQuery in ASP.Net

Image Cropping is the most important and required part in social media projects. There is a JQuery Plugin which allows to crop image using Jquery without any trouble.

Jcrop is the quick and easy way to add image cropping functionality to your web application. It combines the ease-of-use of a typical jQuery plugin with a powerful cross-platform DHTML cropping engine that is faithful to familiar desktop graphics applications.



How to use it.

 First download the plugin and include the references of the required libraries in .aspx page.


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script src="Scripts/jquery.Jcrop.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.Jcrop.js" type="text/javascript"></script>
Add Jquery code for cropping the image

<script type="text/javascript">
    jQuery(document).ready(function () {
        jQuery('[id$=imgCrop]').Jcrop({
            onSelect: storeCoords
        });
    });
    function storeCoords(c) {
        jQuery('[id$=X]').val(c.x);
        jQuery('[id$=Y]').val(c.y);
        jQuery('[id$=Z]').val(c.z);
        jQuery('[id$=A]').val(c.a);
    };
</script>


Add code in your aspx page


<div>
        <asp:Panel ID="pnlCrop" runat="server" Visible="false">
            <asp:Image ID="imgCrop" runat="server" />
            <asp:HiddenField ID="X" runat="server" />
            <asp:HiddenField ID="Y" runat="server" />
            <asp:HiddenField ID="Z" runat="server" />
            <asp:HiddenField ID="A" runat="server" />
        </asp:Panel>
        <asp:Panel ID="pnlCropped" runat="server" Visible="false">
       <asp:Image ID="imgCropped" runat="server" />
        </asp:Panel>
 <asp:Button ID="btnCrop" runat="server" Text="Crop" OnClick="btnCrop_Click" />
</div>


Now, add code in your aspx.cs page


protected void btnCrop_Click(object sender, EventArgs e)
{
 string ImageName = Session["UploadImage"].ToString();
  int z = Convert.ToInt32(Z.Value);
  int a = Convert.ToInt32(A.Value);
  int x = Convert.ToInt32(X.Value);
  int y = Convert.ToInt32(Y.Value);
  byte[] CropImage = Crop(path + ImageName, z, a, x, y);
  using (MemoryStream ms = new MemoryStream(CropImage, 0, CropImage.Length))
  {
     ms.Write(CropImage, 0, CropImage.Length);
     using (SD.Image CroppedImage = SD.Image.FromStream(ms, true))
       {
          string SaveTo = path + "crop" + ImageName;
          CroppedImage.Save(SaveTo, CroppedImage.RawFormat);
           pnlCrop.Visible = false;
           pnlCropped.Visible = true;
           imgCropped.ImageUrl = "images/crop" + ImageName;
       }
    }
 }

static byte[] Crop(string Img, int Width, int Height, int X, int Y)
{
  try
   {
    using (SD.Image OriginalImage = SD.Image.FromFile(Img))
    {
     using (SD.Bitmap bmp = new SD.Bitmap(Width, Height))
      {
      bmp.SetResolution(OriginalImage.HorizontalResolution, OriginalImage.VerticalResolution);
       using (SD.Graphics Graphic = SD.Graphics.FromImage(bmp))
       {
         Graphic.SmoothingMode = SmoothingMode.AntiAlias;
         Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
         Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
         Graphic.DrawImage(OriginalImage, new SD.Rectangle(0, 0, Width, Height), X, Y, Width, 

         MemoryStream ms = new MemoryStream();
         bmp.Save(ms, OriginalImage.RawFormat);
         return ms.GetBuffer();
       }
     }
   }
}
    catch (Exception Ex)
    {
      throw (Ex);
    } 

 }
Download Full Solutions:  CroppingSolutions

 It is really simple. Now you can easily crop the image. Please let me know, if you have any query.