______________________________________________________________________ Tip of the Day! Populating a dropdownlist from an RDMS The following code populates a dropdownlist from the Northwind database hosted on SQL Server. When a category has been selected fom the dropdownlist it is displayed on the aspx page. <%@ Page Language="C#" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> Categories
Please select a category:

Current Category: ______________________________________________________________________ Tip of the Day! Server.Execute and Server.Transfer Server.Execute transfers execution across to a second page, executes that in its entirety and then returns control to the original page. Server.Transfer transfers execution across to a second page and executes that in its entirety, but does not return control to the original page. TransEx.asp ------------ Transfer and Execute Example <% Response.Write "This is the original page


" Server.Execute "page1.html" Response.Write "
We're back on the original page again
" Server.Transfer "page2.html" Response.Write "
We're back on the original page again" %> Page1.html ----------- Page 1

You have been redirected to Page1.html

Page2.html ----------- Page 2

You have been redirected to Page2.html

Note: Because we used Server.Transfer to redirect us to Page2.html, the final Response.Write is not displayed, as control has not been returned to TransEx.asp. ______________________________________________________________________ Tip of the Day! Response.Redirect The following code shows how we can create a page that processes some information from the Request object and makes a decision on which page the browser should be redirected to using the Redirect method. Redirect.html ------------- Redirection Example
ASPToday
C#Today

  
Choose.asp -------------- <%Option explicit Dim strChoice strChoice=Request.Form("Choose") If strChoice="ASP" Then Response.Redirect("http://www.asptoday.com") Else Response.Redirect("http://www.csharptoday.com") End If%> ______________________________________________________________________ Tip of the Day! A JavaScript Popup window The following JavaScript opens a pop up window: ______________________________________________________________________ Tip of the Day! ASP.NET ViewState ASP.NET allows pages/controls to maintain state across round trips. The state is stored within the “viewstate” hidden field and is disabled with the “enableviewstate” attribute. <%@ Page Trace="true" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %>

Select City:



______________________________________________________________________ Tip of the Day! ASP.NET Caching The following snippet illustrates caching in ASP.NET. The names returned from the Northwind database are cached for 10 seconds. <%@ OutputCache VaryByParam="States" Duration="10" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %>

Select City:





Generated at:

______________________________________________________________________ Tip of the Day! How to read an operating system environment variable from ASP.NET The following snippet displays the content of the TEMP environment variable: <%@ Import Namespace="System" %> ______________________________________________________________________ Tip of the Day! Image Swapping The following code, although not very elegant, is a simple and effective way of showing different images on a web site. If you roll your mouse over John's face, the image becomes ASPToday's default author image.

John or Appleman?

______________________________________________________________________ Tip of the Day! Displaying a user's screen resolution The following snippet will display the user's current screen resolution: ______________________________________________________________________ Tip of the Day! config files are case sensitive Because web.config and machine.config are XML files, they are case sensitive, therefore you'd get an error if you created a web.config file that changes the Debug mode rather than the debug mode. ______________________________________________________________________ Tip of the Day! Improving performance by using output parameters and the ExecuteNonQuery method If the data coming back from a query is a single row, consider using output parameters and the ExecuteNonQuery method to achieve the best performance. Because a DataReader does not have to be created, this method provides better performance. ______________________________________________________________________ Tip of the Day! Friendly HTTP Errors To see more detailed information about HTTP errors, make sure that "Friendly HTTP errors" on the Advanced tab of your Internet Explorer Options dialog is unchecked. _____________________________________________________________________ Tip of the Day! Picking up the value of a meta tag using JavaScript In the following snippet, clicking on "Click" will display "ASPToday": Testing Click ______________________________________________________________________ Tip of the Day! A Basic Web Form Control The following snippet is a very simple example of a Web Form Control. It displays a yellow text box with red text saying "This is a test":
______________________________________________________________________ Tip of the Day! The ServerChange Event The following snippet illustrates the ServerChange event, which occurs when the form is posted back and ASP.NET detects that the content or the state of a control has changed.

