Search This Blog

Monday 31 December 2012

How to Create and use Table-Valued Parameter in C# and T-SQL/ How to pass table to stored procedures in SQL


What is Table – Valued Parameter in SQL Server 2008?
Table-valued parameters provide an easy way to marshal multiple rows of data from a client application to SQL Server without requiring multiple round trips or special server-side logic for processing the data. You can use table-valued parameters to encapsulate rows of data in a client application and send the data to the server in a single parameterized command. The incoming data rows are stored in a table variable that can then be operated on by using Transact-SQL.
What we are going to do with Table – Valued Parameter?
We are going to demonstrate a very simple example for using Table – Valued parameter. In this sample project we will insert bulk amount of data into the table by passing a bulk data using datatable in C# to SQL stored procedure.
Create a Table for insert data using Table – Valued Parameter 
Here we are having a table named Officer and having three fields ID,Name and Salary. We are going to fill the table with bulk data.
CREATE TABLE Officer(
ID INT PRIMARY KEY IDENTITY(1,1),
NAME VARCHAR(50),
SALARY DECIMAL(18, 0))
Stored Procedure for insert data by accepting Table Valued Parameter
Now we are going to create a Stored Procedure that accepting a table type as parameter and insert values in this type into the table.
CREATE PROCEDURE InsertOfficerDetails
(
@OfficerData OfficerDetails readonly
)
AS 
INSERT INTO Officer (Name, Salary)
SELECT Name, Salary
FROM @OfficerData;
C# code to call Stored Procedure to insert data in to the table using Table – Valued Parameter
We are creating a simple ASPX page with a single button. When we click this button we are calling above stored procedure by creating and passing some amount of sample data to the stored procedure as Table – Valued Parameter.
ASPX Page 
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CallSP.aspx.cs" 
Inherits="ExperimentLab.CallSP" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
 <title></title>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 <asp:Button ID="btnCallSP" runat="server" Text="Call SP" 
 OnClick="btnCallSP_Click" />
 </div>
 </form>
</body>
</html>
Code Behind
protected void btnCallSP_Click(object sender, EventArgs e)
 {
 try
 {
 DataTable dt = new DataTable();
 DataColumn dtCol = new DataColumn();
 dtCol.ColumnName = "ID";
 dt.Columns.Add(dtCol);
dtCol = new DataColumn();
 dtCol.ColumnName = "Name";
 dt.Columns.Add(dtCol);
dtCol = new DataColumn();
 dtCol.ColumnName = "Salary";
 dt.Columns.Add(dtCol);
for (int i = 0; i < 10; i++)
 {
 DataRow dr = dt.NewRow();
 dr["Name"] = "Name " + i;
 dr["Salary"] = 1000 + i;
 dr["ID"] = i;
 dt.Rows.Add(dr);
 }
 
 string connStr = ConfigurationManager.
 AppSettings["LocalSqlServer"].ToString();
 SqlConnection con = new SqlConnection(connStr);
using (var conn = new SqlConnection(connStr))
 using (var cmd = conn.CreateCommand())
 {
 cmd.Connection = con;
 con.Open();
 cmd.CommandType = CommandType.StoredProcedure;
 cmd.CommandText = "dbo.InsertOfficerDetails";
 SqlParameter param = cmd.Parameters.AddWithValue("@OfficerData", dt);
 cmd.ExecuteNonQuery();
 }
 }
 catch (Exception a)
 {
 Response.Write(a.Message);
 }
 }
Web.Config
<appSettings>
 <add key="LocalSqlServer" 
value="Database=testDB;Server=Servername\SQLEXPRESS;User Id=userid;Password=password"/>
</appSettings>
Hence we discussed about how to create and use Table valued parameters, how to create a store procedure with table type as parameter, how to pass table to stored procedure in C#/Asp.Net,  how to insert multiple rows of data to a table with table valued parameter in SQL, how to insert bulk data to SQL table using Table Valued Parameter in SQL Server 2008 etc.. 

Tuesday 25 December 2012

How to UNPIVOT table in SQL Server / UNPIVOT table example in SQL Server


What is PIVOT and UNPIVOT operator in SQL Server 
We can use the PIVOT and UNPIVOT relational operators to change a table-valued expression into another table. PIVOT rotates a table-valued expression by turning the unique values from one column in the expression into multiple columns in the output, and performs aggregations where they are required on any remaining column values that are wanted in the final output.
Before UNPIVOT
UNPIVOT sample in SQL Server
Before UNPIVOT table
After UNPIVOT
UNPIVOT sample in SQL Server
UNPIVOT sample in SQL Server
A simple UNPIVOT sample in SQL Server
Here we are going to demonstrate a very simple UNPIVOT sample without any complexity. We are having a table named EmploymentHistory and its containing employee name with previous company name that particular employee worked.
Table Structure For showing simple UNPIVOT sample
CREATE TABLE EmploymentHistory 
(Id INT, 
Employee VARCHAR(500), 
Company1 VARCHAR(500), 
Company2 VARCHAR(500), 
Company3 VARCHAR(500)
) 
GO

