Category Archives: .Net

Lazy Loading vs Eager Loading

 

What is  Lazy Loding?

As name implies, if we need to load parent data , it will load parent data without loading the related child  data.This is know as lazy loading

Otherwise, data is loaded only on demand (if required)

When to use ?

If we do not want to load the related entity at the same time as when the main entity is loaded/fetched, in this scenario we can use Lazy Loading.

Example :

Here we will see an example for lazy loading with the entity. Let we discuss with two tables, Here we having one table named as  customers which contain customerid,cusotmerName,CusomerMobileNo,customerdetailId ( it refer the primary key of Customerdetails table). then table Customerdetails which contain customerdetailId,customerAddress,Customercity….

var customerList = context.customers.Take(100);

foreach (var Customer in customerList)
{
// Login here
foreach (var CustomerDetail in customerList.Customerdetails)
{
// Login here
}
}

First line of code shows its is working as lazy, because it load only customers table without customerdetails table ( ie., without relations data).

Note :

From the above code, SQL hit will be high ( it will take 100 hits for fetching the customerdetails). Because every time the related data fetch will be happen inside the loop.


What is Eager Loading?

It Load all the related data with the loading object.

When to use ?

If we  want to load the related entity at the same time as when the main entity is loaded/fetched, in this scenario we can use Eager Loading.

Let we see the example for Eager Loading with the entity

var customerList = context.customers.Include(“Customerdetails”).Take(100);

foreach (var Customer in customerList)
{
// Login here
foreach (var CustomerDetail in customerList.Customerdetails)
{
// Login here
}
}

First line show it will fetch all the related entity for the customers table

Note :

Here SQL hit will be only one time , because it will fetch related entity using include keyword (first itself).

REST Services (Representational state transfer)

What is REST Services :

Definition : 1

  • The REST stands for Representational State Transfer.
  • REST is a set of principles that define how Web standards, such as HTTP and URLs, are supposed to be used.

Definition : 2

In simple, REST is a architectural style construct based on the principle using the Web fundamentals.

From msdn,

  • An architectural style, sometimes called an architectural pattern, is a set of principles.
  • An architectural style improves partitioning and promotes design reuse by providing solutions to frequently recurring problems.
  • You can think of architecture styles and patterns as sets of principles that shape an application.

Let we see Fundamentals/principles details

Resource :

In REST,  every thing will be treat as resource, for example

www.aadharsh.com/image/birthday (image resource)
www.aadharsh.com/user/GKA (Dynamically pulled resource)
www.aadharsh.com/audio/audfile (audio resource)

from above, first URL shows the image resource as the output… same thing for all other URL with different identifiers. Here image/audio/video/static page… every thing are treated as resource instead of thinking physical file/data.


Unique identifier

Every resources identifies by an URL, in earlier for identify all the resource by URL.
For example to identify the user detail we use like below

www.aadharsh.com/GetUserDetails.aspx

Now in REST, added one more constrain. That is every resources  must represent by an unique URL, For example

www.aadharsh.com/GetUserDetails/Kavi
www.aadharsh.com/GetUserDetails/Gnanamurugan

Here if we want to get the user detail for the kavi then we can get GetUserDetails/Kavi in same way for other users ( we want to append username at the end) not as before like this

www.aadharsh.com/GetUserDetails?Name=Kavi
Instead of using Generic page, REST point the unique identifiers to identify the resource

Uniform Interface :

Use simple and uniform interface, for example if client want to Add/Insert/Select/Delete user detail, we use like below method name to perform the above operation

  •   AddUserDetails (it combine with PUT)
  •   InsertUserDetails (it combine with PUT)
  •   SelectUserDetails (it combine with GET)
  •   DeleteUserDetails (it combine with DELETE)

When we watch closely the method name, it seems to be inconsistent and difficult to remember,so REST says to uses simple and uniform interface. This can be obtain by the uniform methods of HTTP protocol and combine the name with the resource operation.Let we see the HTTP protocol methods

  •  GET : Get the Resource
  •  PUT : Create/Update the resource
  •  DELETE : Delete the resource
  •  POST : submit the data to the resource

