Thursday, July 31, 2008

Making a small Popup picture on mouse over event




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

<!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>

<script type="text/javascript">
function get_(div_)
{
div_=div_.id+"1";
document.getElementById(div_).style.display="block";
}
function get_1(div_)
{
div_=div_.id+"1";
document.getElementById(div_).style.display="none";
}
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="Server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:LinkButton ID="lnk" runat="server" Text="Details" onmouseover="get_(this);"
onmouseout="get_1(this);" />
<div id="lnk1" runat="server" style="display: none; position: absolute; background-color: #FEFFB3;
width: 150px"
>
<p>
<strong>Image Name</strong></p>
<p>
<img src='<%#Eval("ImagePath")%>' runat="Server" id="A" /></p>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>








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 MouseOverGrid : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetData();
GridView1.DataBind();

}
}
public DataSet GetData()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable("Movie");
DataRow dr;
dt.Columns.Add(new DataColumn("Id", typeof(Int32)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));

dt.Columns.Add(new DataColumn("ImagePath", typeof(string)));
for (int i = 1; i <= 5; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Name" + i.ToString();
dr[2] = "~/images/sa2.jpeg";
dt.Rows.Add(dr);
}
for (int i = 1; i <= 5; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Name" + i.ToString();
dr[2] = "~/images/pdf-icon.jpg";
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
Session["dt"] = dt;
return ds;
}
}

Wednesday, July 30, 2008

Enum With String Values In C#




In this post i will show how to assign string value to enum(In C# you cannot have an enum that has string values)
Step1
First I created the new custom attribute class, the source is below:
Step2
Then I created a new which I will use to get the string value for an enums value:



using System;
using System.Data;
using System.Configuration;
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.IO;
using System.Reflection;
public class StringValueAttribute : Attribute
{
public string StringValue;

public StringValueAttribute(string value)
{
this.StringValue = value;
}
}
public static class Util
{
public static string GetStringValue(Enum value)
{
// Get the type
Type type = value.GetType();

// Get fieldinfo for this type
FieldInfo fieldInfo = type.GetField(value.ToString());
// Get the stringvalue attributes
StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
typeof(StringValueAttribute), false) as StringValueAttribute[];
// Return the first if there was a match.
return attribs.Length > 0 ? attribs[0].StringValue : null;
}

}


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

<!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:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></div>
</form>
</body>
</html>





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 EnumToString : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
string val = Util.GetStringValue(Test.Something);
Response.Write(val);
}

}

public enum Test : int
{
[StringValue("Value1")]
Foo = 1,
[StringValue("Value2")]
Something = 2
}

using arrayList as DataSource for Gridview



Let us suppose that you have four controls (TextBox ,DropDownList ,ListBox ) and your requirement is that when the user enters texts or make a selection all these items/values gets stored inside an ArrayList and then this Array List is used as the Data Source for a Gridview control.




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

<!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:TextBox ID="TextBox1" runat="server" /><br />
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>A</asp:ListItem>
<asp:ListItem>B</asp:ListItem>
<asp:ListItem>C</asp:ListItem>
</asp:DropDownList><br />
<asp:DropDownList ID="DropDownList2" runat="server">
<asp:ListItem>A</asp:ListItem>
<asp:ListItem>B</asp:ListItem>
<asp:ListItem>C</asp:ListItem>
</asp:DropDownList><br />
<asp:ListBox ID="ListBox1" runat="server">
<asp:ListItem>A</asp:ListItem>
<asp:ListItem>B</asp:ListItem>
<asp:ListItem>C</asp:ListItem>
</asp:ListBox><br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Txt1" HeaderText="TextBox1" />
<asp:BoundField DataField="DDL1" HeaderText="DropDownList1" />
<asp:BoundField DataField="DDL2" HeaderText="DropDownList2" />
<asp:BoundField DataField="Lst1" HeaderText="ListBox1" />
</Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></div>
</form>
</body>
</html>


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.Collections.Generic;

public partial class DynamicData : System.Web.UI.Page
{
private List<Row> Data
{
get
{
if (this.ViewState["Data"] == null)
{
this.ViewState["Data"] = new List<Row>();
}

return this.ViewState["Data"] as List<Row>;
}
}

protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.GetData();
}
}

private void GetData()
{
GridView1.DataSource = this.Data;
GridView1.DataBind();
}

protected void Button1_Click(object sender, EventArgs e)
{
Row obj = new Row();
obj.Txt1 = TextBox1.Text;
obj.DDL1 = DropDownList1.SelectedValue;
obj.DDL2 = DropDownList2.SelectedValue;
obj.Lst1 = ListBox1.SelectedValue;
this.Data.Add(obj);

this.GetData();
}



}
[Serializable()]
public class Row
{

private string _txt1;
private string _ddl1;
private string _ddl2;
private string _Lst1;

public string Lst1
{
get { return _Lst1; }
set { _Lst1 = value; }
}


public string DDL2
{
get { return _ddl2; }
set { _ddl2 = value; }
}


public string DDL1
{
get { return _ddl1; }
set { _ddl1 = value; }
}

public string Txt1
{
get { return _txt1; }
set { _txt1 = value; }
}

}

Tips

how to resolve the error

One or more errors encountered while loading the designer. The errors are listed below. Some errors can be fixed by rebuilding your project, while others may require code changes. for more details check out this link



Binding a Listcontrol(Dropdownlist) to Enumeration Values




<%@ Page Language="C#" %>

<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.Web.UI" %>
<%@ Import Namespace="System.Web.UI.WebControls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
public void AddEnumToList(Type GetSystemType, ListControl List)
{
// Populates the specified list with the
// names and values of the passed system type
string[] strNames;
System.Array arrValues;
int intCount;
strNames = Enum.GetNames(GetSystemType);
arrValues = Enum.GetValues(GetSystemType);
List.Items.Clear();
for (intCount = strNames.GetLowerBound(0); intCount < strNames.GetUpperBound(0); intCount++)
{
List.Items.Add(new ListItem(strNames[intCount].ToString(), arrValues.GetValue(intCount).ToString()));
}
}

public enum Test
{

Jan,
Feb,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December

}


protected void Page_Load(object sender, EventArgs e)
{
Test a = new Test();
AddEnumToList(typeof(Test), DropDownList1);
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList></div>
</form>
</body>
</html>

Tuesday, July 29, 2008

The .NET Replacement for App.Path

A lot of confusion surrounds how to find out the startup path of your application —the .NET equivalent of the App.Path property we had in Visual Basic 6. I’ve personally written my own elongated routines, when in fact the solution is incredibly simple.

If you want to find out the application path of your Windows application, just reference the StartupPath property of the Application object, as so:

Dim strPath As String = Application.StartupPath 

Note that the returned path doesn’t include a trailing slash.

If you’re developing a class library or similar project, however, you might stumble upon a slight problem. You see, not all projects support the Application object. In these cases, you can use the System.Reflection class to analyze the executing assembly and return its location. A little like this:

Dim strPath As String = System.Reflection.Assembly.GetExecutingAssembly().Location 

A bit more in depth, but still pretty darn simple

How To Post Data From ASP.net To Another URL





using System;
using System.Net;
using System.Web;
using System.Collections.Specialized;


public class RemotePost
{
NameValueCollection Inputs = new NameValueCollection();
public string Url = "";
public string Method = "post";
public string FormName = "form1";
public void Add(string name, string value)
{
Inputs.Add(name, value);
}
public void Post()
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write("<html><head>");
HttpContext.Current.Response.Write(string.Format("</head><body onload=\"document.{0}.submit()\">", FormName));
HttpContext.Current.Response.Write(string.Format("<form name=\"{0}\" method=\"{1}\" action=\"{2}\" >", FormName, Method, Url));
int i = 0;
while (i < Inputs.Keys.Count)
{
HttpContext.Current.Response.Write(string.Format("<input name=\"{0}\" type=\"hidden\" value=\"{1}\">", Inputs.Keys[i],Inputs.Keys[i]));
i += 1;
}
HttpContext.Current.Response.Write("</form>");
HttpContext.Current.Response.Write("</body></html>");
HttpContext.Current.Response.End();
}
}


<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

protected void Page_Load(object sender, EventArgs e)
{

}

protected void Button1_Click(object sender, EventArgs e)
{
RemotePost obj = new RemotePost();
obj.Url = "http://localhost/Project/Default.aspx";
obj.Method = "Get";
obj.Add("test", "test");
obj.Post();
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Post Data To Another Application" /></div>
</form>
</body>
</html>


<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form["test"] != null)
{
Response.Write(Request.Form["test"].ToString());

}
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>

</div>
</form>
</body>
</html>

How To Convert HTML to Text, Easily



Whether you want to convert an HTML page into pure text so you can parse out that special piece of information, or you simply want to load a page from the Net into your own word processing package, this mini function could come in handy.

It’s called StripTags and accepts an HTML string. Using a regular expression, it identifies all <tags>, removes them, and returns the modified string. Here’s the code:



<%@ Page Language="C#" ValidateRequest="False" AutoEventWireup="true" CodeFile="StripTag.aspx.cs"
Inherits="StripTag" %>


<!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:TextBox ID="TextBox1" runat="server" Height="172px" Width="363px" TextMode="MultiLine"></asp:TextBox></div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>
</body>
</html>



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 StripTag : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{


}
public string StripTags(string HTML)
{
// Removes tags from passed HTML
return System.Text.RegularExpressions.Regex.Replace(HTML, "<[^>]*>", "");
}


protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = StripTags(TextBox1.Text);

}
}

How to View one record per page in ASP.NET?






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

<!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:TextBox ID="txtProductName" runat="server" OnDataBinding="txtDataBind"></asp:TextBox>
<asp:TextBox ID="txtProductid" runat="server"></asp:TextBox>
<asp:Button ID="btnPrevious" runat="server" Text="Previous" OnClick="PrevBtn"></asp:Button>
<asp:Button ID="btnNext" runat="server" Text="Next" OnClick="NextBtn"></asp:Button>
</div>
</form>
</body>
</html>









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 SinglePage : System.Web.UI.Page
{
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
dt = GetDataTable() as DataTable;

if (!Page.IsPostBack)
{
ViewState["CurrentPos"] = 0;
this.DataBind();
}
}
protected void PrevBtn(object sender, System.EventArgs e)
{
try
{
int CurrentPos = (int)ViewState["CurrentPos"];
if (CurrentPos > 0)
{
CurrentPos -= 1;
}
ViewState["CurrentPos"] = CurrentPos;
this.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}

protected void NextBtn(object sender, System.EventArgs e)
{
try
{
int CurrentPos = (int)ViewState["CurrentPos"];
CurrentPos += 1;
if (CurrentPos > dt.Rows.Count)
{
CurrentPos -= 1;
}
ViewState["CurrentPos"] = CurrentPos;
this.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}

protected void txtDataBind(Object sender, System.EventArgs e)
{
try
{
int CurrentPos = (int)ViewState["CurrentPos"];
ViewState["CurrentPos"] = CurrentPos;
txtProductid.Text = dt.Rows[CurrentPos]["productid"].ToString();
txtProductName.Text = dt.Rows[CurrentPos]["productname"].ToString();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
private DataTable GetDataTable()
{
//create table
DataTable dt = new DataTable("Product");
dt.Columns.Add("ProductID", Type.GetType("System.Int32"));
dt.Columns.Add("ProductName", Type.GetType("System.String"));

//create fields
DataColumn[] pk = new DataColumn[1];
pk[0] = dt.Columns["ProductID"];
dt.PrimaryKey = pk;
dt.Columns["ProductID"].AutoIncrement = true;
dt.Columns["ProductID"].AutoIncrementSeed = 1;
dt.Columns["ProductID"].ReadOnly = true;

//fill rows
DataRow dr;
for (int x = 1; x <= 10; x++)
{
//make every other one different
if (Math.IEEERemainder(x, 2) == 0)
{
dr = dt.NewRow();
dr["ProductName"] = "Riss";

dt.Rows.Add(dr);
}
else
{
dr = dt.NewRow();
dr["ProductName"] = "Product";

dt.Rows.Add(dr);

}
}

return dt;
}
}

Monday, July 28, 2008

Filling typed dataset programmatically

Filling a typed dataset works just like filling an untyped dataset. You
create a data adapter, assign the SelectCommand, and call Fill(). The
only real trick is to get the table and field names right.

A DataAdapeter will generate table names for each distinct result set
generated by the SelectCommand. The names will be "Table", "Table1", "Table2", etc. If you call the overloaded Fill() method which takes a table name parameter, the generated names will follow the same pattern, except your table name will be used instead of "Table".
Once the data adapter has generated the table names, it will look for
matching table names in your data set. The data is then mapped to the matching column names in the matching tables. As long as the
SelectCommand returns the proper column names, the data will populate as you would expect.

Some things to beware of:

* You will *not* get errors if the table or column names are wrong. If
the Data Adapter can't find a given table, it would normally add a new
table to your dataset. For typed data sets, things are slightly
different. You won't get an exception in this case, but you also wont'
get your data. This includes both misnamed tables *and* misnamed
columns -- the data is simply discarded if it can't be fit into your schema.

* If your SelectCommand returns multiple result sets, you will almost
certainly need to map the resulting table names to those in your
dataset. The table names need to be mapped in the order they are
returned by the SelectCommand, and the code looks something like this
(assume the dataset has three tables: MyTable, MyOtherTable, MyThirdTable):


SqlCommand cmd = new SqlCommand("multi_recordset_proc", new SqlConnection("your con. string"));

cmd.CommandType = CommandType.StoredProcedure;

SqlDataAdapter da = new SqlDataAdapter(cmd);
da.TableMappings("MyTable1", "MyOtherTable");
da.TableMappings("MyTable2", "MyThirdTable");
da.Fill(dataset, "MyTable");
* If you have relationships in your dataset, they will be enforced
during the Fill. I beleive this is done on a per-table basis, that is,
the contraints for a given table are disabled, data is populated, and
the constraints are enabled. If you populate a table before populating
parent tables, you will generate an error. You can get around this
problem by being careful of the order you populate tables.
Alternatively, you can do:



ds.EnforceConstraints = false;
da.Fill(ds, "Table");
ds.EnforceConstraints = true;


How To Clear Browser Session In Asp.net

In this post i will show how to clear Browser history in asp.net.just write down following code in Logout button.


protected void LogOut()
{
Session.Abandon();
string nextpage = "Logoutt.aspx";
Response.Write("<script language=javascript>");

Response.Write("{");
Response.Write(" var Backlen=history.length;");

Response.Write(" history.go(-Backlen);");
Response.Write(" window.location.href='" + nextpage + "'; ");

Response.Write("}");
Response.Write("</script>");

}

Sunday, July 27, 2008

How to easily insert row in GridView with SqlDataSource?

Asp.Net 2.0 GridView control is very powerful control. Developers at Microsoft really did a great job when designing it.
Its like Swiss Army knife for selecting, editing, sorting, paging and displaying data.
Combined with various DataSource controls (ObjectDataSource, SqlDataSource) it helps you execute most of your Read, Update and Delete operations without writing a single line of code.

Off course, nothing is perfect. For example, creating new data is is one common task that is not so simple to accomplish with GridView.
Since there is InsertCommand property in DataSource controls that we can set to insert data, there is no reason not to use it with GridView to insert new data, just like we use DeleteCommand to delete data.
For some strange reason there is no built-in way to do this, but there are always workarounds
check out this link

Friday, July 25, 2008

Passing Date from Calendar Pop-Up to Parent Window





This section will help us building a simple DatePicker control using Calendar control and Javascript. Create two aspx pages, ParentPage.aspx and Calendar.aspx. Calendar.aspx will contain a Calendar control and it should be opened as a popup window. When the user selects a date in the Calendar popup it will populate the date selected into a textbox in the ParentPage.aspx page.


ParentPage.aspx


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

<!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>

<script type="text/javascript">
function PopupPicker(ctl)
{
var PopupWindow=null;
PopupWindow=window.open('Calender.aspx?ctl='+ctl,'','width=250,height=250');
PopupWindow.focus();
}
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
<input id="Button2" type="button" value="Click" onclick="PopupPicker('txtDate');" />
</div>
</form>
</body>
</html>



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

<!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>

<script type="text/javascript">
function SetDate(dateValue,ctl)

{

thisForm = window.opener.document.forms[0].elements[ctl].value= dateValue;
self.close();
}
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Calendar ID="Cal1" runat="Server" OnDayRender="Cal1_DayRender"></asp:Calendar>
</div>
</form>
</body>
</html>




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 Calender : System.Web.UI.Page
{
string ctrl;
protected void Page_Load(object sender, EventArgs e)
{
ctrl = Request.QueryString["ctl"].ToString();
}

protected void Cal1_DayRender(object sender, DayRenderEventArgs e)
{

HyperLink hpl = new HyperLink();
hpl.Text = ((LiteralControl)e.Cell.Controls[0]).Text;
hpl.NavigateUrl = "javascript:SetDate('" + e.Day.Date.ToShortDateString() + "','" + ctrl + "');";
e.Cell.Controls.Clear();
e.Cell.Controls.Add(hpl);

}
}
By default, the days in calendar control is rendered as links and generate a postback when it is clicked. Instead of postback, we will call our custom SetDate() JavaScript function by changing the cell of the Calendar control to Hyperlink control and attaching the SetDate() JavaScript function to the hyperlink in clnDatePicker_DayRender event.

Working With PopUp In ASP.net



Whenever we build any web applications it can have requirements to work with popup windows. For example: To pick a date for a date field in an aspx page, we can place a calendar control on a popup so that user can select a date from the calendar instead of typing himself, a simple date picker control. This article will help you understand some of tasks that we more often do with popup windows.

Refreshing a parent page from a popup ASP.Net page

There are situations where we will be required to populate the information’s entered on the popups to the parent page and refresh the parent page so that it can be accessed in the server side. The below example will help us in achieving it.

The below example will populate the entered name in the child.aspx(popup) to the parent(Parent.aspx) and submit the page to the server.

Parent.aspx

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

<!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>
<title>Untitled Page</title>

<script language="javascript">

function OpenWindow(strChildPageUrl)

{

var testwindow = window.open(strChildPageUrl,"Child","width=400px,height=400px,top=0,left=0,scrollbars=1");

}

</script>

</head>
<body>
<form runat="Server">
<div>
<asp:textbox id="txtName" runat="server"></asp:textbox>
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Get Value" />
<input type="button" id="Button1" value="Enter Name" onclick="OpenWindow('Child.aspx')" />
</div>
</form>
</body>
</html>


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 Parent : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}

}
protected void Button2_Click(object sender, EventArgs e)
{
if (txtName.Text != "")

Response.Write(txtName.Text);

}
}

child.aspx



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

<!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>

<script language="javascript">

function SubmitToParent()

{

window.opener.document.forms[0].txtName.value = document.getElementById('txtChildName').value;

window.opener.document.forms[0].submit();

self.close();

}

</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtChildName" runat="server"></asp:TextBox>
<input type="button" id="Button1" value="Submit to Parent" onclick="SubmitToParent()" />
</div>
</form>
</body>
</html>
Window.Open Clears Parent page and writes [Object]



Sometimes we will have requirements to open an asp.net page as a popup when we click a hyperlink. Consider the below code,



<a href="javascript:window.open('http:/google.com')"> google</a>



The above code will clear the existing content on the page and will output only [Object]. This behaviour is because the actual return value of Window.Open function is the window object itself.

To prevent the above behaviour and have the parent page without clearing its existing content we need to change the above code similar to below,



<a href="javascript:void(window.open('http:/google.com'))"> google</a>

or

<a href="#" onclick="javascript:window.open('http:/google.com'); return false;"> google</a>
Opening ASP.Net Popup window in specific location of the screen




Opening ASP.Net Popup window in specific location of the screen



Sometimes we would like to open our popup window on specific location on our screen. This can be done by MoveTo() method of the window object.



function OpenWindow(strChildPageUrl)

{

var testwindow = window.open(strChildPageUrl,"Child","width=400px,height=400px,top=0,left=0,scrollbars=1");

testwindow.moveTo(100,0);

}

The null coalescing operator: ??

This is a new feature of c# 2.0. The null coalescing operator is a short cut for checking if a value is null and if so returning the value of the second operand. Kind of like an IIF. The syntax is as follows


string newValue = someValue ?? "default";

The first operand someValue must be a nullable type. The above code will set the value of newValue to someValue unless it's null, then it'll set it to "default".

You could also use this inline:



Console.WriteLine("The value is " + (someValue ?? "null"));


another use
return (bool)(ViewState["IsPaged"] ?? true);


Programmatically adding LINKs to HTML HEADER in Code Behind

In this example I am adding a link to the html header pointing to an rss feed.


HtmlLink link = new HtmlLink();
link.Attributes.Add("type", "application/rss+xml");
link.Attributes.Add("rel", "alternate");
link.Attributes.Add("href", Page.ResolveClientUrl("~/rss/LatestArticles/"));
this.Header.Controls.Add(link);

How To Restrict the number of rows in a dataview when binding to a GridView


In this post i will show how to restrict the number of items bound to an asp:GridView. Basically I never wanted more than 10 items to be displayed.



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


<!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 ID="GridView1" runat="Server">
</asp:GridView>
</div>
</form>
</body>
</html>




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 RestrictNumRows : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{

FilterRows obj = new FilterRows(GetDataSet().DefaultView,2);
GridView1.DataSource = obj;
GridView1.DataBind();
}

}
public class FilterRows : IEnumerable
{
DataView dataView;
private int rowsToShow;

public FilterRows(DataView dataView, int rowsToShow)
{
this.rowsToShow = rowsToShow;
this.dataView = dataView;
}

public IEnumerator GetEnumerator()
{
return new PageOfData(this.dataView.GetEnumerator(), this.rowsToShow);
}


internal class PageOfData : IEnumerator
{
private IEnumerator e;
private int cnt = 0;
private int rowsToShow;

internal PageOfData(IEnumerator e, int rowsToShow)
{
this.rowsToShow = rowsToShow;
this.e = e;
}

public object Current
{
get { return e.Current; }
}

public bool MoveNext()
{
// If we've hit out limit return false
if (cnt >= rowsToShow)
return false;

// Track the current row
cnt++;

return e.MoveNext();
}

public void Reset()
{
e.Reset();
cnt = 0;
}
}
}
public DataTable GetDataSet()
{

DataTable dt = new DataTable("Company");
DataRow dr;
dt.Columns.Add(new DataColumn("Id", typeof(Int32)));
dt.Columns.Add(new DataColumn("IntField", typeof(Int32)));
dt.Columns.Add(new DataColumn("StringField", typeof(string)));
for (int i = 1; i <= 20; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = i;
dr[2] = "Company" + i + Environment.NewLine + "Title" + i;
dt.Rows.Add(dr);
DataColumn[] Parent_PKColumns = new DataColumn[1];
Parent_PKColumns[0] = dt.Columns["ID"];
dt.PrimaryKey = Parent_PKColumns;
Session["DataSource"] = dt;
}

return dt;
}

}

Select a row in an asp:GridView without using a Select Command




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

<!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 ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID"
Width="200px" AllowPaging="True" OnRowDataBound="PeopleGridView_RowDataBound">
<Columns>
<asp:BoundField DataField="StringField" HeaderText="Name" SortExpression="StringField">
</asp:BoundField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>


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 SelectRow : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetDataSet();
GridView1.DataBind();
}

}
public DataTable GetDataSet()
{

DataTable dt = new DataTable("Company");
DataRow dr;
dt.Columns.Add(new DataColumn("Id", typeof(Int32)));
dt.Columns.Add(new DataColumn("IntField", typeof(Int32)));
dt.Columns.Add(new DataColumn("StringField", typeof(string)));
for (int i = 0; i <= 10; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = i;
dr[2] = "Company" + i + Environment.NewLine + "Title" + i;
dt.Rows.Add(dr);
DataColumn[] Parent_PKColumns = new DataColumn[1];
Parent_PKColumns[0] = dt.Columns["ID"];
dt.PrimaryKey = Parent_PKColumns;
Session["DataSource"] = dt;
}

return dt;
}
protected void PeopleGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";

e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.GridView1, "Select$" + e.Row.RowIndex);
}

}
}

Return new identity from Strongly Typed Dataset DataTable.Insert method

Datasets are pretty good at auto generating stored procedures and wrapping c# code around them for you.

However with the insert method you often want to do something with the object that you have just inserted.

Fortunately there is an easy way to get the Sproc and the c# method to return a reference to the object.

Firstly edit your insert stored procedure adding a @return parameter and a line after the insert to set this to a suitable value.

The exmaple below assumes that you are using bigint identity fields.

ALTER PROCEDURE dbo.insMyRow
(
@Description varchar(500),
@Return bigint output
)
AS
SET NOCOUNT OFF;
INSERT INTO [myTable] ([Description]) VALUES (@Description);

SET @Return = SCOPE_IDENTITY()

Note that SCOPE_IDENTITY() is similar to @@IDENTITY except its scope is limited to the current command and so improves scalability.

Now when you save the Dataset you see that the insert method takes two parameters, the second being a nullable long.

My first thought was that Datasets should be the end of editing stored procedures but I am still impressed that the c# method declaration changes accordingly.

