Posts Tagged ‘C#’

.Net C# – XML Element Value Generic Extention Method

2 Comments

Recently, I was working on integrating a help desk API into one of our applications.  The API would return XML and I was using LINQ-To-XML to get the values of the elements.  However, a number of the elements in the API were allowed to be null, like a field for the completed date of a help desk ticket.  So, I started out writing my code like this…

// constructor for Ticket class
public Ticket(XElement element)
{
     AssignedDate = (!string.IsNullOrEmpty(element.Element("assigned-date").Value)) ? DateTime.Parse(element.Element("assigned-date").Value) : (DateTime?)null;

     // .... on and one for about 40 elements
}

I looked back and thought I should come up with a better way of getting the data from the Element and into the datatype that I needed.  So I came up with this generic extension method…

/// <summary>
/// Gets the value of the element.  Will convert the value to specified type if
///    possible.  If not possible, will return default value for type.
/// </summary>
/// <typeparam name="T">Type that should be returned</typeparam>
/// <param name="ele"></param>
/// <returns></returns>
public static T GetElementValue<T>(this XElement ele)
{
    // if the element is null, then return the default
    if (ele == null)
        return default(T);

    // if value is blank or null, just return the default value
    //   for the type.
    if (string.IsNullOrEmpty(ele.Value))
        return default(T);

    // since the type of the Value property is a string, no need
    //   to do anything fancy.  Just return the value.
    if (typeof(T) == typeof(string))
        return (T)Convert.ChangeType(ele.Value, typeof(T));

    // creates new object of type T to store converted value
    T newObject = default(T);

    // check to see if it's a nullable type.  If so, get the underlying
    //   type.
    // Nullable types don't have a Parse method.  Therefore, we need the
    //   underlying type so we can call the Parse method through reflection
    //   to convert the value.
    PropertyInfo[] properties = typeof(T).GetProperties();
    Type underlyingType = typeof(T);

    // Nullable types will have two properties.  The first is the HasValue
    //   property.  The second is the underlying type.  However, some other
    //   types(such as String), and custom classes/structs could also have
    //   only two properties.  So we check to make sure that there are only
    //   2 properties, then we make sure the first property is the HasValue
    //   property.  Theoretically, this could still give a false positive.
    if (properties.Count() == 2 &&
        string.Equals(properties[0].Name, "HasValue", StringComparison.InvariantCultureIgnoreCase))
        underlyingType = properties[1].PropertyType;

    try
    {
        // calls Parse method for the type
        MethodInfo method = underlyingType.GetMethod("Parse", new[] { typeof(string) });
        newObject = (T)method.Invoke(null, new[] { ele.Value });
    }
    catch (Exception)
    {
        throw;
    }

    return newObject;
}

Now with this extension method, it really cuts down on the amount of code I have to write.  I can now use it like this..

public Ticket(XElement element)
{
     AssignedDate = element.Element("assigned-date").GetElementValue<DateTime?>();
}

I hope this can help out somebody.

Tags: , , ,

.Net C# – Generic Serialization Methods

1 Comment

Short blog post today.  These are a couple of generic serialize and deserialize methods that can be easily used when needing to serialize and deserialize classes.  The methods work with any .Net type.  That includes built-in .Net types and custom classes that you might create yourself.

These methods will only serialize PUBLIC properties of a class.  Also, the XML will be human-readable instead of one long line of text.

Serialize Method

/// <summary>
 /// Serializes the data in the object to the designated file path
 /// </summary>
 /// <typeparam name="T">Type of Object to serialize</typeparam>
 /// <param name="dataToSerialize">Object to serialize</param>
 /// <param name="filePath">FilePath for the XML file</param>
 public static void Serialize<T>(T dataToSerialize, string filePath)
 {
      try
      {
           using (Stream stream = File.Open(filePath, FileMode.Create, FileAccess.ReadWrite))
           {
                 XmlSerializer serializer = new XmlSerializer(typeof(T));
                 XmlTextWriter writer = new XmlTextWriter(stream, Encoding.Default);
                 writer.Formatting = Formatting.Indented;
                 serializer.Serialize(writer, dataToSerialize);
                 writer.Close();
           }
      }
      catch
      {
           throw;
      }
 }

Deserialize Method

/// <summary>
 /// Deserializes the data in the XML file into an object
 /// </summary>
 /// <typeparam name="T">Type of object to deserialize</typeparam>
 /// <param name="filePath">FilePath to XML file</param>
 /// <returns>Object containing deserialized data</returns>
 public static T Deserialize<T>(string filePath)
 {
      try
      {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            T serializedData;

            using (Stream stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
            {
                 serializedData = (T)serializer.Deserialize(stream);
            }

            return serializedData;
      }
      catch
      {
            throw;
      }
 }

Here is some sample code to show the methods in action.

Person p = new Person() { Name = "John Doe", Age = 42 };
XmlHelper.Serialize<Person>(p, @"D:\text.xml");

Person p2 = new Person();
p2 = XmlHelper.Deserialize<Person>(@"D:\text.xml");

Console.WriteLine("Name: {0}", p2.Name);
Console.WriteLine("Age: {0}", p2.Age);

Console.Read();
Tags: ,

.Net, Silverlight Silverlight 4 – Copy/Paste From Clipboard

0 Comments

In this tutorial, I will show how you can use Silverlight 4 to get access to the client clipboard. Silverlight 3 had limited clipboard access, but Microsoft implemented more complete access to the clipboard.

For security purposes, access to the clipboard is only allowed through a user-initialed event. For example, you couldn’t have a timer running in the background to constantly get text from the clipboard.

For first, let’s create a Silverlight 4 application and name it SL4ClipboardAccess. Then Click OK on the next popup.

10-28-2010 10-05-33 AM

I added some controls to the page..

<Grid x:Name="LayoutRoot" Background="White">

    <TextBox
        Name="CopyTextTextBox"
        Height="23"
        HorizontalAlignment="Left"
        Margin="132,36,0,0"
        VerticalAlignment="Top"
        Width="174" />

    <TextBlock
        Name="textBlock1"
        Text="Text To Copy:"
        Height="23"
        HorizontalAlignment="Left"
        Margin="47,40,0,0"
        VerticalAlignment="Top" />

    <Button
        Name="CopyToClipboardButton"
        Content="Copy To Clipboard"
        Click="CopyToClipboardButton_Click"
        Height="39"
        HorizontalAlignment="Left"
        Margin="144,81,0,0"
        VerticalAlignment="Top"
        Width="145"  />

    <Button
        Click="PasteToTextBoxButton_Click"
        Name="PasteToTextBoxButton"
        Content="Paste To Textbox"
        Height="39"
        HorizontalAlignment="Left"
        Margin="144,147,0,0"
        VerticalAlignment="Top"
        Width="145"  />

    <TextBox
        Name="PasteTextTextBox"
        Height="23"
        HorizontalAlignment="Left"
        Margin="132,209,0,0"
        VerticalAlignment="Top"
        Width="174" />

    <TextBlock
        Name="textBlock2"
        Text="Text From Clipboard:"
        Height="23"
        HorizontalAlignment="Left"
        Margin="8,209,0,0"
        VerticalAlignment="Top" />

</Grid>

Which look like this…

10-28-2010 10-19-03 AM

Now, the Click Event for the CopyToClipboard Button would look like this…

private void CopyToClipboardButton_Click(object sender, RoutedEventArgs e)
{
    string textToCopy = CopyTextTextBox.Text;

    try
    {
         Clipboard.SetText(textToCopy);
    }
    catch (SecurityException se)
    {
        MessageBox.Show(se.Message);
    }
}

and the Click Event for the PasteToTextBox Button would be this..

private void PasteToTextBoxButton_Click(object sender, RoutedEventArgs e)
{
    string textFromClipboard = string.Empty;

    try
    {
         textFromClipboard = Clipboard.GetText();
    }
    catch (SecurityException se)
    {
         MessageBox.Show(se.Message);
    }

    PasteTextTextBox.Text = textFromClipboard;
}

Now run the application and type into the Text To Copy textbox. When you click the Copy To Clipboard button, you will be prompted for permission for access to the clipboard.

10-28-2010 10-15-52 AM

After allowing access, click the Paste To TextBox button, and the text will now be in the other textbox.

Very simple tutorial for a very powerful feature.

Tags: , , ,