Subscribe: Zack Owens : ASP.NET
Added By: Feedage Forager Feedage Grade B rated
Language: English
application  body body  body replace  body  code  controller  javascript  mvc  net mvc  net  replace body  replace  string  tenant 
Rate this Feed
Rate this feedRate this feedRate this feedRate this feedRate this feed
Rate this feed 1 starRate this feed 2 starRate this feed 3 starRate this feed 4 starRate this feed 5 star

Comments (0)

Feed Details and Statistics Feed Statistics
Preview: Zack Owens : ASP.NET


Content tagged with ASP.NET


ASP.NET JavaScript Routing for ASP.NET MVC–Constraints

Tue, 04 Jan 2011 22:12:24 GMT

If you haven’t had a look at my previous post about ASP.NET routing, go ahead and check it out before you read this post: And the code is here:   Anyways, this post is about routing constraints. A routing constraint is essentially a way for the routing engine to filter out route patterns based on the day from the URL. For example, if I have a route where all the parameters are required, I could use a constraint on the required parameters to say that the parameter is non-empty. Here’s what the constraint would look like: Notice that this is a class that inherits from IRouteConstraint, which is an interface provided by System.Web.Routing. The match method returns true if the value is a match (and can be further processed by the routing rules) or false if it does not match (and the route will be matched further along the route collection). Because routing constraints are so essential to the route matching process, it was important that they be part of my JavaScript routing engine. But the problem is that we need to somehow represent the constraint in JavaScript. I made a design decision early on that you MUST put this constraint into JavaScript to match a route. I didn’t want to have server interaction for the URL generation, like I’ve seen in so many applications. While this is easy to maintain, it causes maintenance issues in my opinion. So the way constraints work in JavaScript is that the constraint as an object type definition is set on the route manager. When a route is created, a new instance of the constraint is created with the specific parameter. In its current form the constraint function MUST return a function that takes the route data and will return true or false. You will see the NotEmpty constraint in a bit. Another piece to the puzzle is that you can have the JavaScript exist as a string in your application that is pulled in when the routing JavaScript code is generated. There is a simple interface, IJavaScriptAddition, that I have added that will be used to output custom JavaScript. Let’s put it all together. Here is the NotEmpty constraint. There’s a few things at work here. The constraint is called “notEmpty” in JavaScript. When you add the constraint to a parameter in your C# code, the route manager generator will look for the JsConstraint attribute to look for the name of the constraint type name and fallback to the class name. For example, if I didn’t apply the “JsConstraint” attribute, the constraint would be called “NotEmpty”. The JavaScript code essentially adds a function to the “constraintTypeDefs” object on the “notEmpty” property (this is how constraints are added to routes). The function returns another function that will be invoked with routing data. Here’s how you would use the NotEmpty constraint in C# and it will work with the JavaScript routing generator. The only catch to using route constraints currently is that the following is not supported: The constraint will work in C# but is not supported by my JavaScript routing engine. (I take pull requests so if you’d like this… go ahead and implement it).   I just wanted to take this post to explain a little bit about the background on constraints. I am looking at expanding the current functionality, but for now this is a good start. Thanks for all the support with the JavaScript router. Keep the feedback coming! [...]

ASP.NET MVC JavaScript Routing

Mon, 20 Dec 2010 16:15:00 GMT

Have you ever done this sort of thing in your ASP.NET MVC view? The weird thing about this isn’t the alert function, it’s the code block containing the Url formation using the ASP.NET MVC UrlHelper. The terrible thing about this experience is the obvious lack of IntelliSense and this ugly inline JavaScript code. Inline JavaScript isn’t portable to other pages beyond the current page of execution. It is generally considered bad practice to use inline JavaScript in your public-facing pages. How ludicrous would it be to copy and paste the entire jQuery code base into your pages…? Not something you’d ever consider doing. The problem is that your URLs have to be generated by ASP.NET at runtime and really can’t be copied to your JavaScript code without some trickery. How about this? Does the hard-coded URL bother you? It really bothers me. The typical solution to this whole routing in JavaScript issue is to just hard-code your URLs into your JavaScript files and call it done. But what if your URLs change? You have to now go an track down the places in JavaScript and manually replace them. What if you get the pattern wrong? Do you have tests around it? This isn’t something you should have to worry about.   The Solution To Our Problems The solution is to port routing over to JavaScript. Does that sound daunting to you? It’s actually not very hard, but I decided to create my own generator that will do all the work for you. What I have created is a very basic port of the route formation feature of ASP.NET routing. It will generate the formatted URLs based on your routing patterns. Here’s how you’d do this: Does that feel familiar? It looks a lot like something you’d do inside of your ASP.NET MVC views… but this is inside of a JavaScript file… just a plain ol’ file.  Your first question might be why do you have to have that “.toUrl()” thing. The reason is that I wanted to make POST and GET requests dead simple. Here’s how you’d do a POST request (and the same would work with a GET request):   The first parameter is extra data passed to the post request and the second parameter is a function that handles the success of the POST request. If you’re familiar with jQuery’s Ajax goodness, you’ll know how to use it. (if not, check out and the parameters are essentially the same). But we still haven’t gotten rid of the magic strings. We still have controller names and action names represented as strings. This is going to blow your mind… If you’ve seen T4MVC, this will look familiar. We’re essentially doing the same sort of thing with my JavaScript router, but we’re porting the concept to JavaScript. The good news is that parameters to the controllers are directly reflected in the action function, just like T4MVC. And the even better news… IntlliSense is easily transferred to the JavaScript version if you’re using Visual Studio as your JavaScript editor. The additional data parameter gives you the ability to pass extra routing data to the URL formatter.   About the Magic You may be wondering how this all work. It’s actually quite simple. I’ve built a simple jQuery pluggin (called routeManager) that hangs off the main jQuery namespace and routes all the URLs. Every time your solution builds, a routing file will be generated with this pluggin, all your route and controller definitions along with your documentation. Then by the power of Visual Studio, you get some really slick IntelliSense that is hard to live without. But there are a few steps you have to take before this whole thing is going to work. First and foremost, you need a reference to the JsRouting.Core.dll to your projects containing controllers or routes. Second, you have to specify your routes in a bit of a non-standard way. See, we can’t just pull routes out of your App_Start in your Global.asax. We force you to build a route source like [...]

Multi-tenant ASP.NET MVC – Inversion of Control

Wed, 23 Jun 2010 14:30:14 GMT

Part I – Introduction Part II – Foundation Part III – Controllers Part IV – Views Source Code One of the most important aspects of my Multi-tenant ASP.NET MVC implementation is Inversion of Control containers. These containers are essential to wiring up and finding the proper controllers. In my last iteration of code that followed the Views post, my setup for the container was a simple association of types added to the PluginGraph. I really do not want to have to do this manually. Therefore, I want to utilize StructureMap the best I can. This post will show you how I wire up controllers by convention rather than by configuration.   The Convention The main convention I will be targeting is this: the controller that will be wired must have the same name as the root (or a unique name) and must inherit from a controller of the same name or “Controller”. For example, this first class would be in the “Host” project (for this example, the controller is “AccountController”). If a tenant project DID NOT override the AccountController, the host’s AccountController would be added to the container. If a tenant DID override AccountController, the AccountController in the tenant would be used as the AccountController. Here’s the example in code:   // AccountController in the Host project namespace MyApp.HostWeb { public class AccountController : Controller { .... } } // AccountController in the Tenant project namespace MyApp.FirstTenant { public class AccountController : MyApp.HostWeb.AccountController { .... } } The obvious downside to this implementation is that the fully qualified controller name must be used after the “:” to denote inheritance. You could implement this a bit differently, but I’ve chosen this way for simplicity.   Wiring Up Controllers The question that arises is how to inject this convention into container configuration using StructureMap. The way I’ve chosen to go is by using assembly scanner conventions. An assembly scanner will blindly go through all the types in a specified assembly and run the types against a convention. There are some conventions already in place, but we can also write our own conventions. In my implementation, the host and tenant project assemblies will both be scanned for controllers. Here’s how the assembly scanning works inside the configuration of a container:   var container = new Container(); container.Configure(config => { config.Scan(scanner => { // add the conventions scanner.Convention(); // specify assemblies to scan (just examples here, simpler in practice) scanner.TheCallingAssembly(); scanner.Assembly(typeof(Something).Assembly); scanner.Assembly("MyAssembly"); scanner.AssemblyContainingType(); }); });   Writing the Convention The next step is to write ControllerConvention so that the controllers will be added correctly to the container. I’m using a little black magic to intercept types and initialize them properly using an interceptor. However, this is frankly the only way I’ve found that works. But anyways, here’s the code. public class ControllerConvention : IRegistrationConvention { public void Process(Type type, Registry registry) { if (registry == null || !IsValidController(type)) return; var baseClass = type.BaseType; if (!IsValidController(baseClass) || !baseClass.Name.Equals(type.Name)) registry.AddType(typeof(IController), type); else { registry.AddType(typeof(IController), baseClass); registry.RegisterInterceptor(new TypeReplacementInterceptor(baseClass, type)); } } private static bool IsValidController(Type type) { return type != null && !type.IsAbstract && typeof(IController).IsAssignableFrom(type) && typ[...]

Multi-tenant ASP.NET MVC - Views

Wed, 16 Jun 2010 16:56:45 GMT

Part I – Introduction Part II – Foundation Part III – Controllers   So far we have covered the basic premise of tenants and how they will be delegated. Now comes a big issue with multi-tenancy, the views. In some applications, you will not have to override views for each tenant. However, one of my requirements is to add extra views (and controller actions) along with overriding views from the core structure. This presents a bit of a problem in locating views for each tenant request. I have chosen quite an opinionated approach at the present but will coming back to the “views” issue in a later post. What’s the deal? The path I’ve chosen is to use precompiled Spark views. I really love Spark View Engine and was planning on using it in my project anyways. However, I ran across a really neat aspect of the source when I was having a look under the hood. There’s an easy way to hook in embedded views from your project. There are solutions that provide this, but they implement a special Virtual Path Provider. While I think this is a great solution, I would rather just have Spark take care of the view resolution. The magic actually happens during the compilation of the views into a bin-deployable DLL. After the views are compiled, the are simply pulled out of the views DLL. Each tenant has its own views DLL that just has “.Views” appended after the assembly name as a convention. The list of reasons for this approach are quite long. The primary motivation is performance. I’ve had quite a few performance issues in the past and I would like to increase my application’s performance in any way that I can. My customized build of Spark removes insignificant whitespace from the HTML output so I can some some bandwidth and load time without having to deal with whitespace removal at runtime.   How to setup Tenants for the Host In the source, I’ve provided a single tenant as a sample (Sample1). This will serve as a template for subsequent tenants in your application. The first step is to add a “PostBuildStep” installer into the project. I’ve defined one in the source that will eventually change as we focus more on the construction of dependency containers. The next step is to tell the project to run the installer and copy the DLL output to a folder in the host that will pick up as a tenant. Here’s the code that will achieve it (this belongs in Post-build event command line field in the Build Events tab of settings) %systemroot%\Microsoft.NET\Framework\v4.0.30319\installutil "$(TargetPath)" copy /Y "$(TargetDir)$(TargetName)*.dll" "$(SolutionDir)Web\Tenants\" copy /Y "$(TargetDir)$(TargetName)*.pdb" "$(SolutionDir)Web\Tenants\" The DLLs with a name starting with the target assembly name will be copied to the “Tenants” folder in the web project. This means something like MultiTenancy.Tenants.Sample1.dll and MultiTenancy.Tenants.Sample1.Views.dll will both be copied along with the debug symbols. This is probably the simplest way to go about this, but it is a tad inflexible. For example, what if you have dependencies? The preferred method would probably be to use IL Merge to merge your dependencies with your target DLL. This would have to be added in the build events. Another way to achieve that would be to simply bypass Visual Studio events and use MSBuild.   I also got a question about how I was setting up the controller factory. Here’s the basics on how I’m setting up tenants inside the host (Global.asax) protected void Application_Start() { RegisterRoutes(RouteTable.Routes); // create a container just to pull in tenants var topContainer = new Container(); topContainer.Configure(config => { config.Scan(scanner => { scanner.AssembliesFromPath(Path.Combine(Server.MapPath("~/"), "Tenants")); scanner.AddAllTypesOf(); [...]

Mulit-tenant ASP.NET MVC – Controllers

Mon, 07 Jun 2010 16:40:00 GMT

Part I – Introduction Part II – Foundation   The time has come to talk about controllers in a multi-tenant ASP.NET MVC architecture. This is actually the most critical design decision you will make when dealing with multi-tenancy with MVC. In my design, I took into account the design goals I mentioned in the introduction about inversion of control and what a tenant is to my design. Be aware that this is only one way to achieve multi-tenant controllers.   The Premise MvcEx (which is a sample written by Rob Ashton) utilizes dynamic controllers. Essentially a controller is “dynamic” in that multiple action results can be placed in different “controllers” with the same name. This approach is a bit too complicated for my design. I wanted to stick with plain old inheritance when dealing with controllers. The basic premise of my controller design is that my main host defines a set of universal controllers. It is the responsibility of the tenant to decide if the tenant would like to utilize these core controllers. This can be done either by straight usage of the controller or inheritance for extension of the functionality defined by the controller. The controller is resolved by a StructureMap container that is attached to the tenant, as discussed in Part II.   Controller Resolution I have been thinking about two different ways to resolve controllers with StructureMap. One way is to use named instances. This is a really easy way to simply pull the controller right out of the container without a lot of fuss. I ultimately chose not to use this approach. The reason for this decision is to ensure that the controllers are named properly. If a controller has a different named instance that the controller type, then the resolution has a significant disconnect and there are no guarantees. The final approach, the one utilized by the sample, is to simply pull all controller types and correlate the type with a controller name. This has a bit of a application start performance disadvantage, but is significantly more approachable for maintainability. For example, if I wanted to go back and add a “ControllerName” attribute, I would just have to change the ControllerFactory to suit my needs.   The Code The container factory that I have built is actually pretty simple. That’s really all we need. The most significant method is the GetControllersFor method. This method makes the model from the Container and determines all the concrete types for IController.  The thing you might notice is that this doesn’t depend on tenants, but rather containers. You could easily use this controller factory for an application that doesn’t utilize multi-tenancy. public class ContainerControllerFactory : IControllerFactory { private readonly ThreadSafeDictionary> typeCache; public ContainerControllerFactory(IContainerResolver resolver) { Ensure.Argument.NotNull(resolver, "resolver"); this.ContainerResolver = resolver; this.typeCache = new ThreadSafeDictionary>(); } public IContainerResolver ContainerResolver { get; private set; } public virtual IController CreateController(RequestContext requestContext, string controllerName) { var controllerType = this.GetControllerType(requestContext, controllerName); if (controllerType == null) return null; var controller = this.ContainerResolver.Resolve(requestContext).GetInstance(controllerType) as IController; // ensure the action invoker is a ContainerControllerActionInvoker if (controller != null && controller is Controller && !((controller as Controller).ActionInvoker is ContainerControllerActionInvoker)) (controller as Controller).ActionInvoker = new ContainerControllerActionInvoker(this.Conta[...]

Multi-tenant ASP.NET MVC – Introduction

Thu, 27 May 2010 00:56:00 GMT

I’ve read a few different blogs that talk about multi-tenancy and how to resolve some of the issues surrounding multi-tenancy. What I’ve come to realize is that these implementations overcomplicate the issues and give only a muddy implementation! I’ve seen some really illogical code out there. I have recently been building a multi-tenancy framework for internal use at Through this process, I’ve realized a few different techniques to make building multi-tenant applications actually quite easy. I will be posting a few different entries over the issue and my personal implementation. In this first post, I will discuss what multi-tenancy means and how my implementation will be structured.   So what’s the problem? Here’s the deal. Multi-tenancy is basically a technique of code-reuse of web application code. A multi-tenant application is an application that runs a single instance for multiple clients. Here the “client” is different URL bindings on IIS using ASP.NET MVC. The problem with different instances of the, essentially, same application is that you have to spin up different instances of ASP.NET. As the number of running instances of ASP.NET grows, so does the memory footprint of IIS. Stack Exchange shifted its architecture to multi-tenancy March. As the blog post explains, multi-tenancy saves cost in terms of memory utilization and physical disc storage. If you use the same code base for many applications, multi-tenancy just makes sense. You’ll reduce the amount of work it takes to synchronize the site implementations and you’ll thank your lucky stars later for choosing to use one application for multiple sites. Multi-tenancy allows the freedom of extensibility while relying on some pre-built code.   You’d think this would be simple. I have actually seen a real lack of reference material on the subject in terms of ASP.NET MVC. This is somewhat surprising given the number of users of ASP.NET MVC. However, I will certainly fill the void ;). Implementing a multi-tenant application takes a little thinking. It’s not straight-forward because the possibilities of implementation are endless. I have yet to see a great implementation of a multi-tenant MVC application. The only one that comes close to what I have in mind is Rob Ashton’s implementation (all the entries are listed on this page). There’s some really nasty code in there… something I’d really like to avoid. He has also written a library (MvcEx) that attempts to aid multi-tenant development. This code is even worse, in my honest opinion. Once I start seeing Reflection.Emit, I have to assume the worst :) In all seriousness, if his implementation makes sense to you, use it! It’s a fine implementation that should be given a look. At least look at the code. I will reference MvcEx going forward as a comparison to my implementation. I will explain why my approach differs from MvcEx and how it is better or worse (hopefully better).   Core Goals of my Multi-Tenant Implementation The first, and foremost, goal is to use Inversion of Control containers to my advantage. As you will see throughout this series, I pass around containers quite frequently and rely on their use heavily. I will be using StructureMap in my implementation. However, you could probably use your favorite IoC tool instead. However, please don’t be stupid and abstract your IoC tool. Each IoC is powerful and by abstracting the capabilities, you’re doing yourself a real disservice. Who in the world swaps out IoC tools…? No one! (It had to be said.) I will outline some of the goodness of StructureMap as we go along. This is really an invaluable tool in my tool belt and simple to use in my multi-tenant implementation. The second core goal is to represent a tenant as easily as possible. Just as a dependency container will be a first-class citizen, so[...]

Filter IQueryable by String for ASP.NET MVC

Fri, 22 Jan 2010 18:44:00 GMT

In ASP.NET web applications, mostly seen in MVC, it is really nice to have a standard way to filter a query based on a pre-defined set of combinators. It is often annoying to have to test for different Request parameters in a controller action for MVC or on a page for WebForms. In this post I will describe what I’m calling StringToIQueryable, an open source parser library I built in a few days that I’m using on a few projects. Basically you feed a string to the parser and it manipulates an IQueryable according to a set of pre-defined combinators. The syntax is URL-friendly… that was the goal. Hopefully I will show you in this post how useful this tool can be for both consumption and extension. I figure I might as well tell you where the source is first. I decided to use GitHub for this project… so it is hosted on GitHub here. Download it and have at it!   MONADS MONADS MONADS! If Steve Ballmer were a functional programmer, he’d FOR SURE be screaming MONADS MONADS MONADS! I’ve discussed monads in the past (with a little less understanding than I have now :) ). Basically a parser (like what I’ve implemented) is like the IEnumerable monad in C#. There is a whole list of combinators you can use to define exactly what a parser does to arrive at a result. Intermediate results are stored as pairs of the parsed value and the string left to parse. I have defined a few simple combinators (I will talk about Or, When, and OrWhen specifically) that are useful. I’ve also defined some of the standard LINQ query operators… so you can easily use a parser as a LINQ query. As Erik Meijer says, “everything is a query!”.   Parser Internals The parser has really 2 important internals, a delegate and a storage container for the result and “rest” string. Here’s the code for each. // generic delegate for getting result/rest public delegate ParserResult Parse(string input); // class for holding the result and rest public sealed class ParserResult { public ParserResult(T parsed, string remaining) { Parsed = parsed; Remaining = remaining; } public T Parsed { get; private set; } public string Remaining { get; private set; } }   You’ll notice I’m using a generic… so you can pretty much parse anything here. The Parse delegate takes an input and returns a parser result. The parser’s job is to make sure everything is parsed correctly. This is in the ParserLib project of my source code.   The Combinators Combinators in functional programming are kind of an awesome thing. The main operators are bind and return. Bind is implemented with Select, SelectMany and Then. These are really the important operators, but Or, When, and OrWhen are what I find particularly useful when dealing with constraints and possibilities in my URL to IQueryable configuration. Or is a combinator that takes 2 Parse delegates. If the first should return null (indication of failure) then the result of the Parse will be the result of the second delegate. When is a unary parser (takes only 1 parser) and takes a string predicate. If the predicate is satisfied by the input, then the result will be delegated to the Parse instance. Otherwise the parser fails and null is returned. This is especially useful in my implementation of String to IQueryable because I associate a beginning keyword to a parser. OrWhen is a hybrid of Or and When that I built to mainly chain my parsers together. OrWhen takes a string predicate (like When) and 2 parsers (like Or). If the result isn’t null for the first parser, then that is the result. Otherwise the string is tested against the predicate and fails if the predicate fails or returns the result of the parse if the string predicate passes. If you download the code, you will see these defined in the ParserLib project. I’m not going to sho[...]

ClubStarterKit – Caching for performance

Fri, 11 Dec 2009 15:43:56 GMT

First of all, if you haven’t heard, I recently released ClubStarterKit v3 Preview. If you haven’t had a chance to look at it, I highly encourage you to take a look at the whole new codebase. My whole goal when building any application whether it’s an application for a client or the open source ClubStarterKit project is to make the app as fast as possible. There are quite a few layers to the caching mechanisms in CSK that I think could be applied to many other projects. In fact, some of the caching ideas came from an internal web framework we use at There are two “caches” that CSK uses. One is the HTTP Cache that IIS and other web servers use in the background. The other is the client’s web cache. I will give a brief overview of each in this post.   Web Cache The web cache is the simplest to understand of the two types of caches. When a request comes down from the web application, a response key is set on the server side that informs the browser to not look up the same file until a certain date. The trick we can do is to set the date as far as possible so the cache NEVER expires. (In CSK I think the cache is something like 5 years…). But what happens when you change your website? That’s where the application ID comes into play. At every application startup, an identifier is pushed in storage (we use HTTP Application) of a string-based token. In CSK the token is the DateTime of the insertion into the cache so that there are no other collisions. This token is appended onto every CSS file request, image request, and Javascript file request so that the client doesn’t have to wait every time a page is loaded for the same CSS, image and Javascript files to load into the browser when running a particular “application instance”. If, for some reason, the application ID is not passed to the request, then the response isn’t cached. When a part of your application changes, you have the ability to reset the application ID yourself. In CSK you just navigate to /sitecontent/reset and the application ID should be reset. The obvious advantage to this strategy is the reduction in unnecessary bandwidth. And users don’t have to wait for something to download that they already have on their computer. So there are some real benefits to using client-side caching of static files.   HTTP Cache Just like the web cache, the HTTP cache reduces unnecessary bandwidth. The center of the HTTP cache, however, is around the database. It can sometimes be costly to hit a database for the same query. To counteract this we use HTTP caches. These things store data onto the application server and store them for a certain amount of time until it has expired or is expired. A value can be expired by the application server, when the specified TimeSpan is reached or when the item is removed from the cache by the web application. In the CSK, an item is expired from the cache when something is added, such as a new article or a forum post. Once the item is pulled from the cache, the next request forces the cache to go to the database for the query result and store it in the cache. In the CSK we are also refreshing caches for every application id. This just ensures that there isn’t a leak in the caching mechanism and the data can be easily refreshed by a website owner. The rationale for this feature is that hitting the database is a lot more costly when you’re dealing with load. Memory cache is really cheap comparatively. So it just makes sense to “hold” the query results until they are expired by either the application’s usage or the refresh of the application ID. In the worst case, ASP.NET removes the item from the cache because of lack of storage. In that case the query is regenerated anyways. In the CSK there are a few abstractions that I will detail in later posts that are particularly useful[...]

ClubStartKit is Reborn… With a new release

Wed, 09 Dec 2009 06:07:00 GMT

The title says it all. That’s right, I’m back on ClubStarterKit. I’ve tried to assure the CSK community in past blog posts that it isn’t dead. In the last year, I’ve done a lot of thinking and outside programming. I’m FINALLY in a position where I have really progressed in terms of project management skill and web design. Many of the opinions I held when I started the project have simply changed. I’ll detail some of those in a minute. Here’s a link to the new release. Open source software is really tricky, especially for someone who has to go to school and keep up with the day job. It’s simply TOO MUCH for someone else to demand so much on a person. However, demanding open source work onto yourself is highly rewarding. That’s why I’m back. Why the time off? Well, I simply had to build my business. Ultimately, that takes a lot more priority over any other open source work. As harsh as that is, I simply had too much going on. Also, I was in a bit of a rut with CSK. The project started from a need by the community to extend the club starter kit originally started by Microsoft that shipped in the box as a starter kit with Visual Studio 2005. I found plenty of ways to extend the kit for myself and decided to share my extended version. It was a tool for beginners. My role was to share my knowledge of ASP.NET with everyone else. But there was a point where I was just copy and pasting and hacking the crap out of something that wasn’t mine and was written by a bunch of other people. I ripped a lot of things out, especially the data access. What I put in it’s place was a disaster as well, though. I simply didn’t have the forethought to imagine a site that was fully extensible. I simply put out something that was hacked and hacked and hacked. I didn’t put something out that EVERYONE could use, I put something out that EVERYONE had to figure out every little piece and extend. That’s simply irresponsible on my part. So I decided I needed to completely rewrite the thing. There was a point were I was sick and tired of writing VB. To me, it looks WAY too verbose. I couldn’t stand looking at it… and C# was my primary language at a point anyways, and still is. The big news Now I’m ready to come back. I finally have something that I put my stamp on. It’s MINE. I wrote it. There’s not a feeling in this world more satisfying for me than to say a piece of code is completely my creation. No hacks, no copy paste (ok, there’s a little… but at least I know what it does!) and certainly something I think everyone can use, whether it’s bits and pieces or the whole thing. What’s new! Well… for starters, it’s written entirely in C#! While I know some VB people are shivering in their boots, I plan on upgrading the web project to VB if there is an apparent need from the community. I’m not here to waste my time converting something to VB if there’s not a need. C# is such an expressive language and it’s something every VB dev should at least TRY to look at. More on that down the line. Another big new thing is that it runs ASP.NET MVC, not classic web forms. I know that there is some serious turmoil out there over this subject, but it really is a much better way to create web applications in ASP.NET in my opinion. There’s not very much of a difference, as it turns out. It’s a very comfortable shift… more than I thought it would be. It makes applications much easier to understand, write, and test.  I can entertain comments, questions, and concerns by email over this. I’m willing to fight for this :) But really, MVC rocks. It’s simply amazing. I know it hasn’t been released yet, but this release will be targeting Visual Studio 2010 and the .NET Framework 4.0. There’s a lot of really cool new ASP.NET features that I think CSK [...]

Fluent NHibernate with System.ComponentModel.DataAnnotations

Fri, 23 Oct 2009 20:34:00 GMT

So I’m building a product with NHibernate and possibly another ORM. The main focus of the app is a ASP.NET MVC 2.0 web application. So I, obviously, want the built in validation client-side in JavaScript and server side. By default, the MVC stuff uses the System.ComponentModel.DataAnnotations attributes to validate properties on your domain. What I REALLY wanted was to use the Data Annotations with Fluent NHibernate for my DB mapping files. This presents a problem, right? WRONG! Because Fluent NHibernate is so extensible, I can easily create a convention to use the Attributes. Then all I have to do is add the convention to my Fluent NHibernate AutoMapper instance and the properties with the attributes are just taken care of. Isn’t that neat!! Required is a common notion with domains. Something HAS to be defined for an entity to be considered a reputable entry. Here’s the convention to use the Required attribute in Fluent NHibernate.   Code Snippet using System.ComponentModel.DataAnnotations; using FluentNHibernate.Conventions; using FluentNHibernate.Conventions.Instances; namespace Data.NHibernate.Conventions {     public class RequiredConvention : AttributePropertyConvention     {         protected override void Apply(RequiredAttribute attribute, IPropertyInstance instance)         {             instance.Not.Nullable();         }     } }     As you can see… there’s really only 1 line of code!   I just showed you one out of the handful of attributes in the DataAnnotations library. To use the other attributes, you just basically follow the same basic outline of the example above. Not bad, eh :) [...]

ClubStarterKit - where do we go?

Wed, 30 Jul 2008 01:40:28 GMT

Wow, what a year. Not exactly what I'd expected. Before I dive into where we are now, let me preface this post by saying I have NOT forgotten ClubStarterKit! Although I was not the original author, I feel like it's my baby. I can't just forget about it. Not going to happen.   You might be quick to point out that I have done virtually nothing since the v3 beta 1 release. This, my friends, was a big mistake. Not v3 beta 1, which I will discuss later in this post, but the fact that I was not clear in what I hope to get out of the project. I do take the blame on the lack of development. I'm not going to sit here and tell you I have neglected to look at the code in a while. This is partially due to my work life (I have to make some money.. know that I have 2 jobs) and my personal endeavors (as I am a high school student with more to do than dedicate all my time to ClubStarterKit). No one is perfect. But I do sincerely apologize to the ClubStarterKit community for my lack of communication.   My hopes from the project When I started the project, I knew that there was a void. ClubStarterKit v1 was an obvious success because of the idea of sample-driven learning. It did a lot of things that people needed. Now, I really wanted to bring CSK to the level of open source. With this, I opened up the door for contributors. This is an area that I found fairly problematic. We did get some amazing contributions, such as the CMS and the RSVP system. Without these core contributions, I would have spent more time building the features rather than tracking down bugs or expanding other CSK features. Trust me, building out a feature for CSK is not easy. Essentially I had hoped for the ClubStarterKit to be a community effort where there would be multiple core developers. In my idea of "core developer", I seem to be the only one. To me, CSK seems more like a sample that goes through active development. It is my hope to not be a nag about this, but come on CSK community. You guys do some amazing stuff. Then you demand something out of CSK without contributing? I just don't see how this whole thing can work out like this. I'm not a free contractor. I don't even ask for donations! I have been asked by one member of the community to forget my role in CSK and pass it along to another developer. Guess what, no one stepped up. Interesting. Guess it looks like I'm still in, win or lose.   What's the deal with the inactivity? Like I said, there are many factors to this. Mostly, I am starting to regret hard-coding SubSonic into CSK. I now know, after completely hard-coding this stuff in, that I should have allowed external DALs that people wanted. Not everybody like SubSonic and it's query tool. Some people like NHibernate, LINQtoSQL, XML, whatever. I seriously screwed up. My fault, guys. I've learned, let's move on. A big reason for inactivity was time. I just couldn't devote a lot of time on CSK like I used to. Luckily, this is about to change for me. Just know that I'm going to have more time to work on CSK. Period.   What's next? I hate to say it, but v3 beta 1 was kind of bad. I really wanted something fresh. That just wasn't what we got with v3 beta 1. The ideas were there, just the delivery was poor. So this is what I plan on doing. What I want to do, and I would LOVE to hear feedback from you on this, is to completely scrap the current codebase and move over to the ASP.NET MVC framework. I am seriously in love with ASP.NET MVC. Honestly, it will move development, deployment, and testability along. I am in the preliminary planning stages. Also, for development, I would like to use C# and convert the C# code over to VB. The fact that the original kit was released in both languages made it all the more appealing. With a refreshed codebase, we can make this p[...]

Misuse of Delegates???

Mon, 26 May 2008 23:39:00 GMT

In the evolution of the ideas presented in Java, C# has provided the idea of method delegation and delegates, which I'm sure you are well aware of. In C# 3.0 with the introduction of the LINQ, Lambdas were born. With Lambdas, we are able to provide an easy and elegant way to declare delegates. With great power, however, comes great responsibility. Is there a way to overuse Lambdas and Delegates? Here is a sample of code I've written: /// /// If GZIP or DEFLATE compression is accepted/// by the user's browser, we will go ahead/// and compress the file upon the controller action/// /// Controller to invoke Compressionpublic static void Compress(this Controller controller){ string gzip = "gzip"; string deflate = "deflate";  //DELEGATES Func isAccepted = (encoding) => controller.Request.Headers["Accept-encoding"] != null && controller.Request.Headers["Accept-encoding"].Contains(encoding); Action setEncoding = (encoding) => controller.Response.AppendHeader("Content-encoding", encoding);  if (isAccepted.Invoke(gzip)) { controller.Response.Filter = new GZipStream(controller.Response.Filter, CompressionMode.Compress); setEncoding.Invoke(gzip); } else if (isAccepted.Invoke(deflate)) { controller.Response.Filter = new DeflateStream(controller.Response.Filter, CompressionMode.Compress); setEncoding.Invoke(deflate); }}   As you can see from the code, I use the .NET built-in delegates of Action and Func to do the setting of the encoding and the determination of the encoding, respectively.   So here is my question: Is this a misuse of delegates? Should I be putting the code into a separate private method? What are your thoughts?[...]


Sun, 27 Apr 2008 04:24:00 GMT

A month ago, I wrote about my technique to output a CSS sprite for ASP.NET. Granted, I made a big mistake. I put WAY too much bloat into the post. Not a K.I.S.S. moment. I have reworked my CSS sprite technique to be unique to MVC. I've used the most recent build of the MVC framework, which can be downloaded on Codeplex, to take advantage of ActionResult. What the ActionResult does is makes your controllers more testable and makes the execution of the controller more specific. Instead of a void, controllers now return an ActionResult (see Scott Guthrie's post on the interim release). I have a download, see the bottom of the post, that includes a sample application and a class library that you can distribute with any MVC application. The sample pulls 2 images off the Internet, plugs them into a sprite through the Sprite controller.   What you get when you execute the Sprite controller is a sprite that looks like so:   What you do in your CSS file is reference the sprite URL and specify the background-position, width, and height.   Then with the following HTML: you get the images separate from the sprite. What you get is an easy-to-use API for sprite generation and faster-loading website (less HTTP requests per page) using sprites instead of multiple images. If you want all of the CSS editing to happen at runtime, see my original post of CSS Sprites for that code. DOWNLOAD SAMPLE APPLICATION AND CODE[...]

Source Code conversion as part of a Build Process

Sat, 12 Apr 2008 04:10:20 GMT

If you're like me, you want a particular piece of code in your particular language. For example, a lot of people want the Club Starter Kit 2.0, 3.0 in C# since it has been written in VB. Me being the lazy open source developer that doesn't get paid :), I keep delaying the CSK conversion to C# because of my personal stuff. Then I was thinking, what if it were a part of the build process? Then I wouldn't have to go through the arbitrary process of converting a whole application to another language for a release that I will most likely be changing.


Before I go ahead and implement this myself, I was wondering if anyone out in the community has done this sort of thing before? I'm sure it wouldn't be that hard, what with the CruiseControl.NET API being what it is. I have already scoped out some ideas of how to implement. But I was wondering if anyone has ever built this plugin.


PLEASE leave a comment on the blog or email me (zowens2009 at gmail dot com)


THANKS COMMUNITY! I will make you proud if this isn't out there ;)

Coding Pet Peeves

Sun, 09 Mar 2008 19:32:40 GMT

Any experienced coder has pet peeves when it comes to reading other people's code or writing code. It might be that you don't like regions or that every method should have comments. But here are my two biggest pet peeves when it comes to C#.   Var abuse WAY too many people are using var instead of a type. This might save your hand, but it doesn't do much for readability of your code. Don't get me wrong, it is VERY usefully at times. But only about 10% of var use is actually productive. The rest is just abuse!   Angle Bracket Abuse Yes, we all know that C# has angle brackets, get over it :). If you have one statement inside of an if, while, do, for, foreach, or using, you DON'T NEED ANGLE BRACKETS! Take the following code sample I found in a starter kit for example: lock (SyncLock){ if (_cancelRequested == false) { _cancelRequested = true; if (_uploads != null) { foreach (FileUpload upload in _uploads) { upload.UploadAsyncCancel(); } } } } That same thing can be accomplished through this: lock (SyncLock){ if (_cancelRequested == false) { _cancelRequested = true; if (_uploads != null) foreach (FileUpload upload in _uploads) upload.UploadAsyncCancel(); } }   Isn't the second better to read? Plus this saves lines. For those of you who get paid by line, go ahead and put those in there, fine, but for those of you who don't, make your code more readable![...]

CSS Sprite for ASP.NET

Wed, 05 Mar 2008 12:32:00 GMT

