Winners of OReilly and Manning EBooks GiveAway

I had recently posted on Win the Latest Manning EBooks and Win the Latest O’Reilly EBooks. This GiveAway was from http://www.dotnetcurry.com/ to celebrate its 3 years.

Here are the winners of the DotNetCurry 3rd Anniversary GiveAway. Congratulations to all the winners! You will be contacted via Twitter within the next 48 hours. Make sure you check your Twitter Direct Messages from @DotNetCurry. For those who could not win, there will be contests in the near future too. So continue to Follow DotNetCurry on Twitter .

EBooks

Cover ImageSponsorWinner(s)
image C# in Depth - Second Edition by Manning pooran, ogoellner
image jQuery in Action - Second Edition by Manning aspenangwin, frankstepanski
image ASP.NET MVC 2 in Action by Manning cxfx, ddurose
image SQL Server MVP Deep Dives by Manning kensimmons, SQLPrincess
image SharePoint 2007 Developer's Guide to Business Data Catalog by Manning SharePointWhiz, jlangdon
image Programming Windows Azure by O’Reilly dholamahesh, mvisser
image C# 4.0 in a Nutshell - Fourth Edition by O’Reilly JungchanHsieh, Elsheimy
image Developing Large Web Applications by O’Reilly VikramPendse, malcolmsheridan
image Effective UI by O’Reilly voidnothings, MelindaMarsh
image 97 Things Every Programmer Should Know by O’Reilly tim_church, samnangchhun
image Windows 7 Annoyances by O’Reilly gcaughey, reelmccoy
image RESTful Web Services Cookbook by O’Reilly darrelmiller, devKhalid

Congratulations once again to all the winners! You will be contacted via Twitter within the next 48 hours. Make sure you check your Twitter Direct Messages from @DotNetCurry

Using the jQuery Validation Plugin to choose atleast one CheckBox before submitting the Form

Let us see how to use the jQuery Validation Plugin to choose atleast one checkbox before submitting the form

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<
head>
<
style type="text/css">
label.error {
float: none; color: red;
padding-left: .3em; vertical-align: top;
}
</style>
<
script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js">
</
script>
<
script type="text/javascript" src="
http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js">
</
script>

<
script type="text/javascript">
$.validator.addMethod('onecheck', function(value, ele) {
return $("input:checked").length >= 1;
}, 'Please Select Atleast One CheckBox')

$(document).ready(function() {
$("#form1").validate({
rules: {
bev: {
onecheck: true
}
},
errorPlacement: function(error, element) {
error.appendTo('#err');
}
});
});
</script>
<
title></title>
</
head>
<
body>
<
form id="form1">
<
div id="chkboxes">
<
input type="checkbox" name="bev" value="cream" />With cream<br />
<
input type="checkbox" name="bev" value="sugar" />With sugar<br />
<
input type="checkbox" name="bev" value="sugar" />With sugar<br />
</
div>
<
div id="err"></div>
<
input id="btnSubmit" type="submit" value="submit" />
</
form>
</
body>
</
html>

When the user tries to submit the form without selecting a checkbox, the validation fires and the following error message gets displayed

Select atlease one checkbox

The error disappears when a checkbox is selected and the user can now submit the form

Share the same Visual Studio Settings between Team Members

If you have customized your VS 2008/2010 environment with a new font size , color, theme etc. and now want to share these settings with other team members on your network to maintain consistency, then Visual Studio allows you to create a single .vssettings file and share it with your team members.

Here are the steps to do so:

Open Visual Studio 2010 > Go to Tools > Options > Environment > Import and Export Settings. Save the file to a local folder or a UNC share. I have called the file VSCsharpSettings.vssettings

Importing the Settings

Now to apply these settings to a workgroup, go to a workgroup machine, open Visual Studio 2010 > Go to Tools > Options > Environment > Import and Export Settings > Check the checkbox saying use team settings file and enter the path where the original VSCsharpSettings.vssettings file was saved (UNC or local path) and click Ok. You will now see that all the IDE’s on the workgroup that imported this setting file have the new settings applied.

image

In future, whenever you update this setting file, all the other IDE’s on the workgroup that are using this settings file will automatically use the updated category specified in the .vssettings file.

Note: The settings file imported through the Team Settings File option allows developers to keep the customizations they have made to the IDE. It only overrides the category specified in the .vssettings file.

Using jQuery to Set Focus on the first TextBox Kept inside a Panel/Div

In this post, we will use a small example to demonstrate how easy it is to use jQuery to select page elements and work on them.

When a page with a form loads, you often need to set focus on a page element kept inside the form. Here’s an example of how to set focus on the first TextBox kept inside a parent container, div.

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>jQuery to Set Focus on a TextBox Kept inside a Panel/Div</title>
<
style type="text/css">
#divOne
{
height:300px;
width:150px;
top:30px;
}
</style>
<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(function() {
$("#divOne :input[type='text']:first").focus();
});
</script>
</
head>
<
body>
<
div id="divOne">
TextBox1 <input id="textOne" type="text" /> <br />
TextBox2 <input id="textTwo" type="text" /> <br />
TextBox3 <input id="textThree" type="text" /> <br />
</
div>
</
body>
</
html>

The :input selector selects all input, textarea, select and button elements. The :first selector selects the first textbox. As you can see, we are using

$("#divOne :input[type='text']:first").focus()

to set focus on the first textbox element inside the element with ID divOne. The [type=’text’] tells the selector that we are only interested in TextBoxes.

If you run the page, the first TextBox element gets focused as expected:

image

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

Here’s a simple way to customize the placement of the error labels while using the jQuery Validation Plugin. We will display the error message in a control of our choice, in our case a div called “err”.

I had done a post a couple of days ago showing how to Validate IP Address using jQuery. In this example, when the user entered an invalid IP Address, the error (by default) was displayed in a label control that was placed next to the textbox being validated, as shown below:

image  

We will use the same example, but this time display the error message in a div control. To customize the placement of the error message, we will make use of the jQuery Validation errorPlacement option as shown in the example below:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Validate IP Address using jQuery</title>
<
style type="text/css">
label.error {
float: none; color: red;
padding-left: .3em; vertical-align: top;
}
</style>
<
script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js">
</
script>
<
script
type="text/javascript" src="
http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js">
</
script>
<
script type="text/javascript">
$(function() {
$.validator.addMethod('IP4Checker', function(value) {
var ip = "^(?:(?:25[0-5]2[0-4][0-9][01]?[0-9][0-9]?)\.){3}" +
"(?:25[0-5]2[0-4][0-9][01]?[0-9][0-9]?)$";
return value.match(ip);
}, 'Invalid IP address');

$('#form1').validate({
rules: {
ip: {
required: true,
IP4Checker: true
}
},
errorPlacement: function(error, element) {
error.appendTo('#err');
}
});
});
</script>
</
head>
<
body>
<
form id="form1">
<
input id="ip" name="ip" type="text" />
<
br />
<
div id="err"></div>
<
input id="Submit1" type="submit" value="submit" />
</
form>
</
body>
</
html>

Now when we enter an Invalid IP address and submit the form, the error is placed inside the div as shown below

image

Using the jQuery Validation Plugin to Validate a DropDownList

Let us see how to use the jQuery Validation Plugin to validate a DropDownList. We will perform a validation where the user has to select an option before submit the form.

<html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<
title>Validate a DropDownList</title>
<
style type="text/css">
label.error { float: none; color: red; padding-left: .2em; }
</style>
<
script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js">
</
script>

<
script type="text/javascript" src="
http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js">
</
script>
<
script type="text/javascript">
$.validator.addMethod('selectNone',
function(value, element) {
return this.optional(element) ¦¦
(value.indexOf("Select an option") == -1);
}, "Please select an option");

$(function(){
$("#form1").validate({
rules: {
'<%=DropDownList1.ClientID %>': {
selectNone: true
}
}
});
});
</script>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:DropDownList ID="DropDownList1" runat="server"
AppendDataBoundItems="true">
<
asp:ListItem Text="Select an option"></asp:ListItem>
</
asp:DropDownList>
<
br /> <br />
<
asp:Button ID="btnSubmit" runat="server" Text="Submit" />
</
div>
</
form>
</
body>
</
html>

Now if you browse the page and click on Submit without choosing an option, you get the following validation message

Validate DropDownList

Choosing an option removes the validation message and the form can now be submitted.

Remove the Whitespace generated for each Parent TreeNode in an ASP.NET TreeView

I was working on a TreeView bound to a SiteMap control. Due to a space constraint while displaying the TreeView, I had to save as much space as I could while displaying my TreeView. Now by default, when a TreeView is generated, the Parent Root Nodes have a whitespace indent as visible below

image

When the TreeView gets rendered, ASP.NET generates a number of HTML Table tags to format it’s layout. So to remove the whitespace before each parent node, just use the following CSS

<style type="text/css">
.tv table tbody tr td:first-child
{
display:none;
}
</style>

where tv is the CssClass applied to the TreeView.

<asp:TreeView ID="TreeView1" runat="server"
DataSourceID="SiteMapDataSource1" CssClass="tv">

The resultant output is as shown below with the extra whitespace removed:

image

Microsoft Office 2010 GiveAway

Microsoft Office has been one of the most successful products from Microsoft. If you have been keeping yourself up-to-date with the latest news surrounding Microsoft Office, you are probably aware that a new version of MS Office 2010 is soon to be released.

Here’s a chance for you (only residents of India) to own a copy of the latest offering from Office 2010. We are providing 1 Office 2007 Home and Student for you to give away. This will be freely upgradeable to Office 2010 once it releases in June.

How Do I Participate in this GiveAway?

To participate, all you have to do is drop in a comment on this post and let us know why do you want this product. Make sure you enter your emailid or twitterid in the comment. The winner will be contacted and sent an email and they will redeem their awards via microsoftstore.co.in. The prizes can only be shipped to India.

Virtual Launch Event

The community is also hosting a Virtual Launch Event for Office 2010 on May 25 and 26th. The webcasts is FREE to attend and people can participate either online or by going to the nearest available center. The sessions will be delivered by MVPs. To register please visit: http://www.meraoffice.com/

In June, limited cities will be hosting Community Launch Events for Office 2010. At the launch events, attendees will get to see Office 2010 in action and learn how to do their work better with Office 2010. The details are available on http://office.merawindows.com/

Note: This contest is open to residents of India only. The winner will be announced on June 10th, 2010.

Update: The winner of this contest is Harpreet Singh Khandiyal(hsk1313). Congratulations Harpreet! Check your Email.

Using jQuery to Find which ASP.NET Control caused a PostBack

Here’s a simple script that uses jQuery to find out which ASP.NET Button caused a postback. You can similarly implement this script for other ASP.NET Controls too

<html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<
title>Which Control Caused PostBack</title>
<
script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js"
type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("input:submit").click(function () {
$("#HiddenField1").val($(this).attr("id")
+ " caused a postback");
});
});
</script>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:Button ID="Button1" runat="server" Text="Button1" />
<
asp:Button ID="Button2" runat="server" Text="Button2" />
<
asp:Button ID="Button3" runat="server" Text="Button3" />
<
asp:HiddenField ID="HiddenField1" runat="server" />
</
div>
</
form>
</
body>
</
html>

C#

protected void Page_Load(object sender, EventArgs e)
{
Response.Write(HiddenField1.Value);
}

VB.NET

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Response.Write(HiddenField1.Value)
End Sub
As you can see, jQuery uses the Hidden field to store the value of the Button ID that caused a postback. The ID is printed using Response.Write()

Now click the Button2 and you get the following message

image

Format Date in Silverlight 4

In Silverlight 3, to format a date, you needed to write a Converter class that implemented the IValueConverter interface and you needed to implement the Convert and ConvertBack methods – something similar to the following:

public class DateConverter: IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
DateTime dt = (DateTime)value;
return dt.ToShortDateString();
}

public object ConvertBack(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
string str = value.ToString();
DateTime dt = DateTime.MinValue;

if (DateTime.TryParse(str, out dt))
{
return dt;
}
return value;
}
}

You then needed to add a reference to your class and write the following markup to format the date

<TextBox Text="{Binding Path=SomeDate,
Converter={StaticResource DateConverter}}" />

Silverlight 4 introduces the StringFormat binding property that makes formatting absolutely simple. You can format a value using either a predefined format or a custom format and the best part is, you do not need to write a converter class.

So to format a date in “dd/MM/yyyy” format, all you need to do is write the following markup

<TextBox Text="{Binding Path=SomeDate, StringFormat='dd/MM/yyyy'}"/>

which will produce the output 18/05/2010. Simple is good!

Distinct OrderBy in LINQ

One of my colleagues was curious to know how to implement a Distinct-OrderBy on a custom collection in LINQ. Here’s an example. This example uses the Distinct and OrderBy on the CustomerName property of the Customer class.

C#

class Program
{
static void Main(string[] args)
{
var cust = (from c in Customer.GetCustomers()
select c.CustName)
.Distinct()
.OrderBy(x => x);
foreach(var cst in cust)
Console.WriteLine(cst);
Console.ReadLine();
}
}

class Customer
{
public int OrderId { get; set; }
public string CustName { get; set; }

public static List<Customer> GetCustomers()
{
List<Customer> cust = new List<Customer>();
cust.Add(new Customer() { OrderId = 1, CustName = "Zack" });
cust.Add(new Customer() { OrderId = 2, CustName = "Harry" });
cust.Add(new Customer() { OrderId = 3, CustName = "Jill" });
cust.Add(new Customer() { OrderId = 4, CustName = "Zack" });
cust.Add(new Customer() { OrderId = 5, CustName = "Martin" });
cust.Add(new Customer() { OrderId = 6, CustName = "Jill" });
return cust;
}
}

VB.NET

Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim cust = (
From c In Customer.GetCustomers()
Select c.CustName).Distinct().OrderBy(Function(x) x)
For Each cst In cust
Console.WriteLine(cst)
Next cst
Console.ReadLine()
End Sub
End Class

Friend Class
Customer
Public Property OrderId() As Integer
Public Property
CustName() As String

Public Shared Function
GetCustomers() As List(Of Customer)
Dim cust As New List(Of Customer)()
cust.Add(New Customer() With {.OrderId = 1, .CustName = "Zack"})
cust.Add(New Customer() With {.OrderId = 2, .CustName = "Harry"})
cust.Add(New Customer() With {.OrderId = 3, .CustName = "Jill"})
cust.Add(New Customer() With {.OrderId = 4, .CustName = "Zack"})
cust.Add(New Customer() With {.OrderId = 5, .CustName = "Martin"})
cust.Add(New Customer() With {.OrderId = 6, .CustName = "Jill"})
Return cust
End Function
End Class

You can read more about Distinct and OrderBy

OUTPUT

Distinct OrderBy LINQ

Grab .NET Products, Books and Training for Free – 4 Days Left

DotNetCurry recently completed it's 3rd anniversary and is celebrating by doing a Free GiveAway of .NET Books, Training and Products . There are 97 prizes to be won and the last date of the Giveaway is 24th May, 2010 . So Hurry up!

Update: The Contest has ended. The winners will be announced on May 31st. Stay tuned!

Here are some highlights of the GiveAway

  • Licenses of Image Uploader, .NET Chart components, .NET UI Components
  • IDE Productivity Tool, Project Managament Software, .NET Code Quality Software and .NET Obfuscator Licenses
  • .NET and Technology EBooks from O'Reilly, Manning and KnowledgeVisuals
  • .NET Training Subscriptions
  • Windows 7 Ultimate and ESET Antivirus licenses

Just click this link DotNetCurry Completes 3 Years - Free GiveAway to enter the GiveAway , follow @DotNetCurry on twitter and drop a comment on that link saying which product do you want and why? Make sure you enter your twitter handler in the comment.

Good Luck!

Latest jQuery and jQuery UI Theme links on Google CDN

I have often seen developers asking where to find the jQuery UI Library and the jQuery UI Themes on Google CDN. Well here’s the list [Updated - March 2011]:

jQuery Library -
http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js

jQuery Library (Minified) - http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js

jQuery UI Library -
http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/jquery-ui.js

jQuery UI Library (Minified) - http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/jquery-ui.min.js

jQuery UI Base CSS - http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/themes/base/jquery-ui.css

jQuery Localization -
http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/i18n/jquery-ui-i18n.min.js

Note: You may also want to read jQuery and jQuery UI Microsoft CDN Links and Visual Studio jQuery Intellisense over CDN


jQuery UI Themes

image

black-tie

image

blitzer

image

cupertino

image

dark-hive

image

dot-luv

image

eggplant

image

excite-bike

image

flick

image

hot-sneaks

image

humanity

image

le-frog

image

mint-choc

image

overcast

image

pepper-grinder

image

redmond

image

smoothness

image

south-street

image

start

image

sunny

image

swanky-purse

image

trontastic

image

ui-darkness

image

ui-lightness

image

vader

You can Bookmark this link and refer it the next time you plan to look out for a jQuery library on Google CDN. If I missed out on any of the links, let me know and I will add it to the list!

Silverlight 4 Tool and WCF RIA Services 1.0 Released

Microsoft recently announced the release of Silverlight 4 Tools for Visual Studio 2010 and the WCF RIA Services v1.0 and Themes.

Download the Silverlight 4 Tools installer which will install the Silverlight 4 Tools and WCF RIA Services v1.0 over an existing RC installation and will take care of uninstalling previous installation bits. Also check out the Silverlight 4 Training Kit to learn more about how to build business applications with Silverlight 4, Visual Studio 2010 and WCF RIA Services

You can also download the new Silverlight 4 Application Themes which include the Accent Color, Windows 7 and Cosmopolitan theme.

Watch this video announcing the official release of WCF RIA Services v1.0!

image

Read more on Scott’s Blog Silverlight 4 Tools for VS 2010 and WCF RIA Services Released

Using LINQ to select Only Strings from an ArrayList

Here’s a simple example of using LINQ to select only Strings from an ArrayList that contains both integers and strings.

C#

static void Main(string[] args)
{
ArrayList al = new ArrayList { "Hello", 200, "World", false, 100 };
var onlyStr = al.OfType<string>();
Console.WriteLine("Printing Only Strings");
foreach(var str in onlyStr)
Console.WriteLine(str);
Console.ReadLine();
}

VB.NET

Sub Main(ByVal args() As String)
Dim al As ArrayList = New ArrayList From {"Hello", 200, "Word", False, 100}
Dim onlyStr = al.OfType(Of String)()
Console.WriteLine("Printing Only Strings")
For Each str In onlyStr
Console.WriteLine(str)
Next str
Console.ReadLine()
End Sub

As you can see, we are using the Enumerable.OfType<TResult> Method which filters the elements of an IEnumerable based on a specified type, in our case the String type.

OUTPUT

LINQ ofType

Reduce Size of the jQuery DatePicker

I often use the jQuery ui-lightness theme for my DatePicker, which I feel is quite nice. However by default, the DatePicker layout is quite ‘explosive’ and displays with big fonts.

jQuery UI DatePicker

However there is a simple way to change that with a small amount of css. Here’s some sample CSS to reduce the font-size of the DatePicker to reduce its size and change some styling

<style type="text/css">
.ui-datepicker {
font-family:Garamond;
font-size: 11px;
margin-left:10px
}
</style>

Now if you run the same code, the DatePicker shows up like this:

jQuery UI DatePicker