______________________________________________________________________ Tip of the Day! NET QuickStarts If you install the .NET Framework SDK then you get a shortcut on your Start Menu that has a shortcut to "Samples and QuickStart Tutorials". These are a series of samples that illustrate .NET syntax, architecture and features, and best practices. ______________________________________________________________________ Tip of the Day! Increasing Performance By Using Stored Procedures That Contain Multiple Select Statements You can write a stored procedure that contains multiple select statements. The results of each select statement will be returned as a collection of recordsets in the Recordset object. The results of the first recordset are immediately accessible via the Recordset object. To access the other results, just use the NextRecordset Method of the Recordset object. This method will clear the current Recordset object and return the next recordset for your use. For example: Create procedure multipleselects AS BEGIN SELECT * FROM table1 SELECT * FROM table2 SELECT * FROM table3 .. SELECT * FROM tableN END Now inside your ASP code: Rs = dbConn.Execute(“exec multipleselects”) ‘ The current RS is the results from SELECT * FROM table1 ‘ Do something with RS ‘ Ready to move to next RS Set rsNextResults = Rs.NextRecordset ‘ Do something with RS .. The value of doing this is an increase in performance on an ASP page where many SELECT statements are called. By doing this you will eliminate trips from the Web Server to the Database Server, which can be very expensive when the Web Server and Database server are not located on the same system. ______________________________________________________________________ Tip of the Day! Using HTTP_USER_AGENT to establish the client's platform type The following code will tell whether a client is running a Windows operating system, a Mac OS or neither: <% ' VBScript strUA = Request.ServerVariables("HTTP_USER_AGENT") If InStr(strUA, "Win") Then Response.Write "This machine is running a Windows operating system." ElseIf InStr(strUA, "Mac") Then Response.Write "This machine is running a Macintosh operating system." Else Response.Write "This platform isn't running either a Windows or a Macintosh " & _ "operating system." End If %> ______________________________________________________________________ Tip of the Day! Accessing Cookies on the Client-Side Cookies are available to client-side JavaScript as a property of the Document Object: Cookies This HTML page tries to find the cookie called "Name". If the cookie is found it produces a greeting: Welcome, "Name" - the "Name" is taken from the cookie. If a cookie is not found then the user is prompted to supply a name, which is then stored in a cookie. ______________________________________________________________________ Tip of the Day! Dim each variable on a separate line When declaring variables it is best to Dim each variable on a separate line. Then you can easily see when you've missed out the data type. For example: Dim timeIn, timeOut As Date would incorrectly assign timeIn as a Variant. A clearer way would be like this: Dim timeIn As Date Dim timeOut As Date ______________________________________________________________________ Tip of the Day! Automatically Refresh your Web Page To automatically refresh your web page insert the following code into the header: This will refresh the page every minute. ______________________________________________________________________ Tip of the Day! A Web Service Cannot Participate In An Ongoing Transaction A Web Service cannot participate in an ongoing transaction. It will always start a new transaction. The Web Service and the client cannot share transaction context. ______________________________________________________________________ Tip of the Day! Web Service Discovery All paths contained within the .vsdisco file are relative to the .vsdisco file location. ______________________________________________________________________ Tip of the Day! Improving Performance When Iterating Through A Recordset When iterating through a recordset, use ADO Field Object to obtain references to fields/columns before you start your iteration: .. Set rs = objConn.Execute(strSQL) ' Create your field references Set fldRef1 = rs("ColumnA") Set fldRef2 = rs("ColumnB") ' Now iterate through the recordset Do Unitl rs.EOF ' Normally you would do this => ' Response.Write ("ColumnA: " & rs("ColumnA") & " ColumnB: " & rs("ColumnB") & "
") ' With field references, you can do this instead which saves you from looking up the reference each time you need it. Response.Write ("ColumnA: " & fldRef1 & " ColumnB: " & fldRef2 & "
") rs.MoveNext Loop .. This will improve your performance instead of seeking the reference each time you need a value as you iterate through the recordset. ______________________________________________________________________ Tip of the Day! Creating a new XML Element If you need to create a new XML Element and add it to an XML document, you can use the createNode method of the XML document object. In this example we add the
element with an address. Set xmlNode = xmldocument.createNode("element", "ADDRESS", "") xmlNode.Text = "8811 Deerland" xmlDocument.appendChild xmlNode ______________________________________________________________________ Tip of the Day! SoapExceptions When exceptions are thrown during a SOAP conversation, those exceptions are passed as SoapException instances, which can be serialized directly into the Body element of a SOAP Message. ______________________________________________________________________ Tip of the Day! It is a good idea to log errors when developing COM objects When you are writing COM objects for use in your ASP web apps, it's a good idea to log errors while developing. In the VB COM DLL, add this line of code: App.LogEvent Err.Description In NT/2000 it will be added to the Event Log where you can monitor it. When you COM object is running smoothly, remove this line as it uses resources. ______________________________________________________________________ Tip of the Day! Using the Isolated Storage Utility Isolated Stores are private areas containing the files and directories of the current logged in user. An Isolated Store can be manipulated by the "System.IO.IsolatedStorage" namespace. The Isolated Storage Command Line Utility (storeadm.exe) can be used to view Isolated Storage information, remove Isolated Storage for the current user and suppress information messages (not error messages). ______________________________________________________________________ Tip of the Day! The web server process (aspnet_wp.exe) automatically recycles itself if the memory usage rises above 60% of the system total. If you are planning on storing a large amount of data or have the potential for a large number of simultaneous users, you might want to be aware of this possibility. The threshold for the restart is configurable through the machine.config file. ______________________________________________________________________ Tip of the Day! Session Variables Can Decrease Performance When using a distributed web server environment, the use of Session variables can decrease performance by not letting the load balancing service work correctly. ______________________________________________________________________ Tip of the Day! Using HttpRuntime.AppDomainAppVirtualPath to prevent dead links When coding Microsoft IIS-based applications we mostly use relative paths to refer to the file resources. At times, when we need to access the root folder, we might need to give a path like this: click here Where asphelp is the web application (virtual directory) name. But when it is moved to a different web server, and we create a new virtual directory, the link will cease to function normally. Under these circumstances, it would be better if we had accessed the virtual directory name using: HttpRuntime.AppDomainAppVirtualPath HttpRunTime.AppDomainAppVirtualPath gets the virtual path of the directory that contains the application hosted in the current application domain. ______________________________________________________________________ Tip of the Day! Password Fields If a user has to type a password on your ASP page use a password field instead of a Text type field, as the password type field displays asterisks instead of the user's password:


Password Form Example
______________________________________________________________________ Tip of the Day! Using Request.UserHostAddress to display the Client's IP address This code snippet shows how you can use Request.UserHostAddress to find the client's IP address:
<%@ Page language="C#" %>


<%String ClientIP;
  ClientIP=Request.UserHostAddress.ToString();
  IP.Text=ClientIP;%>

The Client's IP address is:

______________________________________________________________________ Tip of the Day! The VS.NET Command Window In Visual Studio.NET, the features of the "Command Window" are identical to the Visual Basic "Immediate Window" ______________________________________________________________________ Tip of the Day! Using script tags in ASP.NET The ASP.NET processing engine thinks that it has reached the end of the script when it finds any tag and reports an error. To get round this you can split the tag up, as the following snippet shows: If Not IsNothing(SelectedDate()) Then strOut &= 'var str' & Id() & 'SelectedDay = '' & Format(CDate('#' & SelectedDate() & '#'), 'dd') & '';' & vbCrLf strOut &= 'var str' & Id() & 'SelectedMY = '' & Format(CDate('#' & SelectedDate() & '#'), 'yyyyMM') & '';' & vbCrLf Else strOut &= 'var str' & Id() & 'SelectedDay = ''; ' &vbCrLf & 'var str' & Id() & 'SelectedMY = '';' & vbCrLf End If strOut &= '' strOut &= 'initcal('' & Id() & '');' & vbCrLf lblTest.Text = strOut End If ______________________________________________________________________ Tip of the Day! Adobe SVG Viewer Shortcut If your browser is SVG-enabled using Adobe SVG viewer, you can zoom in and out using CTRL and SHIFT-CTRL respectively. ______________________________________________________________________ Tip of the Day! Disco.exe Included within Visual Studio.NET is the disco.exe tool. This tool dynamically scans an .asmx or .disco file and creates files locally on your computer that correspond to all the Web Services it locates. This tool can be used to locate Web Services on a server, which can then be used feed into a search engine or local repository. This can be helpful if you want to give developers access to information about what Web Services are available without actually giving them access to the Internet. _______________________________________________________________________ Tip of the Day! Obtaining the URL of the current Request In ASP.NET we can find out the URL of the current request by employing the Url property of the Request object: currurl.aspx --------------

When we invoke the above ASP.NET Page the URL of the current Request is displayed in the browser. ______________________________________________________________________ Tip of the Day! System.Web.Hosting namespace The System.Web.Hosting namespace provides the functionality for hosting ASP.NET applications from managed applications outside Microsoft Internet Information Services (IIS). ______________________________________________________________________ Tip of the Day! The TreeView WebControl When working with the TreeView WebControl, the element must be uppercase for the TreeView data bind to work. ______________________________________________________________________ Tip of the Day! CDONTS line length limit The line length is limited to 74 characters when you send a plain text message using CDONTS. If your line is more than 74 characters long, then it will be broken down into several lines. This happens when setting the text property of a CDONTS NewMail object. According to Microsoft this behavior is by design, but it can be resolved by changing the default properties from plain text to MIME. For more information see http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q201352& ______________________________________________________________________ Tip of the Day! Disabling sessions for a specific ASP page If you want to disable sessions for a specific ASP page, while allowing them to be created and used in other pages of the same application, you can add an entry to the ASP processing directive for that page: <%@LANGUAGE='VBScript" ENABLESESSIONSTATE="False"%> ********************************************************************** Tip of the Day! Disabling client-side script in ASP.NET In ASP.NET you can disable client-side script by setting: EnableClientScript='False' **********************************************************************