-- Load Sample data
INSERT INTO EmploymentHistory SELECT 
1, 'John', 'Tata Motors', 'Ashok Leyland', 'Suzuki'
UNION ALL SELECT 
2, 'Kate', 'Airtel', 'Vodafone', 'Tata Docomo'
UNION ALL SELECT 
3, 'Sam', 'Hercules', 'Hero', 'Atlas'
GO
In order to UNPIVOT above table we can use below mentioned script. The result should be as Employee with each company as a single row.
SELECT Id, 
ROW_NUMBER()OVER(Order By ID) as NewID,
Employee, 
Company
FROM 
( 
SELECT Id, Employee, Company1, Company2, Company3
FROM EmploymentHistory 
) Main
UNPIVOT
( 
Company FOR Companies IN (Company1, Company2, Company3) 
) Sub
UNPIVOT Table with multiple columns
Now we are going to UNPIVOT table with multiple columns. Suppose we are having a table with Employee name, list of company names that particular employee worked and corresponding cities also. The table structure like below.
CREATE TABLE EmploymentHistoryWithCity 
(Id INT, 
Employee VARCHAR(500), 
Company1 VARCHAR(500), 
Company2 VARCHAR(500), 
Company3 VARCHAR(500),
City1 VARCHAR(500), 
City2 VARCHAR(500), 
City3 VARCHAR(500) 
) 
GO
-- Load Sample data 
INSERT INTO EmploymentHistoryWithCity SELECT
1, 'John', 'Tata Motors', 'Ashok Leyland', 'Suzuki', 'Mumbai', 'Kolkata', 'Delhi'
UNION ALL SELECT 
2, 'Kate', 'Airtel', 'Vodafone', 'Tata Docomo', 'Chennai', 'Kolkata', 'Banglore'
UNION ALL SELECT 
3, 'Sam', 'Hercules', 'Hero', 'Atlas', 'Delhi', 'Mumbai', 'Banglore'
GO
UNPIVOT sample in SQL Server
Before UNPIVOT multiple columns table
 

In order to UNPIVOT above table we can use below mentioned script. The result should be as Employee name with Company1 and City1 as a first row, Employee Name with Company2 and City2 as second row and so on
SELECT Id, 
ROW_NUMBER()OVER(Order By ID) as NewID,
Employee, 
Company, 
City 
FROM 
( 
SELECT Id, Employee, Company1, Company2, Company3, City1, City2, City3
FROM EmploymentHistoryWithCity 
) Main
UNPIVOT 
( 
Company FOR companies IN (Company1, Company2, Company3) 
) Sup
UNPIVOT 
( 
City For Cities IN (City1, City2, City3 ) 
) Ct
WHERE RIGHT(companies,1) = RIGHT(Cities,1)
UNPIVOT sample in SQL Server
After UNPIVOT multiple columns table 

Tuesday 18 December 2012

How to PIVOT table in SQL Server / PIVOT table example in SQL Server


What is PIVOT and UNPIVOT operator in SQL Server 
We can use the PIVOT and UNPIVOT relational operators to change a table-valued expression into another table. PIVOT rotates a table-valued expression by turning the unique values from one column in the expression into multiple columns in the output, and performs aggregations where they are required on any remaining column values that are wanted in the final output.
Before PIVOT
Before PIVOT table
After PIVOT
After PIVOT table
A simple PIVOT sample in SQL Server
Here we are going to demonstrate a very simple PIVOT sample without any complexity. We are having a table named Accounts and it containing customer name and their deposit with denominations.
Table Structure For showing simple PIVOT sample
CREATE TABLE Accounts(Customer VARCHAR(25), Denomination VARCHAR(20), QTY INT)
GO
-- Inserting Data into Table
INSERT INTO Accounts(Customer, Denomination, QTY)
VALUES('John','10 $',2)
INSERT INTO Accounts(Customer, Denomination, QTY)
VALUES('John','50 $',6)
INSERT INTO Accounts(Customer, Denomination, QTY)
VALUES('John','100 $',1)
INSERT INTO Accounts(Customer, Denomination, QTY)
VALUES('Ram','10 $',4)
INSERT INTO Accounts(Customer, Denomination, QTY)
VALUES('Ram','50 $',3)
INSERT INTO Accounts(Customer, Denomination, QTY)
VALUES('Ram','100 $',11)
INSERT INTO Accounts(Customer, Denomination, QTY)
VALUES('KATE','10 $',20)
INSERT INTO Accounts(Customer, Denomination, QTY)
VALUES('KATE','50 $',12)
INSERT INTO Accounts(Customer, Denomination, QTY)
VALUES('KATE','100 $',2)
INSERT INTO Accounts(Customer, Denomination, QTY)
VALUES('Eby','10 $',0)
INSERT INTO Accounts(Customer, Denomination, QTY)
VALUES('Eby','50 $',5)
INSERT INTO Accounts(Customer, Denomination, QTY)
VALUES('Eby','100 $',5)
In order to PIVOT above mentioned table we can use below script. The result should be as Customer name with all denomination will be coming as columns with qty as values for each column.
SELECT * FROM Accounts
PIVOT (SUM(QTY) For Denomination IN ([10 $],[50 $],[100 $])) AS Total
Dynamic Query to PIVOT table for dynamic columns 
In the above example we are using a simple structured table and then PIVOT with denomination values. This can be achieved only when we are having denomination values as static. Suppose this denomination values are dynamic (Each country having different denomination like $,EUR, IND etc..), we need to create a dynamic query to PIVOT above table.
Suppose we are having different table for getting Denomination values and we are going to take Denomination values from this table at run time as dynamic.
CREATE TABLE Denomination(Value VARCHAR(25))
GO
INSERT INTO Denomination(Value)
VALUES('10 $')
INSERT INTO Denomination(Value)
VALUES('50 $')
INSERT INTO Denomination(Value)
VALUES('100 $')
First of all, we need to get dynamic columns names from the above table. After that we can create a dynamic query with these columns.
Declare @ColumnNames VARCHAR(100);
SELECT @ColumnNames = COALESCE(@ColumnNames+ ',','') +
'['+ Cast(Value AS VARCHAR(50)) +']' FROM Denomination cust
PRINT @ColumnNames
DECLARE @DynamicQuery Varchar(MAX);
SET @DynamicQuery = '
SELECT * FROM Accounts
PIVOT (SUM(QTY) For Denomination IN (' + @ColumnNames + ')) AS Total'
EXEC (@DynamicQuery);

