Tuesday, October 11, 2011

Using Javascript to POST data between pages


The following is a simple example of how to submit data from one HTML page to another using the POST method from Javascript. Normally, if data needs to be sent from one HTML page to another, it is done by appending the information to the query parameter of the the URL in the familiar “name=value” format. e.g.

< href="post.aspx?user=peter&cc=aus">Click</a>
Although this works fine, in most cases, problems occur when there is a lot of data to send and the URL exceeds about 2000 characters. The other disadvantage is that the URL looks ugly. The traditional method to get around this is to POST the data using a form. e.g.
<form name="myform" method="post" action="post.aspx">
<input name="user" value="peter"/>
<input value="cc" value="aus"/>
<a href="javascript:myform.submit()">Click</a>
<form>
This works fine, however, it does tend to make the formatting of the resulting HTML difficult and increases the size of the final HTML page significantly if there are lots of links on it.
The following javascript function takes the URL of the target page and an associative array of name/values paires and POSTs the data to the supplied URL by dynamically creating a form and then submitting it.
function postwith (to,p) {
  var myForm = document.createElement("form");
  myForm.method="post" ;
  myForm.action = to ;
  for (var k in p) {
    var myInput = document.createElement("input") ;
    myInput.setAttribute("name", k) ;
    myInput.setAttribute("value", p[k]);
    myForm.appendChild(myInput) ;
  }
  document.body.appendChild(myForm) ;
  myForm.submit() ;
  document.body.removeChild(myForm) ;
}
To insert a link into a page just use a normal anchor tag in the HTML and call the function.
<a href="javascript:postwith('post.aspx',{user:'peter',cc:'aus'})">click</a>
This works on Microsoft IE, Mozilla Firefox and OS X Safari.

Sunday, October 2, 2011

Validation - RequiredFieldValidator

The RequiredFieldValidator is actually very simple, and yet very useful. You can use it to make sure that the user has entered something in a TextBox control. Let's give it a try, and add a RequiredFieldValidator to our page. We will also add a TextBox to validate, as well as a button to submit the form with.


<form id="form1" runat="server">
    Your name:<br />
    <asp:TextBox runat="server" id="txtName" />
    <asp:RequiredFieldValidator runat="server" id="reqName" controltovalidate="txtName" errormessage="Please enter your name!" />
    <br /><br />
    <asp:Button runat="server" id="btnSubmitForm" text="Ok" />
</form>
Actually, that's all we need to test the most basic part of the RequiredFieldValidator. I'm sure that all the attributes of the controls makes sense by now, so I won't go into details about them. Try running the website and click the button. You should see something like this: 

 

If your browser supports DHTML, which most modern browers do, then you will notice that the page is not being posted back to the server - the validation is performed clientside! This is one of the really cool things about ASP.NET validators. Validation is only performed serverside if necessary! To see how it feels, you can add enableclientscript="false" to the RequiredFieldValidator and try again. Now you will see the browser posting back to the server, but the result will be the same - the validator still works! 

Right now, the button does nothing, besides posting back if the page is valid. We will change this by adding an onclick event to it:
<asp:Button runat="server" id="btnSubmitForm" text="Ok" onclick="btnSubmitForm_Click" />
In the CodeBehind file, we add the following event handler:
protected void btnSubmitForm_Click(object sender, EventArgs e)
{
    if(Page.IsValid)
    {
        btnSubmitForm.Text = "My form is valid!";
    }
}
As you will notice, we check whether or not the page is valid, before we do anything. This is very important, since this code WILL be reached if the clientside validation is not used, for some reason. Once it comes to serverside validation, it's your job to make sure that no sensitive code is executed unless you want it to. As you see, it's very simple - just check the Page.IsValid parameter, and you're good to go. Try to run the website again, and notice how the text of the button is changed if you submit a valid form. 

Tuesday, September 6, 2011

MS SQL Server Drop all tables quickly


Just a quick and dirty way of dropping all the tables in a database, without dropping the database itself.  Useful for when your writing data migration scripts and staging data and need to wipe out your development environment real quick … or, when you’ve found that uber cool sql-injection-able site and want to wreak some havoc (I don’t condone the latter, but I do think its funny from time to time when it happens to the ‘big companies’).

