How to describe object state

Let’s say that we’re developing an application to manage invoices. Invoices will be created, modified, sent, (hopefully) paid or rejected, …

Depending on the stage that an invoice is in, we can perform different actions on it. For example: it will be very rare that an invoice that was rejected will be paid. Or it shouldn’t be allowed to modify an invoice once it has been sent. So how can we model this in such a way that it becomes easy to develop it, and – in extension – to test it?

Let’s first define some things:

What is a State

A state is a condition during which

  • an object satisfies some condition
  • an object performs some activity
  • an object waits for some event

Examples of states in the invoicing example can be:

  • Creating – we are creating the invoice
  • Modifying – after the invoice was created we modify it
  • Sent – The invoice has been sent to the customer, in some way (like e-mail, snail mail)
  • Accepted – the customer has accepted the invoice
  • Rejected
  • Expired – the expiration date of the invoice is passed
  • Paid – this should be the end state of an invoice

An event is a significant occurrence

  • Something that happens at a point in time.
  • Has no duration.This is not always true. When we send an invoice to the customer, this will take some time. But we consider this as an immediate action.
  • One-way transmission of information. Typically nothing is returned from an event.

State Machine Diagram

image

This simplest form of this diagram is composed of the following elements:

  • States: initial state, final state, simple state
  • Transitions: are indicated by a labeled arrow.

As you can see, with only these 2 elements we can express a lot already. We see immediately that when an invoice has been sent, it can’t be modified anymore. We also see that there currently are no actions when an invoice is expired or rejected, which may indicate that our analysis is incomplete.

Composite state

image

When an invoice is expired we may want to send a reminder, then maybe a second reminder, and then send the invoice to our lawyer. This can all be part of the expired state. So we can make this a composite state, containing sub states. The diagram shows it all. And of course we can do the same with the rejected state.

Actions

image

When entering or leaving a state you may want to perform some actions. In the diagram above when we enter the “Paid” state we always mark the invoice as paid. We put this on all 3 the arrows, indicating that this must be done in 3 instances in our code. Not so DRY, is it?

image

So instead we create an entry action on the “Paid” state, that says: “every time we enter this state we will “Mark Paid” the invoice.” This has several advantages:

  • The diagram becomes simpler (KISS), it contains less overhead.
  • We can’t forget the “Mark Paid” on one of the arrows.
  • For the implementation we now know that entering the “Paid” state also means marking the invoice as paid.
    • The implementation just became easier. This code can easily be derived from the diagram.
    • The tests just became more atomic. We just need to test that the method is called when the state is entered, and we’re good.

This makes most sense when there are multiple paths into the “Paid” state.

We can do the same with the exit action, which will be called when we leave the “Paid” state.

The “do” action will be called (repeatedly) while in the “Paid” state.

Conclusion

There is much more to say about State diagrams, but that will be for another post.

Happy drawing!

References

http://www.uml-diagrams.org/state-machine-diagrams.html

https://en.wikipedia.org/wiki/UML_state_machine

Posted in Analysis, Codeproject, Development, OOAD, UML | Tagged , | 1 Comment

Let’s fix Windows Live Writer on Win10

The problem

I installed Windows 10 on my computer, and then to make blogging easy I wanted to install Windows Live Writer. So I went to https://www.microsoft.com/en-us/download/details.aspx?id=8621 to download it and well enough, I received the setup file wlsetup-web.exe in my download folder.

So things are easy from here: double-click the exe and it will install. Not on Window 10 (which is great, by the way). I received an error message (in Dutch, so I won’t put a screen shot here) telling me that something had gone wrong.

The solution

As always Google is your friend. I found an article explaining what to do, I’ll give you the solution immediately instead of letting you wade through all the answers. It turns out that there is a version that will work, but it is hidden at http://windows.microsoft.com/en-us/windows/essentials.

The download at this location will work for Windows 10.

I hope this short post may help someone. If it helped you then please leave a comment.

Posted in Computers and Internet | Tagged , , | 1 Comment

How to obtain the value of the selected radio button

Here is a simple way to get the value for the selected button in an html form, using jquery:

<form>
<input type=”radio” name=”status” value=”1″ /> Free <br />
<input type=”radio” name=”status” value=”2″ selected /> Reserved <br />
<input type=”radio” name=”status” value=”3″ /> Not available <br />
</form>

 var x = $(‘input[name=status]:checked’).val();

x will now contain 2.

Posted in Development | Tagged , , | 4 Comments

Could not load file or assembly ‘System.Web.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35’

When creating a new MVC5 application using VS2013 I got the following error:

Could not load file or assembly ‘System.Web.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ or one of its dependencies. The located assembly’s manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

I tried the following, to no avail:

  • Updated the MVC 5 package (Nuget)
  • Uninstalled / installed MVC5 (Nuget)
  • Reviewed, then removed binding redirects in the web.config
  • Repaired VS2013 installation
  • Installed VS2013.4

What did help was:

Install-Package Microsoft.AspNet.WebApi

After this my MVC5 Application was running flawless.

Posted in .Net, Development, MVC, MVC5, Web API | 2 Comments

“Object reference not set to an instance of an object” when building my cloud project

In my Azure project I have a worker role and a wcf role. When compiling it failed (with no obvious reason) with this message in the output window:

Error: Object reference not set to an instance of an object

There is no other reference as to where this error would originate from. So it has to come from the builder.

The “fishy” solution to this problem (in my case) was to unload the worker role project, rebuild, then load the worker project again and rebuild all again. Now it is working again.

This is a workaround that worked for me in this instance. I didn’t investigate the root cause of this problem. On StackOverflow there are some threads describing the same problem, so I suppose that there will shortly be updates to VS / Azure SDK to solve this problem.

http://stackoverflow.com/questions/19162614/object-reference-not-set-to-an-instance-of-an-object-when-building-my-cloud-pr

Posted in .Net, Azure, Development | Leave a comment

Managing IIS Express settings

Problem statement

For ease of use I had put a web application using IIS Express at port 80. This implies that later on using IIS (the real one) didn’t work anymore because it uses port 80 by default too.

So I started looking in VS2012 for a way to change IIS Express settings. This doesn’t seem to be possible, so here comes the way that I found.

Changing IIS Express settings

This is a bit tricky.

  1. Start an application in IIS Express (in Visual Studio).
  2. The IIS express icon will appear in the Notification Area (by default right of the taskbar)
  3. Right-click the icon > Show all applications
  4. Click on the site that you want to change (not on its URL, as this will open the web application in your browser). Below you find its path, and more importantly the location of its config file (URI).
  5. Click on the config file URI and you see the contents of it. Now you can change the settings. It *may* be a good idea to first take a backup of this file.
Posted in Geen categorie | Tagged , | Leave a comment

XslLoadException: The type or namespace name ‘SecurityRulesAttribute’ does not exist in the namespace ‘System.Security’ (are you missing an assembly reference?)

While porting a project from .Net 3.5 to .Net 4 we got this weird error. The error occurs when loading an XSLT in memory. Here is the failing piece of code (simplified):

private static XslCompiledTransform ReadXslt(string fname) { XslCompiledTransform xsl = new XslCompiledTransform(); XsltSettings settings = new XsltSettings(false, true); xsl.Load(fname, settings, new XmlUrlResolver());

return xsl; }

The XSLT file being loaded contains C# script:

<msxsl:script language=”C#” implements-prefix=”user” xmlns:user=”urn:my-scripts” xmlns:msxsl=”urn:schemas-microsoft-com:xslt”>
  <![CDATA[
   public string Format(string s, int n)
   {
     if (s.Length < n)
     {
        s = new string(‘0’, n – s.Length) + s;
     }
     return s.Substring(0,n);
   }
  
   // other functions

    ]]>
</msxsl:script>

According to several websites setting the enableScript property in the XsltSettings to true should solve the problem and mostly they are right. But for some weird reason loading the XSLT in this format in a VS Test project keeps failing. I haven’t found the reason, but I did find the working solution!

Checking security on the XSLT files, moving the files directly under the application, … all didn’t work. So moving this application to production would work, only the tests fail Emoticon die tong uitsteekt

Looking further I fell on this web site: http://msdn.microsoft.com/en-us/library/system.xml.xsl.xsltargumentlist.addextensionobject(v=vs.100).aspx. They suggest to use extension objects containing the C#code instead of writing the code inside the XSLT file. This requires a bit more work on the C#side, but it works everywhere (including in the test project).

image

The (partial) code:

private static readonly XmlUrlResolver _myResolver = new XmlUrlResolver();

private static XslCompiledTransform ReadXslt(string fname)
{
    XslCompiledTransform xsl = new XslCompiledTransform();
    XsltSettings settings = new XsltSettings(false, true);
    xsl.Load(fname, settings, _myResolver);
   
    return xsl;
}

// Additional work in transforming the file (remove C# code from the XSLT file)

private class XsltFunctions
{
    public string Format(string s, int n)
    {
        if (s.Length < n)
        {
            s = new string(‘0’, n – s.Length) + s;
        }
        return s.Substring(0, n);
    }
    // Other functions
}

private static XmlDocument TransformOrganisation(string fname, XmlDocument xml)
{
    // Create an XsltArgumentList, to be passed into the Transform() function
    xsltArgs = new XsltArgumentList();
    XsltFunctions ext = new XsltFunctions();
    xsltArgs.AddExtensionObject(“urn:my-scripts”, ext);

    // Transform in memory
    XslCompiledTransform xct = ReadXslt(fname);
    XmlDocument xformed;
    using (MemoryStream ms = new MemoryStream())
    {
        XmlWriter wtr = XmlWriter.Create(ms);
        xml.WriteContentTo(wtr);
        wtr.Close();

        ms.Seek(0, SeekOrigin.Begin);            // reset stream
        XmlReader rdr = XmlReader.Create(ms);
        using (MemoryStream ms2 = new MemoryStream())
        {
            XmlWriter wtr2 = XmlWriter.Create(ms2);

            xct.Transform(rdr, xsltArgs, wtr2);
            xformed = new XmlDocument();
            ms2.Seek(0, SeekOrigin.Begin);        // reset stream
            xformed.Load(ms2);
        }
    }
    return xformed;
}