CSS sprites are becoming popular as a way to increase application performance by eliminating HTTP requests by the client to the web server. It also serves as a path for better cache management. I will need to go through a bit of background before we start (sorry... we'll get to the generation in a second!).   What is a CSS Sprite? A CSS sprite is a fancy name for an image that is composed other images. In your CSS you have this one base image, but you pick the image inside of the image. It does what you expect, to just show that one single image. The following is an example of a CSS sprite:     In your CSS file, you would pick this base image as your background-image and then to pick a particular image, you could need to specify the height, width, and also the position of where the image starts... background-position. Long story short, it cuts down on the number of images that need to be passed from your server to the client that is visiting the site. This adds up over time, especially is you have A LOT of images. A lot of people go to a sprite generator online. Those are nice, but what happens when you need to change an image? You have to go back and re-upload all your images and recalculate your background-positions. That's not a good thing if you are following DRY (don't repeat yourself). Plus it's hard work NO ONE should have to do.   How I handle output caching What I do is this: all my CSS files, JavaScript files, etc have a common ID which is basically what I call the "Distro ID" which is generated at the beginning of my ASP.NET applications so every time you do a publish, the number will change and your files will also change to their updated content. The heavy lifting is all done in the Global.asax file. 1: //C# 2: public class Global : System.Web.HttpApplication { 3: public static string DistributionNumber { get; set; } 4:  5: protected void Application_Start(object sender, EventArgs e){ 6: SetDistro(); 7: .. 8: } 9: private void SetDistro() { 10: DistributionNumber = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString(); 11: } 12: } 1: 'VB 2: Inherits System.Web.HttpApplication 3:  4: Private m_distronum as String = String.Empty 5: Public Shared Property DistributionNumber() As String 6: Get 7: Return m_distronum 8: End Get 9: Set(ByVal value as String) 10: m_distronum = value 11: End Set 12: End Property 13:  14: Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) 15: SetDistro() 16: .. 17: End Sub 18: Private Sub SetDistro() 19: DistributionNumber = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() 20: End Sub   Now since I am mostly using ASP.NET MVC, I have a controller for the Distribution. So my URLs look like this: [BASE_URL]/20080303010101/CSS. I ago ahead and create separate Routes for this, but the default would also work. The ID that is passed to the CSS, JavaScript, Sprite is the distro number. To do the output caching, you need a separate ID so that the browser can differentiate one distribution's CSS, JS, etc from another. This way, we can client side cache with no worries. If you were using Web Forms, I would suggest using separate Generic handlers (one for CSS, JS, and the Sprite). They would accomplish the same thing. Just[...]

Improve ASP.NET Performance - CSSmin

Fri, 15 Feb 2008 06:15:00 GMT

If you follow Douglas Crockford's work, you might know about JSMin, a bit of code written for various languages to optimize JavaScript to make it smaller. One thing it does is makes everything go to one line, eliminating some of the space by removing white space. In Web 2.0 applications, CSS is all you have for styles. In most apps, the CSS can get large really quick. One way to improve your performance (of not only ASP.NET apps) is to minify your CSS. Various people have created this sort of functionality for you, but you aren't given the flexibility of doing the minification yourself. In my company's new website, part of the design decision was to always have an eye out for performance. To do this, we needed 1 CSS file and have it as small as possible. To do the "small as possible" part, we implemented a series of REGEX replacements that did all the work for minifying our CSS. Here's what we came up with:   C#:   1: public static string CompressCSS(string body) 2: { 3: body = Regex.Replace(body, "/\\*.+?\\*/", "", RegexOptions.Singleline); 4: body = body.Replace(" ", string.Empty); 5: body = body.Replace(Environment.NewLine + Environment.NewLine + Environment.NewLine, string.Empty); 6: body = body.Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine); 7: body = body.Replace(Environment.NewLine, string.Empty); 8: body = body.Replace("\\t", string.Empty); 9: body = body.Replace(" {", "{"); 10: body = body.Replace(" :", ":"); 11: body = body.Replace(": ", ":"); 12: body = body.Replace(", ", ","); 13: body = body.Replace("; ", ";"); 14: body = body.Replace(";}", "}"); 15: body = Regex.Replace(body, "/\\*[^\\*]*\\*+([^/\\*]*\\*+)*/", "$1"); 16: body = Regex.Replace(body, "(?<=[>])\\s{2,}(?=[<])|(?<=[>])\\s{2,}(?= )|(?<=&ndsp;)\\s{2,}(?=[<])", string.Empty); 17:  18: return body; 19: }     VB:   1: Public Shared Function CompressCSS(ByVal body As String) As String 2: body = Regex.Replace(body, "/\*.+?\*/", "", RegexOptions.Singleline) 3: body = body.Replace(" ", String.Empty) 4: body = body.Replace(Environment.NewLine + Environment.NewLine + Environment.NewLine, String.Empty) 5: body = body.Replace(Environment.NewLine + Environment.NewLine, Environment.NewLine) 6: body = body.Replace(Environment.NewLine, String.Empty) 7: body = body.Replace("\t", String.Empty) 8: body = body.Replace(" {", "{") 9: body = body.Replace(" :", ":") 10: body = body.Replace(": ", ":") 11: body = body.Replace(", ", ",") 12: body = body.Replace("; ", ";") 13: body = body.Replace(";}", "}") 14: body = Regex.Replace(body, "/\*[^\*]*\*+([^/\*]*\*+)*/", "$1") 15: body = Regex.Replace(body, "(?<=[>])\s{2,}(?=[<])|(?<=[>])\s{2,}(?= )|(?<=&ndsp;)\s{2,}(?=[<])", String.Empty) 16:  17: Return body 18: End Function   So you see it's just a few logical replacements. These few replacements makes a world of difference. The amount saved in bandwidth and caching is amazing. UPDATE: For those who asked, this is how I use this code. First what I do is enumerate through The files in my CSS directory. Here is my static method which I have in a static "Logic" class (more on that later): 1: public static IList GetFiles(string serverPath, string extention) 2: { 3: if (!serverPath.StartsWith("~/")) 4: { 5: if (serverPath.StartsWith("/")) 6: serverPath = "~" + serverPath; 7: else 8: [...]

Poll: JavaScript library for an eCommerce site?

Mon, 11 Feb 2008 04:01:08 GMT


Click Here to vote


Here are your options:

Ext (using jQuery as backend)
Ext (using YUI as backend)
Ext (using Ext base)


Happy voting!

Future of ClubStarterKit project

Tue, 22 Jan 2008 19:20:00 GMT

It's been almost a year since I started the ClubStarterKit project as an open source project up on Codeplex. Since then, we've released Version 2, which added functionality to the original starter kit, and the first Beta of Version 3, which tried to change the data architecture with SubSonic. The problem is that I've sort of abandoned the project for a while to work on my personal projects. But in that time, I've been really looking at better ways to put together the ClubStarterKit. This post is sort of a Version 3 feature list/roadmap that hopefully we can stick with!   The Data Layer We tried to do something cool by redoing the data by using SubSonic. In my eyes, this was only a partial success. The reason I chose SubSonic in the first-place was because the original app really was just a presentation of data, there wasn't really much that went on and from a programmer's perspective, there was a lot of logic just encapsulated in the SqlDataControl. Having inline SQL in a SQLDataControl is really unmanageable and can be a pain to update. With SubSonic, it's easy to update a data sequence to contain an additional field. What I want to do next is have a Data Provider. I realized that not everyone wants to use SubSonic. Some people want to use ADO.NET and I'm sure that some people want to use LINQ now that it is available. What I want to do is give people the option in the provider. The default will still be SubSonic, since I strongly reccomend it, but we will also natively support ADO.NET and LINQ and possibly anything else you guys might want us to support :)   Wiki I've wanted to build a wiki for quite some time. Our CMS does do some pretty cool stuff, which we will be building upon with the final release, but I also want to build a wiki for those clubs that need such functionality. I'll be evaluating some of the wiki stuff I want to put into the ClubStarterKit's wiki engine, but I definitely want it's functionality.   Photo Album I really want to revamp the Photo Album functionality. I really want to make it almost Flickr-like with commenting, tagging, etc. But I also want to add the functionality of a sweet photo-album with effects. I would love to add something like the Lightview since it's really amazing to look at :)   What about all the questions I have in the forums?! I know that I have fallen behind on my forum answering. For that, I TRUELY apologize. I do have a life, you know :) But there really isn't any excuse for not answering people's questions. In the next couple of weeks, I will be cleaning out the issue tracker, taking care of some things, and get those forum questions answered! There are WAY too important for me to just blow them off.   New Website? I am considering building a website for the project. Codeplex is GREAT, but there are some things I would really love to just make myself into a website. It would most-likely run off a modified version of the ClubStarterKit (which I WILL post for you guys to download) and will show off what a modified version could look like. More on that later.   If there are any question about the roadmap, the project, or feature requests, PLEASE LEAVE A COMMENT! If you have an urgent issue or you just want to talk with me one-on-one, email me ( I really want to start getting this rolling again as this starter kit should be on the cutting edge of ASP.NET design! Thanks to the community and the contributors of the project on your feedback and we hope to start getting your ideas and suggestions into the product![...]

TIP OF THE DAY : Override the tag in a webcontrol

Tue, 01 Jan 2008 20:11:00 GMT

For my New Years Resolution, I'm going to try and start blogging more both here and on my company blog. As a result, I'll most likely revert to these small babies -- Tip of the Day. Hopefully these posts can be short and sweet.   Here's the background on this one. I was writing a control that I needed to be the focus of a particular page. I really didn't like how the default base tag of the WebControl class (to write your own control in the assembly rather than use a UserControl) was a SPAN. I really wanted it to be a div. Turns out there is a property you can override in the WebControl class called TagKey.   Here's how you can override it for a div. 1: //C# 2:   3: protected override System.Web.UI.HtmlTextWriterTag TagKey{ 4: get { return HtmlTextWriterTag.Div; } 5: } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } 1: 'VB 2:   3: Protected Overloads Overrides ReadOnly Property TagKey() As System.Web.UI.HtmlTextWriterTag 4: Get 5: Return HtmlTextWriterTag.Div 6: End Get 7: End Property .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } The property type is of type System.Web.UI.HtmlTextWriterTag. So you can do other tags beside div and span. You can check that property out on this MSDN doc page.[...]