Knockout Validation with Bootstrap Popover

I wanted to use Twitter’s Bootstrap Popover’s to let the user know they need to enter values into each of the form’s inputs.
On top of Knockout’s Validation, I decided to create a custom Knockout binding that allows me to check if the Knockout observable is valid and either show or hide the popover with the error message.

See the image below for the final result.

Example of KO Validation with Popover

The mark up is

1
2
3
4
5
6
7
 <div class="row">
                            <div class="col-xs-6">
                                <div class="form-group" data-bind="validationElement: item.notes">
                                    <textarea id="notes" rel="validatePopover" data-position="right" class="form-control input-sm" rows="3" placeholder="Notes ..." data-bind="value: item.notes, validationPopUp: item.notes"></textarea>
                                </div>
                            </div>
                        </div>

If you would like the knockout custom binding code, please visit Github.

Method chaining with deferring object creation

I have decided to write a couple of posts about how I used Method Chaining to help solve and better handle the creation of test data within my Unit Tests. This post and the example code via GitHub shows how I created test data using Method Chaining in a more generic form. There will be more posts to come regarding how this test data gets persisted into a in-memory database which will get used in XUnit Tests.

For my problem, I had to build up test data that will be used within a number of Unit Tests. Creating objects and assigning values to properties through Factory classes is considered a fairly normal approach, however being able to build up objects using method chaining gives me the flexibility to create objects with different characteristics.

For example, var foo = MyFooBuilder.Create().WithName(“My Foo”).WithAge(5).WithCar(“Audi”).Build(). This allows me to build up a foo object using a nice fluent chaining of methods compared to var foo = new Foo() { Name = “My Foo”, Age = 5, Car = “Audi” }. This allows me to keep all the Foo created code in a nice and tidy builder class which provides the flexibility to extend the builder to introduce new characteristics in the future.

What I ended up creating was a generic builder class that allows me to use a object of type T, build up a set of actions to get a newly created object. for example, var foo = MyBuilder.Create().WithProperty(new { Name = “MyPropertyName”, Value = “MyValue” }).Build();

You can view my builder class at https://github.com/codelabnz/BuilderExample

The call is ambiguous between the following methods or properties: ‘Umbraco.Web.UmbracoHelper.Media

I was coding up a new template in the latest version of Umbraco v7 using Razor and discovered this error when trying to get a Media object from one of my properties of the current page.


The call is ambiguous between the following methods or properties: ‘Umbraco.Web.UmbracoHelper.Media(params int[])’ and ‘Umbraco.Web.UmbracoHelper.Media(params string[])’

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: The call is ambiguous between the following methods or properties: ‘Umbraco.Web.UmbracoHelper.Media(params int[])’ and ‘Umbraco.Web.UmbracoHelper.Media(params string[])’

My property was a Media Picker type which I made the assumption it was given me a Integer Node Id to the specific media object.

I started out with the following code:

1
@Umbraco.Media(CurrentPage.ProfileImage).umbracoFile

This caused the error above, so by converting it to a string using the .ToString() method, this caused the compiler to ignore the error and use the correct UmbracoHelper method.

1
@Umbraco.Media(CurrentPage.portfolio5Image.ToString()).umbracoFile

Generic View Model under Knockout.js

I found that my problem on this particular project was having to generate knockout.js models from JSON data that was generated from ASP.NET MVC.   The back-end has several .NET classes, i.e viewdata classes that have several other classes, collections, properties etc. I wanted to treat the back-end as being the master of my model structure so I wouldn’t need to have the model duplicated in several different places through out the project. One of the elements in this problem is how to deal with creating knockout.js models with re-usable code.  The solution I went with was to create a generic JS wrapper that allowed me to pass in JSON and return me a knockout view model using the knockout.js JSON mapping class. This allowed me to use a re-usable wrapper to generate the model and keep the code consistent.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var genericDemo = genericDemo || {};

genericDemo = {
UpdateViewModel: function(data, viewModel) {
ko.mapping.fromJS(data, viewModel);
},
CreateViewModel: function (data, propertyName) {
var appViewModel = function(data)
{
var self = this;
self[propertyName] = ko.mapping.fromJS(data);
}
return new appViewModel(data);
}
};

And here is the implementation