You can call the updated method in the following way.

long? objId=null;

myTableAdapter d =new myTableAdapter();

d.Insert("Descriptive text", ref objId);

the long? just means nullable long.

After filling the table you can now use the FindByxxxID functions of the DataTable to return the DataRow object.

Thursday, July 24, 2008

Building a DAL using Strongly Typed TableAdapters and DataTables in VS 2005 and ASP.NET 2.0

he word Dataset does not need introduction because it is one of most commonly used object in .net world. So proceeding with this assumption, a typed dataset is an object that derives from Dataset class and additionally it provides strongly typed access to its containing tables and columns. To justify the above line still in depth, to access tables and columns in a dataset we use, check out this link for more details

ADO.NET Tutorial

DO.NET is a set of computer software components that can be used by programmers to access data and data services. It is a part of the base class library that is included with the Microsoft .NET Framework. It is commonly used by programmers to access and modify data stored in relational database systems, though it can also be used to access data in non-relational sources. ADO.NET is sometimes considered an evolution of ActiveX Data Objects (ADO) technology, but was changed so extensively that it can be conceived of as an entirely new product.
check out this link for more details

Three Tier Architecture with ASP.NET

Brian Mains talks about the GridView control in the context of 3-tier ASP.NET applications.
Three Tier Architecture with ASP.NET

Load Controls Dynamically in ASP.NET

In this article, I will show you one of the ways you can use to handle adding controls dynamically in an ASP.NET Page
Load Controls Dynamically in ASP.NET

How to display a serial number from 1 to n in a grid view






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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
PageSize="3" OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField DataField="LastName" HeaderText="Name" />
<asp:BoundField DataField="Lectures" HeaderText="Lectures" />
<asp:TemplateField HeaderText="S.No">

<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# (GridView1.PageSize * GridView1.PageIndex) + Container.DisplayIndex + 1 %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>



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 Paging : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetDataTable();
GridView1.DataBind();

}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;

GridView1.DataSource = GetDataTable();
GridView1.DataBind();
}
private DataTable GetDataTable()
{
//create table
DataTable dt = new DataTable("Members");
dt.Columns.Add("ID", Type.GetType("System.Int32"));
dt.Columns.Add("LastName", Type.GetType("System.String"));
dt.Columns.Add("Lectures", Type.GetType("System.Int32"));

//create fields
DataColumn[] pk = new DataColumn[1];
pk[0] = dt.Columns["ID"];
dt.PrimaryKey = pk;
dt.Columns["ID"].AutoIncrement = true;
dt.Columns["ID"].AutoIncrementSeed = 1;
dt.Columns["ID"].ReadOnly = true;

//fill rows
DataRow dr;
for (int x = 1; x <= 10; x++)
{
//make every other one different
if (Math.IEEERemainder(x, 2) == 0)
{
dr = dt.NewRow();
dr["LastName"] = "Riss";
dr["Lectures"] = 14;
dt.Rows.Add(dr);
}
else
{
dr = dt.NewRow();
dr["LastName"] = "Anders";
dr["Lectures"] = 3;
dt.Rows.Add(dr);

}
}

return dt;
}
}
*

create a template field, in that item template, put a label, specify it's text as

Text='<%# (GridView1.PageSize * GridView1.PageIndex) + Container.DisplayIndex + 1 %>'


Wednesday, July 23, 2008

Export Html to Pdf using iTextSharp(GridView)






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

<!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 ID="GridView1" runat="server">
</asp:GridView>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Pdf" /></div>
</form>
</body>
</html>




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 iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using iTextSharp.text.html;

public partial class Pdf : MyPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetData();
GridView1.DataBind();
}

}
protected void Button1_Click(object sender, EventArgs e)
{
MyPage tmpPage = new MyPage();
HtmlForm form = new HtmlForm();
form.Controls.Add(GridView1);
tmpPage.Controls.Add(form);
StringWriter sw = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);
form.Controls[0].RenderControl(htmlWriter);
string htmlContent = sw.ToString();
Document document = new Document();
// step 2:
// we create a writer that listens to the document
// and directs a PDF-stream to a file
PdfWriter.GetInstance(document, new FileStream("c:\\Chap0101.pdf", FileMode.Create));

// step 3: we open the document
document.Open();

// step 4: we add a paragraph to the document
//document.Add(new Paragraph(htmlContent.ToString()));

System.Xml.XmlTextReader _xmlr = new System.Xml.XmlTextReader(new StringReader(htmlContent));

HtmlParser.Parse(document, _xmlr);

// step 5: we close the document
document.Close();

ShowPdf("c:\\Chap0101.pdf");

}

private void ShowPdf(string s)
{
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "inline;filename=" + s);
Response.ContentType = "application/pdf";
Response.WriteFile(s);
Response.Flush();
Response.Clear();
}
public DataSet GetData()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable("Product");
DataRow dr;
dt.Columns.Add(new DataColumn("Price", typeof(Int32)));
dt.Columns.Add(new DataColumn("DisCount", typeof(Int32)));
dt.Columns.Add(new DataColumn("SellPrice", typeof(Int32)));
for (int i = 1; i <= 10; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = i * 2;
dr[2] = 1 * 3;
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
Session["dt"] = dt;
return ds;
}
}


*Create a new clas Mypage.cs in app_code folder.

using System;
using System.Data;
using System.Configuration;
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;

/// <summary>
/// Summary description for MyPage
/// </summary>
public class MyPage : Page
{
public override void VerifyRenderingInServerForm(Control control)
{
GridView grid = control as GridView;
if (grid != null && grid.ID == "GridView1")
return;
else
base.VerifyRenderingInServerForm(control);

}
}

Tuesday, July 22, 2008

How to add an RSS feed to your website





Many websites have RSS feeds, especially websites with blogs. An RSS feed identifies content on your website, including the publication date. Web browsers and blog readers use the RSS feed to notify users when content is updated.

The acronym RSS stands for "really simple syndication", and the "really simple" part is no exaggeration. Thanks to the simplicity of RSS it's very easy to add an RSS feed to your website. You can read about the RSS specification here.

Here's what my RSS feed looks like. Pretty simple, eh?

Step 1: Create an .aspx page (e.g. rss.aspx) that returns information about your content in RSS format. This .aspx page will return data in XML format, not HTML. I recommend using output caching on this page since it's likely to be retrieved frequently. I cache my rss feed for one minute:



<%@ OutputCache Duration="60" VaryByParam="none" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="rss.aspx.cs" Inherits="rss" %>
In the code-behind for the .aspx page, just build your RSS data and output it with Response.Write.

For example, here's my code-behind. The code first calls a dummy Data Method to get all the data about my blog. The data is stored in a dataset. Then the code iterates through each row in the dataset and builds the section of the RSS XML. Finally, the items are inserted into the XML and the XML is output using Response.Write():
Step 2: Now that you have a .aspx page that returns your RSS data, you need to notify web browsers and blog readers that the feed exists. Just add a tag to the section of your .aspx pages. For example, here's my tag:



<head runat="server">
<link rel="alternate" type="application/rss+xml" title="RSS" href="rss.aspx" runat="server" id="rss_link" visible="false" />

<title>Untitled Page</title>
</head>

check out this complete code



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Rss.aspx.cs" Inherits="Rss" %>
<%@ OutputCache Duration="60" VaryByParam="none" %>

<!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">
<link rel="alternate" type="application/rss+xml" title="RSS" href="rss.aspx" runat="server" id="rss_link" visible="false" />

<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>

</div>
</form>
</body>
</html>


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 Rss : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

rss_link.Visible = true;

if (!IsPostBack)
{
DataTable entriesDataSet = new DataTable();
entriesDataSet = Data();

const string itemFormat =
@"
<item>
<title>{0}</title>
<link>{1}</link>
<description>{2}</description>
<pubDate>{3}</pubDate>
</item>"
;

string items = string.Empty;

foreach (DataRow row in entriesDataSet.Rows)
{
string url = string.Format("http://localhost/MyPractice/Rss.aspx?b={0}", row["ID"]);
DateTime pubDate = (DateTime)row["TimeStamp"];

string item = string.Format(itemFormat, row["Title"], url, row["Title"], pubDate.ToString("s"));

items = item + items;
}

const string rssFormatString =
@"<rss version=""2.0"">
<!-- generated {0} -->
<channel>
<title>xyz</title>
<link>http://aspdotnetcodebook.blogspot.com</link>
<description>by xyz</description>
{1}
</channel>
</rss>"
;

string result = string.Format(rssFormatString, DateTime.Now, items);

Response.Clear();
Response.BufferOutput = true;
Response.ContentType = "text/xml";
Response.StatusCode = 200;

Response.Write(result);
Response.End();
}
}

public DataTable Data()
{

DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Title", typeof(string));
dt.Columns.Add("link", typeof(string));
dt.Columns.Add("description", typeof(string));
dt.Columns.Add("TimeStamp", typeof(DateTime));

dt.Rows.Add(new object[] { "1", "test", "http://abc.com ", "test", "12/12/2008" });
dt.Rows.Add(new object[] { "2", "test", "http://abc.com ", "test", "12/12/2008" });
dt.Rows.Add(new object[] { "3", "test", "http://abc.com ", "test", "12/12/2008" });

return dt;
}
}

How To Create A Filebrowser in ASP




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

<!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>
<h1 class="boxes">
Files on the Server:
<asp:Literal ID="litLocation" runat="server" />
</h1>
<asp:Panel ID="panFiles" runat="server" CssClass="boxes">
<asp:PlaceHolder ID="myPlaceHolder" runat="server" />
</asp:Panel>
<asp:Panel ID="Panel1" runat="server" CssClass="boxes">
<asp:TextBox ID="txtFolder" runat="server"></asp:TextBox>
<asp:Button ID="btnNewFolder" runat="server" Text="Create New Folder" OnClick="btnNewFolder_Click" />
</asp:Panel>
<asp:Panel ID="panUpload" runat="server" CssClass="boxes">
Choose a file to upload to the server<br />
<asp:FileUpload ID="fupTest" runat="server" Width="400px" />
<br />
<asp:Button ID="btnUpload" runat="server" Text="Upload File" OnClick="btnUpload_Click" />
<p>
<asp:Label ID="labMessage" runat="server"></asp:Label>
</p>
</asp:Panel>
</div>
</form>
</body>
</html>


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.IO;

