Most Popular Posts for Developers in 2010 - DevCurry.com

I had made a commitment at the beginning of this year to write one post (for developers like me) every day which would make 365 posts by the end of this year. Thanks to Malcolm Sheridan, Mahesh Sabnis and other Guest Bloggers who also contributed posts to DevCurry.com and helped me achieve this goal. Yay!!

This year, DevCurry.com had around 2 million visitors and 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.

Without further ado, let’s check out some of the popular .NET, jQuery and JavaScript posts that you may have missed in 2010. If you are a regular visitor, you can enjoy checking out your favorite posts once again.

ASP.NET and Other .NET Articles

ASP.NET GridView Tips and Tricks Collection

Collection of .NET Framework and Visual Studio Posters

Popular .NET Web Content Management Systems (CMS) - Open Source

.NET 4.0 has 2 Global Assembly Cache (GAC)

Different Ways of using the C# Null Coalescing Operator

Attributes Every .NET Developer Should Know About

Free C# and VB.NET Training Videos

30 Favorite Visual Studio Keyboard Shortcuts

Learn ADO.NET Entity Framework 4 – Free Tutorials

Var vs Dynamic keyword in C# 4.0

Visual Studio jQuery Intellisense over CDN

My Favorite Programming Fonts for Visual Studio Development

HTML 5 Intellisense In Visual Studio 2010 and 2008

Detect an Empty String in .NET 4.0

jQuery events stop working in ASP.NET AJAX UpdatePanel

Create a 3D chart in ASP.NET 4.0

Deserialize JSON string and bind to ASP.NET DropDownList

jQuery and JavaScript Articles

5 jQuery Calendar Plugins that can be used on Websites

5 Online Rich Text Editors built using jQuery

Latest jQuery and jQuery UI Theme links on Google CDN

Test your jQuery code Online using jsFiddle

Learn JavaScript, straight from the Gurus - Free JavaScript Video Lectures

Style an HTML Table using jQuery UI and Theme Switcher Widget

Is my JSON Valid?

jQuery Virtual keyboard with Qwerty layout

Use jQuery to Detect if User has Scrolled to the Bottom or Top of a Page

Search an Array using JavaScript or jQuery - Cross browser implementation

Adding all TextBox values to a Hidden field using jQuery

Rounded Corners with the Cornerz jQuery plugin

jQuery 1.4.4 fadeToggle() function

Remove All Stylesheets from a Page using jQuery

Using jQuery to find out Elements on the Page that do not have an ID attribute

Load a Page Dynamically inside the jQuery UI Dialog

Simultaneously add Multiple Event Handlers to a Selector using jQuery 1.4

Find an Element based on its Style using jQuery

Customize the Display of Error Messages while using the jQuery Validation Plugin

Prevent Duplicate Entries in a HTML DropDown

SlideUp and SlideDown using delay() in jQuery 1.4

You can keep up with the blog by Subscribing to the RSS Feed or via the Facebook page. If you have a feedback or just want to say something, feel free to use the comments section. I have really enjoyed running this blog and will continue with the same zeal and enthusiasm in the year 2011. Wish me luck!

Exception Handling in Silverlight 4 – Manage Unhandled Exceptions

A good practice to follow is to handle the exception where it occurs, using the try-catch block. However there could be certain areas in your code where unknown exceptions crop up. If the exception is not handled by your application, the exception reaches the Silverlight plug-in and the application ends abruptly.

In order to manage unhandled exceptions gracefully, Silverlight has the Application.UnhandledException event in the App.xaml.cs file which provides centralized error handling. Here’s a sample that shows how to gracefully manage unhandled exceptions.

Open your App.xaml code behind file and look for the Application_UnhandledException method.

image

As seen in the code above, you can log the errors into a log file by accessing the Unhandled Exception via the ‘ExceptionObject’ property. Setting ‘e.Handled’ to true tells the Silverlight application that the exception has been handled and the application can continue running.

Note: For errors that originate from the Silverlight plug-in itself, developers use JavaScript to handle them. If you are using VS 2010, you will see that the template automatically creates an onSilverlightError function that implements basic error handling.

image

Resolve JSON is Undefined Error in Internet Explorer

While running JSON code like the one shown below, older browsers like IE7 produces the error - ‘JSON’ is undefined:

JSON code

JSON is undefined

