Search content within the blog

Tuesday, November 25, 2008

Exporting Gridview contents to Excel

ASPX Page Code

<%@ Page Language="C#" EnableEventValidation="false" AutoEventWireup="true" CodeFile="GridviewExportToExcel.aspx.cs"
Inherits="Gridview_Export_To_Excel_GridviewExportToExcel" %>

<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView AllowPaging="true" PageSize="2" ID="gvUsers" runat="server" OnRowDataBound="gvUsers_RowDataBound">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
DisplayIDLink
</HeaderTemplate>
<ItemTemplate>
<asp:LinkButton ID="MyLinkButton" runat="server" Text='<%#Eval("displayid")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DropDownData">
<ItemTemplate>
<asp:DropDownList ID="ddlNames" runat="server">
<asp:ListItem Text="Akshay" Value="Akshay" />
<asp:ListItem Text="Ashwin" Value="Ashwin" />
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Btn_Export" runat="server" Text="Export to Excel (Default)" OnClick="Btn_ExportClick" />
<asp:Button ID="Btn_ExportToExcelPaging" runat="server" Text="Export to Excel Paging"
OnClick="Btn_ExportExcelPaging" />
</div>
</form>
</body>
</html>

ASPX.CS
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;

public partial class Gridview_Export_To_Excel_GridviewExportToExcel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData()
{
SqlConnection myConnection = new SqlConnection("Data Source=server02;Initial Catalog=Trial;User ID=ashwin;Password=ashwin");//change here to ur connectionstring
SqlDataAdapter ad = new SqlDataAdapter("select top 2 orderid,displayid from loobi_order", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds);

gvUsers.DataSource = ds;
gvUsers.DataBind();
}

protected void Btn_ExportClick(object sender, EventArgs e)
{
//ad this section to have those dropdowns,linkbuttons in excel file
string style = @"<style> .text { mso-number-format:\@; } </script> ";

Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
Response.ContentType = "application/excel";

StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);

gvUsers.RenderControl(htw);
// Style is added dynamically
Response.Write(style);
Response.Write(sw.ToString());
Response.End();
}

protected void Btn_ExportExcelPaging(object sender, EventArgs e)
{
//to convert link button, DropDownList etc date to simple text type
DisableControls(gvUsers);

Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
Response.ContentType = "application/excel";

StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);

gvUsers.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}

private void DisableControls(Control gv)
{
LinkButton lb = new LinkButton();
Literal l = new Literal();

string name = String.Empty;

for (int i = 0; i < gv.Controls.Count; i++)
{
if (gv.Controls[i].GetType() == typeof(LinkButton))
{
l.Text = (gv.Controls[i] as LinkButton).Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}

else if (gv.Controls[i].GetType() == typeof(DropDownList))
{
l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}


if (gv.Controls[i].HasControls())
{
DisableControls(gv.Controls[i]);
}
}

}

public override void VerifyRenderingInServerForm(Control control)
{
//this is required while exporting to excel
}

protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{

if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[1].Attributes.Add("class", "text");
}
}
}

Scrolling to top of the page using javascript

Just write the following line in your javascript function,
window.scrollTo(0,0);

Thursday, November 20, 2008

Highlighting the selected item in the menu

Note : This wont work if an update panel is present.

Master Pasge contents having menu

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MenuItemTest.master.cs"
Inherits="Master_Pages_MenuItemTest" %>
<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Menu ID="NavigationMenu" StaticDisplayLevels="1" StaticSubMenuIndent="1" Orientation="horizontal"
Target="_blank" runat="server" OnMenuItemClick="NavigationMenu_MenuItemClick">
<StaticSelectedStyle BackColor="Black" Font-Italic="true" ForeColor="Black" BorderColor="Red" />
<Items>
<asp:MenuItem NavigateUrl="~/Menus/Menu2.aspx" Text="Menu2" Target="_Self"></asp:MenuItem>
<asp:MenuItem NavigateUrl="~/Menus/Menu1.aspx" Text="Menu1" Target="_Self"></asp:MenuItem>
</Items>
</asp:Menu>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>

Add two pages namely menu1.aspx, menu2.aspx