public partial class FileBrowser : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string currentRoot = RetrievePathOfFolderToDisplay();
litLocation.Text = currentRoot;
GenerateListing(currentRoot);
}
/// <summary>
/// Displays the content of the specified folder.
/// </summary>
private void GenerateListing(string rootpath)
{
// First clear out the place holder
myPlaceHolder.Controls.Clear();
// Calculate the path to retrieve folders + files
string path = Server.MapPath("") + "/" + rootpath;
// Make the "go up a level" link if needed
MakeUpOneLevelLink(rootpath);
// Get a list of all folders
DirectoryInfo dirInfo = new DirectoryInfo(path);
DirectoryInfo[] folders = dirInfo.GetDirectories();
// Loop through each folder and display it
foreach (DirectoryInfo folder in folders)
{
DisplayFolder(folder, rootpath);
}
// Get a list of all the files in current path
FileInfo[] files = dirInfo.GetFiles();
// Loop through each file
foreach (FileInfo file in files)
{
DisplayFile(file, rootpath);
}
}
/// <summary>
/// Retrieves the path of the folder to be displayed
/// </summary>
///
private string RetrievePathOfFolderToDisplay()
{
string localpath = Request.QueryString["local"];
// If no query string, use uploads folder as the root
if (localpath == null)
return "uploads";
else
// Remove the URL encoding necessary for
// the querystring
return Server.UrlDecode(localpath);
}
/// <summary>
/// Displays the appropriate controls for the passed folder
/// </summary>
private void DisplayFolder(DirectoryInfo folder, string rootpath)
{
// Get the folder name without the path
string shortfolder = Path.GetFileName(folder.FullName);
// Add a folder icon
Image img = new Image();
img.ImageUrl = "images/mime_folder.png";
myPlaceHolder.Controls.Add(img);
// Add a nonbreakable space
LiteralControl space1 = new LiteralControl("&nbsp;");
myPlaceHolder.Controls.Add(space1);
// Add a link to the folder so user can display it
HyperLink lnk = new HyperLink();
lnk.Text = shortfolder;
// The link for the folder must pass the folder name.
// Because the folder name may contain characters that are
// not allowed in a querystring, we must URL encode it
lnk.NavigateUrl = "FileBrowser.aspx?local=" +
Server.UrlEncode(rootpath + "/" + shortfolder);
myPlaceHolder.Controls.Add(lnk);
// Add a line break
LiteralControl br1 = new LiteralControl("<br/>");
myPlaceHolder.Controls.Add(br1);
}
/// <summary>
/// Displays the appropriate controls for the passed file
/// </summary>
private void DisplayFile(FileInfo file, string rootpath)
{// Get the filename without the path
string shortname = Path.GetFileName(file.FullName);
// Add a file icon
Image img = new Image();
img.ImageUrl = GetIconForExtension(file);
myPlaceHolder.Controls.Add(img);
// Add a nonbreakable space
LiteralControl space2 = new LiteralControl("&nbsp;");
myPlaceHolder.Controls.Add(space2);
// Add a link to the file so user can download/view it
HyperLink lnk = new HyperLink();
lnk.Text = shortname;
lnk.NavigateUrl = Server.UrlDecode(rootpath) + "/" +
shortname;
myPlaceHolder.Controls.Add(lnk);
// Add the file size in kb
long kb = file.Length / 1000;
LiteralControl size = new LiteralControl(" [" + kb +
" KB]");
myPlaceHolder.Controls.Add(size);
// Add a line break
LiteralControl br2 = new LiteralControl("<br/>");
myPlaceHolder.Controls.Add(br2);
}
/// <summary>
/// Returns the filename of the appropriate icon image file
/// based on the extension of the passed file
/// </summary>
private string GetIconForExtension(FileInfo file)
{
string image = "images/";
string ext = Path.GetExtension(file.FullName).ToLower();
if (ext == ".txt")
image += "mime_text.png";
else if (ext == ".doc")
image += "mime_doc.png";
else if (ext == ".pdf")
image += "mime_pdf.png";
else if (ext == ".gif" || ext == ".jpg" || ext == ".wmf")
image += "mime_image.gif";
else if (ext == ".html" || ext == ".htm")

image += "mime_html.gif";
else
image += "mime_unknown.png";
return image;
}
/// <summary>
/// Makes the "go up a level" link (if needed for the
/// current folder) and adds it to the place holder
/// </summary>
private void MakeUpOneLevelLink(string currentFolder)
{
// Get the previous folder (the next one "up" in
// the hierarchy)
string previousFolder = GetPreviousFolder(currentFolder);
// If there is a previous path, add a link to
// place holder
if (previousFolder != "")
{
Image imgBack = new Image();
imgBack.ImageUrl = "images/mime_folder.gif";
myPlaceHolder.Controls.Add(imgBack);
HyperLink lnkBack = new HyperLink();
lnkBack.Text = "..";
lnkBack.NavigateUrl = "FileBrowser.aspx?local=" +
Server.UrlEncode(previousFolder);
myPlaceHolder.Controls.Add(lnkBack);
LiteralControl br = new LiteralControl("<br/>");
myPlaceHolder.Controls.Add(br);
}
}
/// <summary>
/// Gets the previous folder (the next one "up" in the file
/// system hierarchy) from the passed path.
/// If there was no previous folder, return an
/// empty string
/// </summary>
private string GetPreviousFolder(string path)
{
int posOfLastSlash = path.LastIndexOf("/");
if (posOfLastSlash < 0)
return "";
string stripped = path.Remove(posOfLastSlash);
return stripped;
}
/// <summary>
/// Event handler for the upload button for the FileUploader
/// </summary>
protected void btnUpload_Click(object sender, EventArgs e)
{
// The location for the uploaded file is current path
string path = RetrievePathOfFolderToDisplay();
if (fupTest.HasFile)
{
string fullname = Server.MapPath(path + "/" +
fupTest.FileName);
if (System.IO.File.Exists(fullname))
{
labMessage.Text =
"File already exists - uploaded cancelled";
}
else
{
fupTest.SaveAs(fullname);
labMessage.Text = "File successfully uploaded";
// Recreate the file listing to show the
// uploaded file
GenerateListing(path);
}
}
else
{
labMessage.Text = "File was not specified";
}
}
/// <summary>
/// Event handler for the create new folder button
/// </summary>
protected void btnNewFolder_Click(object sender, EventArgs e)
{
// Get the location for the new folder
string folderLocation = RetrievePathOfFolderToDisplay();
string fullPath = Server.MapPath(folderLocation) + "/" +
txtFolder.Text;
// Create the folder on the server
Directory.CreateDirectory(fullPath);
// Recreate the file listing to show the new folder
GenerateListing(folderLocation);
}

}

How To Add Programming Languages in the App_Code Folder

The source code in the App_Code folder is compiled into a single assembly, all the files in the App_Code folder must be in the same programming language. For example, the App_Code folder cannot include source code in both Visual Basic and C#.

However, you can configure your Web application to treat subfolders of the App_Code folder as separate compilable units. Each folder can then contain source code in a different programming language. The configuration is specified by creating a codeSubDirectories element in the compilation element of the Web.config file and adding a reference to the subfolder. The following example illustrates how you would configure subfolders named VBCode and CSCode to compile into separate assemblies:




compilation debug="false">
<codeSubDirectories>
<add directoryName="VBCode" />
<add directoryName="CSCode" />
</codeSubDirectories>
</compilation>

The references to the VBCode and CSCode subfolders do not need to include any
information about what programming language is contained in the subfolder.
with the App_Code folder itself, ASP.NET infers the compiler to use based on the
files in the subfolder.

How To Create a Value Type That Can Be Initialized to Null


You have a variable that is a numeric type, which will hold a numeric value obtained from a database. The database may return this value as a null. You need a simple clean way to store this numeric value, even if it is returned as a null.

Use a nullable value type. There are two ways of creating a nullable value type. The first way is to use the ? type modifier:

In addition, testing the nullable type can be done in
one of two ways. First, by using the HasValue property as shown here:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="NullableType.aspx.cs" Inherits="NullableType" %>

<!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>
<table border="1">
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</td>
<td>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></td>
</tr>
</table>
</div>
</form>
</body>
</html>


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 NullableType : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
//Essentially both of the following statements are equivalent:
int? myDBInt = null;
Nullable<int> myDBInt = new Nullable<int>();


if (myDBInt.HasValue)
Label1.Text = "Has a value: " + myDBInt.Value;
else
Label1.Text = "Does not have a value (NULL)";

}
}

Monday, July 21, 2008

size of the viewstate in ASP.NET




When you are developing an ASP.NET web form, you want to make sure that the viewstate isn't larger than it has to be. The more viewstate you've got, the longer the page takes to render in the browser. I have often seen gigantic viewstates, larger than 50 kb in size. For obvious reasons, this is not desirable if it can be avoided without breaking any functionality.

To test the size of the viewstate, just view the source code and count the lines of the hidden input field where the viewstate resides. This is not a very accurate measure but the is an easier way. Before deploying the final website to the public, you can add this method to the page and it will print out the number of characters in the viewstate. This is a much faster way of testing it for optimization.



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

<!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>
</form>
</body>
</html>




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.Text.RegularExpressions;
public partial class ViewState : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected override void Render(HtmlTextWriter writer)
{
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);
base.Render(htmlWriter);

string viewstate = GetViewstate(sw.ToString());
Response.Write(viewstate.Length);
writer.Write("Size Of View State");
writer.Write(sw.ToString());
}

private string GetViewstate(string html)
{
Regex regex = new Regex("(<input.*?__VIEWSTATE.*?/>)", RegexOptions.IgnoreCase);
Match match = regex.Match(html);

if (match.Success)
{
int start = match.Captures[0].Value.IndexOf("value=\"") + 7;
int stop = match.Captures[0].Value.LastIndexOf("\"");
return match.Captures[0].Value.Substring(start, stop - start);
}

return string.Empty;
}
}

Asynchronous GridView in 5 simple steps

A web page with a data bound GridView control can take a long time to load. The page is not rendered until all the controls are, and the GridView cannot render before data has been retrieved from the database. So, let’s load the GridView asynchronous and make the page load faster and the perceived speed greater.

This little trick is actually very simple and it involves the built-in client callback feature of ASP.NET. Even though I’m not a big fan of that particular feature, it can be quite handy from time to time. The best part of this is that you don’t have to change much to your existing code.

Web page

On the webpage that hosts the GridView control, you have to make 2 small changes.

Step 1. Encapsulate the GridView
The GridView control has to be encapsulated by an HTML control with an id attribute, so that it can be referenced by JavaScript. That is because the GridView does not render when no data is bound to it.

"grid">
Loading...
"Server" ID="gvAsync" />

Step 2. Add a JavaScript
Then a JavaScript is needed to load the rendered and data bound GridView to the HTML control we added in step 1. Place the JavaScript below the GridView’s surrounding div tag.



Code-behind

In the code-behind file there are three small steps to perform.

Step 3. Implement ICallbackEventHandler
We need to implement the interface to turn on the client callback feature.

public partial class asyncgridview : System.Web.UI.Page, ICallbackEventHandler

Step 4. Bind the call back reference
The literal control placed in the JavaScript function in step 2 has to contain the client callback reference. Add the following to the Page_Load.

if (!Page.IsCallback)
ltCallback.Text = ClientScript.GetCallbackEventReference(this, "'bindgrid'", "EndGetData", "'asyncgrid'", false);

Step 5. Bind the grid and return the rendered HTML
To finish the asynchronous loading we have to implement the two methods that are defined by the ICallbackEventHandler interface we implemented in step 3. One of the methods binds a DataTable to the GridView and renders the control. The second returns the rendered HTML to the JavaScript method we defined in step 2.

private string _Callback;

public string GetCallbackResult()
{
return _Callback;
}

public void RaiseCallbackEvent(string eventArgument)
{
DataTable table = RetrieveDataTableFromDatabase();
gvAsync.DataSource = table;
gvAsync.DataBind();

using (System.IO.StringWriter sw = new System.IO.StringWriter())
{
gvAsync.RenderControl(new HtmlTextWriter(sw));
_Callback = sw.ToString();
}
}

You can use your present data binding method to bind the GridView. The important part is that the GridView is data bound before the RaiseCallbackEvent method renders the control.

The same technique can be used for all the data control such as the Repeater, FormView and DataList.






<%@ Page Language="C#" AutoEventWireup="true" CodeFile="asyncgridview.aspx.cs" Inherits="asyncgridview" %>
<!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>Async GridView</title>
</head>
<body>
<form id="form1" runat="server">

<div id="grid">
<span>Loading...</span>
<asp:GridView runat="Server" ID="gvAsync" />
</div>

<script type="text/javascript">
function EndGetData(arg)
{
document.getElementById("grid").innerHTML = arg;
}

setTimeout("<asp:literal runat="server" id="ltCallback" />", 100);
</script>

</form>
</body>
</html>


using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class asyncgridview : System.Web.UI.Page, ICallbackEventHandler
{
protected void Page_Load(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(5000);
if (!Page.IsCallback)
ltCallback.Text = ClientScript.GetCallbackEventReference(this, "'bindgrid'", "EndGetData", "'asyncgrid'", false);
}

private DataTable RetrieveDataTableFromDatabase()
{
DataTable table = new DataTable();
table.Columns.Add("Product", typeof(string));
table.Columns.Add("Price", typeof(float));

table.Rows.Add("Hat", 16);
table.Rows.Add("Jacket", 234);
table.Rows.Add("Socks", 35);

return table;
}

#region ICallbackEventHandler Members

private string _Callback;

public string GetCallbackResult()
{
return _Callback;
}

public void RaiseCallbackEvent(string eventArgument)
{
DataTable table = RetrieveDataTableFromDatabase();
gvAsync.DataSource = table;
gvAsync.DataBind();

using (System.IO.StringWriter sw = new System.IO.StringWriter())
{
gvAsync.RenderControl(new HtmlTextWriter(sw));
_Callback = sw.ToString();
}
}

#endregion
}

How To Open div popup with a LightBox effect




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


<!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>
<script type="text/javascript">

function showBox()
{
var width = document.documentElement.clientWidth + document.documentElement.scrollLeft;

var layer = document.createElement('div');
layer.style.zIndex = 2;
layer.id = 'layer';
layer.style.position = 'absolute';
layer.style.top = '0px';
layer.style.left = '0px';
layer.style.height = document.documentElement.scrollHeight + 'px';
layer.style.width = width + 'px';
layer.style.backgroundColor = 'black';
layer.style.opacity = '.6';
layer.style.filter += ("progid:DXImageTransform.Microsoft.Alpha(opacity=60)");
document.body.appendChild(layer);

var div = document.createElement('div');
div.style.zIndex = 3;
div.id = 'box';
div.style.position = (navigator.userAgent.indexOf('MSIE 6') > -1) ? 'absolute' : 'fixed';
div.style.top = '200px';
div.style.left = (width / 2) - (400 / 2) + 'px';
div.style.height = '50px';
div.style.width = '400px';
div.style.backgroundColor = 'white';
div.style.border = '2px solid silver';
div.style.padding = '20px';
document.body.appendChild(div);

var p = document.createElement('p');
p.innerHTML = 'Some text';
div.appendChild(p);

var a = document.createElement('a');
a.innerHTML = 'Close window';
a.href = 'javascript:void(0)';
a.onclick = function()
{
document.body.removeChild(document.getElementById('layer'));
document.body.removeChild(document.getElementById('box'));
};

div.appendChild(a);
}
</script>
</head>
<body style="height:2000px">
<form id="form1" runat="server">
<div>


