********************************************************************** Tip of the Day! by Ajoy Krishnamoorthy When using a dynamic array in your program, use the Erase statement to free the memory used by dynamic arrays: Dim tstArray() ReDim tstArray(5) ' ' code to use the array ' Erase tstArray ********************************************************************** Tip of the Day! by Editor ASPToday If you have any ASP or ASP.NET tips and tricks that you would like to share with your fellow programmers, email john@asptoday.com and I'll add them to ASPToday! ********************************************************************** Tip of the Day! by Ian Vink When you write binary data to the client, and want the client to save as a name you choose and not yourpage.asp, use this code: <% fn = 'MyDoc.doc' Response.AddHeader 'Content-Disposition','attachment;filename=' & fn ... response.binarywrite(binarydata) %> ********************************************************************** Tip of the Day! by Ian Vink In XML, when you are using VBScript, use + instead of & to concatenate strings together, otherwise you'll get an XML parsing error. ********************************************************************** Tip of the Day! by Srinivasa Sivakumar You can find the Common Language Runtime (CLR) version from ASP.NET as follows: <%@ Import Namespace="System" %> ********************************************************************** Tip of the Day! by Editor ASPToday In response to customer feedback, both ASPToday and C#Today now have a new, improved search engine. These new tools are considerably faster than before, and have been designed to be easier to use. As requested by many people, the new tool also includes a boolean search facility. This new search facility makes it easier to find the content that you want from our rapidly expanding libraries of solutions. Don't forget, though, that if you still can't find what you are looking for you can email john@asptoday.com and adam@csharptoday.com for suggestions. ********************************************************************** Tip of the Day! by Sandra Gopikrishna ASP.NET provides us with a server control called 'AdRotator' to display of advertisements: displayad.aspx ---------------------- The advertisement details, such as the picture to be displayed and the website it's pointing to, are contained in a separate XML file, which has the following structure: ads.xml --------------- http://www.csharptoday.com/images/xxxtoday.gif http://www.csharptoday.com/ Go to C#Today C#Today 80 ********************************************************************** Tip of the Day! by Editor ASPToday ASPToday is currently being rewritten. The new version will have a print friendly option to enable articles to be printed easily, but in the meantime, articles can be printed intact by printing in landscape mode. ********************************************************************** Tip of the Day! by Srinivasa Sivakumar The .NET runtime is portable across multiple operating systems, but not all operating systems use the same directory separation character. For example / is used in Unix flavored operating systems and \ is used in DOS/Windows flavored operating systems. So, it's important to know the directory separation character if we're accessing any operating system specific resources. <%@ Import Namespace='System.IO' %> ********************************************************************* Tip of the Day! by Srinivasa Sivakumar You can use this ASP.NET code to determine whether the System Time Zone uses daylight saving time: <% @Import Namespace="System" %> ********************************************************************** Tip of the Day! by Sandra Gopikrishna In ASP.NET the date and time can be represented as a string. The formatting of such a datetime string can be done by employing methods of the DateTime object: dateformat.aspx ---------------

Formatting DateTime String in ASP.NET

Date in Standard Format is :

Date in Short Format is :

Date in long Format is :

Time in Long Format is :

Time in Short Format is :

