Showing posts with label Silverlight. Show all posts
Showing posts with label Silverlight. Show all posts

Expression Blend Preview for Silverlight 5

Microsoft has released an updated version of the Expression Blend Preview for Silverlight 5 which provides support for creating Silverlight 5 and Silverlight 5 SketchFlow projects.

You may probably recollect that Expression Blend Preview for SL 5 was released in September 2011. This update comes with a GoLive license and its ration date has been extended to June 30, 2013. Moreover the Silverlight 5 SDK installed with Blend supports the RTM version of Silverlight 5.

Note: Expression Blend Preview for Silverlight 5 can be installed side-by-side with Blend 4. Blend Preview for Silverlight 5 supports only Silverlight 5 projects. For Silverlight 3 and 4 projects, please use Expression Blend 4.

You can download this release from the Microsoft Download Center: Microsoft Blend Preview for Silverlight 5.

Most Popular .NET, jQuery and Web Development articles in 2011

With 2012 fast approaching and 2011 drawing to an end, we've put together our list of the Most Popular .NET articles on DevCurry.com this year. The year 2011 featured articles on DevCurry covering many technologies like jQuery, HTML 5, ASP.NET, MVC, Silverlight, WPF, .NET, VS 2010, Entity Framework and Sharepoint, just to name a few.

I would like to thank each one of you who has visited my blog or contributed to it by submitting a Guest post, Subscribing to RSS Feed, by joining me on Twitter or the Facebook page or promoting the articles and giving regular feedbacks via rating, comments or Emails. Many thanks to those too who purchased my jQuery ASP.NET eBook.

Here are some articles that were liked the most by readers like you. Have a very Happy New Year 2012!

.NET Articles


jQuery & JavaScript Articles


HTML 5 & CSS Articles

What’s New in Silverlight 5

Now that Silverlight 5 has been Released To Web (RTW), let’s take a quick overview of what’s new in Silverlight 5


Here’s a summary of the new features in Silverlight 5, since it’s Beta release and since Silverlight 4.0

Performance Improvements
  • Improved XAML Parser Performance
  • Improved ClientHTTPWebRequest scenarios
  • Network Latency Improvements by using background thread
  • H/W accelerated rendering in IE9 windowless mode
  • Multicore JIT for speeding up startup time
  • 64-bit browser support on Windows
Binding Enhancements
  • Debug DataBinding statements (XAML)
  • Reuse Data Templates across application
  • DataContextChanged event to notify when DataContext has changed
  • Added PropertyChanged to the UpdateSourceTrigger enum
  • Binding on Style Setters
Media Support
  • New classes for sound effects with low latency audio playback
  • Variable Playback Rate
  • Hardware acceleration for H.264 media
  • DRM Key Rotation to support Live TV
  • Common remote control button commands for users to control media playback
Graphics Enhancements
  • Independent animations on separate threads
  • Core of the XNA Games Studio 4.0 graphics 3D API included
  • XNA 3D API provides XNA built-in effect, low-level GPU access, 3D primitives, multi-sample anti-aliasing etc.
  • Project Template support via Toolkit
Trusted Applications
  • Display Multiple windows in out-of-browser apps
  • Full-Trust in-browser for deployment and update scenarios
  • Unrestricted File System access
  • In-browser HTML support
  • P/Invoke support to call native windows API
Improved Text Support
  • Support for Pixel snapped text and Open Type fonts for better Text Clarity
  • Multi-Column Text and Linked Text Container support via the new RichTextBlock and RichTextBlockOverflow elements
  • Support for vector based printing
Input Support
  • Detect double-clicks using ClickCount property
  • Search Listbox/ComboBox using keyboard input
Other Support
  • Visual Studio Team Test support
  • New controls like PivotViewer and Drawing Surface
  • New capabilities for OpenFileDialog and SaveFileDialog, with default file name support

Tools You Should Download

Change Silverlight 4 DataGrid Cell on Mouse Actions

I am using the Silverlight DataGrid from its first release and it’s an extremely useful control. However while programming the DataGrid for various UI as well as data binding operations, I still find it difficult to work with some basic DataGrid elements e.g. how to find a specific cell index in the DataGrid? I have come across this question during my training programs and I have discussed various ways to find out a specific cell when the user clicks on it. Last night (a sweet Saturday night), I decided to document a way to change the appearance of the Silverlight DataGridCell when the user moves the Mouse cursor over it. In this article, I am sharing the solution I came up with (there may be multiple ways possible.)

On a side note, check out these useful Silverlight DataGrid articles

Step 1: Open VS2010 and create a Silverlight application, name it as ‘SL4_DataGrid_Cell_Index’. In the MainPage.Xaml.cs, add the following classes as DataClasses.

silverlight datagrid

Step 2: Open MainPage.xaml and add the following XAML in it. The XAML contains DataGrid and also defines styles targeting the DataGridCell.

silverlight datagrid cell style

Step 3: If you carefully observe the XAML code, the LoadingRow event of the DataGrid is used. This event will be fired when the ItemsSource property of the DataGrid is set to some Collection and when the ItemsSource property will generate DataGridRow by creating an instance of it. Open MainPage.Xaml.cs and add the following code in the Loaded event:
image

Here I have also defined a support method ’GetElementParent’, which helps me in getting the Parent of a specific UI element. Typically I required this in the DataGrid because I cannot directly read the DataGridCell object, so first I need to retrieve the current row index and then get Cell contents using the Row object. To read the cell contents I have used the DataColumn object and its GetCellContent method. The code is as below:

silverlight datagrid loading row
Step 4: Run the application and move the mouse. The DataGridCell over which the mouse is hovered, will change its appearance as shown below:

silverlight datagrid mouse hover

Download the source code

Windows Phone 7 Mango Training Videos

I had very recently blogged about the FREE two-day Windows Phone 7 Jump Start class Building Applications for Windows Phone Mango–Free Training on Aug 23/24 by Rob Miles and Andy Wigley, two mobile development MVPs. This course was specially tailored for developers looking to build cool applications and games for the new Windows Phone “Mango” Platform.

In case you missed that training, here’s the list of videos on Channel9 you can download and watch at your own learning pace

Mango Jump Start (01): Building Windows Phone Apps with Visual Studio 2010
Mango Jump Start (02): Silverlight on Windows Phone—Introduction
Mango Jump Start (03): Silverlight on Windows Phone—Advanced
Mango Jump Start (04): Using Expression to Build Windows Phone Interfaces
Mango Jump Start (05): Windows Phone Fast Application Switching
Mango Jump Start (06): Windows Phone Multi-tasking & Background Tasks
Mango Jump Start (07): Using Windows Phone Resources (Bing Maps, Camera, etc.)
Mango Jump Start (08a): Application Data Storage on Windows Phone | Part 1
Mango Jump Start (08b): Application Data Storage on Windows Phone | Part 2
Mango Jump Start (09): Using Networks with Windows Phone
Mango Jump Start (10): Tiles & Notifications on Windows Phone
Mango Jump Start (11a): XNA for Windows Phone | Part 1
Mango Jump Start (11b): XNA for Windows Phone | Part 2
Mango Jump Start (12): Selling a Windows Phone Application

Building Applications for Windows Phone Mango–Free Training on Aug 23/24

Microsoft MVP’s are always on the forefront when it comes to adopting and training others on the latest technologies. Rob Miles and Andy Wigley, two mobile development MVPs are conducting a FREE two-day Jump Start class which is specially tailored for developers looking to build cool applications and games for the new Windows Phone “Mango” Platform.

Since this free Live training is available only on the 23rd and 24th, please retweet and let fellow developers know about this.

Here are the details:

Dates: August 23-24, 2011
Time: 8:00am – 4:00pm PST (Use TimeZone converter to know your local time)
Duration: 8 hours/day, including hour lunch break

Course Contents:

Day One — August 23, 2011 | 8am-4pm PDT | Live online training
• Building Windows Phone Apps with Visual Studio 2010
• Silverlight on Windows Phone – Introduction
• Silverlight on Windows Phone – Advanced
• Using Expression to Build Windows Phone Interfaces
• Windows Phone Fast Application Switching
• Windows Phone Multi-tasking & Background Tasks
• Using Windows Phone Resources (Bing Maps, Camera, etc.)
 
Day Two — August 24, 2011 | 8am-4pm PDT | Live online training
• Application Data Storage on Windows Phone
• Using Networks with Windows Phone
• Windows Azure and Windows Phone
• Notifications on Windows Phone
• XNA for Windows Phone
• Selling a Windows Phone Application

JavaScript, CSS3, Silverlight, ASP.NET, SharePoint articles Link List – July 2011

Here’s a quick wrap up of JavaScript, CSS3, Silverlight, ASP.NET, SharePoint and other .NET articles published on DevCurry.com in the month of July 2011.

jQuery, JavaScript and CSS Articles

jQuery: Load Page in a Div - Loading an external page in a div using jQuery is as simple as calling thejQuery Load method.

JavaScript: View Source code without Comments - One my clients had a requirement of viewing an object while debugging, and they wanted to view only the source code, without comments.

Array Shuffle in JavaScript - I have yet to find a script that truly does a random shuffle across all browsers using JavaScript (no frameworks). However there are a couple of scripts I use, that are ‘good-enough’ to be used when an Array has to be shuffled.

JavaScript Object can have Private Methods - I was watching a JavaScript video tutorial by Douglas Crockford where he explained private members in JavaScript. Although there are no ‘private methods’ in a JavaScript object, we can easily create something similar by defining a function variable with a local scope.

Unary plus operator in JavaScript - The unary plus (+) operator is a unary operator and converts its operand to a number, if it isn’t already. It is equivalent to the Number() constructor called as a function. Let us see some examples of the Unary + operator and what does it imply in different scenarios

Upside Down Text with CSS3 - When it comes to rotating, tilting or scaling text, you would normally rely on JavaScript or images laid on top of each other, to give that effect. However with the CSS3 transformation functions, you can do all of this without any JavaScript code

JavaScript: Convert CamelCase to Dashes and vice-versa - My colleague Satyam shared a nice piece of JavaScript code that converts a camelcase to dashes and dashes to Camelcase.

Text Shadow Filter in IE -  You can drop shadows to text using the text-shadow property which was re-introduced in CSS3.

Conditional CSS and JavaScript for Different Browsers - A common technique adopted by developers is to detect browsers and conditionally differentiate CSS rules and JavaScript for specific versions of browsers. In simple words, a requirement could be that if the browser is IE, use a different set of CSS and JavaScript files.

Free Photo Editors for Web Designers - A good photo editing software comes with a price, but here are some free open source photo editors that could do the job for you!

Swap Variables in JavaScript – Different Methods - Here are some different ways to swap variable values in JavaScript. I will show swapping using a temporary variable, without a temporary variable, XOR operator and a single line swap.

ASP.NET, MVC and Silverlight articles

ASP.NET MVC 3 Documentation Available in 10 Different Languages - As you probably know that localized versions of ASP.NET MVC 3 is available in 9 different languages via the Web Platform Installer. To supplement these releases, Phil Haack recently announced on his blog that now apart from English, the MVC 3 Documentation is also now available in these nine local languages

Silverlight 4: Consuming WCF REST Service using JSON - A nice feature of WCF programming is the support for REST and JSON, using which a client can communicate with the WCF service without using A proxy. In this article, I have used a Silverlight 4 client application to make a call to WCF service using JSON.

Silverlight 4.0 : Open .Exe Files using COM Interoperability - While working with Silverlight Line of Business applications, there may be a scenario where the user wants to open .exe applications e.g. Notepad or Calculator from the local machine. The question here is how to make this possible in Silverlight?

Silverlight 4 and 5 Tutorials–Link List - I recently published a list of Silverlight 4 and Silverlight 5 Tutorials that should be a useful resource for every Silverlight developer out there. 

ASP.NET: Accessing Nested Repeater Control - The ASP.NET Repeater control is a handy data-bound list control that allows you to create a custom layout by repeating a specified template for each item displayed in the list. You can nest a repeater control inside the other to create advanced layouts.

ASP.NET MVC Web Matrix & Razor Tutorials - In this list, we will see some articles written by our authors on WebMatrix and Razor syntax

Silverlight TextBox Numeric Validation - Although we have IDataErrorInfo interface for input data validation in Silverlight, it provides us validation error when the user enters the data and leaves the textbox. However the requirement we are talking about is when the user enters any data in the textbox, it should be automatically validated. This article contains the solution to this requirement.

.NET and SharePoint Articles

Windows Communication Foundation WCF 4.0 Tutorials - Author and Trainer Mahesh Sabnis has been writing some in-depth WCF 4.0 tutorials that I thought of sharing with all my blog readers. This tutorial series covers some basics and advanced concepts of WCF 4.0 programming

SharePoint 2010 Service Pack 1 Released - Microsoft recently released Service Pack 1 for SharePoint 2010 and Office Products.

SharePoint 2010 Content Database and Other Data Storage Changes - Microsoft recently announced some nice changes to SharePoint 2010 Data storage limits

"Partially Succeeded" TFS status in Visual Studio while upgrading to TFS 2010 - While upgrading from TFS to TFS 2010 and to TFS Team Build 2010, you may have come across the ‘partially succeeded’ message.

C#: Find Previous Month's First and Last Day - Here’s a simple query that gives you the first and last day of the previous month

WCF 4.0 : Discoverable Service - In this small article, I have explained the WCF 4.0 Discovery feature. This feature is used when the location of the service gets changed e.g. changing in the hosting environment or changing the physical address of the server etc

SharePoint 2010 and Azure Free Training - If you are a developer/architect who is interested in understanding how SharePoint 2010 and Windows Azure can leverage each other, then Microsoft recently released the July 2011 update of SharePoint 2010 & Windows Azure Training Kit.

Other Articles

Awarded the MVP Title – 4 Years in a Row - I was awarded the Microsoft MVP title again for the 4th consecutive year, and I thank Microsoft for bestowing this award on me.

BizTalk Server 2010 Training Kit and VHD - Microsoft has released the BizTalk Server 2010 pre-configured VHD and Training Kit to help you get started with BizTalk.

Create Social Games in Windows Azure - I recently stumbled upon the Windows Azure Toolkit for Social Games that includes accelerators, libraries, developer tools, and samples that can be used in games created using .NET or HTML5. The goal is to let game developers focus on development instead of operational hurdles.

Entity Framework 4.1 Update - If you are using Entity Framework to create data access applications, then there’s a new update to Entity Framework 4.1. EF 4.1 was announced in April. Microsoft has just released EF 4.1 Update 1 to fix some bugs as well as introduced some new types.

Visual Studio LightSwitch 2011 RTM Trial - Microsoft recently released the Visual Studio LightSwitch 2011 RTM. This tool is available for free to MSDN subscribers. However those who are not MSDN subscribers can download the RTM trial for 30 days.

Silverlight TextBox Numeric Validation

While conducting a Silverlight training at one of my clients who was migrating from ASP.NET AJAX to Silverlight 4.0. While discussing input validations, my students raised a question that in AJAX we have the FilteredTextExtender using which the TextBoxes can be restricted to accept only Character or numeric data. Can we have a similar capability in Silverlight 4.0 too?

On a side note, if you are a Silverlight developer, here’s a must read article - Microsoft Silverlight 4 Tutorials You Must Read

Although we have IDataErrorInfo interface for input data validation in Silverlight, it provides us validation error when the user enters the data and leaves the textbox. However the requirement we are talking about is when the user enters any data in the textbox, it should be automatically validated. This article contains the solution to this requirement.

In this article I have used the ‘System.Windows.Interactivity’, namespace which is available in the following path:


c:\Program Files (x86)\Microsoft SDKs\Expression\Blend\Silverlight\v4.0     \Libraries\System.Windows.Interactivity.dll


Step 1: Open VS2010 and create a new Silverlight project, name it as ‘SL4_Restricting_UserInputs’. In this project add the library file I just shared. This dll is used to set the TextChange behavior for the TextBox.

Step 2: In the project, add a class and name it as ‘TextBoxTextChangedUpdateBehavior’:


silverlight-textbox-change


Note: In the class file, you need to use the System.Windows.Interactivity as shown below:

using System.Windows.Interactivity;


The above class defines the custom textchange behavior for the textbox. This is done as the input to the textbox must be validated the moment the end-user enters the data in the textbox. The Behavior<T> class is used to define the custom behavior for the Silverlight element by attaching the UI Element object to the AssociatedObject and then register the event, for which the Behavior is to be customized.


Step 3: Add the following class to the Project. This class acts as a Data class for the UI TextBoxes. It implements ‘INotifyPropertyCanged’ interface. This is because the public properties exposed by the class are bound with the UI. So when the UI changes, the property will update itself and perform the validation. The code for doing this is as shown below:


/// <summary>
/// The class containing the Validation logic for Numeric and Character data
/// </summary>
public class ValidateInput :  INotifyPropertyChanged
{
string _Numeric;

public string Numeric
{
    get { return _Numeric; }
    set
    {
        string ValueEntered = value.ToString();
        if (ValueEntered.Length != 0)
        {
            //Check for the ASCII for the Numeric
            foreach (char c in ValueEntered)
            {
                if (c >= 48 && c <= 57)
                {
                    _Numeric = value;
                    ErrorMessageNumeric = "";
                    continue;
                }
                else
                {
                    ErrorMessageNumeric = "Sorry!!Please enter only Numeric Values Here";
                    break;
                }
            }
        }
        else
        {
            ErrorMessageNumeric = "";
        }
        OnPropertyChanged("Numeric");
    }
}
string _Character;

public string Character
{
    get { return _Character; }
    set
    {
        string ValueEntered = value.ToString();
        if (ValueEntered.Length != 0)
        {
            //Check for the ASCII for the Character Data
            foreach (char c in ValueEntered)
            {
                if ((c >= 65 && c <= 90)||(c>=97 && c<=122))
                {
                    _Character = value;
                    ErrorMessageCharacter = "";
                    continue;
                }
                else
                {
                    ErrorMessageCharacter = "Sorry!!Please enter only Character Values Here";
                    break;
                }
            }
        }
        else
        {
            ErrorMessageCharacter = "";
        }
        OnPropertyChanged("Numeric");
    }
}
string _ErrorMessageNumeric;

public string ErrorMessageNumeric
{
    get { return _ErrorMessageNumeric; }
    set
    {
        _ErrorMessageNumeric = value;
        OnPropertyChanged("ErrorMessageNumeric");
    }
}

string _ErrorMessageCharacter;
public string ErrorMessageCharacter
{
    get { return _ErrorMessageCharacter; }
    set
    {
        _ErrorMessageCharacter = value;
        OnPropertyChanged("ErrorMessageCharacter");
    }
}

public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string pName)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this,new PropertyChangedEventArgs (pName));
    }
}
    
}



Step 4: Open MainPage.Xaml and add the XAML shown below. This will define an instance of the ValidateInput class created above in the UserControl.Resources. The public properties from the class are bound with the Textboxes. The UI also contains TextBlock which are bound with the properties ErrorMessageNumeric and ErrorMessageCharacter for displaying the error accordingly. Every TextBox is assigned with the Custom Behavior by registering System.Windows.Interactivity namespace in XAML. The XAML code is as below:

silverlight-textbox-validation



Task 5: Run the application and enter alphabets in the textboxes which expect numeric data. The validation message will be displayed as shown below:

clip_image001

Conclusion: While developing Line-of-Business applications using Silverlight, we often come across forms which contain fields like EmpName, DeptName etc. For such fields, we need character data whereas for entries like Salary etc, we require Numeric Data. So using the validation mechanism shown in this article, we are able to provide the user with an instant message when he/she enters wrong data.

Download the source code

Silverlight 4 and 5 Tutorials–Link List

I recently published a list of Silverlight 4 and Silverlight 5 Tutorials that should be a useful resource for every Silverlight developer out there.


The list provides learning resources and covers various Silverlight controls like the DataGrid, DataBinding in Silverlight, Security, Communication in Silverlight using JSON, OData, WCF, REST, using Silverlight COM Automation features to interact with MsOffice tools, Silverlight 5 and much much more.

Similarly you can stay updated with new Silverlight content over here and here!

Silverlight 4.0 : Open .Exe Files using COM Interoperability

While working with Silverlight Line of Business applications, there may be a scenario where the user wants to open .exe applications e.g. Notepad or Calculator from the local machine. The question here is how to make this possible in Silverlight?

In Silverlight 4.0, using the AutomationFactory class we can create an instance of these .exe applications and can use them along with our Silverlight application. CreateObject is the method provided for such type of application development. To make use of this method, you need to add a reference of the .CSharp library in your Silverlight application. This library file is available in the following path on my machine:

C:\Program Files (x86)\Microsoft SDKs\Silverlight\v4.0\Libraries\Client\Microsoft.CSharp.dll

Step 1: Open VS 2010 and create a new Silverlight application targeted to use Silverlight 4.0. Name the application as ‘SL4_Running_System_Executables’.

Step 2: Right click on the project and select properties. Check the ‘Enable running application out of browser’ checkbox as shown below:

Out of Browser

Step 3: Also click on the ‘Out-of-Browser Settings’ button and check the ‘Require elevated trust when running outside the browser’ checkbox as shown below. This will allow the Silverlight application running out of the browser to interact with the system libraries and applications.

Elevated Trust

Step 4: In the MainPage.Xaml, add two buttons as shown below:

Silverlight UI

Step 5: Use the following namespace in the MainPage.xaml.cs file

using System.Runtime.InteropServices.Automation;

Step 6: Write the following code in the Click events for both the Buttons:

Silverlight open exe

The above code makes use of the WScript object which provides access to the root object for the Windows Script Host object model. The WScript.shell provides an object of native Windows shell. You can use this object to make call to .exe’s and libraries from the local system.

Step 7: Run the application and test it by clicking on the buttons as shown below:

image

The business requirements here is that the end-user may want to make note of some data before passing it to the Silverlight application. In such cases, Notepad can be a lightweight program.

Similarly in some cases, the user may want to perform calculations like percentage before entering into a system. In such cases, the Calculator can be an ideal application.

Silverlight 4: Consuming WCF REST Service using JSON

A nice feature of WCF programming is the support for REST and JSON, using which a client can communicate with the WCF service without using A proxy. In this article, I have used a Silverlight 4 client application to make a call to WCF service using JSON. In Silverlight, we have been provided with the System.Json assembly. This provides a ‘JsonArray’ class which represents an ordered sequence of the JSON value objects represented by the JsonValue object. The Load method provided by this class deserializes the result into CLR objects which can then be used for the further processing in the client application.

Step 1: Open VS2010 and create a blank solution, name it as ‘SL4_Calling_REST_Service_with_JSON’. In this solution, add a new WCF service (targeted to .NET 4.0) and call this project as ‘WCF_REST_Service’. Define the following ServiceContract, OperationContract and DataContract in the IService.cs file.

WCF Service

Note that the GetEmployees() method defines JSON as the request and response format from both sides.

Step 2: Implement the above interface in the Service class as shown below in Service.svc.cs file:

WCF Service Class

Step 3: Define the Web.Config file as shown below with the addition of protocol mapping for WebHttpBinding and endpoint behavior for WebHttp.

Web http Binding

Step 4: Publish the service on the IIS Web Server.

Note: On the Root of the IIS, you must have the clientaccesspolicy.xml file so that Silverlight client can make call to it.

Step 5: In the same solution, add a new Silverlight application and call it ‘SL4_JSON_Client’. Add a reference to System.Json assembly in the application. In MainPage.xaml, add a Button and DataGrid control as shown below and also subscribe to the Click event of the Button :

Silverlight Button DataGrid

Step 6: In the MainPage.Xaml.cs, add the Employee class as shown below. This class is used to store the result of the query fired on the result, from the JSON response.

image

Step 7: Add the following code on the Click event of the ‘Get Employees’ button. This code makes an async call to the WCF REST Service using OpenReadAsync method of the WebClient class, by passing WCF Service URL to it. The OpenReadCompleted event will collect the JSON response from the service and then this result will be processed. The code is as below:

wcf-rest-json

Note: Read the comments carefully.

Step 8: Run the application, the result will be as shown below:
image
Download the source code

Silverlight 4: Creating Word Documents in MyDocuments Folder

Silverlight 4.0 supports COM automation. Using this feature we can interact with MS-Word, Excel etc via our application. The business requirement behind this isinteraction that a lot  users prefer to store their data in Word or Excel format for immediate accessibility and modification. A common scenario is that if they are using an application which is reading the data from the remote server using the WCF/Web service and now this data is to be stored on the local machine for local operations, then Word/Excel are the most desired products for these users. In Silverlight 4, using Out-Of-Browser feature with elevated rights and using AutomationFactory, we can easily build application integrating with Word/Excel/Outlook. In the article, I have demonstrated the same.

Step 1: Open VS2010 and create a Silverlight application, name it as ‘SL4_Accessing_MyDocuments’. In this project, add the reference to Microsoft.CSharp. Also right click on the project and go to properties and select the CheckBox for ‘Enable the application running out of browser’ as shown below:

Out Of Browser

Step 2: Click on the ‘Out-of-Browser Settings’ and select the CheckBox for ‘Required elevated trust when running outside the browser’ as shown below:

image

Step 3: Open MainPage.Xaml and write the following Xaml:

Silverlight COM Automation

Step 4: Open MainPage.Xaml.cs (the code behind) and use the following namespaces:
using System.Runtime.InteropServices.Automation;

Step 5: Write the following code on the click event of the ‘Create Word Document’ button:

private void btnCreteWordDocument_Click(object sender, RoutedEventArgs e)
{
    try
    {
         #region Reading from Word File
         //S1: Create a Word Application object with dynamic. 
         // This is late binding. 
         //The References will be resolved at RunTime.
         dynamic objWord = AutomationFactory.CreateObject        ("Word.Application");
         //S2: Add the new Word Document 
         dynamic document = objWord.Documents.Add();
         object startIndex = 0;
         //The Location for writing the Content in the Docuement always 0
          dynamic range = document.Range(ref startIndex);
          //S3: Define Font Name and the Content to be written 
         // (Here you can have your code retrived from the Service Call)
          range.Font.Name = "Times New Roman";
          range.InsertAfter("Hello World!This is the Simple Word File
                 Created using Silverlight 4.0 ");
          Random rnd = new Random();
          //S4: Access the MyDocuments Special Folder and Save the file
          string fileName = Environment.GetFolderPath      (Environment.SpecialFolder.MyDocuments) +
                "\\" + "MyFileSL" + rnd.Next().ToString() + ".docx";
          document.SaveAs(ref fileName);
          objWord.Visible = true;
          #endregion
     }
     catch (Exception ex)
     {
          MessageBox.Show(ex.Message);
     }
}

Please see the code carefully. This code creates an instance of the Word Application using AutomationFactory. The word document is created and the data is written in the document. Please read the comments carefully on every line to understand the code.

Step 6: Run the Application and Click on the Button and the word document will be visible with the data in it.

Conclusion: With this feature in Silverlight, our OOB application can easily interact with Special folders and helps to create documents. So all users using Document format for storing the data can make us of this.

Data Validation in Silverlight using Data Annotations and Data Form

While using Silverlight for developing Line-of-Business applications, the DataForm control is recommended for performing DML operations. This control provides data pagination, insert, and update and delete operations on the records. This control provides ItemsSource property which accepts collection type as an input e.g. ObservableCollection. But while performing Insert and Update operations, it is important to perform Data Validations. In Silverlight, we have been provided with the IDataErrorInfo and INotifyDataErrorInfo interfaces for Data Validations. At the same time, we have been provided with DataAnnotation features using which properties in the source class, can be validated. In the code below, I have demonstrated the use of data annotation for data validations.

Step 1: Open VS2010 and create a new Silverlight application, name it as ‘SL4_DataForn_DataAnnotation’.

Step 2: In the project, add a new class, name it as DataClass.cs, and use the following namespaces in the class:

image2

Step 3: Write the following class with Data Annotation attributes:

public class EmployeeInfo      {
        private int _EmpNo;

        [Display(Name = "EmpNo", Description = "Enter Employee No.")]
        [Required(ErrorMessage = "Field Cannot be Left Blank")]
        public int EmpNo
        {
            get { return _EmpNo; }
            set
            {
                _EmpNo = value;
            }
        }
        private string _EmpName;

        [Display(Name = "EmpName", Description = "Enter Employee Name")]
        [Required(ErrorMessage = "Field Cannot be Left Blank")]
        public string EmpName
        {
            get { return _EmpName; }
            set
            {
                _EmpName = value;
            }
        }
        private string _DeptName;

        [Display(Name = "DeptNo", Description = "Enter Department No.")]
        [Required(ErrorMessage = "Field Cannot be Left Blank")]
        public string DeptName
        {
            get { return _DeptName; }
            set
            {
                _DeptName = value;
            }
        }
        private int _Salary;

        [Display(Name = "Salary", Description = "Enter Salary.")]
        [Required(ErrorMessage = "Field Cannot be Left Blank")]
        public int Salary
        {
            get { return _Salary; }
            set
            {
                _Salary = value;
            }
        }

        private string _Email;
        [Display(Name = "Email", Description = "Enter Email.")]
        [Required(ErrorMessage = "Field Cannot be Left Blank")]
     [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",
                ErrorMessage = "Invalid E-Mail ID")]
        public string Email
        {
            get { return _Email; }
            set
            {
                _Email = value;
            }
        }

        private int _Age;
        [Display(Name = "Age", Description = "Enter Age.")]
        [Required(ErrorMessage = "Field Cannot be Left Blank")]
        [Range(23, 65, ErrorMessage = "Not a Valid Range")]
        public int Age
        {
            get { return _Age; }
            set
            {
                _Age = value;
            }
        }
   
    }


    public class EmployeesInfoCollection : ObservableCollection<EmployeeInfo>
    {
        public EmployeesInfoCollection()
        {
            Add(new EmployeeInfo() { EmpNo = 101, EmpName = "Mahesh Sabnis", DeptName = "CTD", Salary = 56000, Email = "mahesh.sabnis@s***h.com", Age = 33 });
            Add(new EmployeeInfo() { EmpNo = 102, EmpName = "Ravi Tambade", DeptName = "CTD", Salary = 90000, Email = "ravi.tambade@s***h.com", Age = 35 });
            Add(new EmployeeInfo() { EmpNo = 103, EmpName = "Vikram Pendse", DeptName = "SCS", Salary = 45000, Email = "vikram.pendse@s***h.com", Age = 28 });
            Add(new EmployeeInfo() { EmpNo = 104, EmpName = "Natarajan Padallalu", DeptName = "CTD", Salary = 34000, Email = "saket,karnik@s***h.com", Age = 30 });
            Add(new EmployeeInfo() { EmpNo = 105, EmpName = "Kiran Patange", DeptName = "CTD", Salary = 20000, Email = "manish.sharma@s***h.com", Age = 27 });
            Add(new EmployeeInfo() { EmpNo = 106, EmpName = "Sachin Nimbalkar", DeptName = "CTD", Salary = 34000, Email = "varun.lokhande@s***h.com", Age = 27 });
            Add(new EmployeeInfo() { EmpNo = 107, EmpName = "Vishal Dulare", DeptName = "CTD", Salary = 39000, Email = "abhijeet.gole@s***h.com", Age = 29 });
            Add(new EmployeeInfo() { EmpNo = 108, EmpName = "Amitabh Ninawe", DeptName = "CTD", Salary = 20000, Email = "sachin.shukre@s***h.com", Age = 32 });
            Add(new EmployeeInfo() { EmpNo = 109, EmpName = "Sachin Shukra", DeptName = "CTD", Salary = 34000, Email = "jyoti.ghadge@s***h.com", Age = 30 });
            Add(new EmployeeInfo() { EmpNo = 110, EmpName = "Aniket Kirkole", DeptName = "SYS", Salary = 90000, Email = "aniket.kirkole@s***h.com", Age = 37 });
        }
    }


 
The EmployeeInfo class contains properties with the data validations for every property. Classes used for validation attributes are as below:
  • Required: Specifies the value is must.
  • RegularExpression: Specifies the regular expression using which the input data can be verified.
  • Range: Specifies the minimum to maximum range for the data to be entered.
Step 4: Open MainPage.xaml and add the DataForm control as shown below:

Note: Drag-Drop it on the designer because this is not available by default in the toolbox. The xaml code for configuring the DataForm is as below:

Silverlight DataForm Validation

Note that the DataForm control sets the following properties:
  • AutoEdit: When set to False, provides the ‘Edit’ button on the DataFrom Pager control.
  • AutoCommit: When set to false, the button ‘Ok’ is generated to save changes made to the collection using DataFrom field.
Step 5: In the MainPage.xaml.cs write the following code:

Employee Info Collection

The above code defines a public property ‘EmployeeInfoCollection’ which is used to bind with the DataForm control on UI.

Step 6: Run the application, the result will be as below:

Silverlight DataForm Validation

Click on the Edit Button and the record will be enabled. Change the Age and click on the ‘OK’ button that gets generated. Make sure that the Age you enter is more than 100 for the validation to trigger. The result will be as below:

Silverlight DataForm Validation

Likewise, you can validate all entries while performing Insert/Update operations.

Conclusion: DataAnnotation is a feature using which validation logic can be isolated from the UI. Typically this helps in the code-less development.

Silverlight 4: Binding Enum with ComboBox

In this article, we will explore the mechanism of Binding Enumeration data with the ItemsControls family in Silverlight. Enum is used to store constant type of data with integer values as its contents For e.g. Department values like IT, System etc. can be stored in Enum and can be used as constants in your application code. If this data needs to be displayed in a UI using DataBinding, we can make use of reflection to achieve it. The Enum can be read as a Type and the contents in it can be read as Fields using BindingFlag. After reading these Fields, then they can be added to any collection class e.g. ObservableCollection<T> and then this can be used for DataBinding with Silverlight UI elements. The code is as shown below:

Step 1: Open VS2010 and create a Silverlight project, name it as ‘SL4_Enum_Binding_ComboBox’.

Step 2: In the MainPage.xaml.cs add the following Enum:

Silverlight ComboBox Enum

Step 3: In the MainPage.xaml, design the xaml as shown below:

Silverlight ComboBox Enum

Step 4: In the loaded event, write the following code:

Enum ObservableCollection

The above code reads the Enum ‘Department’ as Type and then using reflection, all fields are read. Here I must say that reflection, if used well, is a gift to programmers, using which types can be read easily. The above code defines an ObservableCollection of name Departments which is used to store values retrieved from the Enum in the FieldInfo. The ObservableCollection is the bound with the UI. The above xaml contains ComboBox which is bound with this ObservableCollection.

Step 5: Run the application, and the following result will be displayed:

Silverlight Enum Demo
Download the source code

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!

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