Tag Archive: c#

ToXmlString extension method

This is an extension method that serializes any object to xml. Note that it is “null resistant” in that if the target is null, the extension does not throw an object-not-set-to-an-instance exception, but instead simply returns null.

public static string ToXmlString(this T item) where T : class
            if (item == null)
                return null;
            string xml;
            using (var stream = new MemoryStream())
            using (var writer = XmlWriter.Create(stream))
                new XmlSerializer(item.GetType()).Serialize(writer, item);
                xml = Encoding.UTF8.GetString(stream.ToArray());
            return xml;

Universal Caching

I wrote this library so I don’t have to keep track if I should use HttpRuntime.Cache, AppDomain.CurrentDomain.SetData, HttpContext.Current.Session, or a Dictionary…now I just use GlobalCache or UserCache.  It also makes unit testing a webapp a snap, because if you use IGlobalCache/IUserCache in your code, you just inject the Windows-based cache in your unit test setup.

You can download the solution with dlls here: Universal Caching solution

How to POST model if GET action has parameter in ASP.NET MVC

Do you have a post action that accepts a parameter (and what post action doesn’t?), but you also have a get action that accepts a parameter and you are seeing that submits are going back to the get action and other strange behavior? Here’s how you fix that:

View full article »

New in .NET 4.0: string.IsNullOrWhiteSpace

I thought I’d quickly mention this nice time-saver added in .NET 4.0: string.IsNullOrWhiteSpace. It works just like IsNullOrEmpty but also checks to see if there’s nothing but spaces in the string, so you don’t have to Trim before checking.

If you have a entity with a nested entity, you can show the nested entity’s properties with a little trick.

For example if you have these business objects:

public class MyObj
    public MyOtherObj MyProperty { get; set; }

public class MyOtherObj
     public int SomeProperty { get; set; }

If you want to show a field from MyProperty (e.g. MyOtherObj.SomeProperty), and MyObj is your report’s datasource, your report fieldbox will need to look like this:


(NOTE: do not add “.Value” onto the end of the property name as normal, it will produce a #error at runtime).

© 2017 Robert Corvus