Archive for January, 2009

Xml Serializable Session (Dictionary)

January 8, 2009

In my recent (c#) project, I need save something in a session (or dictionary) and I need save the session into a standard xml document.

XmlSession session = new XmlSession();

session["string"] = "I'm a string";

session["number"] = 42;

// Any object. Make sure it can be serialize to a standard xml document.
session["object"] = new MyObject("obj", 100, DateTime.Now);

using (Stream stream = File.Create("session.xml"))
{
session.Serialize(stream);
}

using (Stream stream = File.OpenRead("session.xml"))
{
session = XmlSession.Deserialize(stream);
}

// "I'm a string"
string s = (string)session["string"];

// 42
int num = (int)session["number"];

MyObject o = (MyObject)session["object"];

If you have encountered the same requirement, you would know that is not a easy work.

You can use the XmlSerializer to do this object-xml mapping, but you need to know all the types of value in your session, especially when you deserialize the xml document.

OK, OK. I did all these for you.

Just download and session it.

XmlSession.cs

Entry.cs

FileSystemRightsHelper

January 8, 2009

The FileSystemRightsHelper class is a utility class to get the IO permission of a directory or a file.

DirectorySecurity security = System.IO.Directory.GetAccessControl(path);

AuthorizationRuleCollection rules = security.GetAccessRules(true, true, typeof(SecurityIdentifier));

FileSystemRightsHelper rights = new FileSystemRightsHelper(rules);

if (rights.CanWrite && rights.CanRead)
{
    Console.WriteLine("R/W access");
}
else
{
    if (rights.CanWrite)
	{
        Console.WriteLine("Only Write access");
    }  
	else if (rights.CanRead) 
	{
        Console.WriteLine("Only Read access");
    }
	else
	{
        Console.WriteLine("No Read and Write accesses");
    }
}

When I want to know “Do I have permission to Read or Write this file?”, I found this article by Bruce Hatt, “Testing File Access Rights in .NET 2.0“.

Thanks Bruce Hatt, I can get the answer of this common question.

Everything is OK, exception the code itself. I DO NOT LIKE THE CODE AT ALL!

So I rewrited my FileSystemRightsHelper (not just simple refactor).

Now it’s more effective and elegent.

Check it out!

FileSystemRightsHelper.cs