Menu1.aspx
<%@ Page Language="C#" MasterPageFile="~/Master Pages/MenuItemTest.master" AutoEventWireup="true" CodeFile="Menu1.aspx.cs" Inherits="Menus_Menu1" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
</asp:Content>

Menu1.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Menu M = (Menu)this.Master.FindControl("NavigationMenu");
if (M != null)
{
M.Items[1].Selected = true;
}
}



Menu2.aspx
<%@ Page Language="C#" MasterPageFile="~/Master Pages/MenuItemTest.master" AutoEventWireup="true" CodeFile="Menu2.aspx.cs" Inherits="Menus_Menu2" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
</asp:Content>



Menu2.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Menu M = (Menu)this.Master.FindControl("NavigationMenu");
if (M != null)
{
M.Items[0].Selected = true;
}
}

Wednesday, November 19, 2008

Reading two Tables Data Using DataTableReader and NextResult

ASPX Page
<asp:GridView runat="server" ID="gvReaderData" AutoGenerateColumns="true"></asp:GridView>


protected void Page_Load(object sender, EventArgs e)
{

//fill first table
DataTable OrderDetails = new DataTable("OrderDetails");
String Sql = "Select top 5 email from Loobi_member";
SqlCommand cmd = new SqlCommand(Sql);
SqlConnection objConnection = new SqlConnection();
objConnection.ConnectionString = "Data Source=Loobi;Initial Catalog=Loobi;User ID=sa; Password=sa";
cmd.Connection = objConnection;
SqlDataAdapter adap = new SqlDataAdapter(cmd);
adap.Fill(OrderDetails);

//fill second table
DataTable LoginDetails = new DataTable("LoginDetails");
String Sql1 = "Select top 5 loginid from Loobi_Login";
SqlCommand cmd1 = new SqlCommand(Sql1);
SqlConnection objConnection1 = new SqlConnection();
objConnection1.ConnectionString = "Data Source=Loobi;Initial Catalog=Loobi;User ID=sa; Password=sa";
cmd1.Connection = objConnection1;
SqlDataAdapter adap1 = new SqlDataAdapter(cmd1);
adap1.Fill(LoginDetails);

DataTableReader objReader=new DataTableReader(new DataTable[]{OrderDetails,LoginDetails});
if (objReader.HasRows)
{
do
{
Response.Write("<br>");
Response.Write("Reading Table contents Started");
Response.Write("<br>");
while (objReader.Read())
{
Response.Write(objReader[0].ToString());
}
Response.Write("<br>");
Response.Write("Table contents completed");
Response.Write("<br>");
} while (objReader.NextResult());

}
else
{
Response.Write("No Data");
}

//Binding Data To Grid named gvReaderData
DataTableReader objEmailsReader = new DataTableReader(OrderDetails);
DataTable tblEmails = new DataTable();
tblEmails.Load(objEmailsReader);
gvReaderData.DataSource = tblEmails;
gvReaderData.DataBind();



}

Forms Authentication Without Role Based Security

Note:
Just copy paste the code to respective pages and try to access AuthenticatedPage.aspx page dirctly you will be re-directed to login page that is logon.aspx page

web.config settings
<system.web>
<authentication mode="Forms">
<forms name=".CookieAshwin" loginUrl="~/FormsAuthentication/logon.aspx"
protection="All" path="/" timeout="30" />
</authentication>
</system.web>




Logon.aspx Code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="logon.aspx.cs" Inherits="FormsAuthentication_Default" %>

<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div>

<input id="txtUserName" type="text" runat="server" style="z-index: 103; left: 295px;
position: absolute; top: 128px" />

<asp:CheckBox ID="chkPersistCookie" runat="server" AutoPostBack="false" Style="z-index: 100;
left: 298px; position: absolute; top: 214px" />
<input id="txtUserPass" type="password" runat="server" style="z-index: 102; left: 297px;
position: absolute; top: 174px" />
<p>
</p>
<input type="submit" value="Logon" runat="server" id="cmdLogin" style="z-index: 104;
left: 382px; position: absolute; top: 254px" onserverclick="cmdLogin_ServerClick">
<asp:Label ID="lblMsg" ForeColor="Red" Font-Name="Verdana" Font-Size="10pt" runat="server"
Style="z-index: 105; left: 183px; position: absolute; top: 78px" Font-Names="Verdana"
Width="406px" />
</div>
</div>
</form>
</body>
</html>

