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<RequiredAttribute>
    {
        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 :)



kick it on DotNetKicks.com

Functional programming isn’t a new concept. There is Scheme, Haskell and a bunch of other really cool languages. But new on the block is F#. F# is Microsoft’s stab at creating a functional programming in the .NET world as a first-class language.

Functional programming paradigms are increasingly important to all .NET developers. This post will detail the functional elements (in my mind) of the Maybe Monad, something I’m sure everyone has written in some way or another (ok maybe not everyone, but there are certainly a lot of implementations out there in C#). But let’s discuss the application, functionally, of the maybe monad.

 

The Basics

There are three areas of the maybe monad that are really important. The first is the concept of “Nothing” and “Just”. Nothing, in this context, would be either a failed operation (say division by 0, for example) or something that just returns null. The “Just” is the opposite of “Nothing”, it’s something. It’s a successful operation that returns a value. Although this concept seems simple, it’s actually quite powerful. We’ll return to this in a bit.

The second of the important concepts with the maybe monad is the “bind” and “return” verbs. “Bind” is the assigning of a value to a Maybe. “Return” the extraction of the value from the maybe. See the Maybe Monad is a container of a value (or lack thereof). The verbs attached to the container relay a façade of the actual value. While my implementation doesn’t deal with bind/return verbs directly, it is used indirectly with the composition and decomposition of the value container.

The third is something we’re ALL familiar with, a type constraint. The formal declaration of the maybe monad declares that there must be a type parameter of type M. This letter is arbitrary, of course, but the concept is important. Without the constraint, the possible values of the true value bound to the maybe container would be limitless. One more reason where generics in C# are invaluable!

 

Let’s get coding!

Start with Nothing

Let’s start out with some initial xUnit.net tests.

[Fact]
public void Maybe_NothingContructor_SetsNothingFlag()
{
var maybe = new Maybe<int>();
bool isNothing = maybe.Nothing;
Assert.True(isNothing);
}

[Fact]
void Maybe_JustContructor_DoesntSetNothingFlag()
{
var maybe = new Maybe<int>(5);
bool isNothing = maybe.Nothing;
Assert.False(isNothing);
}

[Fact]
public void Maybe_JustContructor_SetsNothingFlag_WhenTheValuePassedIsNull()
{
var maybe = new Maybe<int>();
bool isNothing = maybe.Nothing;
Assert.True(isNothing);
}

As you can see there are 2 constructors. The default is the “nothing” constructor. The constructor with a value is the “nothing” if the value is null and the “just” if there is an actual value. This is an immutable container, so I don’t feel so bad setting these values only in the constructor. Here’s what my “Maybe” looks like now.

/// <summary>
/// Value container for storing
/// a) a value ("Just")
/// b) lack of a value ("Nothing")
/// </summary>
/// <typeparam name="M">Type M of the Maybe Monad</typeparam>
public sealed class Maybe<M>
{

/// <summary>
/// Non-value maybe ("Nothing")
/// </summary>
public Maybe()
{
// assign the nothing flag
Nothing = true;
}

/// <summary>
/// Maybe with a value ("Just")
/// </summary>
/// <param name="value"></param>
public Maybe(M value)
{
// assign the nothing flag
// when not null
Nothing = value == null;
}

/// <summary>
/// Determines the state of the
/// value in the container
/// </summary>
public bool Nothing { get; private set; }
}

 

You might be wondering why I made this class sealed. My rationale for this is that, since Maybe is immutable, we don’t want to get rid of some of the guarantees we have with the default implementation. Having a central “maybe” is a nice, simple way to define the maybe behavior.

Now for the return

The notion of a return for the maybe monad essentially means extracting the value from the container. I could define a “Return” function or even a “Value” property. But this is an unnecessary step. We don’t really need added complexity. My theory is that casting would be the best option. It is, after all, just a façade. Plus casting is a bit more expressive anyways. In your implementation, you can do this if you wish :)

[Fact]
public void Maybe_MCast_ReturnsAValue_WhenThereIsAValue()
{
var maybe = new Maybe<string>("");
string value = maybe;
Assert.NotNull(value);
}

[Fact]
public void Maybe_MCast_ReturnsSameValue_WhenThereIsAValue()
{
var initialValue = "";
var maybe = new Maybe<string>(initialValue);
string value = maybe;
Assert.Same(initialValue, value);
}

