December 2005 - Posts

Probably everyone knows this already , but i am going to waste some energy on it anyway, as it raises way too many eyebrows lately :) As long as C# exists it supports the type conversion operator "explicit". Neverheless i've never seen any practical use on the operator before.  Probably because it has the tendency to release the "Huh?!1?" effect among developers. Until i started working with XLinq for my "Visual Fx" objectbuilder strategy. I wrote this little example to clarify:

public Example(XElement node)
{
    string str = (string)node.Attribute("Name"
); //Convert it to a string
    int number = (int)node.Attribute("Number"
);  //Convert it to an int
}

As you can see here, the Attribute property of type XAttribute can be casted to an String aswel to an Int (and several more types like DateTime, TimeSpan, Guid etc). Which is unusual since these types are not in the inheritence chain of XAttribute. This behaviour is conceived by using the "explicit" operator. By implementing this operator, which is easy,  you are responsible for converting the current type to your target type by doing so:

class XAttribute {
  //More really exciting code

  public static explicit operator string(XAttribute a)
  {
      if (a == null)
      {
            return null;
      }
      return a.value;
  }
}

Now this isn't exactly rocket science or anything but good to know when you encouter this behaviour in your new Xlinq applications. I've somewhat mixed feelings on this operator since there is no visual intellisense support for it available, thus there is no way of telling wheter you can simply cast an type using that operator or need to implement your own custom casting. Except for that minor point it certainly eases writing Xlink queries. Also, there is an "implicit" operator which does a  similiar thing except you don't have to write the cast explicitly, thus typing:

string str = node.Attribute("Name")

will suffice. (Note that the XAttribute doesnt implement the "implicit" operator so this won't compile)

More information on explicit and implicit on msdn: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vclrfexplicit.asp

Don't you hate it when you present your nice hardworked CAB driven multi layered ultra winform application to your customer, and they respond with an reaction sometwhat like: "I really dont like that color of that textbox there". And then as nice as you are, you pop up the IDE, change the color of textbox only to hear that you have to change now every textbox there is in your application. When you are finally done changing every darn single textbox, the unit manager comes in screaming that the colors dont match with his suit and you have to change it all back again.

Introducing VisualFx CAB Extension
For these kind of situations i have tried to make something that declaratively defines all the colors and styles on your application using an stylesheet kind of XML file. In this XML file you can define a set of properties as an "style", and bind them to controls using "style bindings". Under the hood it uses an custom objectbuilder strategy, which injects the properties every time the object builder executes the BuildUp method. It uses an simple engine to resolve the possible candidate stylebindings for the given injectee.  Lets examine the following file for example:

<VisualFX>
 <StyleDeclarations>
  <Style StyleId="MyStyle">
   <Properties>
    <Property name="ForeColor" value="Navy" />
    <Property name="BackColor" value="LightSkyBlue" />
   </Properties>
  </Style>
 </StyleDeclarations>
 <StyleBindings>
  <!--  Every TextBox should use MyStyle -->
  <Binding ControlPath="." Type="System.Windows.Forms.TextBox" StyleId="MyStyle"/>

 </StyleBindings>
</VisualFX>

This example here would yield that every textbox in your application visited by the ObjectBuilder would have its properties set to "MyStyle" (Which in this case is ForeColor=Navy, and BackColor=LightSkyBlue.
The colors are set by asking for the appropiate type converter by asking for TypeDescriptor.GetConverter();

Style binding criteria
For now there are 2 main criterias in which you can bind you styles to an control:

Bind using an control type criteria
You can bind your styles to any type of control by specifying the Type attribute on the Binding. For instance: Color all controls with the Type = System.Windows.Forms.TextBox blue.
 <Binding ControlPath="." Type="System.Windows.Forms.TextBox" StyleId="MyStyle"/>

Bind using an Control Path criteria
Every control has an name in winforms. You can also assign your controls by specifing its path name. For instance.  Pain the control blue which is the control with the name
"InfoText", which is a child of the control with the name "InfoPanel" which is a  child of "InfoSmartPart" like this:
 <Binding ControlPath="InfoSmartPart.InfoPanel.InfoText" StyleId="MyStyle"/>

And then there is the third option which is actually an combination of those above.

Where to go from here?
The concept is actually quite simple yet powerful. But i know there is much more in it than i can see right now, therefore i would like you to give me lots of input. I already decided to implement the following features in the upcoming releases:

  • Multiple color schemes (Give the Unitmanager his suit matching colors)
  • Personalization (Set the colors in an propertyscreen)
  • IExtenderProvider / TypeDescriptionProvider for visual support and rendering of styles design-time

Im finishing up the intial version, i still have some last minute changes to implement (thanks to some nice tips from my collegue Marc) , so if you have any comments or ideas, let me know.
I will post the initial version somewhere around dec 20 'th.

When I first played with Linq I didnt move away from my computer for two days, neglecting my friends and family, while gazing at Linqs tremendous power to take over the world. I was particulary interrested in its sexy feature to convert an Linq expression into an so called expression tree, as you can experience with DLinq. As you probably already know,  when you write an linq query the default compiler behaviour converts the query to an delegate. But this behaviour radically changes when you assign your query to an Expression<T> class. In this way the compiler doesn’t convert your query into an delegate but into an expression tree. It is then up to you on how to process this tree in something useful and come up with the right output. There is an excellent article on this behaviour from Ian Griffiths you can find its link below.
 
Making life easier with WmiLinq
 
To show the use and power of expression trees I wrote a basic WMILinq library which makes it possible to query directly against WMI store using an LINQ like syntax. Internally it works somewhat similar as Dlinq, it translates an LINQ query to an expression tree and feeds it to an Query Builder. This analyzes the expression tree and generates an WMI WQL compatible query, which is fed to the WMI library of .NET. When this query is executed the results are mapped back using reflection into entities. I kept it all a bit simple by only supporting the basic WHERE clauses, thus joins are not supported. And for clarity i havent included any query validation, optimization or whatsoever.
  
Its all pretty beta and purely intended as an expression tree sample and educational project. But it sure is interesting to see what is possible with expression trees with such a limited implementation. If microsoft isnt building the same thing right now i might continue developing it though.
 
Lets say we want to query some process information.  For instance, query the processes which have more than 20 kernel threads:
 
using (WmiContext context = new WmiContext(@"\\localhost"))
{               
   var query = from process in context.Source<Win32_Process>() where
          process.ThreadCount > 20 && process.Name.Contains(".exe") select process;
  
   foreach (Win32_Process process in query)
   {
     Console.WriteLine(process.Name + process.CreationDate);
   }
 
  //The above results in the following WQL Query:
  //SELECT * FROM Win32_Process WHERE ThreadCount > 20
}
 
Or start doing things which make totally no sense but to show off our cross linq languages.
For example: Query the desktops and  save the result in xml.
 
using (WmiContext context = new WmiContext(@"\\localhost"))
{        
   var doc = new XDocument(
           new XElement("Desktops", (from desktop in context.Source<Win32_Desktop>()
            where desktop.Name.Contains("service") select
                  new XElement("Desktop", new XAttribute("name", desktop.Name)))));
 
   //The above rusults in the folllowing WQL Query:
   //SELECT * FROM Win32_Desktop WHERE Name Like ‘%service%’      
}
 
As you can see its easy to query every piece of  information that is available in WMI. Hardware information, network information, event logs, performance counters, installed software and so on. I never had much field experience on WMI, and i am not sure how long WMI is going to last, but WMI seemed like an easy enough query language to create an sample for.
 
Create your prototype entities with WmiClassGen
 
As you can see in the examples, im querying the WMI store using the prototype entities like Win32_Process and Win32_Desktop , these are used for specifying the WHERE clause and for mapping the flat data back into entities. Which are somewhat similar as the table classes you use with Dlinq.  Al this neatness isnt much worth if you have to write the WMI entities yourself. Its not much fun, error prone and way too much work for us lazy developers. Therefor I made little tool which generates the WMI entity for you using codedom. The tool does the same thing for WMI as SQLMetal does for databases. Creating an prototype class is as  easy like this.
 
> WmiClassGen.exe /wmi:Win32_UserAccount /out:”c:\Win32_UserAccount.cs”          
 
The first switch here tells the tool to create a prototype class for the Win32_UserAccount object. The out switch tells the tool where to save the result. There are a couple more switches
which you can easily query by passing no parameters at all.
 
And yes,  I made the same mistake as Dlinq I used attributes for mapping :) If I can find the time the next version of WMILinq it will have support for namespaces, WMI events, method invocations, associations and probably XML based mapping.
 

Remember you'll need VS2005 RTM and Linq RTM.
 
Some related reading material on this subject
 
 
The folder documentation contains a (dutch) walktrough. I will write an english one tonight.
 

Hello all!

I am honored to become a member of the skilled bloggers on bloggingabout.net and wish to thank my dear collegue Olaf for introducing me to Dennis,  and ofcourse Dennis for giving me shelter (thanks!).

Expect to see some posts on various topics such as Linq / Dlinq, DSL Tools and CAB soon enough. Im the kind of developer that likes to experiment with new technologies, partly adapt them and come up with something new. Furthermore, i'm 23 live in Holland and currently working at an Dutch company named Macaw as a Senior Developer.

While your at it drop a visit to my beloved collegues:

Olaf Conijn
Wasseem Sadiq
Marc Jacobi
Jan Paul Smit Jean-Paul Smit

Update: Added another beloved collegue: Jean-Paul Smit:-)