Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Reading a Local File using HTML5 and JavaScript

One area where the web has lacked for some time is the lack of a true file system.  HTML5 fills this void by providing a standard way of interacting with local files using the FIle API specification.

These APIs are used to read file locally, handling images etc. Some of the specifications are as listed below:

1. File: Provides read-only information about the file like name, filesize, mimetype etc.

2. FileList: Represents an array of individually selected files from the local system

3. Blob: Represents the raw binary data and allows access to range of bytes within the data which can be used for slicing file

4. FileReader: Provides methods to read data from file or Blob

Backbone.js Handling DOM events and working with Collections

Backbone.js is a lightweight JavaScript library loosely based on the Model-View-Controller (MVC) pattern (it’s not an MVC framework) and it allows developers to create single-page web applications. We covered some basics of Backbone in a previous article

To manage data of web applications, Backbone provides a Model creation strategy. The model allows us to define properties to contain data and business logic. The Collection declaration allows to store collection of the data, which is later used by the view.

In Backbone, the View (UI) is generally rendered using HTML Templates, and elements declared in this Template are accessible to View, but it might be possible that the HTML page (or MVC view or .aspx) already contains HTML elements and you need to handle the DOM events for these elements. The question then is how to handle them?

In the following implementation we will see that the ‘click’ event for the html button element is handled inside the View object. The method which gets executed for the click event is used to add the model object into the collection and then the collection is rendered using HTML Table.

The Absolutely Awesome jQuery Cookbook Released

Howdy! I am writing this post to announce the release of my new eBook The Absolutely Awesome jQuery Cookbook at www.jquerycookbook.com.

This book covers the latest jQuery v1.11.1 or 2.1 and jQuery UI 1.11.2 versions and contains 120+ practical jQuery recipes (about 70 Recipes and 50+ sub-recipes) you can use in your websites and projects right away. Each recipe includes working code, a live demo and a discussion on why and how the solution works. This eBook is available in PDF, .ePub and .mobi formats.

This book is primarily targeted for the everyday jQuery developer and designer who wants to enhance his/her websites and projects or wants to focus on the practical features of jQuery, and how they can be applied to solving real-world problems. The book assumes you have some working knowledge of HTML, CSS, jQuery and JavaScript. Although the first chapter ‘Getting started with jQuery & jQuery UI’ and the fifth chapter ‘Getting started with $.ajax()’ is a crash course introduction to jQuery and Ajax, I have provided links to additional resources, if you are relatively new to jQuery and want to make the best of this book.

You can download sample chapters over here

Using LocalStorage in HTML5 with JavaScript to manage data locally in a Browser

Cookies and HTML5 LocalStorage serve different purposes although they both store data on client-side. While Cookies are meant to be sent to the server with each request, HTML5 LocalStorage comes with the idea of storing data locally, without transmitting it to the server.

In the past, we have used cookies to save data generated by user, on the client side. But there have been multiple issues with cookies, mainly due to its insecure nature. Because of these issues, users browse the web by disabling cookies or deleting them from time to time.

In HTML5, a new standard web storage was created called as LocalStorage and sessionStorage. Typically these are really useful to save data in cases where:
  • Browser Crashes accidently.
  • User closes browser accidently
  • Internet connection lost.
In these cases, there are chances of losing data which an end-user might have already entered before losing it unexpectedly. One of the best feature of the LocalStorage is it is supported by all browsers (IE 8+, Chrome, Opera, Safari,Firefox). In this easy walkthrough we will implement simple mechanism of managing data through the LocalStorage.

Backbone.js Basics and Rendering Collection using View

In the current era of web application development, Single Page Applications (SPAs) are often demanded by customers. Currently there are lots of different frameworks available for developing web application, most of these are server side frameworks e.g. ASP.NET MVC. But one of the important aspects for Web development is to provide Rich user interface with UX (user experience). Thankfully there are several JavaScript client side frameworks available to get this thing done e.g. jQuery, Knockout, Backbone etc. Using these frameworks, a developer can develop Rich and better UX applications.

Backbone Basics

Backbone.js is a lightweight library for structuring client side code. This easily helps to decouple concerns in the application. Typically, this library is used to build SPA’s. The advantage of using backbone is that it provides lightweight data structuring mechanism using model and collection and helps to use these in generated Views. This is very important for designing dynamic applications using JavaScript. You can get detailed information from http://backbonejs.org/.

There are some important features provided by Backbone as discussed below:

KnockoutJS Cheat Sheet for Beginners

This cheat-sheet gives you a quick glance at what is Knockout, why to use it and how to use it. If you are a newcomer to KO or if you are juggling between multiple JS libraries, this cheat-sheet is a handy guide to get your KO karma flowing.

This article is from the Free DNC Magazine for .NET Developers. Subscribe here for Free

1. Knockout is a JavaScript Library (as opposed to Backbone.js which is a framework) that helps you improve the User Experience of your web application.

2. Knockout provides two way data-binding using a ViewModel and provides DOM Templating, it doesn’t deal with sending data over to server or routing.

3. You use Knockout as a drop-in enhancement library to improve usability and user experience, whereas Framework like Backbone is used to group up in new applications (Single Page Apps is a good example).

4. You can create a KO ViewModel as a JavaScript object or as a Function (known as prototype). It’s outside the jQuery document ready.

Hello AngularJS – Building a Tweet Reader

Single Page applications using client side JavaScript frameworks are getting popular and with the latest Web Update for Visual Studio 2012, quite a few SPA templates have been released by Microsoft and prominent Community members like John Papa. We have covered these templates in the past over here.

However these SPA templates are rather opinionated on the usage of the underlying frameworks and may not be the best starting point if we are trying to understand the framework under the hood. So today, we will look at AngularJS in a plain vanilla ASP.NET MVC app. We’ll start with an empty project and go ground up.

What is Angular JS?

Angular JS is (another) client side MVC framework in JavaScript. It was created by a group of developers at Google when they realized that their project (Feedback) had become too unwieldy and needed a cleanup. The three weeks effort at that cleanup lay seed to what we now know as AngularJS. Of course AngularJS was thrown open to community and since then had garnered a pretty vibrant community and a boat load of features.

Using FlipView Control in Windows Store Apps using JavaScript and HTML

For Windows Store Apps, WinJS has provided several controls for displaying data interactively. Some of the examples are SemanticZoom, GridView, ListView, FlipView etc. All these controls accept collection as data source and provides a mechanism so that end-user can easily navigate through it. On the SemanticZoom, I already have some information which you can find from Windows 8: Working with Semantic Zoom using C# and XAML.

FlipView, represents an item control which displays one item at a time and enables user to use the flip behavior which is used for traversing through the collection of items. Typically such a control is used for traversing through Product Catalog, Books information etc. Technically the FlipView is a control provided in Windows Store Apps through Windows Library for JavaScript. The data to FlipView is made available through IListDataSource. (Note: You can get data from an external web sources like, web service, WCF service, WEB API in the JSON format).

We will use the FlipView for iterating through Images that’s passed to it from the WinJS List object.

Step 1: Open VS2012 and create a new Windows Store Apps using JavaScript. Name it as ‘Store_JS_FlipView’. In this project add some images in the ‘images’ folder. (I have some images as Mahesh.png, SachinN.png,SachinS.png, KiranP.jpg).

Hello TypeScript – Getting Started

A first look at TypeScript and what it takes to get started with the newest language on the block from Microsoft using Visual Studio 2012.

What is TypeScript?

October 1, 2012 will probably be remembered in the history of Software Development when Microsoft Technical Fellow and father of C# Anders Hejlsberg announce TypeScript, a new Type conformant JavaScript. A language that compiles down to plain JavaScript but on its own has all the hallmarks of a language with first class tooling support in Visual Studio. If you have an hour to spare, go through Anders introduction, you’ll love it. If not, go through this article and you’ll get the gist. Bottomline, don’t start ranting too soon. TypeScript has a lot to offer.

Getting Started

Microsoft has made it really easy to get started with TypeScript. You have an online web-based code editor cum compiler. They also have a Visual Studio 2012 plugin that works on the Professional and above editions. Since a lot has been made about the benefits of ‘tooling’ while introducing TypeScript, we will download and install the TypeScript plugin.

Note: TypeScript is available in Sublime Text, Vi, Emacs editor

Once the Plugin is installed, start Visual Studio, find the Html Application with TypeScript. Strangely enough it goes under the Visual C# category hence it took a minute to find.

Use HTML 5 Elements in IE 8 using HTML 5 Shiv

There are a lot of new HTML 5 elements like <header>, <article>, <footer> etc. that browsers like IE 8 and versions prior to that, do not support. These browsers need some help recognizing the new HTML5 elements and Remy Sharp’s HTML 5 Shiv provides just that.

To use this script, it must be included before the <body> element (i.e. in the <head>).

To improve performance, include the CSS first and then this script. Here’s how to declare this script

<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]—>

This script enables IE to acknowledge the new HTML 5 elements by directing it to create the elements using JavaScript. The conditional comment shown above only loads the html5 shiv code when the version of IE is lower than 9.

You also need some CSS styling to render the elements as  block-level elements

image

Most Popular .NET, jQuery and Web Development articles in 2011

With 2012 fast approaching and 2011 drawing to an end, we've put together our list of the Most Popular .NET articles on DevCurry.com this year. The year 2011 featured articles on DevCurry covering many technologies like jQuery, HTML 5, ASP.NET, MVC, Silverlight, WPF, .NET, VS 2010, Entity Framework and Sharepoint, just to name a few.

I would like to thank each one of you who has visited my blog or contributed to it by submitting a Guest post, Subscribing to RSS Feed, by joining me on Twitter or the Facebook page or promoting the articles and giving regular feedbacks via rating, comments or Emails. Many thanks to those too who purchased my jQuery ASP.NET eBook.

Here are some articles that were liked the most by readers like you. Have a very Happy New Year 2012!

.NET Articles


jQuery & JavaScript Articles


HTML 5 & CSS Articles

JavaScript Quick Way to Find Max and Min Value in an Array

I have been using some JavaScript techniques in the past to find the maximum and minimum number in an array. I recently stumbled upon a real fast and simple solution to find the max and min number in an array and thought of sharing it with all of you. Let me know what do you think of this method.
Add these two methods in your code:

Array.prototype.max = function () {
    return Math.max.apply(Math, this);
};

Array.prototype.min = function () {
    return Math.min.apply(Math, this);
};

All you have to do now is call these methods on an array:
var max = [10, 12, 18, 24, 15].max();
var min = [10, 12, 18, 24, 15].min();
alert("Max Number: " + max + " Min Number: " + min);

The output is

image

The Math.max and Math.min can take unlimited arguments which is ideal when finding out the max and min in an array. The apply() function allows you to call a function with a this value and pass an array of any number of arguments. Starting with JavaScript 1.8.5, the arguments can be a generic array-like object instead of an array.

Prefix an Integer using JavaScript

While formatting numbers, prefixing an integer is a common operation. For example: If you have the 79, but you want to make it five digits always, just prefix it with three zeros – so it becomes 00079.

Let’s see how simple it is to prefix an integer in JavaScript. This script was originally shared by a programmer tobytai

<head>
<title>Prefix Integers with Zeros - DevCurry.com</title>
<script type="text/javascript">
function PrefInt(number, len) {
   return (Array(len).join('0') + number).slice(-length);
}
document.writeln(PrefInt(79, 4));
</script>
</head>

The OUTPUT is 00079.

If you are not familiar how the Slice() function works, check my article Slice() and Splice() in JavaScript

JavaScript: Find Day of Year

Here’s a simple script that finds the current day of the year

Current Day of Year

We first get the timestamp for the 1st day of the year - number of seconds elapsed since midnight Coordinated Universal Time (UTC) of January 1, 1970, not counting leap seconds. This is done using the following piece of code

var timestmp = new Date().setFullYear(new Date().getFullYear(), 0, 1);

The setFullYear() takes the year, month and day as a parameter. Since month in JavaScript ranges from 0 – 11, we have given the month as 0 i.e. January. The day is set to 1. For the year, we are doing new Date().getFullYear() which returns the current year 2011.

We then divide this timestamp by the total number of seconds in a day – 86400000. This gives us the number of days on Jan 1st of the current year, since the Unix epoch at January 1st 1970 midnight UTC

var yearFirstDay = Math.floor(timestmp / 86400000);

The next line calculates number of days since the Unix epoch at January 1st, 1970 midnight UTC till the current date, that is today.

var today = Math.ceil((new Date().getTime()) / 86400000);

At the end, we calculate the current day of the year by subtracting first day of the year – today.

var dayOfYear = today - yearFirstDay;

OUTPUT of the code if run today, is 217.

JavaScript, CSS3, Silverlight, ASP.NET, SharePoint articles Link List – July 2011

Here’s a quick wrap up of JavaScript, CSS3, Silverlight, ASP.NET, SharePoint and other .NET articles published on DevCurry.com in the month of July 2011.

jQuery, JavaScript and CSS Articles

jQuery: Load Page in a Div - Loading an external page in a div using jQuery is as simple as calling thejQuery Load method.

JavaScript: View Source code without Comments - One my clients had a requirement of viewing an object while debugging, and they wanted to view only the source code, without comments.

Array Shuffle in JavaScript - I have yet to find a script that truly does a random shuffle across all browsers using JavaScript (no frameworks). However there are a couple of scripts I use, that are ‘good-enough’ to be used when an Array has to be shuffled.

JavaScript Object can have Private Methods - I was watching a JavaScript video tutorial by Douglas Crockford where he explained private members in JavaScript. Although there are no ‘private methods’ in a JavaScript object, we can easily create something similar by defining a function variable with a local scope.

Unary plus operator in JavaScript - The unary plus (+) operator is a unary operator and converts its operand to a number, if it isn’t already. It is equivalent to the Number() constructor called as a function. Let us see some examples of the Unary + operator and what does it imply in different scenarios

Upside Down Text with CSS3 - When it comes to rotating, tilting or scaling text, you would normally rely on JavaScript or images laid on top of each other, to give that effect. However with the CSS3 transformation functions, you can do all of this without any JavaScript code

JavaScript: Convert CamelCase to Dashes and vice-versa - My colleague Satyam shared a nice piece of JavaScript code that converts a camelcase to dashes and dashes to Camelcase.

Text Shadow Filter in IE -  You can drop shadows to text using the text-shadow property which was re-introduced in CSS3.

Conditional CSS and JavaScript for Different Browsers - A common technique adopted by developers is to detect browsers and conditionally differentiate CSS rules and JavaScript for specific versions of browsers. In simple words, a requirement could be that if the browser is IE, use a different set of CSS and JavaScript files.

Free Photo Editors for Web Designers - A good photo editing software comes with a price, but here are some free open source photo editors that could do the job for you!

Swap Variables in JavaScript – Different Methods - Here are some different ways to swap variable values in JavaScript. I will show swapping using a temporary variable, without a temporary variable, XOR operator and a single line swap.

ASP.NET, MVC and Silverlight articles

ASP.NET MVC 3 Documentation Available in 10 Different Languages - As you probably know that localized versions of ASP.NET MVC 3 is available in 9 different languages via the Web Platform Installer. To supplement these releases, Phil Haack recently announced on his blog that now apart from English, the MVC 3 Documentation is also now available in these nine local languages

Silverlight 4: Consuming WCF REST Service using JSON - A nice feature of WCF programming is the support for REST and JSON, using which a client can communicate with the WCF service without using A proxy. In this article, I have used a Silverlight 4 client application to make a call to WCF service using JSON.

