Skip to content

Manas Bhardwaj's Stream Posts

Get Unique Values from a JavaScript Array using jQuery

I have seen this question so many times on forums, so decided to put it as tip. Here is a simple code snippet to get unique list of values out of JavaScript array. It makes use of jQueryto do a look up.


function GetUnique(inputArray)
{
	var outputArray = [];
	for (var i = 0; i < inputArray.length; i++)
	{
		if ((jQuery.inArray(inputArray[i], outputArray)) == -1)
		{
			outputArray.push(inputArray[i]);
		}
	}
	return outputArray;
}

If you enjoyed this article, please consider sharing it!

Further Reading:

JavaScript Prototype Chains, Scope Chains, and Performance: What You Need to Know

Don’t SharePoint While Walking

I received this email from someone by the name of Mike Harmon (fake?) from harmon.ie. From the web site, it looks like they are into product development using the SharePoint platform.

harmon.ie

In any case, the you tube video seems to be quite intuitive marketing. And something very unlikely when you really talk about SharePoint 🙂

Disclaimer: I have no relation with harmon.ie and have used tried their product.

3 reasons why I love ReSharper

ReSharper is a renowned productivity tool developed by JetBrains that makes Microsoft Visual Studio a much better IDE. It   brings smart C# code analysis, editing, highlighting and refactoring features to .NET developers. ReSharper extends much of its support to VB.NET, build scripts, ASP.NET, XML, and XAML files. All features are available in mixed solutions where different projects use .NET Framework, .NET Compact Framework, Silverlight, as well as other frameworks and tools from the Visual Studio ecosystem.

I have hardly ever used an add-on with Visual Studio while using it more than decade or so. I never felt an urge to use one and always believed that Visual Studio is one of the best IDE present in the market, in fact it is. Fortunately or unfortunately, our team decided to throw away the (outdated and self-proclaimed) coding standard we were using. This led to a search to find a better tool which can help us a team in doing so. ReSharper came as one of the top search result in Google. Not sure because of relevance or as a sponsored result, but that’s a different story.

Having said so, I have been using this add-on (trail version) for almost three weeks now and simply cannot believe how I managed to do without. It is certainly addictive. Apart from all the features JetBrains has listed on their website, here are 5 reasons why I love ReSharper:

  • Conventions: One of the most striking and handy feature. As a developer, I don’t really have to bother and remember the naming conventions. ReSharper helps me and signals any deviation as I type my code. This means, no longer I have to create lengthy documents and indoctrinate new programmers about the conventions we use as a team.
    A definite PLUS while doing code reviews. All those deviations should have already been taken care of by the developer himself and if not it will just strike through immediately while you are at it.
  • Code Editing Helpers: Another magical feature. I had this project where someone had written a NICE nested foreach loop. I noticed that ReSharper had few suggestions to it. It suggested that a better Linq statement can be used instead of loop. And not only has it suggested, it does it for you. Pretty handy as feature even if you want to learn new, better ways and syntax to write code.
  • Code Smells:  This is how they market the feature. But it really works. ReSharper can tell you if there is a possible NULL reference exception. Very handy when you have a lot of junior developers working on the team. This is one of those scenarios which is most likely to happen if the developer has made an assumption on his own.

Apart from that here are my general observations:

Good:

  • Suggests good coding practices as we type
  • Good refactoring support
  • Supports xml files also for refactoring

Bad:

  • Seems to take a lot of resources

Features personally liked:

  • grey out unused using statements and variables in the editor
  • suggestions to convert string literals to constants when used with hard coded values
  • suggests naming conventions for namespaces, variables etc.
  • suggestions to change the scope of variables to inner most code block
  • suggestion to use object initializers
  • suggestions for possible exceptions in code
  • and a lot more

Action Learning and Action Research

Even though Action Learning and Action Research may look like similar topic at the surface. The two have fundamentally different approach.

(Zeichner, 2001) and (Hopkins, 2002) provided with an overview of how action research developed as a research tradition. The work of Kurt Lewin (1946), who researched extensively on social issues, is often described as a major landmark in the development of action research as a methodology. Lewin’s work was followed by that of Stephen Corey and others in the USA, who applied this methodology for researching into educational issues.

(Koshy, 2005) defines action research as an enquiry, undertaken with rigour and understanding so as to constantly refine practice; the emerging evidence-based outcomes will then contribute to the researching practitioner’s continuing professional development. He further commented that Research is about generating new knowledge. Action research creates new knowledge based on enquiries conducted within specific and often practical contexts. Figure below illustrates the spiral model of action research proposed by Kemmis and McTaggart.

Capture