Communication should be representation :

Representation is nothing but request and response between the client and the server.

Stateless :

Each request from client to server must contain all the information necessary to understand the request, and cannot take advantage of any stored context on the server. In simple, HTTP have nothing to indicates when a session starts or ends.

create user control and how to use from toolbar

Let we saw how to create user control and how to use from toolbar

Step 1: Right Click and Add —> NewItem–>Usercontrol.cs

Step 2: Click “Ok” , And Place the Collection of controls to make a group

Step 3: Make compile after every changes in UserControl, After successful Build, the Usercontrol created in Tool box.

Step 4 : Now drag and drop the User Control to the .aspx

Create Captcha using DLL

Here we discuss about how to create Captcha using DLL

.aspx File

<%@ Register Assembly=”MSCaptcha” Namespace=”MSCaptcha” TagPrefix=”cc1″ %>

<form id=”form1″ runat=”server”>
<div>
<cc1:CaptchaControl ID=”Captcha1″ runat=”server”
CaptchaBackgroundNoise=”Low” CaptchaLength=”5″
CaptchaHeight=”60″ CaptchaWidth=”200″
CaptchaLineNoise=”None” CaptchaMinTimeout=”5″
CaptchaMaxTimeout=”240″ FontColor = “#529E00″ />
</div>
<asp:TextBox ID=”txtCaptcha” runat=”server”></asp:TextBox>
<br />
<asp:Button ID=”btnVerify” runat=”server” Text=”Verify” OnClick=”btnVerify_Click” />
<asp:RequiredFieldValidator ID=”RequiredFieldValidator1″ runat=”server” ErrorMessage=”*Required” ControlToValidate = “txtCaptcha”></asp:RequiredFieldValidator>
<br />
<br />
<asp:Label ID=”lblMessage” runat=”server” Font-Names = “Arial” Text=””></asp:Label>
</form>

CodeBehind File

protected void btnVerify_Click(object sender, EventArgs e)
{
Captcha1.ValidateCaptcha(txtCaptcha.Text.Trim());
if (Captcha1.UserValidated)
{
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = “Valid”;
}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = “InValid”;
}
}

Note : Download .dll here

Code shows how to zip while uploading the file.

This code shows how to zip while uploading the file.

Need to include System.IO.Compression namespace to zip the upload files. In click event write the below code.

using System.IO.Compression;
using System.IO;

protected void btnUpload_Click(object sender, EventArgs e)
{
string strName = Path.GetFileName( FileUpload1.PostedFile.FileName);
Stream myStream = FileUpload1.PostedFile.InputStream;
byte[] myBuffer = new byte[myStream.Length + 1];
myStream.Read(myBuffer, 0, myBuffer.Length);
myStream.Close();
FileStream myCompressedFile = default(FileStream);
myCompressedFile = File.Create(Server.MapPath(Path.ChangeExtension(strName, “gz”)));
GZipStream myStreamZip = new GZipStream(myCompressedFile, CompressionMode.Compress);
myStreamZip.Write(myBuffer, 0, myBuffer.Length);
myStreamZip.Close();
}

Here i am set size as +1 of upladed file size.

Custom Paging with Numbers

Custom Paging with Numbers
===========================

.aspx
======

<div>
PageSize:
<asp:DropDownList ID=”ddlPageSize” runat=”server” AutoPostBack=”true” OnSelectedIndexChanged=”PageSize_Changed”>
<asp:ListItem Text=”10″ Value=”10″ />
<asp:ListItem Text=”25″ Value=”25″ />
<asp:ListItem Text=”50″ Value=”50″ />
<asp:ListItem Text=”75″ Value=”75″ />
</asp:DropDownList>
<hr />
<asp:GridView ID=”gvCustomerDetails” runat=”server”>
</asp:GridView>
<br />
<asp:Button ID=”btnprev” Text=”<<” OnClick=”MovetoPrev” runat=”server” />
<asp:Repeater ID=”rptPage” runat=”server”>
<ItemTemplate>
<asp:LinkButton ID=”lnkPage” runat=”server” Text='<%#Eval(“Text”)%>’ CommandArgument='<%# Eval(“Value”) %>’
OnClick=”GettingPageIndex”></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID=”btnnext” Text=”>>” OnClick=”MovetoNext” runat=”server” />
</div>