Silverlight 4.0 : Open .Exe Files using COM Interoperability - While working with Silverlight Line of Business applications, there may be a scenario where the user wants to open .exe applications e.g. Notepad or Calculator from the local machine. The question here is how to make this possible in Silverlight?

Silverlight 4 and 5 Tutorials–Link List - I recently published a list of Silverlight 4 and Silverlight 5 Tutorials that should be a useful resource for every Silverlight developer out there. 

ASP.NET: Accessing Nested Repeater Control - The ASP.NET Repeater control is a handy data-bound list control that allows you to create a custom layout by repeating a specified template for each item displayed in the list. You can nest a repeater control inside the other to create advanced layouts.

ASP.NET MVC Web Matrix & Razor Tutorials - In this list, we will see some articles written by our authors on WebMatrix and Razor syntax

Silverlight TextBox Numeric Validation - Although we have IDataErrorInfo interface for input data validation in Silverlight, it provides us validation error when the user enters the data and leaves the textbox. However the requirement we are talking about is when the user enters any data in the textbox, it should be automatically validated. This article contains the solution to this requirement.

.NET and SharePoint Articles

Windows Communication Foundation WCF 4.0 Tutorials - Author and Trainer Mahesh Sabnis has been writing some in-depth WCF 4.0 tutorials that I thought of sharing with all my blog readers. This tutorial series covers some basics and advanced concepts of WCF 4.0 programming

SharePoint 2010 Service Pack 1 Released - Microsoft recently released Service Pack 1 for SharePoint 2010 and Office Products.

SharePoint 2010 Content Database and Other Data Storage Changes - Microsoft recently announced some nice changes to SharePoint 2010 Data storage limits

"Partially Succeeded" TFS status in Visual Studio while upgrading to TFS 2010 - While upgrading from TFS to TFS 2010 and to TFS Team Build 2010, you may have come across the ‘partially succeeded’ message.

C#: Find Previous Month's First and Last Day - Here’s a simple query that gives you the first and last day of the previous month

WCF 4.0 : Discoverable Service - In this small article, I have explained the WCF 4.0 Discovery feature. This feature is used when the location of the service gets changed e.g. changing in the hosting environment or changing the physical address of the server etc

SharePoint 2010 and Azure Free Training - If you are a developer/architect who is interested in understanding how SharePoint 2010 and Windows Azure can leverage each other, then Microsoft recently released the July 2011 update of SharePoint 2010 & Windows Azure Training Kit.

Other Articles

Awarded the MVP Title – 4 Years in a Row - I was awarded the Microsoft MVP title again for the 4th consecutive year, and I thank Microsoft for bestowing this award on me.

BizTalk Server 2010 Training Kit and VHD - Microsoft has released the BizTalk Server 2010 pre-configured VHD and Training Kit to help you get started with BizTalk.

Create Social Games in Windows Azure - I recently stumbled upon the Windows Azure Toolkit for Social Games that includes accelerators, libraries, developer tools, and samples that can be used in games created using .NET or HTML5. The goal is to let game developers focus on development instead of operational hurdles.

Entity Framework 4.1 Update - If you are using Entity Framework to create data access applications, then there’s a new update to Entity Framework 4.1. EF 4.1 was announced in April. Microsoft has just released EF 4.1 Update 1 to fix some bugs as well as introduced some new types.

Visual Studio LightSwitch 2011 RTM Trial - Microsoft recently released the Visual Studio LightSwitch 2011 RTM. This tool is available for free to MSDN subscribers. However those who are not MSDN subscribers can download the RTM trial for 30 days.

Swap Variables in JavaScript – Different Methods

Here are some different ways to swap variable values in JavaScript. I will show swapping using a temporary variable, without a temporary variable, XOR operator and a single line swap.

Swap variable values using a temporary variable

// Using a Temp Variable
var x = 10;
var y = 20;
var tmp = x;
x = y;
y = tmp;
alert("Value of X=" + x + " and value of Y=" + y);

Swap variable values without a temporary variable
// Without using a temp variable
var x = 10;
var y = 20;
x = x + y;
y = x - y;
x = x - y;
alert("Value of X=" + x + " and value of Y=" + y);

Swap using Bitwise XOR operator
// Bitwise Exclusive OR operator
var x = 10;
var y = 20;
x ^= y;
y ^= x;
x ^= y;
alert("Value of X=" + x + " and value of Y=" + y);

Single line Swap (works in Firefox)
// JavaScript 1.7 and above
var x = 10;
var y = 20;
[x, y] = [y, x];
alert("Value of X=" + x + " and value of Y=" + y);

OUTPUT
JavaScript Swap variables
If you know of any other method to swap variable values in JavaScript, please share it with fellow readers.

Conditional CSS and JavaScript for Different Browsers

A common technique adopted by developers is to detect browsers and conditionally differentiate CSS rules and JavaScript for specific versions of browsers. In simple words, a requirement could be that if the browser is IE, use a different set of CSS and JavaScript files.

Let us see how to achieve this using conditional comments.

Conditional JavaScript

In the example shown above, if the browser is IE, iescript.js is included. For all other browsers, otherscript.js will be included. You can do the same for CSS files too.

Note: Devs use the technique of identifying browsers using vendor/version and other similar browser detection techniques. However these lead to what is termed as web maintenance nightmare and this technique is inappropriate. Instead of browser sniffing, what is recommended is ‘feature detection’. So if you have to execute code which relies on a browser feature, test it prior to the execution to ensure that the feature works properly.

JavaScript: Convert CamelCase to Dashes and vice-versa

My colleague Satyam shared a nice piece of JavaScript code that converts a camelcase to dashes and dashes to Camelcase.

For eg: if the string has a camelcase in it - like ‘viceVersa’, the result expected is ‘vice-Versa’. Similarly if a string has a dash in it, like ‘dot-net’, the result expected is ‘dotNet’. Let’s see the piece of code to make this possible:

<script type="text/javascript" language="javascript">
   function camelToDash(str) {
      return str.replace(/\W+/g, '-')
                .replace(/([a-z\d])([A-Z])/g, '$1-$2');
   }

   function dashToCamel(str) {
         return str.replace(/\W+(.)/g, function (x, chr) {
                          return chr.toUpperCase();
         })
   }

   var str1 = "devCurry"; 
   str1 = camelToDash(str1);
   var str2 = "dev-curry";
   str2 = dashToCamel(str2);
   alert(str1 + " " + str2);

</script>

Let’s see some important bits of the code shown above.

The /\W+/ pattern matches one or more of any of A-Z, a-z, 0-9, and the underscore character. The "g" (global) flag specifies that the search should find all occurrences of the pattern. The $1,$2,… property represents parenthesized substring matches.

Run the code and you should see the following output

JavaScript camelcase

Unary plus operator in JavaScript

The unary plus (+) operator is a unary operator and converts its operand to a number, if it isn’t already. It is equivalent to the Number() constructor called as a function. Let us see some examples of the Unary + operator and what does it imply in different scenarios

+new Date; // implies Number(new Date)
a + “” // implies String(a)
+a // implies Number(a), so “+1.2” becomes 1.2
a = null; a = +a; // value of a is now 0;
Unary plus is the preferred way of converting something into a number!


Note: The unary plus operator does not change the sign of an integer. So if the number is  negative, the unary + does not change the sign to a positive

JavaScript Object can have Private Methods

I was watching a JavaScript video tutorial by Douglas Crockford where he explained private members in JavaScript. Although there are no ‘private methods’ in a JavaScript object, we can easily create something similar by defining a function variable with a local scope.

As crockford says “If a value is a function, we can consider it a method”. Let us see a simple example that shows how to use a closure and hide a member.

JavaScript private method

Any attempt to call deleteEmployee will result in the following error:

JavaScript private method

Just keep in mind that by doing it this way, it cannot be a part of the prototype. Call it a hack, trick or a hidden feature, nevertheless it is a very useful tip to hide information inside a JavaScript Object!