IgorShare Thoughts and Ideas

Consulting and Training

Archive for the ‘Software’ Category

Workflows are not only for business logic, or how to define an SMTP protocol state machine in a Workflow.

Posted by Igor Moochnick on 01/07/2008


[ Update: 


Since my first written line of code (Fall 1987, yes – 20 years ago), after I’ve learned about the block programming, I thought that the most natural way for people to interact with the outer world is via the building blocks. The idea of lego-like development always haunts me. To my opinion, the way where people drop a set of actions on the table and connect them in some logical ways, is the most natural one. The produced sequence of actions can be visually comprehended by any person who has a very basic logic understanding. So no advanced training is nessesary.

The described above, is the ideal world which is far from reality. The reality teaches us that this way of development is a very restrictive one and you can use it in a very limited domain of problems. But all this means that the block development is the most effective way of logic definition in a certain group of problems.

Recently released Microsoft Workflow Foundation is mainly targeted to define the bushiness workflows, but nobody restricts you to experiment with it and to find another killer-up for workflows. The Foundation is very flexible and extensible, so you can do with it anything you’d like.

In this post I’m going to show you how to use Workflows to define a protocol state machine. Note, that the Workflow Foundation will not generate the fastest code in the world, so you can’t use this state machine in the CPU-hungry servers, but it is a perfect example. Check the picture on the right – what can be easier than this to describe a state machine?

To show you how to use the workflows, I’ve translated the SMTP state machine, shown in my previous post . You can see the workflow on the picture above.

The following instructions can be applied to any situation where it makes sense to describe some logic as a workflow.

In order to use workflows in your application, don’t forget to initialize and start WorkflowRuntime.

   1: // Initialize workflow runtime
   2: workflowRuntime = new WorkflowRuntime();
   3: ...
   4: workflowRuntime.StartRuntime();

Each time when a new connection is detected, the SMTP Server initializes a new SMTP Session with a new Workflow that will be in charge of managing it’s state machine:

WorkflowInstance workflowInstance = workflowRuntime.CreateWorkflow(typeof(SmtpSessionWorkflow), properties);

In many cases a Workflow instance will want to know something about it’s surroundings and a reason why it was instantiated. To do this, you can pass extra parameters to the Workflow during it’s initialization. This is very similar to calling a class constructor with extra parameters. Have you noticed the extra properties parameter, passed to the CreateWorkflow method above? This is how you can create parameters collection:

// Construct workflow parameters
Dictionary<string, object> properties = new Dictionary<string, object>();
properties.Add("SessionID", session.SessoinID);
properties.Add("DomainName", "testserver.com");

And don’t forget to add corresponding public properties (it should have get and set methods) with exactly the same names and the same letters case to your workflow. You’re welcome to use the new .NET 3.0 auto-generated default property handlers notation like this:

public Guid SessionID { set; get; }
public string DomainName { set; get; }

So far so good. Here comes more interesting stuff.

There are a lot of different ways to let a Workflow to communicate with the outside world. It can call a Web Service, CallExternalMethod or a custom Activity. I’ll talk about custom Activities in some future posts, but meanwhile I’d like to cover the simplest way – CallExternalMethod. In order to let your Workflow to be aware of your external service you need to do 2 simple things:

  1. Inherit your service (external object) from an interface with [ExternalDataExchange] attribute
  2. Announce your service (external object) to the WorkflowRuntime

This is how you do the second part:

   1: ExternalDataExchangeService svc = new ExternalDataExchangeService();
   2: workflowRuntime.AddService(svc);
   3: svc.AddService(this);

And this is the interface the SMTP service inherits in my example:


   1: [ExternalDataExchange]
   2: public interface ISmtpEvents
   3: {
   4:   event EventHandler<ExternalDataEventArgs> OnStop;
   5:   event EventHandler<ExternalDataEventArgs> OnError;
   6:   event EventHandler<SmtpEventData> OnCommand;
   7:   void Write(Guid SessionID, string message);
   8: }



Here you can see a snapshot of the event handler that handles MAIL command. When you drop a CallExternalCommand activity (marked by the rectangle with the blue background), you are given an opportunity to select what method and with what parameters will be called. In our case we need to call the Write method with a string parameter message (see the interface definition). [Note: all the methods called by the workflow will have an extra Guid parameter, carrying the calling workflow’s instance unique ID]


This is how the properties of the CallExternalCommand activity should look like:

Note that message property references a workflow’s internal CommandMessage field. You can create this field manually or press on “…” (triple dot) button, that will appear to the right side of the message property value. You have a choice of creating a Field or a property. In any case the wizard will clip_image001[9]generate a code for you, but, if you don’t need to write any special logic, choose a Field. The generated code will be as simple as this:

public String CommandMessage = default(System.String);

But before the Write method will be called the Workflow should assign some value to the CommandMessage. In a simple way it can be done in the method that can be called before the Write. You can define such a method in MethodInvoking property of the CallExternalCommand activity. If you double click the property the wizard will create a code stub that you can fill in. This is how the method can look like:

private void AcceptMailActivity_MethodInvoking(object sender, EventArgs e)
    CommandMessage = "250 OK";

imageThe power of the Workflow foundation is in declaration-based development. You can define the Workflow on the fly and, even, during the runtime. You can supply rules and rules parameters in a separate external file that can be changed or generated by some external process (we’ll talk about this ]in future posts). So, if you’d like to leverage such power, you can use policies. 