.Cs
====

#region Using Namespaces
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using CustomerDetail;
using System.Web.UI.WebControls;
#endregion

public partial class gridviewpaging2 : System.Web.UI.Page
{
#region Private Constants
private const string SQL_CONNECTION = “Data Source=DBSRV;Initial Catalog=Shopping;User ID=sa;Password=sa”;
private const string SQL_SPNAME = “[sproc_GetCustomersDetails]”;
#endregion

#region Public Variables
public static Int64 page_Number = 1;
public int record_Count;
public static int PAGE_SIZE = 10;
#endregion

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadCustomerDetails();
LoadPageSize();
}
}

#region Load Customer Records
private void LoadCustomerDetails()
{
var CustomerDetails = new List<CustomerDetails>();
#region Fetching and Loading the Customer Details
try
{
using (var sqlConn = new SqlConnection(SQL_CONNECTION))
{
using (var sqlCmd = new SqlCommand(SQL_SPNAME, sqlConn))
{
sqlCmd.Parameters.AddWithValue(“@PageNo”, page_Number);
sqlCmd.Parameters.AddWithValue(“@PageSize”,PAGE_SIZE);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlConn.Open();
using (var sqlDataReader = sqlCmd.ExecuteReader())
{
while (sqlDataReader.Read())
{
CustomerDetails.Add(new CustomerDetails(Convert.ToInt32(sqlDataReader[“ID”]), Convert.ToString(sqlDataReader[“CustomerName”]),
Convert.ToString(sqlDataReader[“EmailID”]), Convert.ToString(sqlDataReader[“PhoneNo”])
));
}
sqlDataReader.NextResult();
sqlDataReader.Read();
record_Count = Convert.ToInt32(sqlDataReader[“TotalRec”]);
lbl_TNOPages.Text = ”  ” + Convert.ToInt32(sqlDataReader[“TotalPages”]); ;
}
}
gvCustomerDetails.DataSource = CustomerDetails.AsReadOnly();
gvCustomerDetails.DataBind();
lbl_TPages.Text = ”  ” + (record_Count).ToString();
lbl_CPage.Text = ”  ” + (page_Number).ToString();
lbl_RRecords.Text = ”  ” + ((record_Count) – (page_Number * PAGE_SIZE)).ToString();
EnableAndDisableButton();
}
}
catch (Exception ex)
{
throw ex;
}
#endregion
}
#endregion

#region Load PageSize in DropDown
public void LoadPageSize()
{
ddl_PageSize.Items.Add(“10”);
ddl_PageSize.Items.Add(“20”);
ddl_PageSize.Items.Add(“30”);
ddl_PageSize.Items.Add(“40”);
}
#endregion

#region Enable and Disable the Button
public void EnableAndDisableButton()
{
if (page_Number == 1)
{
btn_Previous.Enabled = false;
if (Int32.Parse(lbl_TPages.Text) > 0)
btn_Next.Enabled = true;
else
btn_Next.Enabled = false;
}
else
{
btn_Previous.Enabled = true;
if (page_Number == Int32.Parse(lbl_TPages.Text))
btn_Next.Enabled = false;
else
btn_Next.Enabled = true;
}
}
#endregion

