Code

RavenDB Management Studio and VMWare Fusion Workaround

0

I am a big advocate of RavenDB. I just love the software, and although it is not perfect, it is on a meteoric ride to getting there. The one nasty issue which plagues me as a VMWare Fusion user is the constant RavenDB management studio crashes. To be fair to the RavenDB team, this is not their fault. The problem lies in the network implementation for silverlight in VMWare fusion itself. You can feel the pain here in the official RavenDB google groups thread.

I am a man of solutions, and there are no excuses to getting your work done… well other than “it’s compiling”. So the easiest way to work around this for me is to allow access to my VM from my host OS. I’ll show you how to do that in a few simple steps.

1. Make sure your VM has its own local IP address

Screenshot_2_12_13_9_53_AM

 

Screenshot_2_12_13_9_54_AM

 

2. Next step is to add your RavenDB port to your VM’s Firewall

Screenshot_2_12_13_9_57_AM-2

 

You’ll want to add the default ports for RavenDB as inbound ports. This is usually 8080, but you want to make sure of this. I added both TCP and UDP just to be safe.

Screenshot_2_12_13_10_02_AM

3. Hit your ravendb studio from your host, and you should be good to go, with no annoying crashes.

Screenshot_2_12_13_10_06_AM

 

Hope you find this post helpful, and have fun developing with RavenDB.

Troubleshooting:

- Make sure RavenDB is running on your VM (duh).

 

Ducksboard for .NET

0

Screenshot_1_15_13_11_34_AM-2

 

A while ago I discovered a cool web service called Ducksboard. What Ducksboard does is allow you to develop a dashboard for your development team, business unit, or really anything. I personally always want to build a dashboard for my projects, but end up not doing it because it always comes as an after thought and I just don’t have the design skills to sit down and write the UI code and the infrastructure to pass data to my Dashboard. Ducksboard has all that figured out for you, all you need to do is call there API and push your data in, or if you are lazy they’ll even call your endpoint and pull data. If I had to say there was one downside to Ducksboard, then that would be the pricing. I still feel it is a little high for $29/month, which is more expensive then my current Azure web hosting at $9/month. I would like to see it lowered to $15/mo so more developers and convince their bosses that it is a good thing to pay for.

So we are .NET folks and want to use strongly typed objects so we can discover what is available to us right through the API. So I decided to write a wrapper library that exposes all the custom widgets that are available in the Ducksboard API. In addition, all the objects included in my library are serializable to JSON so you can use them for a pull api if you chose to do so. The pull API might likely be exposed through your ASP.NET MVC or HttpHandler.

Check it out at http://github.com/khalidabuhakmeh/ducksboard

or install it through Nuget :

Install-Package Ducksboard

Hope you find it as useful as I did. If you have a dashboard that is publicly available, I would love to see it and what others are doing with their dashboards.

Don’t Moq it Up

0

So today I was going through my regular google reader list and came up Hadi Hariri’s Blog post on how to use mocking to unit test your controllers. Here is the post. I was reading it and thought it was a great way to use Moq and the right way to use Moq. If you are using Moq, you should read that post.

I’ve realized like any other tool, you need to use Moq sparingly or else your unit tests will become hellishly difficult to manage. So how do I unit test today? I unit test by getting back to basics.

Virtual Is Your Friend!

I’m sure this isn’t big news to anybody, but protected virtual is the best way to unit test your code. If you start yelling at me about code smell then I implore you to look at any of the fancy ORM tools you are using. They all use virtual to sneak in dynamic proxies and do what I am about to show you.

So you have a controller / class that has some strange external dependency and you just need a single value from this dependency. You don’t want anything more than a string value. Let’s look at what we have below.

public class HomeController : Controller {
	public ActionResult Index() {
		var urlReferer = Request.UrlReferer;

		return View("Index", new { urlReferer =  });
	}
}

Oh jeez, what are we going to do about that Request object? We could use Moq and get into a mess, or we can look at what we are actually trying to do. We just want the UrlReferer. So let’s do that, we will just get that value. Time to refactor.

public class HomeController : Controller {
protected virtual string UrlReferer {
get { return Request.UrlReferer; }
}

public ActionResult Index() {
return View("Index", new { urlReferer = UrlReferer });
}
}

Notice we moved the UrlReferer into its own property and we reduced the size of our index method. Next step is to write our unit test. I Use XUnit, but you can use any framework you like since there is no dependency on any particular library.

public class HomeControllerTests {

	[Fact]
	public void Can_test_home_index() {
		var test = new TestHomeController() { TestUrlReferer = "http://www.google.com" };
		var value = test.Index();
		Assert.IsNotNull(value);
	}

