|
|
Monday, May 04, 2009
I saw a link to this FileHelpers Library today while reading my blog list. This is very interesting – from their site: The FileHelpers are a free and easy to use .NET library to import/export data from fixed length or delimited records in files, strings or streams. The idea is pretty simple: You can strong type your flat file (fixed or delimited) simply describing a class that maps to each record and later read/write your file as an strong typed .NET array The Library also has support for import/export data from differents storages like Excel, Access, SqlServer, etc. I’m going to use this one day – I almost certain of that.
Wednesday, April 29, 2009
Tuesday, April 28, 2009
Stayed up too late last night… tough getting up this morning
Monday, April 27, 2009
Not a lot out there today… or Friday for that matter. Here’s a few nuggets
Every morning I dig through various feeds of content and create a reading list for myself. I try to get through this list throughout the course of the day. Whatever spills over I tried to get to on the weekends. Maybe somebody else out there will find this useful.
- Microsoft released CCI on CodePlex – this is the code inspection engine behind FxCop. This (or some version of it) is also the engine that Visual Studio Code Analysis tooling uses in their Team System SKU’s of VS. That’s pretty interesting… good that Microsoft is becoming more and more transparent, but bad because this, in my experience, is a horrible library. This release will probably cause more people to want to use it. I’d recommend checking out Cecil instead.
- Jumpstart TV’s Grant Fritchey covers SQL Server Execution Plan Operators in 1.39 minutes
- Scott Hanselman talks to the legendary Joel Spolsky – very interesting stuff.
- Danny Cazzulino does an overview of his light and fast DI container Funq
- He has a nice series of screencasts here on how he built it using a Test Driven approach. These take a while to watch, but if you’re interested in learning the advanced features of C# 3.0, Resharper, and/or Test Driven development – watching this guy code will be educational
- Dimecast #104 – Navigate your codebase like a pro with ReSharper 4.5
- Warning: this screencast is done with a guy using the IntelliJ keyboard bindings. Most people there days use ReSharper with the ReSharper keyboard bindings. Watching this might be confusing if you’re trying to memorize keyboard short cuts, but it will be educational if you’re just interested in understand what ReSharper can do
- Test Code is Just Code – useful tidbits on how to write good test code, pitfalls to avoid, and common anti-patterns
Saturday, April 18, 2009
I’ve been playing with Windows 7 Beta on a VM for quite some time and I really like it. I’ve been yearning for something new for a while now, and on a whim… I did it. I installed Windows 7 Ultimate Beta on my main machine. I think this is the first time I’ve committed to a beta OS. We’ll see how this guys, but I have a feeling it’s going to be just fine.
Here’s the software I’m running so far and it’s Win7 compatibility
Firefox Extensions and Plugins I love:
Tuesday, April 14, 2009
This morning, I had Virtual Box in full screen mode on my Windows desktop, and I forgot the keystroke to get out. The typical key combos didn’t work. Strangely, I couldn’t find anything on Google or Virtual Box’s user guide that told me how to get out of full screen. Of course, it tells you how to get out when you go to full screen mode, but if you don’t pay attention (or forget), good luck finding it after the fact. Luckily, I have Virtual Box on my laptop as well, so I had a backup. So anyone out there looking for it, that stumbled across this post… here ya go: Host + F (Host = Right-Ctrl)
Over the years, I’ve switched between VMware Workstation, VMware Server, Microsoft Virtual PC, and Microsoft Virtual Server for my Virtual Machine hosting platforms. A friend of mine recently suggested checking out VirtualBox from Sun. I was somewhat hunting for a new platform because I no longer own a VMware Workstation license, and the free version of VMware Server has went completely web based which I found very difficult to use. I’ve tried to like Virtual PC, but Microsoft has seemed to abandon this product and fully investing in their Hyper-V technology. I’ve heard great things about Hyper-V, but it’s not laptop friendly (i.e. it disables Windows hibernation, and requires 64bit Windows Server 2008 OS). Microsoft Virtual Server is a solid product, but it too is web based, which I just don’t like for personal use. VirtualBox is free, fast, solid, and feature rich. It supports everything you’d expect, as well as USB. It’s not web based which I love, and they seem to roll out new builds nightly. I’m very happy with this product, and it looks pretty nice too. I’d be happy to pay 50-100 bucks for this, but 0 is fine too. 
Friday, April 10, 2009
I’ve been getting into some pretty advanced scenarios with WCF where we need to precisely shape the XML on the wire and the schema’s that are produced by svcutil.exe. Trust me, the moment you start using WCF for exposing services to Java clients, those Java clients are really going to care how the XML looks. WCF makes .NET-to-.NET very easy, and .NET-to-Java doable, but I wouldn’t call it easy. For vanilla scenarios (simple contracts with simple types and basic complex types), it’s pretty easy. The hooks exposed by WCF for shaping the XML are pretty poor in my opinion. IXmlSerializable is your friend when it comes to shaping the xml on the wire. It will work with the Data Contract Serializer in WCF, but if you google around trying to find info on people using IXmlSerializable, you’ll quickly get confused. I wanted to hand-roll how my entity serializes, and this interface is very straightforward for that. For shaping the schema, it’s not straight forward in the slightest. Below are several lessons I learned over a number of days while working with IXmlSerialiable: GetSchema is not what you use to shape the schema! I don’t know what this method is for, but it’s not what it sounds like. Everything you’ll find on google is people returning null. If you programmatically construct an XmlSchema instance, and return it from GetSchema(), it won’t be used. As far as I can tell, the Data Contract Serializer never calls this method. Instead, you have to decorate your class with the XmlSchemaProvider attribute and specify the static method that should be called for shaping the schema. This method should accept an argument of type XmlSchemaSet and in that method is where you should construct your schema, and add it to the XmlSchemaSet. It appears the method you implement must return either an instance of XmlQualifiedName or any derivative of XmlSchemaObject (i.e. XmlSchemaComplexType or XmlSchemaSimpleType). Here’s an example: [XmlSchemaProvider("ConstructSchema")]
public class Product : IXmlSerializable
{
private bool _deserializing;
protected object _data;
public virtual object Data
{
get { return _data; }
set { _data = value; }
}
public static XmlQualifiedName ConstructSchema(XmlSchemaSet schemaSet)
{
const string theNamespace = "http://webservices.kellybrownsberger.com/1.0";
XmlSchema schema = new XmlSchema
{
TargetNamespace = theNamespace,
ElementFormDefault = XmlSchemaForm.Qualified
};
schemaSet.Add(schema);
return new XmlQualifiedName("Product", theNamespace);
}
public XmlSchema GetSchema()
{
throw new NotImplementedException("Not implemented - the XMmlSchemaProvider attribute specifies calling the static GetSchema method instead");
}
public void ReadXml(XmlReader reader)
{
}
public void WriteXml(XmlWriter writer)
{
}
}
Shaping Schema using a read-in xml string
This is handy for two things in my mind – readability and code-gen. People tend to like looking at a schema in an xml representation. It’s more error prone, and not refactor-tool-friendly, but it’s more readable to the masses I think. Secondly, I like to code-gen my contracts in batch (using T4). Typically, I’ll define some XML grammar (DSL if you will), that describes my entities. I can then gen them all and make sure all of the correct attributes are applied. This might seem silly, but in large systems with interoperability being a top-priority, keeping all of your DataContract and DataMember attributes correct (one forgotten or botched namespace declaration can hose our consumers) is a bit daunting. When you get into the more complex things like contract versioning, and types implementing IXmlSerialable, it’s very daunting. Being able to code-gen this stuff has a lot of advantages. Reading in XML Schema as text is code-gen friendly as it can easily be captured as part of the DSL/grammar I mentioned, and the necessary code can be generating quickly and easilyand because your generating it, it’s less error prone.
Example: public static XmlQualifiedName ConstructSchema(XmlSchemaSet schemaSet)
{
const string theNamespace = "http://webservices.kellybrownsberger.com/1.0";
StringBuilder builder = new StringBuilder();
builder.AppendLine(string.Format("<xs:schema xmlns:tns=\"{0}\" elementFormDefault=\"qualified\" targetNamespace=\"{0}\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">", theNamespace));
builder.AppendLine("<xs:complexType name=\"Product\">");
builder.AppendLine("<xs:sequence minOccurs=\"1\" maxOccurs=\"1\">");
builder.AppendLine("<xs:any />");
builder.AppendLine("</xs:sequence>");
builder.AppendLine("</xs:complexType>");
builder.AppendLine("</xs:schema>");
XmlSchema schema = XmlSchema.Read(new StringReader(builder.ToString()), null);
schemaSet.Add(schema);
return new XmlQualifiedName("Product", theNamespace);
}
Shaping Schema programmatically
It took me longer than I care to admit to figure out how to do this correctly (it took me forever to figure out that I needed to sequence to the XmlSchemaComplexType’s Particle property). Here’s an example: public static XmlSchemaComplexType ConstructSchema(XmlSchemaSet schemaSet)
{
const string theNamespace = "http://webservices.kellybrownsberger.com/1.0";
XmlSchema schema = new XmlSchema
{
TargetNamespace = theNamespace,
ElementFormDefault = XmlSchemaForm.Qualified
};
XmlSchemaComplexType type = new XmlSchemaComplexType { Name = "Product" };
schema.Items.Add(type);
XmlSchemaSequence sequence = new XmlSchemaSequence {MinOccurs = 1, MaxOccurs = 1};
sequence.Items.Add(new XmlSchemaAny());
type.Particle = sequence;
schemaSet.Add(schema);
return type;
}
Tuesday, March 17, 2009
I’m finally getting a chance to sink my teeth into Windows Communication Foundation (WCF). I’m finding quite a few gaps on the interoperability side of things, and I think it’s overly complex in it’s configuration schemes and extensibility points, but it’s light years beyond what we had previously in ASMX. From what I can tell, the WCF adoption was just much slower than everyone anticipated. I’m not sure why that is – perhaps it’s the vastness of it that’s intimidated people. Perhaps it was the quality of the the .NET version 2.0 release that resulted in a slow adoption of all of version 3.0+. For whatever reason, this seems to have caused a number of rough edges in the product to sit dormant for a couple of years now. At any rate, WCF is now part of my every day day-job, and I’m trying to find ways to make it more testable. We have a suite of what I’d call System Tests. Unit Tests by my definition, test at the object (or component) boundary while System Tests test at a collection of objects (or components). Our system is highly configurable, and behaviors vary dramatically from one configuration to the next. We’d like to have the ability to have a repeatable suite of automated test that can test all of our out-of-the-box configurations. To date we’ve been executing our tests by .bat file (shelling to MbUnit.Cons.exe) after copying copies of our config files to our hosting IIS project. This is less than awesome for a few reasons: - It’s Slow and Flakey – Running test out of process (which is what IIS is) is always slower than in-process. Keep our test suite blazing fast is highly desirable. Also, when you’re doing this kind of thing, it’s not uncommon to need to restart IIS between tests (IIS caching certain types of config data, etc.), which can really slow down the party.
- It’s Heavy and Hard to Setup – IIS is required to be installed on any machine that wants to run the tests.
- It’s Awkward – We must have .bat files that copy around our Web.config files that contain our test configuration before executing our tests. The natural experience of running our tests directly from the IDE is lost.
Luckily, WCF is highly extensible and customizable in it’s hosting infrastructure. In the System.ServiceModel of the .NET Framework, they expose everything you need to easily create your own host for your WCF services. We’ve all seen the MSN samples that hosts your hello-world service with a Console app. To make our automated tests more awesome, I created a TestableServer service host implementation. The Service Lets say we have a service like this… /// <summary>
/// Here's my service implementation
/// </summary>
public class SomeService : ISomeService
{
public DateTime GetCurrentDate()
{
return DateTime.Now.Date;
}
}
/// <summary>
/// Here's my service contract for my implementation
/// </summary>
[ServiceContract]
public interface ISomeService
{
[OperationContract]
DateTime GetCurrentDate();
}
The Test
With the TestableServer, I can write a tidy little test like so…
[TestFixture]
public class SomeServiceFixture
{
[Test]
public void Can_We_Invoke_GetCurrentDate()
{
using (TestableServer<SomeService, ISomeService> server = new TestableServer<SomeService, ISomeService>(new BasicHttpBinding()))
{
ISomeService proxy = server.CreateProxy();
DateTime actual = proxy.GetCurrentDate();
Assert.AreEqual(DateTime.Now.Date, actual.Date);
}
}
}
By passing a few generics, it has all the information it needs to host my service in-memory and I can execute tests against it directly. Notice in the TestableServer constructor, I’m passing in the binding I’d like to use. Here I can specify netTcpBinding, msmqBinding, or any of they other support bindings. Here I’m using vanilla HTTP.
The Code
There’s not much to it at all, but here’s the code behind TestableServer…
public class TestableServer<TServiceImp, TServiceInt> : IDisposable where TServiceImp : class
{
private ServiceHost _host;
private readonly Type _serviceImplType = typeof(TServiceImp);
private readonly Type _serviceIntType = typeof(TServiceInt);
private readonly string _url;
private readonly Binding _binding;
private ChannelFactory<TServiceInt> _factory;
private TServiceInt _channel;
public TestableServer() : this(new NetTcpBinding()) { }
public TestableServer(Binding binding)
{
_host = new ServiceHost(_serviceImplType);
_binding = binding;
_url = string.Format("{0}://localhost/{1}", _binding.Scheme, Guid.NewGuid());
_host.AddServiceEndpoint(_serviceIntType, _binding, _url);
try
{
_host.Open();
}
catch (TimeoutException timeoutEx)
{
Console.WriteLine("Failed to close the service host - Exception: " + timeoutEx.Message);
throw;
}
catch (CommunicationException communicationEx)
{
Console.WriteLine("Failed to close the service host - Exception: " + communicationEx.Message);
throw;
}
}
public TServiceInt CreateProxy()
{
_factory = new ChannelFactory<TServiceInt>(_binding);
_channel = _factory.CreateChannel(new EndpointAddress(_url));
return _channel;
}
public void Dispose()
{
if ( _factory != null )
{
_factory.Close();
_factory = null;
}
TearDown();
}
private void TearDown()
{
if (_host != null)
{
try
{
if ( _host.State == CommunicationState.Opened || _host.State ==CommunicationState.Opening)
{
_host.Close();
}
}
catch (TimeoutException timeoutEx)
{
Console.WriteLine("Failed to close the service host - Exception: " + timeoutEx.Message);
}
catch (CommunicationException communicationEx)
{
Console.WriteLine("Failed to close the service host - Exception: " + communicationEx.Message);
}
finally
{
_host = null;
}
}
}
}
The Ultimate Goal
So, I haven’t actually achieved my ultimate goal yet, which is to be able to programmatically configure the server/service for each of our supported configurations and execute our test suites against those configurations. That’s what I’m going to work on next, and without IIS between my test fixture and my service implementation, achieving that goal should be relatively simple.
|