Serialize or Deserialize Any .NET Object To and From an XML String

Posted by | Filed under , , , , , , ,

A new and handy feature of C# 3.0 is "extension methods". Extension methods essentially allow you to write methods for classes that you may or may not have written yourself.

Additionally, a great feature of .NET 2.0 is "generics", which allow you to create templates of methods (and classes) for multiple types at once.

Combine extension methods and generics, and you can really cook up some trouble! In terms of XML serialization, you can code a few simple lines to handle all your XML string serialization needs.

Observe:

public static class Extensions
{
   public static string ToXml<T>(this T toSerialize)
   {
 
     var serializer = new XmlSerializer(typeof(T));
      var sb = new StringBuilder();
      using (var writer = new StringWriter(sb))
         serializer.Serialize(writer, toSerialize);
      return sb.ToString();
   }


   public static T DeserializeXmlString<T>(this string xml)
   {
     
var serializer = new XmlSerializer(typeof(T));
      using (var reader = new StringReader(xml))
         return (T)serializer.Deserialize(reader);
   }
}

Observe. After creating the class above and referencing its namespace in your code, the extension method becomes available for use so that you can perform serialization/deserialization trickery like so:

public class MyClass
{

   public
int IntProperty { get; set; }
   public string StringProperty { get; set; }
}

var mc = new MyClass(){ IntProperty = 1, StringProperty = "Test" };
var xml = mc.ToXml();
//output:
//<MyClass>
// <IntProperty>1</IntProperty>
// <StringProperty>Test</StringProperty>
//</MyClass>
var deserializedMc = xml.DeserializeXmlString<MyClass>();

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Getting the Strong Name of an Assembly (Now That Reflector 6.8 Doesn't Seem To)

Posted by | Filed under , , , ,

Red Gate software recently updated their Reflector product to the last free version (6.8). Unfortunately, they also seemed to take away the feature I used the most, namely the ability to get the strong name of an assembly (which is often needed for SharePoint development).

 Luckily, the tool's capability is easy to replace. I simply created a Windows Forms app with a Button, an OpenFileDialog and a TextBox for displaying the strong name. The code to extract the full name of the assembly is as follows, which I added here in the Button.Click event handler. Naturally, button1 is the Button, openFileDialog1 is the OpenFileDialog and textBox1 is the TextBox. You can rename or change the controls however you wish.

private void button1_Click(object sender, EventArgs e)
{

    // Show the open file dialog and get user input.
    DialogResult result = openFileDialog1.ShowDialog();
    if (result == DialogResult.OK)
    {
        // Assuming you pick a .dll, this code will load it and then display
        //the strong name in the TextBox control of the form.

         var
assembly = Assembly.LoadFile(openFileDialog1.FileName);
         textBox1.Text = assembly.FullName;
    }
}

 UPDATE: RedGate fixed the problem and the strong name section is there again if you download the latest version.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Solved! - The service 'System.Workflow.ComponentModel. Compiler.ITypeProvider' must be installed for this operation to succeed.

Posted by | Filed under , , ,

I'm working on a SharePoint project where several componenets (Workflow, List Definitions, Content Types, etc.) are tightly related to the same functionality. To reduce the risk of components breaking because of an out-of-sequence or missing dependency, and just to make things easier, I wanted to throw everything together in the same project. I discovered something interesting about Workflows in the process, however.

Namely, if you try to add a Workflow to a typical project, you'll get an error in the Workflow designer saying:

     "The service 'System.Workflow.ComponentModel.Compiler.ITypeProvider' must be installed for this operation to succeed."

This happens if you added references to the proper assemblies (System.Workflow.Activities, System.Workflow.ComponentModel, System.Workflow.Runtime and microsoft.sharepoint.WorkflowActions)!

Odd, but luckily there are solutions. One is to write a bunch of code to build the support that the Workflow Designer needs, but I was looking for something even simpler. What I discovered, is that you can add support for Workflows to your project (the .csproj or .vbproj file) by cracking it open in notepad and adding some "ProductTypeGuids" to the project XML. Just add both of the GUIDs featured in the ProjectTypeGuids element below (or add the element if it's not there), and you should be good to go!

<PropertyGroup>
    ...
    <AssemblyName>MyCompany.Technnology</AssemblyName>
    <ProjectTypeGuids>{14822709-B5A1-4724-98CA-57A101D1B079};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
    <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
    ...
  </PropertyGroup>

 I'm curious to see if you can add these GUIDs to many types of projects to enable Workflow support (and further curious about if there are any consequences apart from designer support),

Currently rated 5.0 by 4 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Adding a CSS Style & Class To An ASP.NET Page Header

Posted by | Filed under , ,

 There are a variety of techniques out there for wiring up a CSS class to an ASP.NET Web Form through code. You can register a link to a CSS file via Page.Header.Controls.Add() and ASP.NET 2.0 introduced the robust WebResource framework for registering entire style sheets for a given page, but what about when you want to add a dynamic style to the HTML  header?

Typically, the technique would involve something like this:

Page.Header.Controls.Add(
    new LiteralControl(
        @"<style type='text/css'>
                /*type selector*/
                BODY
                {
                    background: Aqua;
                }
                /*class selector*/
                .myClass
                {
                    background: WhiteSmoke;
                    font-size: 20pt;
                }
                </style>
            "

        )
);

...but there are drawbacks to the approach including the need for verbose "style" tags with each chunk of CSS styles you want to add and the lack of validation on style names and values.

Luckily, there's a more sophisticated and elegant approach supported by .NET Framework 2.0 or higher using Page.Header.Stylesheet and the System.Web.UI.WebControls.Style class. With the approach, instead of having to define your CSS class using a string, you can used strongly-typed objects instead! Additionally, all of the styles you add will get added to one single style attribute in the Page header.

Style typeStyle = new Style();
typeStyle.BackColor = Color.Aqua;
Page.Header.StyleSheet.CreateStyleRule(typeStyle, null, "BODY");

Style classStyle = new Style();
classStyle.BackColor = Color.WhiteSmoke;
classStyle.Font.Size = FontUnit.Parse("20pt");
Page.Header.StyleSheet.CreateStyleRule(classStyle, null, ".MyClass");

There is, however, a drawback to the approach which is the limited number of properties available in the Style base class. For instance, if you wanted to set a value for the "margin" CSS style, you'd need to either use or create a subclass of Style that overrides the AddAttributesToRender() method.

Currently rated 4.5 by 2 people

  • Currently 4.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

A Cool Way To Handle ASP.NET Properties Using Nullable Types

Posted by | Filed under , ,

In ASP.NET 1.x, it used to be common to handle the getter of a value type properties thusly:

public int SomeInteger
{
         get
         {
                object val = ViewState["SomeInteger"];
                return val != null ? (int)val : 0;
          }
}

Not bad, but there's more code than needed with nullable types and the "null coalescing operator", anyway. Here's the newer, sleeker way to do the same thing with half the space!

public int SomeInteger
{
         get{ return ViewState["SomeInteger"] as int? ?? 0; }
}

So what's going on in this snippet? Well, we cast the value to a nullable int (int?) which holds a reference to either an int or null then we use the aforementioned ?? operator to return our default value or 0 in the case of null

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5