Tutorial
Tutorial
Tutorial
Net
Results 1 - 10 of 562
1 2 3 4 5
Send user Confirmation email after Registration with Activation Link in ASP.Net
04 Jan 2014 Mudassar Khan 0 Comments 1510 Views ASP.Net
Here Mudassar Ahmed Khan has explained how to send user confirmation email after registration with Activation link in ASP.Net using C# and VB.Net. In order to validate the email address of the user provided during registration, a confirmation email with activation link in sent to the email address and when user clicks the link, his email address is verified and his account gets activated.
More
In this article I will explain how search records (data) on TextBox KeyPress in GridView with paging enabled using jQuery in ASP.Net. The matching records will be shown as highlighted. In one of my previous articles Search GridView records (data) on TextBox KeyPress using jQuery in ASP.Net, I have implemented GridView search using jQuery QuickSearch but the jQuery QuickSearch plugin does not work for GridView which has Paging enabled. Since we need to dynamically search and filter GridView records on TextBox KeyPress, we will need to bind the GridView using jQuery AJAX, C# and VB.Net.
Database
For this article I have used Microsofts Northwind database. You can download it using the link provided below.
Download Northwind Database
HTML Markup Below is the HTML Markup. It has an ASP.Net GridView, a TextBox for entering search term and an HTML DIV control where the Pager will be populated for pagination.
Search: <asp:TextBox ID="txtSearch" runat="server" /> <hr /> <asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false"> <Columns> <asp:BoundField HeaderStyle-Width="150px" DataField="ContactName" HeaderText="Contact Name" ItemStyle-CssClass="ContactName" /> <asp:BoundField HeaderStyle-Width="150px" DataField="CustomerID" HeaderText="CustomerID" /> <asp:BoundField HeaderStyle-Width="150px" DataField="City" HeaderText="City" /> </Columns> </asp:GridView> <br /> <div class="Pager"> </div>
VB.Net
Imports Imports Imports Imports System.Data System.Web.Services System.Configuration System.Data.SqlClient
Populating GridView Dummy with Dummy Data In Page Load event of the page I am populating the GridView with dummy data so that we can use its HTML Table structure to populate data using jQuery. I have created a variable PageSize which will decide the number of records to be displayed per page in GridView Note: The dummy DataTable being populated has the same columns which will be returned from the SQL Query C#
private static int PageSize = 5; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindDummyRow(); } } private void BindDummyRow() { DataTable dummy = new DataTable(); dummy.Columns.Add("CustomerID"); dummy.Columns.Add("ContactName"); dummy.Columns.Add("City"); dummy.Rows.Add(); gvCustomers.DataSource = dummy; gvCustomers.DataBind(); }
VB.Net
Private Shared PageSize As Integer = 5 Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load If Not IsPostBack Then BindDummyRow() End If End Sub Private Sub BindDummyRow() Dim dummy As New DataTable() dummy.Columns.Add("CustomerID") dummy.Columns.Add("ContactName") dummy.Columns.Add("City") dummy.Rows.Add() gvCustomers.DataSource = dummy gvCustomers.DataBind() End Sub
Implement Search and Pagination using SQL Server Stored Procedure The following stored procedure which will perform search and pagination on the table records and return per page data. CREATE PROCEDURE [dbo].[GetCustomers_Pager] @SearchTerm VARCHAR(100) = '' ,@PageIndex INT = 1 ,@PageSize INT = 10 ,@RecordCount INT OUTPUT AS BEGIN SET NOCOUNT ON; SELECT ROW_NUMBER() OVER (
ORDER BY [CustomerID] ASC )AS RowNumber ,[CustomerID] ,[CompanyName] ,[ContactName] ,[City] INTO #Results FROM [Customers] WHERE [ContactName] LIKE @SearchTerm + '%' OR @SearchTerm = '' SELECT @RecordCount = COUNT(*) FROM #Results SELECT * FROM #Results WHERE RowNumber BETWEEN(@PageIndex 1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1 DROP TABLE #Results END
WebMethod to handle jQuery AJAX calls Below is the Web Method which is being called by the jQuery AJAX function which populates the GridView with data and also does Pagination. The SearchTerm and PageIndex are passed as parameter from Client side, while the PageSize we get from the static variable we have declared. Based on these parameters we can fetch the records Page wise. The records fetched along with the Total Record Count are sent to Client Side as XML string. Note: Total Record Count is necessary to populate pager. C#
[WebMethod] public static string GetCustomers(string searchTerm, int pageIndex) { string query = "[GetCustomers_Pager]"; SqlCommand cmd = new SqlCommand(query); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@SearchTerm", searchTerm); cmd.Parameters.AddWithValue("@PageIndex", pageIndex); cmd.Parameters.AddWithValue("@PageSize", PageSize); cmd.Parameters.Add("@RecordCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output; return GetData(cmd, pageIndex).GetXml(); } private static DataSet GetData(SqlCommand cmd, int pageIndex) { string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString; using (SqlConnection con = new SqlConnection(strConnString)) { using (SqlDataAdapter sda = new SqlDataAdapter())
{ cmd.Connection = con; sda.SelectCommand = cmd; using (DataSet ds = new DataSet()) { sda.Fill(ds, "Customers"); DataTable dt = new DataTable("Pager"); dt.Columns.Add("PageIndex"); dt.Columns.Add("PageSize"); dt.Columns.Add("RecordCount"); dt.Rows.Add(); dt.Rows[0]["PageIndex"] = pageIndex; dt.Rows[0]["PageSize"] = PageSize; dt.Rows[0]["RecordCount"] = cmd.Parameters["@RecordCount"].Value; ds.Tables.Add(dt); return ds; } } } }
VB.Net
<WebMethod()> _ Public Shared Function GetCustomers(searchTerm As String, pageIndex As Integer) As String Dim query As String = "[GetCustomers_Pager]" Dim cmd As New SqlCommand(query) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.AddWithValue("@SearchTerm", searchTerm) cmd.Parameters.AddWithValue("@PageIndex", pageIndex) cmd.Parameters.AddWithValue("@PageSize", PageSize) cmd.Parameters.Add("@RecordCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output Return GetData(cmd, pageIndex).GetXml() End Function Private Shared Function GetData(cmd As SqlCommand, pageIndex As Integer) As DataSet Dim strConnString As String = ConfigurationManager.ConnectionStrings("conString").Connec tionString Using con As New SqlConnection(strConnString) Using sda As New SqlDataAdapter() cmd.Connection = con sda.SelectCommand = cmd Using ds As New DataSet() sda.Fill(ds, "Customers") Dim dt As New DataTable("Pager") dt.Columns.Add("PageIndex") dt.Columns.Add("PageSize") dt.Columns.Add("RecordCount") dt.Rows.Add() dt.Rows(0)("PageIndex") = pageIndex dt.Rows(0)("PageSize") = PageSize dt.Rows(0)("RecordCount") = cmd.Parameters("@RecordCount").Value ds.Tables.Add(dt) Return ds End Using
Client Side Implementation Below is the complete Client Side Implementation, here on load event of jQuery the GridView is populated with PageIndex 1 using the method GetCustomers which populates the ASP.Net GridView which was initially populated with dummy data. Using the Record Count, the pager is populated inside the HTML DIV using the ASPSnippets_Pager jQuery Plugin. A jQuery Keyup event handler has been attached to the Search TextBox which will trigger an AJAX call and will filter the GridView with the matched records.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="ASPSnippets_Pager.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { GetCustomers(1); }); $("[id*=txtSearch]").live("keyup", function () { GetCustomers(parseInt(1)); }); $(".Pager .page").live("click", function () { GetCustomers(parseInt($(this).attr('page'))); }); function SearchTerm() { return jQuery.trim($("[id*=txtSearch]").val()); }; function GetCustomers(pageIndex) { $.ajax({ type: "POST", url: "Default.aspx/GetCustomers", data: '{searchTerm: "' + SearchTerm() + '", pageIndex: ' + pageIndex + '}', contentType: "application/json; charset=utf-8", dataType: "json", success: OnSuccess, failure: function (response) { alert(response.d); }, error: function (response) { alert(response.d); } }); } var row; function OnSuccess(response) { var xmlDoc = $.parseXML(response.d); var xml = $(xmlDoc); var customers = xml.find("Customers"); if (row == null) { row = $("[id*=gvCustomers] tr:last-child").clone(true);
} $("[id*=gvCustomers] tr").not($("[id*=gvCustomers] tr:first-child")).remove(); if (customers.length > 0) { $.each(customers, function () { var customer = $(this); $("td", row).eq(0).html($(this).find("ContactName").text()); $("td", row).eq(1).html($(this).find("CustomerID").text()); $("td", row).eq(2).html($(this).find("City").text()); $("[id*=gvCustomers]").append(row); row = $("[id*=gvCustomers] tr:last-child").clone(true); }); var pager = xml.find("Pager"); $(".Pager").ASPSnippets_Pager({ ActiveCssClass: "current", PagerCssClass: "pager", PageIndex: parseInt(pager.find("PageIndex").text()), PageSize: parseInt(pager.find("PageSize").text()), RecordCount: parseInt(pager.find("RecordCount").text()) }); $(".ContactName").each(function () { var searchPattern = new RegExp('(' + SearchTerm() + ')', 'ig'); $(this).html($(this).text().replace(searchPattern, "<span class = 'highlight'>" + SearchTerm() + "</span>")); }); } else { var empty_row = row.clone(true); $("td:first-child", empty_row).attr("colspan", $("td", row).length); $("td:first-child", empty_row).attr("align", "center"); $("td:first-child", empty_row).html("No records found for the search criteria." ); $("td", empty_row).not($("td:first-child", empty_row)).remove(); $("[id*=gvCustomers]").append(empty_row); } }; </script>
CSS Below is the necessary CSS styles which you need to put on your page.
<style type="text/css"> body { font-family: Arial; font-size: 10pt; } table { border: 1px solid #ccc; } table th { background-color: #F7F7F7;
color: #333; font-weight: bold; } table th, table td { padding: 5px; border-color: #ccc; } .Pager span { color: #333; background-color: #F7F7F7; font-weight: bold; text-align: center; display: inline-block; width: 20px; margin-right: 3px; line-height: 150%; border: 1px solid #ccc; } .Pager a { text-align: center; display: inline-block; width: 20px; border: 1px solid #ccc; color: #fff; color: #333; margin-right: 3px; line-height: 150%; text-decoration: none; } .highlight { background-color: #FFFFAF; } </style>
In this article I will explain with example how to implement simple user login form in ASP.Net using C# and VB.Net. The login form has been implemented using ASP.Net controls and Forms Authentication. It also has the Remember Me CheckBox feature which allows user to save the credentials when he visits site next time. This is the third article from the series, in my previous articles I have explained Simple User Registration Form Example in ASP.Net andSend user Confirmation email after Registration with Activation Link in ASP.Net Database I am making use of the same database table Users which was used in the article Simple User Registration Form Example
in ASP.Net
Note: The SQL for creating the database is provided in the attached sample code.
This example consists of two pages Login page (Login.aspx) using which the user will login and the Landing page (Home.aspx) which is the page user will be redirected after successful authentication.
Login Page This is the login form which will do the following:1. Authenticate user by verifying Username and Password. 2. Make sure user has activated his account. Refer my article for details Send user Confirmation email after Registration
with Activation Link in ASP.Net
HTML Markup The HTML markup consists of an ASP.Net Login control for which the OnAuthenticate event handler has been specified.
<form id="form1" runat="server"> <asp:Login ID = "Login1" runat = "server" OnAuthenticate= "ValidateUser"></asp:Login> </form>
VB.Net
Imports Imports Imports Imports System.Data System.Configuration System.Data.SqlClient System.Web.Security
Stored Procedure to Validate the User Credentials The following stored procedure is used to validate the user credentials, this stored procedure first checks whether the username and password are correct else returns -1. If the username and password are correct but the user has not been activated then the code returned is -2. If the username and password are correct and the user account has been activated then UserId of the user is returned by the stored procedure. CREATE PROCEDURE [dbo].[Validate_User] @Username NVARCHAR(20), @Password NVARCHAR(20) AS BEGIN SET NOCOUNT ON; DECLARE @UserId INT, @LastLoginDate DATETIME SELECT @UserId = UserId, @LastLoginDate = LastLoginDate FROM Users WHERE Username = @Username AND [Password] = @Password IF @UserId IS NOT NULL BEGIN IF NOT EXISTS(SELECT UserId FROM UserActivation WHERE UserId = @U serId) BEGIN UPDATE Users SET LastLoginDate = GETDATE() WHERE UserId = @UserId SELECT @UserId [UserId] -- User Valid END ELSE BEGIN SELECT -2 -- User not activated. END END ELSE BEGIN SELECT -1 -- User invalid. END END
Validating the User Credentials The below event handler gets called when the Log In button is clicked. Here the Username and Password entered by the user is passed to the stored procedure and its status is captured and if the value is not -1 (Username or password incorrect) or -2 (Account not activated) then the user is redirected to the Home page usingFormsAuthentication RedirectFromLoginPage method. C#
protected void ValidateUser(object sender, EventArgs e) { int userId = 0;
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("Validate_User")) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Username", Login1.UserName); cmd.Parameters.AddWithValue("@Password", Login1.Password); cmd.Connection = con; con.Open(); userId = Convert.ToInt32(cmd.ExecuteScalar()); con.Close(); } switch (userId) { case -1: Login1.FailureText = "Username and/or password is incorrect."; break; case -2: Login1.FailureText = "Account has not been activated."; break; default: FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet); break; } } }
VB.Net
Protected Sub ValidateUser(sender As Object, e As EventArgs) Dim userId As Integer = 0 Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionStrin g Using con As New SqlConnection(constr) Using cmd As New SqlCommand("Validate_User") cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.AddWithValue("@Username", Login1.UserName) cmd.Parameters.AddWithValue("@Password", Login1.Password) cmd.Connection = con con.Open() userId = Convert.ToInt32(cmd.ExecuteScalar()) con.Close() End Using Select Case userId Case -1 Login1.FailureText = "Username and/or password is incorrect." Exit Select Case -2 Login1.FailureText = "Account has not been activated." Exit Select Case Else FormsAuthentication.RedirectFromLoginPage(Login1.UserName, Login1.RememberMeSet)
Home Page After successful login user will be redirected to this page.
HTML Markup In this page I have made use of ASP.Net LoginName control to display the name of the Logged In user and LoginStatus control to allow user Logout.
<div> Welcome <asp:LoginName ID="LoginName1" runat="server" Font-Bold = "true" /> <br /> <br /> <asp:LoginStatus ID="LoginStatus1" runat="server" /> </div>
VB.Net
Imports System.Web.Security
Inside the Page Load event, first we verify whether the User is authenticated using the IsAuthenticated property. If the user is not authenticated then he is redirected back to the Login page using FormsAuthentication RedirectToLoginPage method. C#
protected void Page_Load(object sender, EventArgs e) { if (!this.Page.User.Identity.IsAuthenticated) { FormsAuthentication.RedirectToLoginPage(); } }
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me. Load If Not Me.Page.User.Identity.IsAuthenticated Then FormsAuthentication.RedirectToLoginPage() End If End Sub
Web.Config Configuration You will need to add the following configuration in the Web.Config file in the <system.web> section.
<authentication mode="Forms"> <formsdefaultUrl="~/Home.aspx" loginUrl="~/Login.aspx" slidingExpiration="true" timeout="2880"></form s> </authentication>
In this article I will explain how to implement infinite scrolling of images like Bing and Google in ASP.Net using jQuery AJAX in C# and VB.Net.
Thus creating an Infinite scrolling image gallery where images will be dynamically loaded from database along with other information when is page scrolling down using DataList control in ASP.Net. This article uses very similar concept used in my article
Load data while Scrolling Page down with jQuery AJAX and ASP.Net
Database Below is the design of the table that will store the URL of the image files along with some other information.
HTML Markup The HTML Markup consists of an ASP.Net DataList control which will be used as a Template to recreate items when page is scrolled.
<asp:DataList ID="dlImages" runat="server" RepeatLayout="Table" RepeatColumns="3" CellPadding="2" CellSpacing="20"> <ItemTemplate> <table class="item" cellpadding="0" cellspacing="0" border="0"> <tr> <td align="center" class="header"> <span class="name"> <%# Eval("Name") %></span> </td> </tr> <tr> <td align="center" class="body"> <img class="image" src='<%# Eval("Url") %>' alt="" /> </td> </tr> <tr> <td align="center"> Photo by <a href="http://www.flickr.com/photos/pearlshelf/">Pearl Photo</a> </td> </tr> <tr> <td class="footer" align="center"> <a href='<%# Eval("Url") %>' target="_blank" class="button">View</a> <input type="hidden" class="is_used" value="0" /> </td> </tr> </table> </ItemTemplate> </asp:DataList>
Implement Pagination in SQL Server Stored Procedure Since we need to get data on demand i.e. in parts we need to have pagination capability in our stored procedure so that we can fetch records based on page index or page number. This stored procedure returns Total Page Count as OUPUT parameter; this count will help notify jQuery that it should stop making AJAX calls as the all the data has been fetched. CREATE PROCEDURE [dbo].[GetImagesPageWise] @PageIndex INT = 1 ,@PageSize INT = 3 ,@PageCount INT OUTPUT AS BEGIN SET NOCOUNT ON; SELECT ROW_NUMBER() OVER ( ORDER BY [Id] ASC )AS RowNumber ,Id ,Name ,Url INTO #Results FROM [Images] DECLARE @RecordCount INT SELECT @RecordCount = COUNT(*) FROM #Results SET @PageCount = CEILING(CAST(@RecordCount AS DECIMAL(10, 2)) / CAST(@Page Size AS DECIMAL(10, 2))) PRINT @PageCount SELECT * FROM #Results WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex 1) * @PageSize + 1) + @PageSize) - 1 DROP TABLE #Results END
Binding a dummy record to the DataList In the Page Load event, I am binding a dummy record to the DataList control. This is very necessary as jQuery needs some HTML content which it can replicate the data fetched via jQuery AJAX. C#
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { this.BindDummyItem(); }
} private void BindDummyItem() { DataTable dummy = new DataTable(); dummy.Columns.Add("Id"); dummy.Columns.Add("Name"); dummy.Columns.Add("Url"); int count = dlImages.RepeatColumns == 0 ? 1 : dlImages.RepeatColumns; for (int i = 0; i < count; i++) { dummy.Rows.Add(); } dlImages.DataSource = dummy; dlImages.DataBind(); }
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load If Not IsPostBack Then Me.BindDummyItem() End If End Sub Private Sub BindDummyItem() Dim dummy As New DataTable() dummy.Columns.Add("Id") dummy.Columns.Add("Name") dummy.Columns.Add("Url") Dim count As Integer = If(dlImages.RepeatColumns = 0, 1, dlImages.RepeatColumns) For i As Integer = 0 To count - 1 dummy.Rows.Add() Next dlImages.DataSource = dummy dlImages.DataBind() End Sub
WebMethod to handle AJAX calls from jQuery and fetch The following web method handles the jQuery AJAX calls when page is scrolled down. It simply fetches the records from the database and the returns the XML to the client. Along with the data, the count of the total pages is also sent so that the client side function is informed whether the last page has been fetched. Note: You need to set PageSize as multiple of the number of items displayed in one row, for example here I am setting PageSize as 9 and I am displaying 3 items per row, so for example if you have 5 items per row then you must have page size as either 5, 10, 15 and so on depending on size of the item and image. C#
[WebMethod] public static string GetImages(int pageIndex) { return GetImagesData(pageIndex).GetXml();
} public static DataSet GetImagesData(int pageIndex) { int pageSize = 9; string query = "[GetImagesPageWise]"; SqlCommand cmd = new SqlCommand(query); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@PageIndex", pageIndex); cmd.Parameters.AddWithValue("@PageSize", pageSize); cmd.Parameters.Add("@PageCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output; return GetData(cmd); } private static DataSet GetData(SqlCommand cmd) { string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(strConnString)) { using (SqlDataAdapter sda = new SqlDataAdapter()) { cmd.Connection = con; sda.SelectCommand = cmd; using (DataSet ds = new DataSet()) { sda.Fill(ds, "Images"); DataTable dt = new DataTable("PageCount"); dt.Columns.Add("PageCount"); dt.Rows.Add(); dt.Rows[0][0] = cmd.Parameters["@PageCount"].Value; ds.Tables.Add(dt); return ds; } } } }
VB.Net
<WebMethod()> _ Public Shared Function GetImages(pageIndex As Integer) As String Return GetImagesData(pageIndex).GetXml() End Function Public Shared Function GetImagesData(pageIndex As Integer) As DataSet Dim pageSize As Integer = 9 Dim query As String = "[GetImagesPageWise]" Dim cmd As New SqlCommand(query) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.AddWithValue("@PageIndex", pageIndex) cmd.Parameters.AddWithValue("@PageSize", pageSize) cmd.Parameters.Add("@PageCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output Return GetData(cmd)
End Function Private Shared Function GetData(cmd As SqlCommand) As DataSet Dim strConnString As String = ConfigurationManager.ConnectionStrings("constr").Connecti onString Using con As New SqlConnection(strConnString) Using sda As New SqlDataAdapter() cmd.Connection = con sda.SelectCommand = cmd Using ds As New DataSet() sda.Fill(ds, "Images") Dim dt As New DataTable("PageCount") dt.Columns.Add("PageCount") dt.Rows.Add() dt.Rows(0)(0) = cmd.Parameters("@PageCount").Value ds.Tables.Add(dt) Return ds End Using End Using End Using End Function
jQuery AJAX and Client Side implementation Below is the client side implementation where the actual job is done, here I have attached a jQuery scroll event handler to the page. When the page is scrolled a jQuery AJAX call is sent to the server for fetching the records. Inside the Success event handler, the response XML is parsed and the records along with the maximum page count are retrieved. Then based on the DataList RepeatColumns property value, the DataList Items are cloned and appended to the page with the values fetched from the server. C#
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript"> var pageIndex = 0; var pageCount; $(window).scroll(function () { if ($(window).scrollTop() == $(document).height() - $(window).height()) { GetRecords(); } }); $(function () { GetRecords(); }); function GetRecords() { pageIndex++; if (pageIndex == 1 || pageIndex <= pageCount) { $("#loader").show(); $.ajax({ type: "POST", url: "CS.aspx/GetImages",
data: '{pageIndex: ' + pageIndex + '}', contentType: "application/json; charset=utf-8", dataType: "json", success: OnSuccess, failure: function (response) { alert(response.responseText); }, error: function (response) { alert(response.responseText); } }); } } function OnSuccess(response) { var xmlDoc = $.parseXML(response.d); var xml = $(xmlDoc); pageCount = parseInt(xml.find("PageCount").eq(0).find("PageCount").text()); var images = xml.find("Images"); var repeatColumns = parseInt("<%=dlImages.RepeatColumns == 0 ? 1 : dlImages.RepeatColumns %>"); var rowCount = Math.ceil(images.length / repeatColumns); var j = 0; images.each(function () { var image = $(this); var row = $("[id*=dlImages] .item:last").closest("tr"); if ($(".is_used[value='1']", row).length == repeatColumns) { row = $("[id*=dlImages] tr").eq(0).clone(); $(".is_used", row).val("0"); $(".image", row).attr("src", ""); $(".button", row).attr("href", ""); $(".loader", row).remove(); $("[id*=dlImages]").append(row); j = 0; } else { row = $("[id*=dlImages] .item:last").closest("tr"); } var cell = $(".item", row).eq(j); $(".name", cell).html(image.find("Name").text()); $(".button", cell).attr("href", image.find("Url").text()); $(".is_used", cell).attr("value", "1"); var img = $(".image", cell); var loader = $("<img class = 'loader' src = 'loader.gif' />" ); img.after(loader); img.hide(); img.attr("src", image.find("Url").text()); img.load(function () { $(this).parent().find(".loader").remove(); $(this).fadeIn(); }); j++; }); $("[id*=dlImages] .is_used[value='0']").closest(".item").remove(); } </script>
VB.Net
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript"> var pageIndex = 0; var pageCount; $(window).scroll(function () { if ($(window).scrollTop() == $(document).height() - $(window).height()) { GetRecords(); } }); $(function () { GetRecords(); }); function GetRecords() { pageIndex++; if (pageIndex == 1 || pageIndex <= pageCount) { $("#loader").show(); $.ajax({ type: "POST", url: "VB.aspx/GetImages", data: '{pageIndex: ' + pageIndex + '}', contentType: "application/json; charset=utf-8", dataType: "json", success: OnSuccess, failure: function (response) { alert(response.responseText); }, error: function (response) { alert(response.responseText); } }); } } function OnSuccess(response) { var xmlDoc = $.parseXML(response.d); var xml = $(xmlDoc); pageCount = parseInt(xml.find("PageCount").eq(0).find("PageCount").text()); var images = xml.find("Images"); var repeatColumns = parseInt("<%=IIf(dlImages.RepeatColumns = 0, 1, dlImages.RepeatColumns) %>"); var rowCount = Math.ceil(images.length / repeatColumns); var j = 0; images.each(function () { var image = $(this); var row = $("[id*=dlImages] .item:last").closest("tr"); if ($(".is_used[value='1']", row).length == repeatColumns) { row = $("[id*=dlImages] tr").eq(0).clone(); $(".is_used", row).val("0"); $(".image", row).attr("src", ""); $(".button", row).attr("href", ""); $(".loader", row).remove(); $("[id*=dlImages]").append(row); j = 0; } else {
row = $("[id*=dlImages] .item:last").closest("tr"); } var cell = $(".item", row).eq(j); $(".name", cell).html(image.find("Name").text()); $(".button", cell).attr("href", image.find("Url").text()); $(".is_used", cell).attr("value", "1"); var img = $(".image", cell); var loader = $("<img class = 'loader' src = 'loader.gif' />"); img.after(loader); img.hide(); img.attr("src", image.find("Url").text()); img.load(function () { $(this).parent().find(".loader").remove(); $(this).fadeIn(); }); j++; }); $("[id*=dlImages] .is_used[value='0']").closest(".item").remove(); } </script>
Send user Confirmation email after Registration with Activation Link in ASP.Net
04 Jan 2014 Mudassar Khan 0 Comments 1510 Views ASP.Net
Here Mudassar Ahmed Khan has explained how to send user confirmation email after registration with Activation link in ASP.Net using C# and VB.Net. In order to validate the email address of the user provided during registration, a confirmation email with activation link in sent to the email address and when user clicks the link, his email address is verified and his account gets activated.
Download
This article is continuation of my previous article Simple User Registration Form Example in ASP.Net, where I have explained how to build a User registration form. In this article I will explain how to send user confirmation email after registration with Activation link in ASP.Net using C# and VB.Net. In order to validate the email address of the user provided during registration, a confirmation email with activation link in sent to the email address and when user clicks the link, his email address is verified and his account gets activated.
Database In the previous article we have already created database named LoginDB which contains the following table named Users in it. For this article I have created a new table named UserActivation.
In the above table column UserId is set as primary key and as well as foreign key to the Users table. Note: The SQL for creating the database is provided in the attached sample code.
Registration Page Note: The registration page has already been explained in my previous article Simple User Registration Form Example in ASP.Net, and hence here only necessary code and explanations (required for this article) are provided. On the registration page I have made some changes in the RegisterUser event handler, if the username and email address are found valid then theSendActivationEmail method is executed (show highlighted in the code snippet below). C#
protected void RegisterUser(object sender, EventArgs e) {
int userId = 0; string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("Insert_User")) { using (SqlDataAdapter sda = new SqlDataAdapter()) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Username", txtUsername.Text.Trim()); cmd.Parameters.AddWithValue("@Password", txtPassword.Text.Trim()); cmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim()); cmd.Connection = con; con.Open(); userId = Convert.ToInt32(cmd.ExecuteScalar()); con.Close(); } } string message = string.Empty; switch (userId) { case -1: message = "Username already exists.\\nPlease choose a different username."; break; case -2: message = "Supplied email address has already been used."; break; default: message = "Registration successful. Activation email has been sent."; SendActivationEmail(userId); break; } ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + message + "');", true); } }
VB.Net
Protected Sub RegisterUser(sender As Object, e As EventArgs) Dim userId As Integer = 0 Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionStrin g Using con As New SqlConnection(constr) Using cmd As New SqlCommand("Insert_User") Using sda As New SqlDataAdapter() cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.AddWithValue("@Username", txtUsername.Text.Trim()) cmd.Parameters.AddWithValue("@Password", txtPassword.Text.Trim()) cmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim()) cmd.Connection = con con.Open() userId = Convert.ToInt32(cmd.ExecuteScalar()) con.Close() End Using
End Using Dim message As String = String.Empty Select Case userId Case -1 message = "Username already exists.\nPlease choose a different username." Exit Select Case -2 message = "Supplied email address has already been used." Exit Select Case Else message = "Registration successful. Activation email has been sent." SendActivationEmail(userId) Exit Select End Select ClientScript.RegisterStartupScript([GetType](), "alert", (Convert.ToString("alert('") & message) + "');", True) End Using End Sub
Inside the SendActivationEmail method, a unique Activation code is generated using Guids NewGuid method and it is inserted in the UserActivation table. Then an email is sent to the users email address with the URL of the Activation page with genera ted Activation Code in the QueryString of the URL. C#
private void SendActivationEmail(int userId) { string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; string activationCode = Guid.NewGuid().ToString(); using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("INSERT INTO UserActivation VALUES(@UserId, @ActivationCode)")) { using (SqlDataAdapter sda = new SqlDataAdapter()) { cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@UserId", userId); cmd.Parameters.AddWithValue("@ActivationCode", activationCode); cmd.Connection = con; con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } } using (MailMessage mm = new MailMessage("[email protected]", txtEmail.Text)) { mm.Subject = "Account Activation"; string body = "Hello " + txtUsername.Text.Trim() + ","; body += "<br /><br />Please click the following link to activate your account" ;
body += "<br /><a href = '" + Request.Url.AbsoluteUri.Replace("CS.aspx", "CS_Activation.aspx?ActivationCode="+ activationCode) + "'>Click here to activate your account.</a>"; body += "<br /><br />Thanks"; mm.Body = body; mm.IsBodyHtml = true; SmtpClient smtp = new SmtpClient(); smtp.Host = "smtp.gmail.com"; smtp.EnableSsl = true; NetworkCredential NetworkCred = new NetworkCredential("[email protected]", "<password>"); smtp.UseDefaultCredentials = true; smtp.Credentials = NetworkCred; smtp.Port = 587; smtp.Send(mm); } }
VB.Net
Private Sub SendActivationEmail(userId As Integer) Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionStrin g Dim activationCode As String = Guid.NewGuid().ToString() Using con As New SqlConnection(constr) Using cmd As New SqlCommand("INSERT INTO UserActivation VALUES(@UserId, @ActivationCode)") Using sda As New SqlDataAdapter() cmd.CommandType = CommandType.Text cmd.Parameters.AddWithValue("@UserId", userId) cmd.Parameters.AddWithValue("@ActivationCode", activationCode) cmd.Connection = con con.Open() cmd.ExecuteNonQuery() con.Close() End Using End Using End Using Using mm As New MailMessage("[email protected]", txtEmail.Text) mm.Subject = "Account Activation" Dim body As String = "Hello " + txtUsername.Text.Trim() + "," body += "<br /><br />Please click the following link to activate your account" body += "<br /><a href = '" + Request.Url.AbsoluteUri.Replace("VB.aspx", Convert.ToString("VB_Activation.aspx?ActivationCod e=") & activationCode) + "'>Click here to activate your account.</a>" body += "<br /><br />Thanks" mm.Body = body mm.IsBodyHtml = True Dim smtp As New SmtpClient() smtp.Host = "smtp.gmail.com" smtp.EnableSsl = True Dim NetworkCred As New NetworkCredential("[email protected]", "<password>") smtp.UseDefaultCredentials = True smtp.Credentials = NetworkCred smtp.Port = 587 smtp.Send(mm) End Using
End Sub
Activation Page When the user clicks the Activation link in the received email he will be land on this page, here the activation code will be validated and if it is valid users account will be activated.
HTML Markup The HTML markup consists of an ASP.Net Literal control to display the Activation status message.
<h1><asp:Literal ID="ltMessage" runat="server" /></h1>
VB.Net
Imports System.Data Imports System.Configuration Imports System.Data.SqlClient
Validating the Activation Code and activating the User Account Inside the Page Load event of the page, the activation code is extracted from QueryString and delete query is executed on the UserActivation table with the extracted Activation Code. If the activation code is valid, the record is deleted and the rows affected is 1. And if the activation code is invalid or the user has been already activated then no record is deleted and rows affected is returned 0. C#
protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; string activationCode = !string.IsNullOrEmpty(Request.QueryString["ActivationCode"]) ? Request.QueryString["ActivationCode"] : Guid.Empty.ToString(); using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("DELETE FROM UserActivation WHERE ActivationCode = @ActivationCode")) { using (SqlDataAdapter sda = new SqlDataAdapter()) { cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@ActivationCode", activationCode); cmd.Connection = con; con.Open(); int rowsAffected = cmd.ExecuteNonQuery(); con.Close(); if (rowsAffected == 1) { ltMessage.Text = "Activation successful."; } else { ltMessage.Text = "Invalid Activation code."; } } } } } }
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load If Not Me.IsPostBack Then Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionS tring Dim activationCode As String = If(Not String.IsNullOrEmpty(Request.QueryString( "ActivationCode")), Request.QueryString("ActivationCode"), Guid.Empty.ToString()) Using con As New SqlConnection(constr) Using cmd As New SqlCommand("DELETE FROM UserActivation WHERE ActivationCode = @ActivationCode") Using sda As New SqlDataAdapter()
cmd.CommandType = CommandType.Text cmd.Parameters.AddWithValue("@ActivationCode", activationCode) cmd.Connection = con con.Open() Dim rowsAffected As Integer = cmd.ExecuteNonQuery() con.Close() If rowsAffected = 1 Then ltMessage.Text = "Activation successful." Else ltMessage.Text = "Invalid Activation code." End If End Using End Using End Using End If End Sub
1343 Views
In this article I will explain how to build a simple user registration form that will allow user register to the website in ASP.Net using C# and VB.Net. User will fill up the registration form with details such as username, password, email address, etc. and these details will be saved in the database table. The registration form will also make sure that duplicate username and email addresses are not saved by verifying whether username and email address must not exists in the table.
Database For this article I have created a new database named LoginDB which contains the following table named Users in it.
In the above table column UserId is set as primary key and it Identity property is set to true. Note: The SQL for creating the database is provided in the attached sample code.
HTML Markup The HTML Markup consists of some TextBox, their corresponding Validators and a Button. Other than RequiredField Validators theres a CompareValidator to compare passwords and a RegularExpressionValidator to validate email address.
<table border="0" cellpadding="0" cellspacing="0"> <tr> <th colspan="3"> Registration </th> </tr>
<tr> <td> Username </td> <td> <asp:TextBox ID="txtUsername" runat="server" /> </td> <td> <asp:RequiredFieldValidator ErrorMessage="Required" ForeColor="Red" ControlToValidate="txtUs ername" runat="server" /> </td> </tr> <tr> <td> Password </td> <td> <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" /> </td> <td> <asp:RequiredFieldValidator ErrorMessage="Required" ForeColor="Red" ControlToValidate="txtPa ssword" runat="server" /> </td> </tr> <tr> <td> Confirm Password </td> <td>
<asp:TextBox ID="txtConfirmPassword" runat="server" TextMode="Password" /> </td> <td> <asp:CompareValidator ErrorMessage="Passwords do not match." ForeColor="Red" ControlToCompare="txtPassword" ControlToValidate="txtConfirmPassword" runat="server" /> </td> </tr> <tr> <td> Email </td> <td> <asp:TextBox ID="txtEmail" runat="server" /> </td> <td> <asp:RequiredFieldValidator ErrorMessage="Required" Display="Dynamic" ForeColor="Red" ControlToValidate="txtEmail" runat="server" /> <asp:RegularExpressionValidator runat="server" Display="Dynamic" ValidationExpression="\w+([+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="txtEmail" ForeColor="Red" ErrorMessage="Invalid email address." /> </td> </tr> <tr> <td> </td> <td> <asp:Button Text="Submit" runat="server" OnClick="RegisterUser" /> </td> <td> </td>
</tr> </table>
Stored Procedure to insert the User details The following stored procedure is used to insert the user details such as username, password and email address. The stored procedure first checks whether the username supplied already exists, if yes then it will return negative 1 value. Then the stored procedure checks whether the email address supplied already exists, if yes then it will return negative 2 value. If both username and email address are valid then the record will be inserted and the auto-generated UserId will be returned by the stored procedure. CREATE PROCEDURE [dbo].[Insert_User] @Username NVARCHAR(20), @Password NVARCHAR(20), @Email NVARCHAR(30) AS
BEGIN SET NOCOUNT ON; IF EXISTS(SELECT UserId FROM Users WHERE Username = @Username) BEGIN SELECT -1 -- Username exists. END ELSE IF EXISTS(SELECT UserId FROM Users WHERE Email = @Email) BEGIN SELECT -2 -- Email exists. END ELSE BEGIN INSERT INTO [Users] ([Username] ,[Password] ,[Email] ,[CreatedDate]) VALUES (@Username ,@Password ,@Email ,GETDATE())
Namespaces
VB.Net
Imports System.Data Imports System.Configuration Imports System.Data.SqlClient
Inserting the User Details The following event handler is raised when the submit button is clicked, here the values from the Registration Forms TextBoxes are passed to the stored procedure and the stored procedure is executed. The return value from the stored procedure is captured in a variable and then based on its value appropriate message is displayed using JavaScript Alert message box. C#
protected void RegisterUser(object sender, EventArgs e) { int userId = 0; string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("Insert_User")) { using (SqlDataAdapter sda = new SqlDataAdapter()) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Username", txtUsername.Text.Trim()); cmd.Parameters.AddWithValue("@Password", txtPassword.Text.Trim());
cmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim()); cmd.Connection = con; con.Open(); userId = Convert.ToInt32(cmd.ExecuteScalar()); con.Close(); } } string message = string.Empty; switch (userId) { case -1: message = "Username already exists.\\nPlease choose a different username."; break; case -2: message = "Supplied email address has already been used."; break; default: message = "Registration successful.\\nUser Id: " + userId.ToString(); break; } ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + message + "');", true); } }
VB.Net
Protected Sub RegisterUser(sender As Object, e As EventArgs) Dim userId As Integer = 0 Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionStrin g Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("Insert_User") Using sda As New SqlDataAdapter() cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.AddWithValue("@Username", txtUsername.Text.Trim()) cmd.Parameters.AddWithValue("@Password", txtPassword.Text.Trim()) cmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim()) cmd.Connection = con con.Open() userId = Convert.ToInt32(cmd.ExecuteScalar()) con.Close() End Using End Using Dim message As String = String.Empty Select Case userId Case -1 message = "Username already exists.\nPlease choose a different username." Exit Select Case -2 message = "Supplied email address has already been used." Exit Select Case Else message = "Registration successful.\nUser Id: " + userId.ToString() Exit Select End Select ClientScript.RegisterStartupScript([GetType](), "alert", (Convert.ToString("alert('") & message) + "');", True) End Using End Sub
In this article I will explain how to consume WCF Rest using jQuery AJAX and make JSON calls in ASP.Net. Database For database I am using the Microsofts Northwind Database. You can download the same using the link below
Download Northwind database
Connection String
Below is the connection string to the database which I have placed in the web.config.
<connectionStrings> <add name="constr" connectionString="Data Source = .\SQL2005; Initial Catalog = Northwind; Integrated Security = true"/> </connectionStrings>
Adding and configuring the WCF Service We need to make some configuration changes to the ASP.Net WCF service in order to make it available to jQuery and JavaScript 1. Adding AspNetCompatibilityRequirements Attribute Add the AspNetCompatibilityRequirements attribute for the Service class to make the WCF service behave like an ASP.Net ASMX Web Service and will able to process requests via HTTP in the following way
C#
VB.Net
End Class
2. Adding ASP.Net AJAX endpoint behaviour Add the following ASP.Net AJAX endpoint behaviour in the Web.Config file to enable AJAX calls to the service. C#
<system.serviceModel> <behaviors> <serviceBehaviors> <behaviorname="ServiceBehavior"> <serviceMetadatahttpGetEnabled="true"/> <serviceDebugincludeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors>
<endpointBehaviors> <behaviorname="ServiceAspNetAjaxBehavior"> <enableWebScript /> </behavior> </endpointBehaviors> </behaviors> <serviceHostingEnvironmentaspNetCompatibilityEnabled="true"/> <services> <servicebehaviorConfiguration="ServiceBehavior"name="Service"> <endpointaddress=""binding="webHttpBinding"contract="IService"behaviorConfiguration="ServiceAspNetAja xBehavior"> <identity> <dnsvalue="localhost"/> </identity> </endpoint> <endpointaddress="mex"binding="mexHttpBinding"contract="IMetadataExchange"/> </service> </services> </system.serviceModel>
VB.Net
<system.serviceModel> <behaviors> <serviceBehaviors> <behaviorname="ServiceBehavior"> <serviceMetadatahttpGetEnabled="true"/> <serviceDebugincludeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors>
<endpointBehaviors> <behaviorname="ServiceAspNetAjaxBehavior"> <enableWebScript/> </behavior> </endpointBehaviors> </behaviors> <serviceHostingEnvironmentaspNetCompatibilityEnabled="true"/> <services> <servicename="Service"behaviorConfiguration="ServiceBehavior"> <endpointaddress=""binding="webHttpBinding"contract="Service"behaviorConfiguration="ServiceAspNetAjax Behavior"> <identity> <dnsvalue="localhost"/> </identity> </endpoint> <endpointcontract="IMetadataExchange"binding="mexHttpBinding"address="mex" /> </service> </services> </system.serviceModel>
Add the WebInvoke attribute for the method to specify the Method and the ResponseFormat in the following way
C#
VB.Net
Building the WCF Service Method Now we will build the WCF Service method that the jQuery AJAX will call to get the data from the server. Basically it is a simple function that searches the Customers table of the Northwind database and returns the records of the matched customers. C# IService.cs
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using System.ServiceModel.Web;
[ServiceContract] public interface IService { [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)] string GetCustomers(string prefix); }
Service.cs
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using System.Data.SqlClient; using System.Configuration; using System.Web.Script.Serialization; using System.ServiceModel.Activation;
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class Service : IService { public string GetCustomers(string prefix) { List<object> customers = new List<object>(); using (SqlConnection conn = new SqlConnection()) { conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlCommand cmd = new SqlCommand()) { cmd.CommandText = "select ContactName, CustomerId from Customers where " + "ContactName like @prefix + '%'"; cmd.Parameters.AddWithValue("@prefix", prefix); cmd.Connection = conn; conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader()) { while (sdr.Read()) { customers.Add(new { Id = sdr["CustomerId"], Name = sdr["ContactName"] }); } } conn.Close(); } return (new JavaScriptSerializer().Serialize(customers)); } } }
VB.Net Service.vb
Imports System.Collections.Generic Imports System.Linq Imports System.Runtime.Serialization Imports System.ServiceModel Imports System.Text Imports System.Data.SqlClient Imports System.Configuration Imports System.Web.Script.Serialization Imports System.ServiceModel.Activation Imports System.ServiceModel.Web
Imports System.Web.Script.Services
<ServiceContract()> _ <AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _ Public Class Service <OperationContract()> _ <WebInvoke(Method:="POST", ResponseFormat:=WebMessageFormat.Json)> _ Public Function GetCustomers(ByVal prefix As String) As String Dim customers As New List(Of Object)() Using conn As New SqlConnection() conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString Using cmd As New SqlCommand() cmd.CommandText = "select ContactName, CustomerId from Customers where " & _ "ContactName like @prefix + '%'" cmd.Parameters.AddWithValue("@prefix", prefix) cmd.Connection = conn conn.Open() Using sdr As SqlDataReader = cmd.ExecuteReader() While sdr.Read() customers.Add(New With { _ Key .Id = sdr("CustomerId"), _ Key .Name = sdr("ContactName") _ }) End While End Using conn.Close() End Using Return (New JavaScriptSerializer().Serialize(customers)) End Using
Explanation: Above I am accepting a parameter prefix from the client side jQuery AJAX function. This parameter is used to search for the customers in the Customers table of the Northwind Database. The returned results are added to a generic list of objects which is later serialized to a JSON string using JavaScriptSerializer.
Client Side AJAX JSON Call using jQuery Below is the HTML Mark up of client web page that will access the ASP.Net AJAX WCF service that we created. It simply calls the ASP.Net AJAX WCF service along with the method name and the returned results are displayed.
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> <script type = "text/javascript"> $("#search").live("click", function () { $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: '<%=ResolveUrl("~/Services/Service.svc/GetCustomers") %>', data: '{"prefix": "' + $("#prefix").val() + '"}', processData: false, dataType: "json", success: function (response) { var customers = eval(response.d); var html = ""; $.each(customers, function () { html += "<span>Name: " + this.Name + " Id: " + this.Id + "</span><br />"; });
$("#results").html(html == "" ? "No results" : html); }, error: function (a, b, c) { alert(a.responseText); } }); }); </script> </head> <body> <form id="form1" runat="server"> <input type = "text" id = "prefix" /> <input id = "search" type = "button" value = "Search" /> <div id = "results"></div> </form> </body> </html>
Explanation: On the click of the button search an AJAX JSON call is made to the ASP.Net AJAX WCF service. The value of the parameter prefix is picked from the textbox prefix. The results returned from the ASP.Net AJAX WCF service are converted to JSON Array. Then a jQuery loop is executed over the array to make it and the results are displayed in a DIV as show in the following screenshot
Screenshot
Downloads You can download the complete working source code in C# and VB.Net using the download link provided below.
In this article I will explain how to set MaxLength for Multiline TextBox in ASP.Net using jQuery. By default the MaxLength property does not work for Multiline TextBox and hence I have created a jQuery Plugin which sets MaxLength for ASP.Net Multiline TextBox and also displays the character count as text is typed.
Implementing the jQuery MaxLength Plugin for ASP.Net MultiLine TextBox (TextArea)
Below you will notice the implementation of the jQuery MaxLength plugin. The jQuery MaxLength plugin has the following required and optional parameters 1. MaxLength (required) Integer value indicating the Maximum character length limit. 2. CharacterCountControl (optional) By default the plugin will display character count below the TextArea, but user has option to explicitly specify the Character Count Control. Note: The character count control can only HTML SPAN or DIV. 3. DisplayCharacterCount (optional) Default true. If set to false the Character counting will be disabled.
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">script> <script type="text/javascript" src="MaxLength.min.js">script> <script type="text/javascript"> $(function () { //Normal Configuration $("[id*=TextBox1]").MaxLength({ MaxLength: 10 });
//Specifying the Character Count control explicitly $("[id*=TextBox2]").MaxLength( { MaxLength: 15, CharacterCountControl: $('#counter') });
}); }); script> head> <body> <form id="form1" runat="server"> <div id="counter"> div> <asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" Width="300" Height="100" Text="Mudassar Khan">asp:TextBox> <br /> <br /> <asp:TextBox ID="TextBox2" runat="server" TextMode="MultiLine" Width="300" Height="100">asp:TextBo x> <br /> <br /> <asp:TextBox ID="TextBox3" runat="server" TextMode="MultiLine" Width="300" Height="100">asp:TextBo x> form> body> html>
974 Views
In this article Ill explain how to bind CheckBoxList Control from Database in ASP.Net using C# and VB.Net.
Database Design I created a new database called as dbHobbies with a table called as Hobbies which has the following structure
Connection String Once the database is ready you can create the connection string that will be used to connect to the database. <add name=" constr"connectionString="Data Source = .\SQLExpress; Initial Catalog = dbHobbies; Integrated Security = true"/>
HTML Markup Below is the HTML Markup of the ASP.net web page. Hobbies: <asp:CheckBoxList ID="chkHobbies" runat="server"> </asp:CheckBoxList> <br /> <asp:Button ID="btnUpdate" runat="server" Text="Button" OnClick = "UpdateHobbies" />
As you can see I have added a CheckBoxList and a Button that will allow the user to update the selections in the database. The screenshot below describes how the User Interface looks
Populating the CheckBoxList from Database The following method is used to populate the Hobbies CheckBoxList from the SQL Server Database C# private void PopulateHobbies() { using (SqlConnection conn = new SqlConnection()) { conn.ConnectionString = ConfigurationManager .ConnectionStrings["constr"].ConnectionString; using (SqlCommand cmd = new SqlCommand()) { cmd.CommandText = "select * from hobbies";
cmd.Connection = conn; conn.Open(); using (SqlDataReader sdr = cmd.ExecuteReader()) { while (sdr.Read()) { ListItem item = new ListItem(); item.Text = sdr["Hobby"].ToString(); item.Value = sdr["HobbyId"].ToString(); item.Selected = Convert.ToBoolean(sdr["IsSelected"]); chkHobbies.Items.Add(item); } } conn.Close(); } } }
VB.Net Private Sub PopulateHobbies() Using conn As New SqlConnection() conn.ConnectionString = ConfigurationManager _ .ConnectionStrings("constr").ConnectionString() Using cmd As New SqlCommand() cmd.CommandText = "select * from hobbies" cmd.Connection = conn conn.Open() Using sdr As SqlDataReader = cmd.ExecuteReader() While sdr.Read() Dim item As New ListItem()
item.Text = sdr("Hobby").ToString() item.Value = sdr("HobbyId").ToString() item.Selected = Convert.ToBoolean(sdr("IsSelected")) chkHobbies.Items.Add(item) End While End Using conn.Close() End Using End Using End Sub
The above method is called up in the page load event in the following way C# protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { this.PopulateHobbies(); } }
VB.Net Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.L oad If Not IsPostBack Then Me.PopulateHobbies() End If End Sub
Saving the Selections in Database The following method is called up on the Submit Button Click event and is used to save the user selections to the database C# protected void UpdateHobbies(object sender, EventArgs e) { using (SqlConnection conn = new SqlConnection()) { conn.ConnectionString = ConfigurationManager .ConnectionStrings["constr"].ConnectionString; using (SqlCommand cmd = new SqlCommand()) { cmd.CommandText = "update hobbies set IsSelected = @IsSelected" + " where HobbyId=@HobbyId"; cmd.Connection = conn; conn.Open(); foreach (ListItem item in chkHobbies.Items) { cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@IsSelected", item.Selected); cmd.Parameters.AddWithValue("@HobbyId", item.Value); cmd.ExecuteNonQuery(); } conn.Close(); } } }
Using conn As New SqlConnection() conn.ConnectionString = ConfigurationManager _ .ConnectionStrings("constr").ConnectionString Using cmd As New SqlCommand() cmd.CommandText = "update hobbies set IsSelected = " & _ "@IsSelected where HobbyId=@HobbyId" cmd.Connection = conn conn.Open() For Each item As ListItem In chkHobbies.Items cmd.Parameters.Clear() cmd.Parameters.AddWithValue("@IsSelected", item.Selected) cmd.Parameters.AddWithValue("@HobbyId", item.Value) cmd.ExecuteNonQuery() Next conn.Close() End Using End Using End Sub
In this article I will explain how to search GridView records (data) on TextBox KeyPress event using jQuery in ASP.Net. In order to search GridView records (data) on TextBox KeyPress event, I am making use of jQuery QuickSearch Plugin which dynamically searches the GridView cells and filters out the unwanted rows and displays only the records (data) that matches the input search term.
HTML Markup The HTML Markup consists of an ASP.Net GridView with BoundField columns. I have specified OnDataBound event of the GridView to dynamically add a row with TextBoxes for searching records in each column of GridView.
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White" runat="server" AutoGenerateColumns="false" OnDataBound="OnDataBound"> <Columns> <asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="30" /> <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="100" /> <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="100" /> </Columns> </asp:GridView>
VB.Net
Imports System.Data
I have created a dynamic DataTable with some dummy data and it has been bind to the GridView control in Page Load event. You can learn more about this technique in my article Create DataTable dynamically and bind to GridView in ASP.Net.
C#
protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)), new DataColumn("Name", typeof(string)), new DataColumn("Country",typeof(string)) }); dt.Rows.Add(1, "John Hammond", "United States"); dt.Rows.Add(2, "Mudassar Khan", "India"); dt.Rows.Add(3, "Suzanne Mathews", "France"); dt.Rows.Add(4, "Robert Schidner", "Russia"); GridView1.DataSource = dt; GridView1.DataBind(); } }
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load If Not Me.IsPostBack Then Dim dt As New DataTable() dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id", GetType(Integer)), New DataColumn("Name",GetType(String)), New DataColum n("Country", GetType(String))})
dt.Rows.Add(1, "John Hammond", "United States") dt.Rows.Add(2, "Mudassar Khan", "India") dt.Rows.Add(3, "Suzanne Mathews", "France") dt.Rows.Add(4, "Robert Schidner", "Russia") GridView1.DataSource = dt GridView1.DataBind() End If End Sub
Adding a Row of TextBox for Searching Data Inside the OnDataBound event handler, I have created a new GridView Header Row with a TextBox in its each Cell and then added this row to the GridView. These TextBoxes will be used to search the respective GridView column on TextBox KeyPress event. You will notice that the CssClass property is set for each TextBox with value search_textbox, this has been done to apply the jQuery QuickSearch plugin client side using the jQuery CSS class selector. C#
protected void OnDataBound(object sender, EventArgs e) { GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal); for (int i = 0; i < GridView1.Columns.Count; i++) { TableHeaderCell cell = new TableHeaderCell(); TextBox txtSearch = new TextBox(); txtSearch.Attributes["placeholder"] = GridView1.Columns[i].HeaderText; txtSearch.CssClass = "search_textbox"; cell.Controls.Add(txtSearch); row.Controls.Add(cell); } GridView1.HeaderRow.Parent.Controls.AddAt(1, row);
VB.Net
Protected Sub OnDataBound(sender As Object, e As EventArgs) Dim row As New GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal) For i As Integer = 0 To GridView1.Columns.Count - 1 Dim cell As New TableHeaderCell() Dim txtSearch As New TextBox() txtSearch.Attributes("placeholder") = GridView1.Columns(i).HeaderText txtSearch.CssClass = "search_textbox" cell.Controls.Add(txtSearch) row.Controls.Add(cell) Next GridView1.HeaderRow.Parent.Controls.AddAt(1, row) End Sub
Applying the jQuery QuickSearch Plugin The jQuery QuickSearch Plugin is applied using the jQuery CSS class selector for each TextBox inside the GridView Header Row. The jQuery QuickSearch Plugin is included in the attached sample code. You can also download it using the following URL. Download jQuery QuickSearch Plugin
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript" src="quicksearch.js"></script> <script type="text/javascript"> $(function () { $('.search_textbox').each(function (i) { $(this).quicksearch("[id*=GridView1] tr:not(:has(th))", { 'testQuery': function (query, txt, row) { return $(row).children(":eq(" + i + ")").text().toLowerCase().indexOf(query[0].toLowerCase()) != -1; } }); }); }); </script>
ASP.Net GridView
Here Mudassar Ahmed Khan has explained how to display the GridViews Selected Row data in TextBoxes placed outside GridView in ASP.Net using C# and VB.Net. Inside the GridView SelectedIndexChanged event handler, the TextBoxes outside GridView will be populated using the data fetched from the GridViews Selected Row.
Download View Demo
In this article I will explain how to display the GridViews Selected Row data in TextBoxes placed outside GridView in ASP.Net using C# and VB.Net. Inside the GridView SelectedIndexChanged event handler, the TextBoxes outside GridView will be populated using the data fetched from the GridViews Selected Row.
HTML Markup The HTML Markup consists of an ASP.Net GridView and TextBoxes which will be used to display the data from the Selected Row. For the GridView, I have specified the OnSelectedIndexChanged event handler.
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White" runat="server" AutoGenerateColumns="false" OnSelectedIndexChanged = "OnSelectedIndexChanged"> <Columns> <asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="30" /> <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" /> <asp:TemplateField HeaderText="Country"> <ItemTemplate> <asp:Label ID="lblCountry" Text='<%# Eval("Country") %>' runat="server" /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <asp:LinkButton Text="Select" ID="lnkSelect" runat="server" CommandName="Select" /> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> <br /> <table cellpadding="0" cellspacing="0"> <tr> <td style="width: 100px">
Id </td> <td> <asp:TextBox ID="txtId" runat="server" /> </td> </tr> <tr> <td> </td> </tr> <tr> <td> Name </td> <td> <asp:TextBox ID="txtName" runat="server" /> </td> </tr> <tr> <td> </td> </tr> <tr> <td> Country </td>
VB.Net
Imports System.Data
Binding the GridView control I have created a dynamic DataTable with some dummy data and it has been bind to the GridView control in Page Load event. Note: You can learn more about this technique in my article Create DataTable dynamically and bind to GridView in ASP.Net.
C#
protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)), new DataColumn("Name", typeof(string)),
new DataColumn("Country",typeof(string)) }); dt.Rows.Add(1, "John Hammond", "United States"); dt.Rows.Add(2, "Mudassar Khan", "India"); dt.Rows.Add(3, "Suzanne Mathews", "France"); dt.Rows.Add(4, "Robert Schidner", "Russia"); GridView1.DataSource = dt; GridView1.DataBind(); } }
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load If Not Me.IsPostBack Then Dim dt As New DataTable() dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id", GetType(Integer)), New DataColumn("Name",GetType(String)), New DataColum n("Country", GetType(String))}) dt.Rows.Add(1, "John Hammond", "United States") dt.Rows.Add(2, "Mudassar Khan", "India") dt.Rows.Add(3, "Suzanne Mathews", "France") dt.Rows.Add(4, "Robert Schidner", "Russia") GridView1.DataSource = dt GridView1.DataBind() End If End Sub
Display GridView Selected Row data in TextBox outside GridView in ASP.Net using the SelectedIndexChanged event
Inside the SelectedIndexChanged event handler of the GridView control, the values from the BoundField and TemplateField columns are extracted and displayed in the respective TextBoxes placed outside the GridView control. C#
protected void OnSelectedIndexChanged(object sender, EventArgs e) { GridViewRow row = GridView1.SelectedRow; txtId.Text = row.Cells[0].Text; txtName.Text = row.Cells[1].Text; txtCountry.Text = (row.FindControl("lblCountry") as Label).Text; }
VB.Net
Protected Sub OnSelectedIndexChanged(sender As Object, e As EventArgs) Dim row As GridViewRow = GridView1.SelectedRow txtId.Text = row.Cells(0).Text txtName.Text = row.Cells(1).Text txtCountry.Text = TryCast(row.FindControl("lblCountry"), Label).Text End Sub
In this article I will explain how to display the GridView Selected Row Details in ASP.Net AJAX ModalPopupExtender Modal Popup using C# and VB.Net. Inside the GridView SelectedIndexChanged event handler, the GridView Selected Row details will be fetched and displayed in the ASP.Net AJAX ModalPopupExtender Modal Popup.
HTML Markup The HTML Markup consists of an ASP.Net GridView and ASP.Net AJAX ModalPopupExtender Modal Popup. For the GridView, I have specified theOnSelectedIndexChanged event handler.
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White" runat="server" AutoGenerateColumns="false" OnSelectedIndexChanged="OnSelectedIndexChanged"> <Columns> <asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="30" /> <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" /> <asp:TemplateField> <ItemTemplate> <asp:Label ID="lblCountry" Text='<%# Eval("Country") %>' runat="server" /> </ItemTemplate> </asp:TemplateField> <asp:ButtonField Text="Select" CommandName="Select" /> </Columns> </asp:GridView> <asp:LinkButton Text="" ID = "lnkFake" runat="server" />
<cc1:ModalPopupExtender ID="mpe" runat="server" PopupControlID="pnlPopup" TargetControlID="lnkFake " CancelControlID="btnClose" BackgroundCssClass="modalBackground"> </cc1:ModalPopupExtender> <asp:Panel ID="pnlPopup" runat="server" CssClass="modalPopup" Style="display: none"> <div class="header"> Details </div> <div class="body"> <table border="0" cellpadding="0" cellspacing="0"> <tr> <td style = "width:60px"> <b>Id: </b> </td> <td> <asp:Label ID="lblId" runat="server" /> </td> </tr> <tr> <td> <b>Name: </b> </td> <td> <asp:Label ID="lblName" runat="server" /> </td> </tr> <tr> <td> <b>Country: </b> </td>
<td> <asp:Label ID="lblCountry" runat="server" /> </td> </tr> </table> </div> <div class="footer" align="right"> <asp:Button ID="btnClose" runat="server" Text="Close" CssClass="button" /> </div> </asp:Panel>
VB.Net
Imports System.Data
Binding the GridView control I have created a dynamic DataTable with some dummy data and it has been bind to the GridView control in Page Load event. Note: You can learn more about this technique in my article Create DataTable dynamically and bind to GridView in ASP.Net.
C#
protected void Page_Load(object sender, EventArgs e) {
if (!this.IsPostBack) { DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)), new DataColumn("Name", typeof(string)), new DataColumn("Country",typeof(string)) }); dt.Rows.Add(1, "John Hammond", "United States"); dt.Rows.Add(2, "Mudassar Khan", "India"); dt.Rows.Add(3, "Suzanne Mathews", "France"); dt.Rows.Add(4, "Robert Schidner", "Russia"); GridView1.DataSource = dt; GridView1.DataBind(); } }
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load If Not Me.IsPostBack Then Dim dt As New DataTable() dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id", GetType(Integer)), New DataColumn("Name", GetType(String)), New DataColu mn("Country", GetType(String))}) dt.Rows.Add(1, "John Hammond", "United States") dt.Rows.Add(2, "Mudassar Khan", "India") dt.Rows.Add(3, "Suzanne Mathews", "France") dt.Rows.Add(4, "Robert Schidner", "Russia") GridView1.DataSource = dt GridView1.DataBind() End If End Sub
Displaying GridView Selected Row Details in AJAX ModalPopupExtender in ASP.Net using the SelectedIndexChanged event Inside the SelectedIndexChanged event handler of the GridView control, the values from the BoundField and TemplateField columns are extracted and displayed in Label controls placed inside the ModalPopupExtenders associated Panel control and then the ModalPopupExtender is shown. C#
protected void OnSelectedIndexChanged(object sender, EventArgs e) { lblId.Text = GridView1.SelectedRow.Cells[0].Text; lblName.Text = GridView1.SelectedRow.Cells[1].Text; lblCountry.Text = (GridView1.SelectedRow.FindControl("lblCountry") as Label).Text; mpe.Show(); }
VB.Net
Protected Sub OnSelectedIndexChanged(sender As Object, e As EventArgs) lblId.Text = GridView1.SelectedRow.Cells(0).Text lblName.Text = GridView1.SelectedRow.Cells(1).Text lblCountry.Text = TryCast(GridView1.SelectedRow.FindControl("lblCountry"), Label).Text mpe.Show() End Sub
Modal Popup CSS styles The following CSS styles used for styling the ASP.Net AJAX ModalPopupExtender.
<style type="text/css"> body { font-family: Arial; font-size: 10pt;
} .modalBackground { background-color: Black; filter: alpha(opacity=40); opacity: 0.4; } .modalPopup { background-color: #FFFFFF; width: 300px; border: 3px solid #0DA9D0; } .modalPopup .header { background-color: #2FBDF1; height: 30px; color: White; line-height: 30px; text-align: center; font-weight: bold; } .modalPopup .body { min-height: 50px; line-height: 30px; text-align: center; padding:5px } .modalPopup .footer
{ padding: 3px; } .modalPopup .button { height: 23px; color: White; line-height: 23px; text-align: center; font-weight: bold; cursor: pointer; background-color: #9F9F9F; border: 1px solid #5C5C5C; } .modalPopup td { text-align:left; } </style>
How to add reference of Web Service (ASMX) in ASP.Net using Visual Studio
19 Dec 2013 Mudassar Khan 1 Comments ASP.Net
Here Mudassar Ahmed Khan has explained how to add reference of a Web Service (ASMX) in your project in Visual Studio 2010 / 2012 / 2013 and use it.
Download
1349 Views
In this short article I will explain how to add reference of a Web Service (ASMX) in your project in Visual Studio 2010 / 2012 / 2013 and use it.
Note: For illustration purpose, I am making use of the Free Web Service used for finding the geographical location of an IP Address.
http://www.webservicex.net/geoipservice.asmx
Adding Reference of the Web Service in Visual Studio 1. Right click the project in Solution Explorer and choose Add Service Reference option from the context menu.
2. Now in the Add Service Reference Dialog you need to click on the Advanced button.
3. In the Service Reference Settings Dialog you need to click on Add Web Reference button.
4. Now in the Add Web Reference Dialog you need to add the URL of the Web Service and click the Green Go button to discover it. Once the Web Service is discovered, give its reference an appropriate name using the Web Reference Name TextBox and click on Add Reference button.
5. Finally you will notice the Web Service Reference has been added to your project.
Accessing the Web Service and its Methods Using the Web Reference Name given in step #4, you can access the Web Service and its methods. HTML Markup
Fetching the location from the Web Service Inside the Button click event handler, an object of GeoIPService is created and then IP Address is passed as parameter to the GetGeoIP method which returns the name of the Country to which the IP address belongs.It is then displayed using the Label control. C#
protected void GetCountry(object sender, EventArgs e) { GeoService.GeoIPService service = new GeoService.GeoIPService(); GeoService.GeoIP output = service.GetGeoIP(txtIPAddress.Text.Trim()); lblCountry.Text = "Country: " + output.CountryName; }
VB.Net
Protected Sub GetCountry(sender As Object, e As EventArgs) Dim service As New GeoService.GeoIPService() Dim output As GeoService.GeoIP = service.GetGeoIP(txtIPAddress.Text.Trim()) lblCountry.Text = "Country: " + output.CountryName End Sub
Display GridView Row details inside jQuery Dialog Modal Popup in ASP.Net
In this short article I will explain how to display GridView Row Details in jQuery UI Dialog Modal Popup in ASP.Net.
HTML Markup The HTML Markup consists of an ASP.Net GridView and an HTML DIV which will be used to display the jQuery UI Dialog Modal Popup. I have set the ItemStyle-CssClass property for each GridView Column so that using jQuery we can access the particular cell of the GridView Row.
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White" runat="server" AutoGenerateColumns="false"> <Columns> <asp:BoundField DataField="Id" ItemStyle-CssClass="Id" HeaderText="Id" ItemStyle-Width="30" /> <asp:BoundField DataField="Name" ItemStyle-CssClass="Name" HeaderText="Name" ItemStyleWidth="150" /> <asp:BoundField DataField="Description" ItemStyle-CssClass="Description" HeaderText="Description" ItemStyle-Width="150" /> <asp:TemplateField> <ItemTemplate> <asp:LinkButton Text="View" ID="lnkView" runat="server" /> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView>
<div id="dialog" style="display: none"> <b>Id:</b> <span id="id"></span> <br /> <b>Name:</b> <span id="name"></span> <br /> <b>Description:</b> <span id="description"></span> </div>
VB.Net
Imports System.Data
Binding the GridView control I have created a dynamic DataTable with some dummy data and it has been bind to the GridView control in Page Load event. Note: You can learn more about this technique in my article Create DataTable dynamically and bind to GridView in ASP.Net C#
protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)), new DataColumn("Description",typeof(string)) }); dt.Rows.Add(1, "John Hammond", "Works as a scientist in USA."); dt.Rows.Add(2, "Mudassar Khan", "ASP.Net programmer and consultant in India."); dt.Rows.Add(3, "Suzanne Mathews", "Content Writer in France."); dt.Rows.Add(4, "Robert Schidner", "Wild life photographer in Russia."); GridView1.DataSource = dt; GridView1.DataBind(); } }
Displaying GridView Row details in jQuery UI Dialog Modal Popup on Button click I have attached a jQuery click event handler to the LinkButton. When the LinkButton is clicked, the values are fetched from the GridView cells of the selected row using their respective CSS class names and are set inside the HTML SPAN tag within the jQuery Dialog DIV. Once the values are set the jQuery Dialog is displayed. Note: You can learn more about jQuery Dialog in my article Simple jQuery Modal Popup Window Example in ASP.Net
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script> <link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/start/jquery-ui.css" rel="stylesheet" type="text/css" /> <script type="text/javascript"> $(document).on("click", "[id*=lnkView]", function () { $("#id").html($(".Id", $(this).closest("tr")).html()); $("#name").html($(".Name", $(this).closest("tr")).html()); $("#description").html($(".Description", $(this).closest("tr")).html()); $("#dialog").dialog({ title: "View Details",
buttons: { Ok: function () { $(this).dialog('close'); } }, modal: true }); return false; }); </script>
In this article I will explain how to bind custom WebUserControl inside ASP.Net GridView controls TemplateField ItemTemplate using C# and VB.Net. I will also explain how to pass data to WebUserControl and also find, access and get value from WebUserControl inside GridView control.
HTML Markup Page The Page markup consists of an ASP.Net GridView with a TemplateField column inside which theres a WebUserControl for displaying country.
<%@ Register Src="~/UserControls/Country.ascx" TagName="Country" TagPrefix="uc" %> <!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 runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White" runat="server" AutoGenerateColumns="false"> <Columns> <asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="30" /> <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" /> <asp:TemplateField HeaderText="Country"> <ItemTemplate> <uc:Country ID="ucCountry" runat="server" Country='<%# Eval("Country") %>' /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate>
<asp:Button Text="Get Details" runat="server" OnClick="GetDetails" /> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </form> </body> </html>
WebUserControl The following WebUserControl used inside the GridView control discussed above. Its markup consists of an ASP.Net Label control for displaying content.
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Country.ascx.cs" Inherits="UserControls_Country " %> <asp:Label ID = "lblCountry" Text="" runat="server" />
VB.Net
Imports System.Data
Binding the GridView control I have created a dynamic DataTable with some dummy data and it has been bind to the GridView control in Page Load event. Note: You can learn more about this technique in my article Create DataTable dynamically and bind to GridView in ASP.Net.
C#
protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)), new DataColumn("Name", typeof(string)), new DataColumn("Country",typeof(string)) }); dt.Rows.Add(1, "John Hammond", "United States"); dt.Rows.Add(2, "Mudassar Khan", "India"); dt.Rows.Add(3, "Suzanne Mathews", "France"); dt.Rows.Add(4, "Robert Schidner", "Russia"); GridView1.DataSource = dt; GridView1.DataBind(); } }
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load If Not Me.IsPostBack Then Dim dt As New DataTable() dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id", GetType(Integer)), New DataColumn("Name", GetType(String)), New DataColu mn("Country", GetType(String))}) dt.Rows.Add(1, "John Hammond", "United States") dt.Rows.Add(2, "Mudassar Khan", "India") dt.Rows.Add(3, "Suzanne Mathews", "France") dt.Rows.Add(4, "Robert Schidner", "Russia") GridView1.DataSource = dt GridView1.DataBind()
Property to set and get data to and from WebUserControl Inside the WebUserControl I have made use of Public Property which will be used to set and get the Text of the Country Label. C#
public string Country { get { return lblCountry.Text; } set { lblCountry.Text = value; } }
VB.Net
Public Property Country() As String Get Return lblCountry.Text End Get Set(value As String) lblCountry.Text = value End Set End Property
This same property is used in the GridView ItemTemplate and its value is set using Eval function as shown below
<uc:Country ID="ucCountry" runat="server" Country='<%# Eval("Country") %>' />
Find and access WebUserControl inside GridViewRow Below is the click event handler for the Button inside GridView, here I have fetched details from the GridView Cells and the Country WebUserControl using its Public property discussed earlier. C#
protected void GetDetails(object sender, EventArgs e) { GridViewRow row = (sender as Button).NamingContainer as GridViewRow; string id = "Id: " + row.Cells[0].Text; string name = "Name: " + row.Cells[1].Text; string country = "Country: " + (row.FindControl("ucCountry") as UserControls_Country).Country; string message = string.Format("{0}\\n{1}\\n{2}", id, name, country); ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + message + "');", true); }
VB.Net
Protected Sub GetDetails(sender As Object, e As EventArgs) Dim row As GridViewRow = TryCast(TryCast(sender, Button).NamingContainer, GridViewRow ) Dim id As String = "Id: " + row.Cells(0).Text Dim name As String = "Name: " + row.Cells(1).Text Dim country As String = "Country: " + TryCast(row.FindControl("ucCountry"), UserControls_Country).Country Dim message As String = String.Format("{0}\n{1}\n{2}", id, name, country) ClientScript.RegisterStartupScript(Me.[GetType](), "alert", (Convert.ToString("alert('") & message) + "');", True) End Sub
Load images while scrolling page down with jQuery AJAX in ASP.Net
17 Dec 2013 Mudassar Khan 1 Comments 2561 Views
In this article I will explain how to dynamically load images from database along with other information when is page scrolling down using DataList control in ASP.Net. This article uses very similar concept used in my article
Load data while Scrolling Page down with jQuery AJAX and ASP.Net
Database Below is the design of the table that will store the URL of the image files along with some other information.
HTML Markup The HTML Markup consists of an ASP.Net DataList control which will be used as a Template to recreate items when page is scrolled.
<asp:DataList ID="dlImages" runat="server" RepeatLayout="Table" RepeatColumns="3" CellPadding="2" CellSpacing="20"> <ItemTemplate> <table class="item" cellpadding="0" cellspacing="0" border="0"> <tr> <td align="center" class="header"> <span class="name"> <%# Eval("Name") %></span> </td> </tr> <tr> <td align="center" class="body"> <img class="image" src='<%# Eval("Url") %>' alt="" /> </td> </tr> <tr> <td align="center"> Photo by <a href="http://www.flickr.com/photos/pearlshelf/">Pearl Photo</a> </td> </tr> <tr> <td class="footer" align="center">
<a href='<%# Eval("Url") %>' target="_blank" class="button">View</a> <input type="hidden" class="is_used" value="0" /> </td> </tr> </table> </ItemTemplate> </asp:DataList>
Implement Pagination in SQL Server Stored Procedure Since we need to get data on demand i.e. in parts we need to have pagination capability in our stored procedure so that we can fetch records based on page index or page number. This stored procedure returns Total Page Count as OUPUT parameter; this count will help notify jQuery that it should stop making AJAX calls as the all the data has been fetched. CREATE PROCEDURE [dbo].[GetImagesPageWise] @PageIndex INT = 1 ,@PageSize INT = 3 ,@PageCount INT OUTPUT AS BEGIN SET NOCOUNT ON;
SELECT ROW_NUMBER() OVER ( ORDER BY [Id] ASC )AS RowNumber ,Id ,Name ,Url INTO #Results FROM [Images]
SET @PageCount = CEILING(CAST(@RecordCount AS DECIMAL(10, 2)) / CAST(@Page Size AS DECIMAL(10, 2))) PRINT @PageCount
SELECT * FROM #Results WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex 1) * @PageSize + 1) + @PageSize) - 1
Binding a dummy record to the DataList In the Page Load event, I am binding a dummy record to the DataList control. This is very necessary as jQuery needs some HTML content which it can replicate the data fetched via jQuery AJAX. C#
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { this.BindDummyItem(); } }
dummy.Columns.Add("Id"); dummy.Columns.Add("Name"); dummy.Columns.Add("Url"); int count = dlImages.RepeatColumns == 0 ? 1 : dlImages.RepeatColumns; for (int i = 0; i < count; i++) { dummy.Rows.Add(); } dlImages.DataSource = dummy; dlImages.DataBind(); }
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load If Not IsPostBack Then Me.BindDummyItem() End If End Sub
Private Sub BindDummyItem() Dim dummy As New DataTable() dummy.Columns.Add("Id") dummy.Columns.Add("Name") dummy.Columns.Add("Url") Dim count As Integer = If(dlImages.RepeatColumns = 0, 1, dlImages.RepeatColumns) For i As Integer = 0 To count - 1 dummy.Rows.Add() Next dlImages.DataSource = dummy dlImages.DataBind()
End Sub
WebMethod to handle AJAX calls from jQuery and fetch The following web method handles the jQuery AJAX calls when page is scrolled down. It simply fetches the records from the database and the returns the XML to the client. Along with the data, the count of the total pages is also sent so that the client side function is informed whether the last page has been fetched. Note: You need to set PageSize as multiple of the number of items displayed in one row, for example here I am setting PageSize as 9 and I am displaying 3 items per row, so for example if you have 5 items per row then you must have page size as either 5, 10, 15 and so on depending on size of the item and image. C#
[WebMethod] public static string GetImages(int pageIndex) { return GetImagesData(pageIndex).GetXml(); }
public static DataSet GetImagesData(int pageIndex) { int pageSize = 9; string query = "[GetImagesPageWise]"; SqlCommand cmd = new SqlCommand(query); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@PageIndex", pageIndex); cmd.Parameters.AddWithValue("@PageSize", pageSize); cmd.Parameters.Add("@PageCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output; return GetData(cmd); }
private static DataSet GetData(SqlCommand cmd) { string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(strConnString)) { using (SqlDataAdapter sda = new SqlDataAdapter()) { cmd.Connection = con; sda.SelectCommand = cmd; using (DataSet ds = new DataSet()) { sda.Fill(ds, "Images"); DataTable dt = new DataTable("PageCount"); dt.Columns.Add("PageCount"); dt.Rows.Add(); dt.Rows[0][0] = cmd.Parameters["@PageCount"].Value; ds.Tables.Add(dt); return ds; } } } }
VB.Net
<WebMethod()> _ Public Shared Function GetImages(pageIndex As Integer) As String Return GetImagesData(pageIndex).GetXml() End Function
Public Shared Function GetImagesData(pageIndex As Integer) As DataSet Dim pageSize As Integer = 9 Dim query As String = "[GetImagesPageWise]" Dim cmd As New SqlCommand(query) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.AddWithValue("@PageIndex", pageIndex) cmd.Parameters.AddWithValue("@PageSize", pageSize) cmd.Parameters.Add("@PageCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output Return GetData(cmd) End Function
Private Shared Function GetData(cmd As SqlCommand) As DataSet Dim strConnString As String = ConfigurationManager.ConnectionStrings("constr").Connecti onString Using con As New SqlConnection(strConnString) Using sda As New SqlDataAdapter() cmd.Connection = con sda.SelectCommand = cmd Using ds As New DataSet() sda.Fill(ds, "Images") Dim dt As New DataTable("PageCount") dt.Columns.Add("PageCount") dt.Rows.Add() dt.Rows(0)(0) = cmd.Parameters("@PageCount").Value ds.Tables.Add(dt) Return ds End Using End Using End Using End Function
jQuery AJAX and Client Side implementation Below is the client side implementation where the actual job is done, here I have attached a jQuery scroll event handler to the page. When the page is scrolled a jQuery AJAX call is sent to the server for fetching the records. Inside the Success event handler, the response XML is parsed and the records along with the maximum page count is retrieved. Then based on the DataList RepeatColumns property value, the DataList Items are cloned and appended to the page with the values fetched from the server. C#
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript"> var pageIndex = 0; var pageCount; $(window).scroll(function () { if ($(window).scrollTop() == $(document).height() - $(window).height()) { GetRecords(); } }); $(function () { GetRecords(); }); function GetRecords() { pageIndex++; if (pageIndex == 1 || pageIndex <= pageCount) { $("#loader").show(); $.ajax({ type: "POST", url: "CS.aspx/GetImages", data: '{pageIndex: ' + pageIndex + '}', contentType: "application/json; charset=utf-8",
dataType: "json", success: OnSuccess, failure: function (response) { alert(response.responseText); }, error: function (response) { alert(response.responseText); } }); } } function OnSuccess(response) { var xmlDoc = $.parseXML(response.d); var xml = $(xmlDoc); pageCount = parseInt(xml.find("PageCount").eq(0).find("PageCount").text()); var images = xml.find("Images"); var repeatColumns = parseInt("<%=dlImages.RepeatColumns == 0 ? 1 : dlImages.RepeatColumns %>"); var rowCount = Math.ceil(images.length / repeatColumns); var j = 0; images.each(function () { var image = $(this); var row = $("[id*=dlImages] .item:last").closest("tr"); if ($(".is_used[value='1']", row).length == repeatColumns) { row = $("[id*=dlImages] tr").eq(0).clone(); $(".is_used", row).val("0"); $(".image", row).attr("src", ""); $(".button", row).attr("href", ""); $(".loader", row).remove(); $("[id*=dlImages]").append(row);
j = 0; } else { row = $("[id*=dlImages] .item:last").closest("tr"); } var cell = $(".item", row).eq(j); $(".name", cell).html(image.find("Name").text()); $(".button", cell).attr("href", image.find("Url").text()); $(".is_used", cell).attr("value", "1"); var img = $(".image", cell); var loader = $("<img class = 'loader' src = 'loader.gif' />" ); img.after(loader); img.hide(); img.attr("src", image.find("Url").text()); img.load(function () { $(this).parent().find(".loader").remove(); $(this).fadeIn(); }); j++; }); $("[id*=dlImages] .is_used[value='0']").closest(".item").remove(); } </script>
VB.Net
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript"> var pageIndex = 0; var pageCount; $(window).scroll(function () { if ($(window).scrollTop() == $(document).height() - $(window).height()) {
GetRecords(); } }); $(function () { GetRecords(); }); function GetRecords() { pageIndex++; if (pageIndex == 1 || pageIndex <= pageCount) { $("#loader").show(); $.ajax({ type: "POST", url: "VB.aspx/GetImages", data: '{pageIndex: ' + pageIndex + '}', contentType: "application/json; charset=utf-8", dataType: "json", success: OnSuccess, failure: function (response) { alert(response.responseText); }, error: function (response) { alert(response.responseText); } }); } } function OnSuccess(response) { var xmlDoc = $.parseXML(response.d); var xml = $(xmlDoc); pageCount = parseInt(xml.find("PageCount").eq(0).find("PageCount").text());
var images = xml.find("Images"); var repeatColumns = parseInt("<%=IIf(dlImages.RepeatColumns = 0, 1, dlImages.RepeatColumns) %>"); var rowCount = Math.ceil(images.length / repeatColumns); var j = 0; images.each(function () { var image = $(this); var row = $("[id*=dlImages] .item:last").closest("tr"); if ($(".is_used[value='1']", row).length == repeatColumns) { row = $("[id*=dlImages] tr").eq(0).clone(); $(".is_used", row).val("0"); $(".image", row).attr("src", ""); $(".button", row).attr("href", ""); $(".loader", row).remove(); $("[id*=dlImages]").append(row); j = 0; } else { row = $("[id*=dlImages] .item:last").closest("tr"); } var cell = $(".item", row).eq(j); $(".name", cell).html(image.find("Name").text()); $(".button", cell).attr("href", image.find("Url").text()); $(".is_used", cell).attr("value", "1"); var img = $(".image", cell); var loader = $("<img class = 'loader' src = 'loader.gif' />" ); img.after(loader); img.hide(); img.attr("src", image.find("Url").text()); img.load(function () { $(this).parent().find(".loader").remove();
Find Co-ordinates (Latitude and Longitude) of an Address Location using Google Geocoding API in ASP.Net using C# and VB.Net
09 Dec 2013 Mudassar Khan 0 Comments 1833 Views
ASP.Net Google
In this short code snippet article I will explain how to find the co-ordinates i.e. Latitude and Longitude of an Address Location using Google Maps Geocoding API. The Google Geocoding API accepts address as parameter and returns the Geographical Co-ordinates and other information in XML or JSON format.
Download View Demo
In this short code snippet article I will explain how to find the co-ordinates i.e. Latitude and Longitude of an Address Location using Google Maps Geocoding API. The Google Geocoding API accepts address as parameter and returns the Geographical Co-ordinates and other information in XML or JSON format.
HTML Markup The HTML markup consists of a TextBox and a Button for searching and a GridView control to display the results.
<asp:TextBox ID="txtLocation" runat="server" Text=""></asp:TextBox> <asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="FindCoordinates" /> <br /> <br /> <asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White" runat="server" AutoGenerateColumns="false"> <Columns> <asp:BoundField DataField="Id" HeaderText="Id" /> <asp:BoundField DataField="Address" HeaderText="Address" /> <asp:BoundField DataField="Latitude" HeaderText="Latitude" /> <asp:BoundField DataField="Longitude" HeaderText="Longitude" /> </Columns> </asp:GridView>
Namespaces
VB.Net
Imports System.IO Imports System.Net Imports System.Text Imports System.Data
Making call to Google Geocoding API to fetch Co-ordinates (Latitude and Longitude) of an Address Location in ASP.Net The following click event handler is executed when the Search Button is clicked, the address from the TextBox is passed to the Google Geocoding API Service using WebRequest. The received response is an XML string which is read into a DataSet using StreamReader. Since the XML returned from Google contains information in multiple tables, I have extracted the relevant information and inserted into a DataTable and finally the DataTable is bound to the GridView control. C#
protected void FindCoordinates(object sender, EventArgs e) { string url = "http://maps.google.com/maps/api/geocode/xml?address=" + txtLocation.Text + "&sensor=false"; WebRequest request = WebRequest.Create(url); using (WebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) {
DataSet dsResult = new DataSet(); dsResult.ReadXml(reader); DataTable dtCoordinates = new DataTable(); dtCoordinates.Columns.AddRange(new DataColumn[4] { new DataColumn("Id", typeof(int)), new DataColumn("Address", typeof(string)), new DataColumn("Latitude",typeof(string)), new DataColumn("Longitude",typeof(string)) }); foreach (DataRow row in dsResult.Tables["result"].Rows) { string geometry_id = dsResult.Tables["geometry"].Select("result_id = " + row["result_id"].ToString())[0]["geometry_id"].ToString(); DataRow location = dsResult.Tables["location"].Select("geometry_id = " + geometry_id)[0]; dtCoordinates.Rows.Add(row["result_id"], row["formatted_address"], location["lat"], location["lng"]); } GridView1.DataSource = dtCoordinates; GridView1.DataBind(); } } }
VB.Net
Protected Sub FindCoordinates(sender As Object, e As EventArgs) Dim url As String = "http://maps.google.com/maps/api/geocode/xml?address=" + txtLocation.Text + "&sensor=false" Dim request As WebRequest = WebRequest.Create(url) Using response As WebResponse = DirectCast(request.GetResponse(), HttpWebResponse) Using reader As New StreamReader(response.GetResponseStream(), Encoding.UTF8) Dim dsResult As New DataSet() dsResult.ReadXml(reader)
Dim dtCoordinates As New DataTable() dtCoordinates.Columns.AddRange(New DataColumn(3) {New DataColumn("Id", GetType(Integer)), New DataColumn("Address", GetType(String)), New DataCol umn("Latitude", GetType(String)), New DataColumn("Longitude", GetType(String))}) For Each row As DataRow In dsResult.Tables("result").Rows Dim geometry_id As String = dsResult.Tables("geometry").[Select]("result_id = " + row("result_id").ToString())(0)("geometry_id").ToString() Dim location As DataRow = dsResult.Tables("location").[Select](Convert.ToString("geometry_id = ") & geometry_id)(0) dtCoordinates.Rows.Add(row("result_id"), row("formatted_address"), location("lat"), location("lng")) Next GridView1.DataSource = dtCoordinates GridView1.DataBind() End Using End Using End Sub
Screenshots When the searched location is an exact match only one result is returned.
When the searched location has multiple matches then we get multiple results
Implement Endless Scroll (Infinite Scroll) in ASP.Net GridView using jQuery AJAX
06 Dec 2013 Mudassar Khan 3 Comments 2778 Views
In this article I will explain how to implement Infinite / Endless / Continuous Scroll technique in ASP.Net GridView where database records are fetched dynamically when GridView is scrolled down using jQuery AJAX and Web Methods.
Database For this article I am making use of the Microsofts Northwind database. You can download it using the link below.
Download and configure Northwind Database
HTML Markup The HTML Markup contains an HTML DIV and an ASP.Net GridView control inside it. I have placed GridView inside the HTML DIV so that we can implement scrolling.
<div id="dvGrid" style="height: 250px; overflow: auto; width: 517px"> <asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" CssClass="Grid" Width = "5 00"> <Columns> <asp:BoundField DataField="ContactName" HeaderText = "Customer Name" ItemStyleCssClass="name" ItemStyle-Width="200" HeaderStyle-Width="200" /> <asp:BoundField DataField="City" HeaderText = "City" ItemStyle-CssClass="city" ItemStyleWidth="100" HeaderStyle-Width="100" /> <asp:BoundField DataField="Country" HeaderText = "Country" ItemStyleCssClass="country" ItemStyle-Width="100"HeaderStyle-Width="100" /> <asp:BoundField DataField="PostalCode" HeaderText = "Postal Code" ItemStyleCssClass="postal" ItemStyle-Width="100" HeaderStyle-Width="100" />
Now here you need to consider few important things if you need a proper design layout 1. You need specify the ItemStyle-Width and HeaderStyle-Width to each column of the GridView. Make sure both properties have same value for a specific column. 2. The total of all ItemStyle-Width of all columns must be set as Width of the GridView. 3. Finally the width of the HTML DIV must be Width of the GridView plus 17px. 17px is the width of the scrollbar. Example here 500 + 17 = 517px 4. Set the height of the HTML DIV in such a way that by default it should display a scrollbar.
Note: I have set the property ItemStyle-CssClass for each column in GridView; this is done to identify the columns when the data will be populated using jQuery AJAX
CSS Style for the GridView The following CSS classes are used to provide look and feel for the ASP.Net GridView
<style type="text/css"> .Grid td { background-color: #A1DCF2; color: black; font-size: 10pt; font-family: Arial; line-height: 200%; cursor: pointer; width: 100px; } .Grid th { background-color: #3AC0F2; color: White;
Stored procedure to fetch records on demand when the GridView is scrolled You will need to execute the following stored procedure in the Northwind Database. The objective of creating the following stored procedure is to get records page wise based on Page Index using the customized paging within the database table using ROW_NUMBER() feature of SQL Server.
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROCEDURE [dbo].[GetCustomersPageWise] @PageIndex INT = 1 ,@PageSize INT = 10 ,@PageCount INT OUTPUT AS BEGIN SET NOCOUNT ON; SELECT ROW_NUMBER() OVER ( ORDER BY [CustomerID] ASC )AS RowNumber ,[CustomerID] ,[CompanyName] ,[ContactName] ,[City]
SET @PageCount = CEILING(CAST(@RecordCount AS DECIMAL(10, 2)) / CAST(@PageSize AS DE CIMAL(10, 2))) PRINT @PageCount
SELECT * FROM #Results WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex 1) * @PageSize + 1) + @PageSize) - 1
VB.Net
Binding the ASP.Net GridView Below is the code to bind the GridView using the data fetched from the stored procedure we have created earlier. You will see C#
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { gvCustomers.DataSource = GetCustomersPageWise(1, 10); gvCustomers.DataBind(); } }
public static DataSet GetCustomersPageWise(int pageIndex, int pageSize) { string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(constring)) { using (SqlCommand cmd = new SqlCommand("[GetCustomersPageWise]")) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@PageIndex", pageIndex); cmd.Parameters.AddWithValue("@PageSize", pageSize); cmd.Parameters.Add("@PageCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output;
using (SqlDataAdapter sda = new SqlDataAdapter()) { cmd.Connection = con; sda.SelectCommand = cmd; using (DataSet ds = new DataSet()) { sda.Fill(ds, "Customers"); DataTable dt = new DataTable("PageCount"); dt.Columns.Add("PageCount"); dt.Rows.Add(); dt.Rows[0][0] = cmd.Parameters["@PageCount"].Value; ds.Tables.Add(dt); return ds; } } } } }
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load If Not IsPostBack Then gvCustomers.DataSource = GetCustomersPageWise(1, 10) gvCustomers.DataBind() End If End Sub
Public Shared Function GetCustomersPageWise(pageIndex As Integer, pageSize As Integer) As DataSet Dim constring As String = ConfigurationManager.ConnectionStrings("constr").ConnectionSt ring
Using con As New SqlConnection(constring) Using cmd As New SqlCommand("[GetCustomersPageWise]") cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.AddWithValue("@PageIndex", pageIndex) cmd.Parameters.AddWithValue("@PageSize", pageSize) cmd.Parameters.Add("@PageCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output Using sda As New SqlDataAdapter() cmd.Connection = con sda.SelectCommand = cmd Using ds As New DataSet() sda.Fill(ds, "Customers") Dim dt As New DataTable("PageCount") dt.Columns.Add("PageCount") dt.Rows.Add() dt.Rows(0)(0) = cmd.Parameters("@PageCount").Value ds.Tables.Add(dt) Return ds End Using End Using End Using End Using End Function
The following screenshot displays the GridView after all the above steps are completed.
Freezing the ASP.Net GridView Header Now we need to Freeze the GridView Header so that when we scroll the GridView the header row must remain fixed. Hence for now we need do View Source of the Page and then copy the GridView Header Row HTML as shown below
Then you need to copy the HTML Table of the GridView and the Header Row and paste it just above the HTML DIV that contains the GridView and complete the HTML table ending tag
With the above steps your GridView should now look as following with two headers.
GridView Load Rows on demand when scrolled using jQuery AJAX Now we will need to create a Web Method which will handle the jQuery AJAX calls when the GridView is scrolled C#
[WebMethod] public static string GetCustomers(int pageIndex) { //Added to similate delay so that we see the loader working //Must be removed when moving to production System.Threading.Thread.Sleep(2000);
VB.Net
<WebMethod()> _ Public Shared Function GetCustomers(pageIndex As Integer) As String 'Added to similate delay so that we see the loader working 'Must be removed when moving to production System.Threading.Thread.Sleep(2000)
Now the following JavaScript code needs to be placed on the page, which will complete our task to create an ASP.Net GridView that loads data on demand when scrolled 1. Firstly I have removed the default GridView header row as now it is not required since we need to use the fixed custom header that we have created 2. Then I have attached a jQuery scroll event handler to the HTML DIV, so that we can trigger the process of fetching next set of records when the HTML DIV is scrolled. 3. When a jQuery AJAX request is made to the server Web Method, I am creating a dummy row with a loading GIF image and then appending it as the last row of the GridView, so that we can display some animation until the records are fetched and loaded. 4. When the jQuery AJAX call receives the response as XML string, the XML is parsed and the values are populated using the class names we have given to each GridView column
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript"> var pageIndex = 1; var pageCount; $(function () { //Remove the original GridView header $("[id$=gvCustomers] tr").eq(0).remove(); });
$("#dvGrid").on("scroll", function (e) { var $o = $(e.currentTarget); if ($o[0].scrollHeight - $o.scrollTop() <= $o.outerHeight()) { GetRecords(); } });
//Function to make AJAX call to the Web Method function GetRecords() { pageIndex++; if (pageIndex == 2 || pageIndex <= pageCount) {
//Show Loader if ($("[id$=gvCustomers] .loader").length == 0) { var row = $("[id$=gvCustomers] tr").eq(0).clone(true); row.addClass("loader"); row.children().remove(); row.append('<td colspan = "999" style = "background-color:white"><img id="loader" alt="" src="103.gif" /></td>'); $("[id$=gvCustomers]").append(row); } $.ajax({ type: "POST", url: "Default.aspx/GetCustomers", data: '{pageIndex: ' + pageIndex + '}', contentType: "application/json; charset=utf-8", dataType: "json", success: OnSuccess, failure: function (response) { alert(response.d);
//Function to recieve XML response append rows to GridView function OnSuccess(response) { var xmlDoc = $.parseXML(response.d); var xml = $(xmlDoc); pageCount = parseInt(xml.find("PageCount").eq(0).find("PageCount").text()); var customers = xml.find("Customers"); $("[id$=gvCustomers] .loader").remove(); customers.each(function () { var customer = $(this); var row = $("[id$=gvCustomers] tr").eq(0).clone(true); $(".name", row).html(customer.find("ContactName").text()); $(".city", row).html(customer.find("City").text()); $(".postal", row).html(customer.find("PostalCode").text()); $(".country", row).html(customer.find("Country").text()); $("[id$=gvCustomers]").append(row); });
ASP.Net LinkedIn
Here Mudassar Ahmed Khan has explained how to login integrate LinkedIn API in ASP.Net Website and allow user to login with LinkedIn account and get LinkedIn User Profile details like ID, Name, Profile Picture, Email Address, etc. using the free ASPSnippets.LinkedInAPI.
Download View Demo
In this article I will explain how to login with LinkedIn Account in ASP.Net Website and get LinkedIn User Profile details like ID, Name, Profile Picture, Email Address, etc. using the free ASPSnippets.LinkedInAPI. This article also explains how create a LinkedIn Application and get the LinkedIn API Key and Secret Key on LinkedIn Developers Site.
Get LinkedIn API Key and Secret Key on LinkedIn Developers Site In order to create an application you need to visit the Linked Developer site using the following URL.
https://www.linkedin.com/secure/developer
After that you need to fill the following form, inside which the most important section is the Default Scope where you need to choose what User details you want to fetch through your application.
Once the form is submitted, you will get the LinkedIn API Key and Secret Key as shown below.
Downloading and referencing Free ASPSnippets LinkedIn API You can download the free ASPSnippets LinkedIn API from following URL
Download ASPSnippets LinkedIn API
And either add it using Add Reference or copy it inside the BIN folder of your website.
HTML Markup In the below HTML Markup, I have an ASP.Net Button which triggers the LinkedIn Authorization process. Once the user profile details are fetched, it will be displayed using the Label and Image controls.
<asp:Button Text="Login with LinkedIn" runat="server" OnClick="Authorize" /> <asp:Panel ID="pnlDetails" runat="server" Visible="false">
<hr /> <asp:Image ID="imgPicture" runat="server" /><br /> Name: <asp:Label ID="lblName" runat="server" /><br /> LinkedInId: <asp:Label ID="lblLinkedInId" runat="server" /><br /> Location: <asp:Label ID="lblLocation" runat="server" /><br /> EmailAddress: <asp:Label ID="lblEmailAddress" runat="server" /><br /> Industry: <asp:Label ID="lblIndustry" runat="server" /><br /> Headline: <asp:Label ID="lblHeadline" runat="server" /><br /> Specialities: <asp:Label ID="lblSpecialities" runat="server" /> </asp:Panel>
VB.Net
Imports System.Data Imports ASPSnippets.LinkedInAPI
LinkedIn Authorization and fetching the LinkedIn User Profile details The very first thing you need to do is set the LinkedIn API Key and Secret Key to its respective properties. Inside the Button click event handler, the Authorize method is called which will redirect user to the LinkedIn Website where he will login and also grant permissions to the application to fetch his profile details. Once the user has authorized the LinkedIn Profile details are fetched using the Fetch method as DataSet object and are displayed on page using Image and Label controls. C#
protected void Page_Load(object sender, EventArgs e) { LinkedInConnect.APIKey = "<Your LinkedIn API Key>"; LinkedInConnect.APISecret = "<Your LinkedIn API Secret>"; LinkedInConnect.RedirectUrl = Request.Url.AbsoluteUri.Split('?')[0]; if (LinkedInConnect.IsAuthorized) { pnlDetails.Visible = true; DataSet ds = LinkedInConnect.Fetch(); imgPicture.ImageUrl = ds.Tables["person"].Rows[0]["picture-url"].ToString(); lblName.Text = ds.Tables["person"].Rows[0]["first-name"].ToString(); lblName.Text += " " + ds.Tables["person"].Rows[0]["last-name"].ToString(); lblEmailAddress.Text = ds.Tables["person"].Rows[0]["email-address"].ToString(); lblHeadline.Text = ds.Tables["person"].Rows[0]["headline"].ToString(); lblIndustry.Text = ds.Tables["person"].Rows[0]["industry"].ToString(); lblLinkedInId.Text = ds.Tables["person"].Rows[0]["id"].ToString(); lblSpecialities.Text = ds.Tables["person"].Rows[0]["specialties"].ToString(); lblLocation.Text = ds.Tables["location"].Rows[0]["name"].ToString(); imgPicture.ImageUrl = ds.Tables["person"].Rows[0]["picture-url"].ToString(); } }
{ LinkedInConnect.Authorize(); }
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load LinkedInConnect.APIKey = "<Your LinkedIn API Key>" LinkedInConnect.APISecret = "<Your LinkedIn API Secret>" LinkedInConnect.RedirectUrl = Request.Url.AbsoluteUri.Split("?")(0) If LinkedInConnect.IsAuthorized Then pnlDetails.Visible = True Dim ds As DataSet = LinkedInConnect.Fetch() imgPicture.ImageUrl = ds.Tables("person").Rows(0)("picture-url").ToString() lblName.Text = ds.Tables("person").Rows(0)("first-name").ToString() lblName.Text += " " + ds.Tables("person").Rows(0)("last-name").ToString() lblEmailAddress.Text = ds.Tables("person").Rows(0)("email-address").ToString() lblHeadline.Text = ds.Tables("person").Rows(0)("headline").ToString() lblIndustry.Text = ds.Tables("person").Rows(0)("industry").ToString() lblLinkedInId.Text = ds.Tables("person").Rows(0)("id").ToString() lblSpecialities.Text = ds.Tables("person").Rows(0)("specialties").ToString() lblLocation.Text = ds.Tables("location").Rows(0)("name").ToString() imgPicture.ImageUrl = ds.Tables("person").Rows(0)("picture-url").ToString() End If End Sub
Bind, Find and Access Custom WebUserControl inside GridView TemplateField in ASP.Net
04 Dec 2013 Mudassar Khan 1 Comments 1744 Views
In this article I will explain how to bind custom WebUserControl inside ASP.Net GridView controls TemplateField ItemTemplate using C# and VB.Net.
I will also explain how to pass data to WebUserControl and also find, access and get value from WebUserControl inside GridView control.
HTML Markup Page The Page markup consists of an ASP.Net GridView with a TemplateField column inside which theres a WebUserControl for displaying country.
<%@ Register Src="~/UserControls/Country.ascx" TagName="Country" TagPrefix="uc" %> <!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 runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White" runat="server" AutoGenerateColumns="false"> <Columns> <asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="30" /> <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" /> <asp:TemplateField HeaderText="Country"> <ItemTemplate> <uc:Country ID="ucCountry" runat="server" Country='<%# Eval("Country") %>' /> </ItemTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <asp:Button Text="Get Details" runat="server" OnClick="GetDetails" /> </ItemTemplate> </asp:TemplateField>
WebUserControl The following WebUserControl used inside the GridView control discussed above. Its markup consists of an ASP.Net Label control for displaying content.
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Country.ascx.cs" Inherits="UserControls_Country " %> <asp:Label ID = "lblCountry" Text="" runat="server" />
VB.Net
Imports System.Data
Binding the GridView control I have created a dynamic DataTable with some dummy data and it has been bind to the GridView control in Page Load event. Note: You can learn more about this technique in my article Create DataTable dynamically and bind to GridView in ASP.Net. C#
protected void Page_Load(object sender, EventArgs e) {
if (!this.IsPostBack) { DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)), new DataColumn("Name", typeof(string)), new DataColumn("Country",typeof(string)) }); dt.Rows.Add(1, "John Hammond", "United States"); dt.Rows.Add(2, "Mudassar Khan", "India"); dt.Rows.Add(3, "Suzanne Mathews", "France"); dt.Rows.Add(4, "Robert Schidner", "Russia"); GridView1.DataSource = dt; GridView1.DataBind(); } }
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load If Not Me.IsPostBack Then Dim dt As New DataTable() dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id", GetType(Integer)), New DataColumn("Name", GetType(String)), New DataColu mn("Country", GetType(String))}) dt.Rows.Add(1, "John Hammond", "United States") dt.Rows.Add(2, "Mudassar Khan", "India") dt.Rows.Add(3, "Suzanne Mathews", "France") dt.Rows.Add(4, "Robert Schidner", "Russia") GridView1.DataSource = dt GridView1.DataBind() End If End Sub
Property to set and get data to and from WebUserControl Inside the WebUserControl I have made use of Public Property which will be used to set and get the Text of the Country Label. C#
public string Country { get { return lblCountry.Text; } set { lblCountry.Text = value; } }
VB.Net
Public Property Country() As String Get Return lblCountry.Text End Get Set(value As String) lblCountry.Text = value End Set End Property
This same property is used in the GridView ItemTemplate and its value is set using Eval function as shown below
<uc:Country ID="ucCountry" runat="server" Country='<%# Eval("Country") %>' />
Find and access WebUserControl inside GridViewRow Below is the click event handler for the Button inside GridView, here I have fetched details from the GridView Cells and the Country WebUserControl using its Public property discussed earlier. C#
protected void GetDetails(object sender, EventArgs e) { GridViewRow row = (sender as Button).NamingContainer as GridViewRow; string id = "Id: " + row.Cells[0].Text; string name = "Name: " + row.Cells[1].Text; string country = "Country: " + (row.FindControl("ucCountry") as UserControls_Country).Country; string message = string.Format("{0}\\n{1}\\n{2}", id, name, country); ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + message + "');", true); }
VB.Net
Protected Sub GetDetails(sender As Object, e As EventArgs) Dim row As GridViewRow = TryCast(TryCast(sender, Button).NamingContainer, GridViewRow ) Dim id As String = "Id: " + row.Cells(0).Text Dim name As String = "Name: " + row.Cells(1).Text Dim country As String = "Country: " + TryCast(row.FindControl("ucCountry"), UserControls_Country).Country Dim message As String = String.Format("{0}\n{1}\n{2}", id, name, country) ClientScript.RegisterStartupScript(Me.[GetType](), "alert", (Convert.ToString("alert('") & message) + "');", True) End Sub
AJAX CRUD operations (Create, Read, Update and Delete) using GridView in ASP.Net
02 Dec 2013 Mudassar Khan 3 Comments 3631 Views
In this article I will explain how to perform AJAX CRUD operations using GridView control in ASP.Net. CRUD is an abbreviation for Create, Read, Update and Delete. This article makes used of ASP.Net AJAX and jQuery with GridView to perform CRUD operations without PostBack.
Concept Basically I have tried to make the normal Add (Insert), Edit, Update and delete functions in ASP.Net GridView simple and also combining the powers of ASP.Net AJAX with that of JQuery to give an elegant and charming user experience.
Database and Connection String For this article as usual I have used my favorite NorthWind database which you can get by clicking on the link below.
Below is the connection string from the web.config <connectionStrings> <add name="conString" connectionString="Data Source=.\SQLExpress; database=Northwind;Integrated Security=true"/> </connectionStrings>
The GridView Below is the markup of the ASP.Net GridView control that Ill be using to demonstrate the various features explained in this article. <div id = "dvGrid" style ="padding:10px;width:550px"> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:GridView ID="GridView1" runat="server" Width = "550px" AutoGenerateColumns = "false" Font-Names = "Arial" Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B" HeaderStyle-BackColor = "green" AllowPaging ="true" ShowFooter = "true" OnPageIndexChanging = "OnPaging" onrowediting="EditCustomer" onrowupdating="UpdateCustomer" onrowcancelingedit="CancelEdit" PageSize = "10" > <Columns> <asp:TemplateField ItemStyle-Width = "30px" HeaderText = "CustomerID"> <ItemTemplate> <asp:Label ID="lblCustomerID" runat="server" Text='<%# Eval("CustomerID")%>'></asp:Label> </ItemTemplate>
<FooterTemplate> <asp:TextBox ID="txtCustomerID" Width = "40px" MaxLength = "5" runat="server"></asp:TextBox> </FooterTemplate> </asp:TemplateField> <asp:TemplateField ItemStyle-Width = "100px" HeaderText = "Name"> <ItemTemplate> <asp:Label ID="lblContactName" runat="server" Text='<%# Eval("ContactName")%>'></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtContactName" runat="server" Text='<%# Eval("ContactName")%>'></asp:TextBox> </EditItemTemplate> <FooterTemplate> <asp:TextBox ID="txtContactName" runat="server"></asp:TextBox> </FooterTemplate> </asp:TemplateField> <asp:TemplateField ItemStyle-Width = "150px" HeaderText = "Company"> <ItemTemplate> <asp:Label ID="lblCompany" runat="server" Text='<%# Eval("CompanyName")%>'></asp:Label> </ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtCompany" runat="server" Text='<%# Eval("CompanyName")%>'></asp:TextBox> </EditItemTemplate>
<FooterTemplate> <asp:TextBox ID="txtCompany" runat="server"></asp:TextBox> </FooterTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <asp:LinkButton ID="lnkRemove" runat="server" CommandArgument = '<%# Eval("CustomerID")%>' OnClientClick = "return confirm('Do you want to delete?')" Text = "Delete" OnClick = "DeleteCustomer"></asp:LinkButton> </ItemTemplate> <FooterTemplate> <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick = "AddNewCustomer" /> </FooterTemplate> </asp:TemplateField> <asp:CommandField ShowEditButton="True" /> </Columns> <AlternatingRowStyle BackColor="#C2D69B" /> </asp:GridView> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID = "GridView1" /> </Triggers> </asp:UpdatePanel> </div>
1. Customer ID 2. Contact Name 3. Company Name I have added a LinkButton in 4 column which will act as custom column for delete functionality. The reason to use a custom button is to provide the JavaScript confirmation box to the user when he clicks Delete. For Edit and Update I have added a command field which will act as the 5 column.
th th
Theres also a Footer Row with 3 TextBoxes which will be used to add new records to the database and an Add button which will be used to add the records. I have enabled pagination and finally wrapped the complete Grid in update panel and the update panel in a div dvGrid and the reason to that Ill explain later in the article
Binding the GridView Below is the code to bind the GridView in the page load event of the page C#
private String strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindData(); } } private void BindData() { string strQuery = "select CustomerID,ContactName,CompanyName" + " from customers"; SqlCommand cmd = new SqlCommand(strQuery); GridView1.DataSource = GetData(cmd);
GridView1.DataBind(); }
VB.Net Private strConnString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.L oad If Not IsPostBack Then BindData() End If End Sub Private Sub BindData() Dim strQuery As String = "select CustomerID,ContactName,CompanyName" & _ " from customers" Dim cmd As New SqlCommand(strQuery) GridView1.DataSource = GetData(cmd) GridView1.DataBind() End Sub
Below is the screenshot of the GridView being populated using the above code
Adding new record As discussed above I have placed 3 textboxes and a button in the Footer Row of the ASP.Net GridView control in order to add new record to the database. On the onclick event if the button the records are inserted into the SQL Server Database and the GridView is updated C# protected void AddNewCustomer(object sender, EventArgs e) { string CustomerID=((TextBox)GridView1.FooterRow.FindControl("txtCustomerID")).Text; string Name = ((TextBox)GridView1.FooterRow.FindControl("txtContactName")).Text; string Company = ((TextBox)GridView1.FooterRow.FindControl("txtCompany")).Text;
SqlConnection con = new SqlConnection(strConnString); SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "insert into customers(CustomerID, ContactName, CompanyName) " + "values(@CustomerID, @ContactName, @CompanyName);" + "select CustomerID,ContactName,CompanyName from customers" ; cmd.Parameters.Add("@CustomerID", SqlDbType.VarChar).Value = CustomerID; cmd.Parameters.Add("@ContactName", SqlDbType.VarChar).Value = Name; cmd.Parameters.Add("@CompanyName", SqlDbType.VarChar).Value = Company; GridView1.DataSource = GetData(cmd); GridView1.DataBind(); }
VB.Net Protected Sub AddNewCustomer(ByVal sender As Object, ByVal e As EventArgs) Dim CustomerID As String = DirectCast(GridView1.FooterRow _ .FindControl("txtCustomerID"), TextBox).Text Dim Name As String = DirectCast(GridView1 _ .FooterRow.FindControl("txtContactName"), TextBox).Text Dim Company As String = DirectCast(GridView1 _ .FooterRow.FindControl("txtCompany"), TextBox).Text Dim con As New SqlConnection(strConnString) Dim cmd As New SqlCommand() cmd.CommandType = CommandType.Text cmd.CommandText = "insert into customers(CustomerID, ContactName, " & _ "CompanyName) values(@CustomerID, @ContactName, @CompanyName);" & _ "select CustomerID,ContactName,CompanyName from customers"
cmd.Parameters.Add("@CustomerID", SqlDbType.VarChar).Value = CustomerID cmd.Parameters.Add("@ContactName", SqlDbType.VarChar).Value = Name cmd.Parameters.Add("@CompanyName", SqlDbType.VarChar).Value = Company GridView1.DataSource = GetData(cmd) GridView1.DataBind() End Sub
You will notice I am firing two queries one to insert the data and second to select the updated data and then rebind the GridView. The figure below displays how new records are added.
Edit and Update existing records As described above I have used command field in order to provide the Edit functionality. Below is the code snippet which is used to edit and update the records C# protected void EditCustomer(object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; BindData();
} protected void CancelEdit(object sender, GridViewCancelEditEventArgs e) { GridView1.EditIndex = -1; BindData(); } protected void UpdateCustomer(object sender, GridViewUpdateEventArgs e) { string CustomerID = ((Label)GridView1.Rows[e.RowIndex] .FindControl("lblCustomerID")).Text; string Name = ((TextBox)GridView1.Rows[e.RowIndex] .FindControl("txtContactName")).Text; string Company = ((TextBox)GridView1.Rows[e.RowIndex] .FindControl("txtCompany")).Text; SqlConnection con = new SqlConnection(strConnString); SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "update customers set ContactName=@ContactName," + "CompanyName=@CompanyName where CustomerID=@CustomerID;" + "select CustomerID,ContactName,CompanyName from customers" ; cmd.Parameters.Add("@CustomerID", SqlDbType.VarChar).Value = CustomerID; cmd.Parameters.Add("@ContactName", SqlDbType.VarChar).Value = Name; cmd.Parameters.Add("@CompanyName", SqlDbType.VarChar).Value = Company; GridView1.EditIndex = -1; GridView1.DataSource = GetData(cmd); GridView1.DataBind(); }
VB.Net Protected Sub EditCustomer(ByVal sender As Object, ByVal e As GridViewEditEventAr gs) GridView1.EditIndex = e.NewEditIndex BindData() End Sub Protected Sub CancelEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEve ntArgs) GridView1.EditIndex = -1 BindData() End Sub Protected Sub UpdateCustomer(ByVal sender As Object, ByVal e As GridViewUpdateEve ntArgs) Dim CustomerID As String = DirectCast(GridView1.Rows(e.RowIndex) _ .FindControl("lblCustomerID"), Label).Text Dim Name As String = DirectCast(GridView1.Rows(e.RowIndex) _ .FindControl("txtContactName"), TextBox).Text Dim Company As String = DirectCast(GridView1.Rows(e.RowIndex) _ .FindControl("txtCompany"), TextBox).Text Dim con As New SqlConnection(strConnString) Dim cmd As New SqlCommand() cmd.CommandType = CommandType.Text cmd.CommandText = "update customers set ContactName=@ContactName," _ & "CompanyName=@CompanyName where CustomerID=@CustomerID;" _ & "select CustomerID,ContactName,CompanyName from customers" cmd.Parameters.Add("@CustomerID", SqlDbType.VarChar).Value = CustomerID cmd.Parameters.Add("@ContactName", SqlDbType.VarChar).Value = Name
cmd.Parameters.Add("@CompanyName", SqlDbType.VarChar).Value = Company GridView1.EditIndex = -1 GridView1.DataSource = GetData(cmd) GridView1.DataBind() End Sub You can view above I am simply getting the data from the textboxes in the Footer Row and then firing an update query along with the select query so that the ASP.Net GridView control is also updated. The figure below displays the Edit and Update functionality.
Deleting existing record with Confirmation As said above I am using custom delete button instead of ASP.Net GridView delete command field and the main reason for that is to add a confirmation. C# protected void DeleteCustomer(object sender, EventArgs e) { LinkButton lnkRemove = (LinkButton)sender; SqlConnection con = new SqlConnection(strConnString); SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text; cmd.CommandText = "delete from customers where " + "CustomerID=@CustomerID;" + "select CustomerID,ContactName,CompanyName from customers" ; cmd.Parameters.Add("@CustomerID", SqlDbType.VarChar).Value = lnkRemove.CommandArgument; GridView1.DataSource = GetData(cmd); GridView1.DataBind(); } VB.Net Protected Sub DeleteCustomer(ByVal sender As Object, ByVal e As EventArgs) Dim lnkRemove As LinkButton = DirectCast(sender, LinkButton) Dim con As New SqlConnection(strConnString) Dim cmd As New SqlCommand() cmd.CommandType = CommandType.Text cmd.CommandText = "delete from customers where " & _ "CustomerID=@CustomerID;" & _ "select CustomerID,ContactName,CompanyName from customers" cmd.Parameters.Add("@CustomerID", SqlDbType.VarChar).Value _ = lnkRemove.CommandArgument GridView1.DataSource = GetData(cmd) GridView1.DataBind() End Sub Based on the sender argument I am getting the reference of the LinkButton that is clicked and with the CommandArgument of the LinkButton I am getting the ID of the record to be deleted. After the delete query I am firing a select query and the rebinding the GridView.
Pagination For pagination I have added the OnPageIndexChanging event on which I am assigning the new page index to the ASP.Net GridView control and then rebinding the data.
VB.Net Protected Sub OnPaging(ByVal sender As Object, ByVal e As GridViewPageEventArgs) BindData() GridView1.PageIndex = e.NewPageIndex GridView1.DataBind() End Sub
ASP.Net AJAX and JQuery As you have seen in the start I had added an Update Panel and a DIV along with ASP.Net GridView Control. Basically the Update Panel will give the asynchronous calls thus not reloading the complete page and the JQuery will block the UI until the update panel is refreshed completely. But instead of blocking the complete page I am blocking only the contents of the DIV dvGrid. To achieve this I am using the JQuery BlockUI Plugin <script type = "text/javascript" src = "scripts/jquery-1.3.2.min.js"></script> <script type = "text/javascript" src = "scripts/jquery.blockUI.js"></script> <script type = "text/javascript"> function BlockUI(elementID) { var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_beginRequest(function() { $("#" + elementID).block({ message: '<table align = "center"><tr><td>' + '<img src="images/loadingAnim.gif"/></td></tr></table>', css: {}, overlayCSS: {backgroundColor:'#000000',opacity: 0.6, border:'3px solid #63B2EB' } }); });
Thats all the scripting required and the following is achieved with the above scripts. It will block the Grid until the update panel finishes its work. Refer the figure below
ASP.Net GridView
Here Mudassar Ahmed Khan has explained how to implement GridView Grouping i.e. group similar GridView Rows in ASP.Net using C# and VB.Net.
Download View Demo
In this article I will explain how to implement GridView Grouping i.e. group similar GridView Rows in ASP.Net using C# and VB.Net.
You can also read some other interesting articles on GridView:Rotate ASP.Net GridView - Convert GridView Columns to Rows and Rows to Columns Collapsible Nested GridView with Paging using ASP.Net Multilevel (N Level) Nested GridView (GridView inside GridView) in ASP.Net with Paging
Database Here I am making use of Microsofts Northwind Database. You can download it from here
HTML Markup The HTML Markup consists of an ASP.Net GridView with three columns populated from the Customers Table of the Northwind Database.
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White" runat = "server" AutoGenerateColumns="false" OnDataBound="OnDataBound"> <Columns> <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="150" /> <asp:BoundField DataField="City" HeaderText="City" ItemStyle-Width="150" /> <asp:BoundField DataField="ContactName" HeaderText="Name" ItemStyle-Width="150" /> </Columns> </asp:GridView>
You will notice that we have specified the OnDataBound event of the GridView, this event will be used to write the logic for merging the GridView Columns or Cells.
using System.Configuration;
VB.Net
Imports System.Data Imports System.Data.SqlClient Imports System.Configuration
Binding the GridView Below is the code to populate the ASP.Net GridView with the records from the Customers Table of the Northwind Database. C#
protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { DataTable dt = new DataTable(); GridView1.DataSource = GetData("SELECT ContactName, Country, City FROM Customers GROUP BY Country, City, ContactName"); GridView1.DataBind(); } } private DataTable GetData(string query) { DataTable dt = new DataTable(); string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand(query)) { using (SqlDataAdapter sda = new SqlDataAdapter())
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load If Not Me.IsPostBack Then Dim dt As New DataTable() GridView1.DataSource = GetData("SELECT ContactName, Country, City FROM Customers GROUP BY Country, City, ContactName") GridView1.DataBind() End If End Sub
Private Function GetData(query As String) As DataTable Dim dt As New DataTable() Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionStrin g Using con As New SqlConnection(constr) Using cmd As New SqlCommand(query) Using sda As New SqlDataAdapter() cmd.CommandType = CommandType.Text cmd.Connection = con sda.SelectCommand = cmd
sda.Fill(dt) End Using End Using Return dt End Using End Function
Merge Common Cells or Columns in a Row in ASP.Net GridView The OnDataBound event of the GridView is executed after the GridView is populated with records. Here a reverse loop is executed over the GridView Rows and then the common Cells are identified and merged into single cell. C#
protected void OnDataBound(object sender, EventArgs e) { for (int i = GridView1.Rows.Count - 1; i > 0; i--) { GridViewRow row = GridView1.Rows[i];
GridViewRow previousRow = GridView1.Rows[i - 1]; for (int j = 0; j < row.Cells.Count; j++) { if (row.Cells[j].Text == previousRow.Cells[j].Text) { if (previousRow.Cells[j].RowSpan == 0) { if (row.Cells[j].RowSpan == 0) { previousRow.Cells[j].RowSpan += 2; } else { previousRow.Cells[j].RowSpan = row.Cells[j].RowSpan + 1; } row.Cells[j].Visible = false; } } } } }
VB.Net
Protected Sub OnDataBound(sender As Object, e As EventArgs) For i As Integer = GridView1.Rows.Count - 1 To 1 Step -1 Dim row As GridViewRow = GridView1.Rows(i) Dim previousRow As GridViewRow = GridView1.Rows(i - 1) For j As Integer = 0 To row.Cells.Count - 1 If row.Cells(j).Text = previousRow.Cells(j).Text Then If previousRow.Cells(j).RowSpan = 0 Then
If row.Cells(j).RowSpan = 0 Then previousRow.Cells(j).RowSpan += 2 Else previousRow.Cells(j).RowSpan = row.Cells(j).RowSpan + 1 End If row.Cells(j).Visible = False End If End If Next Next End Sub
Display image from database in Image control without using Generic Handler in ASP.Net
29 Nov 2013 Mudassar Khan
0 Comments
3246 Views
In this article I will explain how to display images stored in database in ASP.Net Image control without using Generic HTTP Handler. The images stored as Binary data will be fetched as BYTE Array and then the BYTE Array will be converted to BASE64 string and then assigned to the ASP.Net image control. I have already explained how to upload files save files as binary data in database in my article Save Files to SQL Server Database using FileUpload Control. The same database is used for this article.
Binary Images stored in Database The following screenshot displays database table with three images stored in it. The backup file of the database is present in the attached sample.
HTML Markup The HTML Markup consists of a DropDownList control which will populate the list of image files in database and a Image control to display the selected image.
<asp:DropDownList ID="ddlImages" runat="server" AppendDataBoundItems="true" AutoPostBack = "true" O nSelectedIndexChanged = "FetchImage"> <asp:ListItem Text="Select Image" Value="0" /> </asp:DropDownList> <hr /> <asp:Image ID="Image1" runat="server" Visible = "false"/>
VB.Net
Imports System.Data Imports System.Configuration Imports System.Data.SqlClient
Populating the List of Images in DropDownList control Inside the Page Load event, I have written code to populate the list of images from database table. C#
protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { ddlImages.DataSource = GetData("SELECT Id, Name FROM tblFiles"); ddlImages.DataTextField = "Name"; ddlImages.DataValueField = "Id"; ddlImages.DataBind(); } }
{ DataTable dt = new DataTable(); string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand(query)) { using (SqlDataAdapter sda = new SqlDataAdapter()) { cmd.CommandType = CommandType.Text; cmd.Connection = con; sda.SelectCommand = cmd; sda.Fill(dt); } } return dt; } }
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load If Not Me.IsPostBack Then ddlImages.DataSource = GetData("SELECT Id, Name FROM tblFiles") ddlImages.DataTextField = "Name" ddlImages.DataValueField = "Id" ddlImages.DataBind() End If End Sub
Dim dt As New DataTable() Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionStrin g Using con As New SqlConnection(constr) Using cmd As New SqlCommand(query) Using sda As New SqlDataAdapter() cmd.CommandType = CommandType.Text cmd.Connection = con sda.SelectCommand = cmd sda.Fill(dt) End Using End Using Return dt End Using End Function
Displaying the binary image from database in Image Control without using Generic Handler The following event handler is executed on the SelectedIndexChanged event of the DropDownList control. Here the binary image is fetched from database as BYTE array and then the BYTE array is converted to BASE64 string and displayed in Image control. To know more about displaying binary image using BASE64 string please refer Display Byte Array as Image without
using generic handler in ASP.Net.
C#
protected void FetchImage(object sender, EventArgs e) { string id = ddlImages.SelectedItem.Value; Image1.Visible = id != "0"; if (id != "0") { byte[] bytes = (byte[])GetData("SELECT Data FROM tblFiles WHERE Id =" + id).Rows[0]["Data"];
VB.Net
Protected Sub FetchImage(sender As Object, e As EventArgs) Dim id As String = ddlImages.SelectedItem.Value Image1.Visible = id <> "0" If id <> "0" Then Dim bytes As Byte() = DirectCast(GetData(Convert.ToString("SELECT Data FROM tblFiles WHERE Id =") & id).Rows(0)("Data"), Byte()) Dim base64String As String = Convert.ToBase64String(bytes, 0, bytes.Length) Image1.ImageUrl = Convert.ToString("data:image/png;base64,") & base64String End If End Sub
Encrypt AppSettings Key (Tags) in Web.Config File in ASP.Net using C# and VB.Net
27 Nov 2013 Mudassar Khan 0 Comments 1659 Views
ASP.Net Cryptography
Here Mudassar Ahmed Khan has explained how to encrypt and save AppSetting values in Web.Config or App.Config files and then fetch decrypt the encrypted AppSetting values in ASP.Net or Windows Application using C# and VB.Net. The AppSetting values will be first encrypted using AES Symmetric key (Same key) algorithm and then the AppSetting values will be saved in Web.Config or App.Config files. When using it in program, the AppSetting values will be first fetched and then decrypted using AES Algorithm using the same key which was used for encryption.
Download
In this article I will explain how to encrypt and save AppSetting values in Web.Config or App.Config files and then fetch decrypt the encrypted AppSetting values in ASP.Net or Windows Application using C# and VB.Net. The AppSetting values will be first encrypted using AES Symmetric key (Same key) algorithm and then the AppSetting values will be saved in Web.Config or App.Config files. When using it in program, the AppSetting values will be first fetched and then decrypted using AES Algorithm using the same key which was used for encryption. You might also like to read:
Encrypt and Decrypt Word, Excel, PDF, Text or Image Files using C# and VB.Net in ASP.Net Encrypt and Decrypt QueryString Parameter Values in ASP.Net using C# and VB.Net Encrypt and Decrypt Username or Password stored in database in ASP.Net using C# and VB.Net
VB.Net
Imports System.IO Imports System.Xml
AES Algorithm Encryption and Decryption functions Below are the functions for Encryption and Decryption which will be used for the Encrypting or Decrypting QueryString Parameter Values. Note: The following functions have been explained in the article AES Encryption Decryption (Cryptography) Tutorial with example in ASP.Net using C# and VB.Net
AppSetting Key The following AppSetting key will be used for encryption
<add key="Name" value="Mudassar Khan" />
Encrypting AppSetting Value The following function is used to encrypt AppSetting value in Web.Config or App.Config file. This function accepts the name of the AppSetting Key as parameter. It first reads the Web.Config file using XmlDocument and the node is traversed using the name of the AppSetting key. Then from the node the AppSetting value is extracted, it is encrypted and then value set again and the Web.Config file is saved. C#
private void EncryptAppSetting(string key) { string path = Server.MapPath("~/Web.Config"); XmlDocument doc = new XmlDocument(); doc.Load(path); XmlNodeList list = doc.DocumentElement.SelectNodes(string.Format("appSettings/add[@key='{0}']", key));
if (list.Count == 1)
private string Encrypt(string clearText) { string EncryptionKey = "MAKV2SPBNI99212"; byte[] clearBytes = Encoding.Unicode.GetBytes(clearText); using (Aes encryptor = Aes.Create()) { Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); encryptor.Key = pdb.GetBytes(32); encryptor.IV = pdb.GetBytes(16); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(clearBytes, 0, clearBytes.Length); cs.Close(); } clearText = Convert.ToBase64String(ms.ToArray()); } } return clearText; }
VB.Net
Private Sub EncryptAppSetting(key As String) Dim path As String = Server.MapPath("~/Web.Config") Dim doc As New XmlDocument() doc.Load(path) Dim list As XmlNodeList = doc.DocumentElement.SelectNodes(String.Format("appSettings/add[@key='{0}']", key))
If list.Count = 1 Then Dim node As XmlNode = list(0) Dim value As String = node.Attributes("value").Value node.Attributes("value").Value = Encrypt(value) doc.Save(path) End If End Sub
Private Function Encrypt(clearText As String) As String Dim EncryptionKey As String = "MAKV2SPBNI99212" Dim clearBytes As Byte() = Encoding.Unicode.GetBytes(clearText) Using encryptor As Aes = Aes.Create() Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _ &H65, &H64, &H76, &H65, &H64, &H65, _ &H76}) encryptor.Key = pdb.GetBytes(32) encryptor.IV = pdb.GetBytes(16) Using ms As New MemoryStream() Using cs As New CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write) cs.Write(clearBytes, 0, clearBytes.Length)
cs.Close() End Using clearText = Convert.ToBase64String(ms.ToArray()) End Using End Using Return clearText End Function
VB.Net
Me.EncryptAppSetting("Name")
Encrypted AppSetting Key Below is the updated value of the AppSetting key after Encryption is performed.
<add key="Name" value="J1i3VC4bVM/6svrgUor9V8y4gvfGlR6W5mtk2wspmIs= " />
Decrypting AppSetting Value The Decryption is lot simpler, you simply need to fetch the Encrypted AppSetting value using ConfigurationManager AppSettings method and then pass it as parameter to the following Decrypt function. C#
private string Decrypt(string cipherText) { string EncryptionKey = "MAKV2SPBNI99212"; byte[] cipherBytes = Convert.FromBase64String(cipherText); using (Aes encryptor = Aes.Create())
{ Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); encryptor.Key = pdb.GetBytes(32); encryptor.IV = pdb.GetBytes(16); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(cipherBytes, 0, cipherBytes.Length); cs.Close(); } cipherText = Encoding.Unicode.GetString(ms.ToArray()); } } return cipherText; }
VB.Net
Private Function Decrypt(cipherText As String) As String Dim EncryptionKey As String = "MAKV2SPBNI99212" Dim cipherBytes As Byte() = Convert.FromBase64String(cipherText) Using encryptor As Aes = Aes.Create() Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _ &H65, &H64, &H76, &H65, &H64, &H65, _ &H76}) encryptor.Key = pdb.GetBytes(32) encryptor.IV = pdb.GetBytes(16) Using ms As New MemoryStream()
Using cs As New CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write) cs.Write(cipherBytes, 0, cipherBytes.Length) cs.Close() End Using cipherText = Encoding.Unicode.GetString(ms.ToArray()) End Using End Using Return cipherText End Function
VB.Net
Dim name As String = Decrypt(ConfigurationManager.AppSettings("Name"))
In this article I have explained, how to make a AJAX call to ASP.Net WebMethod using jQuery AJAX. jQuery allows you to call Server Side ASP.net methods from client side without any PostBack. Actually it is an AJAX call to the server but it allows us to call the method or function defined server side.
jQuery AJAX Method Syntax The figure below describes the syntax of the call.
HTML Markup <div> Your Name : <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox> <input id="btnGetTime" type="button" value="Show Current Time" onclick = "ShowCurrentTime()" /> </div>
As you noticed above I have added a textbox when user can enter his name and a TML button that calls a JavaScript method to get the Current Time.
Client Side Methods <script src="scripts/jquery-1.3.2.min.js" type="text/javascript"></script> <script type = "text/javascript"> function ShowCurrentTime() { $.ajax({ type: "POST",
url: "Default.aspx/GetCurrentTime", data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }', contentType: "application/json; charset=utf-8", dataType: "json", success: OnSuccess, failure: function(response) { alert(response.d); } }); } function OnSuccess(response) { alert(response.d); } </script>
Above the ShowCurrentTime method makes an AJAX call to the server and executes the GetCurrentTime method which accepts the username and returns a string value.
Server Side Methods C# [System.Web.Services.WebMethod] public static string GetCurrentTime(string name) { return "Hello " + name + Environment.NewLine + "The Current Time is: " + DateTime.Now.ToString(); } VB.Net <System.Web.Services.WebMethod()> _ Public Shared Function GetCurrentTime(ByVal name As String) As String Return "Hello " & name & Environment.NewLine & "The Current Time is: " & _
The above method simply returns a greeting message to the user along with the current server time. An important thing to note is that the method is declared asstatic (C#) and Shared(VB.Net) and also it is declared as Web Method unless you do this you wont be able to call the methods The figure below displays the output displayed to the user when the button is clicked
* All browser logos displayed above are property of their respective owners.
Retrieve data from Database and display on page using jQuery AJAX in ASP.Net
19 Nov 2013 Mudassar Khan 0 Comments 4034 Views
Here Mudassar Ahmed Khan has explained, how to get (retrieve) data from database and display it on page using jQuery AJAX Web Method in ASP.Net using C# and VB.Net
Download View Demo
In this article I will explain how to get (retrieve) data from database and display it on page using jQuery AJAX Web Method in ASP.Net using C# and VB.Net. In order to display data I am making use of GridView control.
Database For this article I have used Microsofts Northwind database. You can download it using the link provided below.
Download Northwind Database
HTML Markup Below is the HTML Markup. It has an ASP.Net GridView gvCustomers and an HTML DIV control where the Pager will be populated for pagination
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" RowStyleBackColor="#A1DCF2" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"> <Columns> <asp:BoundField ItemStyle-Width="150px" DataField="CustomerID" HeaderText="CustomerID" /> <asp:BoundField ItemStyle-Width="150px" DataField="ContactName" HeaderText="Contact Name" /> <asp:BoundField ItemStyle-Width="150px" DataField="City" HeaderText="City" /> </Columns> </asp:GridView> <br /> <div class="Pager"></div>
VB.Net
Imports System.Data Imports System.Web.Services Imports System.Configuration Imports System.Data.SqlClient
Populating GridView Dummy with Dummy Data In Page Load event of the page I am populating the GridView with dummy data so that we can use its HTML Table structure to populate data using jQuery. I have created a variable PageSize which will decide the number of records to be displayed per page in GridView Note: The dummy DataTable being populated has the same columns which will be returned from the SQL Query C#
private static int PageSize = 10; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindDummyRow(); } }
VB.Net
Private Shared PageSize As Integer = 10 Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load If Not IsPostBack Then BindDummyRow() End If End Sub
Private Sub BindDummyRow() Dim dummy As New DataTable() dummy.Columns.Add("CustomerID") dummy.Columns.Add("ContactName") dummy.Columns.Add("City") dummy.Rows.Add() gvCustomers.DataSource = dummy gvCustomers.DataBind() End Sub
Pagination SQL Server Stored Procedure Following is the stored procedure which will perform pagination in SQL Server database and return per page data
CREATE PROCEDURE [dbo].[GetCustomers_Pager]
@PageIndex INT = 1 ,@PageSize INT = 10 ,@RecordCount INT OUTPUT AS BEGIN SET NOCOUNT ON; SELECT ROW_NUMBER() OVER ( ORDER BY [CustomerID] ASC )AS RowNumber ,[CustomerID] ,[CompanyName] ,[ContactName] ,[City] INTO #Results FROM [Customers]
SELECT * FROM #Results WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex 1) * @PageSize + 1) + @PageSize) - 1
WebMethod to handle jQuery AJAX calls Below is the Web Method which is being called by the jQuery AJAX function which populates the GridView with data and also does Pagination.
The PageIndex is passed as parameter from Client side based on what is Page is clicked by the user, while the PageSize we get from the static variable we have declared. Based on these parameters we can fetch the records Page wise. The records fetched along with the Total Record Count are sent to Client Side as XML string. Note: Total Record Count is necessary to populate pager. C#
[WebMethod] public static string GetCustomers(int pageIndex) { string query = "[GetCustomers_Pager]"; SqlCommand cmd = new SqlCommand(query); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@PageIndex", pageIndex); cmd.Parameters.AddWithValue("@PageSize", PageSize); cmd.Parameters.Add("@RecordCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output; return GetData(cmd, pageIndex).GetXml(); }
private static DataSet GetData(SqlCommand cmd, int pageIndex) { string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString; using (SqlConnection con = new SqlConnection(strConnString)) { using (SqlDataAdapter sda = new SqlDataAdapter()) { cmd.Connection = con; sda.SelectCommand = cmd; using (DataSet ds = new DataSet()) { sda.Fill(ds, "Customers");
DataTable dt = new DataTable("Pager"); dt.Columns.Add("PageIndex"); dt.Columns.Add("PageSize"); dt.Columns.Add("RecordCount"); dt.Rows.Add(); dt.Rows[0]["PageIndex"] = pageIndex; dt.Rows[0]["PageSize"] = PageSize; dt.Rows[0]["RecordCount"] = cmd.Parameters["@RecordCount"].Value; ds.Tables.Add(dt); return ds; } } } }
VB.Net
< WebMethod()> _ Public Shared Function GetCustomers(pageIndex As Integer) As String Dim query As String = "[GetCustomers_Pager]" Dim cmd As New SqlCommand(query) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.AddWithValue("@PageIndex", pageIndex) cmd.Parameters.AddWithValue("@PageSize", PageSize) cmd.Parameters.Add("@RecordCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output Return GetData(cmd, pageIndex).GetXml() End Function
Private Shared Function GetData(cmd As SqlCommand, pageIndex As Integer) As DataSet Dim strConnString As String = ConfigurationManager.ConnectionStrings("conString").Connec tionString
Using con As New SqlConnection(strConnString) Using sda As New SqlDataAdapter() cmd.Connection = con sda.SelectCommand = cmd Using ds As New DataSet() sda.Fill(ds, "Customers") Dim dt As New DataTable("Pager") dt.Columns.Add("PageIndex") dt.Columns.Add("PageSize") dt.Columns.Add("RecordCount") dt.Rows.Add() dt.Rows(0)("PageIndex") = pageIndex dt.Rows(0)("PageSize") = PageSize dt.Rows(0)("RecordCount") = cmd.Parameters("@RecordCount").Value ds.Tables.Add(dt) Return ds End Using End Using End Using End Function
Client Side Implementation Below is the complete Client Side Implementation, here on load event of jQuery the GridView is populated with PageIndex 1 using the method GetCustomers which populates the ASP.Net GridView which was initially populated with dummy data. Using the Record Count, the pager is populated inside the HTML DIV using the ASPSnippets_Pager jQuery Plugin.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="ASPSnippets_Pager.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () {
GetCustomers(1); }); $(".Pager .page").live("click", function () { GetCustomers(parseInt($(this).attr('page'))); }); function GetCustomers(pageIndex) { $.ajax({ type: "POST", url: "Default.aspx/GetCustomers", data: '{pageIndex: ' + pageIndex + '}', contentType: "application/json; charset=utf-8", dataType: "json", success: OnSuccess, failure: function (response) { alert(response.d); }, error: function (response) { alert(response.d); } }); }
function OnSuccess(response) { var xmlDoc = $.parseXML(response.d); var xml = $(xmlDoc); var customers = xml.find("Customers"); var row = $("[id*=gvCustomers] tr:last-child").clone(true); $("[id*=gvCustomers] tr").not($("[id*=gvCustomers] tr:first-child")).remove(); $.each(customers, function () { var customer = $(this);
$("td", row).eq(0).html($(this).find("CustomerID").text()); $("td", row).eq(1).html($(this).find("ContactName").text()); $("td", row).eq(2).html($(this).find("City").text()); $("[id*=gvCustomers]").append(row); row = $("[id*=gvCustomers] tr:last-child").clone(true); }); var pager = xml.find("Pager"); $(".Pager").ASPSnippets_Pager({ ActiveCssClass: "current", PagerCssClass: "pager", PageIndex: parseInt(pager.find("PageIndex").text()), PageSize: parseInt(pager.find("PageSize").text()), RecordCount: parseInt(pager.find("RecordCount").text()) }); }; </script>
CSS Below is the necessary CSS styles which you need to put on your page.
<style type="text/css"> body { font-family: Arial; font-size: 10pt; } .Pager span { text-align: center; color: #999; display: inline-block;
width: 20px; background-color: #A1DCF2; margin-right: 3px; line-height: 150%; border: 1px solid #3AC0F2; } .Pager a { text-align: center; display: inline-block; width: 20px; background-color: #3AC0F2; color: #fff; border: 1px solid #3AC0F2; margin-right: 3px; line-height: 150%; text-decoration: none; } </style>
Screenshot Below is the screenshot of ASP.Net GridView with Client Side Paging using jQuery AJAX
Encrypt and Decrypt Word, Excel, PDF, Text or Image Files using C# and VB.Net in ASP.Net
16 Nov 2013 Mudassar Khan 0 Comments 2819 Views
In this article I will explain how to encrypt and decrypt file such as Word (DOC, DOCX), Excel (XLS, XLSX), PDF, Text (TXT) documents or JPG, PNG or GIF Images using C# and VB.Net in ASP.Net website. The file will be uploaded for Encryption and Decryption of Files. For Encryption and Decryption of files, the AES Symmetric key (Same key) algorithm is used. The encrypted and decrypted files can be saved inside folders on disk or can be downloaded to client user.
HTML Markup The HTML markup consists of FileUpload control and two Buttons.
<asp:FileUpload ID="FileUpload1" runat="server" /> <hr /> <asp:Button ID = "btnEncrypt" Text="Encrypt File" runat="server" OnClick = "EncryptFile" /> <asp:Button ID = "btnDecrypt" Text="Decrypt File" runat="server" OnClick = "DecryptFile" />
VB.Net
Imports System.IO Imports System.Security.Cryptography
AES Algorithm Encryption and Decryption functions Below are the functions for Encryption and Decryption which will be used for the Encrypting or Decrypting Files. Note: The following functions have been explained in the article AES Encryption Decryption (Cryptography) Tutorial with
example in ASP.Net using C# and VB.Net
File Encryption The following Button click event handler encrypts the uploaded file. Name, Content Type and the File Bytes of the uploaded file are fetched and the file is save on folder on disk. Once the file is saved in the same location its encrypted counterpart is saved with the postfix _enc. The encrypted file is then sent for download by the client user. After download both the files are deleted. C#
protected void EncryptFile(object sender, EventArgs e) { //Get the Input File Name and Extension. string fileName = Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName); string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);
//Build the File Path for the original (input) and the encrypted (output) file. string input = Server.MapPath("~/Files/") + fileName + fileExtension; string output = Server.MapPath("~/Files/") + fileName + "_enc" + fileExtension;
//Save the Input File, Encrypt it and save the encrypted file in output path. FileUpload1.SaveAs(input); this.Encrypt(input, output);
//Download the Encrypted File. Response.ContentType = FileUpload1.PostedFile.ContentType; Response.Clear(); Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(output)); Response.WriteFile(output); Response.Flush();
//Delete the original (input) and the encrypted (output) file. File.Delete(input); File.Delete(output);
Response.End(); }
{ string EncryptionKey = "MAKV2SPBNI99212"; using (Aes encryptor = Aes.Create()) { Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); encryptor.Key = pdb.GetBytes(32); encryptor.IV = pdb.GetBytes(16); using (FileStream fsOutput = new FileStream(outputfilePath, FileMode.Create)) { using (CryptoStream cs = new CryptoStream(fsOutput, encryptor.CreateEncryptor(), CryptoStreamMode.Write)) { using (FileStream fsInput = new FileStream(inputFilePath, FileMode.Open)) { int data; while ((data = fsInput.ReadByte()) != -1) { cs.WriteByte((byte)data); } } } } } }
VB.Net
Protected Sub EncryptFile(sender As Object, e As EventArgs) 'Get the Input File Name and Extension. Dim fileName As String = Path.GetFileNameWithoutExtension(FileUpload1.PostedFile. FileName)
'Build the File Path for the original (input) and the encrypted (output) file. Dim input As String = Convert.ToString(Server.MapPath("~/Files/") & fileName) & fileExtension Dim output As String = Convert.ToString((Server.MapPath("~/Files/") & fileName) + "_enc") & fileExtension
'Save the Input File, Encrypt it and save the encrypted file in output path. FileUpload1.SaveAs(input) Me.Encrypt(input, output)
'Download the Encrypted File. Response.ContentType = FileUpload1.PostedFile.ContentType Response.Clear() Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(output)) Response.WriteFile(output) Response.Flush()
'Delete the original (input) and the encrypted (output) file. File.Delete(input) File.Delete(output)
Protected Sub DecryptFile(sender As Object, e As EventArgs) 'Get the Input File Name and Extension Dim fileName As String = Path.GetFileNameWithoutExtension(FileUpload1.PostedFile. FileName) Dim fileExtension As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
'Build the File Path for the original (input) and the decrypted (output) file Dim input As String = Convert.ToString(Server.MapPath("~/Files/") & fileName) & fileExtension Dim output As String = Convert.ToString((Server.MapPath("~/Files/") & fileName) + "_dec") & fileExtension
'Save the Input File, Decrypt it and save the decrypted file in output path. FileUpload1.SaveAs(input) Me.Decrypt(input, output)
'Download the Decrypted File. Response.Clear() Response.ContentType = FileUpload1.PostedFile.ContentType Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(output)) Response.WriteFile(output) Response.Flush()
'Delete the original (input) and the decrypted (output) file. File.Delete(input) File.Delete(output)
Private Shared Function Assign(Of T)(ByRef source As T, ByVal value As T) As T source = value Return value End Function
For VB.Net I have made use of a utility method named Assign for assigning variable values and also returning the same. In C# it can be done easily but to do same in VB.Net we need a utility method.
File Decryption Similar to Encryption process, the following Button click event handler encrypts the uploaded file. Name, Content Type and the File Bytes of the uploaded file are fetched and the file is save on folder on disk. Once the file is saved in the same location its decrypted counterpart is saved with the postfix _dec. The decrypted file is then sent for download by the client user. After download both the files are deleted. C#
protected void DecryptFile(object sender, EventArgs e) { //Get the Input File Name and Extension string fileName = Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName); string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);
//Build the File Path for the original (input) and the decrypted (output) file string input = Server.MapPath("~/Files/") + fileName + fileExtension; string output = Server.MapPath("~/Files/") + fileName + "_dec" + fileExtension;
//Save the Input File, Decrypt it and save the decrypted file in output path. FileUpload1.SaveAs(input); this.Decrypt(input, output);
//Download the Decrypted File. Response.Clear(); Response.ContentType = FileUpload1.PostedFile.ContentType; Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(output)); Response.WriteFile(output); Response.Flush();
//Delete the original (input) and the decrypted (output) file. File.Delete(input); File.Delete(output);
Response.End(); }
private void Decrypt(string inputFilePath, string outputfilePath) { string EncryptionKey = "MAKV2SPBNI99212"; using (Aes encryptor = Aes.Create()) { Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); encryptor.Key = pdb.GetBytes(32); encryptor.IV = pdb.GetBytes(16); using (FileStream fsInput = new FileStream(inputFilePath, FileMode.Open)) { using (CryptoStream cs = new CryptoStream(fsInput, encryptor.CreateDecryptor(), CryptoStreamMode.Read)) { using (FileStream fsOutput = new FileStream(outputfilePath, FileMode.Create)) { int data; while ((data = cs.ReadByte()) != -1) { fsOutput.WriteByte((byte)data); } }
} } } }
VB.Net
Private Sub Encrypt(inputFilePath As String, outputfilePath As String) Dim EncryptionKey As String = "MAKV2SPBNI99212" Using encryptor As Aes = Aes.Create() Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _ &H65, &H64, &H76, &H65, &H64, &H65, _ &H76}) encryptor.Key = pdb.GetBytes(32) encryptor.IV = pdb.GetBytes(16) Using fs As New FileStream(outputfilePath, FileMode.Create) Using cs As New CryptoStream(fs, encryptor.CreateEncryptor(), CryptoStreamMode.Write) Using fsInput As New FileStream(inputFilePath, FileMode.Open) Dim data As Integer While (Assign(data, fsInput.ReadByte())) <> -1 cs.WriteByte(CByte(data)) End While End Using End Using End Using End Using End Sub
Private Sub Decrypt(inputFilePath As String, outputfilePath As String) Dim EncryptionKey As String = "MAKV2SPBNI99212"
Using encryptor As Aes = Aes.Create() Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _ &H65, &H64, &H76, &H65, &H64, &H65, _ &H76}) encryptor.Key = pdb.GetBytes(32) encryptor.IV = pdb.GetBytes(16) Using fs As New FileStream(inputFilePath, FileMode.Open) Using cs As New CryptoStream(fs, encryptor.CreateDecryptor(), CryptoStreamMode.Read) Using fsOutput As New FileStream(outputfilePath, FileMode.Create) Dim data As Integer While (Assign(data, cs.ReadByte())) <> -1 fsOutput.WriteByte(CByte(data)) End While End Using End Using End Using End Using End Sub
Insert (Update) Data to Database with jQuery AJAX and WebMethod in ASP.Net
15 Nov 2013 Mudassar Khan 1 Comments 5258 Views
Here Mudassar Ahmed Khan has explained how to insert or update data asynchronously (without PostBack) to database using jQuery AJAX and Page Methods (WebMethod on Page) in ASP.Net.
Download
In this article I will explain how to insert or update data asynchronously (without PostBack) to database using jQuery AJAX and Page Methods (WebMethod on Page) in ASP.Net.
Database Schema I have created a new database named UsersDB which consist of one table named Users with the following schema.
HTML Markup The HTML Markup consists of Username and Password TextBoxes and a GridView to display the inserted Usernames and Passwords via jQuery AJAX.
<table border="0" cellpadding="0" cellspacing="0"> <tr> <td> Username: </td> <td> <asp:TextBox ID="txtUsername" runat="server" Text="" /> </td> </tr> <tr> <td> Password: </td>
<td> <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" /> </td> </tr> <tr> <td> </td> <td> <asp:Button ID="btnSave" Text="Save" runat="server" /> </td> </tr> </table> <hr /> <asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="false" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White" RowStyle-BackColor="#A1DCF2"> <Columns> <asp:BoundField DataField="Username" HeaderText="Username" /> <asp:BoundField DataField="Password" HeaderText="Password" /> </Columns> </asp:GridView>
jQuery AJAX Implementation to save Form data to database in ASP.Net Below is the jQuery AJAX implementation to save the form data i.e. value of the Username and Password TextBoxes to database. Note: If you want to know more about the jQuery AJAX usage in ASP.Net, please refer Call ASP.Net Page Method
using jQuery AJAX
A JavaScript Custom Object with the name user is created and the within it I have added two child properties Username and Password, this resemble a class object in C#. The Username and Password TextBox values are set within these properties and then the Object converted to a string using the JSON stringify method of theJSON2.js library and it is passed as data parameter to the jQuery AJAX Method call to the SaveUser method.
When the jQuery AJAX Call is successful a JavaScript Alert message is displayed and the page is reloaded so that the record can be viewed within the GridView control.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script> <script type="text/javascript"> $(function () { $("[id*=btnSave]").bind("click", function () { var user = {}; user.Username = $("[id*=txtUsername]").val(); user.Password = $("[id*=txtPassword]").val(); $.ajax({ type: "POST", url: "Default.aspx/SaveUser", data: '{user: ' + JSON.stringify(user) + '}', contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { alert("User has been added successfully."); window.location.reload(); } }); return false; }); }); </script>
Class Implementation Below is the class implementation, this class resembles the JavaScript Custom Object (discussed earlier). This object will be used to fetch and hold the Username and Password values sent by the jQuery AJAX method.
Note: It is very important the names of the Properties within the class must exactly match with that of the JavaScript Custom object Properties otherwise the jQuery AJAX will not execute the WebMethod. C#
public class User { public string Username { get; set; } public string Password { get; set; } }
VB.Net
Public Class User Public Property Username() As String Get Return _Username End Get Set(value As String) _Username = Value End Set End Property Private _Username As String Public Property Password() As String Get Return _Password End Get Set(value As String) _Password = Value End Set End Property Private _Password As String End Class
VB.Net
Imports System.Data Imports System.Data.SqlClient Imports System.Configuration Imports System.Web.Services Imports System.Web.Script.Services
Server Side WebMethod to handle the jQuery AJAX Call The following WebMethod will be executed when the jQuery AJAX call is made from client side. This method accepts the User object from client side and then the Username and Password values are inserted in the database. C#
[WebMethod] [ScriptMethod] public static void SaveUser(User user) { string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) {
using (SqlCommand cmd = new SqlCommand("INSERT INTO Users VALUES(@Username, @Password)")) { cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@Username", user.Username); cmd.Parameters.AddWithValue("@Password", user.Password); cmd.Connection = con; con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } }
VB.Net
<WebMethod ()> _ <ScriptMethod ()> _ Public Shared Sub SaveUser(user As User) Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionStrin g Using con As New SqlConnection(constr) Using cmd As New SqlCommand("INSERT INTO Users VALUES(@Username, @Password)") cmd.CommandType = CommandType.Text cmd.Parameters.AddWithValue("@Username", user.Username) cmd.Parameters.AddWithValue("@Password", user.Password) cmd.Connection = con con.Open() cmd.ExecuteNonQuery() con.Close() End Using End Using
End Sub
Adding ASP.Net GridView control to display the inserted records In the Page Load event handler of the Page, the ASP.Net GridView is populated with the records from the Users table. C#
protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("SELECT * FROM Users")) { using (SqlDataAdapter sda = new SqlDataAdapter()) { DataTable dt = new DataTable(); cmd.CommandType = CommandType.Text; cmd.Connection = con; sda.SelectCommand = cmd; sda.Fill(dt); gvUsers.DataSource = dt; gvUsers.DataBind(); } } } } }
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load If Not Me.IsPostBack Then Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionS tring Using con As New SqlConnection(constr) Using cmd As New SqlCommand("SELECT * FROM Users") Using sda As New SqlDataAdapter() Dim dt As New DataTable() cmd.CommandType = CommandType.Text cmd.Connection = con sda.SelectCommand = cmd sda.Fill(dt) gvUsers.DataSource = dt gvUsers.DataBind() End Using End Using End Using End If End Sub
In this article I will explain how to use the Windows Forms WebBrowser control in ASP.Net Website using C# and VB.Net. The WebBrowser control will be used to capture the screenshot of a Website web page.
Referencing the WebBrowser control in ASP.Net Since the WebBrowser is a Windows Forms controls, in order to use it in ASP.Net Web Projects, we will have to add reference to the following libraries.
HTML Markup The HTML Markup consist of a TextBox, a Button and an Image control.
<asp:TextBox ID="txtUrl" runat="server" Text = "" /> <asp:Button Text="Capture" runat="server" OnClick="Capture" /> <br /> <asp:Image ID="imgScreenShot" runat="server" Height="300" Width="400" Visible = "false" />
VB.Net
Imports System.IO Imports System.Drawing Imports System.Threading Imports System.Windows.Forms
Capture Screenshot (Snapshot) Image of Website (Web Page) in ASP.Net using C# and VB.Net When the Button is clicked the following event handler is raised, here a new Thread is initiated and the WebBrowser control is initialized within the Thread. For the WebBrowser I have attached a DocumentCompleted event handler which will be raised when the Web Page is loaded inside the browser. Note: Since ASP.Net applications work in Multi-Threaded Apartments (MTA) we need to start a new Thread for the WebBrowser control and execute the Thread in Single-Threaded Apartments (STA). Inside the DocumentCompleted event handler, the Web Page loaded inside the WebBrowser control is drawn to a Bitmap which is then converted to a Byte Array and then to Base64 string so that it can be displayed in the Image control. To know more about Base64 string, please refer Display byte Array as Image without using Generic Handler in ASP.Net
C#
protected void Capture(object sender, EventArgs e) { string url = txtUrl.Text.Trim(); Thread thread = new Thread(delegate() { using (WebBrowser browser = new WebBrowser()) { browser.ScrollBarsEnabled = false; browser.AllowNavigation = true;
browser.Navigate(url); browser.Width = 1024; browser.Height = 768; browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(DocumentCompleted); while (browser.ReadyState != WebBrowserReadyState.Complete) { System.Windows.Forms.Application.DoEvents(); } } }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); }
private void DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { WebBrowser browser = sender as WebBrowser; using (Bitmap bitmap = new Bitmap(browser.Width, browser.Height)) { browser.DrawToBitmap(bitmap, new Rectangle(0, 0, browser.Width, browser.Height)); using (MemoryStream stream = new MemoryStream()) { bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png); byte[] bytes = stream.ToArray(); imgScreenShot.Visible = true; imgScreenShot.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(bytes); }
} }
VB.Net
Protected Sub Capture(sender As Object, e As EventArgs) Dim url As String = txtUrl.Text.Trim() Dim thread As New Thread(Sub() Using browser As New WebBrowser() browser.ScrollBarsEnabled = False browser.AllowNavigation = True browser.Navigate(url) browser.Width = 1024 browser.Height = 768 AddHandler browser.DocumentCompleted, New WebB rowserDocumentCompletedEventHandler(AddressOf DocumentCompleted) While browser.ReadyState <> WebBrowserReadyState.Complete System.Windows.Forms.Application.DoEvents() End While End Using End Sub) thread.SetApartmentState(ApartmentState.STA) thread.Start() thread.Join() End Sub
Private Sub DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Dim browser As WebBrowser = TryCast(sender, WebBrowser) Using bitmap As New Bitmap(browser.Width, browser.Height) browser.DrawToBitmap(bitmap, New Rectangle(0, 0, browser.Width, browser.Height))
Using stream As New MemoryStream() bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png) Dim bytes As Byte() = stream.ToArray() imgScreenShot.Visible = True imgScreenShot.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(bytes) End Using End Using End Sub
Change (Modify) connection string in Web.Config at Runtime in ASP.Net using C# and VB.Net
13 Nov 2013 Mudassar Khan
0 Comments
2052 Views
In this article I will explain how to programmatically add, modify (change) and update SQL connection strings at runtime in ASP.Net Web.Config file using C# and VB.Net. He has explained how we can access and update the different attributes of a connection string like DataSource, IntitialCatalog, UserId, Password and IntegratedSecurity.
VB.Net
Imports System.Xml Imports System.Data.SqlClient
Code snippet to add or update Connection String in Web.Config file The following method adds or updates the connection string based on the connection string name. If the connection string with the name does not exists a new connection string node will be created in the Web.Config file. C#
private void AddUpdateConnectionString(string name) {
bool isNew = false; string path = Server.MapPath("~/Web.Config"); XmlDocument doc = new XmlDocument(); doc.Load(path); XmlNodeList list = doc.DocumentElement.SelectNodes(string.Format("connectionStrings/add[@name='{0}']", name)); XmlNode node; isNew = list.Count == 0; if (isNew) { node = doc.CreateNode(XmlNodeType.Element, "add", null); XmlAttribute attribute = doc.CreateAttribute("name"); attribute.Value = name; node.Attributes.Append(attribute);
attribute = doc.CreateAttribute("providerName"); attribute.Value = "System.Data.SqlClient"; node.Attributes.Append(attribute); } else { node = list[0]; } string conString = node.Attributes["connectionString"].Value; SqlConnectionStringBuilder conStringBuilder = new SqlConnectionStringBuilder(conString); conStringBuilder.InitialCatalog = "TestDB";
conStringBuilder.DataSource = "myserver"; conStringBuilder.IntegratedSecurity = false; conStringBuilder.UserID = "test"; conStringBuilder.Password = "12345"; node.Attributes["connectionString"].Value = conStringBuilder.ConnectionString; if (isNew) { doc.DocumentElement.SelectNodes("connectionStrings")[0].AppendChild(node); } doc.Save(path); }
VB.Net
Private Sub AddUpdateConnectionString(name As String) Dim isNew As Boolean = False Dim path As String = Server.MapPath("~/Web.Config") Dim doc As New XmlDocument() doc.Load(path) Dim list As XmlNodeList = doc.DocumentElement.SelectNodes(String.Format("connectionStrings/add[@name='{0}']", name)) Dim node As XmlNode isNew = list.Count = 0 If isNew Then node = doc.CreateNode(XmlNodeType.Element, "add", Nothing) Dim attribute As XmlAttribute = doc.CreateAttribute("name") attribute.Value = name node.Attributes.Append(attribute)
node.Attributes.Append(attribute)
attribute = doc.CreateAttribute("providerName") attribute.Value = "System.Data.SqlClient" node.Attributes.Append(attribute) Else node = list(0) End If Dim conString As String = node.Attributes("connectionString").Value Dim conStringBuilder As New SqlConnectionStringBuilder(conString) conStringBuilder.InitialCatalog = "TestDB" conStringBuilder.DataSource = "myserver" conStringBuilder.IntegratedSecurity = False conStringBuilder.UserID = "test" conStringBuilder.Password = "12345" node.Attributes("connectionString").Value = conStringBuilder.ConnectionString If isNew Then doc.DocumentElement.SelectNodes("connectionStrings")(0).AppendChild(node) End If doc.Save(path) End Sub
Capture Screenshot (Snapshot) Image of Website (Web Page) in ASP.Net using C# and VB.Net
12 Nov 2013 Mudassar Khan 2 Comments ASP.Net Tips
Here Mudassar Ahmed Khan has explained how to capture a screenshot (snapshot) of a Website web page using ASP.Net using C# and VB.Net. To capture the screenshot (snapshot) of a Website web page, I am making use of WebBrowser control of Windows Forms Application.
Download
3074 Views
In this article I will explain how to capture a screenshot (snapshot) of a Website web page using ASP.Net using C# and VB.Net. To capture the screenshot (snapshot) of a Website web page, I am making use of WebBrowser control of Windows Forms Application.
Referencing the WebBrowser control in ASP.Net Since the WebBrowser is a Windows Forms controls, in order to use it in ASP.Net Web Projects, we will have to add reference to the following libraries.
HTML Markup The HTML Markup consist of a TextBox, a Button and an Image control.
<asp:TextBox ID="txtUrl" runat="server" Text = "" />
<asp:Button Text="Capture" runat="server" OnClick="Capture" /> <br /> <asp:Image ID="imgScreenShot" runat="server" Height="300" Width="400" Visible = "false" />
VB.Net
Imports System.IO Imports System.Drawing Imports System.Threading Imports System.Windows.Forms
Capture Screenshot (Snapshot) Image of Website (Web Page) in ASP.Net using C# and VB.Net When the Button is clicked the following event handler is raised, here a new Thread is initiated and the WebBrowser control is initialized within the Thread. For the WebBrowser I have attached a DocumentCompleted event handler which will be raised when the Web Page is loaded inside the browser. Note: Since ASP.Net applications work in Multi-Threaded Apartments (MTA) we need to start a new Thread for the WebBrowser control and execute the Thread in Single-Threaded Apartments (STA). Inside the DocumentCompleted event handler, the Web Page loaded inside the WebBrowser control is drawn to a Bitmap which is then converted to a Byte Array and then to Base64 string so that it can be displayed in the Image control. To know more about Base64 string, please refer Display byte Array as Image without using Generic Handler in ASP.Net
C#
protected void Capture(object sender, EventArgs e) { string url = txtUrl.Text.Trim(); Thread thread = new Thread(delegate() { using (WebBrowser browser = new WebBrowser()) { browser.ScrollBarsEnabled = false; browser.AllowNavigation = true; browser.Navigate(url); browser.Width = 1024; browser.Height = 768; browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(DocumentCompleted); while (browser.ReadyState != WebBrowserReadyState.Complete) { System.Windows.Forms.Application.DoEvents(); } } }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); }
private void DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { WebBrowser browser = sender as WebBrowser; using (Bitmap bitmap = new Bitmap(browser.Width, browser.Height)) {
browser.DrawToBitmap(bitmap, new Rectangle(0, 0, browser.Width, browser.Height)); using (MemoryStream stream = new MemoryStream()) { bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png); byte[] bytes = stream.ToArray(); imgScreenShot.Visible = true; imgScreenShot.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(bytes); } } }
VB.Net
Protected Sub Capture(sender As Object, e As EventArgs) Dim url As String = txtUrl.Text.Trim() Dim thread As New Thread(Sub() Using browser As New WebBrowser() browser.ScrollBarsEnabled = False browser.AllowNavigation = True browser.Navigate(url) browser.Width = 1024 browser.Height = 768 AddHandler browser.DocumentCompleted, New WebB rowserDocumentCompletedEventHandler(AddressOf DocumentCompleted) While browser.ReadyState <> WebBrowserReadyState.Complete System.Windows.Forms.Application.DoEvents() End While End Using End Sub) thread.SetApartmentState(ApartmentState.STA)
Private Sub DocumentCompleted(sender As Object, e As WebBrowserDocumentCompletedEventArgs) Dim browser As WebBrowser = TryCast(sender, WebBrowser) Using bitmap As New Bitmap(browser.Width, browser.Height) browser.DrawToBitmap(bitmap, New Rectangle(0, 0, browser.Width, browser.Height)) Using stream As New MemoryStream() bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png) Dim bytes As Byte() = stream.ToArray() imgScreenShot.Visible = True imgScreenShot.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(bytes) End Using End Using End Sub
2243 Views
In this article I have explained how to submit an ASP.Net Form when Enter Key is pressed in ASP.Net using the DefaultButton property of ASP.Net Form and ASP.Net Panel.
This can be done at Form Level as well as using Panels to submit different sections of an ASP.Net Form. Default Button property ensures that whenever user presses Enter key the button that is set as default will be triggered.
Default Button in form. One can set the default button at the form level meaning of all the buttons in the form the one that is set as default will be triggered whenever user presses Enter key. To set the default button one has to do the following <form id="form1" runat="server" defaultbutton="Button1"> <asp:Button ID="Button1" runat="server" Text="Button" OnClick = "Button1_Click" /> <asp:Button ID="Button2" runat="server" Text="Button" OnClick = "Button2_Click" /> <asp:Button ID="Button3" runat="server" Text="Button" OnClick = "Button3_Click" /> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> </form> You just need to provide the ID of the Button to the defaultbutton property and it is set as default. If you want to do it from code behind refer below C# this.Form.DefaultButton = "Button1";
Default Button in Master Page When working with master pages if the button you want to set at default resides in the content page thus the ID of the controls in the content page tend to change hence in that case you need to do the following
C# this.Form.DefaultButton = Button1.UniqueID;
Default Buttons at Panel Level Default buttons can also be set at the panel level using the DefaultButton property of the panel <asp:Panel ID="Panel1" runat="server" DefaultButton = "Button1"> <asp:Button ID="Button1" runat="server" Text="Button" OnClick = "Button1_Click" /> <asp:Button ID="Button2" runat="server" Text="Button" OnClick = "Button2_Click" /> <asp:Button ID="Button3" runat="server" Text="Button" OnClick = "Button3_Click" /> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> </asp:Panel> This will be useful in case you need to set multiple default buttons and use them for specific set controls. So in that case you can place the button inside different panels and whenever user presses enter key within the scope of that panel the default button for that panel is triggered. The same can be done from code behind C# Panel1.DefaultButton = "Button1";
In case you want to use this with Master Pages you will again need to provide the UniqueID in the same way as done for the explained for the Form Default Buttons earlier.
Encrypt and Decrypt QueryString Parameter Values in ASP.Net using C# and VB.Net
03 Nov 2013 Mudassar Khan 5 Comments 5164 Views
ASP.Net Cryptography
Here Mudassar Ahmed Khan has explained how to encrypt QueryString Parameter values and pass it to another page and then decrypt the encrypted QueryString Parameter values in ASP.Net using C# and VB.Net. The QueryString Parameter values will be first encrypted using AES Symmetric key (Same key) algorithm, encoded (as the encrypted output might contain some special characters) and then will be sent to next page. On the destination page the QueryString Parameter values will be first decoded and then decrypted using AES Algorithm using the same key that was used for encryption.
Download View Demo
In this article I will explain how to encrypt QueryString Parameter values and pass it to another page and then decrypt the encrypted QueryString Parameter values in ASP.Net using C# and VB.Net. The QueryString Parameter values will be first encrypted using AES Symmetric key (Same key) algorithm, encoded (as the encrypted output might contain some special characters) and then will be sent to next page. On the destination page the QueryString Parameter values will be first decoded and then decrypted using AES Algorithm using the same key that was used for encryption.
HTML Markup Page 1 The following HTML Markup consists of a TextBox, a DropDownList and a Button. The value from the TextBox and the DropDownLists will be encrypted and send using QueryString Parameters to the next page on Button click.
<table border="0" cellpadding="0" cellspacing="0"> <tr> <td> Name: </td> <td> <asp:TextBox ID="txtName" runat="server" Text="Mudassar Khan" />
</td> </tr> <tr> <td> Technology: </td> <td> <asp:DropDownList ID = "ddlTechnology" runat="server"> <asp:ListItem Text="ASP.Net" Value = "ASP.Net" /> <asp:ListItem Text="PHP" Value = "PHP" /> <asp:ListItem Text="JSP" Value = "JSP" /> </asp:DropDownList> </td> </tr> </table> <hr /> <asp:Button ID="Button1" Text="Submit" runat="server" OnClick = "Submit" />
Page 2 The following HTML Markup consists of two Label controls which will be used to display the QueryString Parameter values received on the page.
<table border="0" cellpadding="0" cellspacing="0"> <tr> <td> Name: </td> <td> <asp:Label ID="lblName" runat="server" Text="" /> </td> </tr>
<tr> <td> Technology: </td> <td> <asp:Label ID="lblTechnology" runat="server" Text="" /> </td> </tr> </table>
VB.Net
Imports System.IO Imports System.Text Imports System.Security.Cryptography
AES Algorithm Encryption and Decryption functions Below are the functions for Encryption and Decryption which will be used for the Encrypting or Decrypting QueryString Parameter Values. Note: The following functions have been explained in the article AES Encryption Decryption (Cryptography) Tutorial with
example in ASP.Net using C# and VB.Net
Encrypting the QueryString Parameter Values When the Button is clicked the following event handler is executed. Here the values of the TextBox and the DropDownList are first encrypted using the AES Symmetric Key Algorithm and then encoded using the UrlEncode method of the HttpUtility class. Finally these values are sent as QueryString Parameters to the next page. Note: Here Encoding is required as the Encrypted string contains special characters and it is necessary to encode special characters before sending them as QueryString parameter. C#
protected void Submit(object sender, EventArgs e) { string name = HttpUtility.UrlEncode(Encrypt(txtName.Text.Trim())); string technology = HttpUtility.UrlEncode(Encrypt(ddlTechnology.SelectedItem.Value)); Response.Redirect(string.Format("~/CS2.aspx?name={0}&technology={1}", name, technology)); }
private string Encrypt(string clearText) { string EncryptionKey = "MAKV2SPBNI99212"; byte[] clearBytes = Encoding.Unicode.GetBytes(clearText); using (Aes encryptor = Aes.Create()) { Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); encryptor.Key = pdb.GetBytes(32); encryptor.IV = pdb.GetBytes(16); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(clearBytes, 0, clearBytes.Length);
VB.Net
Protected Sub Submit(sender As Object, e As EventArgs) Dim name As String = HttpUtility.UrlEncode(Encrypt(txtName.Text.Trim())) Dim technology As String = HttpUtility.UrlEncode(Encrypt(ddlTechnology.SelectedItem .Value)) Response.Redirect(String.Format("~/VB2.aspx?name={0}&technology={1}", name, technology)) End Sub
Private Function Encrypt(clearText As String) As String Dim EncryptionKey As String = "MAKV2SPBNI99212" Dim clearBytes As Byte() = Encoding.Unicode.GetBytes(clearText) Using encryptor As Aes = Aes.Create() Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _ &H65, &H64, &H76, &H65, &H64, &H65, _ &H76}) encryptor.Key = pdb.GetBytes(32) encryptor.IV = pdb.GetBytes(16) Using ms As New MemoryStream() Using cs As New CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write) cs.Write(clearBytes, 0, clearBytes.Length) cs.Close()
End Using clearText = Convert.ToBase64String(ms.ToArray()) End Using End Using Return clearText End Function
Decrypting the QueryString Parameter Values In the Page Load event of the page, the values of the TextBox and DropDownList sent from the previous page are first fetched from the QueryString Parameters and then are decoded using the UrlDecode method of the HttpUtility class. After decoding the string is decrypted using the AES Symmetric Key Algorithm and then the decrypted values are displayed using Label controls. C#
protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { lblName.Text = Decrypt(HttpUtility.UrlDecode(Request.QueryString["name"])); lblTechnology.Text = Decrypt(HttpUtility.UrlDecode(Request.QueryString["technology"])); } }
private string Decrypt(string cipherText) { string EncryptionKey = "MAKV2SPBNI99212"; cipherText = cipherText.Replace(" ", "+"); byte[] cipherBytes = Convert.FromBase64String(cipherText); using (Aes encryptor = Aes.Create()) {
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); encryptor.Key = pdb.GetBytes(32); encryptor.IV = pdb.GetBytes(16); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(cipherBytes, 0, cipherBytes.Length); cs.Close(); } cipherText = Encoding.Unicode.GetString(ms.ToArray()); } } return cipherText; }
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load If Not Me.IsPostBack Then lblName.Text = Decrypt(HttpUtility.UrlDecode(Request.QueryString("name"))) lblTechnology.Text = Decrypt(HttpUtility.UrlDecode(Request.QueryString("technology"))) End If End Sub
Private Function Decrypt(cipherText As String) As String Dim EncryptionKey As String = "MAKV2SPBNI99212" cipherText = cipherText.Replace(" ", "+") Dim cipherBytes As Byte() = Convert.FromBase64String(cipherText)
Using encryptor As Aes = Aes.Create() Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _ &H65, &H64, &H76, &H65, &H64, &H65, _ &H76}) encryptor.Key = pdb.GetBytes(32) encryptor.IV = pdb.GetBytes(16) Using ms As New MemoryStream() Using cs As New CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write) cs.Write(cipherBytes, 0, cipherBytes.Length) cs.Close() End Using cipherText = Encoding.Unicode.GetString(ms.ToArray()) End Using End Using Return cipherText End Function
Read and Import Excel File into DataSet or DataTable using C# and VB.Net in ASP.Net
31 Oct 2013 Mudassar Khan 0 Comments 9642 Views
ASP.Net Excel
Here Mudassar Ahmed Khan has explained how to upload Excel File and then read and import its data into DataSet or DataTable using C# and VB.Net in ASP.Net Web Application. The imported Excel File data is then displayed in ASP.Net GridView control.
Download
how to upload Excel File and then read and import its data into DataSet or DataTable using C# and VB.Net in ASP.Net Web Application.
The imported Excel File data is then displayed in ASP.Net GridView control. In one of my articles I explained How to Read Excel using ADO.Net
Concept 1. User browses and selects an Excel Workbook. 2. User selects whether Header row is present in Excel Sheet or not using radio buttons. 3. User uploads the Excel Workbook 4. Uploaded File is read by the application into a DataSet and displayed on the web page using GridView Control. 5. GridView has paging enabled so that user can view the records easily.
Connection Strings Since there Excel 97-2003 and Excel 2007 use different providers I have placed two connection strings keys in the Web.Config. <connectionStrings> <add name ="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}; Extended Properties='Excel 8.0;HDR={1}'"/> <add name ="Excel07ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties='Excel 8.0;HDR={1}'"/> </connectionStrings>
You will notice above there are two connection strings one for Excel 97 2003 format which uses Microsoft Jet driver and another one is for Excel 2007 format which uses Microsoft Ace driver. I have used Placeholders for Data Source {0} and the HDR {1} property so that I can easily replace fill it in the front end based on the Excel File Selected and the Headers property selected by the user through the checkbox respectively
The front end design of the web page contains a FileUpload Control, a Button which will be used to upload the Excel File, RadioButtonList for the user to select whether headers are present or not by default Yes is selected and finally the GridView control in which I have set AllowPaging property to true. <asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" /> <br /> <asp:Label ID="Label1" runat="server" Text="Has Header ?" /> <asp:RadioButtonList ID="rbHDR" runat="server"> <asp:ListItem Text = "Yes" Value = "Yes" Selected = "True" > </asp:ListItem> <asp:ListItem Text = "No" Value = "No"></asp:ListItem> </asp:RadioButtonList> <asp:GridView ID="GridView1" runat="server" OnPageIndexChanging = "PageIndexChanging" AllowPaging = "true"> </asp:GridView>
Uploading and Reading the Excel Sheet Next comes the part to upload the file and reading it. As you will notice in the aspx I have added OnClick event handler to the Upload button which will be triggered when the upload button is clicked When the upload button is clicked the uploaded File is saved to a Folder whose path is defined in the App Settings section in the Web.Config using the following key <appSettings> <add key ="FolderPath" value ="Files/"/> </appSettings >
Once the File is saved in the folder the Import_To_Grid method is called up which is described later. Below is the code snippet for the Upload button event handler
C#
protected void btnUpload_Click(object sender, EventArgs e) { if (FileUpload1.HasFile) { string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName); string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName); string FolderPath = ConfigurationManager.AppSettings["FolderPath"];
VB.Net Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs ) If FileUpload1.HasFile Then Dim FileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName) Dim Extension As String = Path.GetExtension(FileUpload1.PostedFile.FileName) Dim FolderPath As String = ConfigurationManager.AppSettings("FolderPath")
Dim FilePath As String = Server.MapPath(FolderPath + FileName) FileUpload1.SaveAs(FilePath) Import_To_Grid(FilePath, Extension, rbHDR.SelectedItem.Text) End If End Sub
Now the saved Excel file is read using OLEDB. Based on the extension I decide the driver to be used in order to read the excel file and also whether Excel will be read along with header row or not based on the RadioButtonList. All these values are filled in the placeholders of the connection string. After that I read the schema of the Excel Workbook in order to find out the Sheet Name of the first sheet. Once I get that I fire a select query on the first Excel sheet and fill a datatable which is then passed to the GridView as data source. You can refer the complete function below
C#
private void Import_To_Grid(string FilePath, string Extension, string isHDR) { string conStr=""; switch (Extension) { case ".xls": //Excel 97-03 conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"] .ConnectionString; break; case ".xlsx": //Excel 07 conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"] .ConnectionString; break; } conStr = String.Format(conStr, FilePath, isHDR); OleDbConnection connExcel = new OleDbConnection(conStr); OleDbCommand cmdExcel = new OleDbCommand(); OleDbDataAdapter oda = new OleDbDataAdapter(); DataTable dt = new DataTable(); cmdExcel.Connection = connExcel;
//Get the name of First Sheet connExcel.Open(); DataTable dtExcelSchema; dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString(); connExcel.Close();
//Read Data from First Sheet connExcel.Open(); cmdExcel.CommandText = "SELECT * From [" + SheetName + "]"; oda.SelectCommand = cmdExcel; oda.Fill(dt); connExcel.Close();
VB.Net Private Sub Import_To_Grid(ByVal FilePath As String, ByVal Extension As String, ByV al isHDR As String) Dim conStr As String = "" Select Case Extension Case ".xls" 'Excel 97-03
conStr = ConfigurationManager.ConnectionStrings("Excel03ConString") _ .ConnectionString Exit Select Case ".xlsx" 'Excel 07 conStr = ConfigurationManager.ConnectionStrings("Excel07ConString") _ .ConnectionString Exit Select End Select conStr = String.Format(conStr, FilePath, isHDR)
Dim connExcel As New OleDbConnection(conStr) Dim cmdExcel As New OleDbCommand() Dim oda As New OleDbDataAdapter() Dim dt As New DataTable()
cmdExcel.Connection = connExcel
'Get the name of First Sheet connExcel.Open() Dim dtExcelSchema As DataTable dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing) Dim SheetName As String = dtExcelSchema.Rows(0)("TABLE_NAME").ToString() connExcel.Close()
cmdExcel.CommandText = "SELECT * From [" & SheetName & "]" oda.SelectCommand = cmdExcel oda.Fill(dt) connExcel.Close()
Pagination in GridView Now in order to implement paging we will need to read the excel sheet each time and then rebind datatable to the GridView. Refer below
C# protected void PageIndexChanging(object sender, GridViewPageEventArgs e) { string FolderPath = ConfigurationManager.AppSettings["FolderPath"] ; string FileName = GridView1.Caption; string Extension = Path.GetExtension(FileName); string FilePath = Server.MapPath(FolderPath + FileName);
VB.Net Protected Sub PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEv entArgs) Dim FolderPath As String = ConfigurationManager.AppSettings("FolderPath") Dim FileName As String = GridView1.Caption Dim Extension As String = Path.GetExtension(FileName) Dim FilePath As String = Server.MapPath(FolderPath + FileName)
The figure below displays the GridView populated from the excel workbook that is uploaded using the FileUpload Control.
Important thing to note that always close the connections after reading the Excel Workbook to avoid the following error
The process cannot access the file 'F:\ReadExcelToGrid\Files\Excel07.xlsx' because it is being used by another process.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.IO.IOException: The process cannot access the file 'F:\ReadExcelToGrid\Files\Excel07.xlsx' because it is being used by another process.
Crystal Report ASP.Net Example using DataSet or DataTable in C# VB.Net and Visual Studio 2010
15 Feb 2013 Mudassar Khan 1 Comments 22560 Views
In this article I will explain step by step how to create and use Crystal Reports in ASP.Net Web Application using Visual Studio 2010.
Note: By default Visual Studio 2010 does not include Crystal Reports hence you need to download the Crystal Reports 13. Refer my article for details Download Crystal Reports for Visual Studio 2010
Database Here I am making use of Microsofts Northwind Database. You can download it from here Download and install Northwind Database
1. Add Typed DataSet to the ASP.Net Website Since I am using disconnected Crystal Reports we will make use of Typed DataSet to populate the Crystal Reports with data from database.
2. Adding DataTable to the Typed DataSet Our next step would be to add a DataTable to the Type DataSet.
3. Adding Columns or fields to DataTable In the DataTable we need to specify the column names that we want to display in the Crystal Report.
Note: The Column Names of the DataTable must exactly match with the actual Database Table column names.
By default all the columns are of String Data Type but you can also change the data type as per your need.
4. Add Crystal Report to the ASP.Net Website Now you will need to add a Crystal Report to the ASP.Net Application. You can give it name as per your choice.
As soon as you click OK you get the following dialog. You must select Using the Report Wizard option.
Once you press OK in the above dialog, the Report Wizard starts and you get the following dialog where you need to choose the type of Database connection for your Crystal Report. Since we are using DataSet we will choose the Customers DataSet.
Next the Wizard will ask for the Columns or Fields from the Customer DataSet you need to display on the Crystal Reports. You can choose either all or specific fields as per you choice.
Note: There are more steps in the Wizards but those are Optional hence are not included in this article.
Once you click Finish your Crystal Report should look as below
HTML Markup The HTML Markup is simple and contains a CrystalReportViewer control.
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>title> head> <body> <form id="form1" runat="server"> <CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="true" /> form>
body> html>
VB.Net
Imports System.Data Imports System.Configuration Imports System.Data.SqlClient Imports CrystalDecisions.CrystalReports.Engine
Populating the Crystal Report from Database I am populating Crystal Reports from database in the Page Load event of the page using the following code C#
protected void Page_Load(object sender, EventArgs e) { ReportDocument crystalReport = new ReportDocument(); crystalReport.Load(Server.MapPath("~/CustomerReport.rpt")); Customers dsCustomers = GetData("select * from customers"); crystalReport.SetDataSource(dsCustomers);
CrystalReportViewer1.ReportSource = crystalReport; }
private Customers GetData(string query) { string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; SqlCommand cmd = new SqlCommand(query); using (SqlConnection con = new SqlConnection(conString)) { using (SqlDataAdapter sda = new SqlDataAdapter()) { cmd.Connection = con;
sda.SelectCommand = cmd; using (Customers dsCustomers = new Customers()) { sda.Fill(dsCustomers, "DataTable1"); return dsCustomers; } } } }
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load Dim crystalReport As New ReportDocument() crystalReport.Load(Server.MapPath("~/CustomerReport.rpt")) Dim dsCustomers As Customers = GetData("select * from customers") crystalReport.SetDataSource(dsCustomers) CrystalReportViewer1.ReportSource = crystalReport
End Sub
Private Function GetData(query As String) As Customers Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionSt ring Dim cmd As New SqlCommand(query) Using con As New SqlConnection(conString) Using sda As New SqlDataAdapter() cmd.Connection = con
sda.SelectCommand = cmd Using dsCustomers As New Customers() sda.Fill(dsCustomers, "DataTable1") Return dsCustomers End Using End Using End Using End Function
ASP.Net GridView
Here Mudassar Ahmed Khan has explained how to find and access controls in GridView EmptyDataTemplate (Empty Row) in ASP.Net using C# and VB.Net.
Download
In this article I will explain how to find and access controls in GridView EmptyDataTemplate (Empty Row) in ASP.Net using C# and VB.Net.
HTML Markup The HTML Markup consists of a GridView, a Button and placed a Label control inside the GridView EmptyDataTemplate.
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White" runat="server" AutoGenerateColumns="false"> <Columns> <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" /> <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="150" /> </Columns> <EmptyDataTemplate> <asp:Label ID = "lblEmptyMessage" Text="" runat="server" /> </EmptyDataTemplate> </asp:GridView> <br /> <asp:Button ID = "btnClear" Text="Clear GridView" runat="server" OnClick = "Clear" />
VB.Net
Imports System.Data
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load If Not Me.IsPostBack Then Dim dt As New DataTable() dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id"), New DataColumn("Name"), New DataColumn("Country")}) dt.Rows.Add(1, "John Hammond", "United States") dt.Rows.Add(2, "Mudassar Khan", "India") dt.Rows.Add(3, "Suzanne Mathews", "France") dt.Rows.Add(4, "Robert Schidner", "Russia") GridView1.DataSource = dt GridView1.DataBind() End If
End Sub
Find and Access controls in GridView EmptyDataTemplate The following event handler is executed when the Button is clicked, here I am setting the GridView DataSource to NULL so that we can see the empty data row. Then I am searching for the Label control within the GridView EmptyDataTemplate and setting the empty message to be displayed. C#
protected void Clear(object sender, EventArgs e) { GridView1.DataSource = null; GridView1.DataBind(); Label lblEmptyMessage = GridView1.Controls[0].Controls[0].FindControl("lblEmptyMessage") as Label; lblEmptyMessage.Text = "Currently there are no records in system." ; }
VB.Net
Protected Sub Clear(sender As Object, e As EventArgs) GridView1.DataSource = Nothing GridView1.DataBind() Dim lblEmptyMessage As Label = TryCast(GridView1.Controls(0).Controls(0).FindCont rol("lblEmptyMessage"), Label) lblEmptyMessage.Text = "Currently there are no records in system." End Sub
Here Controls[0] is the Child Table within the GridView and the next Controls[0] is the GridView EmptyDataTemplate Row. C#
Label lblEmptyMessage = GridView1.Controls[0].Controls[0].FindControl("lblEmptyMessage") as Label;
VB.Net
Dim lblEmptyMessage As Label = TryCast(GridView1.Controls(0).Controls(0).FindControl( "lblEmptyMessage"), Label)
In this article I will explain how to save Form data asynchronously (without PostBack) to database using jQuery AJAX and Page Methods (WebMethod on Page) in ASP.Net. For this article I will make use of an ASP.Net WebMethod and the data from the form fields i.e. TextBox, DropDownList, etc. will be inserted into database table.
Database Schema I have created a new database named UsersDB which consist of one table named Users with the following schema.
HTML Markup The HTML Markup consists of Username and Password TextBoxes and a GridView to display the inserted Usernames and Passwords via jQuery AJAX.
<table border="0" cellpadding="0" cellspacing="0"> <tr> <td> Username: </td> <td> <asp:TextBox ID="txtUsername" runat="server" Text="" /> </td> </tr> <tr> <td> Password: </td> <td> <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" /> </td> </tr> <tr> <td> </td> <td>
<asp:Button ID="btnSave" Text="Save" runat="server" /> </td> </tr> </table> <hr /> <asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="false" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White" RowStyle-BackColor="#A1DCF2"> <Columns> <asp:BoundField DataField="Username" HeaderText="Username" /> <asp:BoundField DataField="Password" HeaderText="Password" /> </Columns> </asp:GridView>
jQuery AJAX Implementation to save Form data to database in ASP.Net Below is the jQuery AJAX implementation to save the form data i.e. value of the Username and Password TextBoxes to database. Note: If you want to know more about the jQuery AJAX usage in ASP.Net, please refer Call ASP.Net Page Method
using jQuery AJAX
A JavaScript Custom Object with the name user is created and the within it I have added two child properties Username and Password, this resemble a class object in C#. The Username and Password TextBox values are set within these properties and then the Object converted to a string using the JSON stringify method of theJSON2.js library and it is passed as data parameter to the jQuery AJAX Method call to the SaveUser method. When the jQuery AJAX Call is successful a JavaScript Alert message is displayed and the page is reloaded so that the record can be viewed within the GridView control.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script> <script type="text/javascript"> $(function () { $("[id*=btnSave]").bind("click", function () { var user = {};
user.Username = $("[id*=txtUsername]").val(); user.Password = $("[id*=txtPassword]").val(); $.ajax({ type: "POST", url: "Default.aspx/SaveUser", data: '{user: ' + JSON.stringify(user) + '}', contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { alert("User has been added successfully."); window.location.reload(); } }); return false; }); }); </script>
Class Implementation Below is the class implementation, this class resembles the JavaScript Custom Object (discussed earlier). This object will be used to fetch and hold the Username and Password values sent by the jQuery AJAX method. Note: It is very important the names of the Properties within the class must exactly match with that of the JavaScript Custom object Properties otherwise the jQuery AJAX will not execute the WebMethod. C#
public class User { public string Username { get; set; } public string Password { get; set; } }
VB.Net
Public Class User Public Property Username() As String Get Return _Username End Get Set(value As String) _Username = Value End Set End Property Private _Username As String Public Property Password() As String Get Return _Password End Get Set(value As String) _Password = Value End Set End Property Private _Password As String End Class
VB.Net
Imports System.Data Imports System.Data.SqlClient Imports System.Configuration Imports System.Web.Services Imports System.Web.Script.Services
Server Side WebMethod to handle the jQuery AJAX Call The following WebMethod will be executed when the jQuery AJAX call is made from client side. This method accepts the User object from client side and then the Username and Password values are inserted in the database. C#
[WebMethod] [ScriptMethod] public static void SaveUser(User user) { string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("INSERT INTO Users VALUES(@Username, @Password)")) { cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@Username", user.Username); cmd.Parameters.AddWithValue("@Password", user.Password);
VB.Net
<WebMethod ()> _ <ScriptMethod ()> _ Public Shared Sub SaveUser(user As User) Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionStrin g Using con As New SqlConnection(constr) Using cmd As New SqlCommand("INSERT INTO Users VALUES(@Username, @Password)") cmd.CommandType = CommandType.Text cmd.Parameters.AddWithValue("@Username", user.Username) cmd.Parameters.AddWithValue("@Password", user.Password) cmd.Connection = con con.Open() cmd.ExecuteNonQuery() con.Close() End Using End Using End Sub
In the Page Load event handler of the Page, the ASP.Net GridView is populated with the records from the Users table. C#
protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("SELECT * FROM Users")) { using (SqlDataAdapter sda = new SqlDataAdapter()) { DataTable dt = new DataTable(); cmd.CommandType = CommandType.Text; cmd.Connection = con; sda.SelectCommand = cmd; sda.Fill(dt); gvUsers.DataSource = dt; gvUsers.DataBind(); } } } } }
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionS tring Using con As New SqlConnection(constr) Using cmd As New SqlCommand("SELECT * FROM Users") Using sda As New SqlDataAdapter() Dim dt As New DataTable() cmd.CommandType = CommandType.Text cmd.Connection = con sda.SelectCommand = cmd sda.Fill(dt) gvUsers.DataSource = dt gvUsers.DataBind() End Using End Using End Using End If End Sub
Enable Disable ASP.Net Validator (Client Side Validation) using JavaScript or jQuery
23 Oct 2013 Mudassar Khan 0 Comments 4534 Views
In this article I will explain how to enable disable ASP.Net Validator (Client Side Validation) such has RequiredField validator, RegularExpression validator, Custom validator, etc. using JavaScript or jQuery. In order to enable or disable ASP.Net Validator (Client Side Validation), we need to make use of the inbuilt ValidatorEnable ASP.Net client side JavaScript function.
The HTML Markup consists of an ASP.Net TextBox, a CheckBox to enable or disable the validation when it is checked or unchecked respectively and a Button to trigger the RequiredField Validator for the TextBox.
UserName: <asp:TextBox ID="txtName" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="valName" ControlToValidate="txtName" runat="server" ErrorMessage="*Required" ForeColor="Red" ValidationGroup="Group1" /> <br /> Enable Validation: <input type="checkbox" id="CheckBox1" onclick="ToggleValidator(this);" checked="checked" /> <br /> <asp:Button Text="Submit" runat="server" ValidationGroup="Group1" /> <script type="text/javascript"> function ToggleValidator(chk) { var valName = document.getElementById("<%=valName.ClientID%>"); ValidatorEnable(valName, chk.checked); } </script>
The RequiredField Validator for the TextBox can be enabled or disabled by checking or unchecking the CheckBox respectively. When the CheckBox is clicked the ToggleValidator JavaScript function is executed. Inside this function we first check whether the CheckBox is checked or unchecked and based on its state we either enable or disable the RequiredField Validator valName using the ValidatorEnable JavaScript function.
Enable Disable ASP.Net Validators (Client Side Validation) using jQuery The HTML Markup consists of an ASP.Net TextBox, a CheckBox to enable or disable the validation when it is checked or unchecked respectively and a Button to trigger the RequiredField Validator for the TextBox.
Email: <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="valEmail" ControlToValidate="txtEmail" runat="server" ErrorMessage="*Required" ForeColor="Red" ValidationGroup="Group2" />
<br /> Enable Validation: <input type="checkbox" id="CheckBox2 checked="checked" /> <br /> <asp:Button Text="Submit" runat="server" ValidationGroup="Group2" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="text/javascript"> $(document).on("click", "#CheckBox2", function () { var valEmail = $("[id*=valEmail]"); ValidatorEnable(valEmail[0], $(this).is(":checked")); }); </script>
The RequiredField Validator for the TextBox can be enabled or disabled by checking or unchecking the CheckBox respectively. A jQuery Click event handler has been assigned to the CheckBox, thus when the CheckBox is clicked, we first check whether the CheckBox is checked or unchecked and based on its state we either enable or disable the RequiredField Validator valEmail using the ValidatorEnable JavaScript function.
Open New Window from Server Side (Code Behind) in ASP.Net using C# and VB.Net
ASP.Net JavaScript
Here Mudassar Ahmed Khan has explained how to open new popup window from Server Side (Code Behind) in ASP.Net using C# and VB.Net. In order to open a new popup window from Server Side (Code Behind), we need to use the ClientScript RegisterStartupScript method to register the JavaScript method to open new window.
Download View Demo
In this article I will explain how to open new popup window from Server Side (Code Behind) in ASP.Net using C# and VB.Net. In order to open a new popup window from Server Side (Code Behind), we need to use the ClientScript RegisterStartupScript method to register the JavaScript method to open new window. You might also like to read:JavaScript Popup Window and its Properties ASP.Net Response.Redirect or Server.Transfer Open new window
HTML Markup The HTML Markup consists of a Button control which will open a Popup Window from server side when clicked.
<asp:Button ID="btnNewWindow" Text="Open new Window" runat="server" OnClick="OpenWindow" />
Opening Popup Window from Server Side (Code Behind) using C# and VB.Net On the click event handler of the Button, the window.open JavaScript function is passed is registered to execute on the Page Load using the ClientScript RegisterStartupScript function of ASP.Net. C#
protected void OpenWindow(object sender, EventArgs e) { string url = "Popup.aspx"; string s = "window.open('" + url + "', 'popup_window', 'width=300,height=100,left=100,top=100,resizable=yes');" ;
VB.Net
Protected Sub OpenWindow(sender As Object, e As EventArgs) Dim url As String = "Popup.aspx" Dim s As String = "window.open('" & url + "', 'popup_window', 'width=300,height=100,left=100,top=100,resizable=yes');" ClientScript.RegisterStartupScript(Me.GetType(), "script", s, True) End Sub
Note: It is very important to pass the 3 parameter i.e. the options height, width, etc. when you want to open the page in New Window, if you skip that some newer browsers will open the page in New Tab instead of New Window.
rd
Note: Newer browsers block Popup Windows that are opened automatically without clicking any link or button on the page and since here we open New Popup Window from server side some browsers might block it. Unfortunately there is no solution for it and your sites users must trust and disable popup blockers.
Display image from database in Crystal Report in ASP.Net using C# and VB.Net
22 Oct 2013 Mudassar Khan 1 Comments 5566 Views
In this article I will explain step by step how to display binary images stored in database in Crystal Report in ASP.Net using C# and VB.Net Note: By default Visual Studio 2010 does not include Crystal Reports hence you need to download the Crystal Reports 13. Refer my article for details Download Crystal Reports for Visual Studio 2010
Database Here I am making use of Microsofts Northwind Database. You can download it from here
Download and install Northwind Database
1. Add Typed DataSet to the ASP.Net Website Since I am using disconnected Crystal Reports we will make use of Typed DataSet to populate the Crystal Reports with data from database.
2. Adding DataTable to the Typed DataSet Our next step would be to add a DataTable to the Typed DataSet.
3. Adding Columns or fields to DataTable In the DataTable we need to specify the column names that we want to display in the Crystal Report. Note: The Column Names of the DataTable must exactly match with the actual Database Table column names.
By default all the columns are of String data type but since the Image is stored in binary format for the Photo column we need to change the data type to Byte Arrayusing the properties window as show below.
4. Add Crystal Report to the ASP.Net Website Now you will need to add a Crystal Report to the ASP.Net Application. You can give it name as per your choice.
As soon as you click OK you get the following dialog. You must select using the Report Wizard option.
Once you press OK in the above dialog, the Report Wizard starts and you get the following dialog where you need to choose the type of Database connection for your Crystal Report. Since we are using DataSet we will choose the Employees DataSet.
Next the Wizard will ask for the Columns or Fields from the Employees DataSet you need to display on the Crystal Reports. You can choose either all or specific fields as per you choice.
Note: There are more steps in the Wizards but those are Optional hence are not included in this article.
Once you click Finish your Crystal Report should look as below. Sometimes the Photo might not be shown thus in such case you can Drag and Drop it from the left panel.
HTML Markup The HTML Markup is simple and contains a CrystalReportViewer control.
<!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 runat="server"> <title></title> </head> <body>
<form id="form1" runat="server"> <CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" AutoDataBind="true" /> </form> </body> </html>
VB.Net
Imports System.Data Imports System.Configuration Imports System.Data.SqlClient Imports CrystalDecisions.CrystalReports.Engine
Populating the Crystal Report from Database I am populating Crystal Reports from database in the Page Load event of the page using the following code C#
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { ReportDocument crystalReport = new ReportDocument();
private Employees GetData(string query) { string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; SqlCommand cmd = new SqlCommand(query); using (SqlConnection con = new SqlConnection(conString)) { using (SqlDataAdapter sda = new SqlDataAdapter()) { cmd.Connection = con;
sda.SelectCommand = cmd; using (Employees dsEmployees = new Employees()) { sda.Fill(dsEmployees, "DataTable1"); return dsEmployees; } } } }
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load If Not IsPostBack Then
Dim crystalReport As New ReportDocument() crystalReport.Load(Server.MapPath("~/EmployeesReport.rpt")) Dim dsEmployees As Employees = GetData("select * from employees") crystalReport.SetDataSource(dsEmployees) CrystalReportViewer1.ReportSource = crystalReport End If End Sub
Private Function GetData(query As String) As Employees Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionSt ring Dim cmd As New SqlCommand(query) Using con As New SqlConnection(conString) Using sda As New SqlDataAdapter() cmd.Connection = con
sda.SelectCommand = cmd Using dsEmployees As New Employees() sda.Fill(dsEmployees, "DataTable1") Return dsEmployees End Using End Using End Using End Function
Adding the Crystal Reports Image Handler in Web.Config This is the most important part and without it you will not see the Images in Crystal Report. You need to add the following in the <httpHandlers> section of Web.Config.
Encrypt and Decrypt Username or Password stored in database in ASP.Net using C# and VB.Net
18 Oct 2013 Mudassar Khan 1 Comments 5984 Views
ASP.Net Cryptography
Here Mudassar Ahmed Khan has explained how to encrypt and store Username or Password in SQL Server Database Table and then fetch, decrypt and display it in ASP.Net.
The Username or Password will be first encrypted using AES Symmetric key (Same key) algorithm and then will be stored in the database. And while fetching it will be again decrypted using AES Algorithm using the same key that was used for encryption.
Download
In this article I will explain how to encrypt and store Username or Password in SQL Server Database Table and then fetch, decrypt and display it in ASP.Net. The Username or Password will be first encrypted using AES Symmetric key (Same key) algorithm and then will be stored in the database. And while fetching it will be again decrypted using AES Algorithm using the same key that was used for encryption.
Database Schema I have created a new database named UsersDB which consist of one table named Users with the following schema.
You will notice that I have used NVARCHAR data type for storing Password, the reason is that when encrypted the password can contain special characters and hence it is recommended to use NVARCHAR instead of VARCHAR data type. Note: The attached sample contains the SQL Script file to create the database and the table.
HTML Markup The HTML Markup consists of Username and Password TextBoxes and a GridView to display the saved Usernames and Passwords.
<form id="form1" runat="server"> <table border="0" cellpadding="0" cellspacing="0"> <tr> <td> Username: </td> <td>
<asp:TextBox ID="txtUsername" runat="server" Text="" /> </td> </tr> <tr> <td> Password: </td> <td> <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" /> </td> </tr> <tr> <td> </td> <td> <asp:Button ID="btnSubmit" OnClick="Submit" Text="Submit" runat="server" /> </td> </tr> </table> <hr /> <asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="false" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White" RowStyleBackColor="#A1DCF2" OnRowDataBound = "OnRowDataBound"> <Columns> <asp:BoundField DataField="Username" HeaderText="Username" /> <asp:BoundField DataField="Password" HeaderText="Encrypted Password" /> <asp:BoundField DataField="Password" HeaderText="Desrypted Password" /> </Columns> </asp:GridView> </form>
VB.Net
Imports System.IO Imports System.Text Imports System.Data Imports System.Data.SqlClient Imports System.Configuration Imports System.Security.Cryptography
AES Algorithm Encryption and Decryption functions Below are the functions for Encryption and Decryption which will be used for the Encrypting or Decrypting Username or Password. Note: The following functions have been explained in the article AES Encryption Decryption (Cryptography) Tutorial with
example in ASP.Net using C# and VB.Net
C#
private string Encrypt(string clearText) { string EncryptionKey = "MAKV2SPBNI99212";
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText); using (Aes encryptor = Aes.Create()) { Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); encryptor.Key = pdb.GetBytes(32); encryptor.IV = pdb.GetBytes(16); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(clearBytes, 0, clearBytes.Length); cs.Close(); } clearText = Convert.ToBase64String(ms.ToArray()); } } return clearText; }
private string Decrypt(string cipherText) { string EncryptionKey = "MAKV2SPBNI99212"; byte[] cipherBytes = Convert.FromBase64String(cipherText); using (Aes encryptor = Aes.Create()) { Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); encryptor.Key = pdb.GetBytes(32); encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(cipherBytes, 0, cipherBytes.Length); cs.Close(); } cipherText = Encoding.Unicode.GetString(ms.ToArray()); } } return cipherText; }
VB.Net
Private Function Encrypt(clearText As String) As String Dim EncryptionKey As String = "MAKV2SPBNI99212" Dim clearBytes As Byte() = Encoding.Unicode.GetBytes(clearText) Using encryptor As Aes = Aes.Create() Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _ &H65, &H64, &H76, &H65, &H64, &H65, _ &H76}) encryptor.Key = pdb.GetBytes(32) encryptor.IV = pdb.GetBytes(16) Using ms As New MemoryStream() Using cs As New CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write) cs.Write(clearBytes, 0, clearBytes.Length) cs.Close() End Using
clearText = Convert.ToBase64String(ms.ToArray()) End Using End Using Return clearText End Function
Private Function Decrypt(cipherText As String) As String Dim EncryptionKey As String = "MAKV2SPBNI99212" Dim cipherBytes As Byte() = Convert.FromBase64String(cipherText) Using encryptor As Aes = Aes.Create() Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _ &H65, &H64, &H76, &H65, &H64, &H65, _ &H76}) encryptor.Key = pdb.GetBytes(32) encryptor.IV = pdb.GetBytes(16) Using ms As New MemoryStream() Using cs As New CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write) cs.Write(cipherBytes, 0, cipherBytes.Length) cs.Close() End Using cipherText = Encoding.Unicode.GetString(ms.ToArray()) End Using End Using Return cipherText End Function
When the Button is clicked, the following event handler is raised which inserts the entered Username and Password into the database table. The Username is inserted directly but the Password is first encrypted using the Encryption function (discussed earlier) and then it is inserted. C#
protected void Submit(object sender, EventArgs e) { string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("INSERT INTO Users VALUES(@Username, @Password)")) { cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@Username", txtUsername.Text.Trim()); cmd.Parameters.AddWithValue("@Password", Encrypt(txtPassword.Text.Trim())); cmd.Connection = con; con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } Response.Redirect(Request.Url.AbsoluteUri); }
VB.Net
Protected Sub Submit(sender As Object, e As EventArgs) Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionStrin g Using con As New SqlConnection(constr) Using cmd As New SqlCommand("INSERT INTO Users VALUES(@Username, @Password)") cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("@Username", txtUsername.Text.Trim()) cmd.Parameters.AddWithValue("@Password", Encrypt(txtPassword.Text.Trim())) cmd.Connection = con con.Open() cmd.ExecuteNonQuery() con.Close() End Using End Using Response.Redirect(Request.Url.AbsoluteUri) End Sub
Displaying the Usernames and Encrypted and Decrypted Passwords In the Page Load event of the Page, the GridView control is populated with the records from the Users table. Now in the OnRowDataBound event of the GridView, Password is fetched from the GridView Cell and is Decrypted using the Decrypt function (discussed earlier). C#
protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlConnection con = new SqlConnection(constr)) { using (SqlCommand cmd = new SqlCommand("SELECT * FROM Users"))
{ using (SqlDataAdapter sda = new SqlDataAdapter()) { DataTable dt = new DataTable(); cmd.CommandType = CommandType.Text; cmd.Connection = con; sda.SelectCommand = cmd; sda.Fill(dt); gvUsers.DataSource = dt; gvUsers.DataBind(); } } } } }
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load If Not Me.IsPostBack Then Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionS tring Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("SELECT * FROM Users") Using sda As New SqlDataAdapter() Dim dt As New DataTable() cmd.CommandType = CommandType.Text cmd.Connection = con sda.SelectCommand = cmd sda.Fill(dt) gvUsers.DataSource = dt gvUsers.DataBind() End Using End Using End Using End If End Sub
Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs) If e.Row.RowType = DataControlRowType.DataRow Then e.Row.Cells(2).Text = Decrypt(e.Row.Cells(2).Text) End If End Sub
Here Mudassar Ahmed Khan has explained how to upload files with progress bar in ASP.Net using jQuery Uploadify plugin.
Download
In this article I will explain how to upload multiple files AJAX style along with progress bar in ASP.Net using jQuery Uploadify Plugin. And the answer is Uploadify plugin for JQuery which does the same in few simple steps. In this article Ill explain the same.
Step 1 Download the Uploadify JQuery plugin and the JQuery Library using the links below.
Once downloaded youll need to place the below four files 1. jquery-1.3.2.min.js 2. jquery.uploadify.js 3. uploader.fla 4. uploader.swf in a folder called scripts in the root folder of your ASP.Net website application
Step 2 Start Visual Studio, create a new website and do as done below
Inherit the following files you downloaded earlier in the head section of the aspx or the master page <link rel="Stylesheet" type="text/css" href="CSS/uploadify.css" /> <script type="text/javascript" src="scripts/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="scripts/jquery.uploadify.js"></script>
Add an ASP.Net FileUpload Control to the form tag <form id="form1" runat="server"> <div style = "padding:40px"> <asp:FileUpload ID="FileUpload1" runat="server" /> </div> </form>
Place the following script in the head section or the ContentPlaceHolder in case you are using Master Pages <script type = "text/javascript"> $(window).load( function() { $("#<%=FileUpload1.ClientID %>").fileUpload({
'uploader': 'scripts/uploader.swf', 'cancelImg': 'images/cancel.png', 'buttonText': 'Browse Files', 'script': 'Upload.ashx', 'folder': 'uploads', 'fileDesc': 'Image Files', 'fileExt': '*.jpg;*.jpeg;*.gif;*.png', 'multi': true, 'auto': true }); } ); </script>
As you can see we need to specify some settings along with the FileUpload control. The complete list of settings and their description is available here Important setting to point out is 'script': 'Upload.ashx' which will handle the FileUpload and save the uploaded files on to the disk. Below is the code for the Upload.ashx file
public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Expires = -1; try { HttpPostedFile postedFile = context.Request.Files["Filedata"];
string savepath = ""; string tempPath = ""; tempPath = System.Configuration.ConfigurationManager.AppSettings["FolderPath"]; savepath = context.Server.MapPath(tempPath); string filename = postedFile.FileName; if (!Directory.Exists(savepath)) Directory.CreateDirectory(savepath);
postedFile.SaveAs(savepath + @"\" + filename); context.Response.Write(tempPath + "/" + filename); context.Response.StatusCode = 200; } catch (Exception ex) { context.Response.Write("Error: " + ex.Message); } }
return false; } } }
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.P rocessRequest Dim postedFile As HttpPostedFile = context.Request.Files("Filedata")
Dim savepath As String = "" Dim tempPath As String = "" tempPath = System.Configuration.ConfigurationManager.AppSettings("FolderPath") savepath = context.Server.MapPath(tempPath) Dim filename As String = postedFile.FileName If Not Directory.Exists(savepath) Then Directory.CreateDirectory(savepath) End If
postedFile.SaveAs((savepath & "\") + filename) context.Response.Write((tempPath & "/") + filename) context.Response.StatusCode = 200 End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable Get Return False End Get End Property
End Class
As you will notice that the handler simply accepts the posted files and saves the file in folder called uploads inside the website root directory whose path is placed in an AppSettings key in the Web.Config file Refer below <appSettings> <add key ="FolderPath" value ="uploads"/> </appSettings >
Thats all you need to do now run the application and youll notice your website running Browsing the File
You might have noticed that the files are auto uploaded once browsed if you do not want this feature you can simply set the 'auto' settings to false. But in that case youll need to provide a trigger the uploading of files on user interaction by placing an Upload button First youll need to set the Auto Upload setting to false refer the bold part <script type = "text/javascript"> $(window).load( function() { $("#<%=FileUpload1.ClientID%>").fileUpload({ 'uploader': 'scripts/uploader.swf', 'cancelImg': 'images/cancel.png', 'buttonText': 'Browse Files', 'script': 'Upload.ashx', 'folder': 'uploads',
'fileDesc': 'Image Files', 'fileExt': '*.jpg;*.jpeg;*.gif;*.png', 'multi': true, 'auto': false }); } ); </script>
Then add the following link that will trigger the upload <a href="javascript:$('#<%=FileUpload1.ClientID%>').fileUploadStart()">Start Upload</a>
Thats it now until user clicks the above link uploading of files wont take place. Now since the upload is triggered by user it would be great to give him an additional link to clear the browsed files in one go <a href="javascript:$('#<%=FileUpload1.ClientID%>').fileUploadClearQueue()">Clear</a>
* All browser logos displayed above are property of their respective owners.
Thats it. Hope you liked the article. You can download the sample source code in VB.Net and C# using the link below
Upload, Unzip and Extract contents Zip Archive file in ASP.Net using C# and VB.Net
13 Oct 2013 Mudassar Khan 0 Comments 2656 Views
ASP.Net DotNetZip
Here Mudassar Ahmed Khan has explained how to Upload, Unzip and Extract contents Zip Archive file in ASP.Net using C# and VB.Net. In order to Unzip and Extract contents of Zip Archive file in ASP.Net I am making use of DotNetZip Library which is a free
Open Source Library for .Net. The files are extracted in a folder on server and then displayed in GridView.
Download
In this article I will explain how to Upload, Unzip and Extract contents Zip Archive file in ASP.Net using C# and VB.Net. In order to Unzip and Extract contents of Zip Archive file in ASP.Net I am making use of DotNetZipLibrary which is a free Open Source Library for .Net. The files are extracted in a folder on server and then displayed in GridView. You might also like to read:
Download multiple files as Zip Archive File using GridView in ASP.Net
Referencing the DotNetZip Library You will need to download the DotNetZip Library DLL using the Download Link provided below.
Download DotNetZip Or your will find the DLL in the attached sample at the end of the article.
Once you have the DLL you need to place the Ionic.Zip.Reduced.dll in the BIN Folder.
VB.Net
Imports System.IO Imports Ionic.Zip Imports System.Collections.Generic
HTML Markup The HTML Markup consists of an ASP.Net FileUpload control, a Button and a GridView control.
<asp:FileUpload ID="FileUpload1" runat="server" /> <asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick="Upload" /> <hr /> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" HeaderStyleBackColor="#3AC0F2" HeaderStyle-ForeColor="White" RowStyle-BackColor="#A1DCF2"> <Columns> <asp:BoundField DataField="FileName" HeaderText="File Name" /> <asp:BoundField DataField="CompressedSize" HeaderText="Compressed Size (Bytes)" /> <asp:BoundField DataField="UncompressedSize" HeaderText="Uncompressed Size (Bytes)" /> </Columns> </asp:GridView>
Upload, Unzip and Extract contents of Zip Archive File in ASP.Net Once the Zip file is uploaded it is read using the DotNetZip ZipFile Read method to which I have passed the InputStream object of the FileUpload PostedFile property. Then the Zip File is extracted to the folder. The Extract All method has an additional parameter ExtractExistingFileAction, for which I have specifiedDoNotOverwrite so that if a file with same name exists, it will not be overwritten. C#
protected void Upload(object sender, EventArgs e) { string extractPath = Server.MapPath("~/Files/"); using (ZipFile zip = ZipFile.Read(FileUpload1.PostedFile.InputStream)) { zip.ExtractAll(extractPath, ExtractExistingFileAction.DoNotOverwrite); GridView1.DataSource = zip.Entries; GridView1.DataBind(); }
VB.Net
Protected Sub Upload(sender As Object, e As EventArgs) Dim extractPath As String = Server.MapPath("~/Files/") Using zip As ZipFile = ZipFile.Read(FileUpload1.PostedFile.InputStream) zip.ExtractAll(extractPath, ExtractExistingFileAction.DoNotOverwrite) GridView1.DataSource = zip.Entries GridView1.DataBind() End Using End Sub
Note: If you want to learn how to download files from folder. Please refer
Display list of files and Download from Server folder in ASP.Net GridView
ASP.Net Error: A potentially dangerous Request.Form value was detected from the client
11 Oct 2013 Mudassar Khan 1 Comments 2806 Views
Here Mudassar Ahmed Khan has explained the error exception in ASP.Net A potentially dangerous Request.Form value was detected from the client. The error exception A potentially dangerous Request.Form value was detected from the client occurs when ValidateRequest is set true and someone tries to submit HTML content to server example <a>Hello</a>. This error comes since ASP.Net tries to protect the application from Script Attacks.
A potentially dangerous Request.Form value was detected from the client (TextBox1"=<p>Hello</p>").
Description: Request Validation has detected a potentially dangerous client input value, and processing of the request has been aborted. This value may indicate an attempt to compromise the security of your application, such as a cross-site scripting attack. You can disable request validation by setting validateRequest=false in the Page directive or in the configuration section. However, it is strongly recommended that your application explicitly check all inputs in this case. Exception Details: System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (TextBox1="<p>Hello</p>").
Cause ASP.Net By default validates all input controls for potentially unsafe contents that can lead to Cross Site Scripting and SQL Injections. Thus it disallows such content by throwing the above Exception. By default it is recommended to allow this check to happen on each postback.
Solution On many occasions you need to submit HTML Content to your page through Rich TextBoxes or Rich Text Editors. In that case you can avoid this exception by setting the ValidateRequest tag in the @Page Directive to false.
This will disable the validation of requests for the page you have set the ValidateRequest flag to false. If you want to disable this check throughout your Web Application youll need to set it false in your web.config <system.web> section <pages validateRequest ="false " />
AES Encryption Decryption (Cryptography) Tutorial with example in ASP.Net using C# and VB.Net
06 Oct 2013 Mudassar Khan 8 Comments 8571 Views
ASP.Net Cryptography
Here Mudassar Ahmed Khan has provided a basic tutorial with example on simple encryption and decryption (Cryptography) in ASP.Net using C# and VB.Net. This article makes use of Symmetric (Same) key AES Algorithm for Encryption and Decryption.
Download View Demo
In this article I am providing a basic tutorial with example on simple encryption and decryption (Cryptography) in ASP.Net using C# and VB.Net. This article makes use of Symmetric (Same) key AES Algorithm for Encryption and Decryption.
HTML Markup The HTML Markup consists of TextBox and Labels to accept inputs for encryption and decryption.
<u>Encrypt</u><br /> <br /> Original Text: <asp:TextBox ID="txtOriginalText" runat="server" Text="" /> <br /> <br /> Encrypted Text: <asp:Label ID="lblEncryptedText" runat="server" Text="" /> <br />
<br /> <asp:Button ID="btnEncrypt" OnClick="Encrypt" Text="Encrypt" runat="server" /> <hr /> <u>Decrypt</u> <br /> <br /> Encrypted Text: <asp:TextBox ID="txtEncryptedText" runat="server" Text="" /> <br /> <br /> Decrypted Text: <asp:Label ID="lblDecryptedText" runat="server" Text="" /> <br /> <br /> <asp:Button ID="btnDecrypt" OnClick="Decrypt" Text="Decrypt" runat="server" />
VB.Net
Imports System.IO Imports System.Text Imports System.Security.Cryptography
Encryption For this article I am making use of AES encryption algorithm wherein I am using a Symmetric (Same) key for encryption and decryption process. Firstly the original text i.e. clear text is converted into bytes and then for the AES algorithm to perform encryption, we need to generate Key and IV using the derived bytes and the symmetric key. Using MemoryStream and CryptoStream the clear text is encrypted and written to byte array and finally the byte array is converted to Base64String and returned which is the final outcome i.e. the corresponding encrypted text. C#
protected void Encrypt(object sender, EventArgs e) { lblEncryptedText.Text = this.Encrypt(txtOriginalText.Text.Trim()); }
private string Encrypt(string clearText) { string EncryptionKey = "MAKV2SPBNI99212"; byte[] clearBytes = Encoding.Unicode.GetBytes(clearText); using (Aes encryptor = Aes.Create()) { Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); encryptor.Key = pdb.GetBytes(32); encryptor.IV = pdb.GetBytes(16); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(clearBytes, 0, clearBytes.Length); cs.Close();
VB.Net
Protected Sub Encrypt(sender As Object, e As EventArgs) lblEncryptedText.Text = Me.Encrypt(txtOriginalText.Text.Trim()) End Sub
Private Function Encrypt(clearText As String) As String Dim EncryptionKey As String = "MAKV2SPBNI99212" Dim clearBytes As Byte() = Encoding.Unicode.GetBytes(clearText) Using encryptor As Aes = Aes.Create() Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _ &H65, &H64, &H76, &H65, &H64, &H65, _ &H76}) encryptor.Key = pdb.GetBytes(32) encryptor.IV = pdb.GetBytes(16) Using ms As New MemoryStream() Using cs As New CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write) cs.Write(clearBytes, 0, clearBytes.Length) cs.Close() End Using clearText = Convert.ToBase64String(ms.ToArray()) End Using End Using
Decryption Firstly the encrypted text i.e. cipher text is converted into bytes and then similar to the encryption process here too we will generate Key and IV using the derived bytes and the symmetric key. Using MemoryStream and CryptoStream the cipher text is decrypted and written to byte array and finally the byte array is converted to Base64String and returned, which is the decrypted original text. C#
protected void Decrypt(object sender, EventArgs e) { lblDecryptedText.Text = this.Decrypt(txtEncryptedText.Text.Trim()); }
private string Decrypt(string cipherText) { string EncryptionKey = "MAKV2SPBNI99212"; byte[] cipherBytes = Convert.FromBase64String(cipherText); using (Aes encryptor = Aes.Create()) { Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); encryptor.Key = pdb.GetBytes(32); encryptor.IV = pdb.GetBytes(16); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(cipherBytes, 0, cipherBytes.Length); cs.Close();
VB.Net
Protected Sub Decrypt(sender As Object, e As EventArgs) lblDecryptedText.Text = Me.Decrypt(txtEncryptedText.Text.Trim()) End Sub
Private Function Decrypt(cipherText As String) As String Dim EncryptionKey As String = "MAKV2SPBNI99212" Dim cipherBytes As Byte() = Convert.FromBase64String(cipherText) Using encryptor As Aes = Aes.Create() Dim pdb As New Rfc2898DeriveBytes(EncryptionKey, New Byte() {&H49, &H76, &H61, &H6E, &H20, &H4D, _ &H65, &H64, &H76, &H65, &H64, &H65, _ &H76}) encryptor.Key = pdb.GetBytes(32) encryptor.IV = pdb.GetBytes(16) Using ms As New MemoryStream() Using cs As New CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write) cs.Write(cipherBytes, 0, cipherBytes.Length) cs.Close() End Using cipherText = Encoding.Unicode.GetString(ms.ToArray()) End Using End Using