Prevent a ScrollViewer’s Vertical ScrollBar to be displayed

A ScrollViewer is a container that can display content that is larger than the ScrollViewer itself. However by default the Scroll Viewer displays a Vertical Scrollbar even if the the content falls within the dimension of the ScrollViewer

<Canvas x:Name="can">
<
ScrollViewer Width="200" Height="200"
Canvas.Left="30" Canvas.Top="30">
<
TextBlock Text="Lorem Ipsum Lorem">
</
TextBlock>
</
ScrollViewer>
</
Canvas>

image

In order to prevent a vertical scrollbar to be displayed, just set the VerticalScrollBarVisibility property to Auto

<Canvas x:Name="can">
<
ScrollViewer Width="200" Height="200"
Canvas.Left="30" Canvas.Top="30"
VerticalScrollBarVisibility="Auto">
<
TextBlock Text="Lorem Ipsum Lorem">
</
TextBlock>
</
ScrollViewer>
</
Canvas>

The Vertical ScrollBar does not appear now.

image

Adding all TextBox values to a Hidden field using jQuery

I was recently asked on one of the ASP.NET forums how to store all the values of every text box in a hidden field using JavaScript. I immediately said use jQuery! And this is what I came up with:

<html xmlns="http://www.w3.org/1999/xhtml" >
<
head runat="server">
<
title></title>
<
script src="http://code.jquery.com/jquery-latest.js"
language="javascript" type="text/javascript"></script>
<
script language="javascript" type="text/javascript">
$(function() {
$("#Button1").click(function(event) {
var data = [];
var form = $("form :input[type=text]");
$.each(form, function(e, textBox) {
data.push($.trim(textBox.value));
});
$("#HiddenAddressData").val(data.join(" "));
});
});
</script>

</
head>
<
body>
<
form>
<
input id="Address1" type="text" /><br />
<
input id="Address2" type="text" /><br />
<
input id="State" type="text" /><br />
<
input id="Zip" type="text" /><br />
<
input id="Button1" type="button" value="button" />
<
input id="HiddenAddressData" type="hidden" />
</
form>
</
body>
</
html>


What I'm doing is looping through each form element and adding it to my JavaScript array:

var data = [];
var form = $("form :input[type=text]");
$.each(form, function(e, textBox) {
data.push($.trim(textBox.value));
});

Then I join all the element of the array into a single value that is copied to the hidden field:

$("#HiddenAddressData").val(data.join(" "));

Nice and simple.

How to Programmatically access Constants declared in your Xaml

If you have been looking out for a way to declare some constants in your xaml and then programmatically access them, then here’s a way I follow.

Open your App.xaml and add the following string constant to it

<Application
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SampleSilverlight.App"
xmlns:clr="clr-namespace:System;assembly=mscorlib">
<
Application.Resources>
<
clr:String x:Key="DC">DevCurry</clr:String>
</
Application.Resources>
</
Application>



We will access this string constant programmatically using C# or VB.NET. 
Open your Page.xaml and add a TextBlock and a Button to it.
<StackPanel Height="200" Width="200">
<
TextBlock x:Name="tb"></TextBlock>
<
Button x:Name="btnFetch" Content="Fetch"
Click="btnFetch_Click"></Button>
</
StackPanel>
Now add the following code on button click:
C# 
private void btnFetch_Click(object sender, RoutedEventArgs e)
{
if (Application.Current.Resources.Contains("DC"))
{
tb.Text = (string)Application.Current.Resources["DC"];
}
}
VB.NET
Private Sub btnFetch_Click(ByVal sen As Object, ByVal e As RoutedEventArgs)
If Application.Current.Resources.Contains("DC") Then
tb.Text = CStr(Application.Current.Resources("DC"))
End If
End Sub

The Application.Resources gets a collection of Application-Scoped resources.

On clicking the button, the text ‘DevCurry’ gets displayed


image

Style Document Links on a Page using CSS and jQuery

