Code Tips and Tricks (RSS)

Code Tips and Tricks

Do You Hate Having to Use a CD to Extract ISO's

Here is a great tool you can use to extract images without neeeding a burner.

Mounting ISO files virtually
The following tool for Windows XP allows image files to be mounted virtually as CD-ROM devices. This tool is provided here for your convenience, and is unsupported by Microsoft Product Support Services.

Taken from http://msdn.microsoft.com/subscriptions/faq/default.asp (do a search on ISO)

Note: I have had this working not only on XP, but 2003 and 2000.

Ahh, Finally - Turn off the shutdown tracker in Windows 2003

Andrew tells us how to disable the most annoying thing for me that is by default enabled in Windows 2003-“shutdown tracker“

Code Tip: Manually Setting the Path to WebUIValidation.js

We're currently working on a web project where we were forced to distribute aspnet_client for validation because one version of the project runs within Cassini web server. Hence there would be an exception when trying to find WebUIValidation.js using the default location. The default location is always in the web root and we needed it to be a directory within the actual application. After much searching and coming up with nothing I decided to analyze machine.config and found where the path is set. Eventhough, it's not documented I decided to throw the same tag into the Web.Config for the application (changing the path to what i needed) and behold - it worked.

So here is what it came down to:

<system.web>

<webControls clientScriptsLocation="aspnet_client/system_web/1_1_4322/"/>

</system.web>

Hope this helps out someone some day.

Some DotNetJunkies Blogs Were Down

In case you were wondering why ScottW tells us. All are good now! A big thanks to Scott for resonding so quickly.

Creating a Base Page Class? Read this First!

The ASP.NET Page Object Model

One Day in the Life of an ASP.NET Web Page

Dino Esposito
Wintellect

August, 2003

Applies to:Microsoft® ASP.NET

Summary: Learn about the eventing model built around ASP.NET Web pages and the various stages that a Web page experiences on its way to HTML. The ASP.NET HTTP runtime governs the pipeline of objects that transform the requested URL into a living instance of a page class first, and into plain HTML text next. Discover the events that characterize the lifecycle of a page and how control and page authors can intervene to alter the standard behavior. (6 printed pages)

http://msdn.microsoft.com/asp.net/?pull=/library/en-us/dnaspp/html/aspnet-pageobjectmodel.asp#aspnet-pageobjectmodel_topic2

Finally Enabled HTTP Compression in IIS 6.0. Here's How I Did it!

Here are the steps to enable GZIP compression in IIS 6.0.

First Go here: http://dotnetjunkies.com/weblog/donnymack/posts/876.aspx  - Make sure to follow the instructions to the T.

In the final step you're going to be editing the metabase.xml file (IIS 6.0 Metabase) BACKUP FIRST. I was interested in finding out all the properties here and this is what I found. First, the entry for GZIP compression:

<IIsCompressionScheme Location ="/LM/W3SVC/Filters/Compression/gzip"
  HcCompressionDll="%windir%\system32\inetsrv\gzip.dll"
  HcCreateFlags="1"
  HcDoDynamicCompression="TRUE"
  HcDoOnDemandCompression="TRUE"
  HcDoStaticCompression="TRUE"
  HcDynamicCompressionLevel="10"
  HcFileExtensions="htm
   html
   txt"
  HcOnDemandCompLevel="10"
  HcPriority="1"
  HcScriptFileExtensions="asp
   dll
   exe
   aspx"
 >
</IIsCompressionScheme>

I'll just go over some of the attributes I found useful.

  • HcDoDynamicCompression: Specifies whether dynamic content should be compressed.
    important Important  Because dynamic content is by definition always changing, IIS does not cache compressed versions of dynamic output. Thus, if dynamic compression is enabled, each request for dynamic content causes the content to be compressed. Dynamic compression consumes considerable CPU time and memory resources, and should only be used on servers that have slow network connections, but CPU time to spare.
  • HcDoStaticCompression: Secifies wheter static content should be compressed
  • HcDoOnDemandCompression: specifies whether static files, such as .htm and .txt files, are compressed if a compressed version of the file does not exist. If set to true and a file doesn't exist the user will be sent an uncompressed file while a background thread creates a compressed version for the next request.
  • HcDynamicCompressionLevel: VAL(1-10) specifies the compression level for the compression scheme, when the scheme is compressing dynamic content. Low compression levels produce slightly larger compressed files, but with lower overall impact on CPU and memory resources. Higher compression levels generally result in smaller compressed files, but with higher CPU and memory usage.
  • HcFileExtensions: indicates which file name extensions are supported by the compression scheme. Only static files with the specified file extensions are compressed by IIS. If this setting is empty, no static files are compressed.
  • HcScriptFileExtensions: indicates which file name extensions are supported by the compression scheme. The output from dynamic files with the file extensions specified in this property are compressed by IIS.

More Information on these settings and others: http://msdn.microsoft.com/library/en-us/iisref/htm/AlphabeticMetabasePropertyList.asp?frame=true#H - if this doesn't bring you to the H section - that's where you'll find everything.

 

Response Filter to Take out White Spaces and New Line Feeds using HttpResponse.Filter

I wanted to make a quick way to make every page of our new sites smaller. I was thinking we'll have to start formatting all of our HTML but that would make it nearly unreadable for us to develop with and then I remembered the Filter property of the HttpResponse object so I started investigating and found this article http://www.aspalliance.com/robertb/articles.aspx?articleId=6&print=true by Robert Boedigheimer and I was on my way.

Here is what I came up with to take out all tabs and new line feeds. After testing pages were definately smaller and rendering was quicker. If someone has a better way please let me know:

Implementation

Implementation is done application wide in my base page class' OnInit method which all webforms inherit from:

this

.Response.Filter = new Base.ResponseFilter(Response.Filter);

Response Filter Class File

using System.Text;
using System;
using System.Text.RegularExpressions;
using System.IO;

namespace CodeJunkies.Base {

 public class ResponseFilter : Stream {
 
  #region properties
 
  Stream responseStream;
  long position;
  StringBuilder html = new StringBuilder();
 
  #endregion
 
  #region constructor

  public ResponseFilter(Stream inputStream) {
 
   responseStream = inputStream;
 
  }
 
  #endregion

  #region implemented abstract members
 
  public override bool CanRead {
   get { return true; }
  }

  public override bool CanSeek {
   get { return true; }
  }

  public override bool CanWrite {
   get { return true; }
  }

  public override void Close() {
   responseStream.Close();
  }

  public override void Flush() {
   responseStream.Flush();
  }
 
  public override long Length {
   get { return 0; }
  }

  public override long Position {
   get { return position; }
   set { position = value; }
  }

  public override long Seek(long offset, System.IO.SeekOrigin direction) {
   return responseStream.Seek(offset, direction);
  }

  public override void SetLength(long length) {
   responseStream.SetLength(length);
  }

  public override int Read(byte[] buffer, int offset, int count) {
   return responseStream.Read(buffer, offset, count);
  }
 
  #endregion

  #region write method
 
  public override void Write(byte[] buffer, int offset, int count) {
 
   // string version of the buffer
   string sBuffer = System.Text.UTF8Encoding.UTF8.GetString(buffer, offset, count);

   // end of the HTML file
   Regex oEndFile = new Regex("</html>", RegexOptions.IgnoreCase);
   if (oEndFile.IsMatch(sBuffer)) {
   
    // Append the last buffer of data
    html.Append(sBuffer);
   
    string tempResponse = html.ToString();
  
     string newBuffer = Regex.Replace(tempResponse, "\t", string.Empty );
     newBuffer = Regex.Replace(newBuffer, "\n", string.Empty );
     newBuffer = Regex.Replace(newBuffer, "\r", string.Empty );
     newBuffer = Regex.Replace(newBuffer, "<!--", "<!-- \n" );
     newBuffer = Regex.Replace(newBuffer, "// -->", "// --> \n" );
     
     tempResponse = newBuffer;
  
    byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(tempResponse);
   
    responseStream.Write(data, 0, data.Length);
  
   }
   else {
    html.Append(sBuffer);
   }
  
   }
  
   #endregion
  
  }
 }

 

Web Services Tip: When to Use and When not to Use

This is a very simple tip and a rule that you should live by MOST of the time. Of course a situation always arises when you need to do something that is not recommend, but in general this rule should be followed:

When to Use XML Web Services

Application to Application Communication

When not to Use XML Web Services

Intra-Application Communication

That's it, that's the tip. It may seem obvious, but I've seen XML Web Services used in the wrong way more than once so I know it's not!

Until next time!

More Information on Web Services:

http://msdn.microsoft.com/webservices/default.aspx
http://www.dotnetjunkies.com/quickstart/aspplus/
http://www.dotnetjunkies.com/tutorial/default.aspx?tid=6
http://www.dotnetjunkies.com/Search/?exSearchPhrase=Web%20Services

Solution Design (Class Structure)

This really isn't a tip, more of a peeve I have. I hate when I pick up someone elses solution and find that there are multiple classes contained in one code file. It is uterly annoying and difficult to find things. I suggest creating a seperate file for each class and name you code files the same as your class definitions. Additionally, create a file structure which corresponds with your namespace definitions.

Tip: If you happen upon a solution where you're having a tough time finding things use the Visual Studio.NET's object explorer:

  1. Hit Ctrl+Alt+J, this will open up the solution in the object explorer.
  2. Now you have a treeview look at your project's namespaces
  3. Drill down to a class and select it
  4. In the right pane right-click on a method name and click "Go to Definition" and you're magically taken to the projects class to the line where that method is defined.

Now for some feedback from you:

Question:  In a logical 3-tier solution how do you define you project hierarchy? Do you keep everything in one project, do you have multiple projects and if so how do you name them. Do you have a well defined folder hierarchy within each project etc. I'll release my hierarchy I typically use after I see what others use. Oh, and why do you choose the way you do it? Is it something you learned or something you developed?

The First of Many Posts

I just started a new category for my blog named ASP.NET Best Practices. As I stated in another entry I'm putting together a bible of best practices for ASP.NET development. Until it's finished I'm going to be posting a new tip everyday. After it's finished I'll post the document and it will become a living document. If you have a tip respond to one of my tips and I'll add it. Now some of these tips are pretty obvious, but that is exactly why I'm keeping them in. Because they're so obvious they're often overlooked.

General Coding Tips

Use Code Regions: When using Visual Studio.NET or Visual Studio.NET 2003 you can specify code regions. Code regions are basically blocks of code that you can collapse within the Visual Studio IDE. What code regions enable you to do is group related pieces of code together which makes things easier to find. For instance, I typically will group all my properties for a class within a Properties code region.

The way you specifiy a region is a little different between C# and VB. Let's take a look:

Visual Basic .NET

#Region " P R O P E R T I E S "

Public MyProp As String

#End Region

C#

#region P R O P E R T I E S

public string MyProp;

#endregion

There are a couple rules to using Regions.

1.) Regions must have a starting and ending directive
2.) They can be nested
3.) They can't overlap other block statements