Creating a StreamProxy with Delegate/Lambda to read/write to a file

I saw a question the last time on Stackoverflow. The accepted answer was from Jon Skeet which was:

  • Event handlers (for GUI and more)
  • Starting threads
  • Callbacks (e.g. for async APIs)
  • LINQ and similar (List.Find etc)
  • Anywhere else where I want to effectively apply “template” code with some specialized logic inside (where the delegate provides the specialization)

I was once asked “What is the use of a delegate?”. The main answer that I found was “to delay the call”. Most people see delegate as events most of the time. However, they can be put to much greater use. Here is an example that I’ll gladly share with you all:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class StreamProxy<T> where T : Stream
{
private Func<T> constructorFunction;

private StreamProxy(Func<T> constructor)
{
constructorFunction = constructor;
}

public void Write(Action<StreamWriter> func)
{
using(T stream = constructorFunction())
{
StreamWriter streamWriter = new StreamWriter(stream);
func(streamWriter);
streamWriter.Flush();
}
}

public String Read(Func<StreamReader, String> func)
{
using (T stream = constructorFunction())
{
string result = func(new StreamReader(stream));
return result;
}
}

public static StreamProxy<T> Create(Func<T> func)
{
return new StreamProxy<T>(func);
}
}

To summarize what it does… it accept a delegate that returns a class that derives from “Stream” that will be used as a Constructor. It will return you a StreamProxy object that you can then use to read or write String out of that stream. What is interesting is that when it’s first created… nothing is done on the file. You are just giving instruction to the class on how to access it. When you then read/write from the file, the class knows how to manage a stream and make sure that no locks are left on the files.

Here is a sample usage of that class:

1
2
3
4
5
6
7
8
// Here I use a FileStream but it can also be a MemoryStream or anything that derives from Stream
StreamProxy<FileStream> proxy = StreamProxy<FileStream>.Create(() => new FileStream(@"C:\MyTest.txt", FileMode.OpenOrCreate));

// Writing to a file
proxy.Write(stream => stream.WriteLine("I am using the Stream Proxy!"));

// Reading to a file
string contentOfFile = proxy.Read(stream => stream.ReadToEnd());

That’s all folks! As long as you can give a Stream to this proxy, you won’t need to do any “using” in your code and everything will stay clean!

See you all next time!

Xml Serialization Made Easy

Most of the people who I’ve seen dealing with XML have some different approaches in dealing with the content.

If you want to read XML content, you normally have many way to go. Some people use XPath to retrieve the value with an XmlDocument object to retrieve what they want. Others will browse by nodes and get to what they want.

Do you see the main problem here? The problem is not that you won’t be able to read your information. The problem is the format as well as a lot of “navigation” code to get the information. The easy way to get away with conversions and navigation code is to use the XmlSerializer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
[XmlRoot(ElementName = "Library")]
public class Library
{
[XmlAttribute("id")]
public int ID { get; set; }

[XmlAttribute("name")]
public string Name { get; set; }

public string ToXml()
{

StringBuilder sb = new StringBuilder();
XmlSerializer serializer = new XmlSerializer(typeof(Library));
StringWriter sw = new StringWriter(sb);
serializer.Serialize(sw, this);
return sb.ToString();
}

public static Library FromXml(string xml)
{

StringReader sr = new StringReader(xml);
XmlSerializer serializer = new XmlSerializer(typeof(Library));
Library result = serializer.Deserialize(sr) as Library;
return result;
}
}

This will easily create an XML with one root node with 2 attributes with ID and Name. The XML will also serialize any children with the proper attributes on them. This is an easy way to serialize as well as deserialize XML without having to mess-up with XPath, XmlDocument, node navigation, etc.

Little Introduction

Hi everyone,

My name’s Maxim and I’m from Montreal, Quebec in Canada.

I decided to start a blog mainly because I want to have an online presence and I think I can bring a lot of information to the community which is not currently/properly available.

The main focus will be on .NET. I will be mainly posting code, demo, links that I think are relevant and should be looked into.

I do have a true passion about technology and hope I can actually help out on this side.

See you all later