Logon.aspx.cs code
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class FormsAuthentication_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void cmdLogin_ServerClick(object sender, EventArgs e)
{
if (ValidateUser(txtUserName.Value, txtUserPass.Value))
{
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;

tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
DateTime.Now.AddMinutes(3), chkPersistCookie.Checked, "your custom data");
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
if (chkPersistCookie.Checked)
ck.Expires = tkt.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);

string strRedirect;
strRedirect = Request["ReturnUrl"];
if (strRedirect == null)
strRedirect = "AuthenticatedPage.aspx";
Response.Redirect(strRedirect, true);
}
else
Response.Redirect("logon.aspx", true);
}

private bool ValidateUser(string userName, string passWord)
{
SqlConnection conn;
SqlCommand cmd;
string lookupPassword = null;


try
{
//change here to ur connection string
conn = new SqlConnection("Data Source=Server02;Initial Catalog=Loobi;User ID=sa;Password=sa");
conn.Open();

//change here to ur table name
cmd = new SqlCommand("Select password from loobi_login where loginname=@userName", conn);
cmd.Parameters.Add("@userName", SqlDbType.NVarChar, 65);
cmd.Parameters["@userName"].Value = txtUserName.Value;


lookupPassword = (string)cmd.ExecuteScalar();


cmd.Dispose();
conn.Dispose();
}
catch (Exception ex)
{

System.Diagnostics.Trace.WriteLine("[ValidateUser] Exception " + ex.Message);
}

// If no password found, return false.
if (null == lookupPassword)
{
// You could write failed login attempts here to event log for additional security.
return false;
}

// Compare lookupPassword and input passWord, using a case-sensitive comparison.
return (0 == string.Compare(lookupPassword, passWord, false));


}
}



AuthenticatedPage.aspx Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AuthenticatedPage.aspx.cs" Inherits="FormsAuthentication_AuthenticatedPage" %>

<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Authenticated page
<asp:Button runat="server" ID="btnLogout" Text="LogOut" OnClick="btnLogout_Click" />
</div>
</form>
</body>
</html>


AuthenticatedPage.aspx.cs Code
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class FormsAuthentication_AuthenticatedPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnLogout_Click(object Sender, EventArgs e)
{
FormsAuthentication.SignOut();
Response.Redirect("logon.aspx");
}
}

WaterMark with Javascript

JavaScript
function WatermarkFocus(txtElem, strWatermark) {
if (txtElem.value == strWatermark) txtElem.value = '';
}

function WatermarkBlur(txtElem, strWatermark) {
if (txtElem.value == '') txtElem.value = strWatermark;
}

ASPX
<asp:TextBox ID="txtWatermark" runat="server" />

C#
protected void Page_Load(object sender, EventArgs e)
{
string strWatermark = "Search Karamasoft.com";
txtWatermark.Text = strWatermark;
txtWatermark.Attributes.Add("onfocus", "WatermarkFocus(this, '" + strWatermark + "');");
txtWatermark.Attributes.Add("onblur", "WatermarkBlur(this, '" + strWatermark + "');");
}

To Determine which version of .net are installed in clients system

Note : this works only in IE.

<script type="text/javascript" language="javascript">
function DetermineVersionsInstalled()
{
var a=navigator.userAgent.match(/\.NET CLR [0-9.]+/g);
if (a == null)
{
alert( ".NET Framework(s) is not installed" )
}
else
{
alert("The following versions of .NET Frameworks are installed:");
for(i = 0; i < a.length; ++i)
{
alert(a[i]);

}
}
return false;
}
</script>


<form id="form1" runat="server">
<div>
<asp:Button runat="server" ID="btnFindVersion" Text="Find Version" OnClientClick="Javascript:return DetermineVersionsInstalled();" />
</div>
</form>

Create XML from an Array