The behavior and style of links can be easily specified using CSS, and with a little bit of jQuery, you can avoid applying CSS directly in the HTML. I will show you an example. Let us assume we have a couple of hyperlinks on the page, some of them linking to websites and the others linking to .doc/.xls documents on the web. Now if you have to highlight the hyperlinks linking to only .doc files, here’s how to do so using CSS and jQuery

<html>
<
head>
<
title>Style Document Links on a Page</title>
<
style type="text/css">
.docs
{
color:Gray;
font-style:italic;
background: url(someimage.png) no-repeat center right;
}
</style>
<
script language="javascript" type="text/javascript"
src="http://code.jquery.com/jquery-latest.js"></script>
<
script language="javascript" type="text/javascript">
$(function() {
$('a[href$=.doc]').addClass('docs');
});
</script>
</
head>
<
body>
<
form>
<
div>
<
a href="http://www.dotnetcurry.com">DotNetCurry</a>
<
a href="http://www.microsoft.com/smserver/docs/collectsecurity.doc">
Security Paper</a>
<
a href="http://www.microsoft.com/exchange/evaluation/03SecEnh.doc">
Exchange Server 2003</a>
<
a href="http://www.microsoft.com/msft/download/financialhistoryFY.xls">
Microsoft Fiscal History</a>
</
div>
</
form>
</
body>
</
html>

Observe this piece of code

$('a[href$=.doc]').addClass('docs');

We are using an attribute selector to highlight links containing an href attribute that ends with the extension .doc. The addClass adds the specified class (docs) to each of the set of matched elements

Here’s what the output looks like

image

A Super Cool Silverlight 4 Facebook Client

Microsoft recently unveiled a new Silverlight 4 based Facebook client, demonstrating a rich out-of-browser POC (Proof of Concept) in the familiar context of Facebook. The client is available for both Windows and Mac OS X. Those who saw the keynote of ScottGu during PDC 09, may recollect that an announcement related to this application was made then.

The application can now be downloaded over here

Here are some installation screenshots

image

image

image

image

Once the application is installed, you can view photos, feeds, events, wall comments, inbox mail etc. within in a Cool interface. Here are some screenshots:

Pages

image

Links

image

All Connections

image

Photo Feed

image

I am enjoying accessing my Facebook account through this client! Check out the app over here.

Resolving the error “Validation of viewstate MAC failed” in an ASP.NET 3.5 application

Have you encountered the error

“Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.”

in your ASP.NET application while clicking a button?

The reason for this error is ASP.NET renders some hidden fields, such as the __EVENTVALIDATION field near the bottom of the form, immediately before the closing </div> tag. If event validation is enabled and a user clicks on a button before the page is rendered completely, then __EVENTVALIDATION field is not included in the data that is being posted. Therefore, the .NET Framework treats this postback as invalid and brings up this error.

To resolve this error, a lot of developers set the page property "EnableViewStateMac" to false. Although this may resolve the error in some cases, this is not the preferred way.

To resolve this error, if you are using .NET 3.5, upgrade to .NET 3.5 SP1. If you are using .NET 2.0, then upgrade to .NET 2.0 SP2.

By default, in ASP.NET 3.5 SP1, all system-generated hidden fields are rendered at the top of the page. This makes sure that the information in these fields is sent to the server even if a postback is performed, before the page has finished loading.

If you want to render system-generated fields at the bottom of the page, set the RenderAllHiddenFieldsAtTopOfForm property to False.

<pages renderAllHiddenFieldsAtTopOfForm="false" />


Here is one good resource to learn more about this error

Convert String to Base64 and Base64 to String

The System.Text.Encoding class provides methods to convert string to Base64 and vice versa

String to Base64

The conversion involves two processes:

a. Convert string to a byte array

b. Use the Convert.ToBase64String() method to convert the byte array to a Base64 string

C#

byte[] byt = System.Text.Encoding.UTF8.GetBytes(strOriginal);
// convert the byte array to a Base64 string
strModified = Convert.ToBase64String(byt);

VB.NET