********************************************************************** Tip of the Day! by Sandra Gopikrishna In ASP.NET we can find out the name of the machine hosting the webserver and executing the current page by employing the 'MachineName' property of the Server object: findmachinename.aspx -------------------------------- ********************************************************************** Tip of the Day! by Sandra Gopikrishna In ASP.NET we can obtain the virtual path of the current request, on the fly, by employing the 'FilePath' property of the Request Object: reqvirtpath.aspx ---------------- ********************************************************************** Tip of the Day! by Sandra Gopikrishna ASP.NET's DataGrid Control can bind to any XML file through Databinding: databind.aspx ------------- <%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.Data" %> ********************************************************************** Tip of the Day! by Sandra Gopikrishna The following piece of C# code is the ASP.NET equivalent of the VBScript function now() of ASP. It should be noted that the namespace System.Globalisation should be included while dealing with date and time values in ASP.NET testnow.aspx ------------ <%@ page language = "c#" %> <%@ import namespace = "System.Globalization" %> <% DateTime dt = DateTime.Now; string now = dt.ToString("f",DateTimeFormatInfo.CurrentInfo); Response.Write(now); %> ********************************************************************** Tip of the Day! by Sandra Gopikrishna The ASP.NET "Request Object" contains a method called "IsAuthenticated" for checking whether a given HTTP Connection is authenticated or not: auth.aspx --------- ********************************************************************** Tip of the Day! by Sandra Gopikrishna In ASP.NET we can save the HTTP Request to disk by employing the 'SaveAs' Method of the Request Object: savehttp.aspx ------------- Note that in the above case there will not be any content in the req.txt file. If the param is set to 'true' then header information will be stored in the req.txt file. ********************************************************************** Tip of the Day! by Sandra Gopikrishna In ASP.NET we can map the virtual path into a physical path by using the MapPath Method of the request object: findpath.aspx ------------- ********************************************************************** Tip of the Day! by Sandra Gopikrishna Sandra Gopikrishna Accessing an already designed Crystal Report from ASP is pretty simple and it involves the following steps: 1. First create a Crystal Report object. It is normally created in a session scope so that it can be used for more than one report: Set session("oApp") = Server.CreateObject("Crystal.CRPE.Application") 2. Open the report by using the Open method of Report Object: Set session("oRpt") = session("oApp").OpenReport(path & reportname, 1) 3. Set the SQLQueryString property of the report object to the sql you wish to execute: session("oRpt").SQLQueryString = cstr(NewSQLQueryString) 4. Finally, load the crystalreportviewer in the browser with the report having the result of the executed query. ********************************************************************** Tip of the Day! by S Bashkar The DataGrid Control of ASP.NET is a versatile server control that can be employed to display tabular data with the added flexibility of selecting editing sorting and paging the data. Adding the DataGrid control to ASP.NET is pretty simple and can be done on the fly by employing the following code snippet: dispdtgrid.aspx --------------- DataGrid Control of ASP.NET

DataGrid Control of ASP.NET

