Friday, 27 January 2012

LINQ to SQL Dynamic Stored Procedures

linqpadlogo[Concrete/Little bit interesting] I wanted to call stored procedures by name using a string parameter. Sounds simple and with ADO it's a breeze. But with LINQ to SQL, life is a little more complicated. Here is how I cracked the problem.

 

 

 

LINQ to SQL

In Visual Studio, when you add LINQ to SQL Classes to you project, you are creating a class that provides a convenient set of classes for managing tables, views, functions and stored procedures:

image

When you add LINQ to SQL Classes to your project, Visual Studio creates a .DBML file set. These files describe the managed entities with partial class definitions. The main class is derived from System.Data.Linq.DataContext and provides the link between your code and the database connection. LINQ to SQL works through defining class members that maps LINQ onto the entity and makes use of attributes to map columns, parameters and returns to .Net classes.

LINQ to SQL Classes takes a lot of code out of your application and is easy to use. For example, to call a stored procedure, simply open the .DBML, drag a stored procedure from a data connection on the Server Explorer or Toolbox over onto the Object Relational Designer: this creates the class entries that maps the entity onto LINQ, then from your code, call the stored procedure as shown below:

using (CatalogueDataContext db = new CatalogueDataContext())    
{
db.usp_Biometrics_Update_OperatorFingerprint(input.OperatorId, input.Fingerprint, false);
}

In the above example, I’m calling the stored procedure usp_Biometrics_Update_OperatorFingerprint which is defined in a database called Catalogue, LINQ to SQL provides me with the data context on which the stored procedures are defined. All I need to do us use an instance of CatalogueDataContext and from this, call the stored procedure. Because it’s all about classes, Visual Studio can help me with the parameters and returns through Intellisense. 

The Problem

Under most circumstances calling a stored procedure as described above is sufficient. But there are times when you need to call a stored procedure by name, not by class method. Say for example you have a bunch of stored procedures called:

usp_get_TableName_As_XML

where TableName is a name of a table, any table. The implementation of this stored procedure for any given named table may be complex, for example, they may include selecting output from child tables where foreign key are present. So in this example, a table called Customer may return the following XML:

<rows>
<row>
<customerId>1</customerId>
<customerName>Nigel</customerName>
<addresses>
<address>First Postal Address<address>
<address>Second Postal Address<address>
</addresses>
</row>
</rows>
 
So for each row of Customer data, there may be multiple address rows.
 
For another table called Car the data is simpler:
<rows>
<row>
<registration>AAAAAAA</registration>
<make>Chrysler</make>
<model>Grand Voyager</model>
</row>
</rows>

So for each table, I need a specific stored procedure that returns table data as XML. Each one of these stored procedure returns the XML data as an output parameter and all the stored procedures have the same signature. Below is an illustration of the stored procedure for the table Car:
 
Create Procedure usp_get_Car_As_XML
@xml XML OUTPUT
AS
BEGIN
SET NOCOUNT ON

set @xml = (
Select
registration, make, model
From
Car
)
For XML RAW('row'), Root('rows'))

Return @@Error
END

So the problem is, from code, how do I call the stored procedure for a given table name, returning the XML representation of that table?

The Solution

Well of course I could use some sort of if…elseif… or big switch statement. This will work but I’m not keen on big switch statements. What I really want is to call the stored procedure by name. Fortunately, we can use .Net reflection to find the method in the data context and execute this method:

using (CatalogueDataContextEx db = new CatalogueDataContextEx())
{
XElement xml = null;
String script = String.Format("usp_get_{0}_As_XML", tableName);
db.CallScriptByName(script, ref xml);

//handle the results in xml variable
}
Notice that in this example, the data context is called CatalogueDataContextEx. This is a derived class based on CatalogueDataContext and implements the CallScriptByName() method:
public partial class CatalogueDataContextEx : CatalogueDataContext
{
public void CallScriptByName(String script, ref XElement xml)
{
var sp = typeof(CatalogueDataContext).GetMethod(script);
var result = this.ExecuteMethodCall(this, sp, xml);
xml = (XElement)result.GetParameterValue(0);
}
}

So what is going on here?

In my derived class I have access to all public and protected methods of the data context. This is important as I want to call the ExecuteMethodCall() method on the class, which is protected.

I’m using reflection to get a reference to the stored procedure by name, This is then executed using the ExecuteMethodCall. This call takes a list of the parameters to this stored procedure. In our case, there is only a single output parameter for the XML.

Once the call is made, the results are passed back in a IExecuteResult return parameter. This return can be used to access the call’s parameters, in our case the xml output parameter.

And that’s it.

Future Improvements

This implementation is not completely dynamic. Specifically, the CatalogueDataContext must have definitions for the stored procedures I’m going to call. A better implementation would use a generic data context and build up the method to call.

Wednesday, 21 September 2011

Using IActiveAware and INavigationAware

prism[Concrete/Little bit interesting] The Microsoft Prism framework provides a couple of very useful interfaces for managing awareness of view activation and navigation.

 

 

 

IActiveAware

IActiveAware is a simple interface you can implement on your views to indicate that you want the view to be notified when it is made active or inactive. It looks like this:

public interface IActiveAware
{
    /// <summary>
    /// Gets or sets a value indicating whether the object is active.
    /// </summary>
    /// <value><see langword="true" /> if the object is active; otherwise <see langword="false" />.</value>
    bool IsActive { get; set; }

    /// <summary>
    /// Notifies that the value for <see cref="IsActive"/> property has changed.
    /// </summary>
    event EventHandler IsActiveChanged;
}

The IsActive flag lets you know if your view is active, and the IsActiveChanged event will fire when that state changes.

If you implement this on your view class, then you need to ensure the event gets fired when the state is changed by the region behaviour. You do this by adding the IActiveAware interface to your View-Model:

public class LoginViewModel : NotificationObject, IActiveAware, INavigationAware
{ 
}

An example of the implemented interface is shown here:

#region ViewModel activation
private bool _IsActive = false;
public bool IsActive
{
    get
    {
        return _IsActive;
    }
    set
    {
        _IsActive = value;
        if (value)
            OnActivate();
        else
            OnDeactivate();
    }
}

public event EventHandler IsActiveChanged;
#endregion

In the above example I use the changing state of IsActive to trigger the private methods OnActivate() and OnDeactivate(). These methods are thus called when the view active state changes.

IActiveAware Example - Managing Devices

A good example of the use of IActiveAware is the subscription to an control of devices. We use event aggregation to interface with physical devices, that is, we subscribe to device notifications. The simplest scheme is to subscribe to all the device events in the View-Model constructor:

//Subscribe to device events
eventAggregator.GetEvent<MagneticStripeReaderEvent>().Subscribe(MagneticStripeReaderInputReceived);
eventAggregator.GetEvent<ScannerEvent>().Subscribe(ScannerInputReceived);

Of course, this means that the View-Model will be called back on device events during the entire lifetime of the module housing the View-Model and the associated views.

To ensure you only act on the device events when your view is the active view, simply use the IsActive property appropriately in the event callback:

private void ScannerInputReceived(ScannerEventParameter param)
{
    //Handle input if active and OperatorId has focus
    if (IsActive == false || OperatorHasFocus == false)
        return;

    if (!string.IsNullOrEmpty(param.Barcode))
    {
        OperatorId = param.Barcode;
        ValidateLoginInput(false, null);
    }
    else
    {
        ProgressMessage = Resources.Message_InvalidInput;
    }
}

OnActivate() and OnDeactivate()

These methods when implemented should be used to handle the View-Model initialisation and termination state. For example, in a Login screen, during OnActivate(), the View-Model should initialise the various entry fields and properties used to control the view:

private void OnActivate()
{
    eventAggregator.GetEvent<ChangeTitleEvent>().Publish(Properties.Resources.Title_Login);
    ProgressMessage = String.Empty;
    ChangingPassword = false;
    NewBiometricEntry = false;
    LoginWithPassword = configurationManager.GetBool(ConfigurationNames.LoginWithPassword);
    ResetOperatorPassword();

    LogoutCurrentOperator();
}

Here we are setting the title through a published event, clearing the progress message, clearing some flags (used to control the visibility state of page elements), resetting the OperatorId and Password and ensuring we are logged off. These operations will be performed every time a view in this module is activated.

IActiveAware Limitations and INavigationAware

Responding to IActiveAware works fine in a module that supports a single view. In this scenario, the View-Model activation is one-to-one with the View activation. However, if there are more than one view associated with a View-Model, you will have to implement INotificationAware:

public interface INavigationAware
{
    bool IsNavigationTarget(NavigationContext navigationContext);
    void OnNavigatedFrom(NavigationContext navigationContext);
    void OnNavigatedTo(NavigationContext navigationContext);
}

This interface when implemented provides callbacks to handle the navigationContext switch in the form of OnNavigatedFrom() and OnNavigatedTo(). A typical implementation here is to keep a copy of the navigationContext passed to the OnNavigatedTo(). This can be used later to perform view-to-view navigation:

#region Navigation Aware for view switching in this module
private IRegionNavigationService navigationService;

public bool IsNavigationTarget(NavigationContext navigationContext)
{
    return true;
}

public void OnNavigatedFrom(NavigationContext navigationContext)
{
}

public void OnNavigatedTo(NavigationContext navigationContext)
{
   navigationService = navigationContext.NavigationService;
}
#endregion

and to perform view-to-view navigation (for example, Go Back):

private void onGoBackHandler()
{
    if (navigationService.Journal.CanGoBack)
    {
       navigationService.Journal.GoBack();
    }
}

Note that in the above implementation of the interface we are returning true from the IsNavigationTarget() method. This method is called by the framework to determine if the current views should be reused for the navigation target. Returning true indicated the views should be reused. Since we pre-create all our views, you should return true.

Thursday, 8 September 2011

This is a test Article on the blog

203-sixtoes[Concrete/Interesting]

 

Here is a picture

Like it?

 

 

Actually, this is a test for using Windows Live Writer to publish to SharePoint Wiki. Which sounds easy, but you guessed it, it’s not.

I’ll let you know how I get on.

newrule

Frankly, it’s all rather disappointing. I guess someone at Microsoft, looking to make SharePoint a little more useful thought “well it’s good at lists and HTML docs, if you add a template with an on-page editor, hey presto, you’ve got a Wiki”. Only, it’s not that simple and the editor is far too lightweight.

Windows Live Write (WLW) on the other hand is a well thought out, powerful tool. Clearly the best Blog editor in my mind. It’s the reason I have a Windows VM on my Mac.

So I gave it a go and WLW doesn’t want to talk to the Wiki because it’s not a blog, doesn’t support the APIs, just a list with an editor.

However, it was suggested that I could author my pages against my SharePoint blog. Great. It worked brilliantly. WLW talks to SharePoint blogs and does an excellent job of it.

Once published, all you have to do is open the blog in SharePoint for editing, copy the raw HTML and paste it to the Wiki.

It works, but it’s far from perfect

The main advantage of this is the editor in WLW. It’s excellent, support plug-in for styles, adopts site templates. I’m using it now and what I type is what I will see on the blog site.

A very useful benefit of this approach is image publishing. It’s a royal pain in the arse when editing on the SharePoint Wiki. Using this method, images are published to my blog and can be referenced in the Wiki without need to upload anything or mess around.

But the main problem is I’m publishing to a blog and have a second copy in the Wiki. I may even have a third local copy on my Mac saved by WLW. These copies can easily get out of step.

Worse still, the images are associated with a my blog and my account, not the Wiki. If my account gets deleted, I guess these resources will disappear.

Finally, the point of a Wiki is that the documents are live and through collaboration, the Wiki will change over time. So my copy on my blog is very likely to be out of step. This could result in changes being lost as the WLW view of the document is that of the blog, not the Wiki.

You could of course create a shared blog and keep this as the master document site. I thought of this and it occurred to me that if I was to do this, I might as well try to use that as my Wiki. Well that made the whole exercise seem pointless.

Improved on-page Editing

You can of course change the Wiki template to use a more advanced editor. This is a very satisfactory solution. One of the recommended ones is the Telerik RadEditor that can be integrated into SharePoint 2010:

http://www.telerik.com/help/aspnet-ajax/moss-installing_radeditor__radgrid_web_parts_on_sharepoint_2010.html

Problem is, it cost about $800. And I’ve already spent half that purchasing a better Forum web part because the out of the box solution from Microsoft is just rubbish. Starting to sound like throwing good money after bad,

Microsoft SharePoint Designer 2010

Ok, time to bring the big guns out. I’m only trying to update pages on the Wiki!

Well, this is a powerful tool. It’s also typical of the development/management tools from Microsoft. Yes, I can edit the Wiki, but it’s not easy. Ultimately, this tool provides a Visual Studio / Microsoft Expression type of view on the site and site document. Not really what you want.

newrule

Conclusion

I’ll keep looking for a better solution to editing on-page in SharePoint. Maybe Microsoft will provide a link between WLW and SharePoint Wiki.