Dim byt As Byte() = System.Text.Encoding.UTF8.GetBytes(strOriginal)
' convert the byte array to a Base64 string
strModified = Convert.ToBase64String(byt)

Base64 string to Original String

In order to convert a Base64 string back to the original string, use FromBase64String(). The conversion involves two processes:

a. The FromBase64String() converts the string to a byte array

b. Use the relevant Encoding method to convert the byte array to a string, in our case UTF8.GetString();

C#

byte[] b = Convert.FromBase64String(strModified);
strOriginal = System.Text.Encoding.UTF8.GetString(b);

VB.NET

Dim b As Byte() = Convert.FromBase64String(strModified)
strOriginal = System.Text.Encoding.UTF8.GetString(b)

Check out some additional String functions over here 30 Common String Operations in C# and VB.NET

Prevent Duplicate Entries in a HTML DropDown

I was recently asked a question on the ASP.NET forum on how to prevent duplicate entries being added to a select form element. The user could type anything into a text box, then click the button and it was being added. This is another good use for jQuery! Here's the code.

<html>
<
head>
<
script language="javascript" type="text/javascript"
src="http://code.jquery.com/jquery-latest.js"></script>
<
script language="javascript" type="text/javascript">
$(function() {
$("#Button1").click(function(e) {
var itemExists = false;
var txt = $("#Text1").val();
e.preventDefault();
$("#Select1 option").each(function() {
if ($(this).text() == $.trim(txt)) {
itemExists = true;
alert('Item already exists');
}
});

if (!itemExists) {
$("#Select1").append("<option value=\"1\">" + txt + "</option>");
$("#Text1").val('');
}
});
});
</script>
</
head>
<
body>
<
form>
<
input id="Button1" type="button" value="Add" /><br />
<
input id="Text1" type="text" />
<
select id="Select1">
<
option value="1">Yahoo</option>
<
option value="2">Microsoft</option>
<
option value="3">Google</option>
</
select>
</
form>
</
body>
</
html>



Now duplicate items are not added.

Note: To ignore case, use .toLowerCase() or .toUpperCase() to compare both strings.

See a Live Demo

Ohloh – Open Source Software directory

I recently stumbled upon Ohloh and thought of letting you all know about it. As given on the site “Ohloh is a free public directory of open source software and people. Ohloh is a wiki, and anyone is welcome to join our community and add new projects to our directory, or to make corrections to existing directory pages. This public review makes Ohloh one of the largest, most accurate, and up-to-date software directories available.”

You can see a list of open source software over here

Out of the many more open source software directories out there, two worth mentioning are sourceforge and freshmeat. Microsoft’s own CodePlex is an open source project hosting web site and is pretty cool!

How to populate a DropDownList with Culture-specific Month names

DateTimeFormatInfo.MonthNames is a useful property to fetch the culture-specific full names of the month. This property gets a string array containing the names of the month. Remember to add a reference to the System.Globalization namespace.

Here’s how to use this property and populate a DropDownList with month names:

C#

string[] names = DateTimeFormatInfo.CurrentInfo.MonthNames;
DropDownList1.DataSource = names;
DropDownList1.DataBind();

VB.NET

Dim names() As String = DateTimeFormatInfo.CurrentInfo.MonthNames
DropDownList1.DataSource = names
DropDownList1.DataBind()

OUTPUT

image

Explode and Implode an Element using jQuery

The jQuery UI contains an ‘explode’ effect that looks awesome! In this post, I will show you how to explode as well as implode an element using jQuery. Here’s the code to do so:

<!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" xml:lang="en" lang="en">
<
head>
<
script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</
script>
<
script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js">
</
script>
<
title>Explode and Implode an Element using jQuery</title>
<
meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<
style type="text/css">
#outer{
width:70px;
height:70px;
background-color:Blue;
}
</style>
</
head>
<
body>
<
input id="btnAction" type="button" value="Click Me" />
<
div id="outer">
</
div>

