RSS

Category Archives: Uncategorized

A Simple Defibrillator Class in C#

Timeout Defibrillators are common in the ASP.NET world, where there is often a requirement to keep a session alive during a period of inactivity.  However the same can be said about the windows application domain.  For example, assume that user enters an area of the application which serves up some specific data.  While the user has this screen open, it should be locked to all other users so that the data cannot be modified.  But what happens if the user decides to go to lunch with the screen open preventing all other users from working.

In scenarios like this it would be nice to have a simple class which when invoked starts a timeout process for long periods of inactivity.  When this time out is reached an event is raised to the calling object which allows the application to release the lock.  Additionally there is a method in the class which can be called by the parent object to reset the timer if there is some form of activity on the screen.

Below is my simple Defibrillator class and below that an explanation of the key points of this class and how to use it.

Defibrillator Class

So the basics of this class are:

  • A delegate and event have been created at the top of this page which can be subscribed to by the calling object.  This allows us to raise an event to the parent once the time out has been reached.
  • The constructor allows the user to pass in the time is seconds which should be observed before the timeout is reached.
  • The Start method is called when we are ready to commence the timer.  Note that I have set the Interval between ticks to be 1 second.  The timer object allows us to set a call back method which is invoked after every tick (1 second interval in this case)
  • The Reset method allows us to Reset the timer.  This would probably be called if the parent registers user activity.
  • The TimerProc method is called after every tick of the timer.  Here I am performing a check to see if the timeout has been reached.  If it has the timer is disposed and the event raised back to the Parent.

 

To use the class, simply create a Form which has a reference to the Defibrillator class and add code similar to below:

Invoking the class

Here I am creating an instance of the class with a 10 second timeout.  I am also subscribing to the TimeOut Reached event which will call the method dt_TimeOutReached when the time out completes.

All that’s left is to start the Timer – dt.Start()

 

 
 

Reading an XML file using Linq to XML

A quick and post and more for my own reference but I recently needed to read some elements from an XML document which can be accomplished much easier these days using Linq to XML.

So if I have a simple XML document :

Sample XML document

