Make IIS Express works with http://127.0.0.1

I never notice that IIS Express doesn’t listen to web requests other than localhost. So, to my surprise, when I try http://127.0.0.1, I got HTTP 400, Bad Request instead.

 

127.0.0.1-Error

 

Change 127.0.0.1 to localhost and everything is fine.

localhost

 

Anyway, you can set your IIS Express to let it listen to a request for 127.0.0.1 easily.

1. Look for a file applicationhost.config. It’d be under /documents/IISExpress/config.

2. Go to <sites> section and look for your site. In this example, I have my web project named MyWeb.

iis-express-setting-before

3. Change localhost to 127.0.0.1

iis-express-setting-after

4. Stop IIS Express and run your web site again.

exit-iis-express

 

Now you should be able to access your web site thru 127.0.0.1 address now!

127.0.0.1-work

 

Hope this helps! 🙂

Advertisements

IE8 Object doesn’t support property or method ‘map’

One function that I used very frequently in Functional Programming language like F# is map. For C# I can use Select function in LINQ to do the same thing. With ECMAScript5, JavaScript also comes with built-in map function.

Here are how map functions looks like in JavaScript:

var sqrt = function(x){ return x*x;};
var numbers = [1,2,3];
var squares = numbers.map(sqrt);
// squares is [1,4,9]

However, if you still have to support IE8, unfortunately, it doesn’t support map function.

To make IE8 supports the map function, you can add a Polyfill that you can find on this page. Or if you use either jQuery or Lo-Dash, you can use jQuery.map or _.map as well.

// jQuery
var squares = jQuery.map(numbers, sqrt);

// Lo-Dash
var squares = _.map(numbers, sqrt);

Create a super-duper-happy SPA web app using Durandal, Nancy, and Bootstrap

I start looking at Durandal after attending Jason Clark’s DurandalJS and Twitter Bootstrap at Nashville .NET User Group. Durandal is a SPA framework that incorporated several popular JavaScript libraries like JQuery, Knockout, and RequireJs. It’s also created by Rob Eisenberg who is also behind Caliburn.Micro.

For Nancy, I have heard about it in .NET Rocks and Hanselminutes podcasts for a while, but I haven’t had a chance to look at it until recently. Basically, Nancy (or NancyFX) is a lightweight web framework allowing you to build HTTP based web applications or services using .NET. Nancy is very easy to learn and set up.However, It doesn’t depend on System.Web and doesn’t need to be run on IIS at all. Most importantly, Nancy is very easy to learn and set up as you will see.

The last one is Bootstrap which is a very popular front-end framework that comes with HTML/CSS/JavaScript templates and controls. It allows us to create better-looking responsive web UI with small effort.

Using them together makes our job to create a web app much easier.

 

Ok. Enough with the background. Let’s get start by building a web app using Durandal and Nancy (I will touch on Bootstrap once we have a web app running).

First, we start with just an empty ASP.NET web site.

 

001-Empty-Web-Project

002-Empty-Web-Project 

 

Once we have the web site project, we install Durandal and Nancy via NuGet. Since I want our web app to run on IIS, I also have another package, Nancy.Hosting.Aspnet installed.

image

 

If everything went smoothly, you should see these packages installed in your project. As Durandal is using JQuery, Knockout, and RequreJS, those packages will be installed as well.

004-NuGet-Packages

 

Now, let’s start coding. We start in the client-side by creating modules (viewmodels) and views. If you have played with the Durandal StarterKit, you should be familiar with the files (index.html, main.js, shell.js, etc.). I won’t explain what those files do here, but you can find more information about them here.

Next, we look at the server-side with Nancy. To set up a Nancy site, what I need to do is to create a C# class derived from NancyModule, and define route handler in the constructor. We don’t need to worry about the name. As long as it is derive from NancyModule, Nancy will find it. Here is how I want Nancy to return back index.html for the root URL.

 

 

By default, Nancy will look at static content like JavaScript files, css, images, and so on in /Content folder only. But we already have those static files that Durandal needs in App folder. So to make Durandal works, we need to tell Nancy to look at those folders as well by adding those folders to StaticContentsConventions which can be done in Nancy Bootstrap process. We can do that by creating a class derived from DefaultNancyBootstrapper and add some code.

 

 

Here is how our project looks right now.

005-EDT-Minimum-Final

 

Now, let’s run the web app. And you should see our very simple web app

image 

To make our web app a bit less trivia, I will add another Durandal view and module which will do some AJAX call to get JSON data from the server. Here is the code in the new module.

 

 

The page is expecting the server to send JSON when it hits /api/list. With Nancy, we can do that easily by adding just couple lines of code.

 

 

Now. let’s run our web app again and click the new link!

image

Wow! super easy, right?

 

So far, we just have our client-side and server-side code taken care. However, you probably notice that our web app doesn’t look good at all. This is how Bootstrap can help. By using its reusable CSS templates, we can make our web app looks much better with ease.

Before we can do that we have to install Bootstrap package.

image

 

Next, we bootstrapify our pages by adding Bootstrap CSS class to HTML elements in our Durandal views. Besides reusable JavaScript/CSS components, there are many things that Bootstrap can help, most notably, the grid layout system.

image

 

Let’s run our web app again.

image

 

That’s it. Using Durandal, Nancy, and Bootstrap, we have a super-duper-happy SPA web app done right! 🙂

 