The first glance of the action research spiral gives a quite high resemblance to the action learning cycle presented by (Zuber-Skerritt, 2000), but there are quite few fundamental differences between the two methodologies.

According to (Zuber-Skerritt, 2001), ‘Action Learning’ means learning from and through action or concrete experience, as well as taking action as a result of this learning. Similarly, ‘Action Research’ is a cyclical iterative process of action and reflection on and in action. He further emphasized that, the main difference between ‘Action Learning’ and ‘Action Research’ is the same as that between learning and research generally. Both include active learning, searching, problem solving and systematic inquiry. However, Action Research is more systematic, rigorous, scrutinized, verifiable, and always made public (in publications, oral or written reports). Figure : Commonalities of Action Learning and Action Research shows where Action Learning and Action Research overlap.

Capture1

According to (Dick, 1997), Action research is a process by which change and understanding can be pursued at the one time. It is usually described as cyclic, with action and critical reflection taking place in turn. The reflection is used to review the previous action and plan the next one. It is commonly done by a group of people, though sometimes individuals use it to improve their practice. It has been used often in the field of education for this purpose. It is not unusual for there to be someone from outside the team who acts as a facilitator.

(Dick, 1997) further mentioned the difference between action learning and action research that in action learning, each participants drew different learning from different experience. In action research a team of people drew collective learning from a collective experience.

 

CodeProject Most Valuable Professional for 2013

After a painful start and a root canal treatment already in the first week of the year, something fruitful happened. Just got an email from CodeProject that I’m being nominated for Most Valuable Professional (MVP) for 2013. Thanks to CodeProject and all the fellow community members for support and appreciation.

MVP Email

A complete list of 40 CodeProject MVPs this year is available at:

http://www.codeproject.com/script/Awards/MVPWinners.aspx

From Code Project Newsletter:

Each year we have a tradition of awarding the members who have worked the hardest, helped the most, and given their all for the community. There are two main categories: those who write articles and those who help in the forums and in Quick Answers. You, our members, vote for these articles, for their answers, you download code that’s been posted, bookmark articles and “accept” an answer as the right one. Each small activity adds to the contributors points tally and at the end of the year we have a list of the brightest and the best.

Snakes and Ladders – An attempt using HTML5

Introduction

This article is intended to demonstrate the very simple and crude implementation of Snakes and Ladders game using HTML5. Recently, I started to dig deeper into HTML5. By the time I came to canvas part, this game was one of the candidates which I wanted to try with. For those of you who have never heard of this game, here is a Wiki article about it.

Demo

Find a working demo of this game here.

Snake & Ladder Demo

Background

Though, this game is usually played as a dual player. The current implementation is a single player and is more intended to show the concepts used and the potential behind it. Before I actually start explaining the code and implementation, I would like to touch the background by explaining the HTML Canvas element which is heart of the game. I assume that everyone reading this article would have heard about HTML5 by now.

HTML5 is the successor of HTML4. HTML4 was standardized in 1997 and since then a lot has change in the internet industry. Thus, there a demand for next standardized version of HTML to improve the language and at the same time support the various multimedia blocks which have almost become regular to usage in web development. In general, HTML5 includes many syntactical features like video, audio, canvas, etc. We will be briefly going through Canvas element before proceeding to its usage in Snakes & Ladders game.

Canvas

Canvas as the word suggests is a new element introduced in HTML5 which can be used to draw graphics using java script. It can be used to draw shapes, images and animations. It promises to make like easier for designers, animators by standardizing (we all know the absence of flash on iPads/iPhones).

The canvas element isn’t supported in some older browsers, but is supported in Firefox 1.5 and later, Opera 9 and later, newer versions of Safari, Chrome, and Internet Explorer 9.

Using the code

Well, let’s walk through the code to see the use of canvas in developing the game.

I started with a simple HTML page which contains a canvas element.


<!DOCTYPE html>
<html>
<head>
    <title>Manas Bhardwaj's Snake & Ladder</title>
</head>
<body>
    <canvas id="board" width="650" height="650">
    </canvas>
</body>
</html>

Context

The next step would be access this canvas element using java script.


var canvas = document.getElementById("board");
var context = canvas.getContext("2d");

In the first line we retrieve the canvas DOM node using the getElementById method. We can then access the drawing context using the getContext method. canvas creates a fixed size drawing surface that exposes one or more rendering contexts, which are used to create and manipulate the content shown. We’ll focus on the 2D rendering context.

Drawing Squares


function RenderSquareBoard() 
{        
    var colorA = "white";
    var colorB = "red";

    var initRow = 1; var totalRows = 10; var initcolumn = 1; var totalColumns = 10;

    var x = 0; var y = canvas.height - squareSize;

    var columnNr = 1; var leftToRight = true;
    for (var row = initRow; row <= totalRows; row++) 
    {
        if (leftToRight) 
        {
            x = 0;
        }
        else 
        {
            x = canvas.width - squareSize;
        }

        for (var column = initcolumn; column <= totalColumns; column++) 
        {
            if (columnNr % 2 == 0) 
            {
                context.fillStyle = colorA;
            }
            else 
            {
                context.fillStyle = colorB;
            }

            context.fillRect(x, y, squareSize, squareSize);

            squares[columnNr] = x.toString() + ',' + y.toString();

            contextText.font = "15px tahoma";
            contextText.fillStyle = "black";
            contextText.fillText(columnNr, x, y + squareSize);

            var x1, y1;
            if (leftToRight) 
            {
                x += squareSize;

                x1 = x + (squareSize / 2);
            }
            else 
            {
                x -= squareSize;
                x1 = x - (squareSize / 2);
            }

            y1 = y - (squareSize / 2);

            columnNr++;
        }

        y -= squareSize;
        leftToRight = !leftToRight;
    }
}

Apart from the logic how I build the different squares and keep their co-ordinates for later use to plot the player moves, the import aspect we will see here is draw a rectangle. Canvas only supports one primitive shape – rectangles. All other shapes must be created by combining one or more paths. It was at east handy for me as I did not have to do anything extra for that and could use the in-built functionality.

There are three functions that draw rectangles on the canvas:

fillRect(x,y,width,height): Draws a filled rectangle
strokeRect(x,y,width,height): Draws a rectangular outline
clearRect(x,y,width,height): Clears the specified area and makes it fully transparent.

Drawing Images


function RenderSnakeAndLadders()
{
    var img = new Image();
    img.onload = function () 
    {
    context.drawImage(img, 66, 23);
    };
    img.src = "Images/SnakeA.gif";
}

Importing images is basically a two step process. Firstly we need a reference to a JavaScript Image object or other canvas element as a source. It isn’t possible to use images by simply providing a URL/path to them. Secondly we draw the image on the canvas using the drawImage function.

The GAME

I used two snakes and two ladders in my example to keep it simple. If a player falls on a ladder he climbs up the ladder and thus does not have to cover the whole path. Against this, if a player falls on Snake’s mouth he slips down to the tail. On the click of a button, I generate a random number between 1 and 6. The position of the player is changed based on his score and a new rectangle is drawn to show his new location.


function nextMove() 
{
	var newMove = GenerateRandomNumber(6);
	alert("You got : " + newMove);

	_currentPos = _currentPos + newMove;

	switch (_currentPos) 
	{
	//ladder
	case 6:
	_currentPos = 46;
	break;
	//ladder
	case 39:
	_currentPos = 79;
	break;
	//snake
	case 99:
	_currentPos = 29;
	break;
	//snake
	case 72:
	_currentPos = 2;
	break;             
	}

	var coorintaes = squares[_currentPos];
	coorintaes = coorintaes.split(',');

	context.fillRect(coorintaes[0], coorintaes[1], squareSize, squareSize);

	if (_currentPos == 100)
	{
		alert("Congratulations, you have won the game :)");
		initGame();
	}
}

A Google Doodle for my own birthday

That was a big surprise this morning when I logged on to my computer. Though, I haven’t set Google as my home page on Internet Explorer (Yes, I still use IE :), but as a (bad) habit directly type the google.com. There was a colleague standing next to me, and after looking at Google Doodle, I told him that it looks like some great guy also happens to be born on the same date as of mine. And by the time I hovered over the Doodle, it was really a big fat surprise, Google had customised the doodle for my own birthday with alternate text ‘Happy Birthday Manas!‘.

Frankly, quite impressive.

Hey Google, Many thanks for remembering!!! 😉

Manas Bhardwaj Birthday Google Doodle

P.S. : Dear facebook, twitter: Were you sleeping this morning or just not bothered about it?

Accessing C# Variables in JavaScript

Introduction

So often I come across this question on various forums that ‘How to access the variables/properties from C# in Javascript?’. And this is one of the scenarios which you are (most) likely to come across if you are writing an ASP.Net application.

For most beginners, it might get confusing as they start wondering how to pass on information from a server side variable to client side.

Solution

The one shortcut we used to used during the (good old) ASP days, and which still works in ASP.NET is to declare a public property in codebehind. Let us say we declare a string variable firstName in codebehind.


public string firstName = "Manas";
public string lastName = "Bhardwaj";

Now, we can access this in aspx page/javascript like this:


<script>
var myName;
function GetMyName()
{
	myName = <%=this.firstName%> + ' ' + <%=this.lastName%>;
	alert(myName);
}
</script>

To do it nicely, you can use RegisterClientScriptBlock. RegisterClientScriptBlock accepts the following parameters:
Type: The type of the client script to register.
key: The key of the client script to register.
script: The client script literal to register.
addScriptTags: A Boolean value indicating whether to add script tags.


string script = string.Format("var myName = '{0} {1}';", firstName, lastName);
if (!ClientScript.IsClientScriptBlockRegistered("myScript"))
{
    ClientScript.RegisterClientScriptBlock(typeof(_Default), "myScript", script, true);
}

Once done, the variable ‘myName’ is available at the client side (javascript in aspx page) and can be accessed like:


<script>
function GetMyName()
{
	alert(myName);
}
</script>

Windows Azure : Failed to delete Storage account

I have been playing with my recently setup Windows Azure account. Nothing substantial, but have been creating and deleting VMs, websites.
But this morning I noticed that I have setup a Storage Account as well, which I did not remember setting up. After trying again and again to delete the storage, I was getting the following error:

“Storage account **************** has 1 container(s) which have an active image and/or disk artifacts. Ensure those artifacts are removed from the image repository before deleting this storage account.”

After some research, I got to know that one of disks which was created with VM was still there and it needs to be deleted before removing the stuff from storage account. If you want to delete the storage account, you need to delete any images/disks you have remaining in that storage account.

Go to Virtual Machines -> “Disks” or “Images” tab -> select the images/disks that you have located in the Storage Account you want to delete -> then hit the “Delete disk” or “delete image” command. Back these up if you need before hitting the delete.

Once the images/disks in the storage account have been deleted, you should be able to delete the storage account.

Session log at TechEd 2012

Here is a list of sessions I attended in 4 days at TechEd. Must say that most of them were quite nice and well thought of. I have compiled the sessions with their respective links for online recordings.

    1. Meet the New Windows Azure :
      http://channel9.msdn.com/events/TechEd/Europe/2012/FDN05
    2. Continuous Feedback in Agile Teams :
      http://channel9.msdn.com/events/TechEd/Europe/2012/DEV321
    3. 36 Terabytes: How Microsoft IT Manages SharePoint in the Enterprise :
    4. Developing and Managing SharePoint Solutions with Microsoft Visual Studio :
      http://channel9.msdn.com/events/TechEd/Europe/2012/OSP231
    5. Microsoft Office 365 for Enterprises :
      http://channel9.msdn.com/events/TechEd/Europe/2012/OSP221
    6. What’s New with Internet Information Services (IIS) 8: Open Web Platform for Cloud :
      http://view.officeapps.live.com/op/view.aspx?src=http%3a%2f%2fvideo.ch9.ms%2fteched%2f2012%2feu%2fWSV331.pptx
    7. Introducing the New Visual Studio 2012 Unit Testing Experience :
      http://channel9.msdn.com/events/TechEd/Europe/2012/DEV214
    8. Building Microsoft SharePoint Online Applications in a Hybrid World :
      http://channel9.msdn.com/events/TechEd/Europe/2012/OSP331
    9. Working on an Agile Team with Visual Studio 2012 and Team Foundation Server 2012 :
      http://channel9.msdn.com/events/TechEd/Europe/2012/DEV318
    10. Exploring the Power of Page Layouts in SharePoint 2010 WCM Sites :
      http://channel9.msdn.com/events/TechEd/Europe/2012/OSP335
    11. Microsoft SQL Server Data Tools: Database Development from Zero to Sixty :
      http://channel9.msdn.com/events/TechEd/Europe/2012/DBI311
    12. Business Intelligence and Data Visualization: Microsoft SQL Server 2012 :
      http://channel9.msdn.com/events/TechEd/Europe/2012/DBI206
    13. Application Lifecycle Management: Automated Builds and Testing for SharePoint projects :
      http://channel9.msdn.com/events/TechEd/Europe/2012/OSP432
    14. JavaScript: The Language :
      http://channel9.msdn.com/events/TechEd/Europe/2012/DEV307
    15. Creating and Consuming OData Services for Business Applications :
      http://channel9.msdn.com/events/TechEd/Europe/2012/DEV336
    16. What’s New in Microsoft .NET Framework 4.5 :
      http://channel9.msdn.com/events/TechEd/Europe/2012/DEV331
    17. A Modern Architecture Review: Using the New Code Review Tools :
      http://channel9.msdn.com/events/TechEd/Europe/2012/DEV324
    18. Identify & Fix Performance Problems with Visual Studio 2012 Ultimate :
      http://channel9.msdn.com/events/TechEd/Europe/2012/DEV412
    19. JavaScript: The Developer Experience :
      http://channel9.msdn.com/events/TechEd/Europe/2012/DEV308