I can read this using Linq as below (language is C#) :

C# routine to parse the XML document using Linq

In this method I am first loading the XML file into an XDocument Object found under the System.XML.Linq namespace.

I am then using Linq to return a collection of Items which represent the Parent ‘Client’ Nodes, using the Descendants function.

Then we can loop though each Client Node and simply extract the Element Values for the KEY and POSITION Nodes.  Its also worth noticing in this example that I have included an attribute at the CLIENT Node level.  Using Attributes().First() I am requesting the first attribute found attached to my CLIENT object.

Like I mentioned nothing difficult here but a handy little reference

 
Leave a comment

Posted by on June 22, 2012 in C#, Linq, Uncategorized, XML

 

MVC Validation – Part 2 – Custom Validation

In Part 1 we saw how easy it was to add Data Annotations to our model classes in order to persist validation to the presentation layer.  However what if I wanted to perform my own custom validation on attributes of my model.

Using the example from Part 1 heres how:

Step 1 – Create a new validator class

In Part 1 we created a Customer Object and applied some validation.  You may remember that the Customer object contained a property called ‘Balance’ which as yet enforces no validation.  Therefore we are going to apply out own custom validation to this property which enforces the following rule:

If the Balance Value is less than or equal to 10.00 then display the message ‘The Account is low!!’

Right, first we need to create a new class which will contain out validation logic, so create a new class called ‘BalanceValidator’ within a folder called ‘Validation’ (Just to keep things neat and tidy!!)

Create Validation Class

Step 2 – Write Validation Logic

Again, ensure you have added the ‘System.ComponentModel.DataAnnotations’ namespace to your class.

Next inherit the ‘ValidationAttribute’ class and override the IsValid method

Finally add the validation logic to the IsValid method.

Your BalanceValidator class should now look something like:

BalanceValidator Class

Step 3 – Apply Validation

We now have out custom validation logic so all that is left to do now is apply it to out Balance Property of the Customer Class.

Add the new BalanceValidator attribute to the Balance Property as shown below:

BalanceValidator Attribute

Step 4 – Run the Application

Now as long as you are performing server-side validation (Part 3 will go in Client Side and Server Side Validation) you should be able to enter a value less than 10.00 into the Balance text box and see our Message ‘The Account is low!!’ appear

Running the application

 

MVC Validation – Part 1 – Model Data Annotations

Most Web Applications will require some form of user input and it is often a requirement to validate this input.  With ASP.NET web forms validation could be performed using the validator controls and were often implemented as an afterthought e.g. RequiredFieldValidator, RegularExpressionValidator etc.

Within the world of MVC validation takes another approach.  Using Data Annotations we can apply validation directly to the model objects easily, allowing the validation rules to filter through to the objects that consumes these model objects.

In Part 1 of my posts on MVC Validation I will provide a step by step guide to applying validation to a model object within my solution.

Step 1 – Create an MVC Project

Before we can apply the validation lets create a simple MVC project and when prompted set the view engine to Razor.

The project template will look similar to this:

MVC Solution Template

In order to ensure we can use Data Annotations for enforce our validation make sure there is a reference to System.ComponentModel.DataAnnotations
Step 2 – Create our model class and apply the validation

Within the Models Folder add a new class named Customer and create a few properties e.g.

Customer Class

Also add the using statement for the DataAnnotations reference added earlier

So now we have our model object we can use data annotations to apply validation to properties of the object.

For example, assume that the Forename and Surname and required fields and that the length cannot exceed 50 characters.  Also assume that the email address is also required and that the users input for the email address must be validated using regular expressions.  To enforce these rules we could modify the class using the following annotations:

Validation Decorators

Note: Other annotations available are:

Range: Validates whether a value falls between a minimum and maximum value

DataType: Validates whether the value matches a certain type e.g. could be used to ensure the user supplies a valid date time value

Step 3 – Create a controller and view then run the application

The final stage is just to create a controller class to test the validation.

Right-click on the Controllers folder then click Add à Controller…

Add the following two Create methods

Controller Class

Notice the Create() with the [HttpPost] annotation.  This is the method that is called when the user posts data from the Customer View back to the Server and so this is the method which will invoke the validation check.

Simply call ModelState.IsValid to determine whether or not the user’s input conforms to the validation rules
imposed on the model.

To create the View (our user interface), right-click the Create() Method in the controller and click Add View…

Add View Screen

Click ‘Create a strongly-typed view’ and select our Customer model object.  Also ensure that the Scaffold template is set to ‘Create’.

All that is left now is to run the application.  You may need to modify the invoked URL to be
something like http://localhost:50712/Customer/Create  so that our Create new Customer View isinvoked

Try leaving the Forename and Surname fields blank and putting rubbish into the email field then hitting the Create button, Voila!! Validation without any Validator Controls in sight

 

Update a record through the Entity Framework using Attach

Performing basic Create, Read, Update and Delete Operations via the Entity Framework is very straight forward.  However take this scenario :

  1. The EF is used to return a Customer Record to the Presentation Layer
  2. A User then modifies the Customer record
  3. The modified record is sent back to the EF to update the record in the database.

To Update the record we can write the following code :

public bool UpdateCustomer(Customer customer){

    Customer cust = entities.Customers.FirstOrDefault(c => c.ID == customer.ID);

    cust.Forname = customer.Forename;

    cust.Surname = customer.Surname;

    entities.SaveChanges();

}

But what if the object we are updating contains a lot of attributes.  Surely updating each attribute seperately before calling a Save is a little overkill.

Luckily we are providied with a solution which allows us to attach to a record within the context, perform a straight replace on the record with the new modified record and save back the changes, and all in just 3 lines of code:

bool UpdateCustomer(Customer customer) {

    entities.Customers.Attach(entities.Customers.Single(c => c.ID == customer.ID));

    entities.Customers.ApplyCurrentValues(customer);

    entities.Savechanges();

}

 

Deploying an MVC 2 ASP.NET application in IIS 7.5

 So whats it all about?

 Having been subjected to the previous n-tier, highly coupled, impossible to maintain architecture that makes up one of our software applications for far too long, a development decision was made to move into the MVC arena.  However having done all the hard work of integrating the MVC framework into an existing ASP.NET Forms application (which was actually very straightforward), what worked fine in the Visual Studio IDE, failed miserably when I published to IIS.

So if like me you had an existing Web Forms application into which you have integrated the new MVC 2.0 framework and are about to publish to IIS (I’m using IIS 7.5) then this handy little checklist may be of help.  Or if you have already published and are sitting looking at the following IIS error then this post will definately be of help;

Routing Error - 404 Page not found

 

 

 

  

1. Make sure you Routing is set up correctly

Firstly, assuming your MVC application is running correctly in the IDE, its worth double checking the Routing is configured correctly prior to deployment else you will more than likely end up with the dreaded 404 page not found error.

Your Routing rules should be registered in the Global.asax.cs file within the RegisterRoutes method or the Application_start method

RegisterRoutes method located in Global.asax.cs

 

 2. web.config alterations

Now if you used the template provided by Visual Studio to create your MVC application then chances are your web.config file will contain everything you need, however if like me you are adding MVC to an existing Web Forms application then there are a few bits you need to consider:

Firstly this is the one that caught me out

Assembly Binding for System.Web.MVC DLL

you will need to add this binding information to ensure you are using the correct MVC 2.0 assembly.  Also add the following runAllManagedModulesForAllRequests attribute to the modules section and set to True.  Additionally ensure the Modules section points to the correct UrlRoutingModule assembly (version 4.0.0.0 or 3.5.0.0 depending on your framework)

Adding the correct modules and the runAllManagedModulesForAllRequests attribute

 

 

 

 

 

Note: (If you have you application running through the IDE then chances are that the next few points regarding the web.config are already in place)

Now if your using Framework 4 then Microsoft have made things a little easier, reasons being that the Web.config was cleaned up for the ASP.NET 4.0 release and you only have to add assembly references for:

  • System.web.Abstractions
  • System.Web.Routing
  • System.web.MVC

Assembly References for MVC 2.0

 

If however you are using Framework 3.5 you will need to ensure you have references to the following extra assemblies:

  • system.Core
  • System.Data.DataSetExtensions
  • System.Web.Extensions
  • System.XML.Linq

Also ensure that you have the following namespaces defined in the web.config

Namespaces required for MVC in the web.config

Once again if you are using Framework 3.5 then you will need these extra namespaces
  • System.Linq
  • System.Collections.Generic
3. Configuring IIS
 
So your application is ready and your web.config is ready, all thats required now is to ensure IIS is configured to host your MVC application.If you are using Framework 4.0 then ensure that you have registered/installed the ASP.NET Framework against IIS:
 
Navigate to the correct location normally ‘C:\Windows\Microsoft.NET\Framework\v4.0.30319’
and type aspnet_regiis.exe -i
  
Next load the IIS Manager and Invoke the ISAPI and CGI Restrictions window and allow ASP.NET version 4.0.30319
 

ISAPI and CGI Restrictions

 
 
Create or choose an existing Application Pool to house your application but make sure the Managed pipeline mode is set to IntegratedApplication Pool
 

Application Pool

 
 
 Finally you may need to drill into the Advanced Settings of the application pool and set ‘Enable 32-bit Applications’ to True and Set the ‘Identity‘ to Network Service

Advanced Settings of the App Pool

Right, thats it, your MVC application should now work just as well under IIS as it did through the Visual Studio IDE.  If theres something I’ve missed then let me know and I’ll amend the post, but hope it helps.
 
Leave a comment

Posted by on December 2, 2010 in Uncategorized