Pages

Tuesday, 6 December 2011

Saving the internet

All,

Quote from: http://www.avaaz.org/en/save_the_internet/?mzla

"As concerned global citizens, we call on you to stand for a free and open Internet and vote against both the Protect IP Act and the Stop Online Piracy Act. The Internet is a crucial tool for people around the world to exchange ideas and work collectively to build the world we all want. We urge you to show true global leadership and do all you can to protect this basic pillar of our democracies worldwide."

Please sign up to save the internet. This is important for all of us to continue to have an open and uncensored internet. Imagine if the police monitored all your phone calls, you wouldn't like that would you?

http://www.avaaz.org/en/save_the_internet/?mzla

thanks
RuSs

Monday, 7 November 2011

Explanation of Ninject Bindings and where we used them in our MVC Website (Part 1 - MVC Website)

Afternoon,

Im going to summarize what we have done with our Ninject bindings and injection which allows us to follow the "Inversion of Control (IOC Container)" principle in a project we are working on. 

As mentioned we are using Ninject as our IOC container: http://ninject.org/

The project architecture looks much like the following diagram:

Architecture Diagram

I will work my way from the top to the bottom of the architecture. Starting with the MVC web site all the way through to the Microsoft Crm layer.(This post  (Part 1 - MVC Website) just refers to the web site.)

One of the 2 BIG reasons we are using an IOC container (Ninject) is to allow us to separate all our layers (separation of concerns) so that they are Unit testable and also so that we can swap components out at a later date. We may want to replace our Crm later with a Sql server layer, doubtful but we are catering for this anyway as you never know what will be a requirement in the future. As long as our Sql server repository layer implements the same interface as our existing Crm repository layer, we can more or less swap out the Crm Repository with a new Sql Repository.

Mvc Website:
On the website layer we will be using Ninject to inject the following:
  • A GatewayAgent layer into our controller - the GatewayAgent layer separates the concerns of the controller from the concerns of our WCF SOA layer. 
  • An AutoMapper implimentation into our GatewayAgent - the mapper will map our presentation entities to our Domain entities.
  • Our presentation entity validation classes into our presentation entities - as we are using Fluent validation, we may want to ditch this later and inject a different type of validation.
The following diagram show part of the web site's global.asax file. This code uses Ninject to inject the above 3 items.

The Ninject Binding in the Global.asax class
Obviously, the web site has a reference to the Ninject.dll.

Most of this is set in stone for our site but one thing to note. As more development is done we will need to add more validators as we add more presentation entities to our site. So when we add an Invoice presentation entity to the site a related Invoice Validator class will need to be added to the ConfigureKernel method, shown above, in our global.asax file.

Note: the line:
- kernel.Bind<IValidator<Contact>>().To<ContactValidator>(); 
means, when we call validate on a Contact presentation entity, 
we would like to use the ContactValidator class to carry out the validation

Sample Contact Validator
You can see in the ConfigureKernel method above that we also inject a ContactGateway.
The following line shows this:
kernel.Bind<IContactGateway>().To<ContactGateway>();

This means that when we refer to IContactGateway we would like to use the concrete class ContactGateway.
So in our controller we see the following code:
Sample controller


Why is this good? Because you can then mock up a ContactGateway in a unit test to test your controller.

A unit test for the controller
As mentioned above, we also inject a mapper implementation into our web site:
kernel.Bind<IMapper>().To<AutoMapperMapper>();
This is used to map our domain entities to our presentation entities on the way up and our  presentation entities to our domain entities on the way down.

Why is this good? We may way to use a different mapping tool other than AutoMapper in the future. Injection will enable us to swap AutoMapper out for a different mapper tool.

This is the end of Part 1 - Explanation of Ninject Bindings and where we used them in our MVC Website

I will do another couple of posts on the other layers mentioned in the architecture diagram at the start of this post.

RuSs




Monday, 3 October 2011

How Jimmy Bogard does MVC

Bonjour,

Following is a link to a very good post called "How we do MVC" on some DOs and DON'Ts of MVC. We are about to start a fresh enterprise level project and this article is great for getting a few things done correctly from the start.


There is also another article he has written on "How we do view models":

Hope you find this useful.
RuSs

Monday, 26 September 2011

Entity validation, unit testing and MVC 3 with Fluent - RuleSets and Predicates


Morning all,

I have been looking at validation for my current project. We are building an MVC 3 site that calls a wcf service later that is wrapped around Crm 2011.

Initially I was looking at data annotations out of the box. These work really well and MVC 3 works seamlessly with these with client validation and unobtrusive JQuery. 

 When  I came to look at rulesets however it seems a lot more complicated. I them stumbled upon Fluent validation:

This is a very user friendly clean way of writing validation on your entities in the same way that data annotations are written. The difference came when I started to look at rule sets which you will see in my attached screen shots.

Firstly I defined 2 classes in my domain model. Thsese are called ContactForValidationPOC and AddressForValidationPOC as shown below:

 ----------------------------------------------------------------------------------------------------------



As you can see there are no data annotations and ContactForValidationPOC has a complex property of Addresses.

We are going to write some rulesets that will validate the contact for a STAFF ruleset and a public ruleset. (Note that there are not real world validation needs as of yet,it's just proof of concept code.)

You will notice that at the top of the ContactForValidationPOC class we have an attribute shown as follows:
[Validator(typeof(ContactValidator))] 
This tells the class that there is a validator class call ContactValidator somewhere.
Also please note that I have referenced the correct Fluent  validation dlls in my project. 
You can find the details of this here:
http://fluentvalidation.codeplex.com/ 
So back to the ContactValidator. Here it is:
You can see that we have 2 rule sets. The first is a staff rule set and the second is a public rule set. 
They are quite similar and the only difference really is that the Age must be over 18 for a staff member. 
Both rule sets also use a .Must predicate validator. 
This is a great place to put more complex logic.

Here we need to ensure that there is at least 1 address in the Addresses collection that is marked as IsPrefferedAddress.
Ok, so that is all done, now we need to unit test or validation rules.  
 
So I have a unit test written here. Firstly I set up a new ContactForValidationPOC entity and add a couple of addresses to it. 
I then call Validate on it and ask it to validate using the Staff rule set. After validation we check that the ValidationResult (result) is valid 
and then do a simple check for the number of validation errors. Obviously my test could be more detailed in a real world example. 
As I debug through my test I can see that my entity is not valid (IsValid = false
and it has a collection of validation errors on it.


This is good as we didn't enter a first name, our Age is under 18 and we set all AddressForValidationPOC's in the Addresses collection to IsPrefferedAddress = false.

Ok so we now know that our validation is working correctly on the server side.
We haven't even touched the MVC code yet.

I have whipped up a quick MVC controller with a view and have disabled the settings 
in the web.config that make client side validation work as shown in the following picture:


Note: they should be set to false to prove that server side validation is still working correctly now that we are validating through MVC.

Here are my controller and view: 
Note: I have just forced 2 addresses into the ContactForValidationPOC entity to make things easier, these are both set to IsPrefferedAddress = false 

Here is the view that kicked off the validation:


You can see that, when debugging the controller we get the same validation results. 
IsValid = false and a number of errors relating to our Staff rule set.

Note that in our controller we could have control over what rule set is loaded if we so desired:


We could use some logic to check what type of rule set to load, staff or public.

Now I will change the web.config setting to ensure that client side validation gets included:

We now can fire up the view in a web browser and see client side validation in action:

Well that is it, a high level explanation of domain entity server and client validation using Fluent, unit tests and MVC.

Some positive points:
Some possible negatives:
  • Only the following validators are supported on the client:
    - NotNull/NotEmpty

    - Matches (regex)
    -
    InclusiveBetween (range)
    - CreditCard

    - Email

    - EqualTo (cross-property equality comparison)

    - Length
  • Cant think of any more at the moment.
I hope this was helpful.


RuSs

Tuesday, 6 September 2011

EDMX or DbContext API

Hi all,

I have used EF for a while. I am used to using an EDMX file for my model. I have also recently used Code First and the DbContext API and I really like this.
Last night I started building an app. and was thinking, am I starting on the right foot? Do I use EDMX or DbContext API? If the thing i'm building turns out to be big, will I have chosen the right technology.

What if I use DbContext API and get it to generate my database. Obviously I don't want this to keep generating my database down the track when i'm at a stable point in development (or do I?). Then if I want to tweak my database or domain model will all the strings come un done?

The DbContext API is a simplified version. Will it do everything I need? I dont think ill need stored procedures as I can do everything with linq.

So my real question is. If I am building something that is serious and out there is the real world and it may turn out to require some complex coding, which way do I go? EDMX or DbContext API?

Is EDMX now old school? 

Comments / thoughts?

RuSs

Monday, 5 September 2011

A small update

Morning all,

Well it's been a while since I posted in my blog that i'm sure no one reads! I have finally got used to living in Melbourne and have started enjoying it more now that the weather is getting better.

I will hopefully be posting some interesting stuff on MVC up here is the next few weeks.
Here is a list of things I have looked at in the last few weeks.

  • MVC(3) - I have been trying to get around to getting up to date on MVC for years. Ever since I tried and failed to read Martin fowler's book on design patterns (http://martinfowler.com/eaaDev/uiArchs.html).
    Well finally I have got around to it and I love it. Combined with the Entity Framework edmx or code first it is such a great way to work. This is the way, for most sites, the web should be built. No hidden viewstate, no nightmare page load order and code that you have total granular control over. Awesome!!
  • Razor view engine - initially it looks dodgy but after a little playing around it's cleaner and easier to read than traditional asp.net forms. One thing I have learned about Razor is, if it looks messy and hard to read, then you probably have started putting business logic where it should not go.
  • Unit testing and TDD with MVC - Combined with Ninject and Moq this is easy. You can directly test your controllers. Compare this to ASP.NET web forms where your controller was, sort of, your code behind. You needed httpContext etc. Now you can test just your controller logic without other webby things clouding the test.
  • JQuery - ok so this is not new but im loving it so far.
  • NuGet - the NuGet package manager is quite cool. NuGet is a Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects that use the .NET Framework. When you add a library or tool, NuGet copies files to your solution and automatically makes whatever changes are needed in your project, such as adding references and changing your app.config or web.config file. When you remove a library, NuGet removes files and reverses whatever changes it made in your project so that no clutter is left.
    For example if you need to get the latest JQuery libraries into you solution you open Tools > library package manager > package manager console and type:

    PM> Update-Package jquery

    PM with auto update your JQuery to the correct version. Note that your references inside Views > Shared > _Layout.cshtml (for example) will not be auto updated.

Well, I know this is a bit of a lame post but it was more to get me back into the habit of writing on my blog. I hope to come up with some more interesting stuff soon.

RuSs

Wednesday, 8 June 2011

SQL Profiler - Being self-centered is a good thing (thanks Jeff Handley)

When I'm faced with app. debugging, especially procedures that take awhile to run, or require a series of steps in the application to fire off, I often use SQL Profiler to capture the SQL call.  Then I'll re-run the call directly in SQL Management Studio.  But SQL Profiler can bring back a lot of noise, making it tough to grab only what I need.

I finally created a custom trace template and set it to be my default.  It will only show me calls made from my local workstation to the development database. (we have a shared development database*)

This article will help you set up a personalised trace. For expample you can filter by Application Name or Host Name to reduce the noise in your trace.


Thanks
RuSs

Wednesday, 23 March 2011

Finding all stored procedures updated in the last (n) days

This was quite helpful:
SELECT name
FROM sys.objects
WHERE type = 'P'
AND DATEDIFF(D,modify_date, GETDATE()) < 30

Saturday, 15 January 2011

My new life in Melbourne

Morning, 


After 8 years in London I have decided enough is enough. I'm on the way to Melbourne to see what the future holds.
Im currently getting my CV ready and if anyone out there has any leads I can follow in Melbourne that would be great.
I'm currently in Sydney with my family and will head south in the next couple of weeks.


RuSs

Thursday, 11 November 2010

Re-map an SQL server login to a database login

Hello,


Sometimes users get un-mapped from the server to database login after a database restore.


Here is the command to fix it:
EXEC sp_change_users_login 'Auto_Fix', 'SRSUser'


RuSs

Wednesday, 10 November 2010

Workflow 3.5 and MOSS 2007 - This task is currently locked by a running workflow and cannot be edited.

Morning,


Today I had an interesting issue with my WF3.5 SharePoint workflow.
A user was attempting to action a SharePoint workflow task and was given the error:


This task is currently locked by a running workflow and cannot be edited.






I have seen this error a small number of times (5-10) amongst the 1000's of workflow instances that have passed through my production system.


I am always very careful with quiescing and always release a new workflow version the correct was using workflow.xml, feature.xml and stsadm.


There was a time a few weeks ago when we had to do an emergency bug fix as some of my business logic was not functioning as expected.


I know that I can never change an activity in my workflow without quiescing otherwise the serialization and deserialization (dyhydrate / re-hydrate) from the persistence store gets confused and hence an error like this occurs.


The funny thing is, I only changed code in a utility class and only the code inside an existing method (ie...method definition was not changed) so I thought that there was no need for quiescing. (no core workflow code was altered).


Anyway,just writing here incase anyone has an opinion on this. 


From now on I will quiesce no matter what the emergency is!!


RuSs

Tuesday, 19 October 2010

Workflow 4.0 Activity Designer

In this post i'm going to explain how to make a custom activity better visually. 
First of all I have a custom code activity called RequestManagerAction. It inherits from CodeActivity and overrides its Execute method. (I may do a post on code activities later).


The visual representation of code activity, by default, looks like this:
And by the end of this post it will look like this:
The first step is to create a new peoject for your activity designer. As we want to "design" RequestManagerAction I have created a new project called: RequestManagerActionDesignerLibrary. And inside this I add a new Activity Designer Item from the Workflow - installed templates called RequestManagerActionDesigner.xaml.


the initial view after opening RequestManagerActionDesigner.xaml is a split screen with the Xaml that represents the design in the bottom part of the screen and the actualy visual design in the top part.


In the bottom pane we can see the Xaml. First of all I want to set the Collapsible property to false as I don't want my designer to be collapsible. 


The 2nd taks is to add an ArgumentToExpressionConverter to my Xaml. This defines the mapping between arguments and expressions and provides the functionality to convert between these objects. Typically, this converter is used declaratively when using an ExpressionTextBox in a custom activity designer.




The next thing I want to do it sort out my layout. As my custom activity has 3 properties:


The main aim of what we are doing here is to show ExpressionTextBoxes for all 3 of these.
I will add a grid of 2 columns and 3 rows for our properties.




You can see that inside this grid we have some (3) collapsed TextBlock sections. I will explain these now.


Each TextBlock is for a property.
The first TextBlock is for the ExpenseRequest property of our custom activity:
You can see the obvious items marked out in the above picture.Note that the position inside the grid defined above is set by the Grid.Row and Grid.Column indexes which are zero(0) based.
You can also see that our expression text box is bound to ModelItem.SubmitExpenseRequest.


SubmitExpenseRequest is a class in my Contracts project that is part of my domain model:


The ModelItem represents the activity that that the designer is currently editing. This object sits between the visual elements that present an activity to the developer and the in-memory representation of the activity.


You can now see that we are well on the way to building our custom design:

I will now go ahead and add the other 2 ExpressionTextBoxes and the relevant properties.




You will notice the little smiley icon in the top left of the designer. To add this, I added the following xaml:


Now I am ready to associate my designer with the actual code activity that is already part of my workflow. If you remember it currently looks like this:
First I will add a reference to the project that my code activity is part of:


Once its referenced we can add an attribute to the top of our codeActivity class (Don't forget the System.ComponentModel import at the top!):


Once you have built the projects you will see the "RequestManagerAction" code activity in the toolbox. Drag this onto your workflow surface if it's not already there and you will see that the look of the activity is not just a small yellow box any more. Nice!! 



This is obviously more useful as we don't need to  use the properties pane to set the properties for our code activity, we can just type them straight into the workflow.

RuSs


Friday, 8 October 2010

Workflow 4.0 - Adding annotations to your workflow tracking profile

Lets say you have a workflow that is running on a DEV / TEST and LIVE server. Lets say, also for the sake of it, that we are using the same AppFabric database for all 3. (yes, this is not the best idea but to explain annotations it helps.)
So what we want to acheive is the show, in AppFabric monitoring, which server we are using. So the monitoring with show either:
  • ServerThatEmittedThis: DEV_Server
  • ServerThatEmittedThis: TEST_Server
  • ServerThatEmittedThis: LIVE_Server
Again, this example is useless in the real world but i'm sure by the end of this post you will be able to imagine some real world uses for this functionality.

So you can see that in my current tracking profile I have added an annotation of my DEV server as follows:

You can see in the pic. "ServerThatEmittedThis: DEV_Server" which will now show up in AppFabric monitoring.

So I will now run the workflow which is hosted in IIS / AppFabric. 

My workflow runs and is persisted into my persistence store. So I click on the Active or Idle Intance in my AppFabric dashboard:
Note I could also navigate to the annotated info if my workflow wasnt using a persistence store by Looking on the dashboard for the WCF Call History section and click on the link in the Completed Calls section.

Once I can see the instance I click to select view tracked events:
Once here, I can see all the events that my workflow has passed through. 
Note that I am using a custom tracking profile that emits less than some of the default profiles. My custom tracking profile named: ExpenseServiceTrackingProfile is shown in the first screen shot of a part of my web.config in this post.

As i placed my annotation in my web.config as a child node to the activityStateQuery named Screen Expense I know to expect to see my annotation in AppFabric at the point where my screen expense activity emitting its tracking record. 

As you can see from the above pic. I have clicked on the Screen expense item and at the bottom you can see a tab called "tracked variables" shown below:

So I know that the workflow (server) emitting this tracking record is from my dev server. 

Rubbish example, but  I hope you get the point.

R

Tuesday, 5 October 2010

AppFabric Hosting PowerShell Cmdlets

This seems to be the place for the AppFabric Hosting PowerShell Cmdlets:
http://msdn.microsoft.com/en-us/library/ee767662(v=WS.10).aspx


The following shows the current state of my AppFabric. It has nothing persisted.




I start a workflow that I know will persist to my persistence store:


I can then look back at my AppFabric dashboard and see that 1 workflow is persisted and active.


I can then open Windows PowerShell Modules. It calls this from the server menu behind the scenes:
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -NoExit -ImportSystemModules



Ok so it's loaded. Now, just as a simple example we can query for all instances in the default persistence store.

We call "Get-ASAppServiceInstance".


It returns all the info about my persisted workflow instance.


This is interesting as I have just noticed that I have an extra unnecessary service contract name, a spelling mistake and hence an extra bookmark.



Ok, so I went in, altered the service contract name to get rid of the extra IService ref as it should only have an  IExpenseService ref. I also renamed my bookmark from ManagerActionComplete to ManagerActionCompleted. Then I re-ran my workflow thinking all was ok.

An exception was thrown so obviously I just did something incorrectly.

I re-ran my "Get-ASAppServiceInstance". and saw the following information which of course is very obvious:

The exception is:
ExceptionMessage: A bookmark with the name 'ManagerActionCompleted|{http://tempuri.org/}IExpenseService' already exists.

Obviously I just named a bookmark in my workflow to the same name as another one.

I renamed ManagerActionCompleted to ManagerActionCompletedReminder as this bookmark gets resumed after a delay activity expiration time has elapsed.

So "Get-ASAppServiceInstance" now shows:


We then wait for the delay time to expire and run "Get-ASAppServiceInstance" again and we then see:


Ok so I set off to write myself an investigative blog into  Windows PowerShell Modules for AppFabric and this technology already showed me a couple of issues with my workflow. Nice!!

Again, look at this link for loads of other useful commands:

thanks
RuSs