Tuesday 11 December 2012

How to Calculate Age in Sql Server OR Find age using SQL query


Calculate age of employee using SQL Server
To calculate an age from the SQL table is little bit tricky.  We are demonstrating how to calculate the age from the date of birth fields in the SQL table. While fill the application form it’s better to fill the Date Of Birth field instead of age field. Because age field can calculate from the Date Of Birth field easily and accurately.
Find the age from the Date Of Birth using SQL Server
Here we are having a table called Employee and having coloumns ID,Name and DOB. From this table we need to find the age of each employee using SQL script.

Please see the table structure.
Calculate age from SQL Server
We can use Date Diff function in SQL Server to get the age of each employee. But if we consider date field only it will get wrong answer because it will consider the current year even date of birth not came this year. The below script and result is example.

Calculate age from SQL Server

For avoiding above mentioned issue, we can use below script to find out the age from the Date Of Birth field using SQL Server.
SELECT DOB AS DateOfBirth,
GETDATE() AS CurrentDate,
DATEDIFF(YEAR,DOB,GETDATE()) - 
(CASE WHEN 
 DATEADD(YY,DATEDIFF(YEAR,DOB,GETDATE()),DOB) > GETDATE()
 THEN 1
 ELSE 0 END) AS Age
FROM Employee
Find the age using SQL Server
Calculate age using SQL Server

Tuesday 4 December 2012

How to create asynchronous file up loader using ajax in ASP.Net


Ajax files uploader in ASP.Net/C# to upload files to Server as asynchronous 
In most of the web applications, there might be have an option to upload files to server. If we are using ASP.Net file uplaoder option to upload files, will have postback after every server request. It may be very disturbance to the user. In order to avoid postback while uploading files into server in ASP.Net/C#, we can implement AJAX mechanism.
Include AjaxControlToolkit reference to the Project
First of all we need to refer ajax tool kit to our project. In order to do this, right click the project and add reference and select the folder that included the ajaxtoolkit file. Once we added, in the aspx page below line will be displayed
<%@ Register Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit" tagPrefix="ajax" %>
After that we can incuded ajax  uploader into the ASPX page like this.
<ajax:AsyncFileUpload ID="fileUpload1" OnClientUploadComplete="uploadComplete"OnClientUploadError="uploadError" 
CompleteBackColor="White" Width="350px" runat="server" UploaderStyle="Modern"UploadingBackColor="#CCFFFF" 
ThrobberID="imgLoad" OnUploadedComplete="fileUploadComplete" />
There are some special kind if events are available in the control like onUploadComplete, OnClineUploadError ..
OnClientUploadError – This property is used to execute the client side JavaScript function if file uploading failed.
OnClientUploadStarted – This property is used to execute the client side JavaScript function whenver file uploading start.
OnClientUploadComplete – This property is used to execute the client side JavaScript function after file successfully uploaded.
CompleteBackColor – This property is used to set fileupload control background after file upload complete its default value ‘Lime’.
ErrorBackColor – This property is used to set fileupload control background if file upload failed its default value ‘Red’.
UploadingBackColor – This property is the id of the control which is seen during upload file.
UploaderStyle – This property is used to set fileupload control appearance style either Modern orTraditional. By default its value “Traditional”.
ThrobberID – ID of control that is shown while the file is uploading.

