All posts by Thiyagu

How to get the top and left positon of clicked td/div

How to  get the  top and left positon of clicked td/div

Jquery

$(document).on(“click”, “#tbUserDetails”, function()
{
var getclickTop = $(this).offset().top;
var getclickLeft = $(this).offset().left;
}

Explanation:
.on method is used for dynamically created table using jquery (at runtime)

HTML

<table>
<tr>
<td id=’tbUserDetails’></td>
</tr>
</table>

MVC4 Razor : How to get the value from view to controller

MVC4 Razor : How to get the value from view to controller ?

Explanation :

Here i explain how to get the value from html razor control (view) to controller

Code in View:

@using (Html.BeginForm())
{
@Html.TextBox(“txtCustomerName”)
<input type=”submit” value=”Send” />
}

Code in Controller

[AcceptVerbs(HttpVerbs.Post)] public ActionResult Index1(FormCollection collection)
{
string customerName = collection[“txtCustomerName”].ToString();
return null;
}

Output :

After press send button the value will be catch in controller (as like below)

Note :
As above , we can get value of other control from the view to controller
1. [AcceptVerbs(HttpVerbs.Post)] , will do action when we use Html.BeginForm()
2. FormCollection : It provides to access  the values that were just posted to your page.

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;
}