Passing arrays as arguments to stored procedures is not currently possible in SQL Server, but you can use XML to accomplish this. To do this, you need to create an XML string using your preferred language (C#, VB, etc.). You can use the following function to convert an array to an XML string (which you can then pass to the stored procedure). This example uses C#, but you can use the same logic with other languages:


protected void Page_Load(object sender, EventArgs e)
{
Object[] test = { 1, "item 2", 3, "item 4", 5, "item 6" };
Response.Write(ConvertToXML(test, "params", "param"));
}

protected string ConvertToXML(Object[] args, string rootName, string elemName)
{
string xmlStr = "<" + rootName + ">";

foreach (Object arg in args)
{
xmlStr += "<" + elemName + ">" + arg.ToString() +
"</" + elemName + ">";
}

xmlStr += "</" + rootName + ">";

return xmlStr;
}

Using the test case in the Page_Load method provided above as an example, the output XML would look like the following (but not as neatly formatted):


<params>
<param>1</param>
<param>item 2</param>
<param>3</param>
<param>item 4</param>
<param>5</param>
<param>item 6</param>
</params>

You can now pass that string to a SQL Server stored procedure or to other functions.

Tuesday, November 18, 2008

Adding sitemap provider details in web.config file

Web.config contents

Put this part of code under <system.web> section

<siteMap>
<providers>
<add name="Web1" type="System.Web.XmlSiteMapProvider" siteMapFile="~/SitemapFiles/Custom.sitemap"/>

</providers>

</siteMap>

Here the name can be any custom name and the siteMapFile"~/SitemapFiles/Custom.sitemap"
is the path of the sitemap file from the root.

type="System.Web.XmlSiteMapProvider" if it is XmlSiteMapProvider(change according to ur need)


ASPX Page OR Master Page
<asp:SiteMapPath ID="SiteMapPath1" runat="server" PathSeparator=">" PathDirection="RootToCurrent" CurrentNodeStyle-BackColor="AliceBlue" NodeStyle-BackColor="Beige" RootNodeStyle-BackColor="ActiveCaption" RenderCurrentNodeAsLink="false" ToolTip="Press on the link to go to the section" >
</asp:SiteMapPath>

Code-Behind
SiteMapPath1.Provider = SiteMap.Providers["Web1"];

Obtaining the list of triggers in your database alnog with the table names

select tbl = object_name(parent_obj), "trigger" = name
FROM sysobjects
where type = 'TR'
order by tbl

Enabling the Browser Back Button for GridView, ASP.NET AJAX History

One of the common navigation tools in a website is the back button of the browser. People use the back button quite frequently to go back to the page already visited. When there is a postback, the browser is updated with the information of the page visited and hence the back button gets enabled automatically. Assuming there is a GridView control that we are using in a page which fetches a lot of records, one of the common practices is to enable paging for the GridView such that the initial set of records loads quicker and people can page through the next set of records on a requirement basis.

When this GridView is in a normal ASP.NET Page, when users click on the paging buttons or links, the browser history gets updated and hence, if the users want to check the previous set of records, they can click on the back button and do the same.

However, in case of an ASP.NET AJAX enabled page, typically the GridView inside an Update Panel, it becomes impossible since the postback happens asynchronously and the browser history isn’t aware of the postback and hence the back button isn’t enabled.

To overcome this, ASP.NET 3.5 SP1 provides the History control that allows you to add history points to your AJAX Enabled page’s post backs and hence enable back button navigation for the users.

Let us examine this with a sample on Grid View. First, let us add a regular GridView control to an ASP.NET Page and configure it to use the NorthWind Database’s “Alphabetical list of products” table.

<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" CellPadding="4"
DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None">
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<Columns>
<asp:BoundField DataField="ProductName" HeaderText="ProductName"
SortExpression="ProductName" />
<asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit"
SortExpression="QuantityPerUnit" />
<asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice"
SortExpression="UnitPrice" />
<asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock"
SortExpression="UnitsInStock" />
<asp:BoundField DataField="UnitsOnOrder" HeaderText="UnitsOnOrder"
SortExpression="UnitsOnOrder" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName"
SortExpression="CategoryName" />
</Columns>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [ProductName], [QuantityPerUnit], [UnitPrice], [UnitsInStock], [UnitsOnOrder], [CategoryName] FROM [Alphabetical list of products]">
</asp:SqlDataSource>

Note this sample assumes you have the Northwind Database installed and you have the connection string configured in the web.config to connect to the database. You can download the same from http://www.microsoft.com/downloads/details.aspx?FamilyID=06616212-0356-46a0-8da2-eebc53a68034&displaylang=en for SQL Server 2000, 2005 etc.,

When you run this page, you will be able to page through the records and hit back button to go to the previous set of records.

Let us add Script Manager and Update Panel to this page and then move the contents into the Content Template of the Update Panel.

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>

>> The above GridView code snippet goes here


</ContentTemplate>
</asp:UpdatePanel>

Now when you run the page and click on the paging numbers i.e. 1,2,3..you will notice that the back button isn't enabled since this has been an asynchronous postback within the update panel.

To handle this, we need to do the following things

1. Set the EnableHistory=”true” for the ScriptManager (in this case, ScriptManager1). The updated ScriptManager declaration looks like this

<asp:ScriptManager ID="ScriptManager1" runat="server" EnableHistory="true">
</asp:ScriptManager>

2. Handle the OnPageIndexChanging event of the GridView with an event ex.- OnPageIndexChanging="GridView1_PageIndexChanging" needs to go in the GridView declaration above.

3. Add the handler code in the code behind as follows:-

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e) {

if (ScriptManager1.IsInAsyncPostBack && !ScriptManager1.IsNavigating) {
ScriptManager1.AddHistoryPoint("Index", GridView1.PageIndex.ToString());
}
}