ASPX PAGE
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head id="Head1" runat="server"> 
<title>Untitled Page</title> 
<script type="text/javascript"> 
// This function will execute after file uploaded successfully 
function uploadComplete() { 
document.getElementById('<%=lblMsg.ClientID %>').innerHTML = "File Uploaded Successfully"; 
} 
// This function will execute if file upload fails 
function uploadError() { 
document.getElementById('<%=lblMsg.ClientID %>').innerHTML = "File upload Failed."; 
} 
</script> 
</head> 
<body> 
<form id="form1" runat="server"> 
<ajax:ToolkitScriptManager ID="scriptManager1" runat="server"/> 
<div> 
<ajax:AsyncFileUpload ID="fileUpload1" OnClientUploadComplete="uploadComplete"OnClientUploadError="uploadError"
 CompleteBackColor="White" Width="350px" runat="server" UploaderStyle="Modern"UploadingBackColor="#CCFFFF"
 ThrobberID="imgLoad" OnUploadedComplete="fileUploadComplete" /><br />
 <asp:Image ID="imgLoad" runat="server" ImageUrl="loading.gif" />
 <br />
 <asp:Label ID="lblMsg" runat="server" Text=""></asp:Label>
 </div>
 </form>
 </body>
 </html>
CODE BEHIND
using System;
using System.Web.UI;
using AjaxControlToolkit;

protected void fileUploadComplete(object sender, AsyncFileUploadEventArgs e)
{
string filename = System.IO.Path.GetFileName(fileUpload1.FileName);
fileUpload1.SaveAs(Server.MapPath("Files/") + filename);
}

Tuesday 27 November 2012

How to crop image using ASP.Net/C# OR Cropping image in C# before upload


Crop images before upload to the server in C#/ASP.Net
In our previous post we demonstrate how we can re size image using C# or Create thumbnail image using ASP.Net. Here we are demonstrating how we can crop images using ASP.Net application using Jquery and C#. In some applications we need to upload images and we need only some portion of the images to get clear picture on the photo. In this case we need to give an option to users to crop image before they are uploading the image.
Include Jquery file/CSS files to the application. 
First of all we need to include following jquery/CSS files to the application.
1.       jquery.min.js
2.       jquery.Jcrop.js
3.       jquery.Jcrop.css
Simple steps to crop image using ASP.Net,C#,Jquery
In this application we are having a browse option for selecting an image. Once we selected a image it will display int the screen.
Crop image using ASP.net C#
Select an image to crop using ASP.Net C# Jquery
In the next step we will have the option to select an area to crop the image. Once we selected an area we can click crop button on the screen.
Crop image using ASP.Net C#
Select image area to crop
Then the selected area will be cropped and displayed in the screen.
Crop image using ASP.Net C#
Cropped area of the image
ASPX Page for crop images using Jquery 
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CropImage.aspx.cs" 
Inherits="ExperimentLab.CropImage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
 <title>Crop Image</title>
 <link href="Styles/jquery.Jcrop.css" rel="stylesheet" type="text/css" />
 <script type="text/javascript" 
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
 <script type="text/javascript" src="Scripts/jquery.Jcrop.js"></script>
 <script type="text/javascript">
 jQuery(document).ready(function () {
 jQuery('#imgCrop').Jcrop({
 onSelect: storeCoords
 });
 });
function storeCoords(c) {
 jQuery('#X').val(c.x);
 jQuery('#Y').val(c.y);
 jQuery('#W').val(c.w);
 jQuery('#H').val(c.h);
 };
</script>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 <asp:Panel ID="pnlUpload" runat="server">
 <asp:FileUpload ID="Upload" runat="server" />
 <br />
 <asp:Button ID="btnUpload" runat="server" 
 OnClick="btnUpload_Click" Text="Upload" />
 <asp:Label ID="lblError" runat="server" Visible="false" />
 </asp:Panel>
 <asp:Panel ID="pnlCrop" runat="server" Visible="false">
 <asp:Image ID="imgCrop" runat="server" />
 <br />
 <asp:HiddenField ID="X" runat="server" />
 <asp:HiddenField ID="Y" runat="server" />
 <asp:HiddenField ID="W" runat="server" />
 <asp:HiddenField ID="H" runat="server" />
 <asp:Button ID="btnCrop" runat="server" Text="Crop" 
 OnClick="btnCrop_Click" />
 </asp:Panel>
 <asp:Panel ID="pnlCropped" runat="server" Visible="false">
 <asp:Image ID="imgCropped" runat="server" />
 </asp:Panel>
 </div>
 </form>
</body>
</html>
Code Behind of the ASPX page for Crop image using ASP.Net/C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using SD = System.Drawing;
using System.Drawing.Drawing2D;
namespace ExperimentLab
{
public partial class CropImage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
String path = HttpContext.Current.Request.PhysicalApplicationPath + "images\\";
protected void btnUpload_Click(object sender, EventArgs e)
{
Boolean FileOK = false;
Boolean FileSaved = false; 
if (Upload.HasFile)
{
Session["WorkingImage"] = Upload.FileName;
String FileExtension =
Path.GetExtension(Session["WorkingImage"].ToString()).ToLower();
String[] allowedExtensions = { ".png", ".jpeg", ".jpg", ".gif" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (FileExtension == allowedExtensions[i])
{
 FileOK = true;
}
}
}
if (FileOK)
{
try
{
Upload.PostedFile.SaveAs(path + Session["WorkingImage"]);
FileSaved = true;
}
catch (Exception ex)
{
lblError.Text = "File could not be uploaded." + ex.Message.ToString();
lblError.Visible = true;
FileSaved = false;
}
}
else
{
lblError.Text = "Cannot accept files of this type.";
lblError.Visible = true;
}
if (FileSaved)
{
pnlUpload.Visible = false;
pnlCrop.Visible = true;
imgCrop.ImageUrl = "images/" + Session["WorkingImage"].ToString();
}
}
protected void btnCrop_Click(object sender, EventArgs e)
{
string ImageName = Session["WorkingImage"].ToString();
int w = Convert.ToInt32(W.Value);
int h = Convert.ToInt32(H.Value);
int x = Convert.ToInt32(X.Value);
int y = Convert.ToInt32(Y.Value);
byte[] CropImage = Crop(path + ImageName, w, h, 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, Height, SD.GraphicsUnit.Pixel);
 MemoryStream ms = new MemoryStream();
 bmp.Save(ms, OriginalImage.RawFormat);
 return ms.GetBuffer();
 }
}
}
}
catch (Exception Ex)
{
throw (Ex);
}
}
}
}

Tuesday 20 November 2012

Disable copy paste on textbox in the ASP.Net/C# using javascript/Jquery


Very simple method to disable copy paste in the textbox without any extra script
To achieve some requirements like disable copy paste functionalities in the textbox in aspx page, commonly we need to write some additional javascript functionalities in the aspx page. We can achieve this features using very simple methods.
First Method to disable Ctrl Key and right click on textbox
This method is very simple method and here we don’t need to include any javascript methods or files. We are having oncopy and onpaste event for the textboxes and can call return false for this both event.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="disableCopyPaste.aspx.cs"
 Inherits="ExperimentLab.disableCopyPaste" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
 <title>Sample to Disable Copy, Cut and Paste Options in textbox</title>
</head>
<body>
 <form id="form2" runat="server">
 <div>
 <strong>First Method To disable copy, cut and paste options in textbox</strong><br />
 <asp:TextBox ID="TextBox2" runat="server" oncopy="return false" oncut="return false"
 onpaste="return false"></asp:TextBox>
 </div>
 </form>
</body>
</html>
Second method to prevent copy paste feature in the aspx texbox
In this option, we are calling a javascript function on any key press. This function checks whether user press ctrl key or right click using e.keyCode and e.button variable. If the user press ctrl key or right click, from the javascript function call return false
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="disableCopyPaste.aspx.cs"
 Inherits="ExperimentLab.disableCopyPaste" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
 <title>Sample to Disable Copy, Cut and Paste Options in textbox</title>
 <script language="javascript" type="text/javascript">
//Function to disable Cntrl key/right click
function DisableControlKey(e) {
// Message to display
var message = "Cntrl key/ Right Click Option disabled";
// Condition to check mouse right click / Ctrl key press
if (e.keyCode == 17 || e.button == 2) {
alert(message);
return false;
}
}
</script>
</head>
<body>
 <form id="form2" runat="server">
 <div>
 <strong>Second Method to Disable copy, cut and paste options in textbox</strong><br />
 <asp:TextBox ID="TextBox3" runat="server" onKeyDown="return DisableControlKey(event)"
 onMouseDown="return DisableControlKey(event)"></asp:TextBox>
 </div>
 </form>
</body>
</html>

Tuesday 13 November 2012

Disable right click on a web page in asp.net/C# using Jquery/Javascript


How to disable right click functionality from the asp.net web page
In some of the web page has the requirement to protect source code from the users. Users can right click the page and take the source code. In order protect right click functionality on the web page we can implement javascript functionality to prevent user’s right click on the web page. So user not able to access features available on the right click menus.
By implementing javascript method we can identify the right click event from the user by checking the button code and prevent if the user clicks right click. Below mentioned web page prevented to click right click by the user. When the user trying to right click it will return warning message to user and return the action.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DisableRightClick.aspx.cs"
 Inherits="ExperimentLab.DisableRightClick" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
 <title>Sample to Disable Right Click of Page</title>
 <script language="JavaScript" type="text/javascript">
 //Message to display whenever right click on website
 var message = "Sorry, Right Click have been disabled.";
 function click(e) {
 if (document.all) {
 if (event.button == 2 || event.button == 3) {
 alert(message);
 return false;
 }
 }
else {
 if (e.button == 2 || e.button == 3) {
 e.preventDefault();
 e.stopPropagation();
 alert(message);
 return false;
 }
 }
 }
if (document.all) {
 document.onmousedown = click;
 }
else {
 document.onclick = click;
 }
</script>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 In this page right click not allowed.
 </div>
 </form>
</body>
</html>

Tuesday 6 November 2012

How to calculate difference between two dates in javascript/jquery


Simple steps to calculate difference between two date fields using JavaScript/JQuery 
In some scenario, we need to calculate the difference between two dates from the client side. Here we are going to demonstrate all about date fields using javascript such as Javascript date field validation for different format, difference between two dates in days, hours, minutes, seconds, years and weeks
Very strong and simple Javascript validation for date fields for format dd/mm/yyyy 
Following javascript function simply verify and return result for checking valid date from client side itself. It will automatically validate leap year entries and return correct result. That means if we pass ’29/02/2011′ to the function it will be return false. If we are passing ’29/02/2012′ to the function it will return true. So we don’t need to bother about the leap year or other complex things.
function isValidDate(dateStr) {
// Date validation Function
// Checks For the following valid Date formats:
// DD/MM/YYYY
var re = /^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\
d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))
|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]
\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/;
var valid = re.test(dateStr);
if (valid == false) {
alert(dateStr + ' Date is not in a valid format.')
return false;
}
return true;
}
How to calculate the date difference from client side using javascript?
Now we are going to find the difference between two date fields from the client side javascript or jquery. In some of the scenario, we need to find the number of days between two selected dates  like leave applying modules, hotel room booking etc. In this case we can simply calculate the difference between from date and to date using following function in javascript.
Here we are having two date fields for from date and todate. User has to select a from date and to date by using this controls. Todate should be greater than from date. When user select from date or todate we will call javascript function calculate()  and this function finds the difference between two dates and display the difference in the label. Its also validate as todate should be greater than the from date.
function calculate() {
var value1 = document.getElementById('<%=txtDateFrom.ClientID%>')
.value.split("/");
var value2 = document.getElementById('<%=txtDateTo.ClientID%>')
.value.split("/");
if (value1 != "" && value2 != "") {
var day1 = parseFloat(value1[0]);
var month1 = parseFloat(value1[1]);
var year1 = parseFloat(value1[2]);
var day2 = parseFloat(value2[0]);
var month2 = parseFloat(value2[1]);
var year2 = parseFloat(value2[2]);

if ((year2 < year1) || (year2 == year1 && month2 < month1) || 
(year2 == year1 && month2 == month1 && day2 < day1)) {
alert('From Date should greater than Date From');
document.getElementById('<%=txtVacationDays.ClientID%>').innerHTML = "0";
return;
}                    
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24
var fromDate = new Date(year1, month1 - 1, day1);
var toDate = new Date(year2, month2 - 1, day2);
// Convert both dates to milliseconds
var dateFrom = fromDate.getTime();
var dateTo = toDate.getTime();
// Calculate the difference in milliseconds
var difference_ms = Math.abs(dateTo - dateFrom)
// Convert back to days and return
var DiffDays = Math.round(difference_ms / ONE_DAY)
document.getElementById('<%=txtVacationDays.ClientID%>').innerHTML 
= parseFloat(DiffDays) + 1;
}
}
In order to call this javascript function on aspx textbox change event, we need to set attributes to the textbox on code behind as follows.
protected void Page_Load(object sender, EventArgs e)
{
    txtFromDate.Attributes.Add("Onchange", "calculate();");
    txtToDate.Attributes.Add("Onchange", "calculate();");
}
ASPX page having two date fields as follows :
<table>
 <tr>
 <td>
 First Date:
 <asp:TextBox runat="server" ID="txtFromDate" />
 (DD/MM/YYYY format)<br />
 Second Date: Date:
 <asp:TextBox runat="server" ID="txtToDate" />
 (DD/MM/YYYY format)<br />
 <center>
 <asp:Button runat="server" ID="btnCheck" Text="Check" 
 OnClientClick="return calculate();" />
 </center>
 </td>
 </tr>
</table>

Tuesday 30 October 2012

Create water mark text box in asp.net/C# using javascript within a single step


How to create a water mark text box in asp.net/C# using javascript 
In some scenario in the project, we need to implement water mark text for each textboxes in the form. It will help user to give right direction to enter proper and valid entries for each textboxes. We can achieve this water mark text boxes easily by using javascript methods.
Javascript method to create water mark text boxes in ASP.Net/C# using javascript
Here we are going to create a small asp.net application to show example of water mark text box creation. In aspx page we are having a textbox for username and a button. In the textbox it will show ‘Enter username’ as water mark style with gray color. When a user click mouse on to the textbox it will hide. Once the user leave the mouse pointer from the textbox without enter any data, it will display water mark text.
ASPX PAGE WITH JAVASCRIPT FOR WATER MARK TEXTBOX
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
 <title>Watermark Textbox Using JavaScript</title>
 <script language="javascript" type="text/javascript">
 function WaterMark(txtName, event) {
 var defaultText = "Enter Username";
 // Condition to check textbox length and event type
 if (txtName.value.length == 0 & event.type == "blur") {
 //if condition true then setting text color 
 //and default text in textbox
 txtName.style.color = "Gray";
 txtName.value = defaultText;
 }
// Condition to check textbox value and event type
 if (txtName.value == defaultText & event.type == "focus") {
 txtName.style.color = "black";
 txtName.value = "";
 }
 }