********************************************************************** Tip of the Day! by Editor ASPToday The following code uses the GetLogicalDrives method of the Directory class to display a list of available drives: <%@ Page Language="VB" %> <%@ Import Namespace="System.IO" %> <% Dim Drives() As string Dim Drive As string Drives = Directory.GetLogicalDrives() For Each Drive in Drives Response.Write(drive) Response.Write("
") Next %> ********************************************************************** Tip of the Day! by Editor ASPToday In ASP.NET a hierarchy of directories can be created using a single method call: <%@ Page Language="VB" %> <%@ Import Namespace="System.IO" %> <% Directory.CreateDirectory("C:\one\two\three\four directories") %> ********************************************************************** Tip of the Day! by Sandra Gopikrishna The following example demonstrates a method of obtaining a recordset from the execute method of a connection object, without explicitly creating a recordset in an ASP Page: <%set conn = server.createobject("ADODB.CONNECTION") conn.open "dsn_name", "user_name" , "password" set rs = conn.execute("select * from tab_name") while not rs.eof Response.write rs(0) & "
" rs.movenext wend%> ********************************************************************** Tip of the Day! by Sandra Gopikrishna In ASP.NET we can control the HTTP content type that a server sends back to a client during the request, by employing the ContentType attribute of page directive. The syntax for using this directive is: <%@ Page ContentType="whatever" %> For example, if we want to send xml to the client, the above directive takes this form: <%@ Page ContentType="text/xml" %> ********************************************************************** Tip of the Day! by Srinivasa Sivakumar How to generate a GUID from ASP.NET: <%@ Import Namespace="System" %> ********************************************************************** Tip of the Day! by Ian Vink ASP.NET does not support page-rendering functions, this will require a lot of ASP pages to be re-written. For example: In ASP: <% Sub MyTimeSub() %> Today is <%=Now %> <% End Sub %> <%MyTimeSub%> In ASP.NET, this must be rewritten: <%MyTimeSub()%> ********************************************************************** Tip of the Day! by Sandra Gopikrishna In ASP.NET it is possible to disable the default session state (VIEWSTATE) for a particular control by employing the MaintainState attribute for the control. The following snippet demonstrates a method of disabling the VIEWSTATE for a particular control: ********************************************************************** Tip of the Day! by Sandra Gopikrishna The following ASP.NET snippet demonstrates a method of iterating through all the rows and columns of a data table. .................. 'construct a DataTable say dttab. For Rowcnt = 0 To dttab.Rows.Count - 1 For Colcnt = 0 To dttab.Columns.Count - 1 'the data can be accessed by 'dttab.Rows.Item(Rowcnt).Item(Colcnt) Next Next ................... ********************************************************************** Tip of the Day! by S Bashkar The following ASP.NET tip demonstrates a method of validating the email address entered by the user employing the RegularExpressionValidator and RequiredFieldValidator provided with ASP.NET. emailvalidate.aspx ------------------ <%@ Page Language="VB" %>
Enter Your Email ID Here

*Ensure that email id is in proper >format
*Email is mandatory
Email :
 
********************************************************************** Tip of the Day! by Ian Vink You can use simple binary math using ANDs to maintain a small setting variable. In this example we'll include pieces of a sandwich into one value. <% 'Incease values by doubling each time Butter = 1 Jam = 2 Bread = 4 PeanutButter = 8 'And so on..... 'Add all but the PeanutButter to the Sandwich options list Sandwich = Butter + Bread + Jam 'See what elements they have stored in the Sandwich If eval(Sandwich AND Bread) = Bread then response.write "Has Bread!
" If eval(Sandwich AND Jam = Jam) then response.write "Has Jam!
" If eval(Sandwich AND PeanutButter) = PeanutButter then response.write "Has Peanut Butter!
" %> As you can see from this example, in one small variable, we've stored a number of variables. ********************************************************************** Tip of the Day! by Srinivasa Sivakumar How to find the System Time Zone from ASP.NET: <% @Import Namespace="System" %> ********************************************************************** Tip of the Day! by Ian Vink You can use this code to get a list of all your Path variables running on the IIS server. This could be handy in finding the paths on your web hosting server to required resources. <% Set WshShell = server.CreateObject( "WScript.Shell" ) sPath = WshShell.ExpandEnvironmentStrings("%PATH%") oPath = split(sPath,";") for x = 0 to ubound(oPath) Response.Write oPath(x) & "
" next %> ********************************************************************** Tip of the Day! by Ian Vink If you need to add a column to a table you can do it with a simple SQL call in your ASP page. This example will add the column NumKids as an Integer and allow the field to be NULL. 'Assuming cn is an ADODB connection object and is open and the account has rights to alter the 'table (SQL Server) <% 'connection info here.... cn.execute "ALTER TABLE tblClient ADD NumKids INT NULL" %> ********************************************************************** Tip of the Day! by Ian Vink You can use a little trick to find the home folder of your web application. Sending the MapPath method of the Server object a forward or back slash: <%= server.mappath("\")%> would give you the path: "C:\INETPUB\WWWROOT" if that is the base path to your web application. ********************************************************************* Tip of the Day! by Sandra Gopikrishna In ASP.NET we can find out whether the current request created a new session, or not, by employing the 'IsNewSession' property of the session object: sessstat.aspx -------------- ********************************************************************** Tip of the Day! by Srinivasa Sivakumar If a shared member's value is changed in one instance of the class, then the change will reflect in all the instances of the class. Here is an example: <% @Import Namespace="System " %> You'd get the result as; Value of I is: 20, 20 Value of I is: 40, 40 ********************************************************************** Tip of the Day! by Srinivasa Sivakumar How to find all the logical drives in the system from ASP.NET: <%@ Import Namespace="System" %> ********************************************************************** Tip of the Day! by Sandra Gopikrishna In ASP.NET we can find out the language preferences of the client by employing the 'UserLanguages' property of the Request Object. This property returns an array of all the language preferences of the client in the form of an array: clientlang.aspx ================ ********************************************************************** Tip of the Day! by Sandra Gopikrishna In ASP.NET we can write the content of a file directly to the output stream by using the writefile property of response object. The following ASP.NET snippet displays the content of any specified file on the client browser: writefilecont.aspx ------------------ <%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.Data" %> The above example assumes that the file 'test.txt' is present in the same directory as writefilecont.aspx ********************************************************************** Tip of the Day! by Sandra Gopikrishna ASP.NET exposes the DNS Name of the remote client to the developer by the property 'UserHostName'. The following code snippet demonstrate the method of finding out the DNS Name of the Remote Client in an ASP.NET Page remotdns.aspx ----------------- ********************************************************************** Tip of the Day! by Sandra Gopikrishna In ASP.NET we can find out the number of values stored in a session by using the 'count' property of the session object. The following short snippet demonstrates the method of counting the number of values present in the session. countsessval.aspx ----------------- ********************************************************************** Tip of the Day! by Sandra Gopikrishna In ASP.NET images can be manipulated on the server side by employing the Server Control. This server Control gets rendered as an Control in the clients browser: dispimg.aspx ------------ In the above code segment the path of the image is specified by the attribute ImageURL while the AlternateText attribute specifies the text that needs to be displayed if the image is not shown on the page. ********************************************************************** Tip of the Day! by Sandra Gopikrishna Sometimes we need to check whether page tracing is enabled or not in an ASP.NET page and based on this we may have to take an action. The following ASP.NET snippet demonstrates a method of checking whether tracing is enabled or not: <%@ Page Language = "Vb"%> <% if Trace.isEnabled Then Response.write("Page Tracing is enabled in the following asp.net pahe") else Response.write("Page Tracing is not enabled in the following ASP.NET Page") end if %> ********************************************************************** Tip of the Day! by Sandra Gopikrishna In ASP.NET we can find out the MIME Content type of the incoming request by employing the 'ContentType' property of the Request Object: findcont.aspx -------------

Click the Submit Button to get the MIME Type of current Request

********************************************************************** Tip of the Day! by Sandra Gopikrishna The following ASP.NET snippet demonstrates a method of databinding the Listbox control to an XML File: emp.xml ------- bill 21
7 ivory coast street California USA
Systems Analyst
John 26
8 ivory coast street California USA
Senior Systems Analyst
lbox.aspx ----------- <%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.Data" %> Databinding a list box to XML File
********************************************************************** Tip of the Day! by Sandra Gopikrishna The Repeater control of ASP.NET can be employed to display values that are repeated, such as values in a recordset, by specifying a template. The following code demonstrates a method of using the Repeater control to display values from a hashtable by means of databinding. databindrpt.aspx -------------------------

DataBinding Repeater to a Hashtable

<%# Container.DataItem.Key %> <%# Container.DataItem.Value %>
********************************************************************** Tip of the Day! by Editor ASPToday ASPToday's 800th Article! The Living Book archive at ASPToday contains 800 articles, covering ASP 3.0, ASP.NET, SQL Server, Web Site Security, Web Services, and many more ASP and web related subjects. If our vast archive does not contain what you need, email us at mailto:editor@asptoday.com to let us know. ********************************************************************** Tip of the Day! by Sandra Gopikrishna In ASP.NET page tracing can be enabled by setting the "TRACE" option of the page directive to "TRUE". Page-level tracing allows us to write debugging statements to the client page as part of the output. This can be done using the "Trace.Write" and "Trace.Warn" methods, passing a category and message for each statement. pagetrace.aspx -------------- <%@ PAGE TRACE = "TRUE" LANGUAGE = "VB" %> <% dim x as string x = "10" Trace.Write("myTrace",x) x = "20" Trace.Warn("mytrace warning",x) %> When the above page is run, the content of x is written to the page as part of client output. Note that the content output resulting from Warn method of trace is displayed in red color on the screen. ********************************************************************** Tip of the Day! by Sandra Gopikrishna In ASP.NET we can retrieve browser details by using Request.UserAgent: useragdet.aspx -------------- ********************************************************************** Tip of the Day! by Sandra Gopikrishna The server control of ASP.NET can be employed to display TextBox, TextArea and Password controls on the client's browser by setting its TextMode property accordingly. To display TextBox controls on the client do not set the TextMode property. If we want to display TextArea controls on the client's browser set its TextMode Property to "multiline". Set this property value to "Password" to display Password control. textdisp.aspx ===========

Text Box Control Goes here


TextArea Control Goes here


Password Control Goes here

********************************************************************** Tip of the Day! by Sandra Gopikrishna Using 'Autopostback' to return control to the server and execute a subroutine In ASP.NET CheckBox Server control has a property called 'Autopostback' which we can use to return the control to the server and execute a subroutine specified in the 'OnCheckChanged' event in the CheckBox: autochk.aspx ==========

********************************************************************** Tip of the Day! by Sandra Gopikrishna ASP.NET server controls allow us to set the values of user controls on the server side. Using this technique we can add the values to a drop down list box at Runtime, which used to be an impossible task for an ASP Developer. dropdownlist.aspx ===============
********************************************************************** Tip of the Day! by Sandra Gopikrishna Using 'Autopostback' to return control to the server and execute a subroutine In ASP.NET CheckBox Server control has a property called 'Autopostback' which we can use to return the control to the server and execute a subroutine specified in the 'OnCheckChanged' event in the CheckBox: autochk.aspx ==========

********************************************************************** Tip of the Day! by Sandra Gopikrishna The following snippet demonstrates a method of looping through all the server variables in ASP.NET by accessing the ServerVariables collection of the request object. loopservervar.aspx ------------------ ********************************************************************** Tip of the Day! by Sandra Gopikrishna In ASP.NET we can create our own datatables, with the required number of columns, on the fly by employing ADO.NET. The following snippet demonstrates a method of creating your own data tables in ASP.NET. It should be noted that the namespace System.Data should be imported for creating such data tables. createdttab.aspx ---------------- <%@page language = "VB" DEBUG = "TRUE"%> <%@ Import namespace="System.Data" %> <% Dim mydttab As New DataTable Dim myRow As DataRow Dim i As Integer ' Create Columns mydttab.Columns.Add(New DataColumn( "Column1", GetType(String) ) ) mydttab.Columns.Add(New DataColumn( "Column2", GetType(String) ) ) ' Add Rows here For i = 0 To 2 myRow = mydttab.NewRow() myRow("Column1") = "column1-item" & i.toString() myRow("Column2") = "column2-item" & i.toString() mydttab.Rows.Add(myRow) Next 'Display All the Rows of our created table For each myRow in mydttab.Rows Response.Write( myRow( "Column1" ).toString() & "
" ) Response.Write( myRow( "Column2" ) & "
" ) Next %> ********************************************************************** Tip of the Day! by Sandra Gopikrishna URLENCODING and HTMLENCODING of strings can be done on the fly in ASP.NET by employing the inbuilt functions UrlEncode and HtmlEncode. It should be noted that the ASP.NET pages make use of the namespace "System.Web.HttpUtility" for the purpose of above mentioned encoding. The following ASP.NET code demonstrates the method of URLEncoding and HTMLEncoding: demoencode.aspx --------------- <%@ Page Language="VB" %> <%@ Import Namespace="System.Web.HttpUtility" %> <% 'URLEncoding Demonstrated Dim strURL as String = "next.aspx?param1=1¶m2=2" Dim strURLEncodedText As String = UrlEncode(strURL) Response.write("The URL Encoded Text is
") Response.write(strURLEncodedText & "
") 'HtmlEncoding Demonstrated Dim strHTML As String = "Text within Bold Tag" Dim strHTMLEncodedText As String = HtmlEncode(strHTML) Response.write("The HTML Encoded Text is
") Response.write(strHTMLEncodedText & "
") %> ********************************************************************** Tip of the Day! by Ian Vink You can use this code sample to find the number of hours and minutes, properly formatted, between 2 times: <% time1 = now() time2 = "4-june-2001 05:05pm" DeltaMin = DateDiff("n",time2,time1) HHMM = (DeltaMin \ 60) & ":" & ABS(DeltaMin MOD 60) response.write HHMM %> ********************************************************************** Tip of the Day! by Sandra Gopikrishna ASP.NET Contains a special file called config.web, in which the configuration of the ASP.NET web application can be stored. This config.web file can be conveniently used to store the DSN information used to access a database and this DSN Name can be accessed in all ASP.NET Pages. The following piece of code demonstrates the method of accessing the DSN present in the config.web file from an ASP.NET Page. ********************************************************************** Tip of the Day! by Neal Pandey Using this code you can write data from a form to a text file. The function WriteTextFile will create a text file if it does not already exist. <% ' Function for creating and appending text file Function WriteTextFile(strFile, strText) Const fsoForAppend = 8 Dim objFSO Set objFSO = Server.CreateObject("Scripting.FileSystemObject") ' Open the text file. Create parameter is true. This will create a file if it does not exist Dim objTextStream Set objTextStream = objFSO.OpenTextFile(strFile, fsoForAppend, True) ' Write the contents to the text file objTextStream.WriteLine strText ' Close the file and clean up objTextStream.Close Set objTextStream = Nothing Set objFSO = Nothing End Function Wtext = Request.Form("Email") 'TO DO : Modify the name of the form field WriteTextFile "d:\email.txt", Wtext 'TO DO : Modify the path of the file. Response.Redirect "thanks.htm" 'TO DO : Modify the path of the thank you page %> ********************************************************************** Tip of the Day! by Sandra Gopikrishna The Request Object in ASP.NET contains a method called "IsSecureConnection" for checking whether the given HTTP Connection is secured or not. The following script demonstrates a method of finding out the security status of HTTP Connection: **********************************************************************