jQuery, Silverlight, WPF, SharePoint and .NET articles Link List – May 2011

Here’s a quick wrap up of jQuery, WPF, Silverlight, SharePoint and other .NET articles published on DevCurry.com in the month of May 2011.

jQuery and JavaScript Articles

JavaScript: Recursive Anonymous Function - I recently saw a question on the forums – How to make a JavaScript anonymous function refer to itself? In other words, how to make an anonymous function in JavaScript call itself from within itself.

Extract Object Values using ECMAScript 5 methods - I find the Object.keys method on ECMAScript 5 extremely useful to return an array containing enumerable properties on a given object. I had a JavaScript object and wanted to extract the values of the object in the shortest possible way.

String as Read-only Arrays in JavaScript - During a tech gathering, we were discussing how String acts as a read-only array in JavaScript in the latest browsers. Many of the developers did not know about this, so I thought to write a short post on the same.

Parsing XML using jQuery - I was recently asked if there was a simple way to parse XML using jQuery. My answer was I would always prefer serializing my data to JSON and then read it using jQuery. However if you do not have that option available for some reason, here’s a simple example of reading an XML document using jQuery

jQuery: Editable Combo Box - I stumbled across a cool jQuery plugin that allows you to have editable combo box (HTML Select element). Using this plug-in, you can add, remove and edit items from the list

jQuery 1.6 Released - The jQuery team recently announced the release of version 1.6. This latest version boosts performance as the team has rewritten the way jQuery handles HTML attributes. Event Handlers now perform better, so do animations, with the introduction of a timer that can sync multiple animations to the same timer interval. There are many bug fixes as well

Silverlight and WPF articles

WPF 4: Using DataGrid Context-Menu for Performing Insertion and Deletion Operations - In most cases, when you develop WPF UI application with the DataGrid control, end-users demand Excel like features with various shortcuts for performing Insert and Delete operations. The WPF DataGrid Context Menu helps us to develop similar kind of UI applications.

WPF 4: Using Input Bindings to Go Mouseless - While creating the UI of an application, we need to adopt techniques that makes the user comfortable with the app. If the existing user is habitual of using shortcut keys for various operations, then while developing the new user interface, it is necessary for the UI developer to provide a similar functionality. In WPF, we have such a facility using ‘InputBindings’.

Silverlight 4: Nested DataGrid for Master-Details Scenarios - The Silverlight DataGrid is a very commonly used control for displaying huge amounts of data. Similarly to save screen space and display Master-Details scenarios, a Nested DataGrid is recommended.

Silverlight 4 and COM: Sending Mails Using Outlook - In this post we will see how to access Microsoft Outlook for sending an Email using Silverlight and COM object.

Silverlight 4: Convert Text to Speech - In this post, we will see how to use Silverlight and COM to convert text into speech. We will be using the  the ‘SAPI.SpVoice’ API.

Access Camera using Silverlight 4.0 and COM - In this post, we will see how to access a Camera using Silverlight 4.0 Out-Of-Browser and COM.

Silverlight 4 DataGrid Filtering using DataGridColumnStyle - In Silverlight 4, the DataGrid control provides many features for effective data representation. I must say that most of the end-user’s requirements for Tabular Data representation and interaction can be easily accomplished using the DataGrid control.

Silverlight 5 Beta – Unrestricted File Access in Browser - In this post, we will explore Silverlight 5 Beta unrestricted file access within a browser with elevated trust.

Enterprise Library 5 for Silverlight - Silverlight Integration Pack for Enterprise Library is a collection of guidance and reusable application blocks designed to assist Silverlight application developers with common LOB development challenges.

Silverlight 5 Beta - WebBrowser Control In Browser to Display HTML - In this post, we will see how to use WebBrowser control to display HTML contents in browser using Silverlight 5 beta. In Silverlight 4, we can use the WebBrowser control only in 'Out-Of-Browser' applications.

Silverlight 4: Hide/Unhide DataGrid Columns - Silverlight DataGrid is a nice control provided for Data representation as well as manipulation. Since this control provides its object model separately e.g. DataGridColumn, DataGridColumnHeader etc, it is very easy for us to provide custom data representation capability to this control.

.NET and SharePoint Articles

ASP.NET 4 Granular View State - In this post, we will see how to control a view state at Page level as well as Control level.

Windows Phone 7 applications with SharePoint 2010 Products - Microsoft has released a cool whitepaper that describes how to build Windows Phone 7 applications with SharePoint 2010 Products and Microsoft Forefront Unified Access Gateway (UAG).

.NET - Start Asynchronous Parallel Task and Cancel Them Too - I was having a good discussion with a couple of friends about the support of parallel tasks in .NET. If you too are interested in the same, I have written a couple of articles that can give you an overview of the support for parallelism and concurrency in .NET applications.

Technical Documents for Microsoft SharePoint Server and Foundation 2010 - Microsoft has released two documents that includes technical information about the Microsoft SharePoint Server and Foundation 2010 provider for Windows PowerShell and other helpful reference information about general settings, security, and tools.