Basically we are checking if the ScriptManager is in an asynchronous postback and the ScriptManager is not currently navigating. The AddHistoryPoint is the method that helps us to define history points and we provide the PageIndex to the method using the GridView’s pageindex property.

4. Handle the Script Manager’s Navigate event in the declaration as OnNavigate="ScriptManager1_Navigate"

5. Add the Handler code in the codebehind as follows:-

string indexString = e.State["index"];
if (string.IsNullOrEmpty(indexString)) {
GridView1.PageIndex = 0;

} else {
int Index = Convert.ToInt32(indexString);
GridView1.PageIndex = Index;
}

Once we do the above, when you run the page and navigate across the pages, you could see that the back button is enabled and we can navigate using the back button.

Note that, if there are multiple GridView controls within the updatepanel, we need to handle them separately as currently, we are only handing GridView1. However, if the GridView or any other control is outside the scope of Update Panel, then back button enablement is taken care automatically.

Also, Sorting needs to be handled as well. For a sample on Sorting check http://aspnet.4guysfromrolla.com/articles/100808-1.aspx

Monday, November 17, 2008

Use Of Literal to Display Alerts from code-behind

Literal ltAlertMsg = new Literal();
ltAlertMsg.Mode = LiteralMode.Transform;
this.Controls.Add(ltAlertMsg);
ltAlertMsg.Text =@"<script>alert(""Test Message ."");</script>";

Thursday, November 13, 2008

Obtaining the name of the page viewed or been coded from code-behind

string PageName = null;
if (Request.UrlReferrer != null)
{
Int32 lenStart = Request.UrlReferrer.AbsolutePath.LastIndexOf("/") + 1;
Int32 lenRequired = Request.UrlReferrer.AbsolutePath.Length - lenStart;
PageName = Request.UrlReferrer.AbsolutePath.Substring(lenStart, lenRequired);
Response.Write(PageName .trim());
}

Limiting a User for clicking a button only once while processing$

Control:

<asp:updatepanel id="upOnelick" runat="server">
<contenttemplate>
<asp:Button ID="Button1" runat="server" Text="One Click"
onclick="Button1_Click" />
</contenttemplate>
<triggers>
<asp:asyncpostbacktrigger controlid="Button1" eventname="Click">
</triggers>
</asp:UpdatePanel>
<asp:updatepanel id="upOnelick" runat="server"> <contenttemplate>
<asp:button id="Button1" runat="server" text="One Click" onclick="Button1_Click">
</asp:button>
<triggers>
<asp:asyncpostbacktrigger controlid="Button1" eventname="Click">
</asp:asyncpostbacktrigger>
</triggers>

Javasript:

function pageLoad()
{
var manager = Sys.WebForms.<div id=":g4" class="ArwC7c ckChnd"><$>PageRequestManager.<$>getInstance();
manager.add_initializeRequest(<$>OnInitializeRequest);
}

function OnInitializeRequest(sender, args)
{
var manager = Sys.WebForms.<$>PageRequestManager.<$>getInstance();
// Check if we're posting back because of Button1
if (manager.get_<$>isInAsyncPostBack() && args.get_postBackElement().id.<$>toLowerCase() == "button1")
{
$get("Label1").innerHTML = "Still working on previous request.Please, be patient ...";
args.set_cancel(true);
}
} </div></contenttemplate></asp:updatepanel>

Calling serverside code when closing browser

ASPX.CS Contents

protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form["__EVENTTARGET"] == "FromJavascript")
{
MyFuntion();
}
}

public void MyFuntion()
{
Response.Write("test write from server");
}

ASPX Contents


<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Untitled Page</title>
<script language="javascript">
function PerformServerTasks()
{
__doPostBack("FromJavascript","");
alert("Form Unloading. After you click ok to this message.Server Side code will work");
}
</script>
</head>
<body onunload="PerformServerTasks();">
<form id="form1" runat="server">
<div>
<h1>Test Page</h1>
<%-- <a href="#" onclick="PerformServerTasks();">s</a>--%>
<input id="Text1" type="text" runat="server" value="" />
<asp:TextBox ID="SDF" runat="server" AutoPostBack="True" Text="Dont worry about this textbox.But dont remove it"></asp:TextBox>
</div>
</form>
</body>
</html>

Adding Paging Support to the Repeater or DataList with the PagedDataSource Class

Original Reference: http://aspnet.4guysfromrolla.com/articles/081804-1.aspx
prerequisite's:
  • Create a XML File called Items.XML And Paste the contents present in 'XMLFile Contents' Section.
  • Paste the Contents present in 'ASPX page content' Section into ASPX Page.
  • Paste the Contents present in 'ASPX.CS Content' Section into ASPX .CS Page.
XMLFile Contents

<?xml version="1.0" encoding="utf-8" ?>
<Items>
<Item>
<ItemName>Item1</ItemName>
<ItemDescription>Item1 Description</ItemDescription>
<ItemPrice>1.50</ItemPrice>
<ItemInStock>Y</ItemInStock>
</Item>
<Item>
<ItemName>Item2</ItemName>
<ItemDescription>Item2 Description</ItemDescription>
<ItemPrice>2.50</ItemPrice>
<ItemInStock>Y</ItemInStock>
</Item>

</Item>
</Items>


ASPX page content

<h3>
paging Repeater content using PageDatasourse</h3>
<asp:Button runat="server" ID="btnXMLReader" Text="Fill Repeater" OnClick="btnXMLReader_Click" />
<table width="100%" border="0">
<tr>
<td>
Repeater control with Paging functionality</td>
</tr>
<tr>
<td>
<asp:Label ID="lblCurrentPage" runat="server"></asp:Label></td>
</tr>
<tr>
<td>
<asp:Button ID="cmdPrev" runat="server" Text=" << " OnClick="cmdPrev_Click"></asp:Button>
<asp:Button ID="cmdNext" runat="server" Text=" >> " OnClick="cmdNext_Click"></asp:Button></td>
</tr>
</table>
<table border="1">
<tr>
<td width="60%">
<asp:Repeater runat="server" ID="rptDataFromXML">
<HeaderTemplate >
<table width="100%">
<tr>
<td width="50%" align="center">Data From XML File With Paging Functionality.</td>
<td width="50%" align="center">Page Size=2</td>
</tr>
</table>
</HeaderTemplate>
<ItemTemplate>
<table width="100%">
<tr>
<td align="left" style="color:Blue" width="20%"><%# DataBinder.Eval(Container.DataItem, "ItemName")%></td>
<td align="left" style="color:Red" width="20%"><%# DataBinder.Eval(Container.DataItem, "ItemDescription")%></td>
<td align="left" style="color:Chocolate" width="20%"><%# DataBinder.Eval(Container.DataItem, "ItemInStock")%></td>
</tr>
</table>
</ItemTemplate>
<AlternatingItemTemplate>
<tr>
<td align="left" style="color:Chocolate" width="20%"><%# DataBinder.Eval(Container.DataItem, "ItemName")%></td>
<td align="left" style="color:Blue" width="20%"><%# DataBinder.Eval(Container.DataItem, "ItemDescription")%></td>
<td align="left" style="color:Red" width="20%"><%# DataBinder.Eval(Container.DataItem, "ItemInStock")%></td>
</tr>
</AlternatingItemTemplate>
</asp:Repeater>
</td>
</tr>
</table>
<h3>
End of paging Repeater content using PageDatasourse</h3>