<a href="javascript:void(showBox())">Toggle box</a>


</div>
</form>
</body>
</html>

Binding Data to a Web Forms DataList




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


<!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:DataList ID="dataList" Style="z-index: 102; left: 16px; position: absolute;
top: 56px"
runat="server" OnCancelCommand="dataList_CancelCommand" OnDeleteCommand="dataList_DeleteCommand"
OnEditCommand="dataList_EditCommand" OnItemCommand="dataList_ItemCommand" OnUpdateCommand="dataList_UpdateCommand">
<SelectedItemTemplate>
<asp:Button ID="editButton" runat="server" Text="Edit" CommandName="Edit"></asp:Button>
<b>
<%# DataBinder.Eval(Container.DataItem, "Id") %>
;
<%# DataBinder.Eval(Container.DataItem, "IntField") %>
;
<%# DataBinder.Eval(Container.DataItem, "StringField") %>
</b>
</SelectedItemTemplate>
<ItemTemplate>
<asp:Button ID="selectButton" runat="server" Text="Select" CommandName="Select"></asp:Button>
<%# DataBinder.Eval(Container.DataItem, "Id") %>
;
<%# DataBinder.Eval(Container.DataItem, "IntField") %>
;
<%# DataBinder.Eval(Container.DataItem, "StringField") %>
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="updateButton" runat="server" Text="Update" CommandName="Update"></asp:Button>
<asp:Button ID="deleteButton" runat="server" Text="Delete" CommandName="Delete"></asp:Button>
<asp:Button ID="cancelButton" runat="server" Text="Cancel" CommandName="Cancel"></asp:Button>
<br>
<asp:Label ID="Label1" runat="server">ID: </asp:Label>
<asp:TextBox ID="idTextBox" runat="server" Width="96px" ReadOnly="True" Text='<%# DataBinder.Eval(Container.DataItem, "Id") %>'>
</asp:TextBox>
<br>
<asp:Label ID="Label2" runat="server">IntField: </asp:Label>
<asp:TextBox ID="intFieldTextBox" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,
"IntField") %>'
>
</asp:TextBox>
<br>
<asp:Label ID="Label3" runat="server">StringField: </asp:Label>
<asp:TextBox ID="stringFieldTextBox" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,
"StringField") %>'
>
</asp:TextBox>
</EditItemTemplate>
</asp:DataList>
</div>
</form>
</body>
</html>


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.Text;
public partial class DataListTest : System.Web.UI.Page
{


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

}

}

private void BindList()
{
if (Session["DataSource"] == null)
{
dataList.DataSource = GetDataSet();
dataList.DataKeyField = "Id";
}
else
{
dataList.DataSource = (DataTable)Session["DataSource"];
dataList.DataKeyField = "Id";
}
dataList.DataBind();
}
public DataTable GetDataSet()
{

DataTable dt = new DataTable("Company");
DataRow dr;
dt.Columns.Add(new DataColumn("Id", typeof(Int32)));
dt.Columns.Add(new DataColumn("IntField", typeof(Int32)));
dt.Columns.Add(new DataColumn("StringField", typeof(string)));
for (int i = 0; i <= 10; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = i;
dr[2] = "Company" + i + Environment.NewLine + "Title" + i;
dt.Rows.Add(dr);
DataColumn[] Parent_PKColumns = new DataColumn[1];
Parent_PKColumns[0] = dt.Columns["ID"];
dt.PrimaryKey = Parent_PKColumns;
Session["DataSource"] = dt;
}

return dt;
}

protected void dataList_CancelCommand(object source, DataListCommandEventArgs e)
{
// Set the index of the item being edited out of range.
dataList.EditItemIndex = -1;

BindList();

}
protected void dataList_EditCommand(object source, DataListCommandEventArgs e)
{
// Set the index of the selected item out of range.
dataList.SelectedIndex = -1;
// Set the index of the item being edited to the current record.
dataList.EditItemIndex = e.Item.ItemIndex;
BindList();
}
protected void dataList_DeleteCommand(object source, DataListCommandEventArgs e)
{
// Get the data from the session variable.
DataTable dt = (DataTable)Session["DataSource"];

// Get the ID of the row to delete.
int id = (int)dataList.DataKeys[e.Item.ItemIndex];

// Delete the row from the table.
dt.Rows.Find(id).Delete();

// Update the data source with the changes to the table.
UpdateDataSource(dt);

// Set the index of the item being edited out of range.
dataList.EditItemIndex = -1;




BindList();

}

public void UpdateDataSource(DataTable dt)
{

dt.AcceptChanges();
Session["ds"] = dt;
}
protected void dataList_ItemCommand(object source, DataListCommandEventArgs e)
{
// Check if the "select" button is pressed.
if (e.CommandName == "Select")
{
// Set the index of the item being edited out of range.
dataList.EditItemIndex = -1;
// Set the index of the selected item to the current record.
dataList.SelectedIndex = e.Item.ItemIndex;

BindList();
}
}
protected void dataList_UpdateCommand(object source, DataListCommandEventArgs e)
{
// Get the data from the session variable.
DataTable dt = (DataTable)Session["DataSource"];

// Get the ID of the row to update.
int id = (int)dataList.DataKeys[e.Item.ItemIndex];

// Get the DataRow to update using the ID.
DataRow dr = dt.Rows.Find(id);

// Get the column values for the current record from the DataList.
dr["IntField"] =
Int32.Parse(((TextBox)e.Item.FindControl("intFieldTextBox")).Text);
dr["StringField"] =
((TextBox)e.Item.FindControl("stringFieldTextBox")).Text;

// Update the data source with the changes to the table.
UpdateDataSource(dt);

// Set the index of the item being edited out of range.
dataList.EditItemIndex = -1;

BindList();

}
}

FileUpload and Ajax UpdatePanel

All file upload controls (includes asp, telerik, componentart, component factory and others) does not working in any ajax update panel and upload control needs to full page postback. This means if your upload control located in an update panel, control does not post the file. If you look to the posted file property of the control, you will see it null. So, the control always have to post full page postback.

This is a limitation comes from the XmlHttpRequest component, used in all AJAX frameworks for asynchronous calls to the application. In order to upload a file you should perform a full page postback.

If you have automatically AJAX-enabled button or other control, which normally does postbacks, placed in UpdatePanel you could use one of following workarounds to make the button to perform postbacks again.

1 - You need to create a PostBackTrigger for the button which should initiate postback.



<asp:updatepanel runat="server" id="UpdatePanel1">
<contenttemplate>
<asp:FileUpload runat="server" id="Upload1" />
<asp:button runat="server" id="ButtonSubmit" text="Postback" />
</contenttemplate>
<triggers>
<asp:postbacktrigger controlid="ButtonSubmit" />
</triggers>
</asp:updatepanel>

2 - You can register the page and control to do full page postback. To do this, you can use the script manager. (suggested by EtienneT)


ScriptManager.GetCurrent(Page).RegisterPostBackControl(Upload1);

3 - You can use the "iframe" html object to call upload webpage in frame. But this as you know iframe is not a XHTML object. But this can be smooth fix for you. (suggested by Justin Bozoiner)

Sunday, July 20, 2008

How To Display data in marquee from database by using asp.net c#



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

<!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>
<marquee id="ml" style="text-align: center" direction="up" width="195" height="170"
scrolldelay="20" scrollamount="1">
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<br />
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# Eval("URL") %>'>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Desc") %>'></asp:Label></asp:HyperLink><br />
</ItemTemplate>
</asp:Repeater>
</marquee>
</div>
</form>
</body>
</html>


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 Marquee : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Repeater1.DataSource = GetData();
Repeater1.DataBind();
}

}
public DataSet GetData()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable("News");
DataRow dr;
dt.Columns.Add(new DataColumn("Id", typeof(Int32)));
dt.Columns.Add(new DataColumn("Url", typeof(string)));

dt.Columns.Add(new DataColumn("Desc", typeof(string)));
for (int i = 1; i <= 10; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "URL" + i.ToString();

dr[2] = "Description " + i.ToString();
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
Session["dt"] = dt;
return ds;
}
}

Hidden Field Inside GridView

If you add Visible="False" to any control Such control is not rendered on the client side at all. It is accessible on server side only. If you want to get it invisible, but present in DOM and accessible using JavaScript change
Visible="False" to style="display:none"

How To Add Title Attribute To GridView Row


Let us suppose that you have a :Grid View with about seven rows across.One of the cells is a five-digit code, for a long name.and your requirement is that the user move the mouse over the code cell, and display this long name in a small popup window, to remind the user of which the code describes.Here is a simple solution without using JavaScript. Just add "Title" attribute to each row to display the information. It will have the same effect as mouse over and mouse out




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


<!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 ID="GridView1" AutoGenerateColumns="False" runat="server" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="id" HeaderText="ProductId" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="sellPrice" HeaderText="SalePrice" />
<asp:TemplateField HeaderText="LongName">
<ItemTemplate>
<asp:Label ID="LongName" runat="server" Text='<%#ShortDesc(Eval("Desc").ToString()) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LongAgencyName" Visible="False">
<ItemTemplate>
<asp:Label ID="LongName1" runat="server" Text='<%#Eval("Desc")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>


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 Mouseover : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetData();
GridView1.DataBind();

}
}
public DataSet GetData()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable("Movie");
DataRow dr;
dt.Columns.Add(new DataColumn("Id", typeof(Int32)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));
dt.Columns.Add(new DataColumn("SellPrice", typeof(Int32)));
dt.Columns.Add(new DataColumn("Desc", typeof(string)));
for (int i = 1; i <= 10; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Name" + i.ToString();
dr[2] = (i * 3)+i*i;
dr[3] = "Abcdefghijklmnopqwrstuvwxyz"+i.ToString();
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
Session["dt"] = dt;
return ds;
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbl = (Label)e.Row.FindControl("LongName1");
e.Row.Attributes.Add("Title", lbl.Text);
e.Row.Attributes["style"] = "Cursor:hand";
}

}
public string ShortDesc(string strDesc)
{

return strDesc.Substring(0, 5);

}
}

How To: Prevent Cross-Site Scripting in ASP.NET

This How To shows how you can help protect your ASP.NET applications from cross-site scripting attacks by using proper input validation techniques and by encoding the output. It also describes a number of other protection mechanisms that you can use in addition to these two main countermeasures.

Cross-site scripting (XSS) attacks exploit vulnerabilities in Web page validation by injecting client-side script code. Common vulnerabilities that make your Web applications susceptible to cross-site scripting attacks include failing to properly validate input, failing to encode output, and trusting the data retrieved from a shared database. To protect your application against cross-site scripting attacks, assume that all input is malicious. Constrain and validate all input. Encode all output that could, potentially, include HTML characters. This includes data read from files and databases.

check out this link


How To - Prevent Script Attacks

This post describes the request validation feature of ASP.NET where, by default, the application is prevented from processing unencoded HTML content submitted to the server. This request validation feature can be disabled when the application has been designed to safely process HTML data.

Applies to ASP.NET 1.1 and ASP.NET 2.0.

Check out this article

Wednesday, July 16, 2008

C# Tutorial - Serialize Objects to a File

check out this link

C# Tutorial - The Readonly Keyword

C# has a ton of keywords, and it is sometimes hard to keep track of them all. One keyword that often gets lost in the shuffle is the readonly keyword, often because many people just group it with the const keyword and leave it at that. Well, the readonly keyword deserves better than that - and so here today we are going to talk about what exactly it does, how it differs from const, and why you would ever want to use it at all.The readonly keyword does ............................
check out this link

Introduction to LINQ - Simple XML Parsing

check out this link

C# Tutorial - Extension Methods

take a look extension methods, which is a language feature introduced to C# in .NET 3.0. Extension methods are a piece of syntactic sugar that allow you add new functionality to a class that you don't have direct access to. Sound cool yeah? Cause it is.

Building a Simple CSV Parser in C#




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.IO;
using System.Collections.Generic;

public partial class ParseCSV : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<string[]> testParse =
parseCSV("C:\\TestParse.csv");
DataTable newTable = new DataTable();
foreach (string column in testParse[0])
{
newTable.Columns.Add();
}

