Remove Border Around Images using CSS

Putting an image inside a link adds a border to it. This is usually done to visually indicate to the user that this image is a link. Check this example:

<body>
<
a href="http://www.dotnetcurry.com">
<
img alt="progress" src="images/abc.jpg" />
</
a>
</
body>

image

If you have a requirement to override this behavior, then here’s how to do so:

<style type="text/css">
img
{
border-style: none;
}
</style>

Now when you view the same image, it is displayed without a border

image

How to Center a Table inside a Div using CSS

If you have been looking for a simple way to center a table inside a div, then here it is

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title></title>
<
style type="text/css">
#divOne
{
width:400px;
text-align:center;
border:dotted 1px black;
}

#tblOne
{
width:200px;
margin:0 auto;
border: solid 1px black;
}

</style>
</
head>
<
body>
<
div id="divOne">
<
table id="tblOne">
<
tr>
<
td>R1C1</td>
<
td>R1C2</td>
<
td>R1C3</td>
</
tr>
<
tr>
<
td>R2C1</td>
<
td>R2C2</td>
<
td>R2C3</td>
</
tr>
</
table>
</
div>
</
body>
</
html>

I have seen lot of people missing out on the margin:auto property. Setting margin to auto is the correct way to center a table and works in ‘most’ of the browsers. The border is just for illustration purposes and is not required.

OUTPUT

image

Loop through all the rows of a GridView

One simple way to loop through all the rows in all the pages of a GridView is to access its DataSource. In this example, we will loop through the SQLDataSource to retrieve all the rows in a GridView and access its cell value. You can modify the logic depending on the type of controls you have added to the GridView

C#

protected void btnLoop_Click(object sender, EventArgs e)
{
DataSourceSelectArguments dsaArgs = new DataSourceSelectArguments();
DataView view = (DataView)SqlDataSource1.Select(dsaArgs);
DataTable dt = view.ToTable();
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
string s = dt.Rows[i][j].ToString();
}
}
}

VB.NET

Protected Sub btnLoop_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim dsaArgs As New DataSourceSelectArguments()
Dim view As DataView = CType(SqlDataSource1.Select(dsaArgs), DataView)
Dim dt As DataTable = view.ToTable()
For i As Integer = 0 To dt.Rows.Count - 1
For j As Integer = 0 To dt.Columns.Count - 1
Dim s As String = dt.Rows(i)(j).ToString()
Next j
Next i
End Sub
Note: If you loop through the GridView instead of the DataSource, you will loop through the rows only for 'that current page'

Change the Color of Hyperlink inside a Container Using CSS

A user recently asked me if it was possible to change the color of hyperlinks placed in a container, instead of changing the hyperlink color of the entire page. Here’s a simple solution to change the hyperlink color only inside divOne:

#divOne a:link
{
color:White;
}

#divOne a:visited
{
color:White;
}

#divOne a:hover
{
color:Black;
}

Similarly if you want to change hyperlink color nested in containers; for eg: a hyperlink kept inside a table inside divOne, use this:

#divOne table a:link
{
color:White;
}

How to cancel Update and Delete Operations in a GridView

I was recently asked a simple way to cancel update and delete operation in a GridView. It is quite simple to do so as shown here:

C#

protected void gv_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
e.Cancel = true;
}

void gv_RowDeleting(Object sender, GridViewDeleteEventArgs e)
{
// Check if there is atleast one row left in the GridView
// before deleting
if (gv.Rows.Count <= 1)
{
e.Cancel = true;
}
}

VB.NET

Protected Sub gv_RowUpdating(ByVal sender As Object, _
ByVal e As GridViewUpdateEventArgs)
e.Cancel = True
End Sub

Private Sub
gv_RowDeleting(ByVal sender As Object, _
ByVal e As GridViewDeleteEventArgs)
' Check if there is atleast one row left in the GridView
' before deleting
If gv.Rows.Count <= 1 Then
e.Cancel = True
End If
End Sub
You can also add your own conditions before cancelling these events.

Parse HTML using the HTML Agility Pack

If you haven’t yet heard or explored the HTML Agility Pack, then you must do so. I have been using this library from quite some time to extract links and tags and it works very well. As given on the site:

HTML Agility Pack(HAP) is an agile HTML parser that builds a read/write DOM and supports plain XPATH or XSLT (you actually don't HAVE to understand XPATH nor XSLT to use it, don't worry...). It is a .NET code library that allows you to parse "out of the web" HTML files. The parser is very tolerant with "real world" malformed HTML. The object model is very similar to what proposes System.Xml, but for HTML documents (or streams).

Sample applications of the HAP are:

  • Page fixing or generation. You can fix a page the way you want, modify the DOM, add nodes, copy nodes, well... you name it.
  • Web scanners. You can easily get to img/src or a/hrefs with a bunch XPATH queries.
  • Web scrapers. You can easily scrap any existing web page into an RSS feed for example, with just an XSLT file serving as the binding. An example of this is provided.

Download it here

Calculate Age in Years using C# or VB.NET

I was recently checking out some scripts to calculate the Age of a person in years and came across a simple piece of code shared by NeilPric. Here’s the code for your reference:

C#

static void Main(string[] args)
{
DateTime dob = DateTime.Parse("04/24/1979");

int ageInYrs = DateTime.Now.Year - dob.Year;
if (DateTime.Now.Month < dob.Month
(DateTime.Now.Month == dob.Month &&
DateTime.Now.Day < dob.Day))
ageInYrs--;
Console.WriteLine(ageInYrs);
Console.ReadLine();
}

VB.NET

Sub Main(ByVal args() As String)
Dim dob As Date = Date.Parse("04/24/1979")

Dim ageInYrs As Integer = Date.Now.Year - dob.Year
If Date.Now.Month < dob.Month _
OrElse (Date.Now.Month = dob.Month AndAlso Date.Now.Day < dob.Day) Then
ageInYrs -= 1
End If
Console.WriteLine(ageInYrs)
Console.ReadLine()
End Sub

OUTPUT

30

Generating Test Data For Your Applications

Sometimes on the internet you find websites that are extremely useful. The other day I stumbled upon one such site called GenerateData.com

This website does exactly what the URL suggests, it generates test data for you. This is great if you're in I.T. because invariably for a project, you need test data to demonstrate features to your users.

Generating data is a breeze. Give the data a name, choose the data you want and click Generate.

clip_image002

It generates test data which is great for demo's. Here's a small sample:

clip_image004

Difference between Eval and Bind - Data Binding Expressions in ASP.NET

In simple words, the Eval function is used to define one-way binding (read only). The Bind function is used for two-way binding (read-write)

So in a control like the GridView or the FormView, when you have to display read only data using a label control, you would be using the Eval function whereas when you want to update a database field, you would be using a TextBox and thus using the Bind function.

Note: You can use the Bind function to retrieve the value of a databound field, just as Eval does.

Here’s an example:

<asp:FormView ID="FormView1" runat="server"
AllowPaging="True"
DataKeyNames="CustomerID"
DataSourceID="SqlDataSource1">
<
EditItemTemplate>
CustomerName:
<asp:TextBox ID="txtCustName"
runat="server"
Text='<%# Bind("CName") %>'>
</
asp:TextBox>
</
EditItemTemplate>

<
ItemTemplate>
CustID:
<asp:Label ID="lblCustID"
runat="server"
Text='<%# Eval("CID") %>'>
</
asp:Label>
</
ItemTemplate>
</
asp:FormView>
You can read more on the Eval and Bind functions

Free EBook for Developing High Quality Applications using .NET

The Microsoft Application Architecture Guide, 2nd Edition is a Must Have EBook for Developers and Solution Architects

As mentioned on the site, the guide is intended to help developers and solution architects design and build effective, high quality applications using the Microsoft platform and the .NET Framework more quickly and with less risk; it provides guidance for using architecture principles, design principles, and patterns that are tried and trusted. The guidance is presented in sections that correspond to major architecture and design focus points. It is designed to be used as a reference resource or to be read from beginning to end.

The guide helps you to:

  • Understand the underlying architecture and design principles and patterns for developing successful solutions on the Microsoft platform and the .NET Framework.
  • Identify appropriate strategies and design patterns that will help you design your solution's layers, components, and services.
  • Identify and address the key engineering decision points for your solution.
  • Identify and address the key quality attributes and crosscutting concerns for your solution.
  • Create a candidate baseline architecture for your solution.
  • Choose the right technologies for your solution.
  • Identify patterns & practices solution assets and further guidance that will help you to implement your solution.

You can download the free ebook over here

Visual Studio 2010 and .NET Framework 4 Release Will Get Delayed

As per the latest announcement on Scott Gu’s blog, the final release of VS 2010 and .NET Framework 4.0 has been delayed. These tools are currently in their Beta as posted here a couple of days ago - Visual Studio 2010 and .NET Framework 4 Beta 2 has been Released.

The primary reason for the delay is to buy some more time to work on the Beta 2 feedback collected from customers, specifically around the performance of the product.

During February 2010, a Release Candidate will be made available with these performance and other issues fixed. The goal of the RC will be to collect further feedback and depending on the work to be done, we can expect to hear the final date of release.

You find more information about the delay over here and here

Quality first, always!

Simplest way to Programmatically ShutDown or Restart your System using C# or VB.NET

One of the ways to ShutDown or Restart your system is to use WMI (Windows Management Interface). However it does require you to write a few lines of code. I have found that the simplest way to ShutDown or Restart your computer is to use the Process class in the System.Diagnostics namespace. Here’s an example:

C#

private void btnShutDown_Click(object sender, EventArgs e)
{
Process.Start("shutdown", "-s -f -t 0");
}

private void btnRestart_Click(object sender, EventArgs e)
{
Process.Start("shutdown", "-r -f -t 0");
}

VB.NET

Private Sub btnShutDown_Click(ByVal sender As Object, ByVal e As EventArgs)
Process.Start("shutdown", "-s -f -t 0")
End Sub

Private Sub
btnRestart_Click(ByVal sender As Object, ByVal e As EventArgs)
Process.Start("shutdown", "-r -f -t 0")
End Sub

jQuery 1.4 Alpha 2 Released

jQuery 1.4 Alpha 2 has just been released. The code is a stable release and has been tested in all the browsers they support. The jQuery team are no longer accepting any new features for this release, but rest assured it will be good! Here’s where you can download the code:

The jQuery team need help testing this, so to help them you should use the un-minified version into a live application, a development environment of course, and see if any errors pop up. If you hit an exception or some weirdness occurs immediately login to the bug tracker and file a bug. Be sure to mention that you hit the bug in jQuery 1.4a2!

The final jQuery 1.4 release has been scheduled for January 14, 2010.

ASP.NET MVC 2 Release Candidate

The ASP.NET MVC Team announced the release of ASP.NET MVC 2 Release Candidate. Here are some highlights of this release:

- ASP.NET MVC validation scripts are now in a separate JavaScript file

- ASP.NET MVC validation scripts can be included at the top or bottom of a page

- ASP.NET MVC validation scripts now support globalization

- Html.ValidationSummary helper method can now also display model-level errors, instead of displaying all the validation errors

There are some other improvements that can be found in the ASP.NET MVC 2 RC Release Notes

You can download ASP.NET MVC 2 RC over here

Microsoft Office 2010 Developer Training Kit

Microsoft recently announced the Availability of the Office 2010 Developer Training Kit! As mentioned on the site "The Office 2010 Developer Training Kit content is designed to help developers get started with building solutions, from add-ins to full featured Office Business Applications (OBAs), using Visual Studio 2010 with Office 2010 and SharePoint 2010 as the core platform"

Each of the HOLs in the training kit have a number of exercises to help the developer build your skills. The labs included in the training kit are:

  • Getting Started with Office 2010 Development
  • Office 2010 UI Customizations
  • Client Workflow
  • Security and Deployment
  • Open XML
  • InfoPath and Forms Services
  • Business Connectivity Services
  • Office 2010 Service Applications
  • Developing BI Applications

The training kit can be downloaded over here

Also check out my post on Free Training Kits for Developers and IT Professionals (Microsoft Technologies)

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

The Array.ConvertAll() method is a very useful method to convert an array of one type to an array of another type. Here’s how to use ConvertAll() to convert a String[] to Decimal[]

C#

static void Main(string[] args)
{
string[] strArray = new string[] { "1164", "2213" };
decimal d;
decimal[] d1;
// Check if string can be converted to decimal equivalent
if (strArray.All(number => Decimal.TryParse(number, out d)))
{
d1 = Array.ConvertAll<string, decimal>(strArray, Convert.ToDecimal);
}
}

VB.NET

Sub Main(ByVal args() As String)
Dim strArray() As String = { "1164", "2213" }
Dim d As Decimal
Dim
d1() As Decimal
' Check if string can be converted to decimal equivalent
If strArray.All(Function(number) Decimal.TryParse(number, d)) Then
d1 = Array.ConvertAll(Of String, Decimal)(strArray, Convert.ToDecimal)
End If
End Sub

The first step is to use Enumerable.All(TSource) to determine whether all the elements in a sequence satisfy a condition, in our case, if all the elements of the array can be converted to its decimal equivalent. Once this can be done, we use ConvertAll() to convert an array of string to an array of decimal.

Compare Two Decimal Numbers to N Decimal Places

How do you compare two decimal values to ‘N’ decimal places. So for example, you want to compare two decimal numbers to 5 decimal places. Here’s an example:

C#

static void Main(string[] args)
{
decimal one = 23.5456533464M;
decimal two = 23.5456543444M;
decimal three = 23.5456223334M;

decimal a = Math.Truncate(one * 100000);
decimal b = Math.Truncate(two * 100000);
decimal c = Math.Truncate(three * 100000);
Console.WriteLine("Is Decimal One = Two?: {0}", Equals(a, b));
Console.WriteLine("Is Decimal Two = Three?: {0}", Equals(b, c));
Console.ReadLine();
}

VB.NET

Shared Sub Main(ByVal args() As String)
Dim one As Decimal = 23.5456533464D
Dim two As Decimal = 23.5456543444D
Dim three As Decimal = 23.5456223334D

Dim a As Decimal = Math.Truncate(one * 100000)
Dim b As Decimal = Math.Truncate(two * 100000)
Dim c As Decimal = Math.Truncate(three * 100000)
Console.WriteLine("Is Decimal One = Two?: {0}", Equals(a, b))
Console.WriteLine("Is Decimal Two = Three?: {0}", Equals(b, c))
Console.ReadLine()
End Sub

If you observe, we are multiplying each decimal by 5 zeros and considering only the integral part of the decimal using Math.Truncate.

The first two decimal numbers are equal considering the first 5 decimal places .54565. However the third decimal number is .54562, which is not equal to .54565 and hence the value printed is false

OUTPUT

image

Using TrueForAll with Generic Lists

If you work with generic lists, you’ll know sometimes you need to check the values in the list to see if they match certain criteria. A method I don’t see used allot is TrueForAll. This is part of the List<T> class. It determines whether every element in the List<(Of <(T>)>) matches the conditions defined by the specified predicate. For example you have the following code:

C#

var numbers = new List<int>() { 4, 6, 7, 8, 34, 33, 11};

VB.NET (Option Infer On)

Dim numbers = New List(Of Integer) (New Integer() {4, 6, 7, 8, 34, 33, 11})

If you needed to check if you had any zeros values, you could write a foreach statement like this:

C#

bool isTrue = false;
foreach (var i in numbers)
{
if (i == 0)
{
isTrue = true;
}
}

VB.NET

Dim isTrue As Boolean = False
For Each
i In numbers
If i = 0 Then
isTrue = True
End If
Next
i

There’s nothing wrong with that code, but by using the TrueForAll method, you can roll that up into one line of code:

C#

var numbers = new List<int>() { 4, 6, 7, 8, 34, 33, 11};
var isTrue = numbers.TrueForAll(o => o > 0);

VB.NET

Dim numbers = New List(Of Integer) (New Integer() {4, 6, 7, 8, 34, 33, 11})
Dim isTrue = numbers.TrueForAll(Function(o) o > 0)

That makes your code more readable than the previous example, and it also looks more elegant in my opinion.

List the Different CultureNames using CultureInfo

Here’s the code to list the different cultures in an ASP.NET ListBox using the CultureInfo class. Make sure you import the System.Globalization namespace

C#

protected void Page_Load(object sender, EventArgs e)
{
foreach (var c in CultureInfo.GetCultures(CultureTypes.AllCultures))
{
ListBox1.Items.Add(c.Name);
}
}

VB.NET

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
For Each c In CultureInfo.GetCultures(CultureTypes.AllCultures)
ListBox1.Items.Add(c.Name)
Next c
End Sub

Here’s the output:

image

Redirect from HTTP to HTTPS in ASP.NET

Here’s a simple way to redirect a user from HTTP to HTTPS. I have tested a few scenarios with the code and it has worked fine. Let me know if you face any issues with the code

C#

protected void Page_Load(object sender, EventArgs e)
{
if (!Request.IsSecureConnection)
{
UriBuilder uri = new UriBuilder(Page.Request.Url);
uri.Scheme = Uri.UriSchemeHttps;

// Redirect to https
Response.Redirect(uri.ToString());
}
}

VB.NET

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not Request.IsSecureConnection Then
Dim
uri As New UriBuilder(Page.Request.Url)
uri.Scheme = Uri.UriSchemeHttps

' Redirect to https
Response.Redirect(uri.ToString())
End If
End Sub
The IsSecureConnection property of the HttpRequest class gets a value indicating whether the HTTP connection uses secure sockets. Is not, the uri scheme is changed to https and the user is redirected

List Items of a DropDownList using jQuery

Here’s a script that lists items of a DropDown/Select Box using jQuery. I have used the map(callback) function for this requirement

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<
html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>List Items of a DropDownList</title>
<
script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</
script>

<
script type="text/javascript">
$(function() {
$("#btnList").click(function() {
var ddlItems = $("#DDL option").map(function(a, b) {
return b.text; // to print value say -- b.value
}).get().join("<br/>");
$('#para').html(ddlItems);
});
});
</script>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
select id="DDL">
<
option value="21">David</option>
<
option value="22">Jack</option>
<
option value="23">Jenny</option>
<
option value="24">Julia</option>
</
select>
<
br />
<
input id="btnList" type="button" value="Click Here to List Items" />
<
br />
<
p id="para" />
</
div>
</
form>
</
body>
</
html>



You can read more about Traversing/Map() . The get() function accesses all matched elements and passes it to map() as an array.

See a Live Demo

OUTPUT

image

Why is the ‘Use Aero Peek to Preview the Desktop’ Option Disabled on my machine with Windows 7?

In one of my previous posts, I had written about the ‘Show Desktop and the Aero Peek Feature in Windows 7’. Emma commented on that post saying that the option was grayed out on her machine. This is what it looks like when the option is not available on your machine

image

Here are some pointers to help you resolve this issue:

1. Run the ‘Windows Experience Index’ assessment test on your Windows 7 machine to rate the performance of your hardware. If you get a score of 3.0 or more for the Graphics component, you are good to go to use this feature. Here’s the sample assessment test results of a machine.

image

2. Once you have run the assessment test and have got a score of 3.0 or above, go to Control Panel > Performance Information and Tools > Click on ‘Adjust Visuals Effects’

image

Make sure that these three checkboxes are checked

- Animate controls and elements inside windows
- Enable desktop composition
- Use visual styles on windows and buttons

3. You can also try enabling Aero theme on your machine. To do so, right click on your desktop > Personalize > Choose an Aero Theme. Also make sure the Color scheme is 32-bit.

image

If neither of the steps shown above works, check these links over here for other possible solutions

Aero Peek problems

Aero Peek not available or not working

Hopefully these steps will resolve the issue and you will be able to preview the desktop with Aero Peek

image

Convert LowerCase and UpperCase to TitleCase in .NET

The String class has the ToLower() and the ToUpper() methods to convert a string to lowercase and uppercase respectively. However when it comes to converting the string to TitleCase, the ToTitleCase() method of the TextInfo class comes very handy. Let me demonstrate this with an example:

C#

class Program
{
static void Main(string[] args)
{
string strLow = "lower case";
string strT = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(strLow);
Console.WriteLine("Lower Case to Title Case: " + strT);

string strCap = "UPPER CASE";
strT = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(strCap.ToLower());
Console.WriteLine("Upper Case to Title Case: " + strT);
Console.ReadLine();
}
}

VB.NET

Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim strLow As String = "lower case"
Dim strT As String=CultureInfo.CurrentCulture.TextInfo.ToTitleCase(strLow)
Console.WriteLine("Lower Case to Title Case: " & strT)

Dim strCap As String = "UPPER CASE"
strT = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(strCap.ToLower())
Console.WriteLine("Upper Case to Title Case: " & strT)
Console.ReadLine()
End Sub
End Class

Make sure you import the System.Globalization namespace. As you can observe, we are using the CurrentCulture.TextInfo property to retrieve an instance of the TextInfo class based on the current culture.

Note: As mentioned on the site, “this method does not currently provide proper casing to convert a word that is entirely uppercase, such as an acronym”. This is the reason why we first convert strCap to lower case and then supply the lowercase string to ToTitleCase() in the following manner:

CultureInfo.CurrentCulture.TextInfo.ToTitleCase(strCap.ToLower());

The output after running the code is as shown below:

image

Sixth Sense Technology - A Tech Thriller

Pranav Mistry is the inventor of the Sixth Sense Technology. While speaking at TEDIndia, Pranav demoed the potential of the Sixth Sense Technology. In his own words, Sixth Sense is a wearable gestural interface that augments the physical world around us with digital information and lets us use natural hand gestures to interact with that information. You can treat yourself with this amazing video shown below:


Note: If for some reason, you are unable to view the video in this post, you can also view the video over here

This Indian geek aims at taking the technology to the masses and plans to release the software behind sixthsense to the open source community. WOW

Pranav once again proves that you are only limited by your imagination! You can follow Pranav at twitter using @sixthsensetech and follow the list at #sst

Convert Enum to List<> using C# or VB.NET

A user recently asked me how to convert an Enum to a List<>. Here’s the code to do so:

C#

class Program
{
enum Days { Sat, Sun, Mon, Tue, Wed, Thu, Fri };

static void Main(string[] args)
{
Array arr = Enum.GetValues(typeof(Days));
List<string> lstDays = new List<string>(arr.Length);
for (int i = 0; i < arr.Length; i++)
{
lstDays.Add(arr.GetValue(i).ToString());
}
}
}

VB.NET

Friend Class Program
Private Enum Days
Sat
Sun
Mon
Tue
Wed
Thu
Fri
End Enum

Shared Sub
Main(ByVal args() As String)
Dim arr As Array = System.Enum.GetValues(GetType(Days))
Dim lstDays As New List(Of String)(arr.Length)
For i As Integer = 0 To arr.Length - 1
lstDays.Add(arr.GetValue(i).ToString())
Next i
End Sub
End Class
Additionally you can also add a check to evaluate if arr.GetValue(i) is not null before adding it to the List<>

Show Desktop and the Aero Peek Feature in Windows 7

A lot of Windows 7 users miss the ‘Show Desktop’ that was available in the quick launch bar in previous versions of Windows.

In Windows 7, the ‘Show desktop’ is now placed at the end of the taskbar (see where the blue arrow is pointing towards)

image

When you point your mouse cursor on the ‘Show desktop’ button, the Windows 7 taskbar allows you to ‘Peek’ and temporarily view the desktop. This is done using ‘Preview Desktop with Aero Peek’. Aero Peek lets to take a quick look at open windows without clicking away from the window you are currently working on. In previous versions of Windows, without the Aero Peek, you had to minimize all open windows and then had to restore them.

Here’s a sample screenshot with the Aero Peek in action. Observe that when I hover my mouse pointer over the ‘Show desktop’ button, I am able to take a peek at the desktop without having to minimize all windows. The open gadgets are shown as transparent rectangles.

image

Similarly, the windows reappear when you move the pointer away from the ‘Show desktop’ button. If you ‘click’ on the ‘Show desktop’ button, the windows are minimized and you can work on your desktop. The same can also be achieved using Windows Logo Key on your keyboard + D

To enable or disable the "Preview Desktop with Aero Peek" feature, right click on the taskbar and select Properties. The Taskbar and Start Menu properties dialog appears. Check the ‘Preview desktop with Aero Peek’ section. To disable this feature, uncheck the "Use Aero Peek to preview the desktop” checkbox.

image

jQuery 1.4 Alpha 1

clip_image002

I am excited by the announcement made by John Resig today that jQuery 1.4 Alpha 1 has been released! The code has been tested in all the browsers they support and is stable. Here are the two downloads available right now:

There are a few areas in jQuery that have seen extensive changes since 1.3.2 was released:

· live was drastically overhauled and now supports submit, change, mouseenter, mouseleave, focus, and blur events in all browsers. Also now supports context and data.

· append, prepend, etc. have been heavily optimized.

  • add has been adjusted to always return elements in document order.
  • find, empty, remove, addClass, removeClass, hasClass, attr, and css have been heavily optimized.

There are still some open bugs in this release. The complete list can be found here. The best way to help out with testing this version is to run it in your systems. The jQuery team want to hear about any problems or bugs you find. You can lodge the bug here.

Also the jQuery 2009 Conference was held recently and John Resig gave a number of presentations. These presentations covered the following topics:

· Changes to jQuery’s internals from version 1.3 to 1.4

· Testing jQuery

· State of jQuery 09’

The presentations can be found here.

Google’s Closure Tools

Recently Google announced the release of Closure Tools. This is how Google describe it:

“Millions of Google users worldwide use JavaScript-intensive applications such as Gmail, Google Docs, and Google Maps. Like developers everywhere, Googlers want great web apps to be easier to create, so we've built many tools to help us develop these (and many other) apps. We're happy to announce the open sourcing of these tools, and proud to make them available to the web development community.”

The toolset includes the Closure Compiler, Closure Library and Closure Templates. I’ll focus this post on the Closure Compiler. Google describe the compiler as:

“The Closure Compiler is a tool for making JavaScript download and run faster. It is a true compiler for JavaScript. Instead of compiling from a source language to machine code, it compiles from JavaScript to better JavaScript. It parses your JavaScript, analyzes it, removes dead code and rewrites and minimizes what's left. It also checks syntax, variable references, and types, and warns about common JavaScript pitfalls.”

There’s an online version where you can go and try it out. If you like what you see, you can download the code and run it locally. This would be great to integrate as part of your build process IMO.

clip_image002

The Closure Compiler will compress your JavaScript files. The Simple optimization will remove whitespace and comments. The Advanced optimization will look at your code and try to optimize it. For most people the Simple optimization will be good enough because the compiler won’t re-write your JavaScript.

Choosing Windows SDK

I was trying my hands on the latest Windows SDK and came across this link which I felt is a must bookmark for developers who like to build applications using native (Win32) or the .NET Framework programming models

Here’s the link: Which SDK is Right for Me?

This link helps you decide the SDK you would require, depending on the version of Windows and .NET Framework you will be building applications for. Here’s a screenshot of the chart

image

Very useful indeed!

You may also want to take a peek at the Windows SDK Frequently Asked Questions (FAQ)

Using the Magnifier in Windows 7

A really nice feature of Windows 7 is the Magnifier. The Magnifier enlarges different parts of the screen. This is especially useful for viewing objects that are difficult to see, but also for seeing the whole screen more easily. The magnifier can run in three separate modes. These are:

· Full-screen mode. In full-screen mode, your entire screen is magnified. You can then have Magnifier follow the mouse pointer

· Lens mode. In lens mode, the area around the mouse pointer is magnified. When you move the mouse pointer, the area of the screen that's magnified moves along with it

· Docked mode. In docked mode, only a portion of the screen is magnified, leaving the rest of your desktop in a normal state. You can then control which area of the screen is magnified

The mode I want to show you today is full-screen mode. This is great if you’re doing presentations, such as showing code at .NET User Groups. To zoom in on your current screen, Win + key combination. That will zoom in 200%.

clip_image002

If you hit the Win + key again you’ll zoom in another 100%. Win – reduces the zoom by 100%. The magnifier by default will follow the mouse around. This is a real handy feature I’ve used when presenting code to folks and making sure everyone can see exactly what I’m doing.

Validating Time in ASP.NET using a Regular Expression

In one of the forums, I came across a question where a user wanted to validate time in ASP.NET. The requirements were the following:

- Acceptable values were 23:59, 00:00, 23 (equivalent to 23:00) and so on

- Values to be disallowed were 24:00, 23:5, 23:0 and so on

Here’s the regex shared by RQuadlin to achieve this requirement.

^([ 01]?[0-9]2[0-3])(:([0-5][0-9]))?$

In an ASP.NET scenario, we will be using a Regular Expression Validator to validate time. The markup will look similar to the following:

<div>
<
asp:TextBox ID="txtTime" runat="server">
</
asp:TextBox>
<
asp:RegularExpressionValidator ID="rev"
runat="server" ErrorMessage="InvalidTime" ControlToValidate="txtTime"
ValidationExpression="^([ 01]?[0-9]2[0-3])(:([0-5][0-9]))?$">
</
asp:RegularExpressionValidator>
</
div>

Free .NET Profilers and Some Paid Ones Too

Profiling is an important part of your software development process and allows you to determine improvements in your applications. In simple words, it is tuning your application to increase its performance. Here are some free and paid .NET profilers to do the job for you

Free

EQATEC v3.0 – An easy to use code profiler to spot your app's slow code. Profiles only methods as of this writing. You can use it freely for non-commercial use. Check the pricing page for the free license

CLR Profiler for .NET Framework – Free memory allocation profiler which works for .NET 2.0 and 3.5 as well

slimTune - Free profiler and performance analysis/tuning tool for .NET based applications

Commercial

Visual Studio Team System Profiler – Ships with Visual Studio Team System (Developer and Suite) for finding performance issues in your native, managed or ASP.NET applications

ANTS Profiler v5.1 – Highly recommended profiler to identify performance bottlenecks and optimize performance

dotTrace 3.1 – Performance and memory profiler for .NET

MemProfiler 3.5 - powerful tool for finding memory leaks and optimizing the memory usage in programs written in C#, VB.NET or any other .NET Language

AQTime 6 - performance profiling and memory and resource debugging toolset for .NET applications

Backup Gadgets in Vista

There are some useful gadgets provided in the Windows Vista Sidebar gadgets. I find the Vista Notes Gadget useful to take down small notes. I recently had to move my data to a new machine and wanted to backup these gadgets. There are some tools that help you take a backup, however if you want to take a backup without using any tools, follow these steps:

1. Browse to C:\Users\<yourname>\AppData\Local\Microsoft\Windows Sidebar

2. You will find a file called Settings.ini. This file contains all the data and settings of your gadgets. Copy this file and save it in your backup drive.

3. In the new machine, replace the Settings.ini with the one you have in your backup drive

Voila!

Disable Right Click Easily using jQuery

I’ve seen allot of posts on forums on how to disable the right click event in JavaScript. Well the solution is pretty straight forward if you use jQuery! The trick is to bind to the contextmenu event. The code below is an example of how to do this.

<html xmlns="http://www.w3.org/1999/xhtml" >
<
head>
<
title>jQuery disable right click easily</title>
<
script language="javascript" type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</
script>
<
script type="text/javascript" language="javascript">
$(function() {
$(this).bind("contextmenu", function(e) {
e.preventDefault();
});
});
</script>
</
head>
<
body>
Sed lacus. Donec lectus. Nullam pretium nibh ut turpis.
Nam bibendum. In nulla tortor, elementum vel, tempor at,
varius non, purus. Mauris vitae nisl nec consectetuer.
Donec ipsum. Proin imperdiet est. Phasellus dapibus semper
urna. Pellentesque ornare, orci in consectetuer hendrerit,
urna elit eleifend nunc, ut consectetuer nisl felis ac diam.
Etiam non felis. Donec ut ante. In id eros.
</body>
</
html>



See a Live Demo

Website accessibility using NVDA

Website accessibility is a serious topic for all web developers these days, and if it isn’t, it should be. Making a website that is accessible is not that hard, but it does require you to think from a UI point of view instead of a pure coding thought process. One tool that is freely available for you to download is NonVisual Desktop Access (NVDA). The website describes it as this:

“Providing feedback via synthetic speech and Braille, it enables blind or vision impaired people to access computers running Windows for no more cost than a sighted person”

This tool can help you diagnose accessibility issues your website may have for blind or vision impaired users. It can help you diagnose input fields that can’t be read, missing alternate text for images and a bunch of other things. You can download this great piece of free software from here.

List the First Monday of every month using C# and VB.NET

Here’s some code for listing down the first Monday of every month in an year using C# and VB.NET. The Monday’s listed in this example are for the year 2010

C#

public static void Main(string[] args)
{
for (int mth = 1; mth <= 12; mth++)
{
DateTime dt = new DateTime(2010, mth, 1);
while (dt.DayOfWeek != DayOfWeek.Monday)
{
dt = dt.AddDays(1);
}
Console.WriteLine(dt.ToLongDateString());
}
Console.ReadLine();
}

VB.NET

Public Shared Sub Main(ByVal args() As String)
For mth As Integer = 1 To 12
Dim dt As New DateTime(2010, mth, 1)
Do While dt.DayOfWeek <> DayOfWeek.Monday
dt = dt.AddDays(1)
Loop
Console.WriteLine(dt.ToLongDateString())
Next mth
Console.ReadLine()
End Sub

OUTPUT

image

Multi-Column ComboBox in WPF

WPF XAML has huge capabilities for effective UX development. The following code shows how to display multi-column data values for ComboBox in WPF

C#

using System.Windows;
using System.Collections.ObjectModel;

namespace WPF_MultiColumnCombobox
{
/// <summary>
///
Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
ObservableCollection<Empl> _emp = new ObservableCollection<Empl>();

public Window1()
{
InitializeComponent();
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
_emp.Add(new Empl() {EmpNo = 101, EmpName = "Mahesh", DeptName = "IT" });
_emp.Add(new Empl() {EmpNo = 102, EmpName = "Ajay", DeptName = "IT" });
_emp.Add(new Empl() {EmpNo = 103, EmpName = "Rahul", DeptName = "IT" });
_emp.Add(new Empl() {EmpNo = 104, EmpName = "Pradnya", DeptName = "HR" });
_emp.Add(new Empl() {EmpNo = 105,EmpName = "Abhijeet",DeptName = "ITSF" });
_emp.Add(new Empl() {EmpNo = 106, EmpName = "Keshav", DeptName = "MKTG" });
_emp.Add(new Empl() {EmpNo = 107,EmpName = "Prasanna",DeptName = "MKTG" });
_emp.Add(new Empl() {EmpNo = 108, EmpName = "Shailesh", DeptName = "BH" });
_emp.Add(new Empl() {EmpNo = 109,EmpName = "Sidhhart",DeptName = "ITSF" });
_emp.Add(new Empl() {EmpNo = 1010, EmpName = "Kaipl", DeptName = "AI" });

this.DataContext = _emp;

}
}

public class Empl
{
public int EmpNo { get; set; }
public string EmpName { get; set; }
public string DeptName { get; set; }
}
}

XAML Code

<Window x:Class="WPF_MultiColumnCombobox.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="560" Loaded="Window_Loaded" >
<
Window.Resources>
<
Style x:Key="txtStyle" TargetType="{x:Type TextBlock}">
<
Setter Property="TextAlignment" Value="Center"></Setter>
</
Style>

<
DataTemplate x:Key="EmpKey">
<
Grid Height="50" Width="160" ShowGridLines="True">
<
Grid.ColumnDefinitions>
<
ColumnDefinition Width="40"></ColumnDefinition>
<
ColumnDefinition Width="60"></ColumnDefinition>
<
ColumnDefinition Width="50"></ColumnDefinition>
</
Grid.ColumnDefinitions>

<
TextBlock Grid.Column="0" Text="{Binding EmpNo}"
Style="{StaticResource txtStyle}"></TextBlock>
<
TextBlock Grid.Column="1" Text="{Binding EmpName}"
Style="{StaticResource txtStyle}"></TextBlock>
<
TextBlock Grid.Column="2" Text="{Binding DeptName}"
Style="{StaticResource txtStyle}"></TextBlock>
</
Grid>
</
DataTemplate>

<
Style TargetType="{x:Type ComboBoxItem}">
<
Style.Triggers>
<
DataTrigger Binding="{Binding Path=DeptName}" Value="IT">
<
Setter Property="Background" Value="White"></Setter>
</
DataTrigger>
<
DataTrigger Binding="{Binding Path=DeptName}" Value="HR">
<
Setter Property="Background" Value="Blue"></Setter>
</
DataTrigger>
<
DataTrigger Binding="{Binding Path=DeptName}" Value="ITSF">
<
Setter Property="Background" Value="Gray"></Setter>
</
DataTrigger>
<
DataTrigger Binding="{Binding Path=DeptName}" Value="BH">
<
Setter Property="Background" Value="DarkGray"></Setter>
</
DataTrigger>
<
DataTrigger Binding="{Binding Path=DeptName}" Value="AI">
<
Setter Property="Background" Value="Blue"></Setter>
</
DataTrigger>
<
DataTrigger Binding="{Binding Path=DeptName}" Value="MKTG">
<
Setter Property="Background" Value="DarkBlue"></Setter>
</
DataTrigger>
</
Style.Triggers>
</
Style>
</
Window.Resources>

<
Grid>
<
ComboBox Height="38" Margin="0,27,0,0"
Name="comboBox1"
VerticalAlignment="Top" ItemsSource="{Binding}"
ItemTemplate="{StaticResource EmpKey}"
IsSynchronizedWithCurrentItem="True"
HorizontalAlignment="Left" Width="200">
</
ComboBox>
</
Grid>
</
Window>



The above .Xaml defines DataTemplate which represents the way data will be displayed. We also have the data styles defined based upon the values that will be displayed in the ComboBox. For eg: When the value of the DeptName is “HR”, the color of the row is Blue and so on.

Here’s the output:

image

Clicking on the ComboBox, you get an output similar to the following:

image