I want to share a custom solution that I needed to implement for lifecycle management problem in a long running application, window service. This scenario valid for windows desktop applications and services, actually this solution is applicable for any scenario that you use thread pooling.

Tools

Let’s first mention about the technologies that this post is about.

Quartz.NET is an open source project aimed at creating a free-for-commercial use Job Scheduler, with ‘enterprise’ features.

You can download binaries or source code of the project from its github page.

StructureMap is a Dependency Injection / Inversion of Control tool for .Net that can be used to improve the architectural qualities of an object oriented system by reducing the mechanical costs of good design techniques.

StructureMap is one of my favorite inversion of control container, another one is Windsor. But this post is all about StructureMap container. You can access to StructureMap documentation from its web page and download source code and binaries from its github page.

The Problem Definition

StructureMap works perfectly with very less configuration, and it has a very easy to discover API to work with. Quartz.NET is a ported project from original Quartz project from Java world (act like you are surprised!).

I had a problem with default configuration options of StructureMap and Quartz.NET. When I needed to have one instance of an object per quartz job. I just made a configuration in StructureMap registry and set that objects lifecycle as HybridHttpOrThreadLocalScoped.

HybridHttpOrThreadLocalScoped is one of the lifecycle scopes that you can use in StructureMap, and this scope creates only one instance of an object per HttpContext or Thread. If it is a web application it uses HttpContext, so you can have only one instance of that object per request comes in your application, or if you are running in a windows service or forms application it creates only one instance of that object per thread.

This seems perfectly good at first but remember it creates one instance per thread. When you are using thread pool you will reuse your threads.

ThreadPool

Provides a pool of threads that can be used to execute tasks, post work items, process asynchronous I/O, wait on behalf of other threads, and process timers.

Read the rest of this entry »

Creating a publish folder for web applications is easy, you don’t have to do anything for that, web application project template does it for you. When you working with solutions for more than one project you have deal with different deployable units/packages. I was working on a build script that we need to run in our continuous integration process. But creating separate packages for each project was painful is you want to do it manually, and I tried to understand how web application projects template works and came up with this solution.

CopyToPublishedApplications msbuild file inspired by Microsoft web application projects build process file “Microsoft.WebApplication.targets”.

It creates _PublishedApplications\yourappname folder in your output directory.

By using this msbuild file you don’t have to deal with seperation of files based on projects when you are building solutions with multiple projects.

msbuild file and sample project is located in my github account. please follow the link : https://github.com/hancengiz/misc/tree/master/CopyToPublishedApplications

 

Usage

  • You just need to add below import line at the bottom of the project file and execute msbuild.exe with the /p:CopyToPublishedApplications=true parameter.

<Import Project=”….\CopyToPublishedApplications.msbuild” />

  • Add CopyToPublishedApplications parameter to msbuild command line. default value of CopyToPublishedApplications is false.

msbuild yoursolutionfile.sln /p:OutputPath=C:\yourcioutputfolder /p:CopyToPublishedApplications=true

Read the rest of this entry »

ASP.NET MVC Model Binders map posted form values to a .NET classes, instead of accepting primitive parameters or form value collection you can accept models/view models as input to your action methods. ASP.NET has a default model binder called DefaultModelBinder. It basically works with most of the .NET types like primitive types, arrays, IList, ICollection and IDictionary.

ASP.NET MVC also has extensibility for model binders and you can implement IModelBinder interface (or you can extend DefaultModelBinder) and you can create your custom model binders. IModelBinder interface contains a BindModel method that called by ASP.NET MVC framework and you can have a full control over the deserialization process.

In this post I will demonstrate how default model binder works for simple model binding. I always recommend to creating ViewModel for your MVC application over directly using Models in your controller layer. Because normally you don’t get all properties about your domain model from a request input. You get input request to your controller as ViewModel validate input and execute your logic and do what ever you need to do, like map it back to a Domain Model type and persist it.

In this post I will basically create a form to add a movie record and will use a ViewModel to get form inputs from http request.

Read the rest of this entry »

Unit testing is a method to test and determine that each single unit of testable source code behaves exactly as expected. Unit tests isolates the unit that is under test from the remainder of all source code. Only that particular single unit should be executed when unit test invokes a unit to test and makes assertions to determine the test results.

Your test is not a unit test if your source code invokes another unit when you run a unit test against to a one single unit. It’s integration testing.

You have to write testable code if you want to apply Test Driven Development (TDD) or want to write unit tests at least. If you apply TDD practice “red, green, refactor”, basically if you write your test first and implementation to pass that test you will be forced to write testable code.

The way to write unit tests are using stub and mock objects. Read Martin Fowler’s Mocks Aren’t Stubs article for more information and differences between mock and stub objects.

After this short introduction to unit testing I want to share a code sample.

Read the rest of this entry »

In one of my previous blog post I mentioned about ASP.NET MVC action filters.