[sql start here]
select name into #tables from sys.objects where type = ‘U’
while (select count(1) from #tables) > 0
begin
declare @sql varchar(max)
declare @tbl varchar(255)
select top 1 @tbl = name from #tables
set @sql = ‘drop table ‘ + @tbl
exec(@sql)
delete from #tables where name = @tbl
end
drop table #tables;
[/sql end here]

Tuesday, August 16, 2011

Paging with DataList Control ASP.NET C# 2010


Paging with DataList Control


DataList is a data bound list control that displays items using certain templates defined at the design time.The content of the DataList control is manipulated by using templates sections such as FooterTemplate, HeaderTemplate, ItemTemplate, SelectedItemTemplate ,AlternatingItemTemplate, EditItemTemplate and SeparatorTemplate
PagedDataSource, is a class that encapsulates the paging related properties for data-bound controls such as DataGrid, GridView, DataList, DetailsView.
Now lets take an Example of Displaying Country on Datalist with Paging


Steps.
1. Create Datalist for Country

<asp:DataList ID="dlCountry" runat="server">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Country_Code") %>'></asp:Label>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("Country_Name") %>'></asp:Label>
</ItemTemplate>
</asp:DataList>
<asp:DataList ID=" dlPaging" runat="server" OnItemCommand="dlPaging _ItemCommand">
<ItemTemplate>
<asp:LinkButton ID="lnkbtnPaging" runat="server" CommandArgument='<%# Eval("PageIndex") %>' CommandName="lnkbtnPaging" Text='<%# Eval("PageText") %>'></asp:LinkButton>
</ItemTemplate>
</asp:DataList>

2. now on Code Behind write a method to fetch data from the Country’s table.
private void BindGrid()
{
string sql = “Select * from Country Order By Country_Name”;
SqlDataAdapter da = new SqlDataAdapter(sql, “Yourconnectionstring”);
DataTable dt = new DataTable();
da.Fill(dt);
pds.DataSource = dt.DefaultView;
pds.AllowPaging = true;
pds.PageSize = Convert.ToInt16(ddlPageSize.SelectedValue);
pds.CurrentPageIndex = CurrentPage;
lnkbtnNext.Enabled = !pds.IsLastPage;
lnkbtnPrevious.Enabled = !pds.IsFirstPage;
dlCountry.DataSource = pds;
dlCountry.DataBind();
doPaging();
}
3.Call this BindGrid method in the Page load event.

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
4.Declare a PagedDataSource object at page scope.
PagedDataSource pds = new PagedDataSource();
5. create new property call CurrentPage to maintain the latest selected page index.
and pu this code on it.

public int CurrentPage
{
get
{
if (this.ViewState["CurrentPage"] == null)
return 0;
else
return Convert.ToInt16(this.ViewState["CurrentPage"].ToString());
}
set
{
this.ViewState["CurrentPage"] = value;
}
}
6.write a method ‘doPaging’ to create a list of page numbers.

private void doPaging()
{
DataTable dt = new DataTable();
dt.Columns.Add("PageIndex");
dt.Columns.Add("PageText");
for (int i = 0; i < pds.PageCount; i++)
{
DataRow dr = dt.NewRow();
dr[0] = i;
dr[1] = i + 1;
dt.Rows.Add(dr);
}
dlPaging.DataSource = dt;
dlPaging.DataBind();
}
7. create new paging event

protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("lnkbtnPaging"))
{
CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
BindGrid();
}
}
8. Previous And Next Button Events
protected void lnkbtnPrevious_Click(object sender, EventArgs e)
{
CurrentPage -= 1;
BindGrid();
}
protected void lnkbtnNext_Click(object sender, EventArgs e)
{
CurrentPage += 1;
BindGrid();
}
9.Change PageSize Dynamically

protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
{
CurrentPage = 0;
BindGrid();
}
10.HighLight Selected Page Number
protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
{
LinkButton lnkbtnPage = (LinkButton)e.Item.FindControl("lnkbtnPaging");
if (lnkbtnPage.CommandArgument.ToString() == CurrentPage.ToString())
{
lnkbtnPage.Enabled = false;
lnkbtnPage.Font.Bold = true;
}
}

Thursday, August 4, 2011

.NET Format String 102: DateTime Format String


DateTime has its own set format string modifiers because there are so many ways to display a date and time. There are 2 things that affects how your DateTime is formatted.
1. CultureInfo
Besides the format string modifiers, CultureInfo on your thread also greatly influences the output. My examples will be based on CultureInfo.InvariantCulture.
You can set the CultureInfo on your thread by calling this

Thread
.CurrentThread.CurrentCulture = <some culture>;
eg.
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
2. Format String
There are actually two different ways of formatting a DateTime object. Both methods produce the same results:
DateTime now = DateTime.Now;
now.ToString("<dateTimeFormatString>");
String.Format("<strFormat>", now);