[Fact]
public void Maybe_MCast_ReturnsNull_WhenThereIsNotAValue()
{
var maybe = new Maybe<string>();
string value = maybe;
Assert.Null(value);
}

And here is the code that makes the tests pass.

public sealed class Maybe<M>
{
private M _value;

...
// previous code hidden for brevity

public static implicit operator M(Maybe<M> maybe)
{
if (maybe == null)
throw new ArgumentNullException("maybe");

return maybe._value;
}
}

I added the value field and the implicit cast operator.

Another way to bind

The constructor to define the “Just” and “Nothing” is useful, but what if we wanted save a little code when we are returning a maybe from a method? To do that, we’ll define another implicit operator. This time the operator will take an M and return a Maybe<M>. Here’s our test:

[Fact]
public void Maybe_MaybeCast_ReturnsNothingMaybe_WhenTheValueIsNull()
{
string val = null;
Maybe<string> maybe = val;
Assert.True(maybe.Nothing);
}

[Fact]
public void Maybe_MaybeCast_ReturnsJustMaybe_WhenTheValueIsNotNull()
{
string val = "";
Maybe<string> maybe = val;
Assert.False(maybe.Nothing);
}

And here’s the code.

public sealed class Maybe<M>
{
...
// previous code hidden for brevity

public static implicit operator Maybe<M>(M value)
{
return new Maybe<M>(value);
}
}

 

Apply for Chainability

Being able to chain different functions is really a key part of the maybe monad. The verb I will use is “Apply”. In functional languages, this action just happens due to function composition. We have two options here. We can return the Maybe monad as a Func<Maybe<M>, Maybe<M>> or we can define an Apply method to take a Func<Maybe<M>, Maybe<M2>> where M2 is essentially a new value. The Apply method could serve as a converter. If the initial value of M is Nothing, then the converted value should return a Nothing maybe monad. The great thing about the maybe monad is that there is no need to throw exceptions.Although the throwing of exceptions can provide useful information, most simple operations don’t require such complexity. Just test for Nothing on the maybe. Now you don't have to add a try/catch throughout your code.

I am going to use the Apply method. Although returning a Func<Maybe<M>, Maybe<M>> might add expressive syntax, the Apply method will be a little more flexible for most scenarios. Here’s some tests.

[Fact]
public void Maybe_Apply_ReturnsNothingMonad_WhenTheInitialNothingMaybe()
{
Func<Maybe<string>, Maybe<string>> fun= (m) => new Maybe<string>("");
Maybe<string> initialMaybe = new Maybe<string>();
Maybe<string> appliedMaybe = initialMaybe.Apply(fun);
Assert.True(appliedMaybe.Nothing);
}

[Fact]
public void Maybe_Apply_ReturnsNewMaybeWithNewValue()
{
Func<Maybe<string>, Maybe<string>> addBchar = (maybe) =>
new Maybe<string>(((string)maybe) + "b");

string initial = "", final = "b";

Maybe<string> initialMaybe = new Maybe<string>(initial);
string afterApply = initialMaybe.Apply(addBchar);
Assert.Equal(final, afterApply);
}

As you can see, my implementation will automatically return a nothing maybe monad when a nothing maybe monad is the initial value. OK here’s the code.

 /// <summary>
/// Applies the specified function to this object
/// if this maybe is not nothing
/// </summary>
/// <typeparam name="M2">Return Type</typeparam>
/// <param name="applyFunction">Conversion function</param>
/// <returns>A Nothing maybe if the initial maybe is nothing
/// or the value returned by <see cref="applyFunction"/> if
/// this maybe has a value.
/// </returns>
public Maybe<M2> Apply<M2>(Func<Maybe<M>, Maybe<M2>> applyFunction)
{
if (Nothing)
return new Maybe<M2>();
return applyFunction(this);
}

 

Conclusion

The maybe monad is pretty cool for writing structure C# code. Your methods can now return a Maybe<M> to be perfectly clear if your methods returned actual values or null. This also gives you another definition of null. Perhaps your idea of “null” could be returning a 0. We have added flexibility with this new construct.

I’ve just hit the high marks in this post of my implementation of the maybe monad. Here’s an extended version with tests. Enjoy :)

 

DOWNLOAD




kick it on DotNetKicks.com

I'm in the middle of a project and I wrote my own Cache logic that melds nicely to my project's needs. But how do I test it? I can't mock the System.Web.Caching.Cache class. So I looked in the Abstractions that ship with ASP.NET MVC. What do you know, they're not there!

So I created my own base class and wrapper. Here's the code. Enjoy.

 

using System;
using System.Collections;
using System.Web.Caching;

namespace WebCommon.Abstractions
{
    public abstract class CacheBase : IEnumerable
    {
        public abstract int Count { get; }
        public abstract long EffectivePercentagePhysicalMemoryLimit { get; }
        public abstract long EffectivePrivateBytesLimit { get; }
        public abstract object this[string key] { get; set; }
        public abstract object Add(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback);
        public abstract object Get(string key);
        public abstract IDictionaryEnumerator GetEnumerator();
        public abstract void Insert(string key, object value);
        public abstract void Insert(string key, object value, CacheDependency dependencies);
        public abstract void Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration);
        public abstract void Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback);
        public abstract object Remove(string key);

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
    }
}

using System;
using System.Collections;
using System.Web.Caching;

namespace WebCommon.Abstractions
{
    public class CacheWrapper : CacheBase
    {
        private Cache _cache;

        public CacheWrapper(Cache cache)
        {
            _cache = cache;
        }

        public override int Count
        {
            get { return _cache.Count; }
        }

        public override long EffectivePercentagePhysicalMemoryLimit
        {
            get { return _cache.EffectivePercentagePhysicalMemoryLimit; }
        }

        public override long EffectivePrivateBytesLimit
        {
            get { return _cache.EffectivePrivateBytesLimit; }
        }

        public override object this[string key]
        {
            get
            {
                return _cache[key];
            }
            set
            {
                _cache[key] = value;
            }
        }

        public override object Add(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback)
        {
            return _cache.Add(key, value, dependencies, absoluteExpiration, slidingExpiration, priority, onRemoveCallback);
        }

        public override object Get(string key)
        {
            return _cache.Get(key);
        }

        public override IDictionaryEnumerator GetEnumerator()
        {
            return _cache.GetEnumerator();
        }

        public override void Insert(string key, object value)
        {
            _cache.Insert(key, value);
        }

        public override void Insert(string key, object value, CacheDependency dependencies)
        {
            _cache.Insert(key, value, dependencies);
        }

        public override void Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration)
        {
            _cache.Insert(key, value, dependencies, absoluteExpiration, slidingExpiration);
        }

        public override void Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback)
        {
            _cache.Insert(key, value, dependencies, absoluteExpiration, slidingExpiration, priority, onRemoveCallback);
        }

        public override object Remove(string key)
        {
            return _cache.Remove(key);
        }
    }
}

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 process much easier on the person converting (probably me :) ).

Also, we will have an extensive service layer that can be extended to use a custom DAL or any form of data storage.

Lastly, the features listed in my last post will go in.

 

So, what do you think? I would LOVE to hear your feedback AS LONG AS IT IS PRODUCTIVE AND WILL BENEFIT THE PROJECT.

 

THANKS FOR YOUR CONTINUED UNDERSTADING CLUBSTARTERKIT COMMUNITY!

Thought I'd post a quick extension method that I made today. Hope it helps someone.

 

public static string RemoveWhitespace(this string str)
{
    try
    {
        return new Regex(@"\s*").Replace(str, string.Empty);
    }
    catch (Exception)
    {
        return str;
    }
}

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:

/// <summary>
/// If GZIP or DEFLATE compression is accepted
/// by the user's browser, we will go ahead
/// and compress the file upon the controller action
/// </summary>
/// <param name="controller">Controller to invoke Compression</param>
public static void Compress(this Controller controller)
{
    string gzip = "gzip";
    string deflate = "deflate";
 
    //DELEGATES
    Func<string, bool> isAccepted = (encoding) => controller.Request.Headers["Accept-encoding"] != null && controller.Request.Headers["Accept-encoding"].Contains(encoding);
    Action<string> 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?

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.

image

 

What you get when you execute the Sprite controller is a sprite that looks like so:

image

 

What you do in your CSS file is reference the sprite URL and specify the background-position, width, and height.

image

 

Then with the following HTML:

image

you get the images separate from the sprite.

image

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




kick it on DotNetKicks.com

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 ;)

As long as I'm on the coding conventions track (as many of users have commented on my last post), I'll talk about a small coding convention I am trying to do.

 

I feel more compelled to push an interface into a property, method, or any declaration rather than an object type. Why push around List<string> when you can push around IList<string>? It seems like a much better design decision. It also seems that there is more flexibility as far as future extensions are concerned.

 

Come on, let's hear those thoughts :)

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!

More Posts Next page »