<
script type="text/javascript">
$("#btnAction").toggle(
function() {
$("#outer").hide('explode', {}, 600);
},
function() {
$("#outer").show('explode', {}, 600);
}
);
</script>
</
body>
</
html>

As you can observe, we are toggling the explode/implode effect. The arguments specified is as follows: effect( effect, [options], [speed], [callback] )

When you run the code, the UI appears similar to the following:

image

On clicking the button, the element explodes in the following manner:

image

You can also specify an option like the number of pieces to be exploded to/imploded from like this:

 $("#btnAction").toggle(
function() {
$("#outer").hide('explode', { pieces: 25}, 600);
},
function() {
$("#outer").show('explode', { pieces: 25 }, 600);
}
);

Note: I have included the JavaScript and CSS in the same page. Ideally, these resources should be kept in separate folders

See a Live Demo

Add a Row Number to the GridView

Here’s a simple way to add a Row Number to the GridView. Just add the following tags to your <columns> section of your GridView

 <Columns>                       
<
asp:TemplateField HeaderText="RowNumber">
<
ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</
asp:TemplateField>
...
</Columns>

and you will get the following output

image

51 Tips, Tricks, and Recipes with jQuery & ASP.NET Controls – Review by Elijah Manor

I had written an eBook a couple of months ago called ‘51 Tips, Tricks, and Recipes with jQuery & ASP.NET Controls’. The eBook so far has received some good reviews and mentions and I thank everyone for their valuable comments!

Elijah Manor, ASP.NET MVP, ASPInsider, co-host of The Official jQuery Podcast and a famous tech twitterer recently reviewed the eBook on his blog.

Here’s an excerpt of the review:

I recently finished reading the 51 Tips, Tricks, and Recipes with jQuery & ASP.NET Controls eBook by Suprotim Agarwal. The eBook is $14.99 and it comes with a 14 day 100% money back guarantee. It can be ordered from the DotNetCurry website.

This eBook reminded me a lot of Cody Lindley’s jQuery Enlightenment in that it split it’s eBook into small bit size installments (known as recipes) that can be consumed either sequentially or on a individual basis. The recipes are organized into situations or problems that you might want to solve using jQuery. This eBook differs from jQuery Enlightenment in that it focuses on the interaction with ASP.NET WebForms, which has a unique rendering of its server controls ……

You can read the rest of the review over here

Restrict the Drag operation of an Element to its Container using the jQuery UI

I saw a question on one of the forums where a user asked if it was possible to restrict the drag operation of an element to its container using jQuery. In fact, achieving this is quite simple using the jQuery UI. Here’s how:

<!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" xml:lang="en" lang="en">
<
head>
<
script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</
script>
<
script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js">
</
script>
<
title>Drag an Element within its container</title>
<
meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<
style type="text/css">
#outer
{
width: 400px;
height:400px;
border: solid 1px black;
}
#ele{
width:70px;
height:70px;
background-color:Blue;
}
</style>
</
head>
<
body>
<
div id="outer">
<
p id="ele"></p>
</
div>
<
script type="text/javascript">
$(function() {
var opt = {
cursor: "move",
containment: "parent"
};
$("#ele").draggable(opt);
});
</script>
</
body>
</
html>

I have declared an element ‘ele’ inside a container ‘outer’. Observe how I have set the containment option to “parent”. This constrains dragging to within the bounds of the specified element or region.

Now when you will view the page, you will observe that the ‘ele’ element cannot exceed the boundary of its container ‘outer’.

Note: I have included the JavaScript and CSS in the same page. Ideally, these resources should be kept in separate folders

See a Live Demo

Display the details of the GridView Row being Deleted and Cancel the delete operation

The GridView.RowDeleting event occurs when a GridView row's Delete button is clicked, but before the GridView control deletes the row. Handling this event helps you to display details of the row, cancel the delete operation or to perform some checks before the row is deleted.

C#

protected void GV_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int ID = (int)GV.DataKeys[e.RowIndex].Value;
// If you want to cancel the delete operation, you
// can do so by saying e.Cancel = true;
}

