Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Thursday, 3 September 2015

How to convert C# bool to Javascript boolean in Razor .cshtml views

I was wanting a clean way to convert a C# Boolean property on a view model into a javascript true / false bit of text for passing into our Typescript context settings constructors, and stumbled upon this way …

@Json.Encode(Model.BoolPropertyName)

clip_image002

Works a treat too!

clip_image004

Monday, 11 May 2015

How to retrieve nested property values in JavaScript / Typescript

Use the following function to retrieve the value of a property nested within another property in JavaScript...

 

export function retriveValueFromNestedProperty(objectToIterate: any, propertyName: string): any {

    var array: Array<string> = propertyName.split(".");

    var currentValue: any = objectToIterate[array[0]];

    for (var i = 1; i < array.length; i++) {

        currentValue = currentValue[array[i]];
    }

    return currentValue;
}

Monday, 23 February 2015

Windows 7 Weather Gadget: Cannot connect to service issue

Please follow this to fix the issue.

  1. Go to %localappdata%\Microsoft\Windows Live\Services\Cache
  2. Open "Config.xml" , Right click on it Select Edit, it will open in Notepad.
  3. Click on File>> Save (without doing any changes)
  4. Restart the Gadget after a Minute and it should start working.

However, it may be a temporary fix.  Many (myself included) report the problem returning. 