You can describe a policy as a series of if-then-else statements. In the case when you’ll want a policy to ALWAYS execute some set of actions, you can set the condition to True. So the following policy (on the right) will be EXACTLY identical to the AcceptMailActivity_MethodInvoking method (described above) – note the red rectangles.


A flow that will use such a trick can look like the one, shown on the left. Note that the Workflow will execute the policy “policyAcceptHELO” activity before it’ll execute the “callWrite2” external method activity. The result will be identical, but, having the action defined in a policy, allows us to change it later without recompiling our application.

As you can see the technique of building basic workflows is extremely straightforward – you just grab simple building blocks and drop them on the playground. Draw the arrows and define the parameters. A walk in a park!

Obviously there are a lot of tips and tricks you should know if you want to build something smart and powerful, but it comes in time – just get your hands dirty and don’t be afraid of experimenting.

You can start by taking my sample project and creating your own workflow which will use the underlying infrastructure. You can use the Outlook Express to point to this server – it works. Just configure the SMTP server IP and port correctly (I guess you know how to do this). Compose an e-mail, hit Send and watch the Windows Workflows doing wonders.

For the curios minds out there:


QUESTION: Try to answer my small Quiz without peeping into the answer – what are these 2 events (see the picture on the right) doing at the top of the SMTP state machine workflow?

ANSWER: These are global events. This allows the state machine to react to such events independently of what state it is hanging right now. So, if an Error event comes,  the state machine will abandon the current execution state (there are a lot of tricks here as well) and will start executing the eventOnError logic.

The Workflows theme is vast, so we have to limit our excitement for this post. Stay tuned – more will come. Send me your questions and your comments!

As usual the full source code can be found on my web site http://igor.moochnick.googlepages.com/.




Posted in C#, Software, Thoughts, Tutorials, Workflows | 6 Comments »

Keep your code professional

Posted by Igor Moochnick on 01/06/2008

Microsoft just released new update to the Spell Checker for VS 2005 and VS 2008.

Read Spell checker update 2.1: a few bug fixes and couple of new features article for more details.

Posted in Software, Visual Studio | 1 Comment »

Announcement! Adventures of a WinForms developer in the WPF world

Posted by Igor Moochnick on 01/05/2008


Recently I start to see more and more adoption of the WPF around me, but it still happening very slowly. Mainly this is due to the extreme flexibility of the WPF and lack of the predefined control libraries. This is extremely bad for people who are perfectionists. They like to make their application shine, but can’t do this without a deep knowledge of WPF. And, while starting to learn WPF, they start to wonder around and discover more and more amazing things that can be achieved with it. It’s just impossible to stop and focus on the day-to-day tasks. Big companies can afford to have a dedicated designer, but a small dev or consulting shop can’t. And more than that, today there are only a handful of designers that know WPF in and out. Just admit it – the technology is still new and not widely adopted.

