Blog

CSS Image Preloading

Here is a way to preload images that will be used in a page with just plain old CSS, no JavaScript required.

Example Code: CSS Selector

div#ImageLoader {display:none}



Example Code: HTML

21 <div id=“ImageLoader”>

22 <img src=http://www.mysite.com/images/home_hover.jpg&#8221; width=“1” height=“1”/>

23 <img src=http://www.mysite.com/images/coin_hover.jpg&#8221; width=“1” height=“1”/>

24 <img src=http://www.mysite.com/images/logout_hover.jpg&#8221; width=“1” height=“1”/>

25

26

JavaScript Image Preloading

Here are various JavaScript methods for preloading images you will be using in a webpage. Its up to you to decide when the right time to use it.

Code Example: Single Image

var homeRollOver = new Image(250,250);
homeRollOver.src = "/images/home_hover.jpg"


Code Example: Multi-Image

var imageDir = "/images/";
var images = new Array;

images[0] = new Array("home_hover.jpg",250,250);
images[1] = new Array("blocked.jpg",64,64);
images[2] = new Array("sun_icon.jpg",128,128);

var imageCache = loadImages(imageDir,imageCache);

function loadImages(path,images) {
var imageCache = new Array;
for (var i=0; i<images.length; i++){
imageCache[i] = new Image(images[i][1],images[i][2]);
imageCache[i].src = (path + images[i][0]);
}
return (imageCache);
}

C# GZip/Zip Compression/Decompression

Simple zip compression in C#:

private static void ZipCompress()
{
const string srcFile = “DataFile.xml”;
const string desFile = “Compressed.zip”;

FileStream fsIn = null;
FileStream fsOut = null;
GZipStream gzip = null;
byte[] buffer;

try
{
fsOut = new FileStream(desFile, FileMode.Create, FileAccess.Write, FileShare.None);
gzip = new GZipStream(fsOut, CompressionMode.Compress, true);

fsIn = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read);
buffer = new byte[fsIn.Length];
fsIn.Read(buffer, 0, buffer.Length);
fsIn.Close();

gzip.Write(buffer, 0, buffer.Length);
}
catch (Exception ex)
{
System.Diagnostics.Debug.Assert(false, ex.ToString());
}
finally
{
if (gzip != null)
gzip.Close();
if (fsOut != null)
fsOut.Close();
if (fsIn != null)
fsIn.Close();
}
}

Simple zip decompression in C#:

private static void ZipDecompress()
{
const string srcFile = “Compressed.zip”;
const string desFile = “Decompressed.xml”;

FileStream fsIn = null;
FileStream fsOut = null;
GZipStream gzip = null;
const int bufferSize = 4096;
byte[] buffer = new byte[bufferSize];

try
{
fsIn = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read);
fsOut = new FileStream(desFile, FileMode.Create, FileAccess.Write, FileShare.None);
gzip = new GZipStream(fsIn, CompressionMode.Decompress, true);
while (true)
{
int count = gzip.Read(buffer, 0, bufferSize);
if (count != 0)
fsOut.Write(buffer, 0, count);
if (count != bufferSize)
break;
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.Assert(false, ex.ToString());
}
finally
{
if (gzip != null)
gzip.Close();
if (fsOut != null)
fsOut.Close();
if (fsIn != null)
fsIn.Close();
}
}

ASP.net Retrieving Embedded Resources with WebResource.axd

Say we are building a ASP.net Server Control which contains a lot of images, style sheets and its own .htm help files which also reference several images of their own. This can create a lot of clutter when it comes to packaging and deploying the Server Control. Also due to the many files and folders which categorize and hold all of those images, style sheets and help files there is always the possibility a curios developer using your Server Control might try to rearrange things or substitute content of their own thus breaking the control or maliciously altering the control. In order to clean all this up and solve a lot of these issues in a single blow we can simply embed all these resources right into our assembly (.dll). By doing this we tightly package all resources used by the Server Control and can potentially limit our deployment to just a single assembly (.dll).

So how do we do this? It’s quite easy just follow the steps outlined below.

Step 1: You need to decide which resources you want to have embedded in the assembly. In the example project I chose to embed the style sheet (FancyButtonStyle.css) which defines the way my FancyButton will look as well as the Solution Explorerbackground image (Thundercats.pnd) that is defined within the style sheet. You embed them into the assembly by selecting the file in the Solution Explorer and viewing the properties of the file. In the Properties window there is a property ‘Build Action’ set it to Embedded Resource.

Step 2: Next each of those embedded resources need to be declared in the AssemblyInfo.cs file. Using the WebResource keyword you place the fully qualified path to the resource you are embedding as the first parameter then as the second the mime-type. The third parameter defines whether or not substitution needs to take place within the newly defined resource. What this means is that within resources of mime-type “text” you can define script tags which also define that there are embedded resource url’s within the file. For example within the style sheet ‘FancyButtonStyle.css’ we defined a background-image which has a url property of another embedded resource, the Thundercats.png file. The PerformSubstitution tells .net to parse through the text resources after it is pulled from the assembly and look for script tags which hold the names of embedded resources which need to have their URL generated and inserted into the document. (see thumbnails: AssemblyInfo.cs, Stylesheet)

Step 3: Now write the code within your control’s RenderContents method which will pull out the embedded resources’ URL’s and use them within the HTML to be rendered for the control. (see thumbnail: Render Contents Method)

Solution Explorer
Solution Explorer
Render Contents Method
Render Contents Method

AssemblyInfo.cs
AssemblyInfo.cs
Stylesheet
Stylesheet

C# Singleton Pattern

The Singleton Design Pattern is the standard way programmers create classes which are designed to have one and only one instantiation at any point in time. These classes can be used for configurations or settings objects which are globally available and which need to maintain state when being read or updated by various portions of the application.

This is accomplished by making the class Constructor private so that it cannot be accessed. This stops the class from being instantiated by code external to the class itself. Then a public property is exposed which retrieves a reference to an existing instance of the class stored in a local variable or if an instance does not yet exist the class creates a new instance and saves the reference for later calls.

Example Code:

1 public sealed class MySingleton

2 {

3 private static volatile MySingleton instance;

4 private static object syncer = new Object();

5

6 private MySingleton() { }

7

8 public static MySingleton Instance

9 {

10 get

11 {

12 if (instance == null)

13 {

14 lock (syncer)

15 {

16 instance = new MySingleton();

17 }

18 }

19 return instance;

20 }

21 }

22 }

C# Yield Return in IEnumerable

Stop worrying about all the extra collections and sub-collections you have to create when you search a collection for those objects fitting certain criteria. We all do it on a daily basis, we create methods to search collections for all objects which fit certain criteria and we copy the located objects to a new temporary holder collection. Once the method has finished searching the entire source collection it then returns the temporary holder collection as its result.

Example Code:
private List GetPeopleWithSameName(string name, List srcPeople)
{
    List tempList = new List();
    foreach(Person p in srcPeople)
    {
        if(p.FirstName.Equals(name))
            tempList.Add(p);
    }
    return tempList;
}

What if we didn’t have to worry about creating and maintaining those temporary holder collections in our methods? What if we could get one of those located object at a time, at the very time it is found and pass it off for processing without waiting for the entire collection to be searched? Thanks to the new Yield Return construct we can.

How it works: When the .Net compiler sees the Yield Return construct it creates a nested private class which implements the IEnumerable, IEnumerator and IDisposable interfaces. This dynamically created class is pretty much a utility that maintains the state of your enumeration through the collection you are searching. Because this class tracks the state of the enumeration the method you created can return each object it finds which matches the criteria you set, and it returns it at the moment it finds it. Now we can compress our method as shown below.

Example Code:
private List GetPeopleWithSameName(string name, List srcPeople)
{
    foreach(Person p in srcPeople)
        if(p.FirstName.Equals(name))
            yield return p;
}