foreach (string[] row in testParse)
{
newTable.Rows.Add(row);
}
GridView1.DataSource = newTable;
GridView1.DataBind();
}
public List<string[]> parseCSV(string path)
{
List<string[]> parsedData = new List<string[]>();

using (StreamReader readFile = new StreamReader(path))
{
string line;
string[] row;

while ((line = readFile.ReadLine()) != null)
{
row = line.Split(',');
parsedData.Add(row);
}
}

return parsedData;
}
}


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

<!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 ID="GridView1" runat="server">
</asp:GridView>

</div>
</form>
</body>
</html>

CSV Parser Using List

Javascript Tutorial - Draggable View In A Container

Check out this link Click here

C# Tutorial XML-Serialization

Check out this tutorial for XML serialization Click here

How To Add Tooltip in GridView




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


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>

<script language="JavaScript">
<!--

var bname;
var bversion;
var brows;

function reg()
{
bname=navigator.appName;
bversion=parseInt(navigator.appVersion)
if (bname=="Netscape")
brows=true
else
brows=false
}

// Do not edit anything else in the script !!!!

function don(row,path){
if ((bname=="Netscape" && bversion>=4) || (bname=="Microsoft Internet Explorer" && bversion>=4)){
if (brows){

document.layers['linkex'].document.writeln('<img src='+path+' />');
document.layers['linkex'].document.close();
var rec = getoffset(row);
document.layers['linkex'].top=rec.Top+row.offsetTop;
document.layers['linkex'].left=rec.Left;

document.layers['linkex'].visibility="show";
}
else{
//debugger;
linkex.innerHTML='<img src='+path+' />';
var rec = getoffset(row);
linkex.style.top=rec.Top+row.offsetHeight;
linkex.style.left=rec.Left;
//linkex.style.background=bgcolor;

linkex.style.visibility="visible";
}
}
}

function doff(){
if ((bname=="Netscape" && bversion>=4) || (bname=="Microsoft Internet Explorer" && bversion>=4)){
if (brows)
document.layers['linkex'].visibility="hide";
else
linkex.style.visibility="hidden";
}
}

function getoffset(e)
{
var t=e.offsetTop;
var l=e.offsetLeft;
while(e=e.offsetParent)
{
t+=e.offsetTop;
l+=e.offsetLeft;
}
var rec = new Object();

rec.Top = t;
rec.Left = l;

return rec
}

//-->


</script>

</head>
<body onload='reg();'>
<form id="form1" runat="server">
<div id="linkex" style="position: absolute; visibility: hidden; width: 80%">
</div>
<layer name="linkex" visibility="hide" width="80%:">
</layer>
<div>
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound">
</asp:GridView>
</div>
</form>
</body>
</html>


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 tooltip : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
bind();
}

private void bind()
{
DataTable table = new DataTable();
table.Columns.Add("booktitle");
table.Columns.Add("tooltip");


DataRow dr = table.NewRow();
dr["booktitle"] = "aaaaa";
dr["tooltip"] = "cart_icon.jpg";
table.Rows.Add(dr);
DataRow dr1 = table.NewRow();
dr1["booktitle"] = "ddd";
dr1["tooltip"] = "cart_icon2.jpg";
table.Rows.Add(dr1);
this.GridView1.DataSource = table;
GridView1.DataBind();
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView drv = ((DataRowView)e.Row.DataItem);
string path = drv["tooltip"].ToString();
e.Row.Attributes.Add("onmouseover", "don(this,'" + path + "')");
e.Row.Attributes.Add("onmouseout", "doff()");
}
}
}

Extend BoundField Of GridView


.
In this post i will show you how to extend BoundField Column of Gridview to add MultiLine support
Step 1.Place the code in app_code directory


using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomBoundField
{
public class BoundTextBoxField : System.Web.UI.WebControls.BoundField
{

public TextBoxMode TextMode
{
get
{
TextBoxMode _tm = TextBoxMode.SingleLine;
if (this.ViewState["TextMode"] != null)
_tm = (TextBoxMode)this.ViewState["TextMode"];
return _tm;
}
set { this.ViewState["TextMode"] = value; }
}

public int Columns
{
get
{
int i = 0;
if (this.ViewState["Columns"] != null)
i = (int)this.ViewState["Columns"];
return i;
}
set { this.ViewState["Columns"] = value; }
}

public int Rows
{
get
{
int i = 0;
if (this.ViewState["Rows"] != null)
i = (int)this.ViewState["Rows"];
return i;
}
set { this.ViewState["Rows"] = value; }
}

public bool Wrap
{
get
{
bool b = true;
if (this.ViewState["Wrap"] != null)
b = (bool)this.ViewState["Wrap"];
return b;
}
set { this.ViewState["Wrap"] = value; }
}

protected override void OnDataBindField(object sender, EventArgs e)
{
base.OnDataBindField(sender, e);
Control c = (Control)sender;
if (c is TextBox)
{
TextBox txt = (TextBox)c;
txt.TextMode = this.TextMode;
txt.Columns = this.Columns;
txt.Rows = this.Rows;
txt.Wrap = this.Wrap;
}
}

}

}

Step2. Register the Control in asp page

Default.aspx

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

<%@ Register Namespace="CustomBoundField" TagPrefix="custom"%>

<!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 AutoGenerateColumns="false" ID="GridView1" runat="server" AutoGenerateEditButton="True" OnRowEditing="GridView1_RowEditing">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Single Line" />
<custom:boundtextboxfield datafield="Name" headertext="MultiLine Text" sortexpression="Text"
textmode="MultiLine" rows="5" columns="25" wrap="True" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Default.aspx.cs


using System;
using System.Data;
using System.Configuration;
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 _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}

}
private void BindGrid()
{
GridView1.DataSource = GetDataSource();
GridView1.DataBind();
}
protected DataTable GetDataSource()
{

const string key = "MyDataSource";
DataTable dt = Session[key] as DataTable;

if (dt == null)
{

dt = new DataTable();
dt.Columns.Add("ID", typeof(int));

dt.Columns.Add("Name", typeof(string));
dt.Rows.Add("1", "first object");

dt.Rows.Add("2", "second object");
dt.Rows.Add("3", "second object");
dt.Rows.Add("4", "second object");
Session[key] = dt;

}

return dt;
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();

}

}


Tuesday, July 15, 2008

The XML page cannot be displayed(Tips)



terminate the page lifecyle after output xml data. So make sure you invoke Response.End() method after you do all things.

How to Serialize and DeSerialize an object into XML


In this post , I am going to show how to Serialize and DeSerialize an object (can be a collection object or an object) into XML format using ASP.NET System.Xml.Serialization.XmlSerializer class.

Before I explain how to Serialize and DeSerialize an object, let me tell you why to serialize. We should serialize an object if we want to store the object instance into the disk or we want to store the object into Session or Cache (storing serialized object into Cache or Session works faster than storing the object directly) or pass the object between applications regardless of which platform they have hosted on and technology they are built in.

Now why to use XML Serialization? As XML is an open standard, XML stream can be processed by any application, as needed regardless of platform. XML Serialization coverts (Serializes) the public fields and properties of an object, or parameters and return values of method, into an XML stream.


Required namespace to Serialize and DeSerialize an object in this artilce are:

  1. System.IO

  2. System.Xml

  3. System.Xml.Serialization

In order to show how to Serialize and DeSerialize an object, I will create a class called XmlClass that will have two public variable named name,email and address. My code for this post is as follows



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


<!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:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Serialize" />&nbsp;
<asp:Button ID="Button2" runat="server" Text="DeSerialize" OnClick="Button2_Click" />&nbsp;
</div>
</form>
</body>
</html>



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.Xml;
using System.Xml.Serialization;
using System.IO;

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



}
protected void Button1_Click(object sender, EventArgs e)
{
XmlClass obj = new XmlClass();
obj.name = "test";
obj.emial = "test@gmail.com";
obj.address = "test";
string s = obj.SerializeAnObject(obj);
Response.ContentType = "text/xml";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.Write(s);
Response.End();


}
protected void Button2_Click(object sender, EventArgs e)
{

}
}
public class XmlClass
{

public string name = string.Empty;
public string emial = string.Empty;
public string address = string.Empty;

public string SerializeAnObject(object obj)
{
XmlDocument doc = new XmlDocument();
XmlSerializer serializer = new XmlSerializer(obj.GetType());

MemoryStream stream = new MemoryStream();
try
{
serializer.Serialize(stream, obj);
stream.Position = 0;
doc.Load(stream);
return doc.InnerXml;
}
catch
{
throw;
}

finally
{
stream.Close();
stream.Dispose();
}
}
public object DeSerializeAnObject(string xmlOfAnObject)
{
XmlClass myObject = new XmlClass();
StringReader read = new StringReader(xmlOfAnObject);
XmlSerializer serializer = new XmlSerializer(myObject.GetType());
System.Xml.XmlReader reader = new XmlTextReader(read);
try
{
myObject = (XmlClass)serializer.Deserialize(reader);
return myObject;
}
catch
{
throw;
}
finally
{
reader.Close();
read.Close();
read.Dispose();
}

}
}

How to find public key token for a .NET DLL or assembly




Many times we need to get the Public key token for a strongly named assembly in .NET. FAQ on that “how to get the public key token?”. Answer is very simple use the .NET Framework tools sn.exe. So open the Visual Studio 2008 Command Prompt and then point to the dll’s folder you want to get the public key,

Use the following command,

sn –T Test.dll

This will give you the public key token. Remember one thing this only works if the assembly has to be strongly signed.

Example

C:\Program Files\Microsoft Visual Studio 8\VC>sn -T C:\Test.dll
Microsoft (R) .NET Framework Strong Name Utility Version 2.0.50727.42
Copyright (C) Microsoft Corporation. All rights reserved.
public key token is 91b47bd693f571

Downloadable Assemblies

This technique may be helpfull for createing destributed applications or application that needs to be updateable through LAN or internet. What do you need to know:

  • What is strong name
  • What is assembly
  • How to use command line (cmd.exe)
  • How to use csc compiler
  • Hot to configure application, What is config file
  • What is IIS

Steps:
  • Create strong named assembly
  • Compile it
  • Place at your server
  • Create Solution that will use this assembly
  • Create Config file for your solution with the following contents
     
How to:
1. Create strong named assembly

a. Generate the key (cmd command): sn -k key.snk
b. Put following lines in your assembly source code:
using System;
using System.Reflection;
....


[assembly:AssemblyKeyFile(@"PATH\key.snk")]
[assembly:AssemblyVersion("1.0.0.0")]