(Note: This fix appears to work, even if you're testing in IE10 with ActiveX settings as follows, using this code here http://jsfiddle.net/4aww6o3t/

and you get the Access is denied error from the call to oMSN.GetService("weather")

image

try
{
    // Connect to Weather Service .dll
    var oMSN = new ActiveXObject("wlsrvc.WLServices");
    var oMSN2 = new ActiveXObject("wlsrvc.WLServices");
    this.oMSN = oMSN.GetService("weather"); // Object to send and recieve weather data queries and to poll for service existence
    this.oMSN2 = oMSN2.GetService("weather"); // Object to send a latlong query and recieve a location code corresponding to the latlong
}
catch (objException)
{
    this.isValid = false;
    this.statusMessage = getLocalizedString('ServiceNotAvailable');
    this.oMSN = new Object();
    this.oMSN2 = new Object();
}

Update: 10:48 03/03/2015

Have just managed to write a batch file that fixes this issue ongoing. By adding this batch file to a scheduled task using the Task Scheduler, I've managed to get the gadget to always work now.

Note to use this batch file you'll just have to create a copy of the Settings.ini and call it Settings3Monitors.ini in the folder %userprofile%\AppData\Local\Microsoft\Windows Sidebar

taskkill /IM sidebar.exe /T /F

REM Fix for windows security update

pushd "%localappdata%\microsoft\windows live\services\cache"

IF EXIST ConfigOriginal.xml. (

     echo ConfigOriginal.xml file exists

) ELSE (

     copy Config.xml ConfigOriginal.xml

)

attrib "%localappdata%\microsoft\windows live\services\cache\*.xml" -r

del Config.xml

copy ConfigOriginal.xml Config.xml

echo. >> "Config.xml"

popd

REM Restart sidebar

pushd "%userprofile%\AppData\Local\Microsoft\Windows Sidebar"

xcopy /Y Settings3Monitors.ini Settings.ini

popd

start "" sidebar.exe

Monday, 2 February 2015

MVC / Jquery unobtrusive validation

http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-1

Also for how do attach a new client side method to unobtrusive validation e.g.

jQuery.validator.unobtrusive.adapters.add(adapterName, [params], fn);

see this article...

http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html

 

Note: For any element a in your <form>, you can do this to figure out what validation is attached to the containing <form> for that element...


$.data(a.form, "validator").settings.rules

e.g.

$.data(a.form, "validator").settings.rules.MiddleInitial
Object {maxlength: "1", __dummy__: true}

$.data(a.form, "validator").settings.messages.MiddleInitial
Object {maxlength: "The middle initial must be a single charater"}

Wednesday, 14 January 2015

How to do data dash data- attributes in Razor

Answer: Use an underscore

In the cshtml view file definition when declaring the attributes in the new {} object class for the attributes, use data_mycustomdataattribute to render out data-mycustomdataattribute

@Html.Hidden("controlName", "valueHere", new { @data_mycustomdataattribute = "testing dash"})

This will render the following...

<input data-mycustomdataattribute="testing dash" id="controlName" name="controlName" type="hidden" value="valueHere">

Thursday, 9 October 2014

How to remove history from chrome for a single site

1. Open the chrome://history/ page in Google chrome, and search for the site that you wish to delete history from.

image

2. Inspect the chrome://history/ page in F12 dev tools, then change the frame selected to target this history frame

image

3. Run the following javascript lines from the Console window (Esc)...

var checkBoxes =document.getElementsByClassName('entry-box');

for (i = 0; i< s.length; i++) {checkBoxes[i].childNodes[0].checked = true;}

document.getElementById('remove-selected').disabled = false;

4. Now just click the Remove selected Items button that should be enabled.

image

Alternatively as my colleague Joseph pointed out, you can just use this browser extension if you like,...

https://chrome.google.com/webstore/detail/better-history/obciceimmggglbmelaidpjlmodcebijb?hl=en

Search your history, then this will let you delete the search results.

Tuesday, 8 July 2014

Kendo DropDownList popup keep open alternative code using list property

Should you ever have the need to keep a kendo drop down list open using typescript, then the following example is how you should go about it with the latest kendo libraries that we're referencing

Note: The benefits of doing it this way is that you can strongly type all the typescript code, instead of relying on an undocumented extension property called popup off the drop down list control.

Typescript code:

export class AssignmentDashboard extends Base.HomePageBase {

private filterEventsDdLInitialized = false;

public filterEventsDdlInitialize: () => void = () => {

if (this.filterEventsDdLInitialized === false) {

var filterEventsDdl: kendo.ui.DropDownList = $("#viewEventListFilters").data("kendoDropDownList");

if (!this.isDefined(filterEventsDdl)) {

alert('viewEventListFilters drop down list widget not found');

return;

}

filterEventsDdl.list.on("mousedown", "*", (e: JQueryEventObject) => {

this.lastTarget = <HTMLElement>e.currentTarget;

});

filterEventsDdl.bind("close", (e: kendo.ui.DropDownListCloseEvent) => {

if ($.contains(e.sender.list[0], this.lastTarget)) {

e.preventDefault();

}

this.lastTarget = document.body;

//e.preventDefault(); // comment out for prod. use this to lock ddl during debugging/editing.

});

filterEventsDdl.list.on("click", "input", this.filterOptionChangeHandler);

this.filterEventsDdLInitialized = true;

}

}

CSHTML code:

attach the filterEventsDdlInitialize class method to the e.open event of the drop down in the cshtml… e.g.

.Events(e =>

{

e.Open("$(document).data('assignmentDashboardContext').filterEventsDdlInitialize");

})

e.g.

@(Html.Kendo().DropDownList()

.Name("viewEventListFilters")

.HtmlAttributes(new { style = "width: 240px;" })

.Height(410)

.BindTo(Model.FilterOptionsBinder)

.Text("Events")

.Value("Events")

.Events(e =>

{

e.Open("$(document).data('assignmentDashboardContext').filterEventsDdlInitialize");

})

.Template(tempHolder)

)

Friday, 20 June 2014

Fingerprint css in MVC web sites

http://madskristensen.net/post/cache-busting-in-aspnet

Optimizing for website performance includes setting long expiration dates on our static resources, such s images, stylesheets and JavaScript files. Doing that tells the browser to cache our files so it doesn’t have to request them every time the user loads a page. This is one of the most important things to do when optimizing websites.

In ASP.NET on IIS7+ it’s really easy. Just add this chunk of XML to the web.config’s <system.webServer> element:

<staticcontent>
<clientcache cachecontrolmode="UseMaxAge" cachecontrolmaxage="365.00:00:00" />
</staticcontent>

The above code tells the browsers to automatically cache all static resources for 365 days. That’s good and you should do this right now.

The issue becomes clear the first time you make a change to any static file. How is the browser going to know that you made a change, so it can download the latest version of the file? The answer is that it can’t. It will keep serving the same cached version of the file for the next 365 days regardless of any changes you are making to the files.

Fingerprinting


The good news is that it is fairly trivial to make a change to our code, that changes the URL pointing to the static files and thereby tricking the browser into believing it’s a brand new resource that needs to be downloaded.

Here’s a little class that I use on several websites, that adds a fingerprint, or timestamp, to the URL of the static file.

using System; 
using System.IO;
using System.Web;
using System.Web.Caching;
using System.Web.Hosting;

public class Fingerprint
{
public static string Tag(string rootRelativePath)
{
if (HttpRuntime.Cache[rootRelativePath] == null)
{
string absolute = HostingEnvironment.MapPath("~" + rootRelativePath);

DateTime date = File.GetLastWriteTime(absolute);
int index = rootRelativePath.LastIndexOf('/');

string result = rootRelativePath.Insert(index, "/v-" + date.Ticks);
HttpRuntime.Cache.Insert(rootRelativePath, result, new CacheDependency(absolute));
}

return HttpRuntime.Cache[rootRelativePath] as string;
}
}

All you need to change in order to use this class, is to modify the references to the static files.

Modify references


Here’s what it looks like in Razor for the stylesheet reference:

<link rel="stylesheet" href="@Fingerprint.Tag("/content/site.css")" />

…and in WebForms:

<link rel="stylesheet" href="<%=Fingerprint.Tag(" />content/site.css") %>" />

The result of using the FingerPrint.Tag method will in this case be:

<link rel="stylesheet" href="/content/v-634933238684083941/site.css" />

Since the URL now has a reference to a non-existing folder (v-634933238684083941), we need to make the web server pretend it exist. We do that with URL rewriting.

URL rewrite


By adding this snippet of XML to the web.config’s <system.webServer> section, we instruct IIS 7+ to intercept all URLs with a folder name containing “v=[numbers]” and rewrite the URL to the original file path.

<rewrite>
<rules>
<rule name="fingerprint">
<match url="([\S]+)(/v-[0-9]+/)([\S]+)" />
<action type="Rewrite" url="{R:1}/{R:3}" />
</rule>
</rules>
</rewrite>

You can use this technique for all your JavaScript and image files as well.

The beauty is, that every time you change one of the referenced static files, the fingerprint will change as well. This creates a brand new URL every time so the browsers will download the updated files.

FYI, you need to run the AppPool in Integrated Pipeline mode for the <system.webServer> section to have any effect.

Building a JavaScript Event Aggregator using TypeScript

 

http://www.wintellect.com/blogs/jlikness/building-a-javascript-event-aggregator-using-typescript

Jeremy Likness' Blog

Building a JavaScript Event Aggregator using TypeScript

The event aggregator is a useful mechanism for decoupling notifications. Typically, notifications happen through events. In JavaScript, an event is a notification that happens as the result of an action. You can think of it as a notification that is triggered by something. We call the triggering of the event “raising” the event. Events are a simple notification mechanism that contain a collection of handlers. A handler is really just a function that is called when the event is raised. The event may pass some information to the handler, and your function must react to the event.

Perhaps the most popular event in JavaScript is the “click” event. Events can be wired directly in HTML markup, like this:

<a id="homeLink" href="#home" onclick="alert('Go Home!')">Go Home</a>

A more sophisticated way to provide a handler is to do something like this:

var homeLink = document.getElementById('homeLink');
homeLink.onclick = function(e) {
   alert('Go Home!');
}

Here, the handler is assigned to the onclick function that is raised when the link is clicked.

Events are the core of interacting with HTML DOM. Many JavaScript frameworks provide a mechanism for you to extend JavaScript objects to participate in the event model as well. For example, using Backbone’s events you can register to an event that is triggered by a business object, and raise the event from the business object. This allows you to have events that are not tied to specific user actions in the DOM.

The event model makes sense for most cases. One complaint about this model is that it does force coupling. To register for an event, you must have a reference to the object or DOM element that triggers the event. You provide your handler directly to the source of the event. This is appropriate in most cases, because coupling isn’t always a bad thing. A common example of this is entering search criteria for a grid and pressing the search button.

The search criteria is often bound to a view model that contains properties for the search criteria. The search event will fire, and this will trigger a call to a service that passes the criteria and returns the results for the grid. While these actions should be decoupled to an extent (i.e. the view model will remain free of view-specific code to keep it testable and maintainable, and the service call is probably implemented in a separate function), it makes sense for the view model to be aware of the service because there is a direct action/reaction taking place – the action is to request the list of results and the reaction is to receive the list. Decoupling these (for example, simply sending a message that states, “I want data” and then having a completely separate mechanism to listen for the message “I have data”) can make the code confusing to follow, hard to troubleshoot and difficult to maintain.

There are a few scenarios such as cross-module communication and extensibility that make more sense from a highly decoupled perspective. For cross-module communication, for example, you may want to use an event aggregator. One module may focus on the process of searching for items and adding them to a shopping cart, while another module handles tracking the shopping cart. You may eventually add a third module and extend the application by providing a shipping estimation calculator that responds with a new total whenever items are added to the cart. In these cases, you can decouple the modules by sending a generic message that an item is selected, then build the other modules to receive that message and act on it.

To facilitate this, you can use the publisher/subscriber model as implemented by the event aggregator. The concept of an event aggregator is simple: you have a “broker” that manages notifications. All modules know about the broker, but not about each other, and publish messages to the broker. The broker maintains a list of subscriptions (modules “subscribe” to messages) and notifies the subscribers when a message is listed.

This pattern is a perfect example of how TypeScript can be used to build a facility without compromising the flexibility of the JavaScript language. TypeScript is a superset of JavaScript, so all valid JavaScript is also valid TypeScript code. Instead of trying to replace the language or force typing, TypeScript allows you to define contracts and types where they make sense and are expected, but retain full control over the power of the dynamic and function-oriented aspects of JavaScript.

I decided to start by developing an MVVM module I’ll call Gom because it’s the glue that we can use on the client to hold things together. I’m exploring this solely as a learning exercise as there are plenty of fantastic frameworks like KnockoutJS, AngularJS, and the framework built into Kendo UI that handle data-binding and enterprise concerns. In TypeScript, a module is like a namespace and can be simply defined like this:

module Gom {
}

That’s it – now I can start defining classes and methods that are specific to my module. The first thing I want to keep track of is subscriptions. A subscription is simply a callback – it’s a function that should be called when a notification is sent (or an event is raised). In this model, I’ll give the subscription an identifier as well so the listener can unsubscribe if it is no longer interested in the notification:

class Subscription {
    constructor (           
        public id: number,
        public callback: (payload?: any) => void) {
    }       
}

Note the signature for a function can be declared using a lambda-style expression, showing the parameters that are expected and the return type. The implementation of the class in JavaScript is a self-invoking function scoped to the Gom module:

var Subscription = (function () {
    function Subscription(id, callback) {
        this.id = id;
        this.callback = callback;
    }
    return Subscription;
})();   

What’s nice is that I don’t have to worry about things like creating a constructor or wrapping the function – TypeScript does that for me. Next, I’ll create an interface for a message. Think of a message as a “channel.” I can send a type of message (giving it a name), and I’ll keep track of all subscriptions for that message. It is assumed that both publishers and subscribers understand how to deal with the content of messages that have the same name. In TypeScript, interfaces have no actual JavaScript implementation. They simply provide compile-time checks, design-time auto-completion and help keep your code clean and make it easier to build and maintain.

interface IMessage {
    subscribe(callback: (payload?: any) => void): number;
    unSubscribe(id: number): void;
    notify(payload?: any): void;
}

The subscription takes a callback which has the signature of expecting any type of object (optional) and returning nothing (this is the function the listener will implement) and returns a number (the token for the subscription so it can be unsubscribed). The unsubscribe function takes the identifier, and the notify function takes an optional payload.

We can now implement the interface:

class Message implements IMessage {

    private _subscriptions: Subscription[];
    private _nextId: number;

    constructor (public message: string) {
        this._subscriptions = [];
        this._nextId = 0;
    }

    public subscribe(callback: (payload?: any) => void) {
        var subscription = new Subscription(this._nextId++, callback);
        this._subscriptions[subscription.id] = subscription;
        return subscription.id;
    }

    public unSubscribe(id: number) {
        this._subscriptions[id] = undefined;                       
    }

    public notify(payload?: any) {
        var index;
        for (index = 0; index < this._subscriptions.length; index++) {
            if (this._subscriptions[index]) {
                this._subscriptions[index].callback(payload);
            }
        }
    }
}

Notice how the message maintains it’s own list of subscriptions. For efficiency, it keeps the subscriptions in their assigned slots and simply sets them to undefined when they are unsubscribed. A notification simply iterates through the array and sends the payload to the subscriptions. Empty slots are skipped.

The implementation in JavaScript is again as self-invoking function that scopes the variables appropriately. Note the public functions are class-wide and therefore assigned to the underlying prototype for the object:

var Message = (function () {
    function Message(message) {
        this.message = message;
        this._subscriptions = [];
        this._nextId = 0;
    }
    Message.prototype.subscribe = function (callback) {
        var subscription = new Subscription(this._nextId++, callback);
        this._subscriptions[subscription.id] = subscription;
        return subscription.id;
    };
    Message.prototype.unSubscribe = function (id) {
        this._subscriptions[id] = undefined;
    };
    Message.prototype.notify = function (payload) {
        var index;
        for(index = 0; index < this._subscriptions.length; index++) {
            if(this._subscriptions[index]) {
                this._subscriptions[index].callback(payload);
            }
        }
    };
    return Message;
})();   

All of the classes so far have been scoped internally to the module. This means they are local to the self-invoked function that defines the module, but not available externally. You can’t directly create a Message instance. Instead, I expose an EventManager class. This isexported in TypeScript so it can be referenced externally from the module. The event manager handles a list of messages and exposes the various operations:

export class EventManager {

    private _messages: any;

    constructor () {
        this._messages = {};
    }

    subscribe(message: string, callback: (payload?: any) => void ) {
        var msg: IMessage;           
        msg = this._messages[message] ||
            <IMessage>(this._messages[message] = new Message(message));
                      
        return msg.subscribe(callback);                       
    }
       
    unSubscribe(message: string, token: number) {           
        if (this._messages[message]) {
            (<IMessage>(this._messages[message])).unSubscribe(token);
        }
    }

    publish(message: string, payload?: any) {
        if (this._messages[message]) {
            (<IMessage>(this._messages[message])).notify(payload);
        }
    }
}

Now you can see some more powerful TypeScript features at work. The subscriptions simply exist as properties on the main _messages object. When a subscription comes in, the existence of the Message instance for that subscription is checked, otherwise it is created. The <IMessage> casts the result so you can use auto-complete (type msg and hit the period and you’ll see the list of available methods). This example passes the subscription through to the message.

To unsubscribe the function first checks that the message exists, and only if it does, it passes the token down to unsubscribe. Finally, the publication checks for the existence of subscriptions (if no one subscribed, there is no one to notify) and then passes the payload through. The generated JavaScript (note the assignment to the Gom module so it is available for external consumption):

var EventManager = (function () {
    function EventManager() {
        this._messages = {
        };
    }
    EventManager.prototype.subscribe = function (message, callback) {
        var msg;
        msg = this._messages[message] || (this._messages[message] = new Message(message));
        return msg.subscribe(callback);
    };
    EventManager.prototype.unSubscribe = function (message, token) {
        if(this._messages[message]) {
            ((this._messages[message])).unSubscribe(token);
        }
    };
    EventManager.prototype.publish = function (message, payload) {
        if(this._messages[message]) {
            ((this._messages[message])).notify(payload);
        }
    };
    return EventManager;
})();
Gom.EventManager = EventManager;  

Now I can demonstrate the pub/sub model through a simple page. Here is the full mark-up. The TypeScript is compiled to a corresponding JavaScript file that is referenced.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>GOM - MVVM Glue for JavaScript</title>   
</head>
<body>
    <div><input id="txtMessage" value=""/></div>
    <div><input type="button" id="btnSubmit" value="Publish"/></div>
    <div>
        <h1 id="header">Pub/Sub Example</h1>
        <p id="paragraph">Type a message in the box and click "publish" to continue.</p>
    </div>
    <script src="Scripts/GomEvents.js"></script>
    <script type="text/javascript">
        var events = new Gom.EventManager();
       
        var token = events.subscribe("message", function(msg) {
            document.getElementById("header").innerText = msg;
        });

        (function(tok) {
            events.subscribe("message", function(msg) {
                document.getElementById("paragraph").innerText = msg;
                events.unSubscribe("message", tok);
            });
        })(token);       

        document.getElementById("btnSubmit").onclick = function() {
            events.publish("message", document.getElementById("txtMessage").value);
        };

    </script>
</body>
</html>

This is a very simple example but it illustrates the working event aggregator. Two subscriptions are made, one that will listen for the message called “message” and update an H1 tag, another that listens to the same message and updates the P tag. The second listener will also try to unsubscribe the first listener. The result is that the first message will update the H1 and P tags, while subsequent messages only update the P tag. Finally, a click event is wired to obtain the contents of the text box and publish the message. This is of course a contrived example to illustrate the implementation.

While you would never use the event aggregator for such as simple case, let’s go back to the original scenario of a shopping cart. The payload can be any type of object. In the shopping cart example, you could serialize an item added to the cart into JSON, then publish a “cartAdded” message with that as the payload. The cart module could then receive and track that item, while the shipping estimation module receives the same payload and uses it to estimate the shipping costs.

I believe TypeScript made it easier to design and build the implementation by using a class structure, while still generating clean JavaScript code. The resulting code can be consumed by any other code and doesn’t require TypeScript. More importantly, however, developers in a large enterprise project will now be able to reference the module and consume the contents with full IntelliSense, making it a lot easier to explore APIs and understand what they expect. Here’s an example of auto-completion in the IDE – note that I get a list of available functions as well as their complete signature:

typescriptintellisense

You can download the source for this post here. I leave you with this working example:

Click here to view in a new window.

Enjoy!

Wednesday, 21 May 2014

BrowserLink and other new VS 2013 features

Perhaps the most significant enhancement to creating web applications in Visual Studio for many years. Check out how you can edit your pages in line in the browser, and it updates the source code back in visual studio directly, using the new BrowserLink feature...

http://www.asp.net/visual-studio/overview/2013/visual-studio-2013-web-editor-features-browser-link

More features worth a look are all listed under the parent page here...

http://www.asp.net/visual-studio/overview/2013

Monday, 10 March 2014

Wednesday, 11 December 2013

Altering the HTTP response using Fiddler

Should you ever have the need to change the http response to a web server, then please note in the latest version of Fiddler it's actually possible to do this without having to hack the CustomRules.js file that the Fiddler training videos and documentation tell you about.

You can simply set up an AutoResponder tab rule as follows

1. Stick a file in %userprofile%\Documents\Fiddler2\Captures\Responses folder

2. Highlight the request you want to set up a rule for

3. Got to the AutoResponder tab and check Enable automatic responses and unmagtched requests passthrough

4. Click Add rule

5. In the dropdown list control at the bottom, select the file that you dropped in the folder in step 1 above.

6. Hit the save button

7. Clear the Cache

clip_image001

Now next time you request that resource, the version you have saved on disk will be downloaded instead. You can check this by looking in the IE cache folder %userprofile

%userprofile%\AppData\Local\Microsoft\Windows\Temporary Internet Files

More detail about request and response breakpoints in fiddler here… (this is very useful should you wish to change the request going to the server in the first place as well)…

http://www.youtube.com/watch?v=8bo5kXMAcV0&list=PLvmaC-XMqeBbw72l2G7FG7CntDTErjbHc&index=2

P.S. For more powerful / permanent debugging solution you can just alter the fiddler customrules.js as follows

static function OnBeforeResponse(oSession: Session) {

        if (m_Hide304s && oSession.responseCode == 304) {

            oSession["ui-hide"] = "true";

        }

if (oSession.uriContains("Name=ViewerScript")) {

                                                oSession["x-replywithfile"]="Reserved.ReportViewerWebControl.axd";

                                }

    }

Thursday, 5 December 2013

Microsoft Virtual Academy - ASP.NET MVC

I’ve just got into the Microsoft Virtual Academy, and I have to say it has a wealth of up to date, excellent training videos.

http://www.microsoftvirtualacademy.com/Content/ViewContent.aspx?et=4099&m=4093&ct=19601#?fbid=_Oyn-vcRqgr

Razor syntax escape characters…

image

Html anti forgery token..

http://blog.stevensanderson.com/2008/09/01/prevent-cross-site-request-forgery-csrf-using-aspnet-mvcs-antiforgerytoken-helper/

ASP.NET MVC 4 Content Map

http://www.asp.net/mvc/overview/getting-started/aspnet-mvc-content-map

Script including - always use the longhand version for the <script></script> tag, otherwise your script file will not be downloading to the client browser

JSBin.com - http://jsbin.com/ a fantastic javscript, jquery, html and css online playground like jsfiddle.net and plnkr.co. The nice thing about this one though is that you can download the entire finished article file as a single html page.

What's coming in ASP.NET - www.asp.net/vnext

Signed nightly builds of asp.net vnext - https://aspnetwebstack.codeplex.com/

Getting started with web api - http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

Web API 2 (video) - http://channel9.msdn.com/Events/Build/2013/3-504

Wednesday, 18 September 2013

Preload Images with CSS, Javascript or Ajax

See here for many ways to achieve this...

http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/

Personally I'm sticking with the following...

http://jsfiddle.net/chafferm/VU2dq/

Note the type check for array in this example is probably overkill, as it is for all browser versions, we could have used jQuery isArray instead, or even Array.isArray in ECMA script 5 (IE 9 or higher).

Saturday, 24 August 2013

Plunkr Noughts And Crosses Game

Spent some time with my new favourite javascript online editor of the moment http://plunkr.co. I've found I can use my tablet, an iPad and even a smart phone to edit my HTML using this editor, although most of the time it's done using Google Chrome on a laptop.

My daughter and I find this game is best played with two wireless mouse devices plugged into the laptop, and you take it in turns to move the pieces into the squares.

P.S. Some hidden gems in Plunkr are the keyboard shortcuts:

Ctrl+S = Save
Ctrl+Up/ Ctrl+Down = Cycle through files
Ctrl+Enter = Preview / Run your code

To run the game, click here:
http://run.plnkr.co/plunks/kLcfW2/

To edit the code, feel free at this link:

http://plnkr.co/edit/kLcfW2?p=preview

Plunkr - Noughts and Crosses Game

Thursday, 17 January 2013

Project Silk for all your HTML web application needs

A colleague of mine pointed out this white paper article that Microsoft have kindly put together, which appears to be a full overview on how to construct a web site in this day an age.

"Guidance for building cross-browser web applications with a focus on client-side interactivity. These applications take advantage of the latest web standards like HTML5, CSS3 and ECMAScript 5 along with modern web technologies such as jQuery, Internet Explorer 9, and ASP.NET MVC3"

http://silk.codeplex.com/

You can also download it all in pdf format from the following link

http://www.microsoft.com/en-us/download/details.aspx?id=27290

Friday, 28 December 2012

Javascript framework performance tester

Came across this little gem for testing the performance of javascript frameworks in your browser. Interesting to see how each browser performs...
http://jsperf.com/angular-vs-knockout-vs-ember/2
Also this is quite a good reference for all the difference frameworks that are out there at the moment to choose from
http://addyosmani.github.com/todomvc/
Performance test results for various browsers as follows...
IE 8.0 32-bit on Windows 7 64-bit
image
Chrome IE 9 32-bit on Windows 7 64-bit
image
Chrome 23.0.1271.97 32-bit on Windows 7 64-bit
image

Wednesday, 31 October 2012

Beware the perils of Javascript

These two links are definitely worth a read I think...

http://oreilly.com/javascript/excerpts/javascript-good-parts/bad-parts.html

and especially…

http://oreilly.com/javascript/excerpts/javascript-good-parts/awful-parts.html

e.g.

Semicolon Insertion

JavaScript has a mechanism that tries to correct faulty programs by automatically inserting semicolons. Do not depend on this. It can mask more serious errors.

It sometimes inserts semicolons in places where they are not welcome. Consider the consequences of semicolon insertion on thereturn statement. If a return statement returns a value, that value expression must begin on the same line as the return:

return

{

status: true

};

This appears to return an object containing a status member. Unfortunately, semicolon insertion turns it into a statement that returns undefined. There is no warning that semicolon insertion caused the misinterpretation of the program. The problem can be avoided if the { is placed at the end of the previous line and not at the beginning of the next line:

return {

status: true

};

How to find the last interactive logons in Windows using PowerShell

Use the following powershell script to find the last users to login to a box since a given date, in this case the 21st April 2022 at 12pm un...