Basically:
<strFormat> = {<argument index>:<dateTimeFormatString>}
My examples will use the DateTime.ToString() method.
If you have read any DateTime format string documentation, you will know that the .NET platform has two different styles of DateTime format string:
2-a. Standard Format String
This is basically built in short hand for custom format string. You pass in the one character string to denote which custom format you want.
i.e.
now.ToString("d");  
// "09/27/2006"
now.ToString("D");  // "Tuesday, 27 September 2006"
now.ToString("G");  // "09/27/2006 14:15:39"
All of the format string syntax I discussed in ".NET Format String 101" is invalid here. Also, if you call now.ToString(), it is basically calling now.ToString("G");
I have included my own table mapping Standard Format String to Custom Format string in part 2-c below.MSDN actually has a pretty good table that describe what each item does, and DateTime.ToString() has a pretty good code example that shows what each format string specifier do. Also if you just want samples, MSDN has a "Standard Date Time Format String Output example" here. Because documentation is so good. I won't go into this too much. :)
2-b. Custom Format String
Custom format string gives you the flexibility to build your own formatting. When using a single character format string specifier, you will need to prepend it with a "%", otherwise it will be interpreted as a Standard Format String. Here are the basics for building your own string:
DateTime now = new DateTime(2006, 9, 07, 15, 06, 01, 08, DateTimeKind.Local);
now.ToString();      //"09/27/2006 15:06:01"

Year
now.ToString("%y");   //"6"
now.ToString("yy");   //"06"
now.ToString("yyy");  //"2006"
now.ToString("yyyy"); //"2006"

Month
now.ToString("%M");    //"9"
now.ToString("MM");    //"09"
now.ToString("MMM");   //"Sep"
now.ToString("MMMM");  //"September"

Day
now.ToString("%d");    //"7"
now.ToString("dd");    //"07"
now.ToString("ddd");   //"Thu"
now.ToString("dddd");  //"Thursday"

Hour
now.ToString("%h");    //"3"
now.ToString("hh");    //"03"
now.ToString("hhh");   //"03"
now.ToString("hhhh");  //"03"
now.ToString("%H");    //"15"
now.ToString("HH");    //"15"
now.ToString("HHH");   //"15"
now.ToString("HHHH");  //"15"

Minutes
now.ToString("%m");    //"3"
now.ToString("mm");    //"03"
now.ToString("mmm");   //"03"
now.ToString("mmmm");  //"03"

Seconds
now.ToString("%s");    //"1"
now.ToString("ss");    //"01"
now.ToString("sss");   //"01"
now.ToString("ssss");  //"01"

Milliseconds
now.ToString("%f");    //"0"
now.ToString("ff");    //"00"
now.ToString("fff");   //"008"
now.ToString("ffff");  //"0080"
now.ToString("%F");    //""
now.ToString("FF");    //""
now.ToString("FFF");   //"008"
now.ToString("FFFF");  //"008"

Kind
now.ToString("%K");    //"-07:00"
now.ToString("KK");    //"-07:00-07:00"
now.ToString("KKK");   //"-07:00-07:00-07:00"
now.ToString("KKKK");  //"-07:00-07:00-07:00-07:00"
// Note: The multiple K were just read as multiple instances of the
// single K

DateTime unspecified = new DateTime(now.Ticks, DateTimeKind.Unspecified);
unspecified.ToString("%K");   //""

DateTime utc = new DateTime(now.Ticks, DateTimeKind.Utc);
utc.ToString("%K");           //"Z"

TimeZone
now.ToString("%z");     //"-7"
now.ToString("zz");     //"-07"
now.ToString("zzz");    //"-07:00"
now.ToString("zzzz");   //"-07:00"

Other
now.ToString("%g");    //"A.D."
now.ToString("gg");    //"A.D."
now.ToString("ggg");   //"A.D."
now.ToString("gggg");  //"A.D."

now.ToString("%t");    //"P"
now.ToString("tt");    //"PM"
now.ToString("ttt");   //"PM"
now.ToString("tttt");  //"PM" 
2-c. Additional Resources
Now that you understand what Standard and Custom format strings are, here is a table of Standard Format String to Custom Format String mapping:
Year Month Day Patterns:
d      = "MM/dd/yyyy"
D      = 
"dddd, dd MMMM yyyy"
M or m = 
"MMMM dd"
Y or y = 
"yyyy MMMM"
Time Patterns:
t      = "HH:mm"
T      = 
"HH:mm:ss"
Year Month Day and Time without Time Zones:
f      = "dddd, dd MMMM yyyy HH:mm"
F      = 
"dddd, dd MMMM yyyy HH:mm:ss"
g      = 
"MM/dd/yyyy HH:mm"
G      = 
"MM/dd/yyyy HH:mm:ss"
Year Month Day and Time with Time Zones:
o      = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK"
R or r = 
"ddd, dd MMM yyyy HH':'mm':'ss 'GMT'"
s      = 
"yyyy'-'MM'-'dd'T'HH':'mm':'ss"
u      = 
"yyyy'-'MM'-'dd HH':'mm':'ss'Z'"
U      = 
"dddd, dd MMMM yyyy HH:mm:ss"
All other single characters will throw an exception.
Answering the question...
So finally, to answer the question that began this whole discussion. "What exactly would "zz" do?"  i.e. What would "now.ToString("zz")" return?
Because there are 2 characters, it will be interpreted as a custom format string. "zz" stands for the signed time zone offset with a leading zero for single digit offsets. For me, being in Pacific Standard Time, my return value would be "-07".