Remove all Lower Case Letters using C# - I came across a discussion where the OP wanted to use only the first letter of a word in a string. The first letter of each word was capitalized, so his requirement was to abbreviate the sentence by removing all lower case letters in a string

SharePoint 2010 Performance and Capacity Recommendation - Microsoft has released a series of SharePoint whitepapers and articles that contains information about the performance and capacity characteristics of each SharePoint feature and how it was tested by Microsoft.

Other Articles

Visual Studio Async CTP (SP1 Refresh) - For those who are new to Visual Studio Async, it extends Visual Studio 2010 and provides streamlined syntax for asynchronous development in C# and Visual Basic.

Test Websites in Different IE Browser Versions - If you have a requirement of testing your websites in older versions of Internet Explorer, Microsoft has provided VHD’s (Virtual Hard Disk) with Windows set up with the specified version of Internet Explorer. Here’s the list

Windows Phone 7 ‘s Next Release called Mango announced –Important Links - Microsoft announced the next release of Windows Phone 7 – code named Mango. The primary focus of this Beta release has been  app centric multitasking (partial), IE9 Webbrowser controls (HTML 5 support comes in naturally),  Silverlight 4 and XNA support, additional sensors, Direct camera access, VB.NET support, Local SQL DB, and more.

Office 2011 for Mac: Free Training - If you are using Office 2011 for Mac or plan to do so, then here’s some free training material for you to get up and started with Office 2011. Microsoft has released a set of training downloads (.pdf) and PowerPoint (.pptx) slides of all Office 2011 tutorials and videos.

Win .NET EBooks and PluralSight Training in this GiveAway - My other site DotNetCurry.com is doing a GiveAway to celebrate it’s 4 year on the web. There are 156 prizes consisting of .NET Books, Software and Training and you can win them too!!

Office 2011 for Mac: Free Training

If you are using Office 2011 for Mac or plan to do so, then here’s some free training material for you to get up and started with Office 2011. Microsoft has released a set of training downloads (.pdf) and PowerPoint (.pptx) slides of all Office 2011 tutorials and videos.

Here are the download links:
These training can be customized for group training and you can even view them on your desktop. You can also access the same training over here too www.microsoft.com/mac/how-to

ASP.NET 4 Granular View State

In this post, we will see how to control a view state at Page level as well as Control level. In ASP.NET 4.0, Microsoft has provided a property called 'ViewStateMode' at control level. Now you can turn OFF the View state at Page level and turn ON viewstate at Control level as per your requirements.

Note: In ASP.NET 3.5, when you disable view state at web application level from your web.config file, you cannot enable it at control or page level.

So let's create a simple web site as shown below -

ASP.NET New Website

Now design a Default.aspx page as shown below -

Sample ASP.NET Form

Add a User Control with the name 'CustomersData' to display all the customers in a Grid from Northwind Database as shown below -

image

Add this user control in our Default.aspx page. Now run the Default.aspx page and view the page source as shown below -

clip_image002[6]

We will now disable the view state at Page level as well as Control level.

viewstate-controlstate

Re-run Default.aspx page and view the code.

granular view state

Observe the difference in the previous view state and this view state.

Even if view state of the Page is disabled, you can enable it at control level by using 'ViewStateMode' property at control level as shown below -

viewstatemode

The above code will enable the view state for a Textbox 'txtCustomerName' even if the Viewstate is disabled at page level.

Download the source code

SharePoint 2010 Performance and Capacity Recommendation

Microsoft has released a series of SharePoint whitepapers and articles that contains information about the performance and capacity characteristics of each SharePoint feature and how it was tested by Microsoft. Here’s a list of them:

Capacity Planning Key Concepts

Capacity management and sizing for SharePoint Server 2010 – Explains the key concepts behind capacity management in SharePoint Server 2010.

Performance and Capacity Planning of SharePoint 2010 Features

Business Connectivity Services - Provides guidance on the footprint that use of Business Connectivity Services has on topologies running SharePoint Server 2010

SharePoint Server Caches Overview - Provides information about how the three SharePoint Server 2010 caches help the product scale and grow to meet the demands of your business application

Designing large lists and maximizing list performance (SharePoint Server 2010) - Provides guidance on performance of large document libraries and lists. This document is specific to SharePoint Server 2010, although the throttles and limits that are discussed also apply to Microsoft SharePoint Foundation 2010

Large-scale document repositories - Provides guidance on performance of large-scale document repositories in regards to SharePoint Server 2010.

Estimate capacity and performance for enterprise managed metadata in SharePoint Server 2010 - Provides guidance on how to perform sizing and performance optimization of the managed metadata service in SharePoint Server 2010

My Sites and Social Computing Capacity Planning - Provides guidance on the footprint that use of My Sites and other social computing features has on topologies running SharePoint Server 2010

Estimate performance and capacity requirements for PerformancePoint Services - Provides guidance on the footprint that usage of PerformancePoint Services has on topologies running SharePoint Server 2010

Estimate performance and capacity requirements for SharePoint Server 2010 Search - Discusses capacity planning for different deployments of SharePoint Server 2010 search, including small, medium, and large farms

Capacity requirements for the Web Analytics Shared Service in SharePoint Server 2010 - Provides guidance on the footprint that use of the Web Analytics service has on topologies running SharePoint Server 2010