function WaterMarkPwd(txtName, Password) {
 var defaultText = "Enter Password";
 // Condition to check textbox length and event type
 if (txtName.value.length == 0 & event.type == "blur") {
 //if condition true then setting text color and 
 //default text in textbox
 txtName.style.color = "Gray";
 txtName.value = defaultText;
 }
// Condition to check textbox value and event type
 if (txtName.value == defaultText & event.type == "focus") {
 txtName.style.color = "black";
 txtName.value = "";
 }
 }
 </script>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 <b>UserName:</b>
 <asp:TextBox ID="txtUserName" runat="server" Text="Enter Username" ForeColor="Gray"
 onblur="WaterMark(this, event);" onfocus="WaterMark(this, event);" />
 <asp:Button runat="server" ID="btnLogin" Text="Login" />
 </div>
 </form>
</body>
</html>

Tuesday 23 October 2012

How to maintain scrollposition after post back?


How to maintain scroll position in ASP.Net Pages
When web pages are posted back to the server, by default user is returned to the top of the page. On a large web page, you might have a requirement to scroll down the user automatically to the last position on the page.
MaintainScrollPositionOnPostBack page property can be used to achieve this  in one of the following ways.
  1. Application level:To set the property by default for all pages in the website, open web.config and add the attribute to the pages node.<pages maintainScrollPositionOnPostBack=”true”>
  2. Page Level:for a particular page, open the aspx and set the property<%@ Page MaintainScrollPositionOnPostback=”true” …
  3. Code level: to set the property programmaticallyPage.MaintainScrollPositionOnPostBack = true;

Tuesday 16 October 2012

Import contacts from Gmail using ASP.Net/C# Application


How to import contacts from GMAIL into ASP.Net/C# application
Some of the application especially social network application needs to have the feature for import contacts from our gmail account. By using this feature we can easily import all contacts from our gmail account and can send bulk mail to all or groups in our gmail account
 Is it possible import contacts from GMAIL account using ASP.Net/C# Application?
Of course, we can access and import our gmail contacts into our ASP.Net/C# application using gmail API. GMAIL itself providing some APIs to access gmail accounts from an external applications like ASP.Net or C#. We can call this API from our application by passing our gmail credentials, then will access our account from the application. Here we are demonstrating how we can use GMAIL API to get contacts in GMAIL account using ASP.Net/C# application.
 Very simple Steps to import GMAIL contacts from ASP.Net/C# application
Step-1:  Download Google data API setup.
 Here is the proper link for downloading particular API.
 In this link GMAIL providing so many APIs for communicating with their different project.
 Google.GData.Apps.dll, Google.GData.Client.dll, Google.GData.Contacts.dll, Google.GData.Extensions.dll are the major dll that’s should use for our application.
 Step-2:  Create a very simple ASP.Net application to import contacts from GMAIL. For a simple application, aspx page looks like this
 <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>IMport Gmail Contacts</title>
</head>
<body>
<form id="frmGmailContacts" runat="server">
<div>
<table>
<tr>
<td>
UserName</td>
<td>
<asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Password</td>
<td>
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password">
</asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnImport" runat="server" Text="Import"
onclick="btnImport_Click" />
</td>
</tr>
</table>
</div>
<div>
<asp:GridView ID="gdvContacts" runat="server"></asp:GridView>
</div>
</form>
</body>
</html>
 
Step 3 : In code behind we have to call API for getting contacts on button click event, and assign result set to gridview.

public static DataSet GetGmailContacts(string App_Name, string Uname,
string UPassword)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
DataColumn C2 = new DataColumn();
C2.DataType = Type.GetType("System.String");
C2.ColumnName = "EmailID";
dt.Columns.Add(C2);
RequestSettings rs = new RequestSettings(App_Name, Uname, UPassword);
rs.AutoPaging = true;
ContactsRequest cr = new ContactsRequest(rs);
Feed<Contact> f = cr.GetContacts();
foreach (Contact t in f.Entries)
{
foreach (EMail email in t.Emails)
{
DataRow dr1 = dt.NewRow();
dr1["EmailID"] = email.Address.ToString();
dt.Rows.Add(dr1);
}
}
ds.Tables.Add(dt);
return ds;
}
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = GetGmailContacts("Import GMAIL Contacts",
txtUsername.Text, txtPassword.Text);
gdvContacts.DataSource = ds;
gdvContacts.DataBind();
}

Tuesday 9 October 2012

How to deploy sync framework to windows azure/Deploy sync framework project to windows azure