Action filters provides us to ability create an aspect oriented approach in ASP.NET MVC application. It’s not the only way off course, IoC containers provide this ability too. Specially in enterprise level applications you can use IoC containers to create wrappers around your objects with creating interceptors. Action filter is to easy way to have a cross cutting aspect approach for your controllers in ASP.NET MVC.

ASP.NET MVC 3 has a new action filter type called Global Action Filters. You don’t need to decorate your all controllers, action methods with attributes with Global Action Filters. ASP.NET MVC pipeline invokes your action filter before/after events after you defined your Global Action Filter you just need to register it in one location. So you can create your aspect oriented approach around your controllers/action methods.

To create an Global Action Filters you just need to define a new class which inherits from ActionFilterAttribute

public class MvcProfilerGlobalAttribute : ActionFilterAttribute
{
//...
}

And registration point for your Global Action Filter is Application_Start() method in your Global.asax.cs file or your custom HttpModule implementation.

protected void Application_Start()
{
    //...
    GlobalFilters.Filters.Add(new MvcProfilerGlobalAttribute());
}

I needed to profile and trace all request and find requests which take longest time, requests which run highest cost sql queries and that kind of information in one of my previous enterprise scale service oriented project. I needed this because big team of developers were working on project and it was really hard to review each sql queries because it was a project in production so I found this profiling option is the best way to find service endpoints that needs refactoring and optimization improvements. It was years ago and it was a WCF, Remoting supported framework and I ended up with an interceptor implementation in service side but in this blog post I want to implement with Global Action Filter to demonstrate its capacity. This example is not profiling sql queries but it is open for improvements, this is just an example about Global Action Filters.

Read the rest of this entry »

jQuery validate plugin provides us to validate HTML forms. jQuery validate plugin disables submitting the for until all specified validation rules are valid. It shows an error label next to invalid field and informs users about input errors.

ASP.NET MVC 3 uses jQuery validation (http://docs.jquery.com/Plugins/validation) for form validations and jQuery validation library has a remote validation feature, using this feature by ASP.NET MVC libraries is really easy but I want to show basic sample with HTML and jQuery.

Create below html document as a basic HTML form.

<!DOCTYPE html>
<html>
<head>
    <title>jquery validate</title>
    <!-- javascript will come here -->
</head>
<body>
    <form id="userform" action="/Create" method="post">
    
    <div><label for="FirstName">First name</label></div>
    <div><input id="FirstName" name="FirstName" type="text"/></div>
    
    <div><label for="LastName">Last name</label></div>
    <div><input id="LastName" name="LastName" type="text"/></div>
    
    <div><label for="Email">Email</label></div>
    <div><input id="Email" name="Email" type="text"/></div>

    <div><input type="submit" value="Create" /></div>
    </form>
</body>
</html>

And then add below javascript code between "head" tags of the HTML document.

<script src="/Scripts/jquery-1.4.4.js" type="text/javascript"></script>
    <script src="Scripts/jquery.validate.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("#userform").validate({
                rules: {
                    FirstName: { required: true, maxlength: 64 },
                    LastName: { required: true, maxlength: 64 },
                    Email: { maxlength: 32,email:true, }
                }
            });
        });
</script>

This code demonstrates a basic jQuery validation sample, jQuery Validate plugins validates the form before it submitted, if form is valid it submits the form, otherwise form doesn’t get submitted.

Read the rest of this entry »

Javascript is very important part of web pages and web development. Web pages are static documents and Javascript is a programming language that can run in your browser (when we are talking about web pages).

How Javascript can be obstructive for your web pages?

-Web browser doesn’t have support for Javascript
-Javascript stripped at the company firewall
-Some people choose to disable Javascript by some addons or by browser settings to protect themselves from XSS, CSRF vulnerabilities.
-Some mobile browsers doesn’t have Javascript support

Above reasons makes Javascript obstructive that means probably your HTML document will not perform what you expect when user clicked an element which triggers a Javascript function.

For example, you have an order form that needs some input from user and validates them with Javascript code and submits the form. But if Javascript can’t get executed by browser users can’t order from your site. Anything dynamic with Javascript will fail in your web page for this kind of users.

Do you really want to ignore these users for your “business critical web”?

The idea of unobtrusive Javascript is make your static HTML web pages functioning and add Javascript functionalty over it. Basically your static HTML web page should be able to run and function correctly, and javascript should be supportive layer over that.

Read the rest of this entry »

Fiddler is a web debugging proxy which logs all HTTP(S) traffic between your computer and the Internet.
It’s really great tool for developers when developing a web application or http consumer application. It helps us to inspect all HTTP(S) traffic, set breakpoints, create auto-responders for specific requests to stub out some data.

But as default Fiddler logs all HTTP(S) traffic and log list can be very long if you are using/running other applications that creates HTTP(S) traffic. Fiddler provides a scriptable rules mechanism. It uses javascript syntax and provides a object model to create custom rules.

You can filter out requests from Fiddler log screen by using customized rules. For example if you want to see requests to a specific list of domains (internal development servers?) you can just use below script.

