Miscellaneous Web Snippets

Last Updated: 4/2002

Topics

 

Caching

Where a large amount of processing is required to output a page (e.g. a timetable) it can be marked for placement in an outgoing cache for a specific period of time. Requests for that page will then return that page until the first request following the specified time period which in turn will then be cached again for the specified period.

<%@ OutputCache Duration="timeInSeconds" VaryByParam="*" %>

Items can also be read and written directly from and to the cache:

myStuff = Cache("myKey");
if(myStuff!=null)....
...
Cache("myKey") = myStuff;
Cache.Insert("myOtherKey",myStuff2,null, DateTime.Now.AddHours(1),TimeSpan.Zero);
// Cache.Insert(key, value, dependency, absolute expiry time,
//  time since last accessed expiry time

Back to Topic List 

 

Configuration Files

%Winnt%\Microsoft.NET\Framwork\v...\config\machine.config
overridden by:
   
%wwwroot%\web.config
overridden by:
   
%application%\web.config
overridden by:
    %application\subDir\web.config

Note:
Overriding can be prevented in the location tag of a previous config file by specifying 'allowOverride="false"'. A compilation error will occur if a web.config attempts to override these settings further down.

Back to Topic List 

 

Cookies

Test for an existing cookie by comparing the appropriate entry from Request.Cookies with null, for example:

if (Request.Cookies["myCookie"] == null) ....

A new cookie is created in the same way as any other object:

HttpCookie myCookie = new HttpCookie("cookieName");
cookieName.Values.Add("key", "value");
cookieName.Values.Add("FontSize", "18");

and also has to be added to the collection as normal, although the method name for doing so is non-standard:

Response.Cookies.AppendCookie(myCookie);

Cookies are normally deleted at the end of a session. To make a cookie live beyond that point it's expiry date needs to be set, for example:

myCookie.Expires = DateTime.MaxValue;    // Never expire

Note: Only the first 4096 of a cookie are guaranteed to be stored.

?? How to test to see if cookies are enabled on user's browser? ??

Back to Topic List 

 

E-mail

using System.Web.Mail;

MailMessage myMail = new MailMessage();
myMail.From = "me@me.com";
myMail.To = "you@you.com";
myMail.Subject = "My Subject";
myMail.Body = myMessage;
myMail.BodyFormat = MailFormat.Html;
SmtpMail.Send(myMail);

Note: Haven't tried it because (a) I don't think it will work unless the IIS server is also configured as a SMTP server and (b) the "myMail.Body = myMessage;" line looks like it needs to be fleshed out.

The default regular expression validator shipping with .NET v1.0 is not RFC822 compliant. The following expression is closer:

^([\w\#\$\%\*\+\&\-\.\!\/\=\?\^\`\{\|\}\~]+)@((([\d]{1,3}\.){3}[\d]{1,3})|(([0-9a-zA-Z\-]+\.)+)([a-zA-Z]{2,}))$

Back to Topic List 

 

Getting Session (etc.) Info When Not on a Page

System.Web.HttpContext.Current contains references for the following objected normally access via the Page object:

  • Application
  • Request
  • Response
  • Server
  • Session
  • User

This is very useful to know when working outside of the Page / Control environment.

Back to Topic List 

 

Graphics Server

(Drawing to a bitmap, then returning the image)

  1. Create a bitmap object
  2. Create a graphics object from the bitmap
  3. Use methods of the graphics object to construct the image on the bitmap
  4. Clear the response stream (so that we don't get any frame supplied headers etc. There shouldn't be any yet, but better safe than sorry)
  5. Set the content type (via the response object) to the correct type for the image (there are several possible values depending on whether we are returning an bmp, jpeg, gif etc.)
  6. Save the bitmap to the response stream
  7. Call the End method of the Response object to prevent the framework adding anything.

Example (Note: This is a simplification of the test code I wrote, so may be missing some required libraries etc.):

GraphicsServer.asp (we could place all the code here, but by placing in a code-behind file we get better compile time checking)

<%@Page language="C#" CodeBehind="GraphicsServer.cs" Inherits="MyProject.GraphicsServer" %>

GraphicsServer.cs

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

namespace GraphicsServer {

private void GraphicsServer() {
    // 1. Create a bitmap object
    Bitmap oBitmap = new Bitmap(100,100, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

    // 2. Create a graphics object from the bitmap
    Graphics oGraphics.FromImage(oBitmap);

    // 3. Use methods of the graphics object to construct the image on the bitmap
    oGraphics.FillRectangle(System.Drawing.Brushes.Black, 0, 0, 50, 50);
    oGraphics.FillRectangle(System.Drawing.Brushes.Blue, 50, 0, 50, 50);
    oGraphics.FillRectangle(System.Drawing.Brushes.Green, 0, 50, 50, 50);
    oGraphics.FillRectangle(System.Drawing.Brushes.Yellow, 50, 50, 50, 50);

    // 4. Clear the response stream
    Response.Clear();

    // 5. Set the content type
    Response.ContentType="image/jpeg";

    // 6. Save the bitmap to the response stream
    oBitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);

    // Tidy up
    oGraphics.Dispose();
    oBitmap.Dispose();

    // 7. Call the End method of the Response
    Response.End();
}

}

Back to Topic List 

 

Navigator Object

A browser thing rather than a C# or ASP thing. Supported both in IE & Netscape (although Netscape returns "undefined" for many of these properties). Contains useful properties such as:

  • appVersion / appMinorVersion

  • cookieEnabled

  • cpuClass

  • onLine

  • platform

  • systemLanguage / userLanguage

Back to Topic List 

 

Reading User-Defined Application Settings

Add a reference to the settings file in the main config file (normally web.config for asp projects) using the appSettings tag. Use the add tag to provide default key & value pairs in case the config file you supply is missing (or doesn't specify the requisite key):

<configuration>
        <appSettings file="myFile.config">
                <add key="myKey" value="myValue">
                ...
        </appSettings>
</configuration>

In the file referenced in the above snippet (normally this is called user.config rather than placeholder shown), place overrides for the relevant settings :

<appSettings>
        <add key="myKey" value="myOtherValue">
        ...
</appSettings>

To obtain the value associated with a specific key at run-time, use:

System.Configuration.ConfigurationSettings.AppSettings("myKey");

Back to Topic List 

 

Reading a file through HTTP

System.Net.WebRequest allows web requests to be made programmatically and the results accessed both synchronously and asynchronously. Only files that the user can normally access are available this way. For example, .config files cannot be accessed.

Note that on an intranet it is normally necessary to set the WebRequest's Credentials to the user's default credentials just to be able to access another web-server (note: This is not the same as Windows Authentification). Internet Explorer automatically does this silently after the first failure so this is not typically known.

using System.Net;
...
// Initialise the request (the request is not actually made at this point)
WebRequest myRequest = WebRequest.Create("http://myWebSite/dir1/dir2/file.htm");

// Connect using the user's default credentials - this is just enough to get on
//the network. The user won't be prompted for anything
myRequest.Credentials = CredentialCache.DefaultCredentials;

// Get the file (now the request is made, asynchronously in this case)
WebResponse myResponse = myRequest.GetResponse();

// Convert from a Stream to a StreamReader (so we can do something useful with it)
StreamReader sr = new StreamReader(myResponse.GetResponseStream());

// Do something with the contents of the file
Console.Write(sr.ReadToEnd());

// Tidy-up
sr.Close();
myResponse.Close();

Back to Topic List 

 

Restarting IIS
Enter iisreset at the command line. A remote pc can be specified (iisreset \\somepc). PC can also be rebooted (iisreset /reboot)

Back to Topic List 

 

Security

To obtain the end-user's NT domain login:

  • In IIS, on the Directory Security tab for the directory containing your project select the edit button in "Anonymous access and authentication control" and clear all checkboxes except "Integrated Windows authentication"
     

  • In you C# project, edit Web.Config and change <authentication mode="None"> to <authentication mode="Windows">
     

  • In your code the user name (in the format DOMAIN\UserID) is available in Page.User.Name. If either of the previous steps are missed / cocked-up a blank string is returned in Page.User.Name.
     

Back to Topic List 

 

Smart Navigation

Normally when a page is refreshed the user is returned to the top of the page, the current focus is moved to the first control in the tab order and there is considerable flicker as the display is rebuilt. By adding SmartNavigation="true" to the @Page line, IE5 will leave the page and focus where it is and refresh the form flicker free. This actually makes a lot of difference to the overall refresh effect.

This can be set globally for a site by modifying config.web and adding <pages smartNavigation="true" /> to the <system.web> tag.

There are numerous known difficulties with Smart Navigation and complex web-pages, making it unsuitable for some applications.

Back to Topic List 

 

Unit Class
Use to convert between objects that record their dimensions in different units. For example, a textbox is in points but you have a control next to it that is measures in pixels. Unit is like the Convert class.

Back to Topic List 

 

ViewState

See also: ?? Partially covered elsewhere ??

ASP.NET controls can save their internal state between requests using that control's StateBag's ViewState collection:

protected void SomeControl_Click(Object s, EventArgs e)
    ViewState["ClickTime"] = DateTime.Now().ToString();
....
protected void SomeControl_SomthingElse()
    PrintIWasCalledAt(ViewState["ClickTime"].ToString());

Back to Topic List 

 

Writing to the Response Object

There are several ways to get content directly into the returned "page":

  1. ByteStream (see "Displaying Images from SQL Server")
    --> Response.BinaryWrite(pByte);
     

  2. Streaming (see "Graphics Server")
    Anything that can be saved to a stream can be saved to Response.Stream.
    --> oBitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
     

  3. File
    The contents of a file can be included using Response.WriteFile.
    --> Response.WriteFile(@"c:\myfile.txt");
     

  4. TextWriter
    Reponse.Output returns a TextWriter object which can be written to ?? How! ??

By default the "page" to be returned to the client is completely generated in a server-side buffer until the "page" is complete and then sent to the client. Thus, Response.Clear() will wipe the entire page ensuring a blank starting point for the creation of customised returned results. However, there is a property (BufferedOutput) that can be changed so that the page is sent piece-by-piece to the client as it is constructed. ?? Is it possible to force buffering even on a system with buffering disabled using <%@Page Buffer=true%> ? ??

Response.End()

Note: "Response" is actually "Page.Response", which is a property that points to a HTTPResponse object.

Back to Topic List