VB.NET

Protected Sub GV_RowDeleting(ByVal sender As Object, _
ByVal e As GridViewDeleteEventArgs)
Dim ID As Integer = CInt(GV.DataKeys(e.RowIndex).Value)
' If you want to cancel the delete operation, you
' can do so by saying e.Cancel = true;
End Sub

A GridViewDeleteEventArgs object is passed to the event-handling method, which enables you to determine the index of the current row as well as cancel the delete operation, as shown in the code above.

How To Find if a Select Element has Multiple Selected Items using jQuery

Today on the forums I saw a question that asked is it possible, through JavaScript, to find out if a user has selected any items in a drop down list, and if they have, prompt them with a confirm box asking them a question before performing the next piece of code. I said it was quite easy and here’s how I did it.

<!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>
<
script src="http://code.jquery.com/jquery-latest.js"
language="javascript" type="text/javascript"></script>
<
script language="javascript" type="text/javascript">
$(function() {
$("#Button1").click(function() {
if ($("#Select1 option").is(":selected")) {
if (confirm("Are you sure you want to delete?")) {
$("#Select1 option:selected").each(function() {
alert("Deleting: " + $(this).val());
});
}
}
});
});
</script>
</
head>
<
body>
<
select id="Select1" multiple="multiple">
<
option value="1">1</option>
<
option value="2">2</option>
<
option value="3">3</option>
</
select>
<
input id="Button1" type="button" value="button" />
</
body>
</
html>


When the user clicks the button, if they haven’t selected any items in the drop down list, they won’t be prompted, but if they have, then they will be. Another good use of jQuery!

Note: This code does not delete the items of the DropDownList.

See a Live Demo

Convert Char[] to String and Vice Versa

Today I was asked a question on the forums to convert a char array to string and vice versa. Here’s the code to do so:

C#

static void Main(string[] args)
{
char[] cArr = { 'a', 'b', 'c', 'd', 'e', 'f'};
// Convert char[] to string
string str = new string(cArr);
Console.WriteLine("char[] to string: {0}", str);

// Convert string to char[]
Console.WriteLine("string to char[]");
char[] newArr = str.ToCharArray();
for (int i = 0; i < newArr.Length; i++)
Console.WriteLine(newArr[i]);
Console.ReadLine();
}

VB.NET

Sub Main(ByVal args() As String)
Dim cArr() As Char = { "a"c, "b"c, "c"c, "d"c, "e"c, "f"c}
' Convert char[] to string
Dim str As New String(cArr)
Console.WriteLine("char[] to string: {0}", str)

' Convert string to char[]
Console.WriteLine("string to char[]")
Dim newArr() As Char = str.ToCharArray()
For i As Integer = 0 To newArr.Length - 1
Console.WriteLine(newArr(i))
Next i
Console.ReadLine()
End Sub

OUTPUT

image

Generate a Random Floating Point Number between two Numbers

The Random.NextDouble() method returns a random number between 0.0 and 1.0. However what if you want to specify the upper and lower limits and then generate a random double number? Here’s some code I had written a couple of months ago to generate a random double number between two numbers:

C#

class Program
{
static void Main(string[] args)
{
double dr = GenRand(1.0, 20.0);
Console.WriteLine(dr);
Console.ReadLine();
}

static double GenRand(double one, double two)
{
Random rand = new Random();
return one + rand.NextDouble() * (two - one);
}
}

VB.NET

Friend Class Program
Sub Main(ByVal args() As String)
Dim dr As Double = GenRand(1.0, 20.0)
Console.WriteLine(dr)
Console.ReadLine()
End Sub

Shared Function
GenRand(ByVal one As Double, ByVal two As Double) As Double
Dim
rand As New Random()
Return one + rand.NextDouble() * (two - one)
End Function
End Class

6 jQuery Plug-ins to create Fancy Modal Dialogs

Here is a list of 6 plug-ins you can use to create fancy modal dialogs using jQuery. This section has been taken from my eBook 51 Tips, Tricks and Recipes using jQuery and ASP.NET Controls

BlockUIPlugin (v2) - The jQuery BlockUI Plugin lets you simulate synchronous behavior when using AJAX, without locking the browser. When activated, it will prevent user activity with the page (or part of the page) until it is deactivated. BlockUI adds elements to the DOM to give it both the appearance and behavior of blocking user interaction

ColorBox - A light-weight, customizable lightbox

DOMWindow - jQuery plugin used to create DOM windows

FancyBox - FancyBox is tool for displaying images, html content and multimedia in a Mac-style "lightbox" that floats overtop of web page

jqDialog - jqDialog is a small dialog plugin that provides smooth, persistent, non-intrusive alternatives for alert(), confirm() and prompt(). There is also a notify() dialog that pops up and goes away in X seconds

jqModal - jqModal is a plugin for jQuery to help you display notices, dialogs, and modal windows in a web browser. It is flexible and tiny, akin to a "Swiss Army Knife", and makes a great base as a general purpose windowing framework

jQuery UI DatePicker – Display Multiple Months

Here’s how to display multiple months in the jQuery UI DatePicker using the ‘numberOfMonths’ option.

<label>Multiple Month DatePicker: </label>
<
input id="date2" />
<
script type="text/javascript">
$(function() {
var dt = {
numberOfMonths: 2
};
$("#date2").datepicker(dt);
});
</script>

image

You can even change the DatePicker UI using the different options available. For example, if you wanted to display the year as a dropdown field and also specify the range of years in the dropdown, use the following code:

<body>
<
label>Multiple Month DatePicker: </label>
<
input id="date2" />
<
script type="text/javascript">
$(function() {
var dt = {
changeYear: true,
yearRange: "-3:+3"
};
$("#date2").datepicker(dt);
});
</script>
</
body>

image

The UI shown above displays the year as a dropdown field and displays a range of 3 years both backwards and forward. You can check similar DatePicker options over here to configure the jQuery UI DatePicker

Some Twitter Libraries and Apps in C#

The other day, I was going through a couple of Twitter libraries and apps made in C# and here are some that caught my attention:

linq2twitter - LINQ to Twitter is a LINQ Provider for the Twitter micro-blogging service. It uses standard LINQ syntax for queries and includes method calls for changes via the Twitter API.

tweetsharp - A feature-complete library for the Twitter API. Use this library in your client applications to enable a simple, discoverable fluent interface for building Twitter queries, as well as additional features like asynchronous processing, server-side caching, url shortening, and rate throttling.

Yedda Twitter C# Library - The Yedda Twitter C# Library / or rather a wrapper provides easy access to the Twitter API.

Witty - Witty is a free, open source Twitter client for Windows Vista and XP powered by the Windows Presentation Foundation (WPF).

Csharptwit - The Csharptwitt is an Implementation of Twitter Api in C#.

twitterizer - This net project provides an easy to use, object-oriented interface to twitter's online API

You can check some more C# libraries over here

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

A user recently asked me a question on converting a DataTable to a List<> in .NET 2.0. Here’s the code to do so:

C#

// Assuming there is a DataTable called dt
List<DataRow> drlist = new List<DataRow>();

foreach (DataRow row in dt.Rows)
{
drlist.Add((DataRow)row);
}

VB.NET

' Assuming there is a DataTable called dt
Dim drlist As New List(Of DataRow)()

For Each row As DataRow In dt.Rows
drlist.Add(CType(row, DataRow))
Next row

Please note that this is just a prototype and may not cover all scenarios.

Note: I have not tested this but in .NET 3.5, you should be able to do this:

List<DataRow> drlist = dt.AsEnumerable().ToList();

jQuery UI DatePicker - Update two TextBoxes at the same time with the selected date

The jQuery UI DatePicker widget is very configurable and powerful, and I love using it whenever I can. I was recently working with the DatePicker widget and came across a requirement where two textboxes had to be updated at the same time with the selected date.

Assuming we have two textboxes called ‘date1’ and ‘date2’, to solve this requirement, developers would usually handle the ‘onSelect’ parameter of the datepicker to detect a change and update the second textbox as shown below:

<script type="text/javascript">
$(function() {
$("#date1").datepicker({
onSelect: function() {
$('#date2').val($('#date1').val());
}
});
});
</script>

However the configurable datepicker widget has an ‘altField’ option that allows us to specify a jQuery selector containing the id of the second textbox, making this requirement extremely simple to achieve. Here’s the code:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</
script>
<
link rel="stylesheet" type="text/css" href="
http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css
"/>
<
script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js">
</
script>
<
title>Change value of One Calendar based on the value of the other</title>
</
head>
<
body>
<
label>Choose a date: </label>
<
input id="date1" />
<
br /><br />
<
label>Second date field: </label>
<
input id="date2" />
<
script type="text/javascript">
$(function() {
var dt = {
altField: "#date2"
};
$("#date1").datepicker(dt);
});
</script>
</
body>
</
html>

Here’s a Live Demo

Find selected CheckBoxes in your GridView control

I was recently asked a question on a forum in regards to what rows are selected when you've got an ASP.NET GridView filled with CheckBoxes on a page. The answer is made simple thanks to jQuery. This is the sample table below:

clip_image002

When the user clicks the button they can find all the selected checked check boxes with the following code:

<script language="javascript" type="text/javascript"
src="http://code.jquery.com/jquery-latest.js"></script>
<
script language="javascript" type="text/javascript">
$(function() {
$("#GetSelectedValues").click(function(e) {
$("#GridView1 input:checked").each(function() {
alert($(this).next("label").text());
});
e.preventDefault();
});
});
</script>

Nice and simple.

A recommended way would be to add a class to the GridView and then handle this requirement in the following manner:

Add a class attribute to the GridView (say gv)

<asp:GridView ID="GridView1" class="gv">

and access the control like this:

$(".gv input:checked")

This approach would work even in a MasterPage scenario.

Determine the Element ID on MouseOver using jQuery

A user recently asked me if it was possible to determine the element id when the mouse was hovered over it. This requirement is quite simple using jQuery as demonstrated in the code here:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Find ID on Mouse Hover</title>
<
style type="text/css">
.sample
{
height:100px;
width:200px;
border: solid 1px black;
}
</style>
<
script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</
script>

<
script type="text/javascript">
$(function() {
$('.sample').mouseover(function() {
$('#para').html(this.id);
});
});
</script>
</
head>
<
body>
<
div>
<
div id='divOne' class="sample">
DIVONE
</div>
<
div id='divTwo' class="sample">
DIVTWO
</div>
<
div id='divThree' class="sample">
DIVTHREE
</div>
<
br />
<
br />
<
p id="para" />
</
div>
</
body>
</
html>

See a Live Demo

Windows Azure is now Commercially Available

Microsoft announced the commercial availability of subscriptions for the Windows Azure platform, which includes Windows Azure, SQL Azure, and Windows Azure platform AppFabric.

Customers with Community Technology Preview (CTP) accounts who wish to continue usage of the Windows Azure platform must upgrade their accounts prior to February 1, 2010. New customers can start using the services by signing up for one of the paid subscription offers.

Here are the pricing and offers details.

You can read more about the annoucement over here

If you are an MSDN subscriber, then read this Windows Azure Platform Benefits for MSDN Subscribers

Count the Number of Words in a TextArea using jQuery

If you were looking out for a script to count the number of words in a TextArea, then here it is:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Count Words in a TextArea</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() {
$("#btnCount").click(function() {
var strText = jQuery.trim($('#txtArea').val());
alert('Total No of Words are: ' + strText.split(/\s+/).length);
});
});
</script>
</
head>
<
body>
<
div>
<
textarea id="txtArea" cols="20" rows="10">
</
textarea>
<
br />
<
input id="btnCount" type="button" value="Count Words" />
</
div>
</
body>
</
html>

OUTPUT

image

See a Live Demo

Setting a Default Button in ASP.NET MVC using jQuery

In ASP.NET MVC, there's no concept of a default button as there is in ASP.NET WebForms. To mimic this functionality, this can be accomplished quite painlessly using jQuery. Here's the code to do it.

<script type="text/javascript">
var
ButtonKeys = { "EnterKey": 13 };
$(function() {
$("#MainForm").keypress(function(e) {
if (e.which == ButtonKeys.EnterKey) {
var defaultButtonId = $(this).attr("defaultbutton");
$("#" + defaultButtonId).click();
return false;
}
});
});
</script>
<% using (Html.BeginForm("DefaultButtonTest", "Home", FormMethod.Post,
new { defaultbutton = "SubmitButton",id="MainForm" })){%>
<%= Html.TextBox("test")%>
<input type="submit" name="btnSubmit" id="SubmitButton" value="Submit" />
<%}%>

If you run this example and view the HTML source, you'll see the defaultbutton attribute has been added

<form action="/Home/DefaultButtonTest" defaultbutton="SubmitButton"
id="MainForm" method="post">
<
input id="test" name="test" type="text" value="" />
<
input type="submit" name="btnSubmit" id="SubmitButton" value="Submit" />
<
input type="submit" name="btnSubmit" id="CancelButton" value="Cancel" />
</
form>

6 SlideShow and Image Gallery jQuery Plug-ins

Here is a list of 6 plugins you can use to create SlideShows and Image Galleries using jQuery. This section has been taken from my eBook 51 Tips, Tricks and Recipes using jQuery and ASP.NET Controls

Cycle - The jQuery Cycle Plugin is a lightweight slideshow plugin. It supports pause-on-hover, auto-stop, auto-fit, before/after callbacks, click triggers and many transition effects.

jOmino - Wrap your html elements in a jQuery collection and animate them with a dominoes in motion effect.

PanelGallery - A simple image gallery where the images are sliced and faded in one piece at a time.

PikaChoose - PikaChoose is a image gallery plugin. You place images into an unordered list structure and let PikaChoose do the rest for you

Pliable Photo Gallery - Easy embeddable JavaScript based photo gallery. Great for showing off a small group of images. Guiding principles: simple, less requirements, more conventions

SlicedImageSlider - This plug-in provides sliced Image Navigation. The plugin loops through the given images and displays each image partitioned into n number of slices. It also has other options like direction in which you want the image to slide

If you have used any other image gallery plug-in, drop in a comment and let others know about it.

Programmatically determine the directory where ASP.NET stores temporary files

Today in the forums, I came across an interesting question. The user wanted to know if it was programmatically possible to determine where ASP.NET stored its temporary files.

The answer is yes and it’s done using the HttpRuntime.CodegenDir Property

C#

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

VB.NET

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Response.Write(HttpRuntime.CodegenDir)
End Sub

Running this on my machine, I get the following output

C:\Users\Suprotim\AppData\Local\Temp\Temporary ASP.NET Files\SampleProjects\e2b93d07\cc8b1498

DevCurry completes One Year. Happy New Year!

Happy New Year everyone! Today, it is exactly one year since I launched www.devcurry.com and what a journey it has been! Check my first post Why did I start a new Blog?

I can proudly say that in a years time, www.devcurry.com has grown to be a popular blog amongst developers. With one post a day, DevCurry had something new for its readers everyday. We published 365 posts last year and this would not have been possible alone. Malcolm Sheridan and Mahesh Sabnis also contributed posts to DevCurry and I thank them for their contributions.

Many of you have regularly written to me and shared your valuable feedback. Thanks for the same. Although I have not been able to reply to each one of them, I do make it a point to read them, as and when I find time. I hope to see many more rounds of interactions with my readers and look forward to another fun-filled year and also hope that I will be able to stick to my routine of posting one post everyday. Wish me luck!

You can keep up with the blog by Subscribing to the Feeds or Subscribing via Email.

Cheers and have a wonderful year ahead!