....
namespace My
{

     

<?xml version="1.0" encoding="utf-8" ?>

<configuration>



<runtime>

<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">

<dependentAssembly>

<assemblyIdentity name="lib"

publicKeyToken="0adfbaad3776a0d3"

culture="neutral" />



<codeBase version="1.0.0.0" href="http://localhost/asm/lib.dll"/>

</dependentAssembly>

</assemblyBinding>

</runtime>





</configuration>





Copy files from local server folder to FTP server

In this post i will show how to copy files from local server folder a FTP server folder using FtpWebRequest class.


private void FTPUpload(string filename, string ftpServerIP1)
{
string ftpUserID1 = "";//Ftp UserId
string ftpPassword1=""//ftp password
FileInfo fileInf = new FileInfo(filename);
string uri = "ftp://" + ftpServerIP1 + "/" + fileInf.Name;
FtpWebRequest reqFTP;
// Create FtpWebRequest object from the Uri provided
reqFTP = (FtpWebRequest)FtpWebRequest.Create
(new Uri("ftp://" + ftpServerIP1 + "/" + fileInf.Name));
// Provide the WebPermission Credintials
reqFTP.Credentials = new NetworkCredential(ftpUserID1, ftpPassword1);
// By default KeepAlive is true, where the control connection
// is not closed after a command is executed.
reqFTP.KeepAlive = false;
// Specify the command to be executed.
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
// Specify the data transfer type.
reqFTP.UseBinary = true;
// Notify the server about the size of the uploaded file
reqFTP.ContentLength = fileInf.Length;
int buffLength = 500447300;
byte[] buff = new byte[buffLength];

int contentLen;
// Opens a file stream (System.IO.FileStream) to read the file
// to be uploaded
FileStream fs = fileInf.OpenRead();
try
{
// Stream to which the file to be upload is written
Stream strm = reqFTP.GetRequestStream();
// Read from the file stream 2kb at a time
contentLen = fs.Read(buff, 0, buffLength);
// Till Stream content endswhile (contentLen != 0)
{

// Write Content from the file stream to the FTP Upload
// Stream

strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}

strm.Close();
fs.Close();

}
catch (Exception ex)
{

throw new Exception(ex.Message);
}

}

Monday, July 14, 2008

How To Invoking Webmethods from Remote Machine

We can test a ASP.NET Web service by browsing the .asmx file and trying to invoke the webmethods available, from the local machine.

However, If we would like to invoke the service from other machine, by default, it would display the message "The test form is only available for requests from the local machine."

To enable the Service to be invoked from remote machine, we need to add the following settings to the Web.Config file of the Web Service Application.


<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
This would enable the Web service to be able to be invoked from remote machine. This setting would only be useful in development / testing scenarios and it is advisable to remove / comment the above section when releasing for production, due to security reasons.

We can test a ASP.NET Web service by browsing the .asmx file and trying to invoke the webmethods available, from the local machine.

However, If we would like to invoke the service from other machine, by default, it would display the message "The test form is only available for requests from the local machine."

To enable the Service to be invoked from remote machine, we need to add the following settings to the Web.Config file of the Web Service Application.


<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
This would enable the Web service to be able to be invoked from remote machine. This setting would only be useful in development / testing scenarios and it is advisable to remove / comment the above section when releasing for production, due to security reasons.

ASP.NET AJAX Validators

http://blogs.msdn.com/mattgi/archive/2007/01/23/asp-net-ajax-validators.aspx

Server.MapPath

Server.MapPath is a function that takes one argument, a virtual path on the Web server, and returns the corresponding physical path.

This function can be used in a number of ways.
First, you can use it to obtain the physical path of a particular web page. For example:
C#
string strFilePath;
strFilePath = Server.MapPath("/WebApp/myWebPage.aspx");
You also can use this method to obtain the physical path of a particular directory. For example:
C#
//current directory
string strCurrDir = Server.MapPath("");
//parent directory
string strParentDir = Server.MapPath("..");
//root directory

string strRootDir = Server.MapPath("/");

Whether you use backslahed (\) or forward slashes (/), it is same in this function. If you do not put a forward or backward slash at the beginning of the string passed into Server.MapPath, the current directory that the ASP page is being executed is used as the base for the physical path. Else, the root physical path is used as the base for the physical path. For example:

C#
string strFilePath1 = Server.MapPath("someXmlFile.xml");
string strFilePath2 = Server.MapPath("/someXmlFile.xml");

Sunday, July 13, 2008

Consuming Web Services With ASP.NET AJAX



<%@ Page Language="C#" %>

<!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>SingingEels - Consuming Web Services with ASP.NET AJAX Demo</title>

<script type="text/javascript">
function findVendor() {
var zipCode = $get("ZipCode").value;

VendorLocator.GetNearestDealer(function(result) {
// Assign the Distance
$get("distance").innerHTML = result.Distance;

// Assign the Name
$get("name").innerHTML = result.Name;

// Assign the Phone Number
$get("phoneNumber").innerHTML = result.PhoneNumber;

// Make the dealer results visible
$get("dealerResults").style.display = "";
});
}

</script>

</head>
<body>
<form runat="server">
<asp:ScriptManager ID="ScriptManager" runat="server">
<Services>
<asp:ServiceReference Path="~/VendorLocator.asmx" />
</Services>
</asp:ScriptManager>
<h1>
Search Page</h1>
<p>
Enter your zip code below to find the closest product vendor.</p>
<fieldset>
<label>
Zip Code<input type="text" id="ZipCode" /></label>
<button onclick="findVendor();">
Search
</button>
</fieldset>
<dl id="dealerResults" style="display: none;">
<dt>Distance:</dt>
<dd id="distance" />
<dt>Name:</dt>
<dd id="name" />
<dt>Phone:</dt>
<dd id="phoneNumber" />
</dl>
</form>
</body>
</html>


using System.Web.Script.Services;
using System.Web.Services;

[ScriptService]
public class VendorLocator : WebService
{
[WebMethod, ScriptMethod]
public SearchResult GetNearestDealer()
{
// We are intentionally returning a hard coded result for this example.
return new SearchResult(20, "Bob's Widget Store", "(555) 567-8901");
}
}

// This is our "SearchResult" class which will automatically be JSON serialized
// by ASP.NET AJAX and passed into JavaScript as a parameter.
public class SearchResult
{
public SearchResult()
{
}

public SearchResult(int distance, string name, string phoneNumber)
{
this.distance = distance;

this.name = name;

this.phoneNumber = phoneNumber;
}

private int distance;
public int Distance
{
get { return this.distance; }
set { this.distance = value; }
}

private string name;
public string Name
{
get { return this.name; }
set { this.name = value; }
}

private string phoneNumber;
public string PhoneNumber
{
get { return this.phoneNumber; }
set { this.phoneNumber = value; }
}
}

How To Create Dynamic Control based on a selected value




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


<!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>

<table>

<tr>

<td>

<asp:DropDownList ID="ddlist" runat="server" AutoPostBack="True"
OnSelectedIndexChanged
="ddlist_SelectedIndexChanged">

<asp:ListItem Text="select" Value="0"></asp:ListItem>

<asp:ListItem Text="1" Value="1"></asp:ListItem>

<asp:ListItem Text="2" Value="2"></asp:ListItem>

<asp:ListItem Text="3" Value="3"></asp:ListItem>

<asp:ListItem Text="4" Value="4"></asp:ListItem>

<asp:ListItem Text="5" Value="5"></asp:ListItem>

<asp:ListItem Text="6" Value="6"></asp:ListItem>
<asp:ListItem Text="7" Value="7"></asp:ListItem>

</asp:DropDownList>

</td>

</tr>

<tr>

<td>

<asp:PlaceHolder ID="pnl" runat="server" Visible="true"></asp:PlaceHolder>

</td>

</tr>

</table>

</div>

<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</form>
</body>
</html>


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 Dynamic : System.Web.UI.Page
{

protected override void OnInit(EventArgs e)
{
base.OnInit(e);
HtmlTable oHtmlTable = new HtmlTable();
oHtmlTable.ID = "tbl";
oHtmlTable.EnableViewState = true;
if (IsPostBack)
{
string ostr = Page.Request.Params["__EVENTTARGET"];
string oValue = Page.Request.Form[ostr];
if (oValue != null && int.Parse(oValue) > 0)
{
for (int i = 0; i < int.Parse(oValue); i++)
{
HtmlTableCell ocell = new HtmlTableCell();
HtmlTableRow orow = new HtmlTableRow();
TextBox oTextBox = new TextBox();
oTextBox.ID = "txtBx" + i.ToString();
ocell.Controls.Add(oTextBox);
orow.Cells.Add(ocell);
oHtmlTable.Rows.Add(orow);
}
pnl.Controls.Clear();
pnl.Controls.Add(oHtmlTable);
Session["MyTable"] = (HtmlTable)FindControl("tbl");
}
else
pnl.Controls.Add((HtmlTable)Session["MyTable"]);
}

}
protected void Page_Load(object sender, EventArgs e)
{
PlaceHolder ohtmltable = (PlaceHolder)FindControl("pnl");
updatetextboxes(ohtmltable);
}
protected void ddlist_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
PlaceHolder ohtmltable = (PlaceHolder)FindControl("pnl");//(HtmlTable)FindControl("tbl");
if (ohtmltable != null)
{
updatetextboxes(ohtmltable);
Response.Write("U r successfull");
}
}

private void updatetextboxes(Control oControl)
{
if (oControl.HasControls())
{
foreach (Control c in oControl.Controls)
updatetextboxes(c);
}
else if (oControl is System.Web.UI.WebControls.TextBox)
((TextBox)oControl).Text = ((TextBox)oControl).ID;

}

}

How To Add Client Side Validation in AjaxEnabled Site




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


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"
>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>