For the full source code, please see my github repo. I have each step in git branches as well. If you want to see the site in action, I also set up the Windows Azure web site here,

Happy coding!

Create and Run ASP.NET MVC project with Durandal Starter Kit on Visual Studio 2013

If you’d like to support the Durandal project, please back their Kickstarter project

With Visual Studio 2013 One ASP.NET Web Project, I couldn’t find a way to choose Durandal SPA Template directly even after I install the VSIX file. The easiest way is to create an empty MVC project and install the entire starter kit via NuGet.

Here is how:

1. First we create an empty MVC web project.

CreateWebProject

EmptyMVC

2. Run Install-Package Durandal.StarterKit from the Package Manager Console (i.e., NuGet console).

InstallNuGetPackage

3. Durandal NuGet package comes with DurandalController as a default controller, so you have to change the default controller in App_Start/RouteConfig.cs from “Home” to “Durandal”

RouteConfig

4. Now you should be able to build and run the starterkit.

RunDurandal

Happy coding!

How to : Kendo UI Grid for ASP.NET MVC

Customize the Filter menu items:

Grid Helpers:

@(Html.Kendo().Grid(Model)
    .Name("People")
    .Columns(cols =>
    {
		...
		cols.Bound(m => m.ResidenceState)
			.Title("State")...
			.Filterable(filter =>
			{
				filter.UI("statesFilter");
				filter.Operators(f => f.ForString(o =>
				{
					o.Clear();
					o.IsEqualTo("Is Equal To");
					o.IsNotEqualTo("Is Not Equal To");
				}));
	        });
    ...
    })
)

JavaScript:

function statesFilter(element)
{
   element.kendoDropDownList({
   dataSource:
   {
       data: @(Html.Raw(Json.Encode(ViewData["States"])))
   }});
}

Controller:

public ActionResult Index()
{
    ViewData["States"] = SamplePeople.States;
    return View();
}

With this set up my filter menu shows only “Is Equal To” and “Not Equal To.” My filter menu will also use our state filter UI.

image

Column ClientTemplate:
Grid Helpers:

@(Html.Kendo().Grid(Model)
	.Name("People")
	.Columns(cols =>
	{
		...
		cols.Bound(m => m.ResidenceState)
		.Title("State")
		.ClientTemplate("#=getStatesTemplate(ResidenceState)#")
		...
	})
	...
)

JavaScript:

function getStatesTemplate(state)
{
	switch(state)
	{
		case "California":
		case "Washington":
		case "Tennessee":
		case "Oregon":
		case "Texas":
			return "<b>"+state+"</b>";
		default: return state;
	}
}

California and other states are shown in bold.

image

Customized EditorTemplate:
Grid Helpers:

@(Html.Kendo().Grid(Model)
	.Name("People")
	.Columns(cols =>
	{
		...
		cols.Bound(m => m.ResidenceState)
			.Title("State")
			...
			.EditorTemplateName("StateEditor")
			.Filterable(filter =>
			{
				filter.UI("statesFilter");
				filter.Operators(f => f.ForString(o =>
				{
					o.Clear();
					o.IsEqualTo("Is Equal To");
					o.IsNotEqualTo("Is Not Equal To");
				}));
			});
		...
	})
	...
)

EditorTemplate (Views/Shared/EditorTemplate/StateEditor.cshtml):

@(Html.Kendo().DropDownList()
   .Name("States")
   .BindTo(((System.Collections.IEnumerable)ViewData["States"]) )
)

When I click “edit”, I will get the drop-down list of states.

image

Upgrade TypeScript project from 0.8.0 to version 0.8.1.1

If you created a TypeScript HTML project in Visual Studio 2012 using the old version (e.g., 0.8.0 which is the first preview release) and later you upgraded TypeScript to version 0.8.1.1, you would get this compile error like this.

Error    1    The command “C:\Program Files (x86)\Microsoft SDKs\TypeScript.8.0.0\tsc” …exited with code 3.

Although it is better to just recreate your project using a newer version of TypeScript, you could just modify the csproj file by right-click at the project to unload and edit the file in text mode.

image

image

The TypeScript HTML project template in the 0.8.0 version just adds a “BeforeBuild” target and hard-coded the path to the TypeScript compiler. You should see the target element at the bottom of the file.

  <Target Name="BeforeBuild">
    <Exec Command="&quot;$(PROGRAMFILES)\Microsoft SDKs\TypeScript\0.8.0.0\tsc&quot; @(TypeScriptCompile ->'&quot;%(fullpath)&quot;', ' ')" />
  </Target>

So what you need to do is to change “0.8.0.0” to “0.8.1.1” and everything should work.

However, I would recommend you to recreate your project using the new version, so you could also debug your TypeScript code as well as getting rid of hard-coded version in the project file altogether (the project file generated by 0.8.1.1 is quite different from what 0.8.0 generates).

C# String.format in JavaScript

As a mainly C# developer who has to work on JavaScript more and more, I do miss the string.format method that I do use very often (like when C++ guys misses the sprintf when they do C# Winking smile ).

I found someone re-implement string.format in JavaScript here.

String.format = function () {
	var s = arguments[0];
	for (var i = 0; i < arguments.length - 1; i++) {
		var reg = new RegExp("\\{" + i + "\\}", "gm");
		s = s.replace(reg, arguments[i + 1]);
	}
	return s;
}

You can find my jsfiddle exmple here. Enjoy coding!