	public class TestHomeController : HomeController {
		public string TestUrlReferer {get;set;}
		protected override string UrlReferer { get { return TestUrlReferer; } }
	}

}

We have to inherit from HomeController and create a TestHomeController class. We override the UrlReferer property to inject our test value. Our final step is to write our unit test without having to worry about a crazy mocking library getting in the way.

The nice thing about this method is you can use it for any external dependency and it will always work. It also keeps your tests clear and doesn’t add a lot of overhead to your original classes. So go forward and unit test, and don’t let mocking get in your way.

JQuery Validation Hooks – ASP.Net MVC

0

ASP.Net MVC comes with some great JQuery validation features, but sometimes you need just a little more to accomplish your task. I recently was trying to take advantage of Twitter Bootstrap’s error highlighting. If you have used JQuery validation in MVC, you’ll notice that it only marks the input that failed to validate, but doesn’t do much else. This is great for highlighting the field, but I needed to highlight the label, the helping text, and the input that I have present in my form.

I knew JQuery has a feature to let you bind to events, but I wondered if someone had already run into my particular situation. Surely someone had, and they created a great addition to ASP.Net MVC unobtrusive file that let’s you bind to different events. It’s called jQuery Validate Hooks.

The library let’s you:

  • Find out when our form’s client-side validation runs and do something custom, if it fails
  • Find out when a particular element’s client-side validation runs and do something custom if it passes or fails

Check it out it’s awesome.  jQuery Validate Hooks.

Ultimately my code to utilize this library looked like this:


$(function () {

     // Validation

     $('form').addTriggersToJqueryValidate().triggerElementValidationsOnFormValidation();

        $('form').formValidation(function (element, result) {

        $(element).find('input').each(function (index, value) {

            markControlGroup(value);

        });

    });

    $('form input').on('keyup', function () {

        markControlGroup(this);

    });

});

function markControlGroup(input) {

    var el = $(input);

    if (el.hasClass('input-validation-error')) {

        el.parents('div.control-group').addClass('error');

    } else {

        el.parents('div.control-group').removeClass('error');

    }

}

With the end result looking like this on my form.

Form Validation

That’s pretty cool, and the code above still leverages all the existing validation code that I have. I love JQuery and thanks to the author of this little script, because it is amazing. Also thanks to Twitter for Bootstrap.

Setting up ASP.Net MVC Error Pages

0

My focus as a developer is to give the end user the best application I can. With the focus being on feature development and quick turn around, sometimes bugs get through, even with an extensive suite of unit tests. I also have to be mindful that my set of users includes bots: Google, Bing, and yes Yahoo.

Bots are important in helping your site thrive in the ever growing market of the internet. It is important to communicate correctly to them. Think of them as your official ambassadors to your community of users. If the bots are confused, then they will not portray the correct information to the real live people you want using your site.

Error pages are important in communicating what is a page I want indexed, or what is a page that can be disregarded. Bots normally only show pages that return a 200 (OK) status in results pages. Other statuses do not show up regularly at the top of a search results page.

Question: How do I ensure that my ASP.Net MVC pages are returning the correct status code?

Answer: Setup, Setup, Setup.

There is nothing glamorous about this post, but it is fundamental to security and the overall health of my site’s public image.

Step 1: Web.Config

Config is tricky for several reasons, you want to cover the major errors, and you want the status code to be correct when the page displays your nice error page.


<customErrors mode="RemoteOnly" redirectMode="ResponseRewrite" defaultRedirect="~/Error/500">

<error statusCode="403" redirect="~/Error/403" />

<error statusCode="404" redirect="~/Error/404" />

</customErrors>

Note: For IIS7 users (which should be everyone now), remember to put this in the system.webServer section. This forces IIS7 to let your application handle errors. Without this you’ll get the ugly gray error screens that are par for IIS7.


<httpErrors existingResponse="PassThrough" />

The thing to take away from the configuration above is that the redirectMode is set to ResponseRewrite. This insures that when a page errors on /hello/kitty, it stays on /hello/kitty. This tells the user that this page is borked, and also any bot that might have traveled their. The redirects are pointing to an error controller, but before we get to the controller let’s look at how the routes are set up.

Step 2: Route Setup

Routes are very important, I cannot stress this enough. If you are using the default route setup that comes with Asp.Net MVC then DON’T!!! The default catch all is terrible for many reasons, but the biggest reason is that it will catch urls that have no relevance in the application itself. This will confuse search engines, and ultimately users who see those crazy results in the search engine results.

After meticulously crafting your routes, you will need these two additional routes.


routes.MapRoute(

"Error",

"Error/{status}",

new { controller = "Error", action = "Index", status = UrlParameter.Optional }

);

routes.MapRoute(

"404",

"{*url}",

new { controller = "Error", action = "Index", status = 404 }  // 404s

);

