Archive for the ‘JQuery’ Category

Firefox needs UTF8 for GeoXml3

I’m developing an WebAPI2 solution with Angular that receives, from Android devices, GPS points.
So Latitude , Longitude , Speed etc. are saved in a SQL Server 2014 table; from the web site the headquarter would follow the real time navigation.
The chosen approach was to write an KML file from the db data, and show this KML in a GoogleMaps window.
Having local files (not on another domain) the best solution is to use the GeoXml3 library, which is relatively easy to use (examples here and here).
For the javascript part, no problem: there is an simple setTimeout that calls via jQuery an WebAPI2 method that re-write the kml (the name is the record ID), and then adding an random number to the querystring the boss can follow the persons wandering somewhere, seeing the kml line that slowly progress on the map.
But there was an problem: On IE10 , 11, Chrome, Edge all ok; instead on Firefox (Windows or Ubuntu or Android tablet) no kml shown.
Sometimes the things are discovered in a very casual manner…i tried to save the KML with another name using Notepad++ , and change the code in order to not use the API call and instead try to show immediately this second file where i wanted to test some change, in order to understand what was wrong : bingo, KML immediately visible!
This was a real head scratching…the files (the generated from the system, and the one saved from the previous) in Notepad++ was absolutely the same, no visible difference.
So i tried to compare them with WinMerge and surprise, the generated file was full of strange characters before every normal character, immediately i realized “oops, the encoding?” and only after i noticed in Notepad++ that in the Encoding menu the file saved from Notepad++ itself was UTF8 encoded, and the one produced from the C# code was without encoding.
In the WebAPI2 method effectively i used Unicode: so now, all the browsers shows the KML writing the file as:

private async Task WriteTextAsync(string filePath, string text)
    //byte[] encodedText = Encoding.Unicode.GetBytes(text);
    byte[] encodedText = Encoding.UTF8.GetBytes(text);
    using (FileStream sourceStream = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.None, bufferSize: 1048576, useAsync: true))
        await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);

Breeze SaveChanges issue with Ie10

Every new technology is an hard path , an high mountain to climb.

I’m working to an MVC project with ASP.NET 4.5 , Breeze and Angular, authentication done with the new ASP.NET Identity, Entity Framework 6.

The big problem , for the average developer (me) , is:

  • For Microsoft, on MSDN you can find a lot of verbose pages about the syntax: an simple CRUD example using these technologies , add update delete of records, is hard to find.
  • For thirdy parties technologies you can find abstruse , overcomplexed samples ; but still there is a lack of a simple table management with CRUD operations.

In every case the samples simply ignore (at the least the ones that i discover with Google) the everyday questions with concurrency : another user could have deleted the record that you are trying to save, or you are trying to save a record of a table where there is an unique index for a field.

Ok , this was the rant, now the problem.

The code is about the update of a record in a Vehicle Classes table (ClassiMezzi).

Using Breeze, in a BreezeController (a class decorated with “[BreezeController]”) the typical sample for an update is

public SaveResult SaveChanges(JObject saveBundle)
    return _repo.SaveChanges(saveBundle);

This works with Ie11, the latest Firefox, Chrome, Safari; _repo is an repository object that at the end calls the Entity Framework context provider (in our sample EFContextProvider<ClassiMezziContext>)

But if you try to use this method for adding a new record on a table where there is an index UNIQUE, there are troubles with the error messages using Internet Explorer 10.

For these new apps i simply don’t consider Ie < 10; if you are still using Ie6 , Ie7.. time to upgrade …but to ignore the previous version is a bit excessive, for me: i test everything with the latest Firefox, Chrome also under Linux Android and Mac, for Ie to test the latest version and the previous seems reasonable.

And so, testing the code with multiuser issues (record deleted from another user, check constraints, UNIQUE indexes) i discovered the problem.

From the javascript side , the controller is called with an Ajax call with callbacks for success or failure:

function saveFailed(error) {
    try {
    catch (ex) { }
    service.ClasseMezzoEntity = null;
    if (error.httpResponse.status === 401 || error.httpResponse.status === 403) {
        logError(localize.localizeText("UnauthorizedOperation"), null, true);
    //var strMsg = breeze.saveErrorMessageService.getErrorMessage(error).toLowerCase(); old version ok with Ie11 , not Ie10
    var strMsg =[0].toLowerCase();
    if (strMsg.indexOf("entities may have been modified or deleted since entities were loaded") > 0) {
        logWarning(localize.localizeText("AnotherUsrHasChangeData"), null, true);
    if (strMsg.indexOf("ix_classimezzi") > 0) {
        logWarning(localize.localizeText("ClassNameDuplicated"), null, true);
    if (strMsg.indexOf("errdelete:anotheruser") > 0) {
        logWarning(localize.localizeText("AnotherUsrHasDeleteData"), null, true);
    //  other code for unknown error management
    var msg = breeze.saveErrorMessageService.getErrorMessage(error);
    // etc.
function saveClasseMezzo() {
    service.isSaving = true;// see at the end of this module
    service.lastSaveSuccess = true;
    return manager.saveChanges()

For example we try to add another ClasseMezzo (Vehicle class) with the same name of an existing item on the the db table.

With Ie11 and other latest browsers the first controller code is ok , and if our ajax call fails because the UNIQUE index the first

var strMsg = breeze…. commented code works perfectly.

But while with Ie11 etc. the error.message in javascript contains the string “Cannot insert duplicate key row …” with the index name that helps to manage the error (in this sample the index name is “ix_classimezzi”) in Ie10 we get

That is an anonymous “An error has occurred” that can’t help to manage the error, and no trace of the original SQL error in httpResponse: a big trouble if i would to say to the customer “you are trying to insert an duplicate item” because could be another thing , for example an SQL check violation.

The problem is the simple approach in the WebApi2 controller.

In order to manage correctly the errors coming from multiuser issues the WebAPI2 controller code must be:

[Authorize(Roles = "PowerUser")]
public SaveResult SaveChanges(JObject saveBundle)
    SaveResult objRes = null;
    List<object> objErr = null;
    var classimezziList = JsonConvert.DeserializeObject<List<ClassiMezzi>>(saveBundle.SelectToken("entities").ToString());
        objRes = _repo.SaveChanges(saveBundle);
        return objRes;
    catch (Exception ex)
        var keyMappings = new List<KeyMapping>();
        objErr = new List<object> { JsonConvert.SerializeObject(ex.Message) };
        return new SaveResult()
            Entities = classimezziList.Cast<object>().ToList(),
            Errors = objErr,
            KeyMappings = keyMappings

Let’s examine the code.

We pass to the controller an JSON object , that we want deserialized in order to correctly manage the error; note in the catch management code: is explicitly created an SaveResult object , instead of the automatic creation.

Setting the Errors field to something != null , in our case the error message serialization, we cause the call of the javascript failure callback , and in the javascript failure code the message must be read as

var strMsg =[0].toLowerCase();

because when the code is falling back we have this , now:

So we can manage the things as in the next rows.

This is valid also for Ie11 , and Firefox, Chrome under Windows, Linux, Mac, Android.

At least, this is the situation with the current latest Breeze (1.3.8)

The requested resource does not support http method ‘POST’

After a life of web sites developed with Web Forms, now i’m working with MVC.

Not a basic MVC, but SPA apps using Angular, Breeze, Twitter Bootstrap.. an huge jump.

In the Controller folder of my solution i was thinking to create an utilities controller, in this case for the logging of javascript errors, paging utilities, and so on.

So i initially created a class as:

public class ServicesController : ApiController
	public void SubmitError(string jsRespoText, string jsstatus, string jssource)
		ExceptionUtility.LogJsExceptionFile(jsRespoText, jsstatus, jssource);

	public JsonGenResponse CreatePagerStdTable(int startRowIndex, int totalCount, int pageSize, string jsLoadDataFunName, string Filter, string QueryType)
		// this will be another post…

For the HttpGet , no problem.

When i tried from Fiddler the HttpPost method i got the error written in the subject of this post.

A Controller decorated with [BreezeController] works as POST, and it was tested.. but it uses a JObject parameter, i noticed.

The POST problem pops out when you try to use primitive (string, int..) parameters in a Web API call instead of an object.

A solution could be to use [FromBody], with this attribute WebAPI search the attribute:value in the request body.

But there is a problem : is not possible to specify more than one “[FromBody]” , so is not possible to write:

public void SubmitError([FromBody]string jsRespoText, [FromBody]string jsstatus, [FromBody]string jssource)

The solution is to create a class, in my case

public class JsErrorData
    public string jsRespoText { get; set; }
    public string jsstatus { get; set; }
    public string jssource { get; set; }


And then write the method as

public void SubmitError(JsErrorData jsObjErr)
    ExceptionUtility.LogJsExceptionFile(jsObjErr.jsRespoText, jsObjErr.jsstatus, jsObjErr.jssource);

The javascript caller:

function logJsError(responseText, status, source, callback) {
    var ajaxImpl = breeze.config.getAdapterInstance("ajax");
        type: "POST",
        contentType: "application/json;charset=UTF-8",
        url: strBaseHttp + "api/Services/SubmitError",
        data: "{'jsRespoText': '" + responseText.replace(/'/g, '') + "','jsstatus':'" + status + "','jssource':'" + source + "'}",
        success: function (html) {
        async: true

Now HttpPost is working.

Categories: .NET, JQuery, MVC, SPA

Upgrade of Durandal projects

I’m working with Durandal , and i need to upgrade some old (old..2013…) code.
But this code was written when there was Durandal 1.x , now with NuGet in a Visual Studio 2013 project the version is 2.01 , and are changed a lot of things.

Fortunately in this Durandal site page and in this Papa’s page there are useful guidelines.

Categories: .NET, Durandal, JQuery, MVC, SPA

RequireJS with Visual Studio 2013 & WebAPI

Now that the SPA is the mainstream technology of the moment, i was wondering how really are useful Knockout, Durandal, RequireJS and so on.

These new buzzwords are javascript frameworks, founded (RequireIS no) on the well knowed jQuery.

I have done many web applications with jQuery and SPA concepts , using web forms (.aspx) as html/json generators and then decoding/evaluating the resulted html or JSON by hand.

So i started a lot of tests, trying to convert some old web applications in “à la page” SPA apps.

This is not a simple task , because the technologies are rapidly changing and evolving (as the jQuery versions): so the sample probably working at the time of the publications three months after is not working because jQuery changes, new library versions and so on.

I tried to evaluate RequireJs, the first step was to create with Visual Studio 2013 a new ASP.NET Web Application, using the WebAPI template:

Note that i explicity chosen Web API.

Then the first thing that seems obvious is to add a WebAPI controller:

naming it “TestController”

The generated TestController.cs contains

namespace RequireJsTest.Controllers
    public class TestController : ApiController
        // GET api/<controller>
        public IEnumerable<string> Get()
            return new string[] { "value1", "value2" };

        // GET api/<controller>/5
        public string Get(int id)
            return "hi this is the test " + id.ToString();

In this case i changed the default “value” string with “hi this is the test ” + id.ToString().

By adding the WebAPI there is a new class WebApiConfig in App_Start, called in the global.asax.

Note the comment above // GET api/<controller>/5 : this will be be the path for the call, with the template defined in the WebApiConfig class.

If you try http://localhost:<yourport>/api/test/5 you get a file named 5.json , that contains “hi this is the test 5” (using the default Visual Studio web server).

Now, in the past in a complex web application with many .js sources it was requested a manual and complex management in order to provide the requested js modules in a certain situation, for example we are deleting a db record and it is necessary to provide the infrastructure for the ajax call vs the db and the messaging framework to the user.

With RequireJS the dependencies management in javascript is simplified, the pages and explains very well the concepts.

So we can install RequireJS from TOOLS->Library Package Manager->Manage NuGet Packages for Solution…

and search online:

Done this , to the HomeController.cs we can add a new method

public ActionResult Test()
    ViewBag.Title = "Test Page";
    return View();

Right clicking this method we can Add View for this Controller method,

That creates an Test.cshtml file under Views/Home :

By default there is only an <h2> , we change to

    ViewBag.Title = "Test";


<div id="msgplaceholder"></div>
<script data-main="/app/main" src="@Url.Content("~/Scripts/require.js")"></script>

Require.js is the script added from RequireJS, and now we see what is the “data-main” attribute.

A SPA app typically uses a folder named “app” , immediately under the root, as the main placeholder of the SPA structure.

And another commonly used standard is to use a main.js file as the SPA core.

As the requireJS site write, “The data-main attribute is a special attribute that require.js will check to start script loading”.

So the last <script> loads a file named main.js using the require.js library.

At this point we need to create the main.js , and a structure for the separation of the concepts.

In this case:

In main.js we define some aliases for other js modules, specifying the path:

(function () {
            paths: {
                'testview': '/app/viewmodels/test',
                'datasvc': '/app/services/testsvc',
                'config': '/app/configs/config'

        function (testvw) {
            var id = 10;

Here the function decorated with require([‘testview’] is automatically executed, if you place another function for example

    function (testvw) {
        var id = 10;

    function (testvw) {
        var id = 20;

is automatically executed after the first has finished (the result depend from the callbacks timings).

Note that the function define as required the module that we aliased with ‘testview’, that points to /app/viewmodels/test.js

Here in we can write

    ['jquery', 'datasvc'],
    function ($, datasvc) {
        var showMessage = function (id) {
            datasvc.getTest(id, function (message) {

        return {
            showMessage: showMessage

That is we define that the current module will be publicy knowed as “testview” with “define”, and so in main.js we can write “require([testview]”

In test.js we note that this module is defined with the public name “testview”, and internally requires jQuery , which is already publicy knowed with the $ symbol, and our other module “datasvc”,

Here we can define some functions, the ones that we need public are defined public with the “return” keyword (a sample of Module Pattern).

We know now that datasvc is the alias defined in /app/services/testsvc.js where we can write something as

    ['jquery', 'config'],
    function ($, config) {
           var callWebApi = function (url, type, callbackfunc) {
                    url: url,
                    type: type,
                    dataType: 'json',
                    success: function (data) {
                    error: function (jqXHR, textStatus, errorThrown) {

            getTest = function (id, callback) {
                url = config.baseUrl + id;
                callWebApi(url, 'GET', callback);

        return {
            getTest: getTest

That requires “config” defined in /app/configs/config.js

    function () {
        var baseUrl = '/api/test/';  //important ! Verify that the name must be the same of the controller

        return {
            baseUrl: baseUrl

Note that config.js is not requiring other libraries, so we can write define(‘config’, []

That is nothing in the square brackets.

if we try to run our app and point the browser to /home/test ( for example http://localhost:29404/home/test)

Conclusion: effectively some of these new frameworks are really useful and RequireIS leads to a less “spaghetti” javascript code.

Categories: .NET, JQuery, MVC, SPA, Vs2013

MVC Ajax with IIS 7.5 and with VS Server

I’m not an Visual Studio 2012 Development Server (also of IIS Express…) fan, for a lot of motivations.

An example is a difference in the default paths for an MVC jQuery Ajax call , if is done from the VS dev server or from Windows 7 IIS 7.5 (i will investigate on IIS under Windows 8…) , which is near identical to the IIS on the average, real production server.

In order to see this difference create an simple MVC4 project (as Internet Application) named HelloWorld ; in the Models folder create a class UserData , as

namespace HelloWorld.Models
    public class UserData
        public string UserName { get; set; }

in the HomeController.cs created by default (using the Internet application template) place a method GetMessage

public JsonResult GetMessage(UserData myData)
    myData.UserName = "Hello " + myData.UserName ;
    return Json(myData, JsonRequestBehavior.AllowGet);

In the Scripts folder place an HelloWorld.js script:

var myData = {
    UserName: "Bill Gates"
$(function () {
        type: "GET",
        url: "/Home/GetMessage",
        data: myData,
        contentType: "application/json",
        success: processResult
function processResult(returnedData) {
    window.alert("Returned value : " + returnedData.UserName);

We are using the HomeController so we use “Home” (without “Controller”) as address.

Our javascript can be referenced in Index.cshtml adding after the last line

@section scripts{
   <script src="~/Scripts/HelloWorld.js">

Launching the site we receive

At this point in the solution properties the web server we change from the Visual Studio Development Server to IIS (not Express) , creating in IIS a new Web Application that uses the ASP.NET v4.0 Application Pool

This time launching the application is no more used the address localhost:4560 but the IIS application, and our script is no more working : using Fiddler we can see that there is an 404 error.

If in the javascript we change the URL from

url: “/Home/GetMessage”,


url: “/HelloWorld/Home/GetMessage”,

(that is we add the application name) our app turns back to working, but does not work if we revert the solution to use the Visual Studio Development Server.

There is a trick, changing the VirtualPath to from the single “/” to “/HelloWorld” (the name given to the IIS 7.5 web application and used in the Ajax url)

The Visual Studio web application is still working as the true IIS version.

Categories: .NET, JQuery, MVC, Vs2012

jQuery not working in MVC4 (JSON undefined)

After a long time i’m coming back to work in MVC, obviously MVC4 with Entity Framework 5.

I updated an old project started from the classic Internet application template, the first thing was to update the packages via NuGet so the current jQuery version in my project is 2.03

First launch, and surprise: apparently jQuery is not working; this on my HP laptop with Windows 7 64 bit, Internet Explorer 10.

From the other hand also working in SharePoint i encountered problems with the jQuery upgrading

I tried to create a completely new MVC4 project, launched the project activating the debug in Ie and immediately popped out an error in jQuery:

JSON is undefined ??

With this error, JQuery naturally is not loaded:

I noticed that was active the icon for the compatibility view

By activating the compatibility voilà jQuery working..ok but i can’t’ tell to the customers to activate the compatibility…

The solution is to add in the MVC _Layout.cshtml file this line in the <head> section:

<meta http-equiv="X-UA-Compatible" content="IE=edge;chrome=1" />

With this correction jQuery is working and the compatibility icon is no longer present.

Categories: Javascript, JQuery, MVC, Vs2012

Transform legacy js in Module Pattern

Tipically a lot of existing javascript code is written in the old plain mode:

function cmdAddNew_onClick() {

Every javascript programmers know that this spaghetti-code approach is hard to maintain, every function is public so it is easy to have strange behaviors that is a nightmare to debug.

The worst problems are in portals as the old Aqualogic, where was easy to have portlets with a different behavior is you inverted two portlets position in the page…

A better approach is to write our modules using a modern pattern as the Module pattern or the Singleton, there is lot a documentation about searching on Google, for examples this and this.

A skeleton of a correct Module Pattern implementation could be:

$(document).ready(function ($) {
    mycomsite.customername.projectname.context = (function ($) {
        "use strict";
        var cmdAddNew_onClick = function () {
        var showEditBox = function (id) {
            // js code for showing an Jquery dialog...
        var numericSetvMax = function () {
            return '100';
        return {
            cmdAddNew_onClick: cmdAddNew_onClick,
            numericSetvMax: numericSetvMax            

The main trick is the namespace; note that we pass the jQuery variable to the module in order to use jQuery inside the module.

For example if we are a IT company with a internet site , we are working to a tickets solution for the scandinavian KLM company and the current is the js file for the ticketing by VISA ,a namespace could be

$(document).ready(function ($) {
    comacme.klm.ticketing.visatickets = (function ($) {

But we can’t have js variables with “.” in javascript, you say … the trick is a initial first module of our web app with lines as these :

if (!comacme) {
    var comacme= {};
comacme.klm= {};
comacme.klm.ticketing = {};

So we have defined a pseudonamespace.

Using the Microsoft Ajax Toolkit there is a better support for the namespacing , with the Toolkit we have an object named Type and we can use the method Type.registerNamespace :

<script type="text/javascript">
function pageLoad(sender, args) {
    window.alert(Type.isNamespace(comacme.klm.ticketing)); //displays 'True'
    window.alert(Type.isNamespace(comacme.klm.ticketing.Samples.Test)); //displays 'False'
    var namespaces = Type.getRootNamespaces();
    for (var i = 0, length = namespaces.length; i < length; i++) {
        window.alert(namespaces[i].getName()); //displays 'Sys' and  other namespace components

Ok , but we don’t use the Ajax Toolkit so let’s go back to our sample.

In the return section we indicate the public names, so cmdAddNew_onClick and numericSetvMax (functions, but also variables) are public , showEditBox is private and cannot be accessed.

That is in another javascript module we can write


and it works , instead


gives error, the internal routine is not reachable.

The variables declared correctly (with “var ” in front) remains private in the module.

This encapsulation , if well used, leads to a structure more maintainable.

Ok , but our original problem is that we could have a lot of existing js code written in the spaghetti-mode, how to convert this code to the module pattern with a minimal effort?

The Regular Expression in the Visual Studio 2012 search & replace is our tool.

We can convert an existing js file with a lot of function to the module pattern with these three couples of regexp expressions for search & replace:


$1$2 = function $3


Open the js file (better is you separe the js code form the aspx pages…) in Visual Studio, in Search & Replace (ctrl+h) click on Regular Expression

And write the first two search%replace strings:

Note that Visual Studio 2012 gives an preview of what the search expression has found (and will be replaced):

After the three search & replace we can see something as:

The last operation is to copy the converted code in the namespace structure (below “use strict”, in practice) , inserting in the “return” part the routines names that must be public.

After, there is a tedious work of searching for the original calls (must be added the namespace part) : but this effort should resolve a lot a problems.

Categories: .NET, Ajax, Javascript, JQuery, Vs2012

Unable to get property _focusTabbable

I was working with an .NET 4.5 project which was using jQuery 1.9.0, my js declarations was

<script src="" type="text/javascript"></script> 
<script src="" type="text/javascript"></script> 

Giving the fact that upgrading the jQuery version in an existing project is risky (see this my old post) i left the old declarations, but when i was verifying that all works as expected (inserting duplicated data) there was this error by clicking on every jQuery button after closing a jQuery dialog:

“Unable to get property ‘_focusTabbable’ of undefined or null reference”

This happened when my js code was simply displaying a message in a JQuery dialog: my work is to change the old , simple, plain “window.alert” with something better as user interface (remember that window.alert is really modal, the code is really stopped at the window.alert: with a modal jQuery dialog no!)

Effectively the Internet Explorer debugger shows the problem:

the object .data(“ui-dialog”) is null so the method ._focusTabbable() fails.

I found nothing of useful by googling, so i tried the very latest jQuery versions (at this moment, April 2013)

<script src="" type="text/javascript"></script> 
<script src="" type="text/javascript"></script>

With these latest versions of JQuery and jQueryUI the problem is disappeared, and it seems that there no problems related to the jQuery upgrade.

Categories: .NET, Javascript, JQuery