1
2
3
4
5
//this allowed me to have several view models
var masterViewModel = function() { };
masterViewModel.genericDemoViewModel = genericDemo.Generic.CreateViewModel(@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.MyModelFromMVC)),"propertyname");

console.log(masterViewModel.genericDemoViewModel.propertyname.propertyFromMyMVCModel());

InvalidCastException after upgrading from ASP.NET MVC 3 to ASP.NET MVC 4

I have recently upgraded a MVC 3 application to MVC 4 but along the way en-counted some issues around upgrading references in the project.

Specially, I got this error.

1
2
3
4
5
6
7
8
9
System.InvalidCastException was unhandled by user code
Message=[A]System.Web.WebPages.Razor.Configuration.HostSection cannot be cast
to [B]System.Web.WebPages.Razor.Configuration.HostSection. Type A originates
from 'System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35' in the context 'Default' at location
'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.WebPages.Razor\v4.0_1.0.0.0__31bf3856ad364e35\System.Web.WebPages.Razor.dll'.
Type B originates from 'System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
in the context 'Default' at location 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Web.WebPages.Razor\v4.0_2.0.0.0__31bf3856ad364e35\System.Web.WebPages.Razor.dll'.
Source=System.Web.WebPages.Razor

Sources on the interweb say that you should change the webpages element back to 1.0.0.0 from 2.0.0.0 in your web config:

1
2
3
<appSettings>
  <add key="webpages:Version" value="1.0.0.0"/>
</appSettings>

but this seems a bit strange having to specify a old version to use the new version of System.Mvc.WebPages?

I believe the better solution is to add a binding redirect to tell any reference that has been using System.Mvc.WebPages 1.0.0.0 to use 2.0.0.0.

the following goes into your web.config

1
2
3
4
5
6
7
8
9
10
 <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
   
      <dependentAssembly>
          <assemblyIdentity name="System.Web.WebPages.Razor"
              publicKeyToken="31bf3856ad364e35" />
          <bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>

Upgrading MVC Project 2 to 4 and open it in VS 2012

I have an old MVC 2 project that works fine in VS 2010. However, if you try and open the project in VS 2012 you will get a “incompatible” error and left with no way to upgrade the project to VS 2012.

Here are some pointers to get it working (this is how I got it working for myself).

In VS2010, upgrade your MVC project to version 4. You need to follow the upgrade steps for upgrading to MVC 2 – 3 first.

http://www.asp.net/whitepapers/mvc3-release-notes#upgrading

Secondly, upgrade from MVC 3 to 4 using the following link.

http://www.asp.net/whitepapers/mvc4-release-notes#_Toc303253806

Once you have done this, you need to edit the project file of the working web application (i.e csproj). Firstly, open the solution in VS2012, the web project will not work but you can edit the project file directly in the IDE.

Make sure that you add the MVC 4 ProjectTypes GUID ({E3E379DF-F4C6-4180-9B81-6769533ABE47}) and remove the old MVC ProjectTypes GUID ({F85E285D-A4E0-4152-9332-AB1D724D3325}).