However, until a solution is found, the SharePoint Wiki experience will be very disappointing.

Given that for a Wiki, the ease of authoring and content creation is as important as the content itself, you might just decide that SharePoint doesn’t even qualify as a Wiki.

Monday, 30 May 2011

Fermat’s Last Theorem

image[Concrete/Interesting] A while back I saw a BBC Horizon programme about Fermat’s Last Theorem and the mathematically heroic work by Andrew Wiles in raising the Taniyama-Shimura conjecture from a mere conjecture to a theorem and using this to show a contradiction between the predictions of the epsilon conjecture and Wiles’ proof that all such elliptic curves must be modular. This contraction implies there are no solutions to Fermat’s equation, hence Fermat’s equation is true.

 

Like many, I was excited about this proof and although difficult to follow (Elliptic Curves are hard to understand, no kidding), the proof was without a doubt a clever piece of late 20th century mathematical wizardry, full of deep insight and imagination.

But something was wrong. It was all to clever, all too complex, all to contemporary. So to mark the birth of my new baby boy, Khaliq, I decided to provide a simple proof, maybe not complete in mathematical rigor and probably nowhere near robust enough for Cambridge Mathematics, possibly not even correct, but something I think 17th century mathematicians would have found interesting. See what you think.

newrule

To my son, Khaliq George Mahmood, born 26th May at 11.24pm (7lb, 12oz). Hope you find life as fascinating as I have.

newrule

Fermat’s conjecture is so tidy, so elegant and simply described as:

fermat

That is to say, for all integers, except 2, the equation has no non-zero integer solutions. For 2, where we square x and y, the sum of the squares of x and y is equal to the square of z

For n = 2, this may be familiar to some of you, and is known as The theorem of Pythagoras. Pythagoras, mathematician, philosopher and scientist, provided a proof for his equation based on logic and simple geometry. In fact, the equation was known to many at the time, but is was the application of mathematical rigor that gave Pythagoras the title over the equation.

It is from the relationship between the equation and a right angle triangle that I will start my ‘proof’’.

Mathematical Rigor and Proof

Mathematics is complicated, at least for the majority of us.I don’t want to pretend I am a mathematician or blessed with anything but a cursory level of competence in mathematics.

For a proof to stand on it’s own two legs it must be a convincing argument and this must be based on deductive reasoning which shows a statement to be true in all cases. Ok, so I don’t think I’m going to be able to do that. But I hope I can present an somewhat unproven proposition that I believe to be true – that, at least is a conjecture, and is something others may be able to prove.

So away with the shackles of mathematical rigor, eyes down for what I hope is an interesting conjecture:

Not Now Nigel’s Conjecture

Above n=2 where n is the geometric dimension, there are no simple object with 3 ‘flat’ boundaries.

By way of explanation, for n=2, the equation maps to a 2 dimensional polygon with three flat or straight line boundaries, commonly known as a Triangle:

Pythagoras_theorem

But for higher dimensions, there are no object with 3 ‘flat’ sides. For example, for 3 dimensions, there is no polyhedron with 3 planar surfaces. The nearest is something like a Tetrahedron with 4 sides.

In proving this conjecture and in saying that Fermat’s equation is represented by this geometry, there lies a simple proof to Fermat’s Last Theorem. Q.E.D.

newrule

Saturday, 25 December 2010

Carving Rings

45614449[Abstract/ Sharing]  To close off 2010, I’m posting an article on how to carve a pair of linked rings from a single block of wood. It’s very simple so if you have a chance, why not have a go yourself.

 

 

This post is dedicated to the memory of Julian Guy Tulloch, who died peacefully on the 12th December 2010, aged 78.

Julian first introduced me to carving.

newrule

We start with a small block of wood, 5cm by 5cm by 10cm. The exact dimensions are not too important, you just want a block of wood that is rectangular in nature with a square end:

IMG_0715

I’m using Tilia or Basswood which is good for carving – not too dense and very little grain. You can find this type of wood at craft shops, often described as ‘Carving Blocks’.

Extruded Cross

The first step is to mark out an extruded cross using a pencil:

IMG_0716

I made the cross 1cm wide. The cross is drawn on the two square ends of the block of wood and joined up over the length of the block. Note, the extruded cross is the shaded area on the diagram.

Now, using a small Tenon Saw, you should remove the four corner pieces. These are the un-shaded areas in the diagram above. This should leave the extruded cross:

IMG_0711IMG_0712

Notice that I don’t cut right up to the line. I leave a little margin for error when using the saw. To finish off the extruded cross, I use a carving/milling tip on my Dremel hand tool:

IMG_0714IMG_0713

So far, so good. Now for a little vacuuming!

Overlapping Discs

Next we need to transform our extruded cross into two overlapping discs. The discs are inside the cross, you can see them on the diagram below:

IMG_0720

Because my cross was 5cm across the face, the discs are 5cm in diameter:

IMG_0719

The important bit is the overlap. One disc needs to overlap the other. There needs to be sufficient overlap to carve out the rings, one from each disc. I have decided to have each disc overlap half way through the other disc.

Again, I will use my Tenon Saw to cut away the excess wood. First step is to remove two end pieces – ‘A’ and ‘B’ on the diagram below:

IMG_0721

On the carving, the areas to remove are shown marked A and B:

IMG_0722IMG_0723IMG_0724

After cutting away the wood with the saw we have the following:

IMG_0725IMG_0727IMG_0728

Now we have to remove the rest of the excess wood. In the diagram below, this is marked ‘C’, ‘D’ and ‘E’:

IMG_0729

IMG_0730

‘C’ is a complete bit of the extruded cross and we remove this using the saw:

IMG_0731IMG_0733

Can  you see the two overlapping discs yet?

IMG_0732

Ok, now remove the little pieces ‘D’ and ‘E’. This is the same as ‘A’ and ‘B’. Look, two overlapped blocks:

IMG_0734IMG_0735

It is worth marking out the discs and removing the excess wood to reveal the discs. First, mark out the discs with a pencil. I’m draw these by hand:

IMG_0736IMG_0737

Then remove the excess wood. I’ve used my Dremel for this but carving chisels or even sanding will work. And now we have two interlinked discs:

IMG_0741

Again, let’s tidy up.

Finding the Rings

My discs are 1cm wide. Because of this, my rings are going to be roughly 1cm in diameter before any sanding.

At this point the rings are embedded in the edge of the discs. We need to define the rings by removing the centre of the discs. We are going to do this in two steps. The first step is to clear the majority of the centre of each disc. We will still be left with ring connected together. The second step is to finally free the rings.

For each disc we want to remove the shaded area ‘A’ from as shown in the diagram below:

IMG_0743

You must be very careful not to remove any of the ring or any of the second ring. The result should look like this:

 

IMG_0747

OUCH!!! I cut my hand – be careful.

Ok, tricky  bit coming up so time to tidy up and have a rest.

Tricky Bit – Free the Rings

This bit is a little tricky and can go badly wrong. If you remove too much wood, you may break the rings. The two rings are joined, but only by a small wall of wood. Take a close look at the rings and you can make this out.

The process for removing this wall and separating the rings is a little hard to describe but I will give it a go:

IMG_0756

In the diagram above I’m looking down on one of the rings. There are four points on the top surface that need to be chiselled – ‘A’, ‘B’, ‘C’ and ‘D’ Similarly, from the bottom side of this ring, there are four more points – ‘E’, ‘F’, ‘G’ and ‘H’.

Notice that these 8 points are the 8 corners of a cube. Not a normal cube with straight sides, rather one with concave sides:

IMG_0762

Try to see this in the rings before you start to carve. You want to chisel into these eight points as evenly as possible and when chiselling, you need to chisel diagonally towards the centre of the cube. Bit, by bit you have to remove the cube from the corners, outside to the centre. When the cube has been chiselled away, the rings will magically free:

IMG_0758

Remember, don’t rush it and it should work.

Another tidy up.

Last step – Sanding and Varnish

To complete the rings, you need to sand away excess wood to reveal the rings. You can sand away until you are happy with the results. Again, be careful as you don’t want to spoil the rings at this stage. Once you have sanded to reveal the rings, you need to varnish the rings.

The trick with varnishing is to apply a coat, then sand away the coat. Then repeat. The more times you repeat this, the harder the finish.

Here are my rings, not yet varnished but fully revealed:

IMG_0764IMG_0768IMG_0770

And after Varnishing

After more than 15 repeated varnish and sanding cycles, here is the finished article. Very hard finish with the wood grain showing through like Tiger Stone:

IMG_0791

I’m very pleased with the resultsSmile

Have fun and Happy New Year.