Posts tagged C#

Small Update

Posted in Blog.

Finally got round to fixing an issue where a 404 was being recorded as error.  Should save some disk space :)  I've also added a new friend link for Greg and Jen who are off traveling round the world.

Hopefully this will inspire me to get my ass in gear and do a bit more work on my blog and maybe even write some blog posts! One thing I really want to do is update the design and javascript so when I post code it fits on the page and is syntax highlighted automatically.

Tags: C# , Blog , elmah

Caching File Contents with CacheDependency

Posted in .Net.

The CacheDependency will monitor a file or folder for changes. When it detects a change it will remove the associated key from the cache.

This comes in quite handy for my hangman game which stores the film titles in an xml file.

Below is how I cache the data and setup the CacheDependency. Some validation has been removed to keep it clear.

private HangmanGameCollection ReadGameFile()
{
    if (HttpRuntime.Cache["HangmanGame"] != null)
    {
        return (HangmanGameCollection)HttpRuntime.Cache["HangmanGame"];
    }

    HangmanGameCollection hangmanGames;

    FileInfo xmlFile = new FileInfo(Server.MapPath("~/TopSecret.xml"));

    XmlSerializer xmlSerializer = new XmlSerializer(typeof(HangmanGameCollection));

    using (FileStream fileStream = xmlFile.OpenRead())
    {
        hangmanGames = (HangmanGameCollection)xmlSerializer.Deserialize(fileStream);

        // Put it in cache with a dependency on the xml file
        HttpRuntime.Cache.Insert("HangmanGame", hangmanGames, new CacheDependency(xmlFile.FullName));
    }

    return hangmanGames;
}

private HangmanGameCollection ReadGameFile()
{
    if (HttpRuntime.Cache["HangmanGame"] != null)
    {
        return (HangmanGameCollection)HttpRuntime.Cache["HangmanGame"];
    }

    HangmanGameCollection hangmanGames;

    FileInfo xmlFile = new FileInfo(Server.MapPath("~/TopSecret.xml"));

    XmlSerializer xmlSerializer = new XmlSerializer(typeof(HangmanGameCollection));

    using (FileStream fileStream = xmlFile.OpenRead())
    {
        hangmanGames = (HangmanGameCollection)xmlSerializer.Deserialize(fileStream);

        // Put it in cache with a dependency on the xml file
        HttpRuntime.Cache.Insert("HangmanGame", hangmanGames, new CacheDependency(xmlFile.FullName));
    }

    return hangmanGames;
}

Should maybe do something about fitting in long lines of code :\

Tags: C# , Development , Cache , Hangman

Showing 1 to 2 of 2