Here is a list of available GUIDS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Windows (C#) {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
Windows (VB.NET) {F184B08F-C81C-45F6-A57F-5ABD9991F28F}
Windows (Visual C++) {8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}
Web Application {349C5851-65DF-11DA-9384-00065B846F21}
Web Site {E24C65DC-7377-472B-9ABA-BC803B73C61A}
WCF {3D9AD99F-2412-4246-B90B-4EAA41C64699}
WPF {60DC8134-EBA5-43B8-BCC9-BB4BC16C2548}
XNA (Windows) {6D335F3A-9D43-41b4-9D22-F6F17C4BE596}
XNA (XBox) {2DF5C3F4-5A5F-47a9-8E94-23B4456F55E2}
XNA (Zune) {D399B71A-8929-442a-A9AC-8BEC78BB2433}
Silverlight {A1591282-1198-4647-A2B1-27E5FF5F6F3B}
ASP.NET MVC {F85E285D-A4E0-4152-9332-AB1D724D3325}
ASP.NET MVC 4 {E3E379DF-F4C6-4180-9B81-6769533ABE47}
Test {3AC096D0-A1C2-E12C-1390-A8335801FDAB}
Solution Folder {2150E333-8FDC-42A3-9474-1A3956D46DE8}

http://stackoverflow.com/questions/2911565/what-is-the-significance-of-projecttypeguids-tag-in-the-visual-studio-project-fi

From here you reload the project (after you save the project file) and a way you go.

405 Method Not Allowed using ASP.NET Web API

I have been using the ASP.NET Web API recently on a project and this has been working well together with Backbone.js as the front end framework. I have been using PUT for updating the model and POST for adding to the model.

Everything is going well until I deployed the application on a production server. I got the error when trying to perform a PUT request to the server from the front-end. The error was “405 Method not allowed”.

The reason for this is two parts; one the production server has WebDav installed and this has caused conflicts with ASP.NET Web API and two by default the handler was not allowing the PUT verb.

The solution was to remove the WebDav handler and WebDav module from web.config and change the ExtensionlessUrl handler verb attribute.

1
2
3
4
5
6
7
8
9
10
11
12
<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="WebDAVModule" />
    </modules>
    <handlers>
      <remove name="WebDAV" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
   
  </system.webServer>

hexadecimal value 0x1F, is an invalid character publishing content in Umbraco

I was adding some content into a Umbraco content page when I attempted to publish the page I got a 500 error with the following error message:

1
2
3
4
5
6
7
8
9
10
Server Error in '/' Application.

'', hexadecimal value 0x1F, is an invalid character. Line 1, position 519.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Xml.XmlException: '', hexadecimal value 0x1F, is an invalid character. Line 1, position 519.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

The issue was because of a special/invalid character in the content. This may be caused by copy and paste from a application like Microsoft Word or a similar word processing application. The best way to get around this is to paste the content into a application like Notepad or Notepad++ and then find the invalid character, replace the character and then copy/paste into Umbraco.

Get All Nodes By DocumentType

The following code describes how to get all the nodes by a particular document type across the whole Umbraco site. It uses a recursive method so if you add this as a macro I would suggest caching to reduce the number of times this method runs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using umbraco.presentation.nodeFactory;


public class UmbracoHelper
{
    private const int CONST_NODEAMOUNT = 10;
    /// <summary>
    /// Get all nodes by type, put -1 to start at the root of the website
    /// </summary>
    /// <param name="NodeId"></param>
    /// <param name="typeName"></param>
    /// <returns></returns>
    public static List<Node> GetAllNodesByType(int NodeId, string typeName)
    {
        List<Node> foundNodes = new List<Node>();
        var node = new Node(NodeId);
        foreach (Node childNode in node.Children)
        {
            var child = childNode;
            if (child.NodeTypeAlias == typeName)
            {
                foundNodes.Add(child);
            }

            if (child.Children.Count > 0)
                GetAllNodesByType(ref foundNodes, child, typeName);
        }

        //Take the first 10, this can be changed
        return foundNodes.Take(CONST_NODEAMOUNT).ToList();
    }

    /// <summary>
    /// Recursive method to get the nodes from the child passed in as a parameter
    /// </summary>
    /// <param name="foundNodes"></param>
    /// <param name="node"></param>
    /// <param name="typeName"></param>
    private static void GetAllNodesByType(ref List<Node> foundNodes, Node node, string typeName)
    {
     
        foreach (Node childNode in node.Children)
        {
            var child = childNode;
            if (child.NodeTypeAlias == typeName)
            {
                foundNodes.Add(child);
            }

            if (child.Children.Count > 0)
                GetAllNodesByType(ref foundNodes, child, typeName);
        }
    }

   
    public UmbracoHelper()
    {
       
    }
}

Script error when using RichTextEditor type in Razor macro – Umbraco

I came across this issue when trying to check if the RichTextEditor property had any content before rendering it to the display.

Examine the following code:

1
2
3
4
5
6
7
8
9
@{
var thisNode = Model;

}

@if (!string.IsNullOrEmpty(thisNode.MyRichContent))
{
<div class="text-widget">@thisNode.MyRichContent</div>
}

This causes a script error because Umbraco thinks MyRichContent is a object type.
To get around this, either call .ToString() on the property or do a length condition i.e thisNode.MyRichContent.ToString().Length > 0 to resolve the issue.