Estimate performance and capacity requirements for Web Content Management in SharePoint Server 2010 - Provides guidance on performance and capacity planning for a Web Content Management solution

Estimate performance and capacity planning for workflow in SharePoint Server 2010 – Provides guidance on the footprint that usage of Workflow has on topologies running SharePoint Server 2010

Office Apps Capacity Planning (SharePoint 2010)

Estimate performance and capacity requirements for Access Services in SharePoint Server 2010 - Provides guidance on how using Access Services impacts topologies running SharePoint Server 2010

Estimate performance and capacity requirements for Visio Services in SharePoint Server 2010 - Provides guidance on the footprint that use of Visio Services has on topologies running SharePoint Server 2010

Office Web Apps Capacity Planning - Provides guidance on the footprint that use of Office Web Apps has on topologies running SharePoint Server 2010

Estimate performance and capacity requirements for Excel Services in SharePoint Server 2010 - Provides planning guidance for Excel Services in Microsoft SharePoint Server 2010

Estimate performance and capacity requirements for InfoPath Forms Services in SharePoint Server 2010 - Provides guidance on the footprint that use of InfoPath Forms Services has on topologies running SharePoint Server 2010

Word Automation Services Capacity Planning - Provides capacity planning guidance for Word Automation Services in SharePoint Server 2010

Remove all Lower Case Letters using C#

I came across a discussion where the OP wanted to use only the first letter of a word in a string. The first letter of each word was capitalized, so his requirement was to abbreviate the sentence by removing all lower case letters in a string.

For example: ‘We Love DevCurry.com’ would become ‘WLDC’

Here’s how this can be achieved with a Regular expression. Use the following code:

using System;
using System.Text.RegularExpressions;

namespace WordCapital
{
class Program
{
static void Main(string[] args)
{
string fulltext = "We Love DevCurry.com";
Console.WriteLine("Full Text: {0}", fulltext);
Regex rgx = new Regex("[^A-Z]");
Console.WriteLine("Abbreviated Text : {0}", 
rgx.Replace(fulltext, ""));
Console.ReadLine();
}
}
}

In the code above, we are using Regex to match all characters that are not capitalized and then replace it with an empty string.

OUTPUT

image

jQuery: Editable Combo Box

I stumbled across a cool jQuery plugin that allows you to have editable combo box (HTML Select element). Using this plug-in, you can add, remove and edit items from the list.

Although the plug-in demos have clear instructions on how to setup the plug-in, for the sake of a complete post, here’s how to use this plug-in in your applications:

Step 1: Download the Plug-in and save it as jquery.eComboBox.min.js. Reference the plugin in your page as shown below:

jQuery Combo Edit plugin

Step 2: Declare an HTML Select/ Combo Box on the page

jQuery Combo Edit plugin

Step 3: Call the eComboBox method on the select element

image

and that’s it. Now load the page and select an element. Start typing in the box and the element will be edited. Hit Enter to save.

jQuery Editable Combo Demo

Similarly to add a new element, select {NEW ELEMENT} and start typing the element name. Hit Enter to save.
To Delete, select the element and hit delete on your keyboard.

There are a couple of options you can use to prevent editing, deleting or adding new elements too. Explore them here with a Live Demo

Windows Phone 7 ‘s Next Release called Mango announced –Important Links

Microsoft announced the next release of Windows Phone 7 – code named Mango. The primary focus of this Beta release has been  app centric multitasking (partial), IE9 Webbrowser controls (HTML 5 support comes in naturally),  Silverlight 4 and XNA support, additional sensors, Direct camera access, VB.NET support, Local SQL DB, and more.

You can get an overview of what’s new by watching this video.





Here are some important links:
Although Microsoft aims at bringing the phone at par with IOS and Android, there’s still a long long way to go! The latest version of IOS 4 and Android 3 are way ahead in feature and functionality. But MS is on the right direction. Windows Phone 7.5 s/w update is expected around Christmas. So stay tuned and Happy Mango coding!

Parsing XML using jQuery

I was recently asked if there was a simple way to parse XML using jQuery. My answer was I would always prefer serializing my data to JSON and then read it using jQuery. However if you do not have that option available for some reason, here’s a simple example of reading an XML document using jQuery

Assuming you have made a $.ajax() call and have a string with XML data. Here’s how to read it

Parse XML jQuery

The example is very simple. We are using the jQuery.find to get the descendants of each element that matches the selector and then adding the values in a paragraph using append().

Note: In IE8, this example won’t work. However in a real app scenario, you would use an ajax call to read the XML. Just use content-type: text/xml in your XML and this will fetch you  an XML object which can be read in IE8.

Technical Documents for Microsoft SharePoint Server and Foundation 2010

Microsoft has released two documents that includes technical information about the Microsoft SharePoint Server and Foundation 2010 provider for Windows PowerShell and other helpful reference information about general settings, security, and tools.


The audiences for these books are business application specialists, line-of-
business specialists, information architects, IT generalists, program managers, and
infrastructure specialists who are planning a solution based on SharePoint Foundation
2010.

You may also want to looks at some Video demos and training for SharePoint Server 2010 subject matter experts and TechNet writers walk through tasks and dynamically explain SharePoint-related concepts

String as Read-only Arrays in JavaScript

During a tech gathering, we were discussing how String acts as a read-only array in JavaScript in the latest browsers. Many of the developers did not know about this, so I thought to write a short post on the same. For eg: let us say you have a string as shown below:

var str = “Sample”;


Now you can access individual characters in a String, just like an array

alert(str[2]); // returns ‘m’


and even apply some array functions on it.

alert(Array.prototype.join.call(str, ",") // returns S,a,m,p,l,e,


Note: While applying array functions on the String, remember that the string is behaving like read-only array. So functions that manipulate the string won’t work!

.NET - Start Asynchronous Parallel Task and Cancel Them Too

I was having a good discussion with a couple of friends about the support of parallel tasks in .NET. If you too are interested in the same, I have written a couple of articles that can give you an overview of the support for parallelism and concurrency in .NET applications.

Parallel Tasks in .NET 4.0 -   The Parallel class found in the System.Threading.Tasks namespace “provides library-based data parallel replacements for common operations such as for loops, for each loops, and execution of a set of statements”. In this article, we will use the Invoke method of the Parallel class to call multiple methods, possibly in parallel.

Parallel Tasks in .NET 4.0 (Part II) – Methods that Return value - In one of the previous articles Parallel Tasks in .NET 4.0, we explored a set of new API’s called the "Task Parallel Library (TPL)" which simplifies the process of adding parallelism and concurrency to applications. We used the System.Threading.Tasks.Parallel.Invoke() to call methods that did not return a value. However for methods that return a value, you would need to use the Task(TResult) class which represents an asynchronous operation that can return a value. We will explore how to use this class in this article

Cancelling Tasks in .NET 4.0 - In one of the previous articles Parallel Tasks in .NET 4.0 (Part II) – Methods that Return value, we used the Task(TResult) class which represents an asynchronous operation that can return a value. In this article, we will see how to cancel a task/operation.

Parallel.For Method in .NET 4.0 vs the C# For Loop - In this article, we will explore the static method Parallel.For. A lot of developers ask me about the difference between the C# for loop statement and the Parallel.For. We will see the difference with an example

On a side note, there are many ways to call a method asynchronously using .NET Delegates. Here are two articles that give you an overview of the same

Call a Method Asynchronously using Delegate BeginInvoke and EndInvoke Pattern - In this article, we will explore multiple ways to call a method asynchronously using Delegates. You can call methods asynchronously in four different ways using the BeginInvoke() and EndInvoke() methods of the Delegate class

Call a Method Asynchronously in .NET using Polling Pattern and Callback Pattern - In my previous article, we explored multiple ways to call a method asynchronously using Delegates. In this article, we will see how to call a method asynchronously using the Delegate Polling pattern and the Callback Pattern.

Extract Object Values using ECMAScript 5 methods

I find the Object.keys method on ECMAScript 5 extremely useful to return an array containing enumerable properties on a given object. I had a JavaScript object and wanted to extract the values of the object in the shortest possible way. Since my app was targeting the latest browsers, I decided to use Object.keys and the Array.map() method to achieve the task

Here’s how it was done. First, the object is declared as shown here:

EcmaScript Object.Keys

In order to extract values from the object, we are using the following code:

var values = ExtractValues(jObj);
alert(values);

function ExtractValues(o) {
    return Object.keys(o).map(function (objKey) {
        return o[objKey];
    });
}



As you can see, we are using Object.keys to return an array with properties and then use map which provides a callback function once for each element in an array, and constructs a new array from the results.

Here’s the output

image

Note: As of this writing, this code will work in IE9, Firefox 4, Safari 5 and Chrome 6-11.

Silverlight 4: Hide/Unhide DataGrid Columns

Silverlight DataGrid is a nice control provided for Data representation as well as manipulation. Since this control provides its object model separately e.g. DataGridColumn, DataGridColumnHeader etc, it is very easy for us to provide custom data representation capability to this control. In this article, I have demonstrated how to hide/unhide DataGrid columns depending on the user selection. This caters to requirements where the end-user wants to see only selected data column values from the source.

Step 1: Open VS 2010 and create Silverlight 4 project. Name it as ‘SL4_Hiding_Unhiding_DataGrid_Columns’. To this project, add the following classes. These classes will be used as a data source.

/// <summary>
/// Class containing Employee Details
/// </summary>
public class Employee
{
    public int EmpNo { get; set; }
    public string EmpName { get; set; }
    public string DeptName { get; set; }
    public string Designation { get; set; }
    public decimal Salary { get; set; }
}

/// <summary>
/// Class contains Employee Collection
/// </summary>
public class EmployeeCollection : ObservableCollection<Employee>
{
public EmployeeCollection()
{
    Add(new Employee() { EmpNo = 101, EmpName = "Ram",
        DeptName = "Admin", Designation = "Supreme", Salary = 890000 });
    Add(new Employee() { EmpNo = 101, EmpName = "Bharat",
        DeptName = "Treasury", Designation = "Head", Salary = 390000 });
    Add(new Employee() { EmpNo = 101, EmpName = "Lakshman",
        DeptName = "Security", Designation = "Head", Salary = 290000 });
    Add(new Employee() { EmpNo = 101, EmpName = "Shatrugnaha",
        DeptName = "External Affairs", Designation = "CEO", Salary = 790000 });
    Add(new Employee() { EmpNo = 101, EmpName = "Kirshna",
        DeptName = "Admin", Designation = "Supreme", Salary = 190000 });
    Add(new Employee() { EmpNo = 101, EmpName = "Balram",
        DeptName = "Security", Designation = "Head", Salary = 390000 });
    Add(new Employee() { EmpNo = 101, EmpName = "Gautam",
        DeptName = "Education", Designation = "Supreme", Salary = 790000 });
    Add(new Employee() { EmpNo = 101, EmpName = "Bhargav",
        DeptName = "Security", Designation = "Head", Salary = 990000 });
    Add(new Employee() { EmpNo = 101, EmpName = "Vaman",
        DeptName = "Education", Designation = "Head", Salary = 190000 });
    Add(new Employee() { EmpNo = 101, EmpName = "Udhav",
        DeptName = "External Affairs", Designation = "Head", Salary = 290000 });
}
}



Step 2: In the MainPage.xaml.cs, add a class for storing MetaInfo of the Employee class. This class we will be used to read all public property names in the Employee class. This class will be further used for binding with the ListBox. The end user will select property name from this list box to hide column. The class code is as shown below:

image

Step 3: In the MainPage.Xaml.cs and in the MainPage class, declare the List<ColumnDetails> object. Also write the following method which will read the Employee class using ‘typeof’ operation (Reflection in short) and load its properties in List< ColumnDetails >. The code is as below:

image

and here’s the method:

image

Step 4: In the MainPage.xaml write the following xaml:

<UserControl x:Class="SL4_Hiding_Unhiding_DataGrid_Columns.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="458" d:DesignWidth="844"
             xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
             Loaded="UserControl_Loaded">
    <UserControl.Resources>
        <DataTemplate x:Key="ColumnNameTemplate">
                <CheckBox Width="140" IsChecked="{Binding IsSelected}"
                          Content="{Binding ColumnName}" Click="chBkx_Click"></CheckBox>
        </DataTemplate>
    </UserControl.Resources>

    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="54*" />
            <RowDefinition Height="404*" />
        </Grid.RowDefinitions>
        <TextBlock Name="textBlock1" Text="Employee Information" TextAlignment="Center"
    FontSize="40" />
        <sdk:DataGrid AutoGenerateColumns="False" Grid.Row="1" Height="359"
                      HorizontalAlignment="Left" Margin="29,23,0,0" Name="dgEmp"
                      VerticalAlignment="Top" Width="620" ColumnWidth="*">
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn Header="EmpNo" Binding="{Binding EmpNo}">
        </sdk:DataGridTextColumn>
                <sdk:DataGridTextColumn Header="EmpName" Binding="{Binding EmpName}">
        </sdk:DataGridTextColumn>
                <sdk:DataGridTextColumn Header="DeptName" Binding="{Binding DeptName}">
        </sdk:DataGridTextColumn>
                <sdk:DataGridTextColumn Header="Designation" Binding="{Binding Designation}">
        </sdk:DataGridTextColumn>
                <sdk:DataGridTextColumn Header="Salary" Binding="{Binding Salary}">
        </sdk:DataGridTextColumn>
            </sdk:DataGrid.Columns>
        </sdk:DataGrid>
        <TextBlock Grid.Row="1" Height="38" HorizontalAlignment="Left" Margin="661,23,0,0"
                   Name="textBlock2" Text="Please Uncheck the Column to Hide:"
            VerticalAlignment="Top"
                   Width="125" TextWrapping="Wrap" />
        <ListBox Grid.Row="1" Height="228" HorizontalAlignment="Right" Margin="0,67,52,0"
                 Name="lstEmployeeColumns" VerticalAlignment="Top" Width="131"
                  ItemTemplate="{StaticResource ColumnNameTemplate}" />
     
    </Grid>
</UserControl>



Step 5: Declare the following object in the MainPage class level and in the Loaded event of the MainPage user control, write the following code:

EmployeeCollection EmpCol;
CheckBox chBkx;

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    EmpCol = new EmployeeCollection();
    //Bind EmployeeCollection to DataGrid
    dgEmp.ItemsSource = EmpCol;
    LoadListWithClassProperties();
    //Bind the ColumnName collection to ListBox
    lstEmployeeColumns.ItemsSource = PropertyDetails;
}



The above code binds the EmployeeCollection object to the DataGrid and also makes a call to the LoadListWithClassProperties() method. Finally it binds the PropertyDetails List object to the ListBox.

Step 6: If you see the above Xaml, it defines the DataTemplate of the name ‘ColumnNameTemplate’. This defines CheckBox and implements the ‘Click’ event. This DataTemplate is passed to the ListBox to display all properties from Employee class with checkboxes. Write the Click event in the code-behind for this checkbox. The code Is as below:

    /// <summary>
        /// The logic for hinding/Unhiding the columns from DataGrid
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void chBkx_Click(object sender, RoutedEventArgs e)
        {
            chBkx = sender as CheckBox;
            bool isChecked = Convert.ToBoolean(chBkx.IsChecked);
            if (isChecked == false)
            {
                foreach (DataGridColumn dgColumn in dgEmp.Columns)
                {
                    if (dgColumn.Header.ToString() == chBkx.Content.ToString())
                    {
                        dgColumn.Visibility = System.Windows.Visibility.Collapsed;
                        break;
                    }
                }
            }
            if (isChecked == true)
            {
                foreach (DataGridColumn dgColumn in dgEmp.Columns)
                {
                    if (dgColumn.Header.ToString() == chBkx.Content.ToString())
                    {
                        dgColumn.Visibility = System.Windows.Visibility.Visible;
                        break;
                    }
                }
            }
        }
    }

The above code is the heart of the article. When the user deselects any checkbox from the ListBox, the DataGridColumn having header matching the property name will be hidden. When the user checks the checkbox, the matching DataGridColumn again gets displayed.

Step 7: Run the application and the initial screen will be as below:

clip_image002

From the ListBox deselect the ‘DeptName’ and the result will be as shown below:

clip_image004
Select the DeptName column again and here’s the result:

clip_image006

Win .NET EBooks, Training and Products in our GiveAway – 5 days left!

We are doing a $38K MegaAway of .NET Products, EBooks and Training on my other site http://www.dotnetcurry.com/.  We are doing this GiveAway to celebrate DotNetCurry’s 4th Year on the Web. There are 156 exciting prizes to be won and I want to invite all my DevCurry.com readers to participate and enter a chance to win prizes in the GiveAway. The contest will last for only 5 more days!

Here are some prizes we are giving away:

.NET Products

.NET Training
3 Annual subscriptions of Pluralsight On-Demand .NET Training

.NET EBooks
O’Reilly is sponsoring 5 copies each of the following EBooks 

There are 156 prizes to be won, so make sure you give it a shot! You may just get lucky! Click this link to participate $38K MegaAway of .NET Products, EBooks and Training

Good luck!

Test Websites in Different IE Browser Versions

If you have a requirement of testing your websites in older versions of Internet Explorer, Microsoft has provided VHD’s (Virtual Hard Disk) with Windows set up with the specified version of Internet Explorer. Here’s the list

Windows XP – IE6, IE7 and IE8
Windows Vista – IE7, IE8 and IE9
Windows 7 – IE8 and IE9

All these set ups are patched with the latest security updates and will run on Microsoft Virtual PC.

Download Internet Explorer Application Compatibility VPC Image

Silverlight 5 Beta - WebBrowser Control In Browser to Display HTML

In this post, we will see how to use WebBrowser control to display HTML contents in browser using Silverlight 5 beta. In Silverlight 4, we can use the WebBrowser control only in 'Out-Of-Browser' applications.

In Silverlight 5 Beta, now we can use WebBrowser control in the Browser (IE). For this, you will have to first configure the Silverlight application to run in-browser with evaluated trust. WebBrowser control is used for reusing the HTML or ASP.NET contents as well as to integrate external websites in our Silverlight application.

To start with this demonstration, let's first create a Silverlight application with the name 'SL5HTMLCotentsInBrowser' and choose ‘Silverlight 5’ as shown below -

Silverlight WebBrowser Project

Now let's design our MainPage.xaml as shown below. Replace the <Grid></Grid> with the following code -

image

In the above code, I have set the Height and Width of the Grid and main page to 600 and 1000 respectively.

Now let's design the HTML page and put some content as shown below -

image

This page is saved by the name - ''SiteInformation.hml' under 'ClientBin\HTML' folder. Now let's apply settings to make our WebBrowser control to work as an in-browser control to display the HTML or ASP.NET contents.

To run the application in a browser with evaluated trust, you will have to configure the application as below -
  1. Change the registry entry to run evaluated trust application in browser.
  2. Configure the application to run 'Out-Of-Browser'. Also make your application to run in Evaluated Trust.
  3. Sign the .XAP file with a test certificate.
  4. Deploy the certificate in 'Trusted Publisher' and 'Trusted Root Certification Authorities'.
All the above steps are explained in depth in my article ' Silverlight 5 Beta - Run Elevated Trust Applications in Browser' on http://www.dotnetcurry.com/.

Once you complete the configuration of the application, let's hit 'F5' to run the application. You will see the HTML page contents within the browser. Now click on the link to see the external sites within the WebBrowser control. The output will be as shown below -

Silverlight 5 WebBrowser
Silverlight 5 WebBrowser

Enterprise Library 5 for Silverlight

Silverlight Integration Pack for Enterprise Library is a collection of guidance and reusable application blocks designed to assist Silverlight application developers with common LOB development challenges.

This release includes: Caching Application Block, Exception Handling Application Block, Logging Application Block, Policy Injection Application Block, Validation Application Block, and Unity Application Block.

These blocks are designed to encapsulate recommended practices which facilitate consistency, ease of use, integration, and extensibility. The release also addresses the needs of those who would like to port their existing LOB applications, that already leverage Enterprise Library, to Silverlight.

Silverlight 5 Beta – Unrestricted File Access in Browser

In this post, we will explore Silverlight 5 Beta unrestricted file access within a browser with elevated trust. In a previous article – ‘Silverlight 5 Beta - Run Elevated Trust Applications in Browser’ on http://www.dotnetcurry.com/, I have explained how to configure Silverlight 5 Elevated Trust application within browser.

To start with, let’s first design a Silverlight application with the name ‘SL5UnrestrictedFileAccess’ and choose Silverlight 5 version as shown below –

Silverlight 5 app

Design MainPage.xaml. Replace the <Grid></Grid> with the following code –

Silverlight 5 app Unrestricted Access

Now let's write the following code in the click event of 'Write To File' as shown below –

clip_image006

The above code will create a file on 'C:\' and write a message which we will entered using a Textbox. Now let's write the code to read the file on the click event of 'Read From File' button click event, as shown below -

clip_image008

Now let's run the application and click the 'Write to File' button by writing the message in our textbox. You will get an exception as shown below -

clip_image010

Let's configure the application to run 'Out - Of - Browser'. Also make your application to run in Elevated Trust. Hit 'F5' and run your application. Click the button to test the application. You will see the file is created on 'C:\Test' folder. Surprised? It will run because it is running our application under 'localhost' URL.

Let's try the same by changing the URL. Instead of localhost, let's write your machine name and now run the application. This time, It will throw an exception as below -

clip_image011

To run the application in a browser with elevated trust, you will have to configure the application as below -

1) Change the registry entry to run evaluated trust application in browser.
2) Configure the application to run 'Out - Of - Browser'. Also make your application to run in Elevated Trust.
3) Sign the .XAP file with test certificate.
4) Deploy the certificate in 'Trusted Publisher' and 'Trusted Root Certification Authorities'.

All the above steps are explained in depth in my article Silverlight 5 Beta - Run Evaluated Trust Applications in Browser’ on http://www.dotnetcurry.com/

Once you complete the configuration steps listed above, run the application and click the button 'Write To File' and you will see the file created on your 'C:\Test' folder with the input message as shown below -

clip_image013

To test this application other than 'localhost' you will have to configure the application in IIS.

Blogger is Back to Normal Now!

For all those who were wondering about the downtime of this blog as well as the others hosted on Google's Blogger, here's the answer - Blogger is Back

There was some data corruption that impacted Blogger’s behavior. Since then, bloggers and readers may have experienced a variety of anomalies including intermittent outages, disappearing posts, and arriving at unintended blogs or error pages.

Infact the post for May 12th Silverlight 4 DataGrid Filtering using DataGridColumnStyle was not available for a couple of hours.  After 20 hours of unable to post, happy to be back again!

Back to blogging now...

Silverlight 4 DataGrid Filtering using DataGridColumnStyle

In Silverlight 4, the DataGrid control provides many features for effective data representation. I must say that most of the end-user’s requirements for Tabular Data representation and interaction can be easily accomplished using the DataGrid control. Let’s consider a scenario where the end-user is working on a Silverlight application where the data is displayed using DataGrid and he wants to filter the data in the column using some control in the Row Header, something similar to that in Microsoft Excel.

To provide such a  functionality in the SL DataGrid, we can make use of the DataGridColumnHeader and apply a style on it. This is possible because the DataGrid control has the separate programmable objects like DataGridCell, DataGridRow etc. using which customization on the DataGrid becomes very easy. Follow these steps:

Step 1: Create a Silverlight application, and add the following classes in it

Silverlight DataGrid Source
The above classes define the Employee Entity type and the Employee Collection type for DataBinding with UI.

Step 2: Open MainPage.Xaml and write the following XAML (Note:Please Drag-Drop DataGrid)

image

The above XAML code has the following important features:
  • The DataGrid defines columns which are bound with the public properties declared in the Employee class.
  • The UserControl resources defines Style which is Targeted to DataGridColumnHeader. The style is defined for the Template property of the DataGridColumnHeader. This Template further defines ControlTemplate which is configured to display TextBox in the DataGridColumnHeader. This TextBox subscribe to the TextChanged event which is implemented in the code-behind.
  • The XAML define two CheckBoxes which subscribe to the Click event.
Step 3: Open MainPage.Xaml.cs and write the following code:

using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace SL4_DataGrid_Column_Sum_and_Grouping
{
    public partial class MainPage_ColumnHeader : UserControl
    {
        EmployeeCollection EmpCol;

        //Boolean variables for filtering conditions. The value of this will be set in Click event of the CheckBoxes.
        bool IsEmpNameFilter = false;
        bool IsDeptNameFilter = false;


        public MainPage_ColumnHeader()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Method for Binding the Initial Data with The DataGrid
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            EmpCol = new EmployeeCollection();
            dgEmp.ItemsSource = EmpCol;
        }

        /// <summary>
        /// The ChekcBox click for EmpName Column.
        /// When Clicked and Checked, the DataGridColumnHeader will show the TextBox
        /// User now type values in this TextBox to filter the EmpName Column Values
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkEmpName_Click(object sender, RoutedEventArgs e)
        {
            DataGridColumn Dc = dgEmp.Columns[1];
            bool? Selected = chkEmpName.IsChecked;
            if (Selected == true)
            {
                Style sty = this.Resources["dgHeaderStyle"] as Style;
                Dc.HeaderStyle = sty;
                IsEmpNameFilter = true;
            }
            else
            {
                Dc.HeaderStyle = null;
                dgEmp.ItemsSource = EmpCol;
            }
        }
        /// <summary>
        /// The ChekcBox click for DeptName Column.
        /// When Clicked and Checked, the DataGridColumnHeader will show the TextBox
        /// User now type values in this TextBox to filter the DeptName Column Values
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkDeptName_Click(object sender, RoutedEventArgs e)
        {
            DataGridColumn Dc = dgEmp.Columns[2];
            bool? Selected = chkDeptName.IsChecked;
             if (Selected == true)
             {
                
                 Style sty = this.Resources["dgHeaderStyle"] as Style;
                 Dc.HeaderStyle = sty;
                 IsDeptNameFilter = true;
             }
             else
             {
                 Dc.HeaderStyle = null;
                 dgEmp.ItemsSource = EmpCol;
             }
        }

        
        /// <summary>
        /// This method will filter the collection based upon the the Boolean
        /// value. The filter will be either on the EmpName column or on DeptName
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtFilter_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (IsEmpNameFilter)
            {
                var Res = from Emp in EmpCol
                          where Emp.EmpName.StartsWith((sender as TextBox).Text)
                          select Emp;
                dgEmp.ItemsSource = Res;
            }
            if (IsDeptNameFilter)
            {
                var Res = from Emp in EmpCol
                          where Emp.DeptName.StartsWith((sender as TextBox).Text)
                          select Emp;
                dgEmp.ItemsSource = Res;
            }
        }
    }
}


 

Every method in the above class has self-explanatory comments. The Style defined in the XAML is accessed in the code-behind and is applied when the CheckBox is checked. This style will display TextBox in the specific column header. In this case, ‘EmpName’ and ‘DeptName’ columns are used. Once the textbox is displayed, if the end-user types the text in it, the DataGrid will show the data as per the filer from the ‘EmpCol’ collection.
Step 4: Run the application:
Silverlight DataGrid Filter

Click on the EmpName CheckBox and the ‘EmpName’ header will be replaced by the TextBox. Type the Filter string in it and you shpuld see the following result:

Silverlight DataGrid Filter

Repeat the same for the DeptName column as well.

Download the source code

Access Camera using Silverlight 4.0 and COM

In this post, we will see how to access a Camera using Silverlight 4.0 Out-Of-Browser and COM. To start with, let's first create a Silverlight application to access a camera, as shown below -

Silverlight app

Once you create the project, choose ÁSP.NET Web Site' and Silverlight version 4.0. Now let's add a reference to the 'Microsoft.CSharp.dll' file. You can find this API here - 'C:\Program Files (x86)\Microsoft SDKs\Silverlight\v4.0\Libraries\Client'.

Now let's design the Silverlight MainPage.xaml as shown below. Replace <Grid></Grid> with the following code -

Silverlight Camera App

In the XAML shown above, we are taking a Textbox to provide a name to our captured image and then will save it to our local drive, on the click event of a button.

Now let's write a code in our 'Access Camera' button click event, as shown below -

Silverlight Access Camera

Now go to the Silverlight project properties. Right click Silverlight Project > Properties. Check the checkbox 'Enable Running Application out of the browser' and click on 'Out-Of-Browser Settings' button as shown below -

image

Now let's check the checkbox 'Require evaluated trust when running outside the browser' and compile your Silverlight application. Now hit 'F5' and you will see your application running out-of-browser. Click the button 'Access Camera' and you will see the Devices connect to your computer like Scanner or Camera etc. Choose Camera and you will see something similar -

Silverlight Get Picture

Now select a picture and click on 'Get Picture' button which will save the selected picture with the name given in a Textbox on your local drive. In my case it is 'E:\' with the name 'Sample2.jpg' and this will look like the one shown below -

Silverlight Save Picture

Note: Similarly you can also read Webcam Support in Silverlight 4 to capture Video

Download the Source Code

JavaScript: Recursive Anonymous Function

I recently saw a question on the forums – How to make a JavaScript anonymous function refer to itself? In other words, how to make an anonymous function in JavaScript call itself from within itself.

The answer is by using arguments.callee.

Let’s see an example. First here’s an example of a recursive function that is not anonymous.

<script type="text/javascript">
function factorial(num) {
  // Round num if not integer.
  num = Math.floor(num);

  if (num == 0) {
    return 1;
  }        
  else {
    return (num * factorial(num - 1));
}
}

document.writeln(factorial(7));
</script>

The code shown above returns 5040.

Now if the same were to be written as an anonymous function and called recursively, we will use arguments.callee as shown below:

anonymous recursive function
Output remains the same, i.e. 5040.

Note: arguments.callee cannot be defined in “strict” mode and it can behave slow at times.