#region Next and Previous Button Click
protected void Btn_Next_Click(object sender, EventArgs e)
{
try
{
Button btn = (Button)sender;
if (btn.Text == “Previous”)
page_Number–;
else
page_Number++;
LoadCustomerDetails();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion

#region DropDown SelectedIndex Change
protected void ddl_PageSize_SelectedIndexChanged(object sender, EventArgs e)
{
PAGE_SIZE = Convert.ToInt32(ddl_PageSize.SelectedItem.Text);
LoadCustomerDetails();
}
#endregion
}

CustomerDetails.cs
==================

#region Using Namespaces
using System;
using System.Data;
using System.Configuration;
using System.Web;
#endregion

namespace CustomerDetail
{
public class ConnectionDetails
{
#region Public Method
public string ConnectionInfo
{
get
{
return ConfigurationSettings.AppSettings[“myConnectionString”].ToString();
}
}
#endregion
}

public class CustomerDetails
{
#region Private Members
private readonly int c_id;
private readonly string c_email;
private readonly string c_phoneNumber;
private readonly string c_name;
#endregion

#region Public Members
public int ID
{
get { return c_id; }
}
public string Name
{
get { return c_name; }
}
public string Email
{
get { return c_email; }
}
public string PhoneNumber
{
get { return c_phoneNumber; }
}
#endregion

#region Public Const.
public CustomerDetails(int pID, string pName, string pEmail, string pPhoneNumber)
{
c_id = pID;
c_email = pEmail;
c_name = pName;
c_phoneNumber = pPhoneNumber;
}
#endregion

}

}

Stored Procedure
================

ALTER PROCEDURE [dbo].[sproc_GetCustomersDetails]
@PageNo        INT,
@PageSize    INT
AS
BEGIN
SET NOCOUNT ON;

DECLARE @StartIndex INT, @EndIndex INT, @TotalRec INT, @TotalPages INT;

SELECT @TotalRec = COUNT(1) FROM [tCustomer] WITH (NOLOCK)
WHERE [CustomerName] IS NOT NULL;

IF @PageNo <= 0 SET @PageNo = 1;
IF @PageSize <= 0 SET @PageSize = 1;
IF @PageSize > @TotalRec SET @PageSize = @TotalRec;

SET @TotalPages = CEILING(@TotalRec * 1.0 / @PageSize);
IF (@PageNo > @TotalPages) SET @PageNo = @TotalPages;

SET @StartIndex = (@PageNo – 1) * @PageSize + 1;
SET @EndIndex =  @StartIndex + @PageSize – 1;

IF @StartIndex > @TotalRec SET @StartIndex = @TotalRec;
IF @EndIndex > @TotalRec SET @EndIndex = @TotalRec;

WITH [Customer] AS
(
SELECT ROW_NUMBER() OVER (ORDER BY [CustomerName] ASC) AS [RowNo], [ID]
FROM [tCustomer] WITH (NOLOCK)
WHERE [CustomerName] IS NOT NULL
)
SELECT
[I].[ID],
[I].[CustomerName],
[I].[EmailID],
[I].[PhoneNo]
FROM [tCustomer] AS [I] WITH (NOLOCK)
INNER JOIN [Customer] AS [II] WITH (NOLOCK) ON [II].[RowNo] BETWEEN @StartIndex AND @EndIndex AND [II].[ID] = [I].[ID]
ORDER BY [II].[RowNo] ASC;

SELECT @TotalPages AS [TotalPages], @TotalRec AS [TotalRec];
END;

set get

Let us see the SET , GET with simple explanation

GET
The body of the get accessor is similar to that of a method. It must return a value of the property type.

SET
The set accessor is similar to a method whose return type is void. It uses an implicit parameter called value, whose type is the type of the property

class PDetails
{
private string name;  // the name field
public string Name    // the Name property
{
get { return name; }
set{ name = value; }
}
}

From Outer Class
PDetails obj = new PDetails();
obj .Name = “Joe”;  // the set accessor is invoked here

System.Console.Write(obj .Name);  // the get accessor is invoked here

The data source does not support server-side data paging.

Error :  The data source does not support server-side data paging.

Description:  Error message occure while binding the result set to the Gridview using LINQ Query as like below

gvDetails.DataSource = details

Reason : We cant use an IQueryable object to data bind to a GridView and still use Paging and Sorting.

we must return a List to the GridView using the ToList() method.
Solution:  In that scenario we want to add .ToList() as like below

                         gvDetails.DataSource = details.ToList();

Passing the value from code behind to jquery ( using JSON )

 Passing the value from code behind to jquery ( using JSON )

.ASPX File

<asp:Button ID=”btnSubmit” runat=”server” Text=”Submit” OnClick=”btnSubmit_Click” OnClientClick=”return CheckEmpID();” />

Script File

function CheckEmpID()
{
var EmrID = document.getElementById(“txtEmpId”).value;
if (EmpID == “Enter New EMPID”) return false;
$.ajax({
type: “post”,
url: “EmpWelcomeScreen.aspx/EmpDetails”,
contentType: “application/json; charset=utf-8”,
data: ‘{“EmpId”:”‘ + EmpID + ‘”}’,
dataType: “json”,
success: function (msg) {
if (msg.d[0] == “0”)
document.location = msg.d[1];
else if (msg.d[0] == “1”)
document.getElementById(“lblEmpId”).style.display = “”;
else if (msg.d[0] == “2”)
document.getElementById(“lblIssue”).value = d[1];
},
error: function (data) { }
} );

return false;
}

Code-Behind

[System.Web.Services.WebMethod()]
public static string[] EmpDetails(string EmpId)
{
string[] ReturnString = new string[2];
string EmpName = txtEmpName.Text.ToString()
try
{
if (EmpId.Length > 0)
{
if (EmpName != null)
{
ReturnString[0]=”0″;
ReturnString[1] = “EmpInfoSummary.aspx?Empid=” + EmpId;
}
else
{
ReturnString[0] = “1”;
ReturnString[1] = “Plaese Check The EMPID “;
}
}
}
catch (Exception ex)
{

}
return ReturnString;
}

How to use javascript variables in C# and vise versa

Passing values from server to client side (code-behind to .aspx) for some manipulation using javascript and passing values from script to code behind are one of the most recurring tasks while developing the application. This scenario can be achieved in many ways. In this post we are going to see some techniques to achieve this.

1. Passing values from C# Code Behind to JavaScript.

You can use <%=variable%> to get value from aspx.cs. Variable must be public in aspx.cs file. For example, you can use: var date=”<%=DateTime.Now%>”; to get the server time.

Code behind :

public string value;

protected void Page_Load(object sender, EventArgs e)
{
value = “From Code-Behind”;
}

ASPX Code : Now, we going to display this variable Variable Cadebehindvalue into html page using javascript:

<script type=”text/javascript”>
$(document).ready(function() {
var Cadebehindvalue = ‘<%=value %>’;
var imagePath = <%=strImagePath %>;
alert(Cadebehindvalue);
});
</script>
</head>
<body>
<form id=”form1″ runat=”server”></form>
</body>

2. Passing parameter from C# Code Behind to javascript.

Using RegisterStartupScript we can write a JavaScript function in code behind and call it from code-behind or from HTML. Look at the code below for reference.

Syntax: RegisterStartupScript(Control, Type, String, String, Boolean)

Explanation :

Control : The control that is registering the client script block.
Type : The type of the client script block. This parameter is usually specified by using the typeof operator (C#) or the GetType operator (Visual Basic) to retrieve the type of the control that is registering the script.
Boolean : true to enclose the script block with <script> and </script> tags; otherwise, false.

CodeBehind :

String EmployeeID =”Aadharsh”;

ScriptManager.RegisterStartupScript(this, this.GetType(), “TestKey”, “TableTest(‘” + this.EmployeeID + “‘);”, true);

Java Script in aspx :

function TableTest(EMPID)
{
var width = 600;
var height = 330;
var left = 500;
var top = 100;
window.open(‘welcome.aspx?EMPID=’ + EMPID,’_blank’,’toolbar=no,menubar=no,resizable=no,scrollbars=auto,status=no,location=no,
width=’ + width + ‘,height=’ + height + ‘,left=’ + left + ‘,top=’ + top);
}

3. Passing values from JavaScript to C# Code Behind.

ASPX: Using HiddenField

<script type=”text/javascript”>
$(document).ready(function() {
alert($(“#hdfValue”).val());
});
</script>

inside the body tag

<form id=”form1″ runat=”server”>
<div>
<asp:HiddenField ID=”hdfValue” runat=”server” />
</div>
</form>

Codebehind

protected void Page_Load(object sender, EventArgs e)
{
hdfValue.Value = “Chnaged Value in codebehind”;
}