<script language="javascript" type="text/javascript">
function validate()
{
if (document.getElementById("<%=txtName.ClientID%>").value=="")
{
alert("Name Feild can not be blank");
document.getElementById("<%=txtName.ClientID%>").focus();
return false;
}
if(document.getElementById("<%=txtEmail.ClientID %>").value=="")
{
alert("Email id can not be blank");
document.getElementById("<%=txtEmail.ClientID %>").focus();
return false;
}
var emailPat = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/;
var emailid=document.getElementById("
<%=txtEmail.ClientID %>").value;
var matchArray = emailid.match(emailPat);
if (matchArray == null)
{
alert("
Your email address seems incorrect. Please try again.");
document.getElementById("
<%=txtEmail.ClientID %>").focus();
return false;
}
if(document.getElementById("
<%=txtWebURL.ClientID %>").value=="")
{
alert("
Web URL can not be blank");
document.getElementById("
<%=txtWebURL.ClientID %>").value="http://"
document.getElementById("<%=txtWebURL.ClientID %>").focus();
return false;
}
var Url="^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$"
var tempURL=document.getElementById("<%=txtWebURL.ClientID%>").value;
var matchURL=tempURL.match(Url);
if(matchURL==null)
{
alert("Web URL does not look valid");
document.getElementById("<%=txtWebURL.ClientID %>").focus();
return false;
}
if (document.getElementById("<%=txtZIP.ClientID%>").value=="")
{
alert("Zip Code is not valid");
document.getElementById("<%=txtZIP.ClientID%>").focus();
return false;
}
var digits="0123456789";
var temp;
for (var i=0;i<document.getElementById("<%=txtZIP.ClientID %>").value.length;i++)
{
temp=document.getElementById("<%=txtZIP.ClientID%>").value.substring(i,i+1);
if (digits.indexOf(temp)==-1)
{
alert("Please enter correct zip code");
document.getElementById("<%=txtZIP.ClientID%>").focus();
return false;
}
}
return true;
}
</script>

</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<table>
<tr>
<td>
Name</td>
<td>
<asp:TextBox ID="txtName" runat="Server" />
</td>
<td>
Email</td>
<td>
<asp:TextBox ID="txtEmail" runat="Server" />
</td>
<td>
URL</td>
<td>
<asp:TextBox ID="txtWebURL" runat="Server" /></td>
<td>
Zip</td>
<td>
<asp:TextBox ID="txtZIP" runat="Server" />
</td>
</tr>
</table>
<asp:Button ID="DoButton" OnClick="DoButton_Click" runat="server" Text="Do something" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>


using System;
using System.Data;
using System.Configuration;
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 _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void DoButton_Click(object sender, EventArgs e)
{
//Do something on server side.

string scripttext = "validate()";
ScriptManager.RegisterStartupScript(Page, this.GetType(), "close", scripttext, true);

}
}

Friday, July 11, 2008

Create Windows Service in Visual Studio [C#]

his example shows step-by-step how to create a windows service in Visual Studio 2005.

Create new project and select windows service (Visual C# / Windows / Windows Service). Enter the project name, e.g. „MyService“.










View designer of the Service1.cs and click to Add Installer in the Properties window.



It adds a ProjectInstaller­.cs file to the project. This file contains two components, a ServiceInsta­ller and a ServiceProces­sInstaller.

Click to serviceInstaller1 and in the Properties window set ServiceName to „MyService“, change DisplayName (shown in Microsoft Management Console) and fill in the Description field. You can also set StartType to automatic or manual service starting.



Click to serviceProces­sInstaller1 and change the Account property to a value you need. It's an account under which the system runs the service. Account descriptions can be found in ServiceAccount enumeration.




Complete the implementation of OnStart and OnStop methods in the service class.


String Format for Int [C#]

Integer numbers can be formatted in .NET in many ways. You can use static method String.Format or instance method int.ToString. Following examples shows how to align numbers (with spaces or zeroes), how to format negative numbers or how to do custom formatting like phone numbers.

Add zeroes before number

To add zeroes before a number, use colon separator „:“ and write as many zeroes as you want.

[C#]
String.Format("{0:00000}", 15);          // "00015"
String.Format("{0:00000}", -15); // "-00015"

Align number to the right or left

To align number to the right, use comma „,“ followed by a number of characters. This alignment option must be before the colon separator.

[C#]
String.Format("{0,5}", 15);              // "   15"
String.Format("{0,-5}", 15); // "15 "
String.Format("{0,5:000}", 15); // " 015"
String.Format("{0,-5:000}", 15); // "015 "

Different formatting for negative numbers and zero

You can have special format for negative numbers and zero. Use semicolon separator „;“ to separate formatting to two or three sections. The second section is format for negative numbers, the third section is for zero.

[C#]
String.Format("{0:#;minus #}", 15);      // "15"
String.Format("{0:#;minus #}", -15); // "minus 15"
String.Format("{0:#;minus #;zero}", 0); // "zero"

Custom number formatting (e.g. phone number)

Numbers can be formatted also to any custom format, e.g. like phone numbers or serial numbers.

[C#]
String.Format("{0:+### ### ### ###}", 447900123456); // "+447 900 123 456"
String.Format("{0:##-####-####}", 8958712551); // "89-5871-2551"

Short Tutorial On DataView RowFilter



DataView RowFilter Syntax [C#]

This example describes syntax of DataView.RowFil¬ter expression.
It shows how to correctly build expression string (without „SQL injection“)
using
methods to escape values.

Column names

If a column name contains any of these special characters ~ ( ) # \ / = > < + - * % & | ^ ' " [ ],
you must enclose the column name within square brackets [ ]. If a column name
contains right bracket ] or backslash \, escape it with backslash (\] or \\).

[C#]

dataView.RowFilter = "id = 10";      // no special character in column name "id"

dataView.RowFilter = "$id = 10";     // no special character in column name "$id"

dataView.RowFilter = "[#id] = 10";   // special character "#" in column name "#id"

dataView.RowFilter = "[[id\]] = 10"; // special characters in column name "[id]"

 

Literals

String values are enclosed within single quotes ' '. If the string contains single
quote '
, the quote must be doubled.

[C#]

dataView.RowFilter = "Name = 'John'"        // string value

dataView.RowFilter = "Name = 'John ''A'''"  // string with single quotes "John 'A'"

 

dataView.RowFilter = String.Format("Name = '{0}'", "John 'A'".Replace("'", "''"));

 

Number values are not enclosed within any characters. The values should be the same 
as
is the result of int.ToString() or float.ToString() method for invariant or
English culture.

[C#]

dataView.RowFilter = "Year = 2008"          // integer value

dataView.RowFilter = "Price = 1199.9"       // float value

 

dataView.RowFilter = String.Format(CultureInfo.InvariantCulture.NumberFormat,

                     "Price = {0}", 1199.9f);

 

Date values are enclosed within sharp characters # #. The date format is the
same as is the result of DateTime.ToString() method for invariant or English
culture.

[C#]

dataView.RowFilter = "Date = #12/31/2008#"          // date value (time is 00:00:00)

dataView.RowFilter = "Date = #2008-12-31#"          // also this format is supported

dataView.RowFilter = "Date = #12/31/2008 16:44:58#" // date and time value

 

dataView.RowFilter = String.Format(CultureInfo.InvariantCulture.DateTimeFormat,

                     "Date = #{0}#", new DateTime(2008, 12, 31, 16, 44, 58));

 

Alternatively you can enclose all values within single quotes ' '. It means you
can use string values for numbers or date time values. In this case the current
culture is used to convert the string to the specific value.

[C#]

dataView.RowFilter = "Date = '12/31/2008 16:44:58'" // if current culture is English

dataView.RowFilter = "Date = '31.12.2008 16:44:58'" // if current culture is German

 

dataView.RowFilter = "Price = '1199.90'"            // if current culture is English

dataView.RowFilter = "Price = '1199,90'"            // if current culture is German

 

Comparison operators

Equal, not equal, less, greater operators are used to include only values that suit
to a comparison expression. You can use these operators = <> < <= >
>=.

Note: String comparison is culture-sensitive, it uses CultureInfo from
DataTable.Locale property of related table (dataView.Table.Locale). If the property
is not explicitly set, its default value is DataSet.Locale (and its default value
is current system culture Thread.Curren¬tThread.Curren¬tCulture).

[C#]

dataView.RowFilter = "Num = 10"             // number is equal to 10

dataView.RowFilter = "Date < #1/1/2008#"    // date is less than 1/1/2008

dataView.RowFilter = "Name <> 'John'"       // string is not equal to 'John'

dataView.RowFilter = "Name >= 'Jo'"         // string comparison

 

Operator IN is used to include only values from the list. You can use the operator
for all data types, such as numbers or strings.

[C#]

dataView.RowFilter = "Id IN (1, 2, 3)"                    // integer values

dataView.RowFilter = "Price IN (1.0, 9.9, 11.5)"          // float values

dataView.RowFilter = "Name IN ('John', 'Jim', 'Tom')"     // string values

dataView.RowFilter = "Date IN (#12/31/2008#, #1/1/2009#)" // date time values

 

dataView.RowFilter = "Id NOT IN (1, 2, 3)"  // values not from the list

 

Operator LIKE is used to include only values that match a pattern with wildcards.
Wildcard character is * or %, it can be at the beginning of a pattern '*value',
at the end 'value*', or at both '*value*'. Wildcard in the middle of a
patern 'va*lue' is not allowed.

[C#]

dataView.RowFilter = "Name LIKE 'j*'"       // values that start with 'j'

dataView.RowFilter = "Name LIKE '%jo%'"     // values that contain 'jo'

 

dataView.RowFilter = "Name NOT LIKE 'j*'"   // values that don't start with 'j'

 

If a pattern in a LIKE clause contains any of these special characters * % [ ],
those characters must be escaped in brackets [ ] like this [*], [%], [[] or []].

[C#]

dataView.RowFilter = "Name LIKE '[*]*'"     // values that starts with '*'

dataView.RowFilter = "Name LIKE '[[]*'"     // values that starts with '['

 

The following method escapes a text value for usage in a LIKE clause.

[C#]

public static string EscapeLikeValue(string valueWithoutWildcards)

{

  StringBuilder sb = new StringBuilder();

  for (int i = 0; i < valueWithoutWildcards.Length; i++)

  {

    char c = valueWithoutWildcards[i];

    if (c == '*' || c == '%' || c == '[' || c == ']')

      sb.Append("[").Append(c).Append("]");

    else if (c == '\'')

      sb.Append("''");

    else

      sb.Append(c);

  }

  return sb.ToString();

}

 

[C#]

// select all that starts with the value string (in this case with "*")

string value = "*";

// the dataView.RowFilter will be: "Name LIKE '[*]*'"

dataView.RowFilter = String.Format("Name LIKE '{0}*'", EscapeLikeValue(value));

 

Boolean operators

Boolean operators AND, OR and NOT are used to concatenate expressions.
Operator NOT has precedence over AND operator and it has precedence over
OR operator.

[C#]

// operator AND has precedence over OR operator, parenthesis are needed

dataView.RowFilter = "City = 'Tokyo' AND (Age < 20 OR Age > 60)";

 

// following examples do the same

dataView.RowFilter = "City <> 'Tokyo' AND City <> 'Paris'";

dataView.RowFilter = "NOT City = 'Tokyo' AND NOT City = 'Paris'";

dataView.RowFilter = "NOT (City = 'Tokyo' OR City = 'Paris')";

dataView.RowFilter = "City NOT IN ('Tokyo', 'Paris')";

 

Arithmetic and string operators

Arithmetic operators are addition +, subtraction -, multiplication *,
division / and modulus %.

[C#]

dataView.RowFilter = "MotherAge - Age < 20";   // people with young mother

dataView.RowFilter = "Age % 10 = 0";           // people with decennial birthday

 

There is also one string operator concatenation +.

Parent-Child Relation Referencing

A parent table can be referenced in an expression using parent column name with
Parent. prefix. A column in a child table can be referenced using child column
name with Child. prefix.

The reference to the child column must be in an aggregate function because child
relationships may return multiple rows. For example expression SUM(Child.Price)
returns sum of all prices in child table related to the row in parent table.

If a table has more than one child relation, the prefix must contain relation name.
For example expression Child(OrdersToItemsRelation).Price references to column
Price in child table using relation named OrdersToItemsRe¬lation.

Aggregate Functions

There are supported following aggregate functions SUM, COUNT, MIN, MAX,
AVG (average), STDEV (statistical standard deviation) and VAR (statistical variance).


This example shows aggregate function performed on a single table.

[C#]

// select people with above-average salary

dataView.RowFilter = "Salary > AVG(Salary)";

 

Following example shows aggregate functions performed on two tables which have
parent-child relation. Suppose there are tables Orders and Items with the
parent-child relation.

[C#]

// select orders which have more than 5 items

dataView.RowFilter = "COUNT(Child.IdOrder) > 5";

 

// select orders which total price (sum of items prices) is greater or equal $500

dataView.RowFilter = "SUM(Child.Price) >= 500";

 

Functions

There are also supported following functions. Detailed description can be found here DataColumn.Ex¬pression.

•    CONVERT – converts particular expression to a specified .NET Framework type

•    LEN – gets the length of a string

•    ISNULL – checks an expression and either returns the checked expression or
a replacement value

•    IIF – gets one of two values depending on the result of a logical expression

•    TRIM – removes all leading and trailing blank characters like \r, \n, \t, ‚ ‘

•    SUBSTRING – gets a sub-string of a specified length, starting at a specified
point in the string

 

IFormatProvider for Numbers [C#]

This example shows how to convert float to string and string to float using IFormatProvider. To get IFormatProvider you need to get CultureInfo instance first.

Get invariant or specific CultureInfo

Invariant culture is a special type of culture which is culture-insensitive. You should use this culture when you need culture-independent results, e.g. when you format or parse values in XML file. The invariant culture is internally associated with the English language. To get invariant CultureInfo instance use static property CultureInfo.In­variantCulture.

To get specific CultureInfo instance use static method CultureInfo.Get­CultureInfo with the specific culture name, e.g. for the German language CultureInfo.GetCultureInfo("de-DE").

Format and parse numbers using the IFormatProvider

Once you have the CultureInfo instance use property CultureInfo.Num­berFormat to get an IFormatProvider for numbers (the NumberFormatInfo object)

[C#]
// format float to string
float num = 1.5f;
string str = num.ToString(CultureInfo.InvariantCulture.NumberFormat); // "1.5"
string str = num.ToString(CultureInfo.GetCultureInfo("de-DE").NumberFormat); // "1,5"

[C#]
// parse float from string
float num = float.Parse("1.5", CultureInfo.InvariantCulture.NumberFormat);
float num = float.Parse("1,5", CultureInfo.GetCultureInfo("de-DE").NumberFormat);

Thursday, July 10, 2008

How To Add postback to a href



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


<!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>
<a href="javascript:document.forms[0].MyButton.click();">simulate button click</a>
<asp:Button ID="MyButton" runat="Server" Text="Test"
OnClick="MyButton_Click" Style="visibility: hidden" />


<%--Second way--%>
<%--<a href="javascript:window.location='<%=HttpContext.Current.Request.Url.AbsoluteUri.ToString()%>'" >
Click to Post back</a>--%>

</div>
</form>
</body>
</html>


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 Postback : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void MyButton_Click(object sender, EventArgs e)
{
Response.Write("Postback From Javascript");
}
}

Javascript - Delete Textbox text onFocus

Let's say you have an ASP.Net TextBox server control that has the text:
"Enter Fax #"
Then, you want the text to disappear when the user clicks inside the TextBox - - here is a very simple solution.
In the Page_Load event, put:
txtFax.Attributes("OnFocus")="document.formName.txtFax.value='';"

Select Specific ListBox Item

If you don't know the exact index number in the list of listbox items (listbox1.selectedindex=x), then you can find an item and select it by using the Value of the item:
ListBox1.Items.FindByValue(MyValue).Selected = true
If you don't know theValue of the item, but you know the text, you can find and select the item using the Text of the item:
ListBox1.Items.FindByText("TextYouAreLookingFor").Selected = true

ASP.Net Server Controls Not Showing on pages

It's possible that ASP.Net is not registered correctly on your system.Try running aspnet_regiis from the command prompt.Here's the default location:
C:\[Windows Folder]\Microsoft.NET\Framework\[ASP.Net Version#]\ aspnet_regiis.exe -i
Windows Server 2003, you must use aspnet_regiis -i -enable. This is because of the "Web Service Extensions" feature in IIS 6
(if you install VS.NET or the framework without IIS installed, and then go back in and install IIS afterwards, you have to re-register so that ASP.NET 'hooks' into IIS properly.")

Select Specific DropDownList Item

With a dropdown list - you can dynamically select items in the list with a sort of 'built-in' find routine.To select a certain item, based on the Value of the item in the list:


DropDownList.SelectedIndex = DropDownList.Items.IndexOf(DropDownList.Items.FindByValue(YourValueHere))
To select a certain item, based on the Text of the item in the list:
DropDownList.SelectedIndex = DropDownList.Items.IndexOf(DropDownList.Items.FindByText("YourTextHere"))
OR - you can do it this way:
DropDownList.Items.FindByText("TextYouAreLookingFor").Selected = true
or, using the value of the item
DropDownList.Items.FindByValue("ValueYouAreLookingFor").Selected = true

Force Button Click by Pressing Enter Key

Sometimes, you will notice, that, in an ASP.Net form, depending on the circumstances, pressing the 'Enter' key to submit the form does not work.To force this to happen for a particular button on your page, just put this in the Page_Load routine:
Page.RegisterHiddenField("__EVENTTARGET", "button1")
Then, change 'button1' to the ID of your particular button. Understand, of course, if your cursor is inside of a MultiLine textbox, the default action of the enter key is to create a new line in the textbox, so, if this basically works anywhere outside of that scenario.