ASPX.CS Content

protected void btnXMLReader_Click(object Sender, EventArgs e)
{

#region --Reading data into dataset--
DataSet dsXmlContent = new DataSet();
dsXmlContent.ReadXml(Server.MapPath("XMLFiles/Items.xml"), XmlReadMode.Auto);

#endregion

#region --Bind the data obtained--

objDataSource.PageSize = 2;
objDataSource.AllowPaging = true;
objDataSource.DataSource = dsXmlContent.Tables[0].DefaultView;
objDataSource.CurrentPageIndex = CurrentPage;
if (dsXmlContent.Tables[0].Rows.Count > 0)
{
rptDataFromXML.DataSource = objDataSource;
rptDataFromXML.DataBind();
cmdPrev.Enabled = !(objDataSource.IsFirstPage);
cmdNext.Enabled = !(objDataSource.IsLastPage);
}
else
{
lblCurrentPage.Text = "No Records avaliable";
lblCurrentPage.ForeColor = System.Drawing.Color.Red;
}
#endregion

}
public int CurrentPage
{
get
{
object objTemp = this.ViewState["_currentPage"];
if (objTemp == null)
{
return 0;
}
else
{
return((int)objTemp);
}
}
set
{
this.ViewState["_currentPage"] = value;
}
}
protected void cmdPrev_Click(object sender, EventArgs e)
{
CurrentPage -= 1;
btnXMLReader_Click(sender, e);
}
protected void cmdNext_Click(object sender, EventArgs e)
{
CurrentPage += 1;
btnXMLReader_Click(sender, e);
}

Tuesday, November 11, 2008

Encrypting, Decrypting Web.Config Contents

Original Reference: http://www.dotnetcurry.com/ShowArticle.aspx?ID=185&AspxAutoDetectCookieSupport=1

prerequisite's:
  • Add a global.asax file to your application.
  • Import namespace: <%@ Import Namespace="System.Web.Configuration" %>
  • Configure Application_Start Event and Application_End Event for the application to automatically encrypt, decrypt web.config file contents.
  • For the decrypt part to work first stop the webserver (IIS or Development server) then close the browser.
There are various sections of typical web.config file that usually contain sensitive information:
  • - username and password used to connect to databases
  • - usernam and password needed for runtime impersonation of fixed identity
  • - your smtp server username and password
  • etc
By using the built-in Encryption methods we can protect those configuration sections, so even if someone somehow manages
to obtain our web.config files or just take a brief look at them , there will not be much for him to see there.

ASP.NET 2.0 comes with two encryption providers we can use to protect our configuration files:
  • DataProtectionConfigurationProvider
  • RSAProtectedConfigurationProvider
  • also you can implement your own Providers, because its a plugin based model
here is an example showing the encryption, decryption implemented in global.asax file.

void Application_Start(object sender, EventArgs e)

{
// Code that runs on application startup

#region --Encrypt web.config section contents region wise--
try
{
Configuration objConfig = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
ConfigurationSection objConfigSection = objConfig.GetSection("appSettings");
if (objConfigSection != null)
{
if (!objConfigSection.SectionInformation.IsProtected)
{
objConfigSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
objConfig.Save();
}
}
}
catch (Exception ex)
{

}
#endregion

}

void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
#region --Decrypt the sections of web.config that were encrypted--
try
{
//Configuration confg = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
//ConfigurationSection confStrSect = confg.GetSection("appSettings");
if (objConfigSection != null && objConfigSection.SectionInformation.IsProtected)
{
objConfigSection.SectionInformation.UnprotectSection();
objConfig.Save();
}

}
catch (Exception ex)
{

}
#endregion
}