Deployment of sync framework workerrole / webrole project into azure environment
The article is going to explain that how we can deploy sync framework worker role or webrole projects created in Visual Studio into azure environment. We have created a worker role application that sync azure databases frequently. We are using Sync Framework 2.1 for sync database in the azure. Once it is completed the application, the challenge was to deploy this sync framework to azure platform. We have to include some dlls and also need to do some configuration settings to deploy project into Windows Azure platform
 Steps to do for deploying Sync Framework Project into Azure
 1.Open your Windows Azure Cloud Service project in Visual Studio >> In the Solution Explorer, right-click the
Web Role project, point to Add, and then click Add Reference.
2.Add references to Microsoft.Synchronization.dll, Microsoft.Synchronization.Data.dll, and Microsoft.Synchronization.Data.SqlServer.dll from Sync Framework 2.1
installation folder most of the time it is C:\Program Files (x86)\Microsoft Sync Framework\2.1.
3.Select all files and take the Properties window, then set the value of Aliases property to global and
Copy Local property to True.
4.Create a class file named activationcontext.cs file with the following content and add the file to
Workerrole/Webrole project.
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Runtime.InteropServices;
using System.IO;

namespace Microsoft.Samples.Synchronization
{
    public class ActivationContext
    {
        // Activation Context API Functions

        [DllImport("Kernel32.dll", SetLastError = true)]
        private extern static IntPtr CreateActCtx(ref ACTCTX actctx);

        // Activation context structure
        private struct ACTCTX
        {
            public int cbSize;
            public uint dwFlags;
            public string lpSource;
            public ushort wProcessorArchitecture;
            public ushort wLangId;
            public string lpAssemblyDirectory;
            public string lpResourceName;
            public string lpApplicationName;
        }

        private const int ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID = 0x004;
        private const int ACTCTX_FLAG_SET_PROCESS_DEFAULT = 0x00000010;
        private IntPtr m_hActCtx = (IntPtr)0;
        public const UInt32 ERROR_SXS_PROCESS_DEFAULT_ALREADY_SET = 14011;

     /// <summary>
     /// Explicitly load a manifest and create the process-default activation
     /// context. It takes effect immediately and stays there until the process exits.
    /// </summary>
        static public void CreateActivationContext()
        {
            string rootFolder = AppDomain.CurrentDomain.BaseDirectory;
            string manifestPath = Path.Combine(rootFolder, "webapp.manifest");
            UInt32 dwError = 0;

            // Build the activation context information structure
            ACTCTX info = new ACTCTX();
            info.cbSize = Marshal.SizeOf(typeof(ACTCTX));
            info.dwFlags = ACTCTX_FLAG_SET_PROCESS_DEFAULT;
            info.lpSource = manifestPath;
            if (null != rootFolder && "" != rootFolder)
            {
                info.lpAssemblyDirectory = rootFolder;
                info.dwFlags |= ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID;
            }

            dwError = 0;

            // Create the activation context
            IntPtr result = CreateActCtx(ref info);
            if (-1 == result.ToInt32())
            {
                dwError = (UInt32)Marshal.GetLastWin32Error();
            }

            if (-1 == result.ToInt32() &&
ActivationContext.ERROR_SXS_PROCESS_DEFAULT_ALREADY_SET != dwError)
            {
                string err = string.Format("Cannot create process-default win32 sxs context,
error={0} manifest={1}", dwError, manifestPath);
                ApplicationException ex = new ApplicationException(err);
                throw ex;
            }
        }
    }
}
5.Add a folder named synchronization.assemblies to the Web Role/ Worker Role project and add the following five files to the folder.
 Microsoft.Synchronization.dll
Microsoft.Synchronization.Data.dll
Microsoft.Synchronization.Data.SqlServer.dll
Synchronization21.dll
 Create a file named synchronization.assemblies.manifest, add the following content, and add the file to this folder.
 <?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>
<assemblyIdentity
type="x64"
name="synchronization.assemblies"
version="2.1.0.0"/>
<file name = "synchronization21.dll">
<comClass clsid="{EC413D66-6221-4ebb-AC55-4900FB321011}"
threadingModel="Both"/>   
</file>
</assembly>
6.Multiple-select all files under synchronization.assemblies folder, right-click, and then click Properties.
Set the value of Build Action property to Content and Copy To Output Directory to Copy Always.
7.Create a file named webapp.manifest, add the following content, and add the file to the Web Role project.
<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity name="webapp" version="8.0.0.0" type="x64"/>
<dependency>
<dependentAssembly>
<assemblyIdentity name="synchronization.assemblies" version="2.1.0.0" type="x64"/>
</dependentAssembly>
</dependency>
</assembly>
 8.Set the value of Build Action property to Content and Copy To Output Directory to Copy Always for the webapp.manifest file using Properties window.
9.Add the following statement to the OnStart method before base.OnStart method call in the WebRole.cs file.
 Microsoft.Samples.Synchronization.ActivationContext.CreateActivationContext();