The error occurs while executing the JSON.parse() method by older browsers that have not implemented the JSON object. The solution to this error is to download the json2 library and include it in your script, as shown below:

Json2.js script

The application uses the json2.js library for browsers that haven’t implemented the JSON object yet. After adding the json2.js library, you can now test the application on IE7 and you will get the desired output

image

Note: All the latest browsers like Firefox 3.5+, IE 8+, Chrome, Safari 4+ etc. have built-in JSON capability.

You also want to look at Is my JSON valid?

Auto Generate Row Number in ASP.NET ListView

One of my blog readers Robert asked me a question. Is it possible to create a counter field or an auto-generated Row Number in an ASP.NET ListView.

The solution is to add <%# Container.DataItemIndex + 1 %> to the ItemTemplate of the ListView as shown below:

ListView Row Number

The output with the auto generated serial number/row number is as shown below:

ListView Row Number

If you are working with the ASP.NET GridView, check this post of mine ASP.NET GridView Tips and Tricks series

Task-based Asynchronous Pattern in .NET

Microsoft released a whitepaper that talks about the Task-based Asynchronous Pattern (TAP). TAP represents arbitrary asynchronous operation and is based on the Task and Task{TResult} types in the System.Threading.Tasks namespace.

The document talks about the Task-based Asynchronous pattern and how to implement and consume it in your applications. The document also shows you how to communicate TAP with other .NET Async Pattern types like the IAsyncResult pattern and the event-based asynchronous pattern (EAP), along with a case study.

Download the Task-based Asynchronous Pattern Whitepaper

Link Files Between Different Projects - Visual Studio

You can add file to an existing project either by copying the files directly or create a link between them. When you create a link, the file does not get physically copied to a new location, only a reference is set to it. The process is quite simple as shown here.

Right click your project in Solution Explorer > Add > Existing Item. Browse to the file you want to add and click the small ‘drop-down’ arrow as shown below

image

Choose the ‘Add as Link’ option and the file will get added as a link, rather than directly adding the file to your project. Linked project items in Solution Explorer can be identified by the link indicator in its icon, as shown below.

image

Note: If the original file is deleted, the link gets broken. You also need to manually update a copy whenever changes are made to the original file.

Change Background Color of ASP.NET Button using jQuery

Here’s a simple piece of code that can change the background color of an HTML or ASP.NET Button using jQuery

ASP.NET Button

<html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<
title>Change Background Button Color (from DevCurry.com)</title>
<
style type="text/css">
.bgClr{
background-color:Green;
}
</style>
<
script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.4.min.js">
</
script>
<
script type="text/javascript">
$(function () {
$(".btn").click(function () {
$('.btn').removeClass('bgClr');
$(this).addClass('bgClr');
return false;
});
});
</script>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:Button ID="Button1" runat="server" Text="Button One" class="btn" />
<
asp:Button ID="Button2" runat="server" Text="Button Two" class="btn" />
<
asp:Button ID="Button3" runat="server" Text="Button Three" class="btn" />
</
div>
</
form>
</
body>
</
html>

Observe how we have added the class ‘.btn’ to all button elements. On a button click, we first remove the .bgClr class on all buttons and then add the .bgClr class to the button that was clicked. We are using the jQuery addClass and removeClass methods.


HTML Button

The code in the <head> tag remains the same as above. Just use these HTML controls instead of the server controls

<input id="Button1" type="button" value="Button One" class="btn"/>
<
input id="Button2" type="button" value="Button Two" class="btn"/>
<
input id="Button3" type="button" value="Button Three" class="btn"/>

OUTPUT

image

See a Live Demo

If you are using jQuery with ASP.NET Pages, you may find my eBook helpful 51 Recipes with jQuery and ASP.NET Controls

Slice() and Splice() in JavaScript

The Array.Slice() and Array.Splice() are methods of the Array class, to manipulate arrays. Although they sound similar, these two methods work differently. Let us see an example which demonstrates how the two methods are different from each other

Slice() - Creates a new array from elements of an existing array. It does not modify the original array. The Slice() method takes two arguments. The first argument is an integer that specifies where to start the selection. The second argument is optional and is an integer that specifies where to end the selection.

Slice() Javascript

In the code shown above, slice() starts at position 1 and copies “two”, “three” into the new array (newArrSlice). The original array (nums) is not modified by the slice() method.

Slice() Javascript

Some important points about slice():

  • Index starts from zero
  • If a single argument is given to the slice() method, the array returned will contain all elements from the start position to the end of array.
  • If a negative value is supplied for either parameters, this means that the slice() will count the position from the end of the array, instead of the beginning. So in the above example, if we specify nums.splice(-1,-3), it will return “three” and “four”

Splice() – Deletes and/or inserts elements in an array. Unlike slice(), the splice() method modifies the original array and returns a new array. The Splice() method takes three arguments. The first parameter is the index to start deleting and/or insert elements, the second param is number of elements to remove and third param (optional) is the new elements to be added to the array.

Splice() Javascript

In the code shown above, the splice() method starts at position 2 i.e element “three” and removes a length of 2 elements i.e. removes element “three” and “four”.

Splice() Javascript

Some important points about splice():

  • Index starts from zero
  • If a single argument is given to the splice() method, all elements from the start index to the end of the array will be removed
  • If a negative value is supplied for the parameter, the elements are spliced from the end and not from the beginning of the array

Clipboard Operations (Cut Copy Paste) in Silverlight

In this short article, we will explore how to access the clipboard using a Silverlight 4.0 application. Clipboard Access is one of the new features provided in Silverlight 4.0. The class ‘Clipboard’ with static methods is provided to interact with the clipboard local system. We will be using the following methods of Clipboard class:

  • SetText: Set the Unicode data in the clipboard
  • ContainsText: Asks the clipboard about the presence of the Unicode data
  • GetText: Retrieves the Unicode data from the clipboard.

Step 1: Open VS2010 and create a Silverlight 4.0 Application. In the MainPage.xaml, write the following XAML code:

image

Step 2: In the click events of the ‘Copy’, ‘Cut’ and ‘Paste’ buttons, write the following code:

private void btnCopy_Click(object sender, RoutedEventArgs e)
{
Clipboard.SetText(txtData.SelectedText);
}

private void btnCut_Click(object sender, RoutedEventArgs e)
{
Clipboard.SetText(txtData.SelectedText);
txtData.SelectedText = "";
}

private void btnPaste_Click(object sender, RoutedEventArgs e)
{
if (Clipboard.ContainsText())
{
txtData.SelectedText = Clipboard.GetText();
}
}

Step 3: Run the application and type some data in the textbox. Select some text from the textbox and click on the ‘Copy’ button. Silverlight will prompt asking for access rights for the clipboard as shown below:


image

Click on ‘Yes’ and then set your cursor in the textbox and click on the ‘Paste’ button. You will find the selected text pasted in the textbox. You can do the same thing for ‘Cut’ operation too.

If you are working on Silverlight 4, check some more Silverlight articles

Convert String Array Into String – C# LINQ

A couple months ago, I had written some posts on converting String and Char Arrays

Convert a String Array to a Decimal Array using C# or VB.NET

Convert Char Array to String and Vice Versa

Here’s a very simple way if you want to convert a String Array to String using C# LINQ

static void Main(string[] args)
{
string[] indiaCityVisit = {
"Delhi", "Jodhpur", "Mumbai", "Pune", "Agra",
"Shimla", "Bengaluru", "Mysore", "Ooty",
"Jaipur", "Nagpur", "Amritsar", "Hyderabad",
"Goa", "Ahmedabad" };

string cities = String.Join(",", indiaCityVisit
.Select(s => s.ToString())
.ToArray());
Console.WriteLine(cities);

Console.ReadLine();
}
LINQ String Array to String

Order by Length then by Name - LINQ

When you are working with String arrays, a common requirement is to display the results in an ordered format. Here’s a query that shows you how to first Order the results by Length, and then by Name, using LINQ

static void Main(string[] args)
{
string[] indiaCitiesVisited = {
"Delhi", "Jodhpur", "Mumbai", "Pune", "Agra",
"Shimla", "Bengaluru", "Mysore", "Ooty",
"Jaipur", "Nagpur", "Amritsar", "Hyderabad",
"Goa", "Ahmedabad" };

IEnumerable<string> cityOrder =
indiaCitiesVisited.OrderBy(str => str.Length)
.ThenBy(str => str);
foreach (string city in cityOrder)
Console.WriteLine(city);


Console.ReadLine();
}

As you can see, we first OrderBy the length of the element and ThenBy the element itself (ascending albhabetically by Name). Remember that the ThenBy operator takes an IOrderedEnumerable<T> as the input. That’s why to create an IOrderedEnumerable, the OrderBy method is called prior to ThenBy.

OUTPUT

LINQ OrderBy ThenBy

Disable F1 in Visual Studio

If you are using Visual Studio on a laptop, especially the smaller ones a.k.a. the Netbook, the keys are way too close to each other and I often end up hitting the F1 button instead of the ESC key.

Here’s a simple tip to disable the F1 key in Visual Studio 2005, 2008 or 2010 to save you from some annoyance.

In Visual Studio, Go to Tools > Options > Environment > Keyboard > Select Help.F1Help and say Remove

image

Simple tip but extremely useful for Netbook owners like me!

Add a “Read More” Link using jQuery

The jQuery Expander Plugin is a simple little jQuery plugin to hide/collapse a portion of an element's text and add a "read more" link so that the text can be viewed by the user if he or she wishes

Here’s a simple way to use this plug-in your HTML or ASP.NET Pages

1. Declare a Div or ASP.NET Panel

  <div class="readmore">
The Div Text Comes Here
</div>

2. Add the following jQuery code in the <head> section of your page

<head>
<
title>Add Read More Link (from DevCurry.com)</title>
<script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.4.min.js">
</
script>
<
script type="text/javascript"
src="http://plugins.learningjquery.com/expander/jquery.expander.js">
</
script>
<
script type="text/javascript">
$(function () {
$('div.readmore').expander({
slicePoint: 200,
expandText: 'Click Here to Read More',
userCollapseText: 'Hide Text'
});
});
</script>
</
head>

As you can see, we have used the ‘jQuery’ file and the ‘Expander’ plugin in the <head> of your document. Note: In a production application, download the expander code on your server and reference it from there.

Finally we are customizing the behavior and appearance of the expander, by overriding the default options. Check the entire expander API over here

When the Page Loads, click the ‘Click Here To Read More’ link to expand text

image

Once the Text has been expanded, click the ‘Hide Text’ Button to hide it again.

image

Live Demo

Intellisense Icons in Visual Studio

When you are using Visual Studio Intellisense completion list, you must have observed a collection of icons as shown below

Visual Studio Intellisense Icons

There are 179 such icons and have you ever wondered what do all these icons mean? These are called Babel Icons and you can have different icons for a method depending on whether it is public, protected or private. Here’s a snapshot of these icons

Visual Studio Intellisense Icons

Check the entire list of icons and what do they mean in the Babel Icons table

Windows Azure Free Training Kit - December

Microsoft recently released an updated version of the Free Windows Azure Platform Training Kit which includes technical content including hands-on labs, presentations, and demos that are designed to help you learn how to use the Windows Azure platform including: Windows Azure, SQL Azure and the Windows Azure AppFabric - for FREE!

Here are some highlights of the training kit

  • Updated demos covering Azure SDK 1.3
  • Hands on Lab for new Windows Azure features such as Virtual Machine Role, Elevated Privileges, Full IIS
  • Introduction to SQL Azure Reporting
  • Managing, Debugging, and Monitoring Windows Azure
  • Deploying and Managing SQL Azure Databases with VS 2010 Data-tier Applications
  • Three sample Training Agendas that cover one-day, two-day, and four-day workshops
  • Many more new HOL’s, presentations and scripts

Download the Windows Azure Free Training Kit

Remove White Spaces from a String using jQuery

Users while entering text in textboxes may add extra whitespaces at the beginning or at the end of a textbox. jQuery provides the $.trim() function that removes, spaces, newline and tabs from the beginning and end of the string. Here’s how to use this function to remove white spaces in textboxes in your HTML or ASP.NET Pages

<html xmlns="http://www.w3.org/1999/xhtml" >
<
head>
<
title>Remove White Spaces in String (from DevCurry.com)</title>
<
script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.4.min.js">
</
script>
<
script type="text/javascript">
$(function () {
$('input').blur(function () {
$(this).val(
$.trim($(this).val())
);
});
});
</script>
</
head>
<
body>
<
input id="Text1" type="text" /><br /><br />
<
input id="Text2" type="text" />
</body>
</
html>

When a user enters some text in the textbox with some white space, then on the textbox blur event, the textbox value is fetched using $(this).val() and passed to the $.trim() function, which removes the white spaces at the beginning or end of the string.

Before (Observe White space at the beginning of string)

image

After (Textbox loses focus or user tabs out)

image

See a Live Demo

Use Anonymous Method with a Delegate in C#

A colleague of mine asked me a question - ‘How can we use an Anonymous method with a Delegate and when should we do it”.

By using anonymous methods, you reduce the coding overhead in instantiating delegates, by eliminating the need to create a separate method. You can use it to run code snippets that would otherwise require a named method or use it as a quick event-handler with no name.

Here’s the code that shows how to do it. Comments have been placed inline to understand the code

namespace ConsoleApplication2
{
// Define a Delegate
delegate int AddThenMultiply(int i, int j);

class Class1
{
static void Main(string[] args)
{
// Instatiate delegate type using anonymous method
AddThenMultiply atm = delegate(int i, int j)
{
return (i + j) * 2;
};

// Anonymous delegate call
int result = atm(2, 3);
Console.WriteLine("Result is: " + result);
Console.ReadLine();
}

}
}

OUTPUT

Anonymous Method Delegate Call

Change Background Color of GridView Cell using jQuery

Users often ask how to change the background color of an ASP.NET GridView cell, if the cell matches a condition. It’s actually quite simple using jQuery. Just use this code in the <head> section of your page:

<head runat="server">
<
title>GridView Cell Background Color by DevCurry.com</title>
<
style type="text/css">
.grdCell
{
background-color:Gray;
}
</style>

<
script type="text/javascript" src="
http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</
script>

<
script type='text/javascript'>
$(function () {
$("#grdCust td").filter(function () {
return $(this).text() == "France";
}).addClass("grdCell");
});
</script>
</
head>

Here we are using the jQuery filter() method that reduces the set of matched elements to those that match the selector or pass the function's test. In our case, we are sending the filter() method an anonymous function that can be used to filter the table cells that have the value ‘France’ in them. The $(this) within the function refers to each DOM element in the wrapper set.

As you would expect, only the cells containing the values ‘France’ get highlighted.

image

If you are doing jQuery development with ASP.NET Controls, you will find my eBook helpful 51 Recipes with jQuery and ASP.NET Controls

Serialize XDocument in LINQ To XML

In this post, we will first create an XDocument object that contains XElement objects. You can then serialize the XDocument to a File, XMLWriter or TextWrite

Let us see how to Serialize an XDocument in LINQ to XML to an XMLWriter and then to the disk.

Make sure you add references to the following namespaces:

using System.Xml.Linq;
using System.IO;
using System.Xml;

static void Main(string[] args)
{
XNamespace empNM = "urn:lst-emp:emp";

XDocument xDoc = new XDocument(
new XDeclaration("1.0", "UTF-16", null),
new XElement("Employees",
new XElement("Employee",
new XComment("DevCurry.com Employees"),
new XElement("EmpId", "1"),
new XElement("Name", "Kathy"),
new XElement("Sex", "Female")
)));

using (StringWriter strW = new StringWriter())
{
using (XmlWriter xmlW = XmlWriter.Create(strW))
{
xDoc.Save(xmlW);
// Save to Disk
xDoc.Save("C:\\XDocSerialized.xml");
Console.WriteLine("Saved");
}
}

Console.ReadLine();
}

Open the XDocSerialized.xml file in notepad and you should see the following output

image

ASP.NET GridView Sorting with Image

Continuing my ASP.NET GridView Tips and Tricks series, this post shows you how to display the Up and Down Arrow Images, while sorting the ASP.NET GridView

To sort the GridView columns using images (up and down arrows), use the GridView control’s
RowDataBound event as shown below:

protected void grdCust_RowDataBound(object sender, GridViewRowEventArgs e)
{
string imgAsc = @" <img src='images\asc.jpg' title='Ascending' />";
string imgDes = @" <img src='images\des.jpg' title='Descendng' />";

if (e.Row.RowType == DataControlRowType.Header)
{
foreach (TableCell cell in e.Row.Cells)
{
LinkButton lbSort = (LinkButton)cell.Controls[0];
if (lbSort.Text == grdCust.SortExpression)
{
if (grdCust.SortDirection == SortDirection.Ascending)
lbSort.Text += imgAsc;
else
lbSort.Text += imgDes;
}
}
}
}

In the code shown above, we first check if the current row is a header row. If yes, then depending on the Sort Expression, add the image to the LinkButton that matches the column. You can also use some CSS to remove the image borders and align it with the Sort Link.

image

Read some more GridView Tips and Tricks over here

Print Source Code in Color using Visual Studio 2010

Although Visual Studio 2008 supported printing of source code with color, Visual Studio 2010 prints code in Black and White. The VS team while releasing VS 2010 added no support for printing source code, with colored syntax! A lot of us jokingly thought that the VS team wanted to discourage printing and someone was a Go-Green fan in their team :) although the actual reason was, that they could not add color printing in VS 2010 due to time constraints.

The good news is, using the recently released Free Color Printing extension, you can now print code in color using VS 2010. I too am a Go-Green guy, but if I have to print, colors are goood!

Note that Color Printing extension only works on Visual Studio 2010 Premium, Professional and Ultimate editions. Since the Express editions do not support extensions, source code color printing is not available to developers using VS 2010 Express editions.

Hopefully with the release of VS 2010 SP1 next year, I expect the support for code color printing out-of-the-box. By the way, if you missed the announcement, VS 2010 SP1 Beta is out.

Download Color Printing Extension from the Visual Studio Gallery

Visual Studio 2010 SP1 Beta Released

Microsoft released the first beta Service Pack (SP1) for Visual Studio 2010 yesterday. Here are the download links:

Download Visual Studio 2010 Service Pack 1 Beta (MSDN Subscribers only)

Download Visual Studio 2010 Service Pack 1 Beta (General Availability)

Amongst the SP1 Beta highlights that Jason has summed up in is blog, what caught my attention were the following points:

  • IntelliTrace support for 64bit and SharePoint
  • Performance Wizard for Silverlight
  • Unit Testing on .NET 3.5
  • Silverlight 4 Tools for Visual Studio 2010 Integration

Note: As of this writing, if you are using ASP.NET MVC 3 RC, the VS 2010 SP1 Beta release breaks Razor IntelliSense. However the MVC team is working on a quick fix to be released early next week. This release also breaks Visual Studio Async CTP and I will update this post when a patch is available for the same. Till that time, if you are using Async CTP, stick to the VS 2010 RTM release and do not upgrade to SP1 Beta.

Search an Array using JavaScript or jQuery - Cross browser implementation

When one thinks of searching an array using JavaScript, you are tempted to use the indexOf method, which is as simple as using arr.indexOf(item). However remember that the indexOf or lastIndexOf methods have been formalized in ECMAScript 5. So they are not supported by all browsers (like IE8 does not support, although IE9 Preview supports it).

Now you have a couple of options using which you can use JavaScript to search an array, cross-browser.

Using JavaScript (implementation of indexOf by Mozilla)

Mozilla has provided a cross-browser implementation of the indexOf method which is as follows

<script type="text/javascript">
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */) {
"use strict";

if (this === void 0 this === null)
throw new TypeError();

var t = Object(this);
var len = t.length >>> 0;
if (len === 0)
return -1;

var n = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n !== n)
n = 0;
else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
n = (n > 0 -1) * Math.floor(Math.abs(n));
}

if (n >= len)
return -1;

var k = n >= 0
? n
: Math.max(len - Math.abs(n), 0);

for (; k < len; k++) {
if (k in t && t[k] === searchElement)
return k;
}
return -1;
};
}

// Now you can use
var nums = new Array("one", "two", "three", "four");
alert(nums.indexOf("two"));
</script>

The code above returns the first index at which a given element (in our case “two”) can be found in the array, or -1 if it is not present. Since “two” is present in the array, the alert box displays the value 1.

Using jQuery

The jQuery inArray searches for a specified value within an array and return its index (or -1 if not found)

The search can be done using just one line of jQuery code as shown below

<head>
<
title>Search if Item exists in Array by DevCurry.com</title>
<
script type="text/javascript" src="
http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</
script>
<
script type="text/javascript">
var
nums = new Array("one", "two", "three", "four");
alert($.inArray("two", nums));
</script>
</
head>

jQuery Virtual keyboard with Qwerty layout

The free Virtual Keyboard Widget is an on-screen virtual keyboard embedded within the browser window which will popup when a specified input field is focused. The user can then type and preview their input before Accepting or Canceling

You can download the plugin over here. This plugin uses the jQuery UI library.

Here’s a simple example of using the on-screen virtual Keyboard with the Qwerty layout (default), which pops up when a specified input field is focused, in our case the password field.

image

OUTPUT

image

You can also specify options like showing only a Numeric keypad instead of showing the entire keypad.

image

image

Check the list of different options and how to create a custom layout of your own over here at http://snipplr.com/view/21577/virtual-keyboard-widget/

Here’s the complete code:

<html xmlns="http://www.w3.org/1999/xhtml" >
<
head>
<
title>jQuery Qwerty Keyboard (from DevCurry.com)</title>
<
link type="text/css" rel="Stylesheet"
href="http://ajax.microsoft.com/ajax/jquery.ui/1.8.6/themes/
smoothness/jquery-ui.css" />
<
style type="text/css">
.ui-keyboard{padding: .3em; position: absolute; z-index: 16000;}
.ui-keyboard-button{height: 2em; width: 2em; margin: .1em;}
.ui-keyboard-actionkey{width: 4em;}
.ui-keyboard-space{width: 15em;}
.ui-keyboard-preview{width: 100%; text-align: left;}
</style>
<
script type="text/javascript" src="
http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</
script>
<
script type="text/javascript" src="
http://ajax.microsoft.com/ajax/jquery.ui/1.8.6/jquery-ui.min.js">
</
script>
<
script src="jquery.keyboard.js" type="text/javascript">
</
script>

<
script type="text/javascript">
$(function () {
$('input[type=password]').keyboard({
layout: "num"
});
});
</script>
</
head>
<
body>
<
input id="txtPass" type="password" />
</
body>
</
html>

As you can see, this is a nice lightweight plugin which makes it very simple to integrate an on-screen virtual keyboard in your applications.

See a Live Demo

Access a COM port in .NET

To access a COM port in .NET, just use the SerialPort class, which represents a serial port resource. Here’s how to access the COM ports on your computer and list some of its properties

C#

static void Main(string[] args)
{
// Retrieve a list of serial port names.
string[] ports = SerialPort.GetPortNames();

Console.WriteLine("List of Serial ports on your machine:");

// Display each port name to the console.
foreach (string sPort in ports)
{
using (SerialPort port = new SerialPort(sPort))
{
Console.WriteLine("BaudRate : " + port.BaudRate);
Console.WriteLine("ReadTimeout : " + port.ReadTimeout);
// Send a message to the port
port.Open();
port.Write("Hello Port!");
}
}

Console.ReadLine();
}

VB.NET (Converted Code)

Sub Main()
' Retrieve a list of serial port names.
Dim ports() As String = SerialPort.GetPortNames()

Console.WriteLine("List of Serial ports on your machine:")

' Display each port name to the console.
For Each sPort As String In ports
Using port As New SerialPort(sPort)
Console.WriteLine("BaudRate : " & port.BaudRate)
Console.WriteLine("ReadTimeout : " & port.ReadTimeout)
' Send a message to the port
port.Open()
port.Write("Hello Port!")
End Using
Next
sPort

Console.ReadLine()
End Sub

Learn ADO.NET Entity Framework 4 – Free Tutorials

The ADO.NET Entity Framework (EF) is an Object/Relational mapping (ORM) framework and is a set of technologies in ADO.NET, for developing applications that interacts with data.

I recently started a new series on Entity Framework 4.0 on DotNetCurry.com. If you are interested in learning Entity Framework 4.0, I recommend you bookmark this post and check out the tutorials. Here are some of the tutorials I have already written:

Entity Framework 4.0 FAQ – Getting Started Guide - In this article, I introduce Entity Framework 4.0, the history behind this framework and why it has become the recommended LINQ-based Data Access technology over LINQ To SQL

Create an Entity Data Model From a Database - In this article, I demonstrate how to create our first Entity Framework application using Visual Studio 2010. We will create an Entity Data Model (EDM) from an existing database.

Exploring how the Entity Data Model (EDM) Generates Code and Executes Queries - In this article, I explain what happens behind the scenes in the Entity Data Model and also look at the files responsible to generate the code and execute queries on your behalf.

Model-First Development in Entity Framework 4.0 - Create a Database from a Model - Developers who practice the Domain-Driven Development (DDD) style create a conceptual model first. The idea is to design the application based on a model. EF 4.0 supports creating the model first and generating a database from the model and in this article, I have shown you how to do model-first development.

Create an Entity Framework Model and Use it in Multiple Projects - This article shows the steps required to create an Entity Data Model which can be used in multiple projects.

Add, Update and Delete Objects in Entity Framework 4.0 - In this article, we will see how to Add, Update and Delete objects in our conceptual Entity model and push the changes to the underlying database.

Bind Entity Framework 4 Model to ASP.NET GridView
- In this article we will see how to bind an Entity Framework model that has been created in a different project, to an ASP.NET GridView.

Profiling and Logging Entity Framework Queries
- In this article, we will see how to log the SQL queries that get generated by Entity Framework. We will also some see profiling tools available.


Bookmark this post and stay tuned for more tutorials on Entity Framework 4.0. Please retweet this post to let fellow developers know about this series. Thanks!

Change Url of all Anchor Elements using jQuery

Sometime ago I had written about Change the URL of an ASP.NET Hyperlink Control at runtime using jQuery where I had shown how to dynamically change the url of ‘one’ hyperlink control.

However if you have a requirement of changing the url’s of 'multiple' anchor elements at runtime, use this code:

<html xmlns="http://www.w3.org/1999/xhtml" >
<
head>
<
title>Change Url's of All Anchor's (from DevCurry.com)</title>
<
script type="text/javascript" src="
http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</
script>

<
script type="text/javascript">
$(function () {
$('a', '#divone').click(function () {
$(this).attr("href", "http://www.devcurry.com");
});
});
</script>
</
head>
<
body>
<
div id="divone">
<
a href="#">One</a>
<
a href="#">Two</a>
<
a href="#">Three</a>
<
a href="#">Four</a>
<
a href="#">Five</a>
</
div>
</
body>
</
html>

The code shown above changes the Href of all the anchor elements inside ‘divone’ to the url www.devcurry.com , and that too with just one line of jQuery code!

Here’s a related article How to convert ASP.NET Bulleted List items or UnOrdered List to Hyperlinks using jQuery

See a Live Demo

Split a String Collection into Groups using LINQ

I was recently working on an interesting problem which involved splitting a string collection into groups. We had a huge collection of email addresses stored in a string array. The task was to loop the array and select 10 emails at a time and send it for processing.

Here’s some LINQ code originally shared by Eric Lippert, that can be helpful if you have a similar requirement without using a loop for grouping.

static void Main(string[] args)
{
string[] email = {"One@devcurry.com", "Two@devcurry.com",
"Three@devcurry.com", "Four@devcurry.com",
"Five@devcurry.com", "Six@devcurry.com",
"Seven@devcurry.com", "Eight@devcurry.com"};

var emailGrp = from i in Enumerable.Range(0, email.Length)
group email[i] by i / 3;

foreach(var mail in emailGrp)
SendEmail(string.Join(";", mail.ToArray()));


Console.ReadLine();
}


static void SendEmail(string email)
{
// Assuming that you have code for sending mails here
Console.WriteLine(email);
Console.WriteLine("--Batch Processed--");
}

The code above uses the LINQ GroupBy operator to group 3 email addresses at a time and send it for processing. Note that a group...by clause translates to an invocation of GroupBy.

OUTPUT

Split String Collection

Change the Background Color of jQuery Datepicker

Here’s a simple way using CSS to change the Background Color of the jQuery UI Datepicker control

<html xmlns="http://www.w3.org/1999/xhtml" >
<
head>
<
title>Change Background Color of jQuery UI
DatePicker(from DevCurry.com)</title>
<
link type="text/css" rel="Stylesheet"
href="http://ajax.microsoft.com/ajax/jquery.ui/1.8.6/themes/
smoothness/jquery-ui.css" />

<
style type="text/css">
.ui-datepicker {
background: #333;
border: 1px solid #555;
color: #EEE;
}
</style>

<
script type="text/javascript" src="
http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</
script>
<
script type="text/javascript" src="
http://ajax.microsoft.com/ajax/jquery.ui/1.8.6/jquery-ui.min.js">
</
script>


<
script type="text/javascript">
$(function () {
$("#datepic").datepicker();
});
</script>
</
head>
<
body>
<
input id="datepic"/>
</
body>
</
html>

As you can see, all that we are doing to change the background formatting for the Datepicker is to change the .ui-datepicker CSS class, as shown below.

<style type="text/css">
.ui-datepicker {
background: #333;
border: 1px solid #555;
color: #EEE;
}
</style>

Before:

jQuery UI Datepicker Default

After:

jQuery UI Datepicker Background

Check out some more similar jQuery DataPicker Tips