The first route should be familiar looking. It is what will catch the redirects from the configuration. The second route is a catch all. Yes I just admonished you for having a catch all route, but this one is different. We have a catch all for mistakes. Think of it as a safety net for a trapeze artist. It is important to have specifically defined you routes for this to work. The next step is create the controller.

Step 3: The Error Controller


public class ErrorController : Controller

{

public ActionResult Index(int? status)

{

var codes = Enum.GetValues(typeof (HttpStatusCode)).Cast<int>();

var httpCode = status.HasValue

? (int?)codes.FirstOrDefault(c => c == status.Value) ?? 500

: 500;

// insure response is the right code

Response.StatusCode = httpCode;

switch (httpCode) {

case 404:

ViewBag.Message = "The page you were looking for could not be found.";

break;

default:

ViewBag.Message = "An error occurred while processing your request.";

break;

}

return View("Error");

}

}

The thing to note here is the Response.StatusCode being set. It will ensure when you page is rendered that the resulting response is correctly tagged. Now you can craft a beautiful Error view and drop it in Shared or in the Error views folder. I usually drop mine in Shared.

Conclusion

 

Error pages are very important to get right, they communicate to your users and search engines that what they are currently looking at is a mistake and to ignore it. Hopefully they never see those pages, but when they do, they know that you are hard at work fixing the issue that caused them to see it in the first place.

 

Stay Code Thirsty My Friends.

Restful Routing – Documentation Site

0

As a developer I always love finding projects that make my life easier. As a web developer I spend most of my time using ASP.Net MVC to do my development. If you’ve spent any time in an MVC framework, you know how cumbersome it can be to manage routes. With Restful Routing the thought and effort behind building your application’s routes is already done for you.

I’ve always loved Restful Routing and I am an active contributor to the project. This post is to try to get other developers excited about using this library.

The new documentation site was built using ASP.Net MVC 3 and RestfulRouting. It is a living guide of how to use the library to accomplish the different scenarios it affords.

Check it out @ RestfulRouting.com

Must Have NuGet Packages

2

I am loving NuGet, and as it matures it just becomes more of a paradigm shift. How do you program without this thing? What was development like before it? So what are NuGet packages I am usually including in my projects. Here is a list of the them below, in no particular order.

  • Depot (Common Caching)
  • Dynamic Expression API (LINQ Extensions)
  • ELMAH on XML (Error Logging)
  • FileDB (a leap in storing files)
  • SimpleMembership
  • ValueInjecter
  • WebActivator
  • RhinoETL
  • FluentMigrator
  • RestfulRouting
  • JQuery
  • FluentValidation
  • Entity Framework Code First
  • NUnit
  • Moq
  • WaTin
  • RestSharp
  • MvcFlash (yes I am bias :P )

Great respect goes out to these projects and their contributors, except MvcFlash cause I don’t want to strain my arm patting myself on the back :P .

Update: How could I forget about MvcMailer.

How to Increase Decimal Precision in Entity Framework

1

So you are saving your decimal values to the database, but you are noticing that they are being rounded. Not what you want, because you want to be as close as you can be. If you are using entity framework you just need to add this little snippet to your OnModelCreating method in your DataContext.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
           modelBuilder.Entity<Address>()
                .Property(m => m.Latitude)
                .HasPrecision(19, 5);

            modelBuilder.Entity<Address>()
                .Property(m => m.Longitude)
                .HasPrecision(19, 5);
        }

The example above makes sure that my latitude and longitude at least have a precision of 5. Make sure you database reflects this precision.

Capitalize First Letter of Every Word (C#)

5

I hate non uniform data, I really do. It’s one of those things that a client will enter into the system a thousand times incorrectly with no rhyme or reason. It is also followed by the eventual, can you fix these million records so they are correct. Ugh! What?!? Ok, so you can fix it in your database or create code at display time to fix it. I always opt for the second, since you can’t trust your users to stop doing what they have been doing. So here is code to nicely display peoples names, cities, or whatever needs to the first letter capitalized.

 public static string CapitalizeFirst(this string input)
        {
            if (string.IsNullOrEmpty(input)) {
                return input;
            }

           var words = input.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries);
           var result = words.Select(w => w[0].ToString().ToUpper() + w.ToLower().Remove(0, 1)).Aggregate((s,w) => s + ' ' + w );
           return result.Trim();
        }

Not rocket science, I know but still equally helpful.

LamdaComparer – A Must Have Snippet

1

I found this blog post about LambdaComparer and it is a must have snippet if you are doing anything with LINQ. Check it out http://brendan.enrick.com/post/linq-your-collections-with-iequalitycomparer-and-lambda-expressions.aspx

Go to Top