To add rules, choose Customize Rules on Fiddler’s Rules menu. Enter code inside the suggested function and save the file. Fiddler will automatically reload the rules.

in OnBeforeRequest method :

if (oSession.uriContains("mydevelopmentserver1.int")){
oSession["ui-hide"] = "true"; // any string value is OK to hide
}

Fiddler custom rules object model provides more functionality. For example to return a 404 response for a specific request from Fiddler level (actually request doesn’t hit the real endpoint).

in OnBeforeRequest method :

if (oSession.uriContains("mydevelopmentserver1.int/productservice")){
oSession["ui-color"]="orange";
oSession["ui-bold"]="true";
oSession.oRequest.FailSession(404, "Blocked", "Fiddler blocked product service request");
}

Fiddler is a really powerful tool and I strongly suggest to keep it running when you are developing a web application for HTTP(S) client application.

For more information about Fiddler scripting samples you can check this web page.

Before I write some code and sample oriented articles about ASP.NET MVC Framework Action Filters. I want to make a quick introduction and talk about filters. You may need to do something before or after your action methods get executed. ASP.NET MVC Framework provides some level of filters to do that kind of things. Filters are not different then normal classes in .NET, and you can use declarative programming features to active this special classes, filters.

Types of ASP.NET Filters

Authorization Filters : These are for performing authorization logics on action methods. Implements IAuthorizationFilter interface. Built-in samples : AuthorizeAttribute and RequireHttpsAttribute.

Action Filters : Implements IActionFilter interface and provides OnActionExecuting and OnActionExecuted methods to perform things before and after of action methods get executed.

Result Filters : Implements IResultFilter and provides OnResultExecuting and OnResultExecuted methods to perform additional logics before and after ActionResult objects get executed. Builtin sample : OutputCacheAttribute, this attribute can returns cached result before action method get executed.

Exception Filters : Implements IExcetionFilter and gets executed if an unhandled exception occurs on action method. You can log and create custom result if unhandled exception occurs.

Filter objects don’t keep state, they are transient objects and for each request they get initialized and disposed when request completes.

If you set some value to the ActionExecutingContext.Result property in OnActionExecuting and OnResultExecuting methods pending filters will not be executed.

You can use existing xxxAttribute classes which implement required interfaces and inherits from Attribute. FilterAttribute (base of all), ActionFilterAttribute, AuthorizeAttribute, HandleErrorAttribute.

Controller base class implements all this interfaces by default so it has all these 6 method implementations and it does nothing by default but if you want to override one of them you can create your own base class and override it. That means instead of creating your custom filter with required  implementation and decorating your controllers with that attribute you can create a base controller and override methods.

But we should keep in my mind overridden methods get executed before all custom created filter attributes regardless of Order value in attributes.

Now you have this question : When we should create and use filter attributes or when should we override methods from controller class?

If you don’t have a custom base controller class for each controller and if you want to reuse filter attributes in all controllers use filter attributes. If someone asks my opinion, I prefer to create different attributes to have a better design.  And this doesn’t mean that you need to apply your filters to all your controllers separately. I would still prefer to have a custom base controller class and decorate my custom filter attributes on the base class level if I want to apply an attribute to all controllers. Check Layer Super Type design pattern from Martin Fowler’s Patterns of Enterprise Application Architecture book. (http://www.martinfowler.com/eaaCatalog/layerSupertype.html)

Before finishing this article I want to mention about Order’s of attributes. Normally your filter attributes should not be depended on each others execution but it’s better to know when these are get executed.

Executin order of filters :

  1. Authorization filters
  2. Action filters
  3. Response filters
  4. Exception filters

If you have more filters applied for a filter type, Order property defines execution order of filters.

I am planning to write some samples for filters and I hope this quick introduction can help some people to understand the concept.

In my previous blog entry (How to create custom HTML Helpers for ASP.NET MVC 3 and Razor View Engine) I mentioned extensibility point of Razor View Engine to change view/page base class type. It’s not a new approach for ASP.NET developers, we have been applying same pattern for ASP.NET Web Pages too.

You have to create a class which inherits from System.Web.Mvc.WebViewPage. You have to make it abstract class, so you don’t need to override abstract Execute method which inherits from WebPageExecutingBase, ASP.NET MVC runtime uses this method on runtime, actually creates an override method for this method at runtime, so if you override this method it will not change anything it will be overridden at runtime when ASP.NET create a type for your view/page.

    public abstract class DeveloqWebViewPage<T> : WebViewPage
    {
        public YourProjectSpecificHelper YourProjectSpecificHelper { get; set; }
        public YourCustomUiLibraryHelper YourCustomUiLibraryHelper { get; set; }

        public override void InitHelpers()
        {
            base.InitHelpers();
            YourProjectSpecificHelper = new YourProjectSpecificHelper();
            YourCustomUiLibraryHelper = new YourCustomUiLibraryHelper();
        }
    }

Read the rest of this entry »

top