Using C# script (or any other not-XSLT extensions) inside XSLT files is now being deprecated, so this is the way to add additional functions to your XSLT files. It is safer because it won’t allow somebody to change your XSLT file and run arbitrary code.

Posted in .Net, Development | Tagged , , | 1 Comment

Advanced logging in IIS 7.5

In the standard installation of IIS 7.5 it is not possible to log the incoming requests, not the outgoing responses. The reason for this is probably that Microsoft wants to keep the attack surface as small as possible. But I needed logging so I asked the web master at TMME (thanks Kim) how to do this.

MS’s iis.net offers free extensions: http://www.iis.net/download/AdvancedLogging
http://learn.iis.net/page.aspx/579/advanced-logging-for-iis—custom-logging/

Using the first link to install the Advanced Logging I got an additional icon in the web app properties page:

image

Possible error:

When opening the “Advanced logging” you’ll see that 1 item is present already. This is defined at site level and inherited to the app level. When you try to modify this item you’ll get:

80070032

This is not the most “speaking” error, but it indicates that you’re not supposed to modify at this level. You can either modify the logging at the site level, or create an additional entry for the purposes of your web app.

BTW, the second link explains how to set up the logging, in case you wondered.

Posted in Computers and Internet, Development, IIS, Logging | Tagged , , | 2 Comments

Using a TreeView in WPF

Using a tree view in Windows Forms is straightforward, but in WPF the control has undergone a lot of modifications. In this blog I’ll describe how to do some tasks that seem to be easy enough, and describe some caveats.

Scrollbar problem

This is the sample window (Don’t mind the colors, they’re just to show the point):

<Window x:Class=”FindInSvclog.MainWindow”
        xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
        xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
        Title=”MainWindow” Height=”350″ Width=”568″>
    <StackPanel>
        <Canvas Width=”500″ Height=”228″ Name=”searchCanvas”>
        </Canvas>
        <Grid Grid.Row=”1″>
            <Grid.RowDefinitions>
                <RowDefinition></RowDefinition>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width=”1*”></ColumnDefinition>
                <ColumnDefinition Width=”1*”></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <TreeView Background=”#FF00FF00″ Name=”FileTree” AlternationCount=”1″ />
            <GridSplitter Width=”5px” ResizeDirection=”Columns” Background=”DarkSlateGray”/>
            <TextBlock Grid.Column=”1″ Background=”#FF0000FF” />
        </Grid>
    </StackPanel>
</Window>

The highlighted TreeView doesn’t have a vertical scrollbar, even though it should.

The problem isn’t related to the TreeView, but to the StackPanel: In a StackPanel every item gets all the space it needs. So the StackPanel doesn’t report its current size back (this is the correct behavior!). Changing the StackPanel into a Grid solved the problem completely.

Posted in .Net, Development | Tagged , , | Leave a comment

Rediscovered the Debug attributes

There are 2 attributes that can easily be applied to your classes / methods to modify the behavior at debugging time. The attributes don’t change the runtime behavior of your code.

[DebuggerDisplay]

This attribute defines how you’ll see a type or member in the debugger window (like the quick preview, Shift-F9).

There are 3 possibilities:

  1. This attribute is not applied, and the class doesn’t implement ToString( ). In this case the type of the object is shown (which is the default behavior of Object.ToString( ) ).
  2. This attribute is not applied, but the class implements ToString( ). The return value of ToString( ) is shown. Make sure that ToString( ) doesn’t change your object data, or that it doesn’t take ages to execute.
  3. The attribute is applied. Even when ToString( ) is implemented the DebuggerDisplay attribute will be applied.

Example:

[DebuggerDisplay(“Context= {_ctx.Brand}, {_ctx.CountryCode}”]
class SuffixSync
{
    private readonly MyContext _ctx = MyContext.GetContext();

    [ … ]

}

image

[DebuggerBrowsable]

This attribute determines if and how a field or property is displayed in the debugger variable windows.

This example will prevent the debugger to show the e_gateway field:

class SuffixSync
{
    private readonly MyContext _ctx = MyContext.GetContext();
    private readonly IMediator _mediator;
  
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private readonly Gateway _gateway = new Gateway();

image

Other values for the enumeration are

  • DebuggerBrowsableState.Collapsed: shows the element as collapsed.
  • DebuggerBrowsableState.RootHidden: indicates that the member itself is not shown, but its constituent objects are displayed if it is an array or collection.

Reference:

http://msdn.microsoft.com/en-us/library/ms228992(VS.90).aspx

Posted in .Net, Debugging, Development | Tagged , | Leave a comment