So, I’ve decided to walk you through all the small tips and tricks that I’ve passed through a year ago while playing with CTP bits of WPF and .NET 3.0. The tutorial will be based around a single application. I plan to show how different new .NET 3/3.5 technologies (WPF, WCF, WF) can be used in a series of small posts. Each time making the application smarter and more functional.

I think it’s a time to have a code alternative to Northwind database. If all the DB-related examples are written against Northwind, what are the DB-unrelated examples should be written against? Don’t you think?

I’ve put a screen-shot for a tease. If you can figure out what this application doing you can win a nice mug.

NOTE: If, by any chance this post will see a designer that knows WPF and want to join me in writing a nice WPF-related tutorials. Shoot me a note.

Posted in C#, Software, Thoughts, Tutorials, WCF, Workflows, WPF | Leave a Comment »

Hello, WordPress!!!

Posted by Igor Moochnick on 01/04/2008

I’ve decided to give WordPress a try run. There are way more services provided by WordPress than BlogSpot.

Still catching up with .NET Rocks shows. And the one I’ve listened today was about Astoria. Yahoooo!!! It’s finally here. Can’t way to start playing with the CTP bits – they were released in December.
If you haven’t heard about Astoria – listen the show yourself, you’ll enjoy it: image

In simple words: Astoria is ADO.NET Data Services. It’s a Web Services layer that exposes (any) Data regardless of a data storage using a model called the Entity Data Model (EDM), an Entity-Relationship derivative. It will work by accepting an HTTP REST requests (it’s planned to expand the transports collection later) to a resource and returning back a result in the HTTP reply. The returned data currently can be in the XML or JSON formats. So Astoria is THE DB layer for the AJAX-based applications.

ADO.Net Data Services enables easily creating data services using:

  1. Entity Framework data sources, which expose a conceptual model of data stored in relational databases (SQL, Oracle, DB2, MySql, etc)
  2. Any IQueryable + “extensions for update” (interface to support update semantics for ADO.NET Data Services) implementation. This enables ADO.Net Data Services to expose any data store via REST-based endpoints regardless of its storage mechanism.

Here is a tease. This is how the call to Northwind will look like:

static void Main(string[] args)
    NorthwindEntities ctx = new 
    ctx.MergeOption = MergeOption.AppendOnly;

    var q = from c in ctx.Customers
            where c.City == "London"
            orderby c.CompanyName
            select c;

    foreach (var cust in q)

So stay tuned. I’m going to talk more in details about Astoria.

I should say ADO.NET Data Services, but it’s soooo looooong. May be we should call it ADS.NET – A(do) D(ata) S(serviced) . NET ?

By the way, ADO stands for ActiveX Data Services. Where is ActiveX in all this?


Posted in C#, Software, Thoughts | Leave a Comment »

Let’s give a Windows Live Writer a test run

Posted by Igor Moochnick on 12/25/2007

I’ve decided to try WLW for a change. This is a test post.

Amazingly – it works !!!

Let’s see how the code coloring will work:

private void Window_Loaded(object sender, RoutedEventArgs e)
WebBrowser wb = new WebBrowser();

windowsFormsHost.Child = wb;

And it looks like the code should be pasted as HTML. Hmm… not a lot of help there.


  And pictures? It looks like they are working via Picasa Web Albums. You’re getting a free 1Gb storage account there with your Google account.

   So have fun with this new blog editor !

Posted in Software, Thoughts | Leave a Comment »

Integrating Web Browser with WPF Forms

Posted by Igor Moochnick on 12/24/2007

There are so many situations where you need to render an HTML in your forms. It may happen when you’d want, for example, to show an external web page, feed or a locally generated content like XML or an HTML. The Web Browser is extremely handy for the Web Automation (I’ll talk about it in future posts) since you have full HTML DOM available for control at your fingertips. So, having WPF now out there is not changing a thing – it’s still possible to host Web Browser inside a form.

Look how easy it is. Let’s say you want to show your blog on an application form. To do so:

  1. Create a WPF application with a Form.
  2. From the toolbox drop a WindowsFormsHost on the form. Give it a name, let’s say, “windowsFormsHost”. Make sure that the references to the WindowsFormsInteroperability and System.Windows.Forms were added to your project. To make a better presentation make the Margin = 0 – the control will fill in all the available form’s space.
  3. In the XAML source add “Loaded” attribute with “Window_Loaded” value to the tag.
  4. Add the following code to the Window_Loaded handler in the .cs file:
    WebBrowser wb = new WebBrowser();
    windowsFormsHost.Child = wb;

Build, run and enjoy!

Source code can be found as usual on my site.

Posted in C#, Software, WPF | 5 Comments »

RSS is not only for the news

Posted by Igor Moochnick on 12/23/2007

The new Syndication libraries, provided in the .NET 3.5, making creation of the RSS feeds a walk in a park. By combining them with the power of the WCF you can get an amazing results.
RSS technology allows you to reverse the client/server tandem from push to pull paradigm. Instead of client sending data to server you can publish the available data and make server to decide what to pull(download) and what to ignore, This can save a lot of valuable resources like time, network bandwidth, data transfer and processing.

To make my case more interesting and appealing let’s imagine a situation where you want to make a back-up agent that will be archiving all the text files. In order to do so, all the desktops will publish all the newly changed files that need to be archived. The server will subscribe to all the relevant feeds. In this article I’ll cover, for starters, only the client’s side and in the following articles we’ll talk about different discovery and subscription mechanisms that we have in our disposal in .NET for the server.

The following snippet shows you how to create s simple syndication feed:

SyndicationFeed feed = new SyndicationFeed();
List items = new List();
SyndicationItem item = new SyndicationItem(title, path, GetFileUri(path));
feed.Items = items;

As you can see it’s extremely easy, but this was just a half of the job. The other half is to publish the feed. There are a lot of ways to do it, but I’m going to cover one of them. Since WCF is one of the best things to use in windows services (as well as in Web services), I’m going to use it to publish the feed. Here how you will initialize the WCF host with the Feed Service as a singleton (single-instance):

FileChangeFeedService service = new FileChangeFeedService();
ServiceHost serviceHost = new ServiceHost(service);

Note: don’t forget to mark the service class as a single-instance service by adding ServiceBehavior attribute –

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,
IncludeExceptionDetailInFaults = true)]

Announce: I’ll be talking about REST in the following posts as well as a new “Give it a REST” presentation is ready for broader public to attend.One of the beautiful things that became available with .NET 3.5 is Url templates. This allows to put HTTP verbs on the methods of a web service as well as to map the Url parts (not only parameters) to a method parameters. This in many cases will eliminate any need for parsing of the data. All the mentioned above, make the WCF Web Services REST compatible.For example:

[WebGet(UriTemplate = “?format={format}”)]
SyndicationFeedFormatter Feed(string format);

This contract method will be called if a web request will come to the following URL:http://localhost/feed?format=rssThe format parameter (“rss” in our case) will be extracted from the URL and passed as a parameter to the Feed method. This allows us to seamlessly provide different feed formatting (thanks to the new WCF libraries):

public SyndicationFeedFormatter Feed(string format)
if ((format != null) && (format.ToLower() == “rss”))
return new Rss20FeedFormatter(feed);       

return new Atom10FeedFormatter(feed);

Note: if no parameters will be provided (i.e.: http://localhost/feed) the Feed method will be called with a NULL value.And here is what will glue everything together – the config file:

      <service name="FileChangeFeed.FileChangeFeedService">
        <endpoint address="http://localhost:8080/feed"
           behaviorConfiguration="webBehavior" />
        <behavior name="webBehavior">
          <webHttp />

Note the endpoint behavior. As you can guess the feed can be published over any protocol, but if you’ll want to view the feed using standard RSS feed readers, it’s better to publish it over HTTP.As soon as you’ll start the application and the service will be published – put the base Uri (http://localhost:8080/feed) in IE’s address box and you’ll see a rendered RSS feed view.Have fun with RSS feeds and don’t be afraid to explore your possibilities.The source code can be found on my site.


Posted in C#, REST, Software, WCF | 1 Comment »

Spell checker for HTML, ASP.NET, JScript, VB, C#, CSS and C++ for Visual Studio 2005 and 2008

Posted by Igor Moochnick on 12/18/2007

Finally there is no excuse for the developers to misspell class and method names. Now everybody can enjoy the luxury of the Spell checkers that we always had in office applications.

Posted in Software, Thoughts | Leave a Comment »

Part 2 – Securing Server with SSL

Posted by Igor Moochnick on 11/21/2007

It’s not a walk in the park to work with certificates. There are a lot of bells and whistles to it than it meets the eye, but I’ll try to walk you through this nightmare step-by-step in the set of the following posts. But first, I’ll show you how you can jump-start your development and encrypt your traffic with some hand-made and self-issued certificates.

There are a lot of ways to self-issue a test certificate, but I’m going to share with you the EASIEST one I use myself. Follow these simple steps, one by one, to create a test certificate:

  1. Create a root certificate:

    makecert -pe -n “CN=Igor Cert Authority” -ss my -sr LocalMachine -a sha1 -sky signature -r “Igor Cert Authority.cer”

    If you’ll run the MMC console with Certificates Add-in (Computer Account/Local Computer) and navigate to Certificates/Personal/Certificates node, you will see that the “Igor Cert Authority” certificate already installed:

  2. Create a certificate for the encryption purposes:

    makecert -pe -n “CN=myhost” -ss my -sr LocalMachine -a sha1 -sky exchange -eku -in “Igor Cert Authority” -is my -ir LocalMachine myhost.cer

    Note: the best way to use your machine’s DNS name in all the places I’ve used “myhost”

    If you’ll refresh the MMC console with Certificates Add-In – you’ll see that the new “myhost” certificate will be configured for you as well.

The result of the exercise above is the “myhost.cer” file that you can use now to encrypt your communication.

For the sake of this demonstration, let’s use the NULL SMTP server I’ve put together. This server will receive all the incoming SMTP requests and will process them as if it’s a real SMTP server. The server will encrypt the incoming communication with the certificate that was created in the steps above.

  1. Create a certificate object from the CERT file:
       1:  X509Certificate serverCertificate = X509Certificate.CreateFromCertFile("myhost.cer");
  2. As soon as the new client connection is established – encrypt the stream with this certificate:
       1:  TcpListener listener = new TcpListener(IPAddress.Loopback, port);
    2: ...
    3: TcpClient client = listener.AcceptTcpClient();
    4: ...
    6: // Create the SslStream using the client's network stream.
    7: SslStream sslStream = new SslStream(client.GetStream(), false);
    9: // Authenticate the server but don't require the client to authenticate.
    10: sslStream.AuthenticateAsServer(serverCertificate, false, SslProtocols.Tls, false);

In order to test the server, I’ve used the Outlook Express (it is in most cases installed by default on every machine). Don’t forget to tell the Outlook Express that the communication should be secure (note the check box in the Outgoing SMTP mail section):

After the configuration is complete – have fun by sending e-mails. The sever will process all the outgoing traffic over the encrypted channel:

You can download the source of the NULL SMTP Server from my site here.

Tune-in for the upcoming set of articles that will show you a lot of new and cool staff.

Posted in C#, Software | 2 Comments »

Visual Studio 2008 and .NET 3.5 Released

Posted by Igor Moochnick on 11/21/2007

I don’t want to announce the obvious, but just point you to a great blog to check for the news. Go to Scott Gu’s Blog for the latest news about the Visual Studio and .NET features.

Posted in C#, Software | Leave a Comment »

%d bloggers like this: