Friday, September 4, 2015

VS Code: Multiple build tasks with multiple solutions

There are multiple solution files in the same folder in our current solution.
You can find the tasks.json file below to build these solutions separately.
You can run the task by

  1. pressing CTRL+SHIFT+P
  2. selecting Run Task
  3. choosing the appropriate option

Monday, June 15, 2015

MVC6 SecretManager

I tried to install ASP.NET MVC6 Secret Manager package with DNVM  1.0.0-beta4. It failed with:
Unable to locate SecretManager >= 1.0.0-beta4-10173
There is an easy fix: you can remove the last part of the version identifier.

  1. Open project.json file
  2. Change version to 
 "dependencies": {
    "SecretManager": "1.0.0-beta4-*"
  },
Files to be changed:
Package path:%UserProfile%\.dnx\packages\SecretManager\1.0.0-beta4\app\project.json
Cache path:%UserProfile%\.dnx\bin\packages\SecretManager\1.0.0-beta4\app\project.json

Wednesday, June 10, 2015

RouteValueDictionary

I got an error recently when I enable DonutCache donutHole-based caching for a RenderAction:
Type 'System.String[]' with data contract name 'ArrayOfstring:http://schemas.microsoft.com/2003/10/Serialization/Arrays' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
It seems RouteValueDictionary cannot manage IEnumerable or String[] as a parameter. The solution is simple, it's a well-known issue:
http://stackoverflow.com/questions/19960420/adding-array-of-complex-types-to-routevaluedictionary

So this is how you can use the extension method:
Html.RenderAction(
                             ActionName,
                             ControllerName,
                             new RouteValueDictionary(new 
                             {      usual properties here }));


Thursday, May 15, 2014

Partial apply in C#

Partial apply by Wikipedia:

In computer science, partial application (or partial function application) refers to the process of fixing a number of arguments to a function, producing another function of smaller arity. Given a function \scriptstyle f \colon (X \times Y \times Z) \to N , we might fix (or 'bind') the first argument, producing a function of type  \scriptstyle\text{partial}(f) \colon (Y \times Z) \to N . Evaluation of this function might be represented as f_{partial}(2, 3). Note that the result of partial function application in this case is a function that takes two arguments.

In short, that means you define (bind) some of the possible arguments and leave some to be filled in later (free).

Scala

def sum(a:Int, b:Int, c:Int):Int = a+b+c  //> sum: (a: Int, b: Int, c: Int)Int
sum(1,2,3)                                //> res11: Int = 6

def sum1 = sum(1, _:Int, _:Int)           //> sum1: => (Int, Int) => Int
sum1(2,3)                                 //> res12: Int = 6

def sum2 = sum(_:Int, 2, _:Int)           //> sum2: => (Int, Int) => Int
sum2(1,3)                                 //> res13: Int = 6

sum1 binds the first parameter but the other two parameters are free. As you can see from the result it gets translated to a lambda with two parameters.

sum2 binds the second parameter. The result is the same, a lambda with two parameters.

C#

C# has no built-in operator for applying a function, so we have to write the lambdas directly.

readonly Func sum = (x, y, z) => x + y + z;

[Fact]
public void Sum()
{
    var result = sum(1, 2, 3);

    Assert.Equal(6, result);
}

[Fact]
public void Sum_PartialApply_FirstParam()
{
    Func sum1 = (y, z) => sum(1, y, z);

    var result = sum1(2, 3);

    Assert.Equal(6, result);
}

[Fact]
public void Sum_PartialApply_SecondParam()
{
    Func sum2 = (x, z) => sum(x, 2, z);

    var result = sum2(1, 3);

    Assert.Equal(6, result);
}

Wednesday, May 14, 2014

Loan pattern in C#

There is a pattern is Scala called loan pattern. You open a resource, “loan” the resource to another function, and the loaner closes the resource.

Scala

This function expects a file a function. When it's called it creates the resource, executes the function and closes the resource.

def withPrintWriter(file: File, op: PrintWriter => Unit) {
  val writer = new PrintWriter(file)
  try {
    op(writer)
  } finally {
    writer.close()
  }
}

This is how it's called:

withPrintWriter(
  new File("date.txt"),
  writer => writer.println(new java.util.Date)
)

C#

Now I extended the definition with currying:

readonly Func, string>> openFile = 
    path => 
        handler =>
            {
                var reader = new StreamReader(path);
                try
                {
                    return handler(reader);
                }
                finally
                {
                    reader.Close();
                    Console.WriteLine("Stream closed");
                }
            };

Here are two examples on calling the function above:

readonly Func readAllLines = input => input.ReadToEnd();
readonly Func readSingleLine = input => input.ReadLine();

[Fact]
public void LoanPattern_AllText()
{
    var result = openFile("TextFile1.txt")(readAllLines);
    Assert.Equal("This is the test content.\r\nThis is a second line.", result);
}

[Fact]
public void LoanPattern_ReadSingleLine()
{
    var result = openFile("TextFile1.txt")(readSingleLine);
    Assert.Equal("This is the test content.", result);
}

Result

Now the code calling the function (openFile) is much simpler and there is no need for error handling in the caller. Furthermore thanks to currying, even the resource name can be bound in the constructor, hiding the resource initialization as well.

Thursday, May 8, 2014

Currying in Scala and C#

Currying is an interesting and powerful functional programming concept. Interestingly currying can be used in C# as well.

The usual approach

Let's define a simple add function that sums two numbers in C#:

[Fact]
public void SimpleAdd_AsInlineFunction_WithLambda()
{
    Func<int, int, int> add = (x, y) => x + y;
    var result = add(5, 7);
    Assert.Equal(12, result);
}

The same in Scala:

def add(x:Int,y:Int) = x+y                      //> add: (x: Int, y: Int)Int
add(5,7)                                        //> res0: Int = 12
Or with lambda:
def add_lambda = (x:Int,y:Int) => x+y           //> add_lambda: => (Int, Int) => Int
add_lambda(5,7)                                 //> res1: Int = 12

Currying

Now Implement the same function in C#, but this time with currying:

[Fact]
public void CurryingAdd()
{
    Func<int, Func<int, int>> add = x => y => x + y;
    var result = add(5)(7);
    Assert.Equal(12, result);
}

In Scala:

def add_lambda_currying(x:Int) = (y:Int) => x+y //> add_lambda_currying: (x: Int)Int => Int
add_lambda_currying(5)(7)                       //> res2: Int = 12

With simplified Scala syntax:

def add_currying(x:Int)(y:Int): Int = x+y       //> add_currying: (x: Int)(y: Int)Int
add_currying(5)(7)                              //> res3: Int = 12

Partial apply

Now let’s suppose I want to bind the first parameter to a concrete value (bound) but I want to keep the second parameter unbounded (free).

This is the way in C#:

[Fact]
public void CurryingAdd_Add5()
{
    Func> add = x => y => x + y;
    var add5 = add(5);
    
    var result1 = add5(7);
    Assert.Equal(12, result1);

    var result2 = add5(122);
    Assert.Equal(127, result2);
}

The same idea in Scala:

def add5_lambda_currying = add_lambda_currying(5)  //> add5_lambda_currying: => Int => Int
add5_lambda_currying(7)                         //> res3: Int = 12

def add5_currying = add_currying(5) _           //> add5_currying: => Int => Int
add5_currying(7)                                //> res5: Int = 12

In case of the add5_currying example please notice the underscore (_) at the end of the expression. That means partial apply and indicates that I don’t want to bind the second parameter. There is no need for such indicator with lambda syntax.

Friday, February 7, 2014

Functional C# - insight by Python

Python has many powerful functions. I realized there are many similar functions available in .NET.

Enumerable.Aggregate
Function Description .NET
zip Pairs iterables element by element:

* x = [1, 2, 3]
* y = [4, 5, 6]
* zipped = zip(x, y)
* zipped
[(1, 4), (2, 5), (3, 6)]

Enumerable.Zip

int[] numbers = { 1, 2, 3, 4 };
string[] words = { "one", "two", "three" };

var numbersAndWords = 
    numbers.Zip(words, (first, second) => first + " " + second);

foreach (var item in numbersAndWords)
    Console.WriteLine(item);

// 1 one 
// 2 two 
// 3 three

reduce Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example,
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
calculates
((((1+2)+3)+4)+5)
.
Enumerable.Aggregate

string sentence = "the quick brown fox jumps over the lazy dog";

// Split the string into individual words. 
string[] words = sentence.Split(' ');

// Prepend each word to the beginning of the  
// new sentence to reverse the word order. 
string reversed = words.Aggregate((workingSentence, next) =>
                                                  next + " " + workingSentence);

// dog lazy the over jumps fox brown quick the 
filterConstruct a list from those elements of iterable for which function returns true.

filter(lambda x: x%2, range(10)) 
result: 1 3 5 7 9
Enumerable.Where
List fruits =
new List { "apple", "passionfruit", "banana", "mango", 
    "orange", "blueberry", "grape", "strawberry" };

IEnumerable query = fruits.Where(fruit => fruit.Length < 6);

/*
This code produces the following output:

apple
mango
grape
*/

Monday, November 11, 2013

Pragmatism

My background

I'm a .NET, mainly C# programmer. Nowadays I focus on web applications. I usually work on enterprise-grade applications.

I came across Python a year ago on a training session. I was shocked by the syntax but I felt the power of the language and the toolset.

Pragmatism

I think I need to define what is pragmatism for me in the context of software engineering: when a customer has a business problem, your responsibility as an engineer is to choose the proper tools to fulfil the real needs of this customer.

Pragmatic tools

A tool can be a language, a framework, a design or architectural pattern.

Business domain

The real need means a customer usually can't express the whole problem to the team (or even mislead the the team with half or missing information) so the developer (or analyst) needs to dig deep into the business problem and understand the domain before the actual coding gets started.

Pragmatic programming

The first thing is to understand the business domain. A developer has to constantly check the requirements against the customer's ideas and the business domain to make sure there is no misunderstanding. It also applies to the QA (tester) personnel as well. Only the joint work of the analysts, developers and QAs (regarding only the development team) can ensure the success of the implementation considering the business domain and real needs.

The pragmatic programmer does not stick to the favorite language (e.g. C#) she knows:
  • C# is a good choice for GUI, especially with WPF and Windows in mind. On the other hand Python can be a better choice for log analysis, mathematical modeling and statistical processing (considering NumPy, SciPy and Pandas). 
  • WCF (as an XML web service) is powerful for enterprise-grade service implementations but REST can be a better choice for thin APIs with mobile clients.
  • WCF is a powerful end-point provider but node.js can be a better choice if you have an AJAX-heavy web application with some kind of model-based JS framework. In case of node.js you don't need to transform your data from a static-typed language to a dynamic language. Less layers, less transformation, less technology and tooling. 
  • ASP.NET MVC is an easy-to-learn and thin layer for web application development. I like it, but I know Ruby on Rails or even Django (Python) can be as powerful or even more powerful for your particular task.
  • Entity Framework is powerful with its own limitations, but sometimes it worths going back to the basics with direct ADO.NET calls. Or does it? Consider Dapper, OrmLite and such.
  • Object-oriented programming is well-understood but functional elements can make the code more robust and easier to manage.
  • Defensive programming with guards is useful but what about code contracts (even the Microsoft implementation or in general)?
  • Scrum is good and has proved, but how can I adapt it to the current customer? Or shouldn't I choose Kanban? Or Scrumban? Do I need to integrate with an existing project management 'system'? Anyway, do I need to choose an agile methodology at all (yes, it should be prefered :) )?
There are always alternatives and the engineer's job should be choosing the right mix of these alternatives.

Wednesday, April 17, 2013

Unit testing a Powershell Commandlet

I chose to write Powershell commandlets in C#. I created a class library (DLL) project and inherited a class from Cmdlet base class. I created a snapin class derived from PSSnapIn to be able to install my commandlets from powershell.

Unit testing

Writing a unit test

[TestClass]
    public class UnitTest1
    {
        private static RunspaceConfiguration config;
        private static Runspace runspace;
        private static Pipeline pipe;
        private static Command command;

        [ClassInitialize]
        public static void TestFixtureSetup(TestContext context)
        {
            config = RunspaceConfiguration.Create();

            PSSnapInException warning;
            config.AddPSSnapIn("SnapinName", out warning);

            runspace = RunspaceFactory.CreateRunspace(config);
            runspace.Open();
        }

        [ClassCleanup]
        public static void TestFixtureTeardown()
        {
            runspace.Close();
        }

        [TestInitialize]
        public void Setup()
        {
            pipe = runspace.CreatePipeline();
            command = new Command("CommandName");
            pipe.Commands.Add(command);
        }

        [TestMethod]
        public void TestMethod1()
        {
            command.Parameters.Add(new CommandParameter("ParameterName", "Value"));

            var psObject = pipe.Invoke();
        }
    }

Snapin couldn't be found

I wrote a unit test against one of my commands but it couldn't find my snapin, I got the following exception:
System.Management.Automation.PSArgumentException: System.Management.Automation.PSArgumentException: The Windows PowerShell snap-in '...' is not installed on this computer..

I could use my snapin from Powershell command line.

Solution

Add the following lines as post-build events:
c:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe $(TargetPath)
c:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe  $(TargetPath)

Both 32-bit and 64-bit installation will happen this way.

Cause

Visual Studio 2012 is a 32-bit process. I registered with 64-bit install util only. Now I register both versions.

Monday, April 15, 2013

XAML Resource Loading

Visual Studio 2012 kept locking my .DLLs. It happened mostly after starting a debugger session. I could trace back the problem to a GetManifestResourceStream() call.

Solution

This is my solution that seems to be working:

public Stream GetResourceStreamByType(Type type, string resourceName)
{
  var location = Assembly.GetAssembly(type).Location;
  var assemblyBytes = File.ReadAllBytes(location);

  var appDomain = AppDomain.CreateDomain("Resource domain");
  var assembly = appDomain.Load(assemblyBytes);

  return assembly.GetManifestResourceStream(resourceName);
}

public BitmapImage GetBitmapByType(Type type, string resourceName)
{
  var bmp = new BitmapImage();
  using (var source = GetResourceStreamByType(type, resourceName))
  {
    bmp.BeginInit();
    bmp.StreamSource = source;
    bmp.EndInit();
  }

  return bmp;
}

Reasons

Loading the resource by calling the GetManifestResourceStream() on the current assembly loads the assembly into the debugger's app domain which is Visual Studio in this case. Reading the bytes and loading them manually prevents this behavior.

I couldn't reload the form again after loading the resources this way so I had to create a separate app domain as well. Without separate app domain the assembly was already loaded and the reloading didn't happen with an error message like 'does not have a resource identified by the URI'.

Tuesday, September 4, 2012

Ember–Handlebars.helpers in Windows 8 Metro

I tried to use Ember.js Handlebars helper {{action}} in a Windows 8 Metro (Windows Store) application. The data marker attribute appeared, but the function was never called.

I managed to find the root cause: Ember.js uses jQuery.ready() for initialization.

Solution

Change

waitForDOMContentLoaded: function() {
    this.deferReadiness();

    var self = this;
    this.$().ready(function() {
      self.advanceReadiness();
    });
  },

to

waitForDOMContentLoaded: function() {
    this.deferReadiness();

    var self = this;
      
    WinJS.Application.addEventListener("ready", function () {
        self.advanceReadiness();
    });

  },
and comment out 2 lines as shown below:
advanceReadiness: function() {
    this._readinessDeferrals--;

    //if (this._readinessDeferrals === 0) {
      Ember.run.once(this, this.didBecomeReady);
    //}
  },

Now you will use the Metro infrastructure for events.

Sunday, September 2, 2012

Handlebars and Ember templating in Window 8 Metro

Handlebars uses script blocks for template markup. E.g.

<script type="text/x-handlebars" data-template-name="say-hello">
      Hello, <b>{{MyApp.name}}</b>
</script>

Unfortunately the Metro JavaScript engine removes the data-template-name attribute from the script tag, so this method can’t be used for templating.

As JS files are available locally for execution, the template files can be stored in separate HTML files and can be parsed from code. The implementation is simple:

        

Windows.ApplicationModel.Package.current.installedLocation.getFolderAsync(path).done(function(folder) {
    var search = folder.createFileQuery(Windows.Storage.Search.CommonFileQuery.orderByName);
                search.getFilesAsync().done(function (res) {
                        res.forEach(function (file) {
                                var template;
                                Windows.Storage.FileIO.readTextAsync(file).then(function(fileContent) {
                                       var template = Ember.Handlebars.compile(fileContent);
                                       Ember.TEMPLATES[file.displayName] = template;
[…]

I omitted the async promises from the code for readability, but the code won’t work without them.

The code above

  1. reads all the files from a folder
  2. compiles the template
  3. stores the compiled template as an Ember template

Now Ember.js and Handlebars.js are fully functional, even Ember.View can be used with view.append().

Saturday, September 1, 2012

Digital TV Experience

I have some experience with a Samsung smart TV I will summarize here.

TV

I have access to analog TV signal, and I must tell you this is not what a digital TV was made for. It’s acceptable, but

  • the image is not sharp, thanks to the low resolution
  • the aspect ratio of the picture (aka picture size) changes among channels, or even between programs
  • the TV tries to enhance the quality of the image (e.g. sharpens the edges at still images), and sometimes that can be annoying
  • no electronic program guide (EPG)

I tried to receive DVB-T signal but I couldn’t. Just a few channels with long breaks in receiving. Though the image quality was wonderful and I got EPG.

Teletext

Teletext comes with the channels supporting this technology. It is the shadow of the analog era. Digital TVs try to enhance this technology:

  • store pages in memory, no need to wait for paging
  • more txt display modes

Don’t expect too much from this.

Multimedia

Digital TVs support a standard protocol (DLNA) for receiving multimedia streams from other devices. Just put the two devices onto the same subnet of your LAN (use the same router with cable or Wi-Fi) and the two devices will see each other. In my case I run a Samsung AllShare DLNA server on my desktop computer and

  • I can select the movie I want to play from the TV’s menu
  • I can start playing the movie on my TV pressing a button on my computer using AllShare or Windows Media Player.

Smartphones have the same capabilities. Moreover

  • I can start playing a movie on the TV from my computer pressing a button on my smart phone
  • I can control the TV from the smart phone as a TV remote (needs special app on your phone)

You can by a NAS with DLNA support and you will have an always online media server without noisy fans.

HDMI

Connecting a HDMI cable to the TV and the computer, means the computer’s desktop can be displayed on the TV, in excellent quality.

Even the sound can be redirected to the TV’s speakers or sound system. Just open the sound playback devices and set the TV as the default sound device.

If your TV supports HDMI Ethernet channel, you can use your TV as a(n Internet) router for multimedia device (blue-ray player etc.).

Smart features

I have access to a Samsung smart TV. It has an Internet browser and apps can be downloaded from a store. There are some useful apps like online radio and TV  channel guide, but the most useful app is the Internet browser. It has Flash support and loads most of the websites I tried to visit.

For better experience I suggest you to buy a wireless keyboard and mouse. There are multimedia keyboards combining these devices into a small device just like a game controller.

Friday, August 31, 2012

Require JS with Win 8 Metro interface

Require.js works with Windows 8 Metro-style (Windows Store) applications.

Page scripts

There is a JavaScript file for each HTML page files. You cannot wrap this .js file into a require function. The page events (e.g. the ready event) won’t be called.

You can place a require call into the event handler function and that works.

Thursday, April 12, 2012

Git: create a tag on a (remote) branch

You can create a tag on the local branch and you must push the tag to the remote.

Command line

> git tag …

> git push --tags

TortoiseGit

  1. Create tag
    1. set tag name
    2. set tag/branch/version
    3. enter message
  2. Sync/Push
    1. Select Push tags instead of Push button in the dropdown

Git Extensions

  1. Browse
  2. Right click on the commit log you want to tag
  3. Select Create new tag
  4. Enter data
  5. Push
    1. Select Push tags tab

Friday, February 10, 2012

Hate JavaScript?

Do you hate JavaScript? Well, I have bad news. There are still no alternatives in the web browsers.

I develop ASP.NET (MVC) –based web applications, and I must use JavaScript. What’s the big difference between the modern web applications and websites from a few years ago? Well, the server-side/client-side ratio. A few years ago I was happy coding on server-side. I did as much as I could do in C#, in ASP.NET. I did learn JavaScript but I avoided it as much as I could (so I never knew it well enough).

Now you can’t avoid JavaScript anymore. More and more code is on client-side. More and more business logic and architectural challenges are on client-side, right in the browser. I’ve written database-like features and even messaging systems in JavaScript. That challenge reminds me the early days of other languages. Missing features, missing language support, missing best practices, missing design patterns. Pure greenfield tasks.

How well do you speak JavaScript? A few years ago it was enough to understand how to define a function and some variables. Learn how DOM works. How different DOMs work. That’s not a small thing if you did it well. But did we write good, quality code with low bug ratio and good manageability? I’d say no.

A few years later there came the object-oriented world to JavaScript. We, I personally, had to learn the idea behind prototype-based languages. That’s a hard step with a ‘real’ object-oriented (Java, C#, C++) mindset. How can I implement inheritance? How can I hide data? How can I achieve polymorphism? Tough questions. Luckily along came design patterns. There are even a few books on the topic in JavaScript. Still, it’s not easy. I personally can recite 4-5 inheritance patterns. There are at least 2 data hiding patterns I can recall right now.

Well, many options, with their own drawbacks. It’s not easy to choose, e.g. at the beginning of a new project. There is no universal solution. There is no good solution. You have to consider the tasks you have to do with your object model and the knowledge level of the colleagues. Usually the later is harder. How much knowledge people have about JavaScript in e.g. Java/C# world? As much as they get along the projects. They teach each other.  To good and bed. What I saw in the last years, mostly obsolete and sometimes bad. Not easy to show them the current trends and solutions. Or may I say, contemporary engineering practices. People can, and usually are, be very proud of their coding style, quality, cleverness, etc. How can they be so neglect on these in an other language, e.g. JavaScript?

Now there are frameworks for DOM manipulation (jQuery, dojo, YUI), for common tasks (Underscore, YUI, Closure), and there are architectural frameworks (Knockout, Backbone) as well. As you can see, they are fractured and you must use different frameworks for different tasks. You should choose well because it’s very very hard to change frameworks, and you have to watch out for compatibility. Framework version changes represent huge risk in the lifetime of a project. Even a minor version change can render your web application totally useless. So test heavily.

No we have two ways. Full manual testing with a lot of humans. Or follow the ‘new’ trend and use some kind of automated test frameworks (Selenium, Watir). If they work the way you think. If it’s not more time to maintain your tests than execute them manually.

The same applies to unit tests. There are various frameworks in different flavors (xUnit, BDD, etc.) with different capabilities and APIs. Some live long, some live short. Choose well. Update regularly. Follow the news, trends.

Well, I chose a unit testing framework. Now I should test my code. How? It produces HTML into the DOM and calculates things according to different business rules – in the same function. Well, good luck. Try separating your business logic from visual stuff. Rings the bell? MVC? MVVM? Well, I’d say Knockout and Backbone. I’d say use (revealing) module pattern for your view model and your rendering as well. Separate them. Use a framework, e.g. Require.js. If you do it good, you can even get rid of the inheritance and other OO problems. Now you can test your business logic separated from the UI.

Next problem: I have a dynamic AJAX (AJAJ - Asynchronous Javascript and JSON) application calling back to the server. That’s not good. Let’s spy. Let’s stub.  Let’s mock. Find a framework, I chose Sinon.

So, let’s summarize. I do my job well if I know functions, variables, OO patterns, DOM frameworks, task frameworks, architectural frameworks, testing frameworks, module patterns, JavaScript mocking frameworks. Is that enough?

I have bed news. We in the web world develop applications like C++ coders develop applications for Windows, Linux, BSD… at the same time with the same code base. Instead of OSs, we have browsers and JavaScript standard versions. Now we have mobile devices as well, with different kind of browsers. So keep up, learn and write code in JavaScript. It’s better to learn and understand it than hope for surviving it. The next few years are about JavaScript and the Web. Get used to it, accept it. Do it as good as you do your job on server-side.

Thursday, January 19, 2012

jQuery div vs native doc fragment

I assumed creating a div with jQuery takes more time compared to native document fragment creation. Surprise, I was wrong. I’ve created a test page on JSPerf at http://jsperf.com/jquery-vs-documentfragment. Simply put, the speed depends on the browser.

Verdict: Use document fragment in all browsers except Internet Explorer. In general, use document fragment:

document.createDocumentFragment();

Monday, November 14, 2011

Less CSS and IIS 7

In case you are using Less CSS to generate CSS markups, IIS won’t find your .less files by default. You will get a 404 Not Found error. The problem is the missing MIME type.

The solution is simple, just register the MIME type for .less in web.config:

<system.webServer>
<staticContent>
<mimeMap fileExtension=".less" mimeType="text/css"/>
</staticContent>
</system.webServer>

Sunday, September 18, 2011

ASP.NET MVC Internals 3: Controller structure

Controllers implement the IController interface:
public interface IController 
{
    void Execute(RequestContext requestContext);
}
ControllerBase abstract class implements the IController interface:
public abstract class ControllerBase : MarshalByRefObject, IController 
{

    private TempDataDictionary _tempDataDictionary;
    private bool _validateRequest = true;
    private IDictionary<string, ValueProviderResult> _valueProvider;
    private ViewDataDictionary _viewDataDictionary;

    public ControllerContext ControllerContext {
        get;
        set;
    }

    public TempDataDictionary TempData {
        get {
            if (_tempDataDictionary == null) {
                _tempDataDictionary = new TempDataDictionary();
            }
            return _tempDataDictionary;
        }
        set {
            _tempDataDictionary = value;
        }
    }

    public bool ValidateRequest {
        get {
            return _validateRequest;
        }
        set {
            _validateRequest = value;
        }
    }

    public IDictionary<string, ValueProviderResult> ValueProvider {
        get {
            if (_valueProvider == null) {
                _valueProvider = new ValueProviderDictionary(ControllerContext);
            }
            return _valueProvider;
        }
        set {
            _valueProvider = value;
        }
    }

    public ViewDataDictionary ViewData {
        get {
            if (_viewDataDictionary == null) {
                _viewDataDictionary = new ViewDataDictionary();
            }
            return _viewDataDictionary;
        }
        set {
            _viewDataDictionary = value;
        }
    }

    protected virtual void Execute(RequestContext requestContext) {
        if (requestContext == null) {
            throw new ArgumentNullException("requestContext");
        }

        Initialize(requestContext);
        ExecuteCore();
    }

    protected abstract void ExecuteCore();

    protected virtual void Initialize(RequestContext requestContext) {
        ControllerContext = new ControllerContext(requestContext, this);
    }
    
    [...]
}

Saturday, September 17, 2011

ASP.NET MVC Internals 2: Controller

The MvcHandler class processes an HTTP request. The routing framework calls its ProcessRequest() function in case of an incoming request matching an MVC route.
public class MvcHandler : IHttpHandler, IRequiresSessionState 
{
    [...]
    protected internal virtual void ProcessRequest(HttpContextBase httpContext) 
    {
        AddVersionHeader(httpContext);

        // Get the controller type
        string controllerName = RequestContext.RouteData.GetRequiredString(&quot;controller&quot;);

        // Instantiate the controller and call Execute
        IControllerFactory factory = ControllerBuilder.GetControllerFactory();
        IController controller = factory.CreateController(RequestContext, controllerName);
        if (controller == null) {
            throw new InvalidOperationException(
                String.Format(
                    CultureInfo.CurrentUICulture,
                    MvcResources.ControllerBuilder_FactoryReturnedNull,
                    factory.GetType(),
                    controllerName));
        }
        try {
            controller.Execute(RequestContext);
        }
        finally {
            factory.ReleaseController(controller);
        }
    }
    [...]
}

Firstly it reads the controller name from the routing data and after that it creates a controller by the name read before. Finally it calls the Execute method of the controller to run the controller’s code.