jQuery Remote Validation with ASP.NET MVC
Update 29/09/2010
I've included a sample project at the end of the post. The project can also be downloaded here: RemoteValidation.zip.
Note: When I say ASP.NET MVC, this post only applies to version 2 and above, which at the time of writing includes MVC3 Preview 1.
There is a bit of client-side magic that happens on some forms these days. You’ve probably seen it; you type in a username or an email address into a registration form and before you have finished entering the next field, the form is already telling you whether or not the username/email address has already been used. Or, maybe you’ve typed in a gift code that immediately validates (or not).
This magic, contrary to the belief of some posse’s of some Faygo wielding clowns, is not magic but a technique called “remote validation”. Remote Validation is providing validation on the client (using something like JavaScript, Flash or Silverlight) that can utilise server side logic by way of an Ajax request. In most cases, validating the input against your data store.
At this point it should be noted that I will be focusing on an implementation that relies on the jQuery Validation plug-in. If you would prefer to use the MSAJAX library, I will now point you to Brad Wilson’s excellent post on the subject. My implementation is based on Brad’s, with a few differences, that I’ll mention on the way.
Okay to the implementation. As with a lot of things, jQuery makes our lives a lot easier. I expect John Resig should at least take some credit for my steady marital status, I’m not getting complacent. jQuery offers a plug-in, one of not very many officially supported plug-ins, called jQuery Validate. I am sure you are already acquainted. The validation plug-in offers remote validation out of the box, the implementation is both incredibly simple and efficient. Below is an example borrowed (I’m not giving it back) from the jQuery documentation.
$("#myform").validate({
rules: {
email: {
required: true,
email: true,
remote: "check-email.php"
}
}
});
The above example says three things about the field called email.
- It’s required.
- It’s and email address.
- As an extra check, the browser should pass the email address to an endpoint called “check-email.php”.
The remote endpoint has but one job, to return true or false (as a JSON object). It is up to you how that decision is arrived at. By default, this check is made either when the field loses focus or before the form is submitted.
That is fantastic if you can be bothered to write all of a long sentence each time, yeah I have better things to do like try and learn Japanese and the Ukulele simultaneously. Yeah, that’s how I roll, yo.
What we need to do is bake in some ASP.NET MVC wizardry. I have loved data annotations, since I first saw them in that scaffolding thing, umm Dynamic Data. Just awesome, one day I’d like to build a website with just a long string of attributes.
Okay, I’m going to assume that you are already familiar with how Html.EnableClientValidation() works for jQuery for the rest of this post. If there is any call for it, I focus on this on another post.
That assumed, we need to create a new Attribute to flag our property with. Our use case scenario will be a basic registration form (very basic) that requires a username, that has not already been used. Our model is below:
using System.ComponentModel.DataAnnotations;
public class Reg {
[HiddenInput(DisplayValue = false)]
public int ID { get; set; }
[StringLength(50), Required]
public string Name { get; set; }
[StringLength(250), Required]
public string Email { get; set; }
}
So our form is going to require a name and an email with maximum string lengths. Lets create an Attribute that says check me against something remote:
using System;
using System.ComponentModel.DataAnnotations;
using System.Configuration;
[AttributeUsage(AttributeTargets.Property)]
public class RemoteAttribute : ValidationAttribute {
#region Properties
public string Key { get; set; }
public string[] AdditionalProperties { get; set; }
#endregion
#region Methods
public virtual string GetUrl() {
return ConfigurationManager.AppSettings[Key];
}
public override bool IsValid(object value) {
return true;
}
#endregion
}
The key difference between mine and Brad’s Remote Attribute, is the way the remote URL is retrieved. Brad’s URL is baked straight into the Attribute, whereas mine is takes the URL from a Web Config AppSetting. I made this change because I tend to reuse models between projects and didn’t want my routing to be dictated to by my model. In the future I would like to have the option to set the URL in the Global.asax, so I can make use of T4MVC’s strongly typed ActionResults.
I have also added a string array called AdditionalProperties, this will contain a list of additional properties that I also want to pass to the remote endpoint. This is useful if you don’t want to invalidate an email address on a registration, because it already exists on the registration you’re currently editing. I’m going to infer my parameter name from the property.
If you haven’t read Brad’s post, I should mention that we’re returning true in IsValid() because this Attribute will not be performing traditional server-side validation. This is not because I’m lazy, but rather because we don’t know what that validation will be until it is implemented. I am quite lazy.
We’re also going to need an Adapter. An Adapter tells the compiler how to pass the Attribute to the client. Here it is:
using System.Collections.Generic;
using System.Web.Mvc;
public class RemoteAttributeAdapter : DataAnnotationsModelValidator<RemoteAttribute> {
public RemoteAttributeAdapter(ModelMetadata metadata, ControllerContext context, RemoteAttribute attribute) : base(metadata, context, attribute) { }
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules() {
var rule = new ModelClientValidationRule {
ErrorMessage = ErrorMessage,
ValidationType = "remote"
};
rule.ValidationParameters["url"] = Attribute.GetUrl();
rule.ValidationParameters["type"] = "post";
rule.ValidationParameters["additionalProperties"] = Attribute.AdditionalProperties; ;
return new[] { rule };
}
}
For the most part this Adapter is just pairing up my attribute’s properties with the parameter’s of the jQuery validation plug-in. The only property that isn’t like for like at this stage is the additionalParameters parameter, this will map to a jQuery parameter called data.
Note: I’ve also hardcoded that the request be a POST. Bad practice, possibly, but I can’t see a call of this nature legitimately being a GET. I am posting information for comparison, not to specifically get information. You may have your own take on this, in which case you are free to adjust your implementation.
Which brings to the second example provided by the jQuery documentation:
$("#myform").validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "check-email.php",
type: "post",
data: {
username: function() {
return $("#username").val();
}
}
}
}
}
});
In the example, additional parameters are sent to the endpoint to add context to the validation method. I will replicate this in my client-side validation. My client-side validation will not be reinventing the wheel, I will be building on the file called MicrosoftMvcJQueryValidation.js. This file was originally provided in some of the preview releases of ASP.NET MVC2, and I can now never bloody find, so will include the script in it’s entirety at the bottom of this post. For now though, lets look at the additions I have made:
function __MVC_ApplyValidator_Remote(object, validationParameters, fieldName) {
var obj = object["remote"] = {};
var props = validationParameters.additionalProperties;
obj["url"] = validationParameters.url;
obj["type"] = validationParameters.type;
obj["beforeSend"] = function () {
var elementName = fieldName + "_validationMessage";
$("#" + elementName).addClass("remote");
};
obj["complete"] = function () {
var elementName = fieldName + "_validationMessage";
$("#" + elementName).removeClass("remote");
};
if (props) {
var data = {};
for (var i = 0, l = props.length; i < l; ++i) {
var param = props[i];
data[props[i]] = function () {
return $("#" + param).val();
}
}
obj["data"] = data;
}
}
The above block of code is added at around line 32, and maps the ASP.NET MVC generated JS to a jQuery Validate object. In additional to what you might have been expecting, I have also bound to two event handlers. This allows me to provide field by field loading indications the user “Hey user, I’m doing something clever to this field.” I do this in addition to ajaxStart and ajaxStop.
If you focus in on the for statement, you’ll see that I’m iterating through the additionalParameters array to produce a data parameter exactly the same in function as in the second jQuery example.
Let’s look at the second addition I’ve made:
// Line 110
function __MVC_CreateRulesForField(validationField, fieldName) {
// Line 137
case "remote":
__MVC_ApplyValidator_Remote(rulesObj, thisRule.ValidationParameters, fieldName);
break;
// Line 156
rulesObj[fieldName] = __MVC_CreateRulesForField(validationField, fieldName);
In the addition above I am simply adding an extra case into the switch that determines which adapter method to fire. This was necessary because I require the field name to be passed to the adapter.
Right, we’re almost there. Just four more steps:
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RemoteAttribute), typeof(RemoteAttributeAdapter));
Step One: Add the above line of code to the Application_Start method of your Global.asax.
using System.ComponentModel.DataAnnotations;
public class Reg {
[HiddenInput(DisplayValue = false)]
public int ID { get; set; }
[StringLength(50), Required, Remote(Key = "name-test", AdditionalProperties = new[] { "ID" })]
public string Name { get; set; }
[StringLength(250), Required]
public string Email { get; set; }
}
Step Two: Adjust our model to include the new RemoteAttribute. I’m telling the attribute to look for an AppSetting of “name-test” in web.config.
<add key="name-test" value="/Home/NameTest"/>
Step Three: Add an AppSetting called “name-test” to your web.config.
public virtual ActionResult NameTest() {
return Json(true);
}
Step Four: If you have not already done so, create your end point.
Discussing the creation of the form is beyond the scope of this post, mainly because it is dead easy and would sit better in a general post about jQuery validation with ASP.NET MVC. I will clarify that you need to reference jQuery and jQuery Validate. You will also need to add Html.EnableClientValidation() to the top of your form.
So what have we done here. We have created an Attribute and an AttributeAdapter pair that will allow you to describe a remote interaction between the server and your model. We have registered this Attribute/Adapter pair in our Global.asax file, so ASP.NET knows to look out for it. We have then transformed the interaction into a state that jQuery can the use using our modified MicrosoftMvcJQueryValidation.js file.
You can download a sample project at the following location: RemoteValidation.zip. If you're just interested in the amended MicrosoftMvcJQueryValidation.js file, it can be downloaded here: MicrosoftMvcJQueryValidation_remote.js
Request.IsAjaxRequest()
Hi,
This is just a quick post to explain how Request.IsAjaxRequest() knows that a request sent to the server is an Ajax request rather than a traditional browser request.
First of all though, what is an Ajax request? Well strictly speaking, the X in the acronym AJAX stands for XMLHttpRequest. XMLHttpRequest is an object, created by Microsoft at the turn of the century, which allows the sending of HTTP requests using JavaScript (the J). The acronym was first coined by Jesse Garrett in 2005, but has mutated, in meaning, over time. The term Ajax now encompasses a number of alternate techniques for transferring data without need of a page refresh, i.e. Flash and iframes.
So you could say an Ajax request is quite an elusive fish, and you'd be right, if a little odd for using the word 'fish'. Aside from the multiple techniques that encompass Ajax, you have the fact that each technique is using the HTTP protocol. They are, in sense, mimicking a traditional browser request. So, there is really no way to tell the difference between a browser request and an Ajax request.
Am I saying that Request.IsAjaxRequest() doesn't work then? No, it'd be a pretty crap and decidedly pointless post if that was the case. I am in fact building a sense of excitement, and now the big reveal.
Request.IsAjaxRequest() is a test; a method for testing a request as it hits the server for one of two things:
- A header called X-Requested-With with the value XMLHttpRequest.
- The Request collection (encompassing QueryString and Form) contains a key value pair, where X-Requested-With is the key and XMLHttpRequest is the value.
Be advised that in both cases ASP.NET MVC is case sensitive.
What is particularly great about this solution is that, the convention is already in use in both the MSAJAX and jQuery libraries, as well as others I understand. If you prefer your JavaScript vanilla, then it is a simple step to apply either of the two prerequisites above.
Rich
Ajax Forms with ASP.NET MVC and jQuery
This post uses jQuery, jquery.form.js, jquery.validate.js, ASP.NET MVC 2 and .NET 4.
I’ve been content loading my projects for a little while now using a graceful Ajax technique that combines jQuery with MVC PartialViews. Please see this post1 for more information.
This technique works fine with GET requests but I recently had a requirement for a form within some “content loaded” content. The whole point of content loading is that the HTML should be semantically correct and work without the need for JavaScript, so I obviously wanted to keep the form as clean as possible.
<div class="form-wrapper">
<%= Html.ValidationSummary() %>
<% using (Html.BeginForm("Edit", "Pages")) { %>
<%= Html.EditorForModel() %>
<input type="submit" name="submit" value="Submit" />
<%= Html.Encode(TempData["Message"]) %>
<% } %>
</div>
The example above is a very simple but incredibly scalable form thanks to EditorForModel, however notice that I’m not using any Ajax Extension Methods. I try to reduce dependence on the Microsoft JavaScript libraries whenever possible. This is not out of any particular dislike for those libraries, I just prefer jQuery and want to keep my file sizes down. The form above is placed in a PartialView, as per the fore mentioned Graceful Modals post, which is in term referenced by a parent View. We’ll call the View FormView and the PartialView _FormView.
We’ll also employ the Graceful Modals technique in the Controller actions, as seen below, by using AjaxView in place of View.
// Edit
public virtual ActionResult FormView(int id) {
return AjaxView(_modelService.Load(id));
}
[HttpPost]
public virtual ActionResult FormView(ModelOfChoice model) {
if (!ModelState.IsValid)
return AjaxView(model);
// Save to Database
_modelService.Save(model);
TempData["Message"] = "Record Saved.";
return AjaxRedirectToAction(MVC.Something.FormView(model.ID));
}
A new method is used here called AjaxRedirectToAction, I’m still undecided on the best implementation, but a few signatures I’ve been playing around with can be seen below. You should also note that I try and create signatures to be compatible with T4MVC2 when possible.
protected ActionResult AjaxRedirectToRoute(RouteValueDictionary routeValues, Func<ActionResult> ajaxCallback) {
if (Request != null && Request.IsAjaxRequest())
return ajaxCallback();
return RedirectToRoute(routeValues);
}
protected ActionResult AjaxRedirectToRoute(RouteValueDictionary routeValues) {
return AjaxRedirectToRoute(routeValues, () => { return Content("ok"); });
}
protected ActionResult AjaxRedirectToRoute(ActionResult result) {
return AjaxRedirectToRoute(result.GetRouteValueDictionary(), () => { return AjaxView(); });
}
The purpose of this method is to implement the Redirect-After-Post pattern for non JavaScript requests.
All that is left to do now is wire up the JavaScript. Firstly, I’m going to make slight change to jquery.form.js. The change deals with the over zealous caching by all versions of Internet Explorer, whereby IE doesn’t differentiate based on headers. By default Microsoft Ajax and jQuery use a header to signify that a request originates in JavaScript. When designing a graceful solution, you must accept that within the same session a user may access Actions with either a standard request or an Ajax request. If the user is exposed to a combination, we want to make sure the browser is displaying the correct output for the right request.
MVC makes allowances for the fact that not all environments allow custom headers to be sent with a request, by allowing the header value to be sent as a Query String parameter. IE does differentiate on Query Strings, so the change to jquery.form.js will add this parameter. The change is added at line 62.
var ajaxified = url;
if (ajaxified.indexOf("?") >= 0)
ajaxified += "&";
else ajaxified += "?";
ajaxified += "X-Requested-With=XMLHttpRequest";
url = ajaxified;
The last job is the wire up itself, which is an almost out-of-the-box implantation of jquery.validate.js and jquery.form.js. The code is below.
$("form").validate({
submitHandler: function(form) {
$(form).ajaxSubmit({
target: ".form-wrapper"
});
}
});
At this point we should have a form that posts back to the server using Ajax or a standard page request, dependent on the existence of JavaScript. These forms should live quite happily within dynamically generated content and server rendered content.
A production implementation of this technique can be seen at http://21wappinglane.com.
Graceful modals with ASP.NET MVC2 & jQuery
Update 28/09/2010
I've included a sample project at the end of the post. The project can also be downloaded here: GracefulModals.zip.
I don’t profess to understand all of what MVC2 has to offer in terms of Ajax interoperability, so I maybe off base with a technique I’ve been working on to create graceful modals with a minimal repetition of mark-up. So I welcome feedback inclusive of constructive criticism.
What do I mean by graceful modals? Well, I believe the web in general should make sense without JavaScript or CSS switched on. It won’t be brilliant or really exciting, but it should be work semantically with buttons and links that do stuff. No broken forms and no links that go nowhere.
Okay, but what about the modals? Well modals don’t make a lot of sense to a non JavaScript world and who wants pop-ups? The link (to the modal) has got to do something, so it might as well still link to the modal content. This is graceful, an anchor tag that opens up a modal when JavaScript is switched on but still links to content when JavaScript is switched off.
In the past I would have created a Web Service or a Page Method to populate the modal using XML or JSON. In the past I have even been known to pre-render the modal on the server.
Shudder.
While there is nothing wrong with Web Service/Page Method technique, it is very close to what I now use. But for me at least, the implementation involved repetition of mark-up, sometimes hard coded directly into JavaScript.
Yuck.
What do I do now? I use MVC2 exclusively for new projects. Before MVC came out I had found myself completely disillusioned with the Web Forms environment and was considering drastic steps towards Java or PHP. MVC saved me from such horrors, changing the way I think about the interaction between client and server.
To clarify, I found the PostBack model of Web Forms to restrictive and the Server controls full of semantically incorrect mark-up. Upset Web Form developers can just assume I’m to stupid to understand it. I was totally joking about PHP and Java, I wouldn’t have considered making the move if I didn’t have respect. But seriously after using VS2010 any other IDE would be like flints and rock. Ug-ug.
I’m pretty sure the technique I use works in MVC1 on .NET 3.5, but be warned any code samples will be illustrated using MVC2/.NET4.
The first thing I do when creating a modal window, is create a standard page (Index) that links to another very standard page (Index2). This is my foundation, it works absent of any enhancements that will be added later.
If you are familiar with MVC you will know that these pages are Views and the link is to an Action that returns the second of the two Views.
At the moment, the Action that returns the second of the two Views (Indesx2) returns a fully marked up HTML page including header and body tags, etc… This isn’t going to be any good for dynamically populating a modal, so we need to split out the mark-up that we want to display in the modal without any duplication.
Keep it DRY folks.
The best way to do this is with a Partial, so I’ll create one called _Index2. I picked up the underscore naming convention from another post (can’t remember which) and have found it very handy as you can run into problems naming your Partials the same as your Views. Especially when you start treating Views as Partials, but that is a another story.
I’ve put the main content portion of my Index2 View into my _Index2 Partial and now need to reference _Index2 (Partial) from Index2 (View), which is easily done with the following code:
<% Html.RenderPartial("_Index2"); %>
Which I have shortened ever so slightly to:
<% Html.RenderPartial(); %>
With the following helper that assumes the underscore naming convention:
public static void RenderPartial(this HtmlHelper helper) {
helper.RenderPartial(String.Format("_{0}", helper.ViewContext.RouteData.Values["action"].ToString()));
}
My Index2 View now looks like:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> <asp:Content ContentPlaceHolderID="MainContent" runat="server"> <% Html.RenderPartial(); %> </asp:Content>
And my Index2 Partial looks like:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> <p> content</p>
I want to do one more thing to my mark-up. I will add a class to the anchor on my Index View to signify that I want the content to open up in a modal, which is shown below:
<%= Html.ActionLink("Index2", MVC.Home.Index2(), null, new { @class = "modal" }) %>
If you run all this now, you’ll notice no difference, clicking on the anchor in Index will still link to the Index2 View with content still intact. What I will do now, is create my modal. For the purposes of this post, I am just going to add a div called “modal” to my Master page. The fore mentioned div will be the container for our dynamic content.
Before we go on to the JavaScript, we need to make sure we can retrieve the content from Index2 without all the template HTML from the Master/View. To do this, I am going to enlist the help of a method I have created in the Controller called AjaxView. It works just like the View method but with an Ajax twist. The code is below:
protected ActionResult AjaxView(string viewName = null, object model = null) {
if (RouteData != null && String.IsNullOrEmpty(viewName))
viewName = RouteData.Values["action"].ToString();
if (Request != null && Request.IsAjaxRequest())
return PartialView(String.Format("_{0}", viewName), model);
return View(viewName, null, model);
}
protected ActionResult AjaxView(object model) {
return AjaxView(null, model);
}
The key to AjaxView is the extension method IsAjaxRequest. You can bing IsAjaxRequest for a full explanation but essentially the magic behind this method is in the client side libraries that support it. Libraries like jQuery and MsAjax add a header to Ajax requests to identify the request as being Ajax rather than a standard page request. IsAjaxRequest checks for this header and returns true if the header is found.
Our Index2 Action will now look like this:
public virtual ActionResult Index2() {
return AjaxView();
}
With any luck, the standard page requests to /Home/Index2 will be directed to Index2.aspx and Ajax requests will be directed to _Index2.ascx. Let’s Ajaxify that request!
We’re going to do this with the following jQuery click event wrapped in a document ready event:
$("a.modal").click(function(evt) {
var $this = $(this);
$("#modal").html("");
evt.preventDefault();
var url = $this.attr("href");
if (url && url != "")
$("#modal").load(url, function(responseText, textStatus, xhr) {
if (textStatus == "error") {
$("#modal").html("<p>An error has occurred, please try again later.</p>");
return;
}
if ($.isFunction(callback))
callback(textStatus);
});
});
The jQuery above attaches a click event handler to every anchor with a class of “modal”. The handler over overrides the standard click behaviour of the anchor and instead makes an Ajax request based on the anchor’s href attribute. The Ajax request is made using jQuery’s load function which is pointing at our modal div. The load function makes the request and populates the modal div with the response.
There we have it. Now, when we click on the anchor in Index (with JavaScript switched on) the page is not refreshed but instead the content from Index2 is dynamically loaded into the modal div. Clicking on the same link with JavaScript switched off still directs the browser to Index2 as before. This have been achieved with no duplication of mark-up using C# methods and JavaScript functions that can be reused with very little effort. Graceful.
You can download a sample project at the following location: GracefulModals.zip.
Related Links
Did everyone else know this?
We were messing around in a MVC 2 project the other day, when we came across a need to manipulate the class name of a DIV element in a Master Page from a View. I was going to start messing around with ViewData and whatnot but I really didn’t want to put too much effort into it. We were only likely to change the class name a couple of times so I wanted a quick and easy solution. Laziness is the mother of workarounds.
What we came up with was really quick and really easy, it also freaks Intellisense out. We put a Content Placeholder in the class value of the DIV. At the time it felt crazy, wondrous and groundbreaking, now it feels a little obvious. But I wanted to share anyway.
Here is a snippet from the Master Page:
<div class="<asp:ContentPlaceHolder ID="ClassName" runat="server" />">
And the corresponding View:
<asp:Content ContentPlaceHolderID="ClassName" runat="server">my-class</asp:Content>
Shazaaam! I can now tag up templated elements server side in mark up.
AttachFile Plug-in
I’m preparing a release to CodePlex and the Windows Live Gallery of my Windows Live Writer plug-in Attach File. The battery on my laptop is about to run out though so I honestly can’t be bothered with the MSI file that is a requirement of the Gallery submission. So, at the bottom of this post is a direct link to a zip containing the DLLs needed to add the plug-in functionality to Live Writer. Simply drag the two files to the Plugins folder of the Windows Live Writer installation directory.
I should note that the second of the two files is a third party DLL from CodePlex that provides the FTP communications layer. I will eventually do my own, but credit where it is due. The FTP project can be located at http://ftpclient.codeplex.com/.
Also, the icon is from FamFamFam. And yes, the link below was created using AttachFile.
Attach To Process
Just a quick note on debugging Windows Live Writer plug-ins. I only mention it because I have not seen it discussed elsewhere, you can attach Visual Studio to the Live Writer process. Attaching to the Live Writer process enables you to step through the code line by line, as you would a Windows Forms App in Visual Studio.
If you are already developing Live Writer plug-ins, you may be aware that by adding the following line to the Post Build Event, you can import the plug-in directly into Live Writer upon completion of a successful build.
XCOPY /D /Y /R "$(TargetPath)" "C:\Program Files\Windows Live\Writer\Plugins\"
On loading up Live Writer after successful build, switch back to Visual Studio and click on Debug > Attach to Process. You’ll now be presented with a window similar to the one in the screenshot below.
Double clicking on WindowsLiveWriter.exe will now provide debugging capabilities to the plug-in. Try it, create a a couple of break points and start interacting with the plug-in in Live Writer. I use this same technique for debugging Windows Services.
Setting Up a Windows Service Project in VS2008
Setting up, debugging and deploying a windows service can be a daunting task, but it is actually relatively straight forward. Relative to something ever so slightly more difficult to a console application.
Before I jump into the steps I have one piece of advice that has helped me side step a lot of grief. It is possible to debug a windows service using Visual Studio, by installing it on your development machine. The process can become a bit laborious though, in the early stages of development. My advice is to write all the guts of your service in a separate class library and add that library (as a reference) to a console application in the same solution. Use the console application to debug the majority of your code before adding the windows service project. You can then debug the various service state changes with the windows service itself.
Also, I have noticed that running a windows service on Vista is not exactly the same as running a service on Windows Server 2003. I don’t always do it, but I recommend some sort of internal logging so that you can work out any quirks without the aide of Visual Studio. I have my own code, that I am preparing to add to my K3R library, but I notice Live Labs have there own library on CodePlex now. The Live Labs logging library can be found here.
- Add a windows service project. Add references to your class libraries, if you have them.
- Open up Service1.cs (I’ve renamed mine to Service.cs) in design mode. This can be achieved by right clicking on Service.cs and selecting “View Designer”.
- Right click anywhere on the grey area of Service.cs and select “Add Installer”. This creates a new file called ProjectInstaller.cs.
- In the design mode of Project Installer.cs, I renamed serviceProcessInstaller1 to ServiceProcessInstaller and selected the account I would the service to run under. This is all done by selecting what was serviceProcessInstaller1 and opening the Properties window.
- I also renamed serviceInstaller1 to ServiceInstaller and personalised a few of the Misc properties; Description, Service Name, etc… The important property here though, is StartType. The selections you make here should be self explanatory.
- Add a setup project to the solution. I called mine ServiceSetup.
- Right click on the ServiceSetup project and click Add > Project Output. Select the windows service project from the drop down and add the project’s “Primary output” to setup project.
- Right click on the Service Setup project again and click View > Custom Actions. Right click on the root of Custom Actions and click Add Custom Action. Select the “Primary output” (of the Service project) from the Application Folder.
- Set up the properties of the new setup project, getting briefly annoyed that there isn’t a British locale.
- You are there. Providing your solution builds, you’re ready to install your service on a test machine. Remeber, you will have to start the service manually first of all, even if you have set the StartType to Automatic.
I should say, this post really constitutes a quick start guide and if you’re looking for more detailed information, I recommend an excellent series of posts on Arcane Code, links of which I’ve listed below.
Operator, can you connect me to 555 Coolsville?
I’ve admired the operator keyword from afar for some time, the ability to overload operators and conversions is pretty wicked. It wasn’t until this morning that I had a requirement, so I’ve had a little play, in order to understand the basics.
My first experiment was very basic, my intention was to create a class that I can add together using the + operator. The code is below.
public class Account {
public int Balance { get; set; }
public static int operator + (Account a, Account b) {
return a.Balance + b.Balance;
}
}
var a = new Account { Balance = 5 };
var b = new Account { Balance = 5 };
int totalBalance = a + b; // 10
Now I happen to think that is pretty smart. My example was very basic, but think of all of the calculations that could be encapsulated within an operator overload. Within this framework you could calculate multiple property values and even output to a secondary custom class representing a balance sheet.
This last example was created to understand the relationship between calculations involving more than two instances of a class. Before I continue, I realise there are already short cuts in place to quickly create Generic lists. This example overloads the % operator to allow the quick creation of Generic lists. What is particularly interesting is that you can describe the relationships between your class and any other class that it may encounter.
public class Account {
public int Balance { get; set; };
public static List operator %(Account a, Account b) {
return new List {
a,
b
};
}
public static List operator %(List a, Account b) {
a.Add(b);
return a;
}
}
var a = new Account { Balance = 5 };
var b = new Account { Balance = 5 };
var c = new Account { Balance = 6 };
(a % b % c).Count; // 3
Imagine the example above returning a custom collection or another object that allowed you to query the three accounts simultaneously for balances and other financial totals.
K3R ADO.NET .NET 3.5 Wrapper
I have recently created a project on CodePlex for a class library I have been using for a little while called K3R.Data. The project is located here.
Before I continue, this code might seem completely redundant to developers fully conversant with ADO.NET changes from .NET 3.0 onwards. I confess I am not fully conversant, I try, but the .NET framework is such a vast subject that it is difficult to keep up with every aspect. To that end, any constructive feedback regarding my code (including it’s redundancy) is always welcome.
using (Connection conn = new Connection(connectionString, "stored_procedure")) {
conn.AddParameter("@active", active);
SqlParameter outputParam = conn.AddParameter("@output", SqlDbType.Int, ParameterDirection.Output);
conn.ExecuteNonQuery();
}
K3R.Data was originally written in .NET 2.0. I created the code to circumvent much of the repetitive code associated with database connections. The .NET 2.0 code effectively merged the SqlConnection and SqlCommand objects into a single class. The code has a biases towards stored procedures and the SqlDataReader class. I’m not keen on DataSet’s, I find them a bit cumbersome. I prefer strongly typed custom objects and generic lists. The .NET 2.0 code also streamlines the adding of output SQL parameters, which can now be done in a single line.
The code in it’s current state is built for .NET 3.5. The code now sports enhanced generics support and extension methods.
Club club = new Club {
ID = dr["id"].DBValueOrDefault(),
Name = dr["name"].DBValueOrDefault("")
};
The K3R.Data class library includes a class called Extension. This class includes a number of extension methods for dealing with loosely typed data and the SqlDataReader class. Most of the methods make use of generics, which can be used to imply strong data types for data returned in a SqlDataReader. The example above demonstrates a extension method that allows you to provide default values when a DBNull.Value is returned, or use the default value for the given data type.
So that’s the essence of the beast, if a .NET class library can be called a beast. This post does not constitute all of K3R.Data’s functionality, but does give an indication of what I have tried to achieve. Other features include extension methods for interrogating SqlDataReader objects and for converting data into generic structures like key/value pairs.



