Lars Holm Jensen's Code Blog

Just another WordPress codeblog on C#, Silverlight and all things .NET

Archive for June, 2011

C# string to alphanumeric

with one comment

Short and easy way to get the alphanumeric content of a string:

public static string ToAlphaNumeric(this string str)
{
    return new string(str.Where(c => char.IsLetterOrDigit(c)).ToArray());
}

Written by larsholm

June 16th, 2011 at 9:32 pm

Posted in .NET

Tagged with , , , ,

Persist .NET objects to XML

without comments

Here’s two extensions I use to easily persist objects to XML string in C#. Although it looks like it, it does not seem to require that the class of the object is decorated with the DataContract attribute, it just works.

public static string ToXml(this object o)
{
    StringWriter sw = new StringWriter();
    XmlWriter xw = XmlWriter.Create(sw);
    DataContractSerializer dcs = new DataContractSerializer(o.GetType());
    dcs.WriteObject(xw, o);
    xw.Close();
    return sw.ToString();
}

public static T FromXmlTo(this string s) where T : class
{
    DataContractSerializer dcs = new DataContractSerializer(typeof(T));

    StringReader sr = new StringReader(s);
    XmlReader xtr = XmlReader.Create(sr);

    return dcs.ReadObject(xtr) as T;
}

Let me here how it works out for you guys..

Written by larsholm

June 16th, 2011 at 9:06 pm

Posted in .NET

Tagged with , , , , ,

Embed managed dlls easily in a .NET assembly

with 31 comments

Here’s a very quick and dirty way to include managed dlls in your .exe-file. Just right-click your project in Visual Studio, choose Project Properties -> Resources -> Add Resource -> Add Existing File

Add all your dependencies and finally include the code below in your App.xaml.cs or equivalent.. everything else is taken care of.

public App()
{
    AppDomain.CurrentDomain.AssemblyResolve +=new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}

System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    string dllName = args.Name.Contains(',') ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(".dll","");

    dllName = dllName.Replace(".", "_");

    if (dllName.EndsWith("_resources")) return null;

    System.Resources.ResourceManager rm = new System.Resources.ResourceManager(GetType().Namespace + ".Properties.Resources", System.Reflection.Assembly.GetExecutingAssembly());

    byte[] bytes = (byte[])rm.GetObject(dllName);

    return System.Reflection.Assembly.Load(bytes);
}

The code is a little bit more complicated than need be. But I wanted to avoid using a named namespace in order to keep the code copy-paste-ready. By the way LINQPad uses a similar method, though Joe Albahari has gone a step further and encrypted his resources.

Written by larsholm

June 15th, 2011 at 8:10 pm

Posted in .NET

Tagged with , , , , , ,