WPF Templates Very Neat Example

by Law Metzler 26. September 2009 16:31

We've been developing a couple of applications using the WPF (Windows Presentation Framework) and I've been spending a good amount of time reviewing it.  And I have to say, it really is hand over fist a very great framework to work with.

While we had developed a few Silverlight controls and apps using it in the last few years, I've personally haven't had the time to really get knee deep into the details of it until now, and boy what I have been missing.  From a coding standpoint, it's still just C# (or VB if you're so inclined); but from an designing point of view, it offers a wealth of features and enhancements.

In essence, WPF allows the separation of visual design and actual programming much in the same way as Asp.Net does so with code behind.  While programming for Windows Forms had the resemblance of the separation of the two (at least if you were using Visual Studio or another editor), it really was not separated at all, as the whole layout and stying was done inside the class's "Initialize" method.

With WPF, all the design is done inside the XAML file, which is simply an XML file.  And with tools like Microsoft's Expression, designer's and developers can work hand in hand with the tools designed for them.  (Let's face it, Visual Studio leaves a lot to be desired when in the hands of a graphic artist)

But while WPF separates code and design like ASP.NET, it extends the capabilities of the XAML in ways that ASP.NET could never even dream of.  Submitted for your approval, see this implementation of the standard listbox.

Tags: , ,

Implementing the Xml-Rpc Spec in C#: Part 2

by Law Metzler 11. September 2009 16:29

Sorry for the long span between posts, but things have been pretty busy here.

In the first part of this series, we reviews the Xml-Rpc specifications and used the XSD tool to generate our starting point.  Now, we'll tackle some of the basic changes we've done to those generated files.

Standards and Compliance

The first thing we need to do is to move the classes into a form that that is compliant with the software development standards for Bambit.  This is, for the most part, rather trivial, if not just tedious.  It includes:

  1. Putting each class into it's separate file
  2. Changing properties that simply expose private data variables to auto-properties
  3. Create proper casing for classes, properties and methods

As I said, simple, but (somewhat) tedious.

Class Implementation Changes

MethodCall Class

In the MethodCall class, the xsd file had originally created a special class called methodCallParams, which itself simply wrapped an array of parameter objects.  This was overly redundant to me, so I eliminated the methodCallParams class entirely, and changed the property


[System.Xml.Serialization.XmlElementAttribute("param")]
public parameter[] param {
get {
return this.paramField;
}
set {
this.paramField = value;
}
}

 to

[XmlArray("params")]
[XmlArrayItem("param")]
public List<Parameter> Parameters { get; set; }

This was a lot cleaner.  First, the naming  convention follows our guidelines. Second, we eliminated a class entirely.  Third, we changed from a non-expandable array data type, to a List<>.  This allows us to add to the list at any point in time, so calling code can keep adding parameters, instead of having to assign all parameters at once.

In doing this, we need to create a default ctor to initialize the List<>.  If we don't do this, De-serializing will explode on us, due to the fact that, when de-serializing to a List object, the Framework assumes that the object is valid and simply calls Add instead of putting the entire list on at once, so it will try to call Add on a null object.

Value Class

This class was given a lot of additions to, all having to do with casting.

Since the specifications state that a value can be a whole host of things, it must be stored as an object (outside of customizing the serialization and keeping a whole slew of different type variables).  However, an object is much too vague to be of real use in most situations.  So what we did was to store the actual object as an object, but add cast operators to the Value class itself.  To be effective, we made casts both ways, so that casting from a double, int or any other valid type to a Value would be allowed, as would casting from a Value to any other type (as long as the Value WAS of that type).

To do this, casting from a Double (or any other valid type) to a Value would be an implicit conversion, while converting from a Value back would be an explicit.  The reason for this is that, in an implicit casting, you should NEVER thrown an exception, while explicit conversions allow for an exception to be thrown. Since the Value object can be any other type at any time, it is allowed to be implicitly cast.  However, if the Value already contains an RpcStruct object and we try to cast it to a double, we will blow up.

We then entered every cast possible, in the following form:

public static explicit operator <TYPE>(Value value) { return (<TYPE>)value.Item;}

public static implicit operator Value(<TYPE> item)

{

  return new Value { Item=item, ItemType = <APPROPRIATE ITEM TYPE> } ;
}

 

For instance, the conversion casting for a double was:

public static explicit operator double(Value value) { return (double)value.Item;}
public static implicit operator Value(double item) 

{

   return new Value { Item=item, ItemType = ItemChoiceType .Value } ;
}

 

As you can see, our implicit conversion will never fail, as assigning the "Item" (which is an object) anything is completely legal.  Our explicit will fail only if the framework does not know how to do the conversion itself.  We could have done some checking on ItemChoiceType ourselves, but this would have been a bad idea.  First, it's extra work on our end that is redundant.  Second, if we try to cast to a double and it's an integer, we would fail (unless we actually check all the different types that can be cast to/from), when it is a perfectly legal cast.  As such, it's much better just to let the Framework do the work for us.

 

Well, that covers a few of the design decisions.  In the next installment, I'll go over changes to the RpcStruct and MethodResponse classes.


NOTE:

We've released this project under the LGPL and you can download it at codeplex, BXmlRpc.  The current generated documentation can be found at http://bxmlrpc.bambitinc.com/Documentation/

Tags: , , , , ,

Implementing the Xml-Rpc Spec in C#: Part 2

by Law Metzler 26. August 2009 16:27

Sorry for the long span between posts, but things have been pretty busy here.

In the first part of this series, we reviews the Xml-Rpc specifications and used the XSD tool to generate our starting point.  Now, we'll tackle some of the basic changes we've done to those generated files.

Standards and Compliance

The first thing we need to do is to move the classes into a form that that is compliant with the software development standards for Bambit.  This is, for the most part, rather trivial, if not just tedious.  It includes:

  1. Putting each class into it's separate file
  2. Changing properties that simply expose private data variables to auto-properties
  3. Create proper casing for classes, properties and methods

As I said, simple, but (somewhat) tedious.

Class Implementation Changes

MethodCall Class

In the MethodCall class, the xsd file had originally created a special class called methodCallParams, which itself simply wrapped an array of parameter objects.  This was overly redundant to me, so I eliminated the methodCallParams class entirely, and changed the property


[System.Xml.Serialization.XmlElementAttribute("param")]
public parameter[] param {
get {
return this.paramField;
}
set {
this.paramField = value;
}
}

 to

[XmlArray("params")]
[XmlArrayItem("param")]
public List<Parameter> Parameters { get; set; }

This was a lot cleaner.  First, the naming  convention follows our guidelines. Second, we eliminated a class entirely.  Third, we changed from a non-expandable array data type, to a List<>.  This allows us to add to the list at any point in time, so calling code can keep adding parameters, instead of having to assign all parameters at once.

In doing this, we need to create a default ctor to initialize the List<>.  If we don't do this, De-serializing will explode on us, due to the fact that, when de-serializing to a List object, the Framework assumes that the object is valid and simply calls Add instead of putting the entire list on at once, so it will try to call Add on a null object.

Value Class

This class was given a lot of additions to, all having to do with casting.

Since the specifications state that a value can be a whole host of things, it must be stored as an object (outside of customizing the serialization and keeping a whole slew of different type variables).  However, an object is much too vague to be of real use in most situations.  So what we did was to store the actual object as an object, but add cast operators to the Value class itself.  To be effective, we made casts both ways, so that casting from a double, int or any other valid type to a Value would be allowed, as would casting from a Value to any other type (as long as the Value WAS of that type).

To do this, casting from a Double (or any other valid type) to a Value would be an implicit conversion, while converting from a Value back would be an explicit.  The reason for this is that, in an implicit casting, you should NEVER thrown an exception, while explicit conversions allow for an exception to be thrown. Since the Value object can be any other type at any time, it is allowed to be implicitly cast.  However, if the Value already contains an RpcStruct object and we try to cast it to a double, we will blow up.

We then entered every cast possible, in the following form:

public static explicit operator <TYPE>(Value value) { return (<TYPE>)value.Item;}

public static implicit operator Value(<TYPE> item)

{

  return new Value { Item=item, ItemType = <APPROPRIATE ITEM TYPE> } ;
}

 

For instance, the conversion casting for a double was:

public static explicit operator double(Value value) { return (double)value.Item;}
public static implicit operator Value(double item) 

{

   return new Value { Item=item, ItemType = ItemChoiceType .Value } ;
}

 

As you can see, our implicit conversion will never fail, as assigning the "Item" (which is an object) anything is completely legal.  Our explicit will fail only if the framework does not know how to do the conversion itself.  We could have done some checking on ItemChoiceType ourselves, but this would have been a bad idea.  First, it's extra work on our end that is redundant.  Second, if we try to cast to a double and it's an integer, we would fail (unless we actually check all the different types that can be cast to/from), when it is a perfectly legal cast.  As such, it's much better just to let the Framework do the work for us.

 

Well, that covers a few of the design decisions.  In the next installment, I'll go over changes to the RpcStruct and MethodResponse classes.


NOTE:

We've released this project under the LGPL and you can download it at codeplex, BXmlRpc.  The current generated documentation can be found at http://bxmlrpc.bambitinc.com/Documentation/

Tags: , , , , ,

C# Extension Methods and log4net

by Law Metzler 22. July 2009 16:00

 

Here at Bambit Technologies, we use log4net in nearly every application that we build, from web sites, to desktop apps to server services.  It's well written, easy to implement and extremely versatile.  With that said, there's a couple things I would like changed or implemented.

One of the biggest changes I would like to see is when logging an exception.  Generally, to log an exception you make a call like this:

 

ILog myLogger=LogManager.GetLogger(); 

Exception exception=new Exception("Something happened");

myLogger.Error("Something happened, and it wasn't good", exception);

 

Pretty straight forward, right? 

But what if I want to format the string I am logging, then you have to do the following:

 

	
myLogger.Error(string.Format("Something bad happened: {0}", errorString), exception);

 

Essentially adding a "string.Format" call to the message string.  log4net DOES have the method "ErrorFormat", but if you call it like:

 

	
myLogger.ErrorFormat("Something bad happened: {0}", errorString, exception);

 

the actual exception is lost, as it is passed in as an argument to the format string.

 

For a long time we resigned ourselves to just adding the extra String.Format call, as trying to change the implementation for all the different types of loggers would be a headache at best, not to mention having to test and verify and rebuild everytime a new version of log4net comes out (which, admittedly isn't that often, it's extremely stable)

 

Extension Methods

Now, with the 3.0 framework, we have a new option: Extension Methods.  Extension methods are exactly what they sound like, ways to extend a class with added functionality.

To see how this helps us with log4net, we create an extension class with the new methods we would like to see implemented.

 

public static Exception Exception(this ILog logger, Exception exception, string fmt, 
params object[] args)
{
logger.Error(string.Format(fmt, args), exception);
return exception;
}

To see the complete code listing, see this link

Now, when I need to log an exception, I can simply call:

 

myLogger.Exception(exception, "Something is definatly wrong: {0}", errorString);

 

 

You'll also note that each of these methods returns the exception I pass in.  This simply allows us to join everything in one statement:

 

	throw myLogger.Exception(
new Exception("Something is wrong"),
"Something is wrong:", errorString);

 

which comes in pretty handy.

Tags: , , , ,

Implementing the Xml-Rpc Spec in C#: Part 1

by Law Metzler 21. July 2009 15:58

When we fist decided to implement a blog on our site, we figured it would be quick and easy to roll our own, and for the most part it was.  After all, a blog is only composed of a handful of tables, each with a spattering of columns.  You have the blog itself, then you have comments.  That's the long and short of blogging.

At least at first glance.

After you get the blogs up, you certainly want to implement trackbacks and pingbacks.  If you don't know what these are, they are simply a way of interlinking sites, so that if I comment on a blog at foobar.com, they can add a link back to my site, saying comments were made there.

Trackbacks are relatively straight forward as they are simply HTTP calls made in a REST fashion (spec can be found here)

Pingbacks are only slightly more involved.

Enter the XmlRpc Spec

Pingbacks are entriely built arond the Xml-Rpc specificaion, which is exactly what it sounds like, remote procedure calls via Xml, a simpler version of SOAP if you will (I'll leave the Xml-Rpc vs SOAP vs REST argument for another day).  I'll be the first to admit, somehow up to this point in my programming experience, I had somehow avoided interfacing with Xml-Rpc directly. So I did what I always do when confronted with a new spec, I read the manual.

This is a point that I want to stress.  I know a lot of developers who can churn out code to email someone without having read one single RFC concerning SMTP, MIME or any other similiar technology.  This is a sure way to limit your usefullness as a programmer.  Along with learning a language a year, coders should also strive to understand the undelying concepts of the systems they are working with.

But I digress.  To return to point, I went and read the spec, which on the surface seemed pretty simple.  Since I didn't know how to implement it myself and it seemed rather simple, I decided to take a crack at implementing my own library.

In the beginning, there's the XML

Since Xml-Rpc utilizes HTTP for the request/response, and since the HttpWebRequest method is built into the .Net libraries already, I decided to start with the xml.  The spec site gives a very verbal breakdown of how the xml is structured, but it is missing a schema definition file, so that's where I began.  This can be found here.

Once I have the xsd defined, I used XSD.exe tool that comes with Visual Studio to create the first version of the classes to serialize the documents.  The XSD.exe tool is an extremely valuable tool, but, generally, we only use it to get a base to work from.  You can find the results of this generation here.

 

In the next part, I'll go over the changes to the Xml

 

NOTE:

We've released this project under the LGPL and you can download it at codeplex, BXmlRpc.  The current generated documentation can be found at http://bxmlrpc.bambitinc.com/Documentation/

Tags: , , , ,

Tutorial

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen