ASP.NET:Email Web Page
The code is very simple.allow to email the contents of a web
page The page, with codebehind, is listed below:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SendWebPageWithEmail.aspx.cs"
Inherits="Samples_SendWebPageWithEmail" %>
<!DOCTYPE html public "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<form ID="Form2" runat="server" method="post">
<table align="center" border="1">
<tr><td colspan="2"><span ID="lblTitle">ASP.NET Email Web Page</span></td> </tr>
<tr><td>URL:</td></td><asp:textbox ID="txtURL" runat="server" Width="362px"></asp:textbox>
</tr><tr><td> To Email:</td>
<td style="width: 158px"><asp:textbox ID="txtTo" runat="server" Width="362px"></asp:textbox>
</td></tr><tr><td>From Email:</td><td style="width: 158px">
<asp:textbox ID="txtFrom" runat="server" Width="362px"></asp:textbox>
</td></tr><tr><td>Email Subject:</td><td style="width: 158px">
<asp:textbox ID="txtSubject" runat="server" Width="362px"></asp:textbox>
</td></tr><tr><td><asp:button ID="btn_Send" runat="server" OnClick="btn_Send_Click" Text="Send" /></td>
<td style="width: 158px"><asp:literal ID="ltr_sent" runat="server"></asp:literal>
<asp:label ID="lbl_Result" runat="server"></asp:label>
</td></tr>
</table></form></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.Net;
using System.IO;
public partial class Samples_SendWebPageWithEmail : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private String readWebPage( string url)
{
String result;
WebResponse objResponse;
WebRequest objRequest = System.Net.HttpWebRequest.Create(url);
objResponse = objRequest.GetResponse();
using (StreamReader sr =new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
sr.Close();
}
return result;
}
protected void btn_Send_Click(object sender, EventArgs e)
{
String message = readWebPage(txtURL.Text);
if (Page.IsValid)
{
try
{
MailMessage EmailMsg = new MailMessage();
EmailMsg.To.Add(txtTo.Text);
EmailMsg.From = new MailAddress(txtFrom.Text);
EmailMsg.IsBodyHtml = true;
EmailMsg.Priority = MailPriority.Normal;
EmailMsg.Subject = txtSubject.Text;
EmailMsg.Body = message;
EmailMsg.IsBodyHtml = true; SmtpClient SMTPServer = new SmtpClient("MailServerName");
SMTPServer.UseDefaultCredentials = false;
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential("Username","Password");
SMTPServer.Credentials = SMTPUserInfo;
SMTPServer.Send(EmailMsg);
lbl_Result.Text = "Page successfully sent!";
ltr_Sent.Text = message;
}
catch (Exception ex)
{
lbl_Result.Text = "An error occurred: " + ex.ToString();
}}}
Asp.Net Multiple File Upload...
The HtmlInputFile and the FileUpload controls allow the user to
upload files to the server. FileUpload is a 2.0 addition server control
that has most of the same features of the HtmlInputFile control, but
with a few added properties. However, it would be easier to have a
control that allows the user to upload more than one file at a time, or
to allow the user to add a specific number of input file boxes
dynamically in the form. Before we begin, you should be aware of some
limitations. These controls do not store their viewstate; they implement
the methods of IPostBackDataHandler; however, the LoadPostData method
always returns false. Even overriding these methods yields no effect, as
the value property for the file upload is read-only. I’ve done some
research, and supposedly in newer browsers this could be set, but I have
not come across a solution to do so. If you read my article on the
Collapsible Panel, you will have seen this event notation, where each
event has an ING and an ED event, one firing before the action takes
place (while also allowing you to cancel it), and one that fires
afterward. This is the structure for events to add and clear input boxes
in the control. The control also implements IRepeatInfoUser, to render
the file upload boxes in a horizontal or vertical fashion, or creating a
table structure. This just adds to the versatility of the control, even
though in most situations, it won’t be desired. In the rendering
process, I render Add and Clear links using the header or footer
sections of the render item. To determine this, the HasHeader and
HasFooter methods of IRepeatInfoUser check the LinkLocation property
enumeration.
public ReadOnly Property HasFooter() As Boolean Implements System.Web.UI.WebControls.IRepeatInfoUser.HasFooter
Get Return (Me.LinkLocation = LinkLocationType.Bottom)
End Get End Property
<Browsable(False)>public ReadOnly Property HasHeader() As Boolean Implements
System.Web.UI.WebControls.IRepeatInfoUser.HasHeader
Get Return (Me.LinkLocation = LinkLocationType.Top)
End Get End Property
<Browsable(False)>
public Sub RenderItem(ByVal itemType As System.Web.UI.WebControls.ListItemType,
ByVal repeatIndex As Integer,
_ByVal repeatInfo As System.Web.UI.WebControls.RepeatInfo,
_ByVal writer As System.Web.UI.HtmlTextWriter)
Implements System.Web.UI.WebControls.IRepeatInfoUser.RenderItem writer.RenderBeginTag(HtmlTextWriterTag.Tr)
writer.RenderBeginTag(HtmlTextWriterTag.Td)
If (itemType = ListItemType.Header OrElse itemType = ListItemType.Footer) Then
writer.AddAttribute(HtmlTextWriterAttribute.Href,
"javascript:" & Page.ClientScript.GetPostBackEventReference(Me, "add"))
writer.RenderBeginTag(HtmlTextWriterTag.A)
writer.Write(Me.AddLinkText)
writer.RenderEndTag()
writer.Write(" ")
writer.AddAttribute(HtmlTextWriterAttribute.Href, "javascript:" &
Page.ClientScript.GetPostBackEventReference(Me, "clear"))
writer.RenderBeginTag(HtmlTextWriterTag.A)
writer.Write(Me.ClearLinkText)
writer.RenderEndTag()
ElseIf (itemType = ListItemType.Item OrElse itemType = ListItemType.AlternatingItem) Then
Me.Controls(repeatIndex).RenderControl(writer)
End If writer.RenderEndTag() '/td
writer.RenderEndTag() '/tr
End Sub
The fileupload controls are created in CreateChildControls and
rendered above as the item. The file boxes are based upon the
InputBoxes property, which is an integer value, stating how many input
boxes to use for the control. This value is added or
reset through the AddNew and Clear methods, which AddNew adds one to it
everytime, and Clear resets it back to one.
Protected Overrides Sub CreateChildControls()
For intI As Integer = 1 To Me.InputBoxes
Dim objBox As New FileUpload
objBox.ID = "fu" & intI
Me.Controls.Add(objBox)
Next End Sub
This control also makes use of the method GetPostBackEventReference
in the RenderItem method. This method returns
a javascript string with the function that will perform the posting back
(which is rendered in a link’s href property).
The references are shown below; we use two event arguments for this
control: add and clear. RaisePostBackEvent handles
the postback. It receives the event argument, and calls the appropriate
method. 'In RenderItem method, rendered in the HREF property of an
Page.ClientScript.GetPostBackEventReference(Me, "add")
Page.ClientScript.GetPostBackEventReference(Me, "clear")
public Sub RaisePostBackEvent(ByVal eventArgument As String)
Implements System.Web.UI.IPostBackEventHandler.RaisePostBackEvent
Dim strArg As String = eventArgument.ToLower()
If (strArg = "add" OrElse strArg = "addnew") Then
AddNew()
ElseIf (strArg = "clear") Then Clear()
End If End Sub
This control also makes use of IPostBackDataHandler and uses the
LoadPostData method to check any possible uploaded files,
and if there is one, raise an event. This allows the developer to handle
the uploading of the file. As an alternative,
this control could
handle that action through an automated means by using an UploadFolder
property, referencing a folder on the web server.
public Function LoadPostData(ByVal postDataKey As String, ByVal postCollection As
_System.Collections.Specialized.NameValueCollection) As Boolean Implements_
System.Web.UI.IPostBackDataHandler.LoadPostData Me.EnsureChildControls()
For Each objControl As Control In Me.Controls
If (TypeOf (objControl) Is FileUpload) Then
Dim objUpload As FileUpload = CType(objControl, FileUpload)
If (objUpload.HasFile) Then OnInputBoxPosted(New PostedFileEventArgs(objUpload.PostedFile))
End If
End If
Next
End Function
For the control to receive postbacks, you have to call
Page.RegisterRequiresPostBack method. This will then allow LoadPostData
to fire.
protected Overrides Sub OnPreRender(ByVale As System.EventArgs)
MyBase.OnPreRender(e)
If (Page IsNot Nothing) Then Page.RegisterRequiresPostBack(Me)
End If
End Sub
This control works well with allowing users to upload multiple files.
If using the links (add and clear), you may want to list a disclaimer
stating that the user should add the desired number of textboxes first
before browsing to all of the files, as they won’t be saved. Also, the
control allows you to upload the files through a button of your own. If
you don’t want the add/clear links shown, set the LinkLocation property
to the None enumeration, and they will disappear. This class comes with
a PostedFileEventArgs that contains details about the posted file, which
is made available to the user in the InputBoxPosted event. It is defined
below.
public Class PostedFileEventArgs
Inherits System.EventArgs
Private m_objFile As HttpPostedFile
public ReadOnly Property FileName() As String
Get
Return m_objFile.FileName
End Get
End Property <Browsable(False)>
Public ReadOnly Property FileStream() As Stream
Get
Return m_objFile.InputStream
End Get
End Property
<Browsable(False)>
Public Sub New(ByVal objFile As HttpPostedFile)
m_objFile = objFile
End Sub
public Sub SaveAs(ByVal strFilePath As String)
m_objFile.SaveAs(strFilePath)
End Sub
End Class
When the test page runs, test the links for adding/clearing.
Also, try setting the InputBoxes property, and play around with the
IRepeatInfoUser
properties to change the
layout. Lastly, when you upload files, it will render the name of the
file in the page.
How to respond with code 404 (Not Found) in
ASP.NET
Suppose you configured custom 404 page in web.config file in
the
customErrors section. So whenever user requests non-existent aspx
page,
ASP.NET run-time returns well formatted message to the user.
Also you have a page that shows articles from a database according
to
article ID passed in the url (for example: article.aspx?id=1). But if
user passes article ID that doesn't exists the page must return code
404 (Not Found) and show the custom 404 page like in the previous
situation. Fortunately you don't need to parse the
customErrors
section to get name of the custom 404 page. Just throw
HttpException: new
HttpException(404, "Article not found");
ASP.NET run-time will catch the exception and will redirect to
the custom 404.
Code snippets for some common operations with
exceptions
Download and install these additional code snippets for common
operations with exceptions. To use them type shortcut for the code
snippet that you want to add to your code and then type Tab, Tab to
invoke it.
- thr
- throw new
- thrni
- throw new NotImplementedException("");
Send an e-mail any time an unhandled exception
occurs
Turn off
Session State if you're not using it
Since ASP.NETSession State is on by default, you pay the cost
in memory even if you don't use it. If you're not using Session State,
turn it off and save yourself the overhead. There are several ways to do
this:
1.If you're not using SessionState at all, turn it off
completely via web.config file:
<system.web>
<sessionState mode="Off"></sessionState>
2.If you're using SessionState,
but it's required only for a few pages, then first turn
it off for all pages:
<system.web>
<pages
enableSessionState="false">
then enable it for a specific page:
<%@
Page ... EnableSessionState="true"
%>
P.S. obviously such optimization makes sense only for high-traffic web
sites.
How to debug Windows Service startup
Actually you can use this trick every time when:
1.You want to debug a process startup.
2.You can't run the process by hitting F5 in Visual Studio (for
example, Windows Service).
So the problem is that you can't simply attach the
Visual Studio debugger to the process as there isn't one to attach to
until after you start the process. However, once you start the
process if you have a bug such as an exception in the process's
initialization you won't get the debugger attached to the process before
it's too late.
Calling
Debugger.Launch() or
Debugger.Break()
in your code allow you to debug such problems. This methods pop up the
following screen asking you which instance of the debugger it should use
to debug the application.
How to change HTML markup produced by ASP.NET
controls
There are at least two ways of changing HTML markup produced by
standard ASP.NET controls. The most obvious one is to derive a new class
based on an existing ASP.NET control class and override the necessary
rendering methods. Another option that is worth considering
is to write a small control
adapter for the existing ASP.NET control. This is a little chunk of
logic that you add to your web site to effectively "adapt" an ASP.NET
control to render the HTML you prefer. This approach has the following
two major advantages over custom controls:
1.You don't need to add the @Register directives to
your pages.
2.The ASP.NET framework comes with a built-in means to apply the
adapters to just certain browsers. When you build entirely new custom
controls you have to write your own logic to handle browser detection to
vary the response.
For example you can use
ASP.NET 2.0 CSS Friendly
Control Adapters package to generate CSS friendly markup from some
of the more commonly used ASP.NET controls.
Label to a form input field
If you set a label to a form element set the
AssociatedControlID property. This will force the label to render as
<label> rather than <span>.
A benefit of using the AssociatedControlID property is
that clicking a label when this property is set automatically changes
the form focus to the associated form input.
Add Windows Explorer to your Visual Studio
tools menu
I often need to open Windows Explorer and browse to the current
file, folder, or project that I am working on in Visual Studio.
This tip allows you to achieve this by clicking "Windows Explorer" in
the Tools menu, and is one of the most simple-yet-useful tips I know of.
To set it up, click Tools, then External
Tools..., then click Add. Now enter the
following data:
Title: Windows Explorer
Command: explorer.exe
Arguments: /select,"$(ItemPath)"
Leave Initial directoy blank, and click
OK.
Now when you click Tools, Windows Explorer,
Windows Explorer will open with the current file you are editing
selected.
Correct event invocation
Be aware that if there are no subscribers a .NET event will be null.
Therefore when raising the event from C# test it for null first.
public event EventHandler
SelectedNodeChanged;
protected
virtual void OnSelectedNodeChanged(object sender, EventArgs e)
{//Event will be null if there are no subscribers
if
(SelectedNodeChanged != null)
{
SelectedNodeChanged(this,e);} }
However in multithreaded application the last subscriber
can unsubscribe immediately after the null check and before the event is
raised. To avoid a null reference exception make a temporary copy
of the event.
public event EventHandler SelectedNodeChanged;
protected virtual void OnSelectedNodeChanged(object sender, EventArgs e)
{
//Make a temporary copy of the event to avoid possibility of
//a race condition if the last subscriber unsubscribes
//immediately after the null check and before the event is raised.
EventHandler handler = SelectedNodeChanged;
//Event will be null if there are no subscribers
if(handler != null)
{handler(this,e);} }
How to view code that is covered by the
IntelliSense pop-up
When working in Visual Studio 2008 and the IntelliSense pop-up
is visible, but you would like to view the code that is covered by it,
press and hold the Ctrl key, and the pop-up becomes
transparent so that you can view the code that is below the pop-up.
When returning DataReader from a function, specify
CommandBehavior.CloseConnection
When you create an ADO.NET DataReader object,
specify the CommandBehavior.CloseConnection enumeration
in your call to ExecuteReader. This ensures that when
you close the DataReader, the SQL connection is also
closed. This is especially helpful when you return a DataReader
from a function, and you do not have control over the calling code. If
the caller forgets to close the connection but closes the reader, both
are closed when the DataReader is created by using
CommandBehavior.CloseConnection.
This is shown in the following code fragment.
public SqlDataReader CustomerRead(int CustomerID){
//... create connection and command, open connection
return myCommand.ExecuteReader(CommandBehavior.CloseConnection);
}
//... client code
SqlDataReader myReader = CustomerRead(10248);
//... read some data
myReader.Close();
// reader and connection are closed
Use explicit casting instead of
DataBinder.Eval
The
DataBinder.Eval method uses .NET reflection to evaluate the
arguments that are passed in and to return the results. Consider
limiting the use of DataBinder.Eval during data binding operations in
order to improve ASP.NET page performance. Consider the
following ItemTemplate element within a Repeater control using
DataBinder.Eval:
<ItemTemplate>
<tr><td><%#DataBinder.Eval(Container.DataItem,
"field1") %></td>
<td><%#DataBinder.Eval(Container.DataItem,
"field2") %></td></tr></ItemTemplate>
Using explicit casting offers better performance by avoiding
the cost of .NET reflection. Cast the Container.DataItem as a
DataRowView:
<ItemTemplate><tr>
<td><%# ((DataRowView)Container.DataItem)["field1"] %></td>
<td><%# ((DataRowView)Container.DataItem)["field2"] %></td>
</tr>
</ItemTemplate>
Consider using weak references for your custom
caching solutions
Consider using
weak references when you implement a custom caching solution, so
that cached objects can be released by garbage collection when there is
memory pressure. You should use weak references mostly for objects that
are not small in size because the weak referencing itself involves some
overhead. They are suitable for medium to large-sized objects stored in
a collection.
Automatically insert attribute value quotes
Visual Studio HTML/ASPX editor can save you some time if you
enable option
Tools | Options... | Text Editor | HTML | Format | Insert
attribute value quotes when typing.
When this option is enabled, once you type a name of an attribute and
following "=" symbol, Visual Studio automatically inserts a pair of
quotes and invokes IntelliSense menu. After that you need only to select
an attribute value from the menu and hit the Enter button. It's another
nice timesaver.
Correct using of ASP.NET Cache
Often in ASP.NET application we see a code which looks like
this one:
if (Cache["SomeData"]!=null)
{ string name = ((SomeClass)Cache["SomeData"]).Name;}
This code is not safe enough and the second statement can generate a
NullReferenceException sometimes. There is no guaranttee that a cached
object will stay in the cache between two calls. After the first call
it can be deleted either by garbage collector or by another thread to
refresh cached data. So
to overcome this problem rewrite the code using
as operator:
SomeClass< someClass = Cache["SomeData"] as SomeClass;
if (someClass != null)
{
string name = someClass.Name;
//.....
}
How to create fully qualified URLs
With ASP.NET it's quite easy to get absolute path to a page by
calling the VirtualPathUtility.ToAbsolute method. Getting absolute URL
is not that obvious but still quite easy. Just combine request url with
absolute path to your ASP.NET page:
string absolutePath =
VirtualPathUtility.ToAbsolute("~/test/MyWebForm.aspx");
Uri newUri =
new Uri(Request.Url,
absolutePath);
COALESCE function instead of long CASE WHEN ... ELSE
(T-SQL)
Instead of using long "
SELECT ...
CASE WHEN ... ELSE ..."
construction, you can use the
COALESCE function when you need to find a value that is not NULL.
Lets review the following T-SQL expression,
in which we need to select an available "source":
SELECT TheSource =
CASE
WHEN localSource IS NOT NULL THEN
localSource
WHEN intranetSource
IS NOT NULL THEN
intranetSource
WHEN internetSource
IS NOT NULL THEN
internetSource
ELSE
'' END
FROM ...
Now lets rewrite the code above using COALESCE function:
SELECT TheSource =COALESCE(localSource,intranetSource, internetSource, '')
FROM ...
The tip applies to MS SQL Server 2000/2005.
Cut a line into memory
While in Visual Studio.NET source code editor, press
Ctrl+L to cut a line of
code into memory. This is an easy way to move lines around your pages,
or delete a set of lines quickly. Simple, yet useful!
How to check email works without using SMTP
Testing code that sends email has always been a pain. You had
to set up a SMTP service just to test that your .NET application sends
the e-mail correctly. However, there is a way to send
e-mails with no SMTP server set up. Just configure your .NET application
to drop e-mails into a specified folder instead of sending them via SMTP
server:
<system.net> <mailSettings><smtp deliveryMethod="SpecifiedPickupDirectory">
<specifiedPickupDirectory pickupDirectoryLocation="c:\Test\"/> </smtp> </mailSettings>
</system.net>
This will instruct SmtpClient class to generate mail message,
save it as .eml file and drop it into c:\emailTest\folder.
What is the difference between
UriBuilder.ToString and UriBuilder.Uri.ToString
-
UriBuilder.ToString - the resulting string always contains
Port, even if it is the default port for the
Scheme. For example - http://localhost:80/tips.
-
UriBuilder.Uri.ToString - the resulting string only contains the
port if it is not the default port for the scheme. For example -
http://localhost/tips.
Therefore, in most of the cases UriBuilder.Uri.ToString
should be used to omit redundant port specification.
Visual Studio Bookmarks
Bookmarks can be used to mark places in the code, like the code
that you might want to jump back and forward. Bookmarks can be related
to task list shortcuts, kind of the same functinality. The
bookmarks can be setup very easy, by pressing
Ctrl+K,
Ctrl+K to leave bookmark.
For navigation, you can press
Ctrl+K,
Ctrl+N to move to the
next bookmark,
or Ctrl+K,
CTRL+P for the previous
bookmark. It's easy, just try it now.
Generating compiler warnings for calls to an
obsolete methods
Throughout the product development cycle, occasionally certain
methods become obsolete. If you can't modify those methods, will need to
write another implementation of the method using a slightly different
name or signature. To maintain compatibility, you do not want to remove
the old method and break your code. This is where the .NET
Obsolete attribute comes in handy:
[Obsolete("Use the new LogRequestEx instead.")]
public
static void LogRequest(string feedUrl,
string referer)
{
Setting the Obsolete attribute as above makes a warning message
appear in the Visual Studio's Error List stating that the particular
call to a method is obsolete. The warning message also includes your
personalized message that you pass as the attribute's argument (such as,
"Use the new LogRequestEx instead").
Big solutions can be organized using Solution
Folders
Here is an example of a big Visual Studio.NET solution that
contains numerous projects: Such a big Visual Studio.NET
solutions can be organized by grouping related projects into
folders. Just right-click on the solution node and choose
Add | New Solution Folder to add a Solution Folder.
Then just Drag'n'Drop projects into this folder. This
also will allow you to do some operations on a group of projects. For
example, unload all projects in a Solution Folder, collapse or hide
entire Solution Folder so that you can work easily in Solution Explorer
in Visual Studio.NET.
How to change the default view for Web pages and
WinForms in Visual Studio
By default Visual Studio.NET initially displays Web pages and
WinForms in a Design view. But if you prefer Source view, you can set it
to be the default view. For Web pages:
1.Go to Tools | Options... | HTML Designer and
select Source View.
2.Click OK button. For WinForms:
1.Right-click on a WinForm in the Solution Explorer and then click
Open With.... Open With dialog opens.
2.Choose CSharp Editor in the list and then click
Set as Default button.
3.Click OK button.
Use DebuggerBrowsable attribute to clean up
class view in a debugger
The
DebuggerBrowsable attribute determines if and how a field or
property is displayed in the debugger variable windows. Let's review the
following code example:
public class VehicleSeries{
private
string _name;
public string Name
{
get { return_name; }
set { _name = value; }
}
private List<string> _vehicles = newList<string>();
public List<string> Vehicles
{
get { return _vehicles; }
set { _vehicles = value; }
} }
The resulting display within the debugger is shown below:
Now lets remove duplicate information and show constituent vehicles
by adding a few DebuggerBrowsable attributes:
public class VehicleSeries
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private
string _name;
public string Name
{
get { return_name; }
set { _name = value; }} [DebuggerBrowsable(DebuggerBrowsableState.Never)]
private List<string> _vehicles = newList<string>();
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public List<string> Vehicles { get {
return _vehicles; }
set { _vehicles = value; }
} }
What is the difference between URL and URI?
A URL is the address of some resource on the web, which means
that normally you type the address into a browser and you get something
back. There are other type of resources than web pages, but that's the
easiest conceptually. The browser goes out somewhere on the internet and
accesses something. A URI is just a unique string that
uniquely identifies something, commonly a namespace. Sometimes they look
like a URL that you could type into the address bar of your web browser,
but it doesn't have to point to any physical resource on the web.
URI is the more generic term, and a URL is a particular type of
URI in that a URL has to uniquely identify some resource on the web.
Don't generate unnecessary WinForm members for
Label controls
To get rid of some auto-generated form level fields that point
to a control that will never be referenced (for example, labels, panels,
etc.), do the following:
1.In the Windows Forms Designer, select a control.
2.Set
GenerateMember property for this control to false.
As a result a member of the form will not be generated for this control.
It saves you 4 bytes per member and more importantly removes "clutter"
from IntelliSense and any diagrams you auto generate.
Simplify the usability of your generic methods
with type parameter inference
When the parameter signature of a generic method includes a
parameter that is of the same type as the type parameter for the method,
it's not necessary to specify the type parameter when calling the
method. Let's review an example:
public class Class1
{
//both method type argument and parameter are of
the same type public
void SomeGenericMethod<T>(T sameAsTypeParameter)
{
} }
public
class Test
{
static
void Main()
{
Class1 obj = new Class1();
//It's not necessary to specify method type parameter
//Instead of obj.SomeGenericMethod<int>(100)
use
obj.SomeGenericMethod(100);
} }
As you can see in the example above, the syntax for calling
generic method is identical to syntax of calling non-generic method.
This ability is called generic type inference. To enable inference, the
parameter signature of a generic method must include a parameter that is
of the same type as the type parameter for the method.
Note: the compiler cannot infer the type based on the type of the
returned value alone.
Two approaches to update database row if
exists, insert if not
The biggest challenge with update/insert (so called
upsert) is to minimize
any kind of locks. Unfortunately there is no silver bullet for this
yet. So let's review two the most commonly used methods:
1. Update, if @@ROWCOUNT = 0 then insert
UPDATE Table1 SET
Column1 = @newValue WHERE Id = @id
IF @@ROWCOUNT = 0 BEGIN
INSERT INTO Table1 (Id, Column1) VALUES (@id, @newValue) END
This method is good if you know that in most of the cases a row
will exist and update will be performed. Otherwise the second method
should be used.
2. If row exists update, otherwise insert
IF EXISTS(SELECT * FROM
Table1 WHERE Id = @id)
BEGIN UPDATE Table1
SET Column1 = @newValue WHERE
Id = @id
END
ELSE
BEGIN
INSERT INTO Table1 (Id, Column1) VALUES (@id, @newValue)
END
This one is good if you know that in most of the cases a row
will not exist and insert will be performed. For such cases it executes
SELECT statement followed by INSERT statement. That results in less
expensive lock comparing to UPDATE + INSERT in previous method.
P.S. both methods should be used in transaction with
isolation level
Serializable.
Improve your code readability: make more sense to conditions
Instead of:
if (!string.IsNullOrEmpty(state) && state.Length == 2)
{
}
do this:
bool stateIsValid =!string.IsNullOrEmpty(state) && state.Length== 2;
if (stateIsValid)
{
}
Speed up inserting records into database with
SqlBulkCopy class
When you need to insert a great deal of rows into database (for
example, when importing data from a flat file or when importing data
from one database into another one), and you need to do it
programmatically because it needs to be pre-processed on the fly, then
you should use
SqlBulkCopy class. The class uses
Tabular Data
Stream for fast transmitting data from client to a database server
(therefore you'll see a bunch of "strange" INSERT BULK statements in a
SQL Profiler):
DataTable dataTable = new DataTable();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{bulkCopy.DestinationTableName = ;
bulkCopy.WriteToServer(dataTable);
}
Also try different values for
SqlBulkCopy.BatchSize to adjust performance for your case.
P.S. the tip applies only to MS SQL Server.
Create elegant code with Action delegate and
List.ForEach method
Let's review the following code which works with generic
collection:
List<Tip>tips = new
List<Tip>();
//represents a list of Tips //create SiteMapNode from each Tip
foreach (Tip tip in tips)
{
string url = string.Format("{0}/tips/{1}.aspx", appPath, tip.Id);
SiteMapNode node = new
SiteMapNode(this,url, url, tip.Title);
node["lastmod"]=tip.PubDate.ToString("u");
AddNode(node, rootNode);
}
Although this code works well we can improve it using
Action
delegate and
List.ForEach method. First we have to extract code to create
SiteMapNode into a method:
private void AddSiteMapNode(Tip tip){
string url = string.Format("{0}/tips/{1}.aspx", appPath, tip.Id);
SiteMapNode node = new SiteMapNode(this,url,url,tip.Title);
node["lastmod"]=tip.PubDate.ToString("u");
AddNode(node, rootNode);
}
Separating it into a separate method has a few advantages,
practically the ability to reuse the same logic for other uses. Now once
we have this method creating SiteMapNode's from Tips collection would
be: tips.ForEach(AddSiteMapNode);
P.S. this
tip also can be used with
Array.ForEach method.
Disable Submit button after it was clicked
While submitting the form data to a server to be handled by the
Click event of Submit button, it would be a good practice to disable the
button. Here is a small code sample to achieve this:
btnSubmit.OnClientClick = ClientScript.GetPostBackEventReference(btnSubmit, "") + ";
this.value='Submitting...';
this.disabled = true;";
Note: don't apply the tip to buttons which cause validation. Such
buttons require more advanced onclick handler which checks client-side
validation result.
Setting focus during a validation error
The validation controls now (starting with ASP.NET 2.0) allow
you to easily set focus on a control in error using the
SetFocusOnError property:
<asp:RequiredFieldValidator SetFocusOnError="true" ErrorMessage="msg" ControlToValidate="TextBox1" runat="server" />
Which is better: Control or WebControl?
The
System.Web.UI.Control class is the base class for all server
controls. This provides the properties, methods, and events shared by
all web controls. The
System.Web.UI.WebControls.WebControl class derives from the Control
class and adds style properties such as span, Forecolor, and Backcolor.
Microsoft recommends:
- if your custom control contains no user interface elements
then derive from Control Class.
- if your custom control provides a user interface, then
derive from WebControl class.
Handling errors at the method level
1.If potential errors are recoverable in
the routine
Use a combination of try…Catch blocks as a retry mechanism for error
handling.
2.If useful information can be added to the
exception
Create and throw a new exception with the added information.
3.If cleanup is required
Perform it in the finally block.
4.If potential errors are not recoverable in the
routine
Recovery should be handled by the calling routine and its error-handling
structure.
How to call a surrogate for Dispose() on
StringBuilder objects
A typical use for the StringBuilder type looks like below:
class Program
{
static string UseStringBuilder(string token)
{
StringBuilder sb = new class="GramE"> StringBuilder();
int i = 10;
while (i-- > 0)
{
sb.Append(token +'\n');
}
string result = sb.ToString();
return result;}
static voidMain(string[] args)
{
Console.WriteLine(UseStringBuilder("first"));
Console.WriteLine(UseStringBuilder("second"));
} }
The issue with this code is that when sb goes out of scope it
is mark for garbage collection, but the memory stored in it lingers
until the garbage collector invokes its finalizer. That could amount to
a lot of unused memory and hence might cost you some unnecessary garbage
collections by the CLR. Given this behavior it would only look natural
to call something like Dispose to take care of the underline memory
buffer used in the StringBuilder. Unfortunately there is no
Dispose method for this class, or any method to hint at freeing this
unused memory in a deterministic way. The trick to get rid of this
memory without invoking the finalizer is to set the Length to 0. The
efficient code will become:
span class="keyword">classProgram
{
static string UseStringBuilder(string token)
{
StringBuilder sb = new StringBuilder();
int i = 10;
while (i-- > 0)
{
sb.Append(token + '\n');}
string result = sb.ToString();
sb.Length = 0; // this is the Dispose equivalent
return result;
}
static
void Main(string[] args)
{
Console.WriteLine(UseStringBuilder("first"));
//no need to call System.GC.Collect()
for the unreferenced StringBuilder object Console.WriteLine(UseStringBuilder("second"));
} }
Update: use this trick with
caution. There's no guarantee that future implementations of the runtime
will act as described (tested only on .NET 2.0, 3.0 and 3.5). Only apply
if you are working with big strings and have problems with
memory/performance. Otherwise you will just complicate your code.
Thanks to Jeff Dean for pointing that out.
How to determine whether a property or a
method is more appropriate for your needs
Use a method when:
- The operation is a conversion, such as
Object.ToString.
- The operation is expensive enough that you want to
communicate to the user that they should consider caching the result.
- Obtaining a property value using the get
accessor would have an observable side effect.
- Calling the member twice in succession produces different
results.
- The order of execution is important. Note that a type's
properties should be able to be set and retrieved in any order.
- The member returns an array. Properties that return arrays
can be very misleading. Usually it is necessary to return a copy of
the internal array so that the user cannot change internal state.
This, coupled with the fact that a user can easily assume it is an
indexed property, leads to inefficient code.
Verbatim string literals
Verbatim string literal does not require the use of escape
characters to define special characters. Instead, any information in the
source code, including new lines, is included in the string. To define a
string literal an @ symbol is placed before the opening quotation mark.
Verbatim string literals are often used for specifying paths and
multi-line strings:
string path = @"C:\Program Files\My Program";
//verbatim literal string path2 = "C:\\Program
Files\\My Program";
//regular literalclass="keyword"
string msg = @"Hello, This is a multi-line
string";
//verbatim literal string msg2
= "Hello,\nThis is multi-line
string";
//regular literal P.S. the only character that requires a
different action is the quotation mark itself, which must be entered
twice to indicate a single character.
Speed up Visual Studio 2005
- Make sure Visual Studio 2005 SP1 is installed.
- Turn off animation.
Go to Tools | Options | Environment and uncheck
Animate environment tools.
- Disable Navigation Bar.
If you are using ReSharper, you don't need VS2005 to update the list
of methods and fields at the top of the file (CTRL-F12 does this
nicely). Go to Tools | Options | Text Editor | C# and
uncheck Navigation bar.
- Turn off Track Changes.
Go to Tools | Options | Text Editor and uncheck
Track changes. This will reduce overhead and speeds
up IDE response.
- Turn off Track Active item.
This will turn off jumping in the explorer whenever you select
different files in different projects. Go to Tools | Options |
Projects and Solutions and uncheck Track Active Item
in Solution Explorer. This will ensure that if you are moving
across files in different projects, left pane will still be steady
instead of jumping around.
- Turn off AutoToolboxPopulate.
There is an option in VS 2005 that will cause VS to automatically
populate the toolbox with any controls you compile as part of your
solution. This is a useful feature when developing controls since it
updates them when you build, but it can cause VS to end up taking a
long time in some circumstances. To disable this option, select the
Tools | Options | Windows Forms Designer and then set
AutoToolboxPopulate to False.
Optimize the launch of the Visual Studio
2005
1.Go to Tools | Options. 2.In
Environment | Startup section, change At startup
setting to Show empty environment.
1.Open the properties of Visual Studio 2005 shortcut. 2.Add
the parameter /nosplash
to the target.
- Close all unnecessary panels/tabs to prevent them from
appearing when the IDE loads.
Conditional breakpoints in Visual Studio
You can specify a breakpoint condition which will be
evaluated when a breakpoint is reached. The debugger will break only
if the condition is satisfied. To specify a condition:
1.In a source window, right-click a line containing a breakpoint
glyph and choose Condition from Breakpoints
in the shortcut menu
2.In the Breakpoint Condition dialog box,
define a boolean condition using the code in your local scope. For
example, you can only break when _culture != "en-US".
3.Choose Is true
if you want to break when the expression is satisfied or
Has changed if you want to break when the value
of the expression has changed.
4.Click OK.
Use Path.GetRandomFileName() or
Path.GetTempFileName() when working with temp files
Do not reinvent function for generating unique name for
temporary files. Use one of the existing methods:
Consider using
System.IO.Path.Combine() instead of string concatenation
Let's review the following code for creating a file path:
public string GetFullPath(string fileName) {
string folder = ConfigurationManager.AppSettings["MyFolder"];
return folder + fileName;
}
This code is prone to error. For example, when you set the
folder setting, you have to remember to make sure it ends with a
slash.
To avoid such problems use Path.Combine()
method which will ensure that the folder has ending slash:
public string GetFullPath(string filename) {
string folder = ConfigurationManager.AppSettings["MyFolder"];
return Path.Combine(folder, filename);
}
Always check Page.IsValid in your button's
EventHandler
Just because you are using ASP.NET validation controls, do
not assume the page could not be submitted with invalid data.
Also, just because you hide a control, do not assume
buttons/textboxes/etc on it are not submit-able. It is perfectly fine
to hide a control that a user should not access, but with very little
code (or using a third party tool) users can easily make an HttpPost
with any data they choose.
Use DebuggerStepThrough attribute to save
time when debugging
When debugging code, one of the annoying things is to step
into an one-line method or property. Assume that you have the
following property:
private string word;
publicstring Word { get { return word; }
set{ word = value; }
}
And you have a code that uses that property when calling a
method: DoSomething(obj.Word);
When you
debug that line, and hit F11 to step into the method, you'll step into
the get section of the property, and only then move on to the method.
By placing
System.Diagnostics.DebuggerStepThrough attribute above get and set
sections of the property you instruct the debugger to step through
that property and not into it:
public string Word
{
[System.Diagnostics.DebuggerStepThrough]
get { return word; }
[System.Diagnostics.DebuggerStepThrough]
set { word = value;}}
This instruction will cause the debugger not to step into
method (property) as normal, but you can always place a breakpoint in
that method and stop there.
Speed up string comparison
The
Compare method compares strings in a local-aware fashion, so it
has to convert the Unicode code of each character into a numeric value
that reflects its position in the current culture's alphabet. For
example, the Compare method considers the "b" lowercase character to
come immediately after the "A" uppercase char and before the "B"
uppercase char, even though the "A" and "B" characters are contiguous
in the Unicode character set. This conversion activity takes time and
consume CPU cycles, so you'll find that VB.NET is less efficient than
VB6 at comparing strings. Using the = operator and other comparison
operators doesn't help at all, because they map to the Compare method
behind the scenes, so these operators suffer from the same performance
loss. If you are only interested in checking whether two
strings contain the same characters (in a case-sensitive comparison),
you can speed up your code by using the
CompareOrdinal shared method. This method is 3-4 times faster than
the Compare method (or the = operator) because it just scans the two
strings and compare the Unicode numeric code of each character.
Quickly move to matching brace in Visual
Studio
Just press Ctrl+]
and VS.NET will take you to the matching brace. It also will take you
to the matching comment, region or quote depending on what is at the
cursor now.
Linking a file in Visual Studio.NET
If in VS.NET you add to the current project an existing file
that's located outside the current project's directory, the file is
first copied in the project's directory, and then it's added to the
project. However, you may want to share the same source file among
multiple projects.
As a trivially simple example, perhaps you get tired of specifying the
same AssemblyCompany and AssemblyCopyright strings, over and over
again, in all your projects? Wouldn't it be nice to have a little
two-line C# file tucked away somewhere, and include it by reference in
all your projects?
[assembly: System.Reflection.AssemblyCompany(".Faithorg")][assembly:
System.Reflection.AssemblyCopyright("© 2009 All rights reserved.")]
To add a shared file, open the dialog to select an existing
file with the Project | Add Existing Item… menu item and select the
file you want to include. Then, instead of clicking the Open button,
click the arrow on the left of that button, and click Link File from
the list that drops down. This way you link to the original file, not
to a local copy of it.
Don’t clear the stack trace when re-throwing
an exception
Often, we need to put some exception handling on catch blocks
(e.g., to rollback a transaction) and re-throw the exception. There
are two ways of doing it. The wrong way:
try{
}
catch (Exception ex)
{
throw
ex;}
Why is this wrong? Because, when you examine the stack trace,
the point of the exception will be the line of the
"throw
="font-size:
11pt"> ex;",
hiding the real error location.
Instead of "throw
="font-size:
11pt"> ex;", which will throw a new
exception and clear the stack trace,
simply use
"throw;":
try{ // Some code that
throws an exception}
catch
(Exception ex)
{
If you don’t specify the exception, the throw statement will simply
rethrow the very same exception the catch statement caught.
This will keep your stack trace intact, but still allows you to put
code in your catch blocks.
Exceptions cause performance to suffer
significantly
Do not rely on exceptions in your code and write code that
avoids exceptions. Since exceptions cause performance to suffer
significantly, you should never use them as a way to control normal
program flow. If it is possible to detect in code a condition that
would cause an exception, do so. Do not catch the exception itself
before you handle that condition. Do not use exceptions to control
logic. A database connection that fails to open is an exception but a
user who mistypes his password is simply a condition that needs to be
handled. Common scenarios include checking for null, assigning a value
to a String that will be parsed into a numeric value, or checking for
specific values before applying math operations.
try
{
value = 100/number;}
catch(Exception ex)
{
value = 0;
}
Quickly locate where the exceptions are
thrown
How many times has this happened to you? You're working on
code that's not quite functioning correctly. You suspect there's an
exception being thrown somewhere, but it's being caught and ignored.
Maybe this was intentional, or maybe it was poorly written code.
Either way, you need to locate the problem. To do this,
open the Exceptions dialog, either through the menu (Debug >
Exceptions) or the keyboard shortcut (Ctrl+D, E). Under the Thrown
column, check the box next to the Common Language Runtime Exceptions.
Now, when an exception is thrown, VS immediately breaks at the
offending line of code.
Visual Studio Full Screen Mode
You can quickly toggle into Full Screen mode by pressing
Shift+Alt+Enter.
Incremental search in Visual Studio
1.Press Ctrl+I.
2.Start typing the text you are searching for. Note: you'll see the
cursor jump to the first match, highlighting the current search
string. 3.Press Ctrl+I
again to jump to the next occurrence of the search string. 4.To stop
search, press Esc.
Advanced tip: Press Ctrl+Shift+I
to search backwards.
Auto-complete the word in Visual Studio 2005
Type the first few characters of a control/variable/type name
and hit Ctrl+Space
or Alt+RightArrow
to auto-complete the word. If there is more than one possibility
Intellisense suggestions will pop up a window with available options.
Always set the "applicationName" property
when configuring Membership and other Providers
Users created with the membership API will be associated with
applicationName value specified in provider declaration in
web.config file. This diagramm shows how user is associated with
applicationName in database: When no applicationName
attribute is configured, ASP.NET uses the application vroot path
within the web-server to automatically calculate the applicationName
to use when adding data to an ASP.NET Application Service database.
Now let's assume you develop an ASP.NET 2.0 application locally using
Membership, Roles or Profile features and you haven't specified
applicationName attribute. You create several new users. Because
applicationName property was not specified your users were associated
with auto calculated value (something like "/WebSite1").
This works fine when the application continues to run in the
"/WebSite1" application virtual path. But if it is copied to another
location or server with a different virtual path (for example: "/app1"
or more commonly just "/"), then when the Membership APIs are used
they will not "see" the users already in our database – since they
will lookup membership data using a different application name and
filter the users in the application_Users table accordingly. That is
why you'll get a "Login attempt unsuccessful, please try again."
message when you try to login.
The best way to prevent this from ever happening is to always
specify the "applicationName" attribute when declaring your providers.
One good default value to use is "/" – which is the root application
name. This is the value specified for the default provider that ships
with ASP.NET 2.0 (which by default stores the application service data
within the ASPNETDB.MDF file under /app_data), and is why if you don't
override the provider settings it will work if you copy an app to
another machine. P.S. The reason why the applicationName
setting even exists in the first place is so that you can map multiple
applications and sites to the same database.
Don't forget to <clear/> when adding
providers
You want to configure ASP.NET 2.0 to store your
Membership/Role Management/Profile data within a remote SQL database.
You decide to register a new provider within your web.config file like
below:
<membership> <providers> <add name="AspNetSqlMembershipProvider"
,type="System.Web.Security.SqlMembershipProvider,
System.Web, Version=2.0.0.0, =neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="MyDatabase"
enablePasswordRetrieval="false"
enablePasswordReset="true"
="true" requiresUniqueEmail="false"
passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7"
minRequiredNonalphanumericCharacters="1"
passwordAttemptWindow="10"
passwordStrengthRegularExpression=""
applicationName="/"/>
</providers> </membership>
When you run your application on a machine without SQL
Express, though, you see some weird behavior. You might get a SQL
error like so:
An error has occurred while establishing a connection
to the server. When connecting to SQL Server 2005, this failure may be
caused by the fact that under the default settings SQL Server does not
allow remote connections. (provider: SQL Network Interfaces, error: 26
- Error Locating Server/Instance Specified) The root
cause of the above problem rests in how the new provider was
registered within the web.config file.
The <providers> section within the web.config file is implemented as a
collection, and so it is possible to register multiple providers at
the same time (this is useful when you want to have some users
authenticated using one Membership store, and others authenticated
using a separate Membership store). By default ASP.NET
2.0 registers a set of default SQL Express providers within the root
web.config file on your machine that create a SQL Express database
within your /app_data directory to store/manage
membership/role/profile data when you first access it. Because this is
registered at the machine-wide level, all provider collections by
default inherit this registration. Unless you explictly <clear/> or
override the inherited value, your application will have this default
membership/role/profile provider registered. Because the
above web.config file simply added a new provider -- and didn't clear
or replace the default provider registration -- the above application
now has two Membership providers configured. When you do a
Membership.CreateUser() call in your code, ASP.NET will attempt to
create the user in both membership databases. If you don't have SQL
Express installed on your system, the create-user attempt will fail
for this database - which leads to the errors and/or weird behavior
above.
To fix this problem add an explicit <clear/> directive before your
<add/> statements within your web.config file:
<membership> <providers> <add name="AspNetSqlMembershipProvider" ,
type="System.Web.Security.SqlMembershipProvider,
System.Web, Version=2.0.0.0, =neutral, =b03f5f7f11d50a3a"
connectionStringName="MyDatabase"
enablePasswordRetrieval="false" enablePasswordReset="true"
requiresQuestionAndAnswer="true" requiresUniqueEmail="false"
passwordFormat="Hashed" maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1"
passwordAttemptWindow="10" passwordStrengthRegularExpression="" applicationName="/"/>
</providers> </membership>
Note that you must do this for each provider declaration that
you register. So if you are adding providers for <roles> and
<profile>, make sure you add the <clear/> directive in their providers
section as well.
How to perform DateTime calculations in a
right way
When coding, be careful if you need to perform DateTime
calculations (add/subtract) on values representing time zones that
practice daylight savings time. Unexpected calculation errors can
result. Instead, convert the local time value to universal time,
perform the calculation, and convert back to achieve maximum accuracy
. DateTime d; d
= DateTime.Parse class="GramE">("Oct
26, 2003 12:00:00 AM");
//date assignment d =
d.ToUniversalTime().AddHours(3.0).ToLocalTime();
//' - displays 10/26/2003 02:00:00 AM – Correct!
MessageBox.Show(d.ToString());
Working with DateTime structs seems to be simple, but it's not
How to maintain the position of the
scrollbar on postbacks
In ASP.NET 1.1 it was a pain to maintain the position of the
scrollbar when doing a postback operation. This was especially true
when you had a grid on the page and went to edit a specific row.
Instead of staying on the desired row, the page would reload and you'd
be placed back at the top and have to scroll down. In ASP.NET 2.0 you
can simply add the MaintainScrollPostionOnPostBack attribute to the
Page directive:
<%Page Language="C#" ...
MaintainScrollPositionOnPostback="true"
%>
strongly-typed access to previous page
during cross-page postback
ASP.NET 2.0 introduced the concept of cross-page postbacks
where one page could postback information to a page other than itself.
This is done by setting the PostBackUrl property of a button to the
name of the page that the button should postback data to. Normally,
the posted data can be accessed by doing something like
PreviousPage.FindControl().
However, this requires a cast if you need to access properties of the
target control in the previous page (which you normally need to do).
If you add a public property into the code-behind page that initiates
the postback operation, you can access the property in a
strongly-typed manner by adding the PreviousPageType directive into
the target page of the postback. For example, if you have
a page called Default.aspx that exposes a public property that returns
a Textbox that is defined in the page, the page that data is posted to
(lets call it SearchResults.aspx) can access that property in a
strongly-typed manner (no FindControl() call is necessary) by adding
the PreviousPageType directive into the top of the page:
<%@ PreviousPageType
VirtualPath="Default.aspx"
%>
By adding this directive, the code in SearchResults.aspx
can access the TextBox defined in Default.aspx in a strongly-typed
manner. The following example assumes the property defined in
Default.aspx is named
SearchTextBox. TextBox tb =
PreviousPage.SearchTextBox;
This code obviously only works if the previous page is Default.aspx.
PreviousPageType also has a TypeName property as well where you could
define a base type that one or more pages derive from to make this
technique work with multiple pages.
How to get virtual path of web application
Getting the virtual paths local to server is pretty straight
forward most of the time; just use Page.ResolveURL("~/whatever").
But what if you're in the BLL part of your app? Seeing as the
Page.ResolveURL is not a static method you would have to create a new
instance of Page before you can reference it... not good enough.
In BLL use
System.Web.HttpRuntime.AppDomainAppVirtualPath static property to
get local virtual path of web application:
string url =
HttpRuntime.AppDomainAppVirtualPath
+ "/whatever";
Note: if web application is in a server root folder
AppDomainAppVirtualPath returns just "/". If web application is in a
non-root folder it returns virtual path of the folder without "/" in
the end.
strongly-typed
access to Master Pages controls
If you have public properties defined in a Master Page that
you'd like to access in a strongly-typed manner you can add the
MasterType directive into a page as shown next:
<%MasterType
VirtualPath="MasterPage.master"
%>
You can then access properties in the target master page from a
content page by writing code like the following:
this.Master.HeaderText = "Label
updated using MasterType directive with VirtualPath attribute.";
Conditional compilation with
ConditionalAttribute
It is possible to conditionally compile code out of the final
product, this is usually useful when you want to have extra checks in
the code (asserts, invariant checking) during development and testing,
in debug mode, but do not want to incur the cost of this checking in
the final release product.
Just put all of the checking into a method and place Conditional
attribute on it.
public sealed classDebug { [Conditional("DEBUG")]
publicstatic void Assert(bool condition, string message) {
TraceInternal.Assert(condition,message);
} }
What this actually does is tell the compiler to only call the
method when the supplied preprocessor symbol is defined.
The method will still be compiled and will still exist in the
assembly. So, in a debug build a program that looks like this:
static void Main(string[] args) {
Debug.Assert(true,);}
//will still look like that, but when compiled in release mode, will look like this:
private static void Main(string[]args)
{
}
Note: the Debug classe of the .NET Framework use the
ConditionalAttribute. So you don't have to worry about any performance
hit whatsoever when you call various methods of this class as a
debugging aid. These calls just won't make it in the release build.
How to locate control nested inside of
another control
Finding controls within a Page's control hierarchy can be
painful but if you know how the controls are nested you can use the
lesser known "$" shortcut to find controls without having to write
recursive code. The following example shows how to use the
DefaultFocus property to set the focus on a textbox that is nested
inside of a FormView control. Notice that the "$" is used to delimit
the nesting:
<form id="form1" DefaultFocus="formVw$txtName"
runat="server"> <div>
<asp:FormView ID="formVw"
runat="server"><ItemTemplate>
Name:<asp:TextBox
ID="txtName"
runat="server"Text='<%#Eval("FirstName") + " " + Eval("LastName")%>' /></ItemTemplate>
</asp:FormView></div>
</form>
This little trick can also be used on the server-side when calling FindControl():
TextBox tb = this.FindControl("form1$formVw$txtName")
as TextBox;
if (tb != null)
{
/Access TextBox control
}
How to set the default focus to a control when the
page loads
This is another extremely simple thing that can be done without
resorting to writing JavaScript. If you only have a single textbox (or
two) on a page why should the user have to click in the textbox to
start typing? Shouldn't the cursor already be blinking in the textbox
so they can type away? Using the DefaultFocus property of the HtmlForm
control you can easily do this.
<form id="frm" DefaultFocus="txtUserName" runat="server"></form>
GridView Tips and Tricks
The web.config holding the connection will look similar to the
following:
<configuration> <appSettings/> <connectionStrings>
<add name="NorthwindConnectionString" connectionString="Data Source =
(local);IntegratedSecurity = SSPI; Initial Catalog=Northwind;"/>
</connectionStrings> </configuration>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>GridView Tips and Tricks </title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridViewID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CategoryID"
DataSourceID= "SqlDataSource1"
ShowFooter="true" AllowPaging="True" AllowSorting="True" PageSize="5"
OnRowDataBound="GridView1_RowDataBound">
<Columns> <asp:TemplateField
HeaderText="CategoryID" InsertVisible="False" SortExpression="CategoryID">
<ItemTemplate><asp:LabelID="lblCategoryID" runat="server" Text='<%# Bind("CategoryID")%>'>
</asp:Label></ItemTemplate> </asp:TemplateField>
<asp:TemplateField HeaderText="CategoryName"SortExpression="CategoryName">
<EditItemTemplate>
<asp:TextBox ID="txtCategoryName" runat="server" Text='<%#Bind("CategoryName") %>'> </asp:TextBox>
</EditItemTemplate> <ItemTemplate><asp:Label ID="lblCategoryName" runat="server" Text='<%#Bind("CategoryName")%>'>
</asp:Label></ItemTemplate> </asp:TemplateField> <asp:TemplateFieldHeaderText="Description"
SortExpression="Description">
<EditItemTemplate><asp:TextBoxID="txtDesc" runat="server" Text='<%# Bind("Description")%>'>
</asp:TextBox></EditItemTemplate> <ItemTemplate><asp:Label ID="lblDesc" runat="server"
Text='<%#Bind("Description") %>'></asp:Label>
</ItemTemplate> </asp:TemplateField> </Columns></asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=SUPROTIM;Initial
Catalog=Northwind;Integrated Security=True"
ProviderName="System.Data.SqlClient"
SelectCommand="SELECT
[CategoryID],[CategoryName], [Description] FROM [Categories]"
UpdateCommand="UPDATE
[Categories]SET [CategoryName] = @CategoryName, [Description] = @Description WHERE
[CategoryID]= @CategoryID"/>
Enable Disable Controls inside a GridView
There are at times when you have to disable controls on some rows,
when a certain condition is satisfied. In this snippet, we will see
how to disable editing for rows that have the CategoryName as
‘Confections’. Use the following code:
C#
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs
e) {
if (e.Row.RowType ==DataControlRowType.DataRow)
{ if (e.Row.DataItem!=
null)
{
Label lblControl=(Label)e.Row.Cells[2].FindControl("lblCategoryName");
if(lblControl.Text=="Confections")
{ e.Row.Cells[0].Enabled=
false; } } } }
VB.NET
Protected Sub
GridView1_RowDataBound(ByVal
sender As
Object,ByVale
As GridViewRowEventArgs)
If e.Row.RowType
= DataControlRowType.DataRow Then
If Not
e.Row.DataItem Is
Nothing Then Dim lblControl
As Label=
CType(e.Row.Cells(2).FindControl("lblCategoryName"),Label)
If lblControl.Text = "Confections"
Then e.Row.Cells(0).Enabled=
False
End If End If End
If
End Sub
Adding Arrows for Sorting Columns in a GridView
>When you are sorting the columns in a GridView, it would be a nice
to have feature, to display arrows which depict either an ascending or
descending sort as shown below. Create a folder called ‘images’ and
add two small images called up.gif and down.gif:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.Header)
{ foreach (TableCell cell
in e.Row.Cells) {
if (cell.HasControls())
{
LinkButton btnSort = (LinkButton)cell.Controls[0];
Image image = new
Image(); if(btnSort.Text == GridView1.SortExpression)
{
if (GridView1.SortDirection ==
SortDirection.Ascending)
{ image.ImageUrl
= "images/up.gif"; } else
{ image.ImageUrl = "images/down.gif";
} }
cell.Controls.Add(image); }
}
VB.NET
Protected Sub GridView1_RowDataBound(ByVal sender As Object,ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.Header Then
For Each cell As TableCell In e.Row.Cells
If cell.HasControls() Then
Dim btnSort As LinkButton=CType(cell.Controls(0),LinkButton)
Dim image As Image = New Image() If btnSort.Text
= GridView1.SortExpression Then
If GridView1.SortDirection= SortDirection.Ascending Then
image.ImageUrl="images/up.gif"
Else image.ImageUrl="images/down.gif"
End If
End
If cell.Controls.Add(image)
End If
Next cell
How to programmatically hide a column in the
GridView
There are two conditions to be checked in the Page_Load to hide a
columns in the GridView, let us say the 3rd column: If
‘AutoGenerateColumns’ = True on the GridView
C#
GridView1.HeaderRow.Cells[2].Visible= false;
foreach (GridViewRow
gvr in GridView1.Rows)
{
gvr.Cells[2].Visible = false;
}
VB.NET
GridView1.HeaderRow.Cells(2).Visible =
False
For Each
gvr As GridViewRow
In GridView1.Rows
gvr.Cells(2).Visible = False
Next
gvr
If ‘AutoGenerateColumns’ = False on the GridView
C#
GridView1.Columns[2].Visible=false;
VB.NET
GridView1.Columns(2).Visible=False
Handling Concurrency Issues in GridView
>If you are using the SqlDataSource (or ObjectDataSource), you can
use both the SqlDataSource.ConflictDetection and
OldValuesParameterFormatString property to handle concurrency issues.
These two properties together control how to perform updates and
delete operations when the underlying data source changes, while the
operation is being carried out. The original and modified versions of
each column can be tracked using the two properties. Displaying
Empty Data in a GridView When there are no results returned from
the GridView control’s data source, the short and simple way of
displaying a message to the user, is to use the GridView’s
EmptyDataText property.
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataKeyNames="CategoryID" DataSourceID="SqlDataSource1"
EmptyDataText="No data available"
ShowFooter="true"AllowPaging="True"
AllowSorting="True"
PageSize="5"OnRowDataBound="GridView1_RowDataBound">
Note: You can also add style to the EmptyDataText by
using the
EmptyDataRowStyle property.
Displaying an Image in case of Empty Data in a
GridView
As an alternative to using the EmptyDataText property, if you need
to display an image or any HTML/ASP.NET control, you can use the
EmptyDataTemplate. In this snippet below, we are using the image
control in the <EmptyDataTemplate> to display an image.
<asp:GridView ID="GridView1"
runat="server"
AutoGenerateColumns="False" DataKeyNames="CategoryID" DataSourceID="SqlDataSource1"
ShowFooter="true"
AllowPaging="True"
AllowSorting="True"
PageSize="5"
OnRowDataBound="GridView1_RowDataBound">
<EmptyDataTemplate> <asp:Image
id="imgNoData" ImageUrl="~/images/NoDataFound.jpg" AlternateText="No
data found"
runat="server"/> </EmptyDataTemplate>
How to Bind a List<> to a GridView
Let us see how to bind a List<> to a GridView. We assume that the
‘AutoGenerateColumns’ = True.
We will create a class called Employees and bind it to the GridView
with the help of a List<>. Create a class called ‘Employees’
C#
public class Employee{
private string enm;
private int ageofemp;
private string department;
public string EName
get { return
enm;}
set{enm = value;}
}
public int Age {
get{ return ageofemp; }
set{ ageofemp = value;
}
}
public string Dept {
get{
return department;
}
set
{
department = value;
}
}
public Employee(string ename,
int age,
string dept)
{
this.enm = ename;
this.ageofemp = age;
this.department = dept;
}
VB.NET
Public Class Employee
Private enm AsPrivate
ageofemp As IntegerPrivate department
As String
Public
Property EName()As
String
Get
Return enm
End
Get
Set(ByVal value
As String)
enm = value End
Set
End
Property
Public
Property Age() m As Integer
Get
Return ageofemp
End Get
Set(ByVal value
As Integer) ageofemp = value
End Set
End
Property
Public
Property Dept() As
String
Get
Return department
End
Get
Set(ByVal value
As String)
department = value
End Set
End
Property
Public
Sub New(ByVal
ename As ,
ByVal age As Integer, ByVal
dept As String)
Me.enm = ename
Me.ageofemp = age
Me.department = dept
End
Sub
End Class
Bind the ‘Employee’ data to the GridView using a List<>
C#
protected void Page_Load(object sender,EventArgs e)
{ System.Collections.Generic.List<Employee> emp = new System.Collections.Generic.List<Employee>();
emp.Add(new Employee("Harsha", 22, "Marketing"));
emp.Add(new Employee("Thomas", 28, "Advertising"));
emp.Add(new Employee("Pervez", 23, "Advertising"));
emp.Add(new Employee("Rouf", 44, "Production"));
emp.Add(new Employee("shabir", 28, "PPC"));
GridView1.DataSource = emp;
GridView1.DataBind();
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object,ByVal e As EventArgs)
Dim emp As List(OfEmployee)=New List(Of Employee)() emp.Add(New Employee("Harsha",22,"Marketing"))
emp.Add(New Employee("Thomas",28,"Advertising"))
emp.Add(New Employee("Pervez",23,"Advertising"))
emp.Add(New Employee("Rouf", 44,"Production"))
emp.Add(New Employee("shabir",28,"PPC"))
GridView1.DataSource = emp
GridView1.DataBind()
End Sub
Change the color of a GridView Row based on some condition
C#
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItem !=
null)
{
DataRowView drv = (DataRowView)e.Row.DataItem;
string catName = Convert.ToString(drv["CategoryName"]);
if (catName.Trim()
=="Confections")
e.Row.BackColor = System.Drawing.Color.LightBlue;
}
}
VB.NET
Protected Sub GridView1_RowCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If Not e.Row.DataItem Is Nothing Then
Dim drv As DataRowView CType(e.Row.DataItem,DataRowView)
Dim catName As String = Convert.ToString(drv("CategoryName"))
If catName.Trim()="Confections" Then
e.Row.BackColor = System.Drawing.Color.LightBlue
End If
End If
End Sub
How to create an Image Command Field Column and
add to the GridView at runtime
if (!Page.IsPostBack)
{
CommandField cmdField = new CommandField();
cmdField.ButtonType = ButtonType.Image;
cmdField.SelectImageUrl = "~/Images/Home_Np1.GIF";
cmdField.ShowSelectButton = true; cmdField.HeaderText = "Select";
GridView1.Columns.Add(cmdField);
GridView1.DataBind(); }
VB.NET
If (Not(Page.IsPostBack))Then
Dim cmdField As CommandField =
New CommandField()
cmdField.ButtonType = ButtonType.Image
cmdField.SelectImageUrl = "~/Images/Home_Np1.GIF" cmdField.ShowSelectButton =True
cmdField.HeaderText = "Select"
GridView1.Columns.Add(cmdField) GridView1.DataBind()
End If
How to display images in the GridView from Filesystem based on
an existing Column Let us imagine that you have a folder ‘Images’
where you have stored images for each category. Eg: 1.GIF, 2.GIF,
3.GIF and so on. Now you want to display a different image based on
each CategoryID. So for CategoryID = 1, the image is 1.GIF; for
CategoryID=2, the image is 2.GIF and so on.
<asp:TemplateField> <ItemTemplate>
<asp:Image
runat="server"
ImageUrl='<%#
"~/Images/"+ Eval("CategoryID")
+ ".GIF"%>'>
</asp:Image>
</ItemTemplate>
</asp:TemplateField>
How to Retrieve Images from the database and
display it in a GridView
I will assume that we have a image column called CatImg in the
Categories table. The first step would be to create an ImageHandler.
In such scenarios such as the gridview, usually prefer to go in for a
handler when I have to return binary data directly from the database.
It gives more control on the resource returned. Moreover it is a
preferred solution when you have to set the image programmatically. To
add a handler, right click project > Add New Item > Generic Handler >
ShowImage.ashx. The code shown below, uses the Request.QueryString["id"]
to retrieve the CategoryID from it. The ID is then passed to the
‘ShowCatImage()’ method where the image is fetched from the database
and returned in a MemoryStream object. We then read the stream into a
byte array. Using the OutputStream.Write(), we write the sequence of
bytes to the current stream and you get to see your image.
C#
<%@WebHandler Language="C#" Class="ShowImage"%>
using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;
public class ShowImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Int32 catid;
if (context.Request.QueryString["id"] != null)
catid = Convert.ToInt32(context.Request.QueryString["id"]);
else
throw new
ArgumentException("No parameter specified");
context.Response.ContentType = "image/jpeg";
Stream strm = ShowCatImage(catid);
byte[] buffer =new byte[4096];
int byteSeq = strm.Read(buffer,
0, 4096);
while (byteSeq >
0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
//context.Response.BinaryWrite(buffer);
}
public
Stream ShowCatImage(int
catid)
{
string conn = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
SqlConnection connection =
new SqlConnection(conn);
string sql = "SELECT catImg FROM Categories WHERE CategoryID = @ID";
SqlCommand cmd = new SqlCommand(sql,
connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID",
catid);
connection.Open();
object img = cmd.ExecuteScalar();
try
{
return
new MemoryStream((byte[])img);
}
catch
{
return
null;
}
finally
{
connection.Close();
}
}
public
bool IsReusable
{
get{
return
false;}
}
}
VB.NET
<%@ WebHandler Language="vb" Class="ShowImage"%>
Imports System
Imports System.Configuration
Imports System.Web
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Public Class ShowImage
Implements IHttpHandler
Public Sub ProcessRequest(ByVal context
As HttpContext)
Implements IHttpHandler.ProcessRequest
Dim catid As Int32
If Not
context.Request.QueryString("id")
Is Nothing Then
catid = Convert.ToInt32(context.Request.QueryString("id"))
Else
Throw
New ArgumentException("No parameter specified")
End If
context.Response.ContentType = "image/jpeg"
Dim strm
As Stream = ShowCatImage(catid)
Dim buffer As Byte()
= New
Byte(4095){}
Dim byteSeq As Integer = strm.Read(buffer, 0, 4096)
Do While
byteSeq > 0
context.Response.OutputStream.Write(buffer,0, byteSeq)
byteSeq = strm.Read(buffer, 0, 4096)
Loop
'context.Response.BinaryWrite(buffer);
End
Sub
Public
Function ShowCatImage(ByVal
catid As Integer)
As Stream
Dim conn
As String = ConfigurationManager.ConnectionStrings
("NorthwindConnectionString").ConnectionString
Dim connection As SqlConnection =
New SqlConnection(conn)
Dim sql
As String = "SELECT catImg FROM Categories WHERE CategoryID = @ID"
Dim cmd
As SqlCommand = New
SqlCommand(sql, connection)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("@ID", catid)
connection.Open()
Dim img
As Object = cmd.ExecuteScalar()
Try
Return
New MemoryStream(CType(img,Byte()))
Catch
Return
Nothing
Finally
connection.Close()
End
Try End
Function
Public
ReadOnly Property IsReusable()
As
Implements IHttpHandler.IsReusable
Get
Return
False End
Get End Property End Class
To access this image in the GridView based on the CategoryID, just
add the following:
<asp:TemplateField><ItemTemplate>
<asp:Image
runat="server"
ImageUrl='<%#"ShowImage.ashx?id="
+ Eval("CategoryID")%>'>
</asp:Image>
</ItemTemplate> </asp:TemplateField>
How to programmatically enable/disable a
control in the GridView when in the Edit Mode
If you want to quickly take a decision whether to enable or disable
a control when the user edits the row, then use the Enabled attribute
and set it to a method that returns a bool value:
<asp:TemplateFieldHeaderText="CategoryName"SortExpression="CategoryName">
<EditItemTemplate> <asp:TextBox
ID="txtCategoryName"
runat="server"
Enabled='<%#
EnableDisableTextBox()%>
' Text='<%#Bind("CategoryName")
%> '></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label
ID="lblCategoryName"
runat="server"
Text='<%#Bind("CategoryName")%>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
C#
protected bool EnableDisableTextBox()
{
if (1 == 1)
return
false;
}
VB.NET
Protected Function EnableDisableTextBox() As
Boolean
If 1 = 1 Then
Return False End If End Function
You can test this code by adding a CommandField to the GridView as
shown below
<asp:CommandField
ButtonType="Link"
ShowEditButton="true"
/>
How to loop through all the rows in all the
pages of a GridView
One simple way to loop through all the rows in all the pages of a
GridView is to access its DataSource. In this example, we will loop
through the SQLDataSource to retrieve all the rows in a GridView and
access its cell value. You can modify the logic depending on the type
of controls you have added to the GridView
C#
protected void Button1_Click(object sender, EventArgs e)
{
DataSourceSelectArguments dsaArgs = new DataSourceSelectArguments();
DataView view = (DataView)SqlDataSource1.Select(dsaArgs);
DataTable dt = view.ToTable();
for (int i = 0;i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
string s = dt.Rows[i][j].ToString();
}
}
}
}
VB.NET
Protected Sub Button1_Click(ByVal sender
As Object, ByVal ByVale As EventArgs)
Dim dsaArgs As DataSourceSelectArguments = New DataSourceSelectArguments()
Dim view As DataView = CType(SqlDataSource1.Select(dsaArgs), DataView)
Dim dt As DataTable = view.ToTable()
For i As Integer = 0 To dt.Rows.Count(-1)
For j As Integer = 0 To dt.Columns.Count(-1)
Dim s As String = dt.Rows(i)(j).ToString()
Next j
Next i
End Sub
Add or Remove Trailing Slash
Many web applications use "virtual URLs" - that is the URLs that do
not directly map to the file and directory layout on web server’s file
system. An example of such application may be an ASP.NET MVC
application with URL format similar to this:
http://stackoverflow.com/questions/60857/modrewrite-equivalent-for-iis-7-0
) or a PHP application with URL format that looks like this:
http://ruslany.net/2008/11/url-rewrite-module-release-to-web/)
If you try to request these URLs with or without trailing slash you
will still get the same page. That is OK for human visitors, but may
be a problem for search engine crawlers as well as for web analytics
services. Different URLs for the same page may cause crawlers to treat
the same page as different pages, thus affecting the page ranking.
They will also cause Web Analytics statistics for this page to be
split up. This problem is very easy to fix with a rewrite rule. Having
or not having a trailing slash in the URL is a matter of taste, but
once you’ve made a choice you can enforce the canonical URL format by
using one of these rewrite rules: To always remove trailing slash from
the URL:
name="Remove
trailing slash" ="true">
<match url="(.*)/$" />
<add input="{}" matchType="IsFile" negate="true" />
<add input="{}" matchType="IsDirectory" negate="true" />
<action type="Redirect" redirectType="Permanent" url="{R:1}" />
To always add trailing slash to the URL:
< name="Add trailing slash" stopProcessing="true">
<match url="(.*[^/])$" />
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
<action type="Redirect" redirectType="Permanent" url="{R:1}/" />
Enforce Lower Case URLs
A problem similar to the trailing slash problem may happen when
somebody links to your web page by using different casing,
<rule name="Convert to lower case" stopProcessing="true">
<match url="[A-Z]" ignoreCase="false" />
<action type="Redirect" url="{ToLower:{R:0}}" redirectType="Permanent" />
</rule>
Canonical Hostnames
Very often you may have one IIS web site that uses several
different host names. The most common example is when a site can be
accessed via http://www.yoursitename.com and via
http://yoursitename.com. Or, perhaps, you have
recently changed you domain name from oldsitename.com
to newsitename.com and you want your visitors to use
new domain name when bookmarking links to your site. A very simple
redirect rule will take care of that:
<rule name="Canonical Host Name" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTP_HOST}" negate="true" pattern="^ruslany\.net$" />
</conditions>
<action type="Redirect" url="http://ruslany.net/{R:1}" redirectType="Permanent" />
</rule>
Redirect to HTTPS
When a site that requires SSL is accessed via non-secure HTTP
connection, IIS responds with HTTP 403 (Unauthorized) status code.
This may be fine if you always expect that your site visitors will be
typing "https://…" in the browser’s address bar. But if you want your
site to be easily discoverable and more user friendly, you probably
would not want to return 403 response to visitors who came over
unsecure HTTP connection. Instead you would want to redirect them to
the secure equivalent of the URL they have requested. A typical
example is this URL:
http://www.paypal.com.
If you follow it you will see that browser gets redirected to
https://www.paypal.com.
With URL Rewrite Module you can perform this kind of redirection by
using the following rule:
<rule name="Redirect to HTTPS" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="^OFF$" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="SeeOther" />
</rule>
Note that for this rule to work within the same web site you will
need to disable "Require SSL" checkbox for the web site. If you do not
want to do that, then you can create two web sites in IIS – one with
http binding and another with https binding – and then add this rule
to the web.config file of the site with http binding.
Return HTTP 503 Status Code in Response
HTTP status code 503 means that the server is currently unable to
handle the request due to maintenance. This status code implies that
the outage is temporary, so when search engine crawler gets HTTP 503
response from your site, it will know not to index this response, but
instead to come back later. When you stop the IIS application pool for
your web site, IIS will return HTTP 503 for all requests to that site.
But what if you are doing maintenance to a certain location of the web
site and you do not want to shut down the entire site because of that?
With URL Rewrite Module you can return 503 response only when HTTP
requests are made to a specific URL path:
<rule name="Return 503" stopProcessing="true">
<match url="^products/sale/.*" />
<action type="CustomResponse" statusCode="503"
subStatusCode="0"
statusReason="Site is unavailable"
statusDescription="Site is down for maintenance" />
</rule>
Prevent Image Hotlinking
Image
Hotlinking is the use of an image from one site into a web
page belonging to a second site. Unauthorized image hotlinking from
your site increases bandwidth use, even though the site is not being
viewed as intended. There are other concerns with image hotlinking,
for example copyrights or usage of images in an inappropriate context.
With URL Rewrite Module, it is very easy to prevent image hotlinking.
For example the following rewrite rule prevents hotlinking to all
images on a web site
http://ruslany.net/:
<rule name="Prevent image hotlinking">
<match url=".*\.(gif|jpg|png)$"/>
<conditions>
<add input="{HTTP_REFERER}" pattern="^$" negate="true" />
<add input="{HTTP_REFERER}" pattern="^http://ruslany\.net/.*$" negate="true" />
</conditions>
<action type= />
</rule>
This rule will rewrite a request for any image file to
/images/say_no_to_hotlinking.jpg only if the HTTP Referer
header on the request is not empty and is not equal to the site’s
domain.
Reverse Proxy To Another Site/Server
By using URL Rewrite Module together with
Application
Request Routing module you can have IIS 7 act as a reverse
proxy. For example, you have an intranet web server and you want to
expose its content over internet. To enable that you will need to
perform the following configuration steps on the server that will act
as a proxy:
Step1: Check the "Enable proxy" checkbox
located in Application Request Routing feature view is IIS Manager.
Step2: Add the following rule to the web site that
will be used to proxy HTTP requests:
<rule name="Proxy">
<match url="(.*)" />
<action type="Rewrite" url= />
</rule>
Note the http:// prefix in the rewrite
rule action. That is what indicates that this request must be proxy’ed,
instead of being rewritten. When rule has "Rewrite" action with the
URL that contains the protocol prefix, then URL Rewrite Module will
not perform its standard URL rewriting logic. Instead it will pass the
request to Application Request Routing module, which will proxy that
request to the URL specified in the rule.
Preserve Protocol Prefix in Reverse Proxy
The rule in previous tip always uses non-secure connection to the
internal content server. Even if the request came to the proxy server
over HTTPS, the proxy server will pass that request to the content
server over HTTP. In many cases this may be exactly what you want to
do. But sometimes it may be necessary to preserve the secure
connection all the way to the content server. In other words, if
client connects to the server over HTTPS, then the proxy should use
"https://" prefix when making requests to content server. Similarly,
if client connected over HTTP, then proxy should use "http://"
connection to content server. This logic can be easily expressed by
this rewrite rule:
<rule name="Proxy">
<match url="(.*)" />
<conditions>
<add input="{CACHE_URL}" pattern="^(https?)://" />
</conditions>
<action type="Rewrite" url=/>
</rule>
Rewrite/Redirect Based on Query String Parameters
When rewriting/redirection decisions are being made by using values
extracted from the query string, very often one cannot rely on having
the query string parameters always listed in exact same order. So the
rewrite rule must be written in such a way so that it can extract the
query string parameters independently of their relative order in the
query string. The following rule shows an example of how two different
query string parameters are extracted from the query string and then
used in the rewritten URL:
<rule name="Query String Rewrite">
<match url="page\.asp$" />
<conditions>
<add input="{QUERY_STRING}" pattern="p1=(\d+)" />
<add input="##{C:1}##_{QUERY_STRING}" pattern="##([^#]+)##_.*p2=(\d+)" />
</conditions>
<action type="rewrite" url="newpage.aspx?param1={C:1}&amp;param2={C:2}" appendQueryString="false"/>
</rule>
With this rule, when request is made to page.asp?p2=321&p1=123, it
will be rewritten to newpage.aspx?param1=123¶m2=321. Parameters p1
and p2 can be in any order in the original query string.
Avoid Rewriting of Requests for ASP.NET Web
Resources
ASP.NET-based web applications very often make requests to
WebResources.axd file to retrieve assembly resources and serve them to
the Web browser. There is no such file exists on the server because
ASP.NET generates the content dynamically when WebResources.axd is
requested. So if you have a URL rewrite rule that does rewriting or
redirection only if requested URL corresponds to a file or a folder on
a web server’s file system, that rule may accidentally rewrite
requests made to WebResources.axd and thus break your application.
This problem can be easily prevented if you add one extra condition to
the rewrite rule:
<rule name="RewriteUserFriendlyURL1" stopProcessing="true">
<match url="^([^/]+)/?$" />
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
<!-- The following condition prevents rule from rewriting requests to .axd files -->
<add input="{URL}" negate="true" pattern="\.axd$" />
</conditions>
<action type="Rewrite" url="article.aspx?p={R:1}" />
</rule>
How To Clear All Textboxes in ASP.NET asp.net
private void Button1_Click(object sender, System.EventArgs e)
{
Control myForm = Page.FindControl("Form1″);
foreach (Control ctl in myForm.Controls)
{
if (ctl.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox"))
{
((TextBox)ctl).Text = "";
}
}
}
How To Prevent Caching of web form in ASP.NET
private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetAllowResponseInBrowserHistory(false);
}
}
How To Refresh aspx Page at Regular Interval
using HTML/Javascript >
meta content="10" http-equiv="refresh" />
Using .NET
Response.AppendHeader("Refresh", "10;URL=Nextpage.aspx");
Retrieve Details of the Row being Deleted in
GridView
The ID of the row being deleted must be in the
GridView.DataKeyNames collection.
C#
protected void GridView1_RowDeleting(object sender, e)
{
int ID = (int)GridView1.DataKeys[e.RowIndex].Value;
}
VB.NET
Protected Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As )
Dim ID As Integer = (GridView1.DataKeys(e.RowIndex).Value)
End Sub
Tip 7: Cancelling Update and Delete in a GridView
RowUpdating - Occurs when a row's Update button is clicked, but before the GridView control
updates the row.
RowDeleting – Occurs when a row's Delete button is clicked, but before the GridView control
deletes the row.
C#
protected void gvDetail_RowUpdating(object sender, e)
{
e.Cancel = true;
}
void GridView1_RowDeleting(Object sender, e)
{
if (GridView1.Rows.Count <= 1)
{
e.Cancel = true;
}
}
VB.NET
Protected Sub gvDetail_RowUpdating(ByVal sender As Object, ByVal e As )
e.Cancel = True
End Sub
Private Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As )
If GridView1.Rows.Count <= 1 Then
e.Cancel = True
End If End Sub
Paging and Sorting in GridView without using
DataSource control
C#
<asp:gridview ID="gridView" runat="server" OnPageIndexChanging="gridView_PageIndexChanging"
OnSorting="gridView_Sorting">
</asp:gridview>
private string ConvertSortDirectionToSql(SortDirection sortDireciton)
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;
case SortDirection.Descending:
newSortDirection = "DESC";
break;
}
return newSortDirection
}
protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridView.PageIndex = e.NewPageIndex;
gridView.DataBind();
}
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = gridView.DataSource as DataTable;
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
gridView.DataSource = dataView;
gridView.DataBind();
}
}
VB.NET
Private Function ConvertSortDirectionToSql(ByVal sortDireciton As SortDirection) As String
Dim newSortDirection As String = String.Empty
Select Case sortDirection
Case SortDirection.Ascending
newSortDirection = "ASC"
Case SortDirection.Descending
newSortDirection = "DESC"
End Select
Return newSortDirection
End Function
Protected Sub gridView_PageIndexChanging(ByVal
sender As Object, ByVal e As )
gridView.PageIndex = e.NewPageIndex
gridView.DataBind()
End Sub
Protected Sub gridView_Sorting(ByVal sender As Object, ByVal e As )
Dim dataTable As = (gridView.DataSource, DataTable)
If Not dataTable Is Nothing Then
Dim dataView As= New (dataTable)
dataView.Sort = e.SortExpression & " " & ConvertSortDirectionToSql(e.SortDirection)
gridView.DataSource = dataView
gridView.DataBind()
End If End Sub
Export GridView To Excel
C#
protected void Button1_Click(
object sender,
EventArgs e)
{.AddHeader(
"content-disposition",
"attachment;filename=FileName.xls");.Charset = String.Empty;.ContentType = "
application/vnd.xls";
System.IO. sw =
new System.IO.StringWriter();.Web.UI.HtmlTextWriter hw =
new
HtmlTextWriter(sw);
GridView1.RenderControl(hw);.Write(sw.ToString());.
End();}
VB.NET
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls")
Response.Charset = .Empty
Response.ContentType = "application/vnd.xls"
Dim sw As System.IO.StringWriter = New System.IO.StringWriter()
Dim hw As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(sw)
GridView1.RenderControl(hw)
Response.Write(sw.ToString())
Response.End()
End Sub
Request.Form - get values for fields having the same name
Problem
You know it’s possible to have controls with the same name on one
page. In this case Request.Form["txtSomeText"] returns the values form
all 5 textboxes comma separted. (For example: text1,text2,
text3.text4, text5). Example:
.....
<input type="text" name="txtSomeText" />
<input type="text" name="txtSomeText" />
<input type="text" name="txtSomeText" />
<input type="text" name="txtSomeText" />
<input type="text" name="txtSomeText" />
.......
The question iin this case is
"How to get the values for each
textbox?".
You can say "I’ll split the values…" but it’s not a good solution.
What if one of the values is "text,text,text"? I spent a lot of time
splitting strings and searching for workaround of "comma values"
(a,b,c) until I found the solution. Here it is..
Solution:
It’s simple:
Request.Form
returns NameValueCollection.
GetValues is a
NameValueCollection class method which gives us the
requested result.
Request.Form.GetValues("txtSomeText")
returns a string array with all the values.
Operator ===
Have you ever used the strict equal operator? I learned about it
few days ago…
Below is a quick explanation of its behavior: "The strict equal to
operator returns true if both operands are equal (and of the same
type). It doesn’t perform any data type conversion, so an expression
like 1 === true returns false and 1 === "1″ also returns false,
because this operator checks for the type of the operands. 1 is a
numerical value and "1″ is a string value; their types are different."
Hide div and the white space it occupies
Most of the developers will say "I can use javascript and CSS
‘visibility’ property to do that", but shortly after that they’ll
realize that this is not enough. This solution will hide the div tag
content, but the space it occupies will stay. You can reproduce this
behavior using the code below:
if (objDiv.style.visibility == 'visible' ||
objDiv.style.visibility == '')
{
objDiv.style.visibility = 'hidden';
}
else
{
objDiv.style.visibility = 'visible';
}
where objDiv is the div object which you’re trying to hide. Solution
It’s simple - initialize "display" property in addition. So the above code
will look like:
if (objDiv.style.visibility == 'visible' ||
objDiv.style.visibility == '')
{
objDiv.style.visibility = 'hidden';
objDiv.style.display = 'none';
}
else
{
objDiv.style.visibility = 'visible';
objDiv.style.display = 'block';
}
Cookie is lost when browser is closed Task
When user visits a site for the first time a disclaimer page must be
displayed. Once the user agree with it a cookie value is changed to "true" and
the next time the user opens the site the disclaimer is not displayed.
Problem
The cookie is lost when the browser is closed if you change cookie value.
Research
Below is some example code that I used to investigate the problem: Open Visual
Studio
Create new web site
Copy and paste the following code to the Page_Load method of defaut.aspx.cs
file:
if (Request.Cookies["test"] == null)
{
HttpCookie cookieDisclaimer = new HttpCookie("test", "cookie test");
cookieDisclaimer.Expires = DateTime.MaxValue; // the cookie never expires
Response.Cookies.Add(cookieDisclaimer);
Response.Write("cookie added");
}
else
{
// NOTE: We'll add some lines here later
Response.Write(Request.Cookies["test"].Value);
}
- Buld the website and open in a browser
- The first time the browser opens the cookie is created. Click F5 several
times and you’ll see cookie value displayed.
- Close the browser, open it again and navigate to the website URL. You’ll
see directly the the cookie value which means that the cookie exists.
Now let’s update the code, so cookie value is changed.
Add the following code below "NOTE: We’ll add some lines here later":
Response.Cookies["test"].Value = "cookie test";
Execute the steps described above and you’ll see that every time you open
a browser the cookie is created. So the cookie expires when the browser is
closed. According to me this is not the correct cookie behaviour. Correct
me if I’m wrong Solution
The solution is simple: everytime you change the cookie value, you
need to set cookie expiration date too. So adding the following
code after "NOTE: We’ll add some lines here later" fix the problem:
Response.Cookies["test"].Value = "cookie test";
Response.Cookies["test"].Expires = DateTime.MaxValue;
I hope the solution above is useful. How To Define Mozilla Specific CSS
Today I found a great approach for defining Mozilla specific styles
without using
Mozilla CSS extentions. The only thing needed is to put all Mozilla
specific CSS definitions in a "@-moz-document" block and specify the
url, url-prefix or domain to which pages the styles have to be applied:
@-moz-document url(http://www.w3.org/),
url-prefix(http://www.w3.org/Style/),
domain(mozilla.org)
{
body { ... }
}
Browser compatibility
Available since Mozilla 1.8 / Firefox 1.5.
DateDiff Function in C#
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication2
{
public enum DateInterval {
Year,
Month,
Weekday,
Day,
Hour,
Minute,
Second
}
class Program {
static void Main(string[] args)
{
DateTime dt1 = new DateTime(1994, 12, 12);
DateTime dt2 = new DateTime(1994, 12, 12);
long date = DateDiff(DateInterval.Day, dt1, dt2);
Console.Write(date);
Console.ReadLine();
}
public static long DateDiff(DateInterval interval, DateTime date1, DateTime date2)
{
TimeSpan ts = ts = date2 - date1;
switch (interval)
{
case DateInterval.Year:
return date2.Year - date1.Year;
case DateInterval.Month:
return (date2.Month - date1.Month) + (12 * (date2.Year - date1.Year));
case DateInterval.Weekday:
return Fix(ts.TotalDays) / 7;
case DateInterval.Day:
return Fix(ts.TotalDays);
case DateInterval.Hour:
return Fix(ts.TotalHours);
case DateInterval.Minute:
return Fix(ts.TotalMinutes);
default:
return Fix(ts.TotalSeconds);
}
}
private static long Fix(double Number)
{
if (Number >= 0)
{
return (long)Math.Floor(Number);
}
return (long)Math.Ceiling(Number);
}
}
}
change some text before it is sent to the client
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="InterceptHtml.aspx.cs"
Inherits="InterceptHtml" %>
<!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>change text</title>
</head>
<body>
<form id="form1″ runat="server">
<div>
Hello World!
<br />
Hi
</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;
using System.IO;
public partial class InterceptHtml : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Filter = new ReplaceHTML(Response.Filter);
}
protected override void Render(HtmlTextWriter writer)
{
output = new StringWriter();
base.Render(new HtmlTextWriter(output));
writer.Write(output.ToString().Replace("Hi", "Welcome
to faith\">www.myfaithsolution.com</a>"));
}
}
II nd Method
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 class ReplaceHTML : System.IO.Stream
{
private System.IO.Stream Base;
public ReplaceHTML(System.IO.Stream ResponseStream)
{
if (ResponseStream == null)
throw new ArgumentNullException("ResponseStream");
this.Base = ResponseStream;
}
public override
int Read(byte[] buffer, int offset,
int count)
{
return this.Base.Read(buffer, offset, count);
}
public override void SetLength(long value)
{
}
public override void Write(byte[] buffer, int offset, int count)
{
string HTML = System.Text.Encoding.UTF8.GetString(buffer, offset, count);
HTML = HTML.Replace("Hello World!", "I’ve
replaced the Hello World example!");
buffer = System.Text..UTF8.GetBytes(HTML);
this.Base.Write(buffer, 0, buffer.Length);
}
public override bool CanRead
{
get { throw
new ("The method or
operation is not
implemented."); }
}
public override bool CanSeek
{
get { throw
new ("The method or
operation is not
implemented."); }
}
public override bool CanWrite
{
get { throw
new ("The method or
operation is not
implemented."); }
}
public override void Flush()
{
HttpContext.Current.Response.Flush();
}
public override long Length
{
get { throw
new ("The method or
operation is not
implemented."); }
}
public override long Position
{
get
{
throw new ("The method or operation
is not implemented.");
}
set
{
throw new ("The method or operation
is not implemented.");
}
}
public override long Seek(long offset, System.IO.SeekOrigin origin)
{
throw new ("The method or operation not implimented");
}
}
How To Add Please Wait message to a Button
<%@Page Language="C#" AutoEventWireup="true"
CodeFile="PleaseWaitButton.aspx.cs"
Inherits="PleaseWaitButton"%>
"-//W3C//DTD XHTML 1.0
Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
"form1″runat"Button1″"server""Button"
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 PleaseWaitButton : System.Web.UI.Page {
protected void
Button1_Click(object sender, System.EventArgs e)
{
System.Threading.Thread.Sleep(5000);
ClientScript.RegisterClientScriptBlock(this.GetType(), "reset",
"document.getElementById(’" + Button1.ClientID + "‘).disabled=false;", true);
protected void Page_Load(object sender, System.EventArgs e){
System.Threading.Thread.Sleep(5000);
Button1.Attributes.Add("onclick", ClientScript.GetPostBackEventReference(Button1, "") + ";
this.value=’Please wait…’;this.disabled = true;");
}
}
CheckBox OnClick Hide/Show HTML Table
<%@ Page ="C#" "true" ="HideShow.aspx.cs" Inherits="HideShow"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
="http://www.w3.org/1999/xhtml">
runat="server">
function ShowHide(obj)
{
if(!obj.checked) {
document.getElementById(‘tbl_QuestionTags_Software’).style.display = ‘none’;
document.getElementById(‘tbl_QuestionTags_Software’).style.visibility="hidden";
}
else {
document.getElementById(‘tbl_QuestionTags_Software’).style.display = ";
document.getElementById(‘tbl_QuestionTags_Software’).style.visibility ="visible";
}
}
Untitled Page
id="form1″ runat="server">
< ID="chk_QuestionTags_Software" runat="server" CssClass="text" Text="Software"
="ShowHide(chk_QuestionTags_Software)" />
id="tbl_QuestionTags_Software" border="1″ bordercolor="red" cellpadding="0″
="0″ ="width: 100%">
<
</html>
How To Validate Checkboxlist control
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ValidateCheckBoxList.aspx.cs"
Inherits="ValidateCheckBoxList" %>
<!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:CheckBoxList ID="CheckBoxList1 runat="server">
<asp:ListItem Text="a" Value="b"></asp:ListItem>
<asp:ListItem Text="a" Value="b"></asp:ListItem>
</asp:CheckBoxList>
<asp:CustomValidator ID="CustomValidator1 runat="server" ErrorMessage="CustomValidator"
OnServerValidate="CustomValidator1_ServerValidate">
</asp:CustomValidator>
<asp:Button ID="Button1 runat="server" Text="Validate" /></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 ValidateCheckBoxList : System.Web.UI.
{
protected void Page_Load(sender, e)
{
}
protected void CustomValidator1_ServerValidate(object source, args)
{
int i;
i = 0;
foreach ( item in CheckBoxList1.Items)
{
if (item.Selected)
{
i = i + 1;
}
}
if (i > 1)
{
args.IsValid = false;
CustomValidator1.ErrorMessage = "more than one item is selected!";
}
else
{
args.IsValid = true;
} }
}
GridView Inside GridView
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataRelation.aspx.cs"
Inherits="DataRelation" %>
<%@ Import Namespace="System.Data" %>
<!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">
<Columns>
<asp:BoundField DataField="CompanyName"
HeaderText="CompanyName" />
<asp:TemplateField>
<ItemTemplate>
<asp:GridView ID="GridView2″
DataSource=’<%#((DataRowView)Container.DataItem).CreateChildView("ParentChild") %>’
runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Dept"
HeaderText="Department" />
<asp:BoundField DataField="name"
HeaderText="Name" />
</Columns>
</asp:GridView>
</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 DataRelation : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = CreateDS().Tables["Company"];
GridView1.DataBind();
}}
private DataSet CreateDS()
{
DataSet ds;
if (Session["DataList_ParentChild"] == null)
{
ds = new DataSet();
DataTable dt = new DataTable("Company");
DataRow dr;
dt.Columns.Add(new DataColumn("ID", typeof(Int32)));
dt.Columns.Add(new DataColumn("CompanyID", typeof(Int32)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));
dt.Columns.Add(new DataColumn("Dept", typeof(string)));
for (int i = 1; i < 10; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Company " + i;
dr[3] = "Manager name";
dr[4] = "Adminstration";
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
DataColumn[] Parent_PKColumns = new DataColumn[1];
Parent_PKColumns[0] = dt.Columns["ID"];
dt.PrimaryKey = Parent_PKColumns;
dt = new DataTable("Employees");
dt.Columns.Add(new DataColumn("ID", typeof(Int32)));
dt.Columns.Add(new DataColumn("CompanyID", typeof(Int32)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));
dt.Columns.Add(new DataColumn("Dept", typeof(string)));
for (int i = 1; i < 10; i++)
{
int imax = 0;
if (i % 2 == 0) imax = 5;
else imax = 4;
for (int y = 2; y < imax; y++) //3 emplyees for each company
{
dr = dt.NewRow();
dr[0] = y + i * 5;
dr[1] = i;
dr[2] = "Employee # " + dr[0];
dr[3] = "Dept # " + (y + i);
dt.Rows.Add(dr);
}
}
DataColumn[] Child_PKColumns = new DataColumn[1];
Child_PKColumns[0] = dt.Columns["ID"];
dt.PrimaryKey = Child_PKColumns;
ds.Tables.Add(dt);
DataColumn[] Child_FKColumns = new DataColumn[1];
Child_FKColumns[0] = dt.Columns["CompanyID"];
ds.Relations.Add("ParentChild", Parent_PKColumns, Child_FKColumns);
Session["DataList_ParentChild"] = ds;
}
else
{
ds = (DataSet)Session["DataList_ParentChild"];
}
return ds;
}
}
How To Disabling a button until processing is
Complete
Here’s the scenario - let’s say you have an Insert subroutine, called
‘doInsert’.
You want to immediately disable the Submit button, so that the
end-user won’t click it
multiple times, therefore, submitting the same data multiple times.
For this, use a regular HTML button, including a Runat="server" and an
‘OnServerClick’
event designation - like this:
<INPUT id="Button1″ onclick="document.form1.Button1.disabled=true;" type="button"
value="Submit - Insert Data" name="Button1″ runat="server" onserverclick="doInsert">
Then, in the very last line of the ‘doInsert’ subroutine, add this
line:
Button1.enabled="True"
How To Generate Random Image Using HttpHandler
in ASP.NET
How to construct an image generator used to create a visual
security code that helps prevent automated sign ups in your web
applications.The text generated is stored in Session to be used
for comparison to the user’s input.
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.Drawing.Imaging;
using System.Text;
using System.Web.SessionState;
public class Handler : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/gif";
Bitmap b = new Bitmap(200, 60);
Graphics g = Graphics.FromImage(b);
g.FillRectangle(new SolidBrush(Color.White), 0, 0, 200, 60);
span span = new span(spanFamily.GenericSansSerif, 48, spanStyle.Bold,
GraphicsUnit.Pixel);
Random r = new Random();
string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string letter;
StringBuilder sb = new StringBuilder();
for (int x = 0; x < 5; x++)
{
letter = letters.Substring(r.Next(0, letters.Length - 1), 1);
sb.Append(letter);
g.DrawString(letter, span, new SolidBrush(Color.Black), x * 38, r.Next(0, 15));
}
Pen linepen = new Pen(new SolidBrush(Color.Black), 2);
for (int x = 0; x < 6; x++)
g.DrawLine(linepen, new Point(r.Next(0, 199), r.Next(0, 59)),
new Point(r.Next(0, 199), r.Next(0, 59)));
b.Save(context.Response.OutputStream, ImageFormat.Gif);
context.Session["image"] = sb;
context.Response.End();
}
public bool IsReusable
{get{
return true;
}
}
br
br
br
br
br
br
}
How To Use
<img src="Handler.ashx" alt="Random Image" />
What is Diffrence between Src and Codebehind
You may have noticed that Visual Studio.NET adds an interesting keyword to the
Page directive of an ASP.NET web form: CodeBehind. However, you will not find
this documented in the .NET documentation for the Page directive. Visual
Studio.NET implements CodeBehind by precompiling the base class, then uses the
Inherits keyword to refer to that class. The CodeBehind keyword allows the IDE
to remember the file containing your base class. However, what if you do not
want to precompile your class into an assembly?
According to the .NET documentation, the Src attribute of the Page directive:
Specifies the source file name of the code-behind class to dynamically compile
when the page is requested.
Note: RAD designers, such as Visual Studio.NET, do not use this attribute.
Instead, they precompile code-behind classes and then use the Inherits
attribute.
So, by using the Src attribute to indicate the file, and the Inherits keyword
to indicate the class, you can accomplish Codebehind. Here is an example Web
Form Inheriting from the HelloWorld class in the HelloWorld.cs file:
<%@ Page Language="C#" Inherits="DotNetCoders.HelloWorld" Src="HelloWorld.cs" trace="true" %>
<html>
<body>
<asp:Label id="ProgrammersMessage" runat="server" />
</body>
</html>As you can see, the differences in the page directives are as follows:Visual Studio.NET
<%@ Page language="C#" Inherits="DotNetCoders.HelloWorld"
Codebehind="HelloWorld.aspx.cs" %>
Inherits keyword
How To Change The color of GridView Row Color by Using
Simple Mouse Click
In this article I will demonstrate that how you can change the color of the
GridView row by using simple mouse click and change it back to its original
color by clicking the row twice.
Take a look at the RowCreated event below to have a better idea:
protected void MyGridView_RowCreated(object sender, GridViewRowEventArgs e)
{
string rowID = String.Empty;
if (e.Row.RowType == DataControlRowType.DataRow)
{
rowID = "row"+e.Row.RowIndex;
e.Row.Attributes.Add("id","row"+e.Row.RowIndex);
e.Row.Attributes.Add("onclick","ChangeRowColor(" +"‘" + rowID + "‘" + ")");
}
}
JavaScript Function:
<script language ="javascript" type="text/javascript">
document.body.style.cursor = ‘pointer’;
var oldColor = ";
function ChangeRowColor(rowID)
{
var color = document.getElementById(rowID).style.backgroundColor;
if(color != ‘yellow’)
oldColor = color;
if(color == ‘yellow’)
document.getElementById(rowID).style.backgroundColor = oldColor;
else document.getElementById(rowID).style.backgroundColor = ‘yellow’;
}
</script>
The ChangeRowColor function takes in the id of the row and finds the color
of the row. Then it checks that if the color is ‘yellow’ which, is the
color of the highlight row. If it is not yellow then it simply assigns the
color to the public variable oldColor which is used to save the previous
color of the GridView row.
If the color is yellow then we get the previous color and assign to the
row so that it can come back to its original state.
Aug 16How To Prevents users to go back to the previous pages
Sometimes we are in a situation that we don’t want the user to visit the
previous pages. This can be a scenario when the user logs out but uses the
back button to navigate to the pages. In this article I will show you some
simple ways you can use to prevent user from going back.
Using History(+1) Method:
Let’s say that you have a page called Default.aspx which is the secure
page and when you click the button you are redirected to
another page Default2.aspx. Now from Default2.aspx. you don’t want to go
back to the Default.aspx.. You can achieve this easily using few lines of
code.
Let’s first catch the button click event and send the user to the
Default2.aspx page.
protected void Button1_Click(object sender, EventArgs e){
Response.Redirect("Default2.aspx");
}
Now if you press the button you will be redirected to the Default2.aspx
page. If you press the back button you will be taken to the Default.aspx
page.
Now we will implement the functionality that will prevent the user to go
to the Default2.aspx page.
In the Default.aspx html write the following code:
<body onLoad="if(history.length>0)history.go(+1)">
That’s it. It means every time you will go to the Default.aspx page you
will be forwarded to the Default2.aspx
Using DataView. RowFilter to remove nulls
I wanted to set a filter on my DataView so rows with a null value (in my
case the STATE column) would be filtered out. This is how I did it:
[csharp]dv.RowFilter = "IsNull(STATE,'null') <> 'null'";[/csharp]
How To Compare Version Information of Two Executable
Modules
You need to programmatically compare the version information of two
executable modules. An executable module is a file that contains
executable code such as an .exe or .dll file. The ability to compare
the version information of two executable modules can be very useful
to an application in situations such as:
Trying to determine if it has all of the "right" pieces present to
execute
Deciding on an assembly to dynamically load through reflection
Looking for the newest version of a file or .dll from many files
spread out in the local filesystem or on a network
Use the CompareFileVersions method to compare executable module
version information. This method accepts two filenames, including
their paths, as parameters. The version information of each module is
retrieved and compared. This file returns a FileComparison
enumeration, defined as follows:
public enum FileComparison
{
Same = 0,
Newer = 1, // File1 is newer than File2
Older = 2, // File1 is older than File2
Error = 3
}
The code for the CompareFileVersions method is shown below
with proper commenting.
public static FileComparison CompareFileVersions(string file1, string file2)
{
FileComparison retValue = FileComparison.Error;
// Do both files exist? if (!File.Exists(file1))
{
Console.WriteLine(file1 + " does not exist");
}
else if (!File.Exists(file2))
{
Console.WriteLine(file2 + " does not exist");
}
else
{
// Get the version information. FileVersionInfo file1Version = FileVersionInfo.GetVersionInfo(file1);
FileVersionInfo file2Version = FileVersionInfo.GetVersionInfo(file2);
// Check major.
if (file1Version.FileMajorPart > file2Version.FileMajorPart)
{
Console.WriteLine(file1 + " is a newer version");
retValue = FileComparison.Newer;
}
else if (file1Version.FileMajorPart <>
{
Console.WriteLine(file2 + " is a newer version");
retValue = FileComparison.Older;
}
else // Major version is equal,
check next… {
// Check minor.
if (file1Version.FileMinorPart > file2Version.FileMinorPart)
{
Console.WriteLine(file1 + " is a newer version");
retValue = FileComparison.Newer;
}
else if (file1Version.FileMinorPart <>
{
Console.WriteLine(file2 + " is a newer version");
retValue = FileComparison.Older;
}
else // Minor version is equal, check next…
{
// Check build.
if (file1Version.FileBuildPart > file2Version.FileBuildPart)
{
Console.WriteLine(file1 + " is a newer version");
retValue = FileComparison.Newer;
}
else if (file1Version.FileBuildPart <>
{
Console.WriteLine(file2 + " is a newer version");
retValue = FileComparison.Older;
}
else // Build version is equal, check next…
{
// Check private.
if (file1Version.FilePrivatePart >
file2Version.FilePrivatePart)
{
Console.WriteLine(file1 + " is a newer version");
retValue = FileComparison.Newer;
}
else if (file1Version.FilePrivatePart <
file2Version.FilePrivatePart)
{
Console.WriteLine(file2 + " is a newer version");
retValue = FileComparison.Older;
}
else
{
// Identical versions Console.WriteLine("The files have the same version");
retValue = FileComparison.Same;
}}}
}
}
return retValue;
}
Not all executable modules have version information. If you load a
module with no version information using the FileVersionInfo class,
you will not provoke an exception, nor will you get null back for
the object reference. Instead, you will get a valid FileVersionInfo
object with all data members in their initial state (which is null
for .NET objects).
Assemblies actually have two sets of version information: the
version information available in the assembly manifest and the PE
(Portable Executable) file version information. FileVersionInfo
reads the assembly manifest version information.
The first action this method takes is to determine whether the two
files passed in to the file1 and file2 parameters actually exist. If
so, the static GetVersionInfo method of the FileVersionInfo class is
called to get version information for the two files.
The CompareFileVersions method attempts to compare each portion of
the file’s version number using the following properties of the
FileVersionInfo object returned by GetVersionInfo:
FileMajorPart
The first 2 bytes of the version number
FileMinorPart
The second 2 bytes of the version number
FileBuildPart
The third 2 bytes of the version number
FilePrivatePart
The final 2 bytes of the version number
The full version number is comprised of these four parts, making up
an 8-byte number representing the file’s version number.
The CompareFileVersions method first compares the FileMajorPart
version information of the two files. If these are equal, the
FileMinorPart version information of the two files is compared. This
continues through the FileBuildPart and finally the FilePrivatePart
version information values? If all four parts are equal, the files
are considered to have the same version number. If either file is
found to have a higher number than the other file, it is considered
to be the latest version.
How To Get Information for All Drives on a
System
Your application needs to know if a drive (HDD, CD drive, DVD
drive, etc.) is available and ready to be written to and/or read
from. Additionally, it would be nice to know if you have enough
available free space on the drive to write information to.
Use the various properties in the DriveInfo class as shown here:
public static void DisplayAllDriveInfo()
{
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
if (drive.IsReady)
{
Console.WriteLine("Drive " + drive.Name + " is ready.");
Console.WriteLine("AvailableFreeSpace: " + drive.AvailableFreeSpace);
Console.WriteLine("DriveFormat: " + drive.DriveFormat);
Console.WriteLine("DriveType: " + drive.DriveType);
Console.WriteLine("Name: " + drive.Name);
Console.WriteLine("RootDirectory.FullName: " +drive.RootDirectory.FullName);
Console.WriteLine("TotalFreeSpace: " + drive.TotalFreeSpace);
Console.WriteLine("TotalSize: " + drive.TotalSize);
Console.WriteLine("VolumeLabel: " + drive.VolumeLabel);
}
else
{
Console.WriteLine("Drive " + drive.Name + " is not ready.");
}}}
Of particular interest are the IsReady and AvailableFreeSpace
properties.The IsReady property determines if the drive is ready
to be queried, written to, or read from.The AvailableFreeSpace
property returns the free space on that drive in bytes.
How To Convert an IP Address To Hostname
You have an IP address that you need to resolve into a
hostname.se the Dns.GetHostEntry method to get the hostname
for an IP address. In the following code, an IP address is
resolved, and the hostname is accessible from the HostName
property of the IPHostEntry:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
// Use the Dns class to resolve the address.
IPHostEntry iphost = Dns.GetHostEntry("127.0.0.1";
// HostName property holds the hostname. string hostName = iphost.HostName;// Print out name.
Console.WriteLine(hostName);
This article has been posted at new york dating site
architect providing free online dating service.
Surprises never cease so as the growth of our online dating
site, which has been on rampage.
Aug 12How To Convert a Hostname to an IP Address
You have a string representation of a host (such as
www.google.com ), and you need to obtain the IP address from
this hostname.
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;
namespace ConsoleApplication1
{
class Program{
static void Main(string[] args){
Console.WriteLine(HostName2IP("www.google.com"));
Cbr
}Console.Read();
}Cbr
}Console.Read();
}Cbr
}Console.Read();
}Cbr
}Console.Read();
}Cbr
}Console.Read();
}Cbr
}Console.Read();
}Cbr
}Console.Read();
}Cbr
}Console.Read();
}Cbr
}Console.Read();
}Cbr
}Console.Read();
}Cbr
}Console.Read();
}Cbr
}Console.Read();
}Cbr
}Console.Read();
}Cbr
}Console.Read();
}Cbr
}Console.Read();
}Cbr
}Console.Read();
}
public static string HostName2IP(string hostname){
// Resolve the hostname into an iphost entry using the
Dns class.
IPHostEntry iphost = System.Net.Dns.GetHostEntry(hostname);
// Get all of the possible IP addresses for this hostname.
IPAddress[] addresses = iphost.AddressList;
bbr style="color: #009900"br style="color: #009900"bbr style="color: #009900"br style="color: #009900"bbr style="color: #009900"br style="color: #009900"bbr style="color: #009900"br style="color: #009900"bbr style="color: #009900"br style="color: #009900"bbr style="color: #009900"br style="color:
#009900"bbr style="color: #009900"br style="color: #009900"bbr style="color: #009900"br style="color: #009900"
// Make a text representation of the list. StringBuilder addressList = new StringBuilder();
// Get each IP address. foreach (IPAddress address in addresses)
{// Append it to the list. addressList.AppendFormat("IP Address: {0};", address.ToString());
}
return addressList.ToString();
}}}
How to locate control nested inside of another control
Finding controls within a Page’s control hierarchy can be hard to find but
if you know how the controls are nested you can use the lesser known "$"
shortcut to find controls without having to write recursive code. The
following example shows how to use the DefaultFocus property to set the
focus on a textbox that is nested inside of a FormView control. Notice that
the "$" is used to delimit the nesting:
<form id="Form2" runat="server" defaultfocus="formVw$txtName">
<div>
<asp:formview ID="formVw" runat="server">
<itemtemplate>
Name: Text='<%# Eval("FirstName") + " " + Eval("LastName") %>' />
</itemtemplate>
</asp:formview>
</div>
</form>
This little trick can also be used on the server-side when
calling FindControl(): TextBox tb = this.FindControl("form1$formVw$txtName") as TextBox; if (tb != null)
{ //Access TextBox control }
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 PleaseWaitButton : System.Web.UI.Page
{
protected void Button1_Click(object sender, System.EventArgs e)
{
System.Threading.Thread.Sleep(5000);
ClientScript.RegisterClientScriptBlock(this.GetType(), "reset", "document.getElementById(’"
+ Button1.ClientID + "‘).disabled=false;", true);
}
protected void Page_Load(object sender, System.EventArgs e)
{
System.Threading.Thread.Sleep(5000);
Button1.Attributes.Add("onclick", ClientScript.GetPostBackEventReference(Button1, "") + ";
this.value=’Please wait…’;this.disabled = true;");
}
}
Adding Google Search To Your Program using ASP.NET
asp.net
Setting up 1. Download the Google API from http://www.google.com/apis/ and
then follow the instructions to acquire a search key.
2. Get the >NET SDK if you don’t have it already and don’t have VS.NET
3. You can use the packaged Google api web service proxy or generate your
own proxy class using the wsdl.exe util that comes packaged with ASP.NET
SDK.
4. Compile the proxy class using a command something like vbc /t:library
/out:Google.dll Google.vb /r:System.web.dll /r:System.web.Services.dll
/r:System.data.dll /r:system.dll /r:System.xml.dll
Note that for this we renamed the generated proxy class file to
Google.vb mostly for clarity.
5. Next copy the generated Google.dll into the bin folder of your web
app.
6. Add an entry in Web.config to hold the google key you received — in
ours we put it in the appsettings section of web.config and called the key
googlekey. Alternatively, you can hard-code the key in the search page.
7. Write the search page - a sample of our code is shown in the next
section
public void GoogleSearch()
{
com.google.api.GoogleSearchService objSearch = new com.google.api.GoogleSearchService();
br
br
br
br
br
br
// Invoke the search method com.google.api.GoogleSearchResult objResults =
objSearch.doGoogleSearch("license-key-goes-here", "India", 0, 10, false, "", false, "", "", ""
);
// Loop through result elements short shtCount;
for (shtCount = 0; shtCount <= objResults.endIndex - 1; shtCount++){
MessageBox.Show(objResults.resultElements(shtCount).title +
" - " + objResults.resultElements(shtCount).URL); } }
Getting and Setting the Application Version Number
In the AssemblyInfo.cs file for each project, you have the opportunity to set
the version number of the Assembly.
A version number is designed by four number: major.minor.build.revision. The
default is 1.0.* If left to this, third number (build) will be set to the
number of days since January 1, 2000 local time. The fourth number (revision)
will be set to the number of seconds since midnight local time. This is useful
since it will always increment every time you build the assembly, unless you
are working at 2 a.m. on the last Sunday in October in most places in the
United States. However, in a production environment, you may want to control
those numbers manually.
In which case, you could set the version to something like 1.3.25.31.
Note that .NET considers changes to the major or minor
version to be significant changes, but changes to the build and revision are
not.
So if you have a reference to an Assembly in the Global Assembly Cache and the
major or minor version changes, the new version is considered incompatible
with the old version and the previous version will still be linked to. To
retrieve the version number from the assembly in your code, you use can do
this:
String strVersion =
System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
To retrieve the version number from the assembly that is calling your
assembly, you can use this:
String strVersion =
System.Reflection.Assembly.GetCallingAssembly().GetName().Version();
Seeing What is in the ViewState in ASP.NET Web Forms asp.net
Have you ever wondered what is actually encoded in the __VIEWSTATE hidden
variable on your Web Forms? It’s actually a base64 serialized encoding of a
datatype called a Triplet,
that has other objects nested within it. I threw together a small class that
has a single static method that will write the viewstate to a file. It indents
to see the hierarchy. It also deserializes the viewstate into a Triplet object
that you can view in the debugger.
This code is only for debugging, and should not be left in the shipping
application.
Call the method in the Page_Load event of your Web Form, like this:
DebugViewState.SeeViewState(Request.Form["__VIEWSTATE"],
@"c:\temp\viewstate.txt");
and include this class in the project:
using System;
using System.Diagnostics;
using System.Web.UI;
public class DebugViewState
{
public static void SeeViewState(string strViewState, string strFilename)
{
if (strViewState != null)
{
Debug.Listeners.Clear();
System.IO.File.Delete(strFilename);
Debug.Listeners.Add(new TextWriterTraceListener(strFilename));
string strViewStateDecoded =
(new System.Text.UTF8Encoding()).
GetString(Convert.FromBase64String(strViewState));
string[] astrDecoded = strViewStateDecoded.Replace("<", "<\n").
Replace(">", "\n>").Replace(";", ";\n").Split(’\n’);
Debug.IndentSize = 4;
foreach (string str in astrDecoded)
if (str.Length > 0)
if (str.EndsWith(@"\<"))
Debug.Write(str);
else if (str.EndsWith(@"\"))
Debug.Write(str);
else if (str.EndsWith("<"))
{ Debug.WriteLine(str);
Debug.Indent(); }
else if (str.StartsWith(">;") || str.StartsWith(">"))
{
Debug.Unindent();
Debug.WriteLine(str);
}
else if (str.EndsWith(@"\;"))
Debug.Write(str);
else Debug.WriteLine(str);
Debug.Close();
Debug.Listeners.Clear();
//Get into the debugger after executing this line to see
how .NET looks //at //the ViewState info. Compare it to the text file produced above.
Triplet trp = (Triplet) ((new LosFormatter()).Deserialize(strViewState));
} } }
Send the Right error codes in Asp.net asp.net
If you have a broken internal link on your ASP.NET website and follow it,
you will see the well known yellow screen of death (YSOD). Not only is it
ugly, but it could also tell the visitor more than they should know about
your system. The broken link sends a 404 HTTP status code to the client, but
instead of providing the visitor with the YSOD, it will be better to use the
browsers build-in view for those kinds of errors.
It’s a view visitors know and not an arbitrary YSOD with strange
information. Of course, this is only true if you have no custom error HTML
page. Keep in mind that custom error aspx pages are not good enough, because
if a global ASP.NET exception occurs, then they won’t work either. You can
bypass the default YSOD by adding this method to the global.asax.
private void Application_Error(object sender, EventArgs e)
{
HttpException ex = Server.GetLastError() as HttpException;
if (ex !=null)
{
Response.StatusCode = ex.GetHttpCode();
}
else
{
Response.StatusCode = 500;
}
Response.End();
}
Do Postback With Parameters in javascript asp.net
Whenever you use a Button or LinkButton it is because you want to be able
to do a postback when it is clicked. The same could be the case for
CheckBox or DropDownList etc. but then you need to set the AutoPostback
property to true. It all works very much the same way from a user’s point
of view - click or select and the page performs a postback. However, in
some cases you want to be able to do a postback from a custom JavaScript
function that emulates the click of an e.g. LinkButton. That is very
simple to do so, but did you know that you also can send custom
information via such a postback? Example The following LinkButton calls
the server-side event handler OnSaveClick.
<asp:LinkButton runat="Server" ID="btnSave" Text="Save" OnClick="OnSaveClick" />
This is pretty much standard and no tricks have been used so far. Now we
need the JavaScript method that forces the LinkButton to do a postback
that calls the server-side method OnSaveClick.
<script type="text/javascript">
function SaveWithParameter(parameter)
{__doPostBack(’btnSave ‘, parameter)}
/script>
Notice that the function takes a parameter that it sends to the
__doPostBack function. All we need to do now is to call the
SaveWithParamter function from JavaScript. > SaveWithParameter("Hello
world!"); Now the page performs a postback and we can now access the
"Hello world!" string that we sent as a parameter from within the
OnSaveClick event handler.
protected void OnSaveClick(object sender, EventArgs e)
{
string parameter = Request[
"__EVENTARGUMENT"];
}
What we just did was to perform a postback from a custom JavaScript
function and send a parameter to the server-side event handler. It
sounds a lot harder than it is, right? > In ASP.NET 2.0 you have to set
the EnableEventValidation="false" attribute in the page declaration or
in web.config to make it work.
How To Generate Unique numbers and String in C#
The System.Guid is used whenever we need to generate a unique key, but
it is very long. That’s in many cases not an issue, but in a web
scenario where it is part of the URL we need to use its string
representation which is 36 characters long. It clutters up the URL and
is just basically ugly. It is not possible to shorten it without
loosing some of the uniqueness of the GUID, but we can come a long way
if we can accept a 16 character string instead.
We can change the standard GUID string representation:
21726045-e8f7-4b09-abd8-4bcc926e9e28 Into a shorter string:
3c4ebc5f5f2c4edc The following method creates the shorter string and
it is actually very unique. An iteration of 10 million didn’t create a
duplicate. It uses the uniqueness of a GUID to create the string.
private string GenerateId()
{
long i = 1;
foreach (byte b in Guid.NewGuid().ToByteArray())
{
i *= ((int)b + 1);
}
return string.Format("{0:x}", i - DateTime.Now.Ticks);
}
If you instead want numbers instead of a string, you can do that to
but then you need to go up to 19 characters. The following method
converts a GUID to an Int64.
private long GenerateId()
{
byte[] buffer = Guid.NewGuid().ToByteArray();
return BitConverter.ToInt64(buffer, 0);
}
The standard GUID is still the best way to ensure the uniqueness
even though it isn’t 100% unique.
How To Compress and Decompress Strings in C#
asp.net
You need a way to compress the data you write to a file using one
of the stream-based classes. In addition, you need a way to
decompress the data from this compressed file when you read it
back in. Use the System.IO.Compression.DeflateStream or the
System.IO.Compression. GZipStream classes to read and write
compressed data to a file. The Compress and DeCompress methods
shown below demonstrate how to use these classes to compress and
expand data on the fly.
using System.IO.Compression;
using System.Text;
using System.IO;
public static string Compress(string text)
{
byte[] buffer = Encoding.UTF8.GetBytes(text);
MemoryStream ms =new MemoryStream();
using (GZipStream zip =new GZipStream(ms, CompressionMode.Compress, true))
{
zip.Write(buffer, 0, buffer.Length);
}
ms.Position = 0;
MemoryStream outStream =new MemoryStream();
byte[] compressed =new byte[ms.Length];
ms.Read(compressed, 0, compressed.Length);
byte[] gzBuffer =new byte[compressed.Length + 4];
System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
return Convert.ToBase64String (gzBuffer);
}
public static string Decompress(string compressedText)
{
byte[] gzBuffer = Convert.FromBase64String(compressedText);
using (MemoryStream ms =new MemoryStream())
{
int msgLength = BitConverter.ToInt32(gzBuffer, 0);
ms.Write(gzBuffer, 4, gzBuffer.Length - 4);
byte[] buffer =new byte[msgLength];
ms.Position = 0;
using (GZipStream zip =new GZipStream(ms, CompressionMode.Decompress))
{
zip.Read(buffer, 0, buffer.Length);
}
return Encoding.UTF8.GetString(buffer);
}
}
The strings need to be longer than 3-400 characters; otherwise
the compression rate is not good enough.
How To do Screen Scraping in C#
public static
string ScreenScrape(string url)
{
System.Net.WebRequest request = System.Net.WebRequest.Create(url);
// set properties of the request
using (System.Net.WebResponse response = request.GetResponse())
{
using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
}
How To Create Javascript Alert from ASP.NET code behind In
Windows Forms it is very easy to pop up a status message by
calling
MessageBox?Show("message").
It is that kind of object model we want in ASP.NET for printing
out JavaScript alerts.
We want Alert.Show("message") in ASP.NET. I’ve written a static
class called Alert with one public method called Show?
The implementation is as simple as can be. Just put the .cs file
in the App_Code folder on your website and you instantly have
access to the method from all pages and user controls. I’ve
written a static class called Alert with one public method
called Show.
The implementation is as simple as can be. Just put the .cs file
in the App_Code folder on your website and you instantly have
access to the method from all pages and user controls.
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;
// A JavaScript alert
public static class Alert
{
////// Shows a client-side JavaScript alert in the browser.
///The message to appear in the alert.
public static void Show(string message)
{
// Cleans the message to allow single quotation marks
string cleanMessage = message.Replace("‘", "\\’");
string script = " ";
// Gets the executing web page
Page page = HttpContext.Current.CurrentHandler as Page;
// Checks if the handler is a Page and that the script isn’t already on the Page
if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
{
page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);
}
}
}
How To Use Add a button in you asp.net file
and add following code in click event of the button
void btnSave_Click(object sender, EventArgs e)
{
try
{
SaveSomething();
Alert.Show("You document has been saved");
}
catch (ReadOnlyException)
{
Alert.Show("You do not have write permission to this file");
}
}
Creating a page method for testing
purposes.
Writing a page method is easy.
They must be declared as static, and they must be
decorated with the
[WebMethod] attribute.
Beyond that, ASP.NET AJAX takes care of the rest on the
server side. This will be our page method for the example:
What about the ScriptManager and
EnablePageMethods?
public partial class _Default : Page
{
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
Traditionally, one of your first steps when utilizing page
methods is to set the ScriptManager’s
EnablePageMethods property to true. Luckily, that
property is a bit of a misnomer. It doesn’t enable page
methods at all , but simply generates an inline
JavaScript proxy for all of the appropriate methods in your
page’s code-behind. For example, if a ScriptManager is added
to the above example’s corresponding Default.aspx and its
EnablePageMethods property is set to true, this JavaScript
will be injected into the page:
var PageMethods = function() {
PageMethods.(this);
this._timeout = 0;
this._userContext = null;
this._succeeded = null;
this._failed = null;
}
PageMethods. = {
_get_path:function() {
var p = this.();
if (p) return p;
else return PageMethods._staticInstance.();},
GetDate:function(succeededCallback, failedCallback, userContext) {
return this._invoke(this._get_path(), 'GetDate',false,{},
succeededCallback,failedCallback,userContext); }}
PageMethods.('PageMethods',Sys..);
PageMethods._staticInstance = new PageMethods();
// Generic initialization code omitted for brevity.
PageMethods.("/jQuery-Page-Method/Default.aspx");
PageMethods. = function(onSuccess,onFailed,userContext) {
PageMethods._staticInstance.(onSuccess,onFailed,userContext);
}
Don’t worry if you don’t understand this code. You don’t
need to understand how it works. Just understand that this
JavaScript proxy is what allows you to call page methods via
the PageMethods.MethodName syntax. The important takeaway
here is that the PageMethods proxy object boils down to a
fancy wrapper for a regular ASP.NET service call.
Calling the page method with jQuery
instead.
Knowing that a page method is consumed in the same way as a
web service, consuming it with jQuery isn’t difficult.Using
the jQuery.ajax method, this is all there
is to it:
$.({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Putting it all together.
Corresponding to the example page method above, here’s our
Default.aspx:
Calling a page method with jQuery</title>
Click here for the time.</div>
As you can see, there’s no ScriptManager
required, much less EnablePageMethods. As referenced in
Default.aspx, this is Default.js:
$(document).(function() {
// Add the page method call as an onclick handler for the
div.
$("#Result").(function() {
$.({
type: "POST",
url: "Default.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Replace the div's content with the page method's return.
$("#Result").(msg.);
}
});
});
});
The end result is that when our result div is clicked,
jQuery makes an AJAX call to the GetDate
page method and replaces the div’s text with its result.
How do stored procedures work in
Access?
Unlike other objects in Access, stored procedures have no
interface and cannot be created or run through the Access
User Interface. The way to get them into your database is
to simply code them. I'll show how that's done in ADO.NET.
When a stored procedure is added to an Access Database,
the Jet Engine reworks the stored procedure syntax into a
query object. To an Access developer this may sound like
unnecessary work to code a query. However, it does have
its advantages. Consider an application that has to break
out into different versions when maintaining both an
Access Database and a SQL Server Database. Using stored
procedures will make it easier to write the code for the
database tier of the application as the program will
change very little between the different versions.
Creating Stored Procedures
To demonstrate, I'll first show how to create the SQL
statements to create stored procedures. At the end of the
article I'll show the entire code needed to run these
statements against the database. Using the Northwind
database that comes with Access, four stored procedures
will be created. Focusing on the Products table for all of
them, let's start off with the easiest one; select all
data of each row in the table. To create the stored
procedure, execute the following SQL statement against the
database:
CREATE PROC procProductsList AS SELECT * FROM Products;
The statement: "CREATE PROC procCustomerList" is the part
that actually creates the stored procedure. The part
following "AS" can be any valid SQL Statement.
Often in a stored procedure you'll want to pass a value to
be used in the query. Consider that you may want to delete
a record based on a particular ProductID. The following
stored procedure shows how to do just that:
CREATE PROC procProductsDeleteItem(inProductsID LONG)" &
"AS DELETE FROM Products WHERE ProductsID = inProductsID;"
On the first line, notice the parenthesis right after the
CREATE PROC declaration. There is a parameter defined as a
Long value. This is where you add the variable to delete
the record in question.
The next two statements show how to create an add and an
update stored procedure for the Products table
respectively. Note that not all fields are included for
the sake of brevity:
CREATE PROC procProductsAddItem(inProductName VARCHAR(40), " &
"inSupplierID LONG, inCategoryID LONG) " &
"AS INSERT INTO Products (ProductName, SupplierID, CategoryID) " &
"Values (inProductName, inSupplierID, inCategoryID);"
"CREATE PROC procProductsUpdateItem(inProductID LONG, " &
"
inProductName VARCHAR(40)) " &
"AS UPDATE Products SET ProductName = inProductName " &
" WHERE ProductID = inProductID;
Notice that a comma separates each parameter when more
than one is specified.
Limitations
There are some limitations you may encounter here,
especially if you're used to the power of SQL Server.
- Output parameters cannot be used.
- Don't use the @ character. The @ character is often
used in Transact SQL (SQL Server), where it represents a
local variable. Access doesn't always convert this
character and will sometimes leave it out. This can cause
esoteric bugs which can lead to premature hair loss.
- Temporary tables are not available in Access.
- I suspect many of the options available in Transact
SQL are not available in Access as it's not Transact SQL
compatible.
Imports System
Imports System.Data
Imports System.Data.OleDb
Module CreateSP
Sub Main()
ProductsProcs()
End Sub
Sub ProductsProcs()
Dim sSQL As String
table
sSQL = "CREATE PROC procProductsList AS SELECT * FROM Products;"
CreateStoredProc(sSQL)
' procProductsDeleteItem - Returns
the details (one record) from the
' JobTitle table
sSQL = "CREATE PROC procProductsDeleteItem(@ProductID LONG) AS " _
& "DELETE FROM Products WHERE ProductID = @ProductID;"
CreateStoredProc(sSQL)
' procProductsAddItem - Add one record
to the JobTitle table
sSQL = "CREATE PROC procProductsAddItem(inProductName VARCHAR(40), " _
& "inSupplierID LONG, inCategoryID LONG) AS INSERT INTO " _
& "Products (ProductName, SupplierID, CategoryID) Values " _
& "(inProductName, inSupplierID, CategoryID);"
CreateStoredProc(sSQL)
' procProductsUpdateItem - Update
one record on the JobTitle table
sSQL = "CREATE PROC procProductsUpdateItem(inProductID LONG, " _
& "inProductName VARCHAR(40)) AS UPDATE Products SET " _
& "ProductName = inProductName WHERE ProductID = inProductID;"
CreateStoredProc(sSQL)
End Sub
' Execute the creation of Stored Procedures
Sub CreateStoredProc(ByVal sSQL As String)
Dim con As OleDbConnection
Dim cmd As OleDbCommand = New OleDbCommand()
Dim da As OleDbDataAdapter
' Change Data Source to the location of Northwind.mdb on your local ' system.
Dim sConStr As String = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data " _
& "Source=C:\Program Files\Microsoft " & "Office\Office10\Samples\Northwind.mdb"
con = New OleDbConnection(sConStr)
cmd.Connection = con
cmd.CommandText = sSQL
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Sub
End Module
How to create a date/time info bar at
the top of your page
This shows you how to use the onload event in the body tag
to show the current date and time when the user loads the
page, nicely formatted as well.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<title>Javascript</title>
<script type="text/javascript">
function initialize() {
showDateAndTime();
}
function showDateAndTime() {
//variables
var datCurrentDate = new Date();
var strCurrentDate = datCurrentDate.toLocaleString();
//set the text
document.getElementById('dateTimeLine').innerHTML = strCurrentDate;
}
</script>
<style type="text/css">
.infoBar {
font-size: 10pt;
color: #333;
font-family: verdana;
background-color: beige;
text-align: right;
padding: 2px;
font-weight: bold;
}
</style>
</head>
<body onload="initialize()">
<div class="infoBar" id="dateTimeLine"></div>
</body> </html>
Always Use 'var'
Variables in javascript either have global scope or
function scope, and using the 'var' keyword is vital to
keeping them straight. When declaring a variable for use
either as a global variable or as a function-level
variable, always prefix the declaration with the 'var'
keyword. The example below highlights the potential
problem caused by not doing so.
Problem Caused By Not Using Var
var i=0; // This is good - creates a global variable
function test() {
for (i=0; i<10; i++) {
alert("Hello World!");
}
}
test();
alert(i); // The global variable i is now 10!
Since the variable i inside the function was not declared
as a function-level variable by using the 'var' keyword,
it references the global variable in this example. It is a
good idea to always declare global variables using 'var',
but it is vital to declare function-scoped variables using
'var'. The two approaches below are functionally
identical.
Fixed Function
function test() {
var i=0;
for (i=0; i<10; i++) {
alert("Hello World!");
}
}
Fixed Function
function test() {
for (var i=0; i<10; i++) {
alert("Hello World!");
}
}
Use Square Bracket Notation
When accessing object properties that are determined at
run-time or which contain characters not compatible with
dot notation, use square bracket notation. If you are not
an experienced javascript programmer, it's not a bad
practice to use square bracket notation all the time.
Objects properties in javascript can be accessed primarily
in two ways: Dot notation and Square bracket notation.
Dot notation
MyObject.property
Square bracket notation
MyObject["property"]
With dot notation, the property name is hard-coded and
cannot be changed at run-time. With bracket notation, the
property name is a string which is evaluated to resolve
the property name. The string can be hard-coded, or a
variable, or even a function call which returns a string
property name.
If a property name is being generated at run-time, the
bracket notation is required. For example, if you have
properties "value1", "value2", and "value3", and want to
access the property using a variable i=2:
This Will Work
MyObject["value"+i]
This Will Not
MyObject.value+i
Also, in some server-side environments (PHP, Struts, etc)
form field names are appended with [] to denote that the
form field should be treated as an array on the
server-side. However, referencing a field name containing
[] using dot notation will not work because [] is the
syntax for reference a javascript array. So, square
bracket notation is required.
This Will Work
formref.elements["name[]"]
This Will Not
formref.elements.name[]
The recommendation for using square bracket notation is to
always use it when it is required (obviously). Using it
when not strictly required is a matter of personal
preference and convention. One good rule of thumb is to
use dot notation to access standard properties of objects,
and square bracket notation to access properties which are
defined as objects in the page. So, while
document["getElementById"]() is perfectly vaid using
square bracket notation, document.getElementById()
is the preferred syntax because getElementById is a
standard property of the document object as defined in the
DOM specifications. Mixing the use of dot and square
bracket notation makes it clear which properties are
standard and which are names defined by the content:
document.forms["myformname"].elements["myinput"].value
Here, the forms property is a standard property
of document, while the form name myformname
is defined by the page content. Likewise, the elements
property and value property are both defined by
the specs, but then myinput name is defined in
the page. This syntax is very clear and easy to understand
and is a recommended convention to follow, but not a
strict rule.
Avoid 'eval'
The eval() function in javascript is a way to run
arbitrary code at run-time. In almost all cases, eval
should never be used. If it exists in your page, there is
almost always a more correct way to accomplish what you
are doing. For example, eval is often used by programmers
who do not know about using
Square Bracket Notation.
The rule is, "Eval is evil." Don't use it unless you are
an experienced developer and know that your case is an
exception.
Reference Forms and Form Elements
Correctly
All forms in an HTML form should have a name attribute.
For XHTML documents, the name attribute is not required
and instead the form tag should have an id attribute and
should be referenced using document.getElementById().
Referencing forms using indexes, such as document.forms[0]
is a bad practice in almost all cases. Some browsers make
the form available as a property of the document itself
using its name. This is not reliable and shouldn't be
used.
The example below uses square bracket notation and correct
object references to show the most fool-proof way of
referencing a form input.
Correct Reference To Form Input
document.forms["formname"].elements["inputname"]
Bad Practice
document.formname.inputname
If you will be referencing multiple form elements within a
function, it's best to make a reference to the form object
first and store it in a variable. This avoids multiple
lookups to resolve the form object reference.
var formElements = document.forms["mainForm"].elements;
formElements["input1"].value="a";
formElements["input2"].value="b";
When validating an input field using onChange or similar
event handlers, it is always a good idea to pass a
reference to the input element itself into the function.
Every input element within a form has a reference to the
form object that it is contained in.
<input type="text" name="address" onChange="validate(this)">
function validate(input_obj) {
// Get a reference to the form which contains this element
var theform = input_obj.form;
// Now you can check other inputs in the same form without
// hard-coding a reference to the form itself
if (theform.elements["city"].value=="") {
alert("Error");
}
}
By passing a reference to the form element and accessing
its form property, you can write a function which does not
contain a hard reference to any specific form name on the
page. This is a good practice because the function becomes
more reusable.
Avoid 'with'
The 'with' statement in javascript inserts an object at
the front scope chain, so any property/variable references
will first try to be resolved against the object. This is
often used as a shortcut to avoid multiple long
references.
Example Using with
with (document.forms["mainForm"].elements) {
input1.value = "junk";
input2.value = "junk";
}
The problem is that the programmer has no way to verify
that input1 or input2 are actually being resolved as
properties of the form elements array. It is checked first
for properties with these names, but if they aren't found
then it continues to search up the scope chain.
Eventually, it reaches the global object where it tries to
treat "input1" and "input2" as global variables and tries
to set their "value" properties, which result in an error.
Instead, create a reference to the reused object and use
it to resolve references.
Using A Reference Instead
var elements = document.forms["mainForm"].elements;
elements.input1.value = "junk";
elements.input2.value = "junk";
Use onclick In Anchors Instead Of
javascript: Pseudo-Protocol
When you want to trigger javascript code from an anchor
<A> tag, the onclick handler should be used rather than
the javascript: pseudo-protocol. The javascript code that
runs within the onclick handler must return true or false
(or an expression than evalues to true or false) back to
the tag itself - if it returns true, then the HREF of the
anchor will be followed like a normal link. If it returns
false, then the HREF will be ignored. This is why "return
false;" is often included at the end of the code within an
onclick handler.
Correct Syntax
<a href="javascript_required.html" onclick="doSomething(); return false;">go</a>
In this case, the "doSomething()" function (defined by the
user somewhere in the page) will be called when the link
is clicked, and then false will be returned. The href will
never be followed for javascript-enabled browsers.
However, if the browser does not have javascript enabled,
the javascript_required.html file will be loaded, where
you can inform your user that javascript is required.
Often, links will just contain href="#" for the sake of
simplicity, when you know for sure that your users will
have javascript enabled. This practice is discouraged.
It's always a good idea to put a local fall-back page that
will be loaded for users with javascript disabled.
Sometimes, you want to conditionally follow a link. For
example, if a user is navigating away from your form page
and you first want to validate that nothing has changed.
In this case, your onclick will call a function and it
will return a value itself to say whether the link should
be followed.
Conditional Link Following
<a href="/" onClick="return validate();">Home</a>
function validate() {
return prompt("Are you sure you want to exit this page?");
}
In this case, the validate() function should always return
either true or false. True if the user should be allowed
to navigate back to the home page, or false if the link
should not be followed. This example prompts the user for
confirmation, then returns true or false, depending on if
the user clicked OK or Cancel.
Below are examples of things NOT to do. If you see code
like this in your pages, it is not correct and should be
fixed.
What Not To Do
<a href="javascript:doSomething()">link</a>
<a href="#" onClick="doSomething()">link</a>
<a href="#" onClick="javascript:doSomething();">link</a>
<a href="#" onClick="javascript:doSomething(); return false;">link</a>
Use The Unary + Operator To TypeConvert
To Number
In javascript, the + operator is used for both addition
and concatenation. This can cause problems when adding up
form field values, for example, since javascript is a
non-typed language. Form field values will be treated as
strings, and if you + them together, javascript will treat
it as concatenation instead of addition.
Problematic Example
<form name="myform" action="[url]">
<input type="text" name="val1" value="1">
<input type="text" name="val2" value="2">
</form>
function total() {
var theform = document.forms["myform"];
var total = theform.elements["val1"].value + theform.elements["val2"].value;
alert(total); // This will alert "12", but what you wanted was 3!
}
To fix this problem, Javascript needs a hint to tell it to
treat the values as numbers, rather than strings. You can
use the unary + operator to convert the string value into
a number. Prefixing a variable or expression with + will
force it to evaluate as a number, which can then be
successfully used in a math operation.
Fixed Example
function total() {
var theform = document.forms["myform"];
var total = (+theform.elements["val1"].value) + (+theform.elements["val2"].value);
alert(total); // This will alert 3
}
Avoid document.all
document.all was introduced by Microsoft in IE and is not
a standard javascript DOM feature. Although many newer
browsers do support it to try to support poorly-written
scripts that depend on it, many browsers do not.
There is never a reason to use document.all in javascript
except as a fall-back case when other methods are not
supported and very early IE support (<5.0) is required.
You should never use document.all support as a way to
determine if the browser is IE, since other browsers also
now support it.
Only Use document.all As A Last Resort
if (document.getElementById) {
var obj = document.getElementById("myId");
}
else if (document.all) {
var obj = document.all("myId");
}
Some rules for using document.all are
- Always try other standard methods first
- Only fall back to using document.all as a last resort
- Only use it if you need to support IE versions earlier
than 5.0
- Always check that it is supported with "if
(document.all) { }" around the block where you use it.
Don't Use HTML Comments In Script Blocks
In the ancient days of javascript (1995), some browsers
like Netscape 1.0 didn't have any support or knowledge of
the script tag. So when javascript was first released, a
technique was needed to hide the code from older browsers
so they wouldn't show it as text in the page. The 'hack'
was to use HTML comments within the script block to hide
the code.
Using HTML Comments In Script Is Bad
<script language="javascript">
<!--
// code here
//-->
</script>
No browsers in common use today are ignorant of the
<script> tag, so hiding of javascript source is no longer
necessary. In fact, it can be considered harmful for the
following reasons:
- Within XHTML documents, the source will actually be
hidden from all browsers and rendered useless
- -- is not allowed within HTML comments, so any
decrement operations in script are invalid
Avoid Cluttering The Global Namespace
Global variables and functions are rarely required. Using
global may cause naming conflicts between javascript
source files and cause code to break. For this reason, it
is a good practice to encapsulate functionality within a
single global namespace.
There are several ways to accomplish this task, some of
which are much more complicated than others. The simplest
approach is to create a single global object and assign
properties and methods to this object.
Creating A Namespace
var MyLib = {}; // global Object cointainer
MyLib.value = 1;
MyLib.increment = function() { MyLib.value++; }
MyLib.show = function() { alert(MyLib.value); }
MyLib.value=6;
MyLib.increment();
MyLib.show(); // alerts 7
Avoid sync "Ajax" calls
When making "Ajax" requests, you may choose either async
or sync mode. Async mode runs the request in the
background while other browser activities can continue to
process. Sync mode will wait for the request to return
before continuing.
Requests made with sync mode should be avoided. These
requests will cause the browser to lock up for the user
until the request returns. In cases where the server is
busy and the response takes a while, the user's browser
(and maybe OS) will not allow anything else to be done. In
cases where a response is never properly received, the
browser may continue to block until the request is timed
out.
If you think that your situation requires sync mode, it is
most likely time to re-think your design. Very few (if
any) situations actually require Ajax requests in sync
mode.
Use JSON
When storing data structures as plain text or
sending/retrieving data structures via
Ajax, use JSON instead of XML when possible.
JSON (JavaScript Object Notation) is a more
compact and efficient data format, and is
language-neutral.
Use Correct <script> Tags
The LANGUAGE attribute is deprecated in the <script> tag.
The proper way to create a javascript code block is:
<script type="text/javascript">
// code here </script>
How to play an audio file by clicking a
link
This code plays two different .wav files depending on
which link you click. I tested it in IE6 and Firefox2.
Works nicely for short files (e.g. pronouncing words on an
educational site) or for intranet applications. Explorer
will use Windows Media Player and for Firefox you have to
install QuickTime, an easy install.
<html> <head>
<script type="text/javascript">
function playAudio(audioPathAndFileName)
{
document.getElementById("dummyPlayTag").innerHTML=
'<embed src="' + audioPathAndFileName
+ '" hidden="true" autostart="true" loop="false">';
}
</script> </head> <body>
<a href="#" onclick="playAudio('customAudio/elvis.wav')">Elvis</a>
<a href="#" onclick="playAudio('customAudio/benFranklin.wav')">Ben Franklin</a>
<span id="dummyPlayTag"></span> </body>
</html>
Data Grid or Grid View Row Pointer
//Row pointer is used to
identify the row which is selected Layout source code:
<asp:GridView
ID="GridView1″
runat="server"
OnRowCreated="GridView1_RowCreated"
AutoGenerateColumns="False"
CellPadding="4″
ForeColor="#333333″
GridLines="None"
Width="100%">
//VB.NET 2.0 Code Behind:
Protected Sub
GridView1_RowCreated(ByVal
sender As Object, ByVal e As
GridViewRowEventArgs)
Dim rowID As String =
String.Empty
If e.Row.RowType = DataControlRowType.DataRow Then
rowID = "row" & e.Row.RowIndex
e.Row.Attributes.Add("id", "row" & e.Row.RowIndex)
e.Row.Attributes.Add("onmouseover",
"ChangeRowColor(" & "‘" & rowID & "‘" & ")")
e.Row.Attributes.Add("onmouseout",
"ChangeRowColors(" & "‘" & rowID & "‘" & ")")
End If
End Sub
Code to generate a random filename
Here's a short function that will generate
a random filename
Private Function GetRandomFileName() As String Dim r As New Random()
Dim i As Integer Dim strTemp
As String ="" For i = 0 To 8 strTemp= strTemp & Chr(Int((26
* r.NextDouble()) + 65)) Next Return "c:\\"
& strTemp & ".bmp"
End Function
How do I determine the
executing assemblies path?
If your wanting to do this with a Windows Forms
application, just use:
Dim path
As
String = System.IO.Path.GetDirectoryName(Application.ExecutablePath)
Otherwise, you can use:
Dim path
As
String =
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly.Location)
How do I get a list of
installed printers?
Use the System.Drawing.Printing.PrinterSettings.InstalledPrinters
collection.
How do I translate a Win32
error number into a human readable text message?
You have two ways (using VB.NET) to get a numeric
Win32 error message. One is to use the
System.Runtime.InteropServices.Marshal.GetLastWin32Error
method, while the other is to use the VB.NET specific
Err.LastDllError method. Now that you have the
numeric representation of the Win32 error, we want to
turn it into a text representation, you know, the
error message in English.
There's couple of ways to accomplish this.
First, we'll explore the Win32 P/Invoke way first.
Using this method is the way that the SDK
documentation is pointing out. What I've done is
wrapped the FormatMessage API call with a VB.NET
friendly wrapped version.
Private
Declare Function FormatMessageA
Lib "kernel32" (ByVal
flags As Integer, ByRef source As
Object, ByVal messageID As
Integer, ByVal languageID
As Integer,
ByVal buffer As String,
ByVal size As
Integer, ByRef arguments As
Integer) As
Integer
Public Shared Function FormatMessage(ByVal
[error] As Integer) As String Const
FORMAT_MESSAGE_FROM_SYSTEM As
Short = &H1000 Const LANG_NEUTRAL
As Short = &H0 Dim buffer As
String = Space(999)
FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, 0, [error], LANG_NEUTRAL, buffer,
999, 0)
buffer = Replace(Replace(buffer, Chr(13), ""), Chr(10), "")
Return buffer.Substring(0, buffer.IndexOf(Chr(0)))
End Function
You can then use this method as follows:
Throw New
Exception(Marshal.GetLastWin32Error)
A more friendly .NET Framework method is to use the
Win32Exception class. Normally when you want to
know what the human readable version of the numeric
value is, you will probably throw this so the user of
your application can see the error. At the very
least, so you can easily figure out what is the
problem.
Imports
System.ComponentModel
Imports
System.Runtime.InteropServices
Throw New
Win32Exception(Marshal.GetLastWin32Error)
How do I change the color
of the text on a tab of the TabControl?
You'll have to set the TabControls DrawMode property
to OwnerDrawFixed and draw the text in the
TabControls DrawItem procedure.
Private Sub TabControl1_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles
TabControl1.DrawItem Dim r As RectangleF = RectangleF.op_Implicit(e.Bounds) Dim ItemBrush As
New SolidBrush(TabControl1.BackColor)
Dim sf As
New StringFormat
sf.Alignment = StringAlignment.Center sf.LineAlignment = StringAlignment.Center
If CBool(e.State
And DrawItemState.Selected) Then e.Graphics.FillRectangle(ItemBrush, e.Bounds)
e.Graphics.DrawString(TabControl1.TabPages(e.Index).Text,
e.span, Brushes.Red, r, sf) Else e.Graphics.DrawString(TabControl1.TabPages(e.Index).Text,
e.span, Brushes.Blue, r, sf) End If
End Sub
How can I determine the
date for next Friday?
Public
Function GetNextFriday(ByVal
startDate As
Date) As
Date If startDate.DayOfWeek < DayOfWeek.Friday
Then ' If todays day of week is less than
Friday. ' Add the number of days till next Friday.
Return startDate.AddDays(DayOfWeek.Friday - startDate.DayOfWeek) Else ' Otherwise, subtract
the difference from 7. Return startDate.AddDays(7 - (startDate.DayOfWeek
-DayOfWeek.Friday)) End If
End Function
How do I catch errors in
'release' builds, but not while debugging?
Here's the scenario. You want to setup a
global error handler (which you should) for your
application. This is a good thing.
However, it causes a pain when trying to develop
within the debugger since now every time an error
occurs, your global error handler will capture the
error. Here's a solution:
Often times, applications will have a global
exception handler in the Main method that catches
any exceptions that weren't handled elsewhere. The
compiler itself uses a strategy similar to this for
out of memory situations -- once we've run out of
memory, the compiler's toast, so we throw an
exception indicating "out of memory" and then catch
it at the top level, giving a nice "out of memory,
please restart the compiler" error. (Hopefully none
of you have ever seen it.) Anyway, when you're
debugging the application it can be convenient to
not catch exceptions at the top level so that you
immediately break into the debugger when you get a
global exception. A simple way to do this is to use
When to not catch the exception when a debugger is
present:
Sub Main()
Try
RunApplication()
Catch ex As Exception When Not System.Diagnostics.Debugger.IsAttached
HandleGlobalException(ex)
End Try End Sub
How do I determine if an
assembly was built for debug or release?
If you want to determine if your assembly was built
using debug or release, you would think you could
use the FileVersionInfo.IsDebug or IsRelease;
however, the compiler doesn't apparently set the
proper bit as you would expect. Since that
doesn't work, you could use the DebuggableAttribute
on the assembly by using the following code.
Dim assm
As Reflection.Assembly = Reflection.Assembly.LoadFrom(Application.ExecutablePath)
Dim found As Boolean = assm.GetCustomAttributes(GetType(DebuggableAttribute),
False).Length > 0
Me.Text = "Assembly is "
& IIf(found, "debug", "release")
How do I load an image
from a file using a file stream?
Protected Shared Function GetImageFromFile(ByVal FileName As String) As Byte()
Dim myFile As String = FileName
Dim fs As FileStream = New FileStream(myFile, FileMode.Open, FileAccess.Read)
Dim br As BinaryReader = New BinaryReader(fs)
Dim bytesize As Long = fs.Length
ReDim GetImageFromFile(bytesize)
GetImageFromFile = br.ReadBytes(bytesize)
End Function
To use the above function:
Dim img
As
New Bitmap(New
IO.MemoryStream(GetImageFromURL("c:\file.jpg")))
Me.BackgroundImage =
img
How do I load an image
from a URI address?
Function GetImageFromURL(ByVal url As String) As Byte()
Dim wr As HttpWebRequest = DirectCast(WebRequest.Create(url),HttpWebRequest)
Dim wresponse As HttpWebResponse =DirectCast(wr.GetResponse, HttpWebResponse )
Dim responseStream As Stream = wresponse.GetResponseStream
Dim br As BinaryReader = New BinaryReader(responseStream)
Dim bytesize AsLong = wresponse.ContentLength
Return br.ReadBytes(bytesize)
End Function
To use the above function:
Dim img As New Bitmap(New IO.MemoryStream(GetImageFromURL("http://s/n.JPG")))
Me.BackgroundImage = img
How do I generate a GUID
(Globally Unique IDentifier)?
You can use the System.Guid class.
Dim guid As String = System.Guid.NewGuid.ToString
>
You can also control how the guid is formatted.
For example, if you use ToString("N"), the dashes
("-") will be removed.
How to get client date and time
You can use java script function to show the date and time.
<script type="text/javascript">
function displayTime()
{
var localTime = new Date();
var year= localTime.getYear();
var month= localTime.getMonth() +1;
var date = localTime.getDate();
var hours = localTime .getHours();
var minutes = localTime .getMinutes();
var seconds = localTime .getSeconds();
var div=document.getElementById("div1");
div.innerText=year+"-"+month+"-"+date+" "+hours+":"+minutes+":"+seconds;
}
</script>
Then you can call it at web page.
<body onload="displayTime();">
<form id="form2" runat="server">
<div id="div1"></div>
</form>
</body>
How to access a control by using JavaScript
Reference the ClientID property (or UniqueID) of the control in the JavaScript.
protected void Page_Load(object sender, EventArgs e)
{
Button btn= new Button();
btn.ID = "btn5";
btn.Attributes.Add("runat", "server");
btn.Attributes.Add("onclick", "pop('" + btn.ClientID + "')");
btn.Text = "Test";
this.form1.Controls.Add(btn);
}
function pop(InputBoxID)
{
var InputControl = document.getElementById(InputBoxID);
alert(InputControl.value);
}
Or
you can use the following method:
btn.Attributes.Add("onclick", "pop(this)");
function pop(InputBox)
{
alert(InputBox.value);
}
How to invoke a server-side function with JavaScript
Firstly, you can drag a server button and put the server function into the
button Click even,
protected void Button1_Click(object sender, EventArgs e)
{
FunctionName();
}
Secondly, you can call the server function at JavaScript by using the following
code,
document.getElementById("Button1").click();
How to retrieve server side variables using JavaScript code
<asp:HiddenField ID="HiddenField1" runat="server" />
public partial class LoginDemo : System.Web.UI.Page
{
private string str="hello";
protected void Page_Load(object sender, EventArgs e)
{
HiddenField1.Value=str;
}
}
Then
you can access the control HiddenField1 using javascipt:
<script type="text/JavaScript">
Var tt=document.getElementByID(“HiddenField1”);
alert(tt.value);
</script>
How to assign a value to a hidden field using JavaScript in ASP.NET
We
can use JavaScript to set the value of a hidden control and get its value at the
server after a post back.
<input id="Hidden1" type="hidden" />
<script type="text/JavaScript">
var str=”hello”
document.getElementByID(“Hidden1”).value=str
</script>
protected void Page_Load(object sender, EventArgs e)
{
string str=request["Hidden1"].ToString();
}
How to register the JavaScript function at Code-Behind
Use
ResterStartupScript
this.Page.ClientScript.RegisterStartupScript(this.GetType(),"alert","<script>alert(‘hello’);</script>");
Use Literal control,
private void Button2_Click(object sender, System.EventArgs e)
{
string str;
str="<script language='JavaScript'>";
str+="selectRange()";
str+="<script>";
Literal1.Text=str;
}
How to display images with a delay of five second
With this script you can see clickable images rotating in real-time
without requiring banner rotation software or page reloads/refreshes .You should
see a new banner rotating every 5 seconds:
<%@ 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">
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>JavaScript</title>
<script language="javascript" type="text/javascript">
var image="";
var banners=0;
function loadbanners() {
if (banners==1)
{
image="images/AJAX.gif";
}
if (banners==2)
{
image="images/ASPDotNet.gif";
}
if (banners==3)
{
image=" images/MSDN.gif";
}
}
function cycle()
{
if (++banners > 3)
banners=1;
loadbanners();
document.getElementById("banner1").src =image;
window.setTimeout('cycle();',5000);
}
</script>
</head>
<body onload="cycle();">
<form id="form2" runat="server">
<div>
<img alt="" id="banner1" src="images/start.png" />
</div>
</form>
</body>
</html>
How to get browser screen settings and apply it to page controls
You can use the JavaScript,
suppose the control type is <image>, see the code below:
<html>
<body>
<input onclick="resizeImage()"/>
<img src="http://www.microsoft.com/library/toolbar/3.0/images/banners/ms_masthead_ltr.gif" id="Img1" />
<script language="JavaScript">
var winWidth = 0;
var winHeight = 0;
function resizeImage(){
var img=document.getElementById("testImage")
if (window.innerWidth)
winWidth = window.innerWidth;
else if ((document.body) && (document.body.clientWidth))
winWidth = document.body.clientWidth;
if (window.innerHeight)
winHeight = window.innerHeight;
else if ((document.body) && (document.body.clientHeight))
winHeight = document.body.clientHeight;
if (document.documentElement && document.documentElement.clientHeight &&
document.documentElement.clientWidth)
{
winHeight = document.documentElement.clientHeight;
winWidth = document.documentElement.clientWidth;
}
img.width= winHeight;
img.width= winWidth;
}
</script>
</body>
</html>
How to clear the session when the user closes a window
Use
the code,
<script type="text/javascript">
function window.onbeforeunload()
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
if(event.clientX>document.body.clientWidth&&event.clientY<0||event.altKey)
{
xmlhttp.open("GET","exit.aspx",false);
xmlhttp.send();
}
}
</script>
Ways to pass data between
pages
How to use cookies
Create a page named page1.aspx, and then drag a button and a TextBox onto
the page. Double click the button and then add the following code:
protected void Button1_Click(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("UserName");
cookie.Value = TextBox1.Text;
cookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
Response.Redirect("Page2.aspx");
}
<div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
On page2.aspx, double click the form and put the following code in it:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["UserName"] != null)
Response.Write(Request.Cookies["UserName"].Value);
}
How to use QueryString
private void Button1_Click (object sender, System.EventArgs e)
{
string url;
url="anotherwebform.aspx?name=" +
TextBox1.Text + "&email=" + TextBox2.Text;
Response.Redirect(url);
}
Destination web form
private void Page_Load (object sender, System.EventArgs e)
{
Label1.Text=Request.QueryString["name"];
Label2.Text=Request.QueryString["email"];
}
How to use Session
private void Button1_Click(object sender, System.EventArgs e)
{
//Drag TextBox1 and TextBox2 onto a web form
Session["name"]=TextBox1.Text;
Session["email"]=TextBox2.Text;
Server.Transfer("anotherwebform.aspx");
}
Destination web form
private void Page_Load(object sender, System.EventArgs e)
{
Label1.Text=Session["name"].ToString();
Label2.Text=Session["email"].ToString();
Session.Remove("name");
Session.Remove("email");
}
How to use Context
//Page1.aspx stores value in context before transferring
Context.Items("UserName") = txtName.Text;
Server.Transfer("Page2.aspx");
//Page2.aspx retrieves the value from Page1’s context
string sName;
sName = Context.Items("UserName").ToString;
Response.Write("Your name is " + sName);
How to use PreviousPage
FirstForm.aspx
<asp:Button id="buttonPassValue" runat="server" Text="Button" PostBackUrl="~/SecondForm.aspx">
</asp:Button>
SecondForm.aspx.cs
TextBox1.Text = Request.Form["TextBox1"].ToString();
Or SecondForm.aspx.cs
TextBox textBoxTemp = (TextBox) PreviousPage.FindControl("TextBox1");
TextBox1.Text = textBoxTemp.Text;
As you’ve noticed, this is a simple and clean implementation of passing
values between pages.
How to use Submit Form
page1.aspx,
<%@ 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">
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script language="javascript">
function CopyTextToHiddenField()
{
var textbox1Value = document.getElementById("<%=TextBox1.ClientID%>").value;
document.forms[1].document.getElementById("Hidden1").value = textbox1Value;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</form>
<form name="SubmittedForm" action="page2.aspx"
method="post">
<input id="Submit1" type="submit" value="submit" onclick="CopyTextToHiddenField()" />
<input name="Hidden1" type="hidden" />
</form>
</body>
</html>
page2.aspx,
<%@ 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)
{
Response.Write(Request.Form["Hidden1"]);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
2.7
How to use Server.Transfer
page1.aspx,
<%@ 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 Button_Click(object sender, EventArgs e)
{
Server.Transfer("page2.aspx", true);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button_Click" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>
page2.aspx,
<%@ 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)
{
Response.Write(Request.Form["TextBox1"]);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
How to upload a file
if (FileUpLoad1.HasFile)
{
FileUpLoad1.SaveAs(Server.MapPath("upload")+ "\\" + FileUpLoad1.FileName);
}
Why upload fails when using
an ASP.NET FileUpload control to upload large files
For security reasons, ASP.NET is limited in terms of an uploaded file
size. The default maximum file size is 4 MB but this can be changed by modifying
the MaxRequestLength attribute of Machine.config's <httpRuntime> element.
<httpRuntime executionTimeout="240" maxRequestLength="20480" />
How to upload an image
files only
See the code,
Fileupload.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Fileupload.aspx.cs"
Inherits="FileuploadDemo" %>
<!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>Upload Image Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Image ID="Image1" runat="server" />
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
</div>
</form>
</body>
</html>
Fileupload.aspx.cs:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class FileuploadDemo : System.Web.UI.Page
{
protected void btnSubmit_Click(object sender, EventArgs e)
{
string fileFullname = this.FileUpload1.PostedFile.FileName;
string dataName = DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss");
string fileName = fileFullname.Substring(fileFullname.LastIndexOf("\\") + 1);
string type = fileFullname.Substring(fileFullname.LastIndexOf(".") + 1);
if (FileUpload1.PostedFile.ContentType.ToUpper().IndexOf("IMAGE") > -1)
{
System.Drawing.Image img = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
int Width = img.Width;
int Height = img.Height;
if (Width > 1000 || Height > 1000 || FileUpload1.PostedFile.ContentLength > 1024 * 1024 * 200)
{
this.ClientScript.RegisterStartupScript(this.GetType(), "Startup",
"<script
language='javascript'>alert('The image size is too large!');</script>");
}
else
{
if (type == "jpg" || type == "gif" || type == "bmp" || type == "JPG" || type == "GIF")
{
string ImagePath = "images/";
string sPath = Server.MapPath(ImagePath) + dataName + fileName;
string imgPath = ImagePath + dataName + fileName;
this.FileUpload1.PostedFile.SaveAs(sPath);
this.ClientScript.RegisterStartupScript(this.GetType(),
"Startup", "<script language='javascript'>alert('Success!');</script>");
this.Image1.ImageUrl = imgPath;
this.btnSubmit.Enabled = false;
this.btnSubmit.Text = "Success!";
this.btnSubmit.Enabled = true;
}
else
{
this.ClientScript.RegisterStartupScript(this.GetType(), "Startup",
"<script
language='javascript'>alert('File type is not right!');</script>");
}
}
}
else
{
this.ClientScript.RegisterStartupScript(this.GetType(), "Startup",
"<script language='javascript'>alert('The
uploaded file is not a image file!');</script>");
}
}
}
How to get a File Upload
control work with an UpdatePanel
The FileUpload control does not work with asynchronous post backs and
therefore does not work from within an AJAX UpdatePanel.
The trick to make the FileUpload to work within an Ajax UpdatePanel is to
setup a PostBackTrigger in the UpdatePanel control.
Demo code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers >
<asp:PostBackTrigger ControlID ="Button1" />
</Triggers>
<ContentTemplate >
<asp:FileUpload ID ="fileupload1" runat ="server" /><br />
<asp:Button ID ="Button1" runat ="server" Text
="Upload" OnClick="Button1_Click" /><br />
<asp:Label ID ="Lable1" runat ="server" Text =""></asp:Label>
<asp:LinkButton ID ="LinkButton1" runat="server" Text
="Click Here" OnClick="LinkButton1_Click"></asp:LinkButton>
</ContentTemplate>
</asp:UpdatePanel>
How to change the culture settings for a Calendar
In calendar.aspx.cs:
private void Page_Load(object sender, System.EventArgs e)
{
System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.CreateSpecificCulture("ens");
System.Threading.Thread.CurrentThread.CurrentCulture = culture;
System.Threading.Thread.CurrentThread.CurrentUICulture = culture;
}
How to select multiple non-sequential dates at Code-Behind
Invoke the member function ‘Add’ of the control's SelectedDates
collection. You can add dates in any sequence, because the collection will
automatically arrange them in order for you.
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
Calendar1.SelectedDates.Clear();
Calendar1.SelectedDates.Add(new DateTime(2008, 8, 1));
Calendar1.SelectedDates.Add(new DateTime(2008, 8, 7));
Calendar1.SelectedDates.Add(new DateTime(2008, 8, 15));
}
How to disable some dates in Calendar control
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
string date="02/01/2008";
DateTime dt = DateTime.Parse(date);
if (e.Day.Date == dt)
e.Day.IsSelectable = false;
}
How to extend Calendar control for Server-Side validation
How to
set ToolTips and links in Calendar control’s DayRender event
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
e.Cell.Controls.Clear();
HyperLink link = new HyperLink();
link.Text = e.Day.Date.Day;
link.ToolTip = "anything you want here!";
link.NavigateUrl = url;
e.Cell.Controls.Add(link);
}
How to give some dates different appearances
We can do this with the following code:
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.Date.Month == 2 && e.Day.Date.Day == 25)
{
e.Cell.BackColor = System.Drawing.Color.Yellow;
}
if (e.Day.Date.DayOfWeek == DayOfWeek.Friday || e.Day.Date.DayOfWeek == DayOfWeek.Saturday)
{
e.Cell.Controls.Clear();
e.Cell.Text = "today isweekend";
}
}
How to enable ASP.NET DropDownList with OptionGroup support
We can override the function of DropDownList, and add the additional
property for it.
Here are some good articles about it.
How to disable an item in
DropDownList
<asp:DropDownList ID="DropDownList1" runat ="server" Width="235px" AutoPostBack="False">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
</asp:DropDownList>
protected void Page_Load(object sender, EventArgs e)
{
DropDownList1.Attributes.Add("onchange", "change();");
}
<script type ="text/javascript" >
function change()
{
var dd=document.getElementById ('<%=DropDownList1.ClientID %>');
var value=dd.options[dd.selectedIndex].value;
if(value!="2") //supose you want to disable the item numbered 2
{
setTimeout("__doPostBack('DropDownList1','')", 0);
}
}
</script>
How to hold the selected
value for a DropDownList
You should place your data binding code for the dropdownlist in the
!page.Ispostback block.
the !postback block will ensure it will only be filled once during post
backs.
if(!Page.IsPostBack)
{
//bind template drop down here
}
How to add a new property to UserControl
You can setup new properties inside the class definition of the user
control at its .ascx.cs file.Example:
ascx file,
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs"
Inherits="WebUserControl" %>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Calendar ID="Calendar1" runat="server"></asp:Calendar>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
ascx.cs file,
public partial class WebUserControl : System.Web.UI.UserControl
{
String text2 = String.Empty;
public String Text
{
get
{
return Label1 .Text ;
}
set
{
Label1 .Text = value;
}
}
public String Text2
{
get
{
return text2;
}
set
{
text2 = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Text = text2;
}
}
aspx file
<%@ Register src="WebUserControl.ascx" mce_src="WebUserControl.ascx"
TagName="WebUserControl" TagPrefix="uc1" %>
<uc1:WebUserControl id="WebUserControl1" runat="server" Text="Hello world"
Text2="Hello world.">
</uc1:WebUserControl>
How to access a dynamically created UserControl
You can use FindControl method to get a reference to the target child
control of your user control and then use it just like any other controls.
Example:
UC.ascx,
<%@ Control Language="C#" ClassName="UC" %>
<script runat="server">
</script>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
Page.aspx:
<%@ Page Language="C#" %> <%@ Register src="UC.ascx" tagname="UC"
tagprefix="uc1" %>
<!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 btnLoad_Click(object sender, EventArgs e)
{
UC uc = new UC();
uc.LoadControl("~/uc/UC.ascx");
uc.ID = "MyUC";
form1.Controls.Add(uc);
(form1.FindControl("MyUC").FindControl("txtName") as TextBox).Text = "ASP.NET";
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>User Control Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnLoad" runat="server" Text="Loading user control ..."
onclick="btnLoad_Click" />
</div>
</form>
</body>
</html>
How to access a control inside a UserControl
Assume there is a user control called UC and there is only a TextBox
control inside it. Now drag this user control into a web page, you can use the
following code to visit the TextBox control.
((TextBox)UC1.FindControl("TextBox1")).Text = "demo";
How to create a dynamic control
We can create the dynamic control in the Page_Init() event or Page_Load()
event,
protected void Page_Load(object sender, EventArgs e)
{
TextBox dynamicTextBox = new TextBox();
dynamicTextBox.ID = "DynamicTextBox";
dynamicTextBox.AutoPostBack = true;
dynamicTextBox.Text = "InitData";
dynamicTextBox.TextChanged += new EventHandler(dynamicTextBox_TextChanged);
this.Form.Controls.Add(dynamicTextBox);
}
void dynamicTextBox_TextChanged(object sender, EventArgs e)
{
Response.Write("hello");
}
How to access a user entered value in a
dynamic created TextBox control
a.
Get the value from the form's POST data. Here is the code:
if(Request.Form["dynamicTextBox"] != null)
selectedValue = Request.Form["dynamicTextBox"].ToString();
b.
Get the value by finding the control at the webpage.
TextBox txt=this.form1.FindControl("dynamicTextBox") as TextBox;
See the whole demo code,
<%@ 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">
public string Res = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
TextBox dynamicTextBox = new TextBox();
dynamicTextBox.ID = "dynamicTextBox";
form1.Controls.Add(dynamicTextBox);
}
protected void btnForm_Click(object sender, EventArgs e)
{
lblMsg.Text += "<br /> Form way:";
if (Request.Form["dynamicTextBox"] != null)
Res = Request.Form["dynamicTextBox"].ToString();
lblMsg.Text += Res;
}
protected void btnFindControl_Click(object sender, EventArgs e)
{
lblMsg.Text += "<br /> FindControl way: ";
TextBox dynamicTextBox = this.form1.FindControl("dynamicTextBox") as TextBox;
Res = dynamicTextBox.Text;
lblMsg.Text += Res;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblMsg" runat="server" Text=""></asp:Label>
<asp:Button ID="btnForm" runat="server" Text="Form Way" OnClick="btnForm_Click" />
<asp:Button ID="btnFindControl" runat="server" Text="FindControl Way" OnClick="btnFindControl_Click" />
</div>
</form>
</body>
</html>
Dynamic controls accessed by JavaScript
Reference the ClientID property (or UniqueID) of the control in the
Javascript.
protected void Page_Load(object sender, EventArgs e)
{
Button btn= new Button();
btn.ID = "btn5";
btn.Attributes.Add("runat", "server");
btn.Attributes.Add("onclick", "pop('" + btn.ClientID + "')");
btn.Text = "Test";
this.form1.Controls.Add(btn);
}
function pop(InputBoxID)
{
var InputControl = document.getElementById(InputBoxID);
alert(InputControl.value);
}
Or,
Use the following method.
btn.Attributes.Add("onclick", "pop(this)");
function pop(InputBox)
{
alert(InputBox.value);
}
How to retain all added
server controls dynamically after post back
You should recreate these dynamic control at Page_load or Page_init()
function everytime.
protected void Page_Load(object sender, EventArgs e)
{
//recreate these dynamic control.
}
Related posts:
Why dynamically created
controls disappear after a post back
The dynamic button must be re-created on each post back, so remove the
if(!Page.IsPostBack). It's probably better if you create the controls at the
Page_Init event.
How to use with Code-Behind
Label1.Attributes.Add("style", "background-color:Red");
How to use with JavaScript
document.getElementById("Label1").style.backgroundColor = "Red";
Add the following code inside of the “head” tag,
How to use with html
<link href="<%= CSS %>"
rel="stylesheet" type="text/css" />
Note: CSS is valuable
Linked style sheet usually lives in <head> tag, but there is no need to
worry if it is put inside <body> tag. As
As well, <head> tag must have a runat=”server” attribute.
How to set an image as Button’s background
<input name="Submit" type="button" value=""
style="border-style: none; background-color: Transparent;
background-image: url('bg.png'); width: 68px; height: 20px; vertical-align: middle;" />
How to color items in
ListBox
Demo code:
<style type="text/css">
.optred{background-color:red;}
.optblue{background-color:blue;}
</style>
protected void Page_PreRender(object sender, EventArgs e)
{
bool flag=false;
foreach (ListItem li in ListBox1.Items)
{
if (flag)
{
li.Attributes.Add("class", "optred");
flag = false;
}
else
{
li.Attributes.Add("class", "optblue");
flag = true;
}
}
}
How to print a part of a
web page with CSS
CSS CODE:
<style media="print">
.Noprint
{
display: none;
}
.Print
{
page-break-after: always;
}
</style>
HTML CODE:
<div class="Noprint">
I am not print;
</div>
<div class="Print">
I will print;
</div>
How to print a part of a web page with
JavaScript (1)
JavaScript CODE:
<script language="JavaScript" type="text/JavaScript">
function doPrint() {
bdhtml=window.document.body.innerHTML;
sprnstr="<!--startprint-->";
eprnstr="<!--endprint-->";
prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr)+17);
prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));
window.document.body.innerHTML=prnhtml;
window.print();
}
</script>
HTML CODE:
<!--startprint-->
This area will print!
<!--endprint-->
<br />
I will not print?
<input id="btnPrint" type="button" value="Print" onclick="doPrint()" />
How to print a part of a
web page with JavaScript (2)
JavaScript CODE:
<script language="javascript" type="text/javascript">
function printdiv(divID)
{
var headstr = "<html><head><title></title></head><body>";
var footstr = "</body>";
var newstr = document.all.item(divID).innerHTML;
var oldstr = document.body.innerHTML;
document.body.innerHTML = headstr+newstr+footstr;
window.print();
document.body.innerHTML = oldstr;
return false;
}
</script>
HTML CODE: <input name="b_print" type="button" onclick="printdiv('divID');" value=" Print " /> <div id="divID"> <h1 style="color:green">
The Div content which you want to print</h1> </div>
What classes are needed to send e-mails in ASP.NET
Class MailMessage and SmtpMail are used to send emails from an ASP.NET
application. MailMessage and SmtpMail are from System.Web.Mail namespace of .NET
Framework 1.1 Class Library. Also, you can use System.Net.Mail instead of
System.Web.Mail if you have .NET Framework version 2.0 installed.
How to send
emails by using System.Net.Mail
CODE-BEHIND:
MailMessage message = new MailMessage();
message.From = new MailAddress("fromusername@DomainName");
message.To.Add(new MailAddress("tousername@DomainName"));
message.CC.Add(new MailAddress("ccusername@DomainName"));
message.Subject = "Subject";
message.Body = "Content";
SmtpClient client = new SmtpClient();
client.Send(message);
web.config:
<system.net>
<mailSettings>
<smtp from="username@DomainName">
<network host="SMTPServerName" port="25" userName="username" password="secret" defaultCredentials="true" />
</smtp>
</mailSettings>
</system.net>