Monday 30 January 2012

Search Records In GridView And Highlight Results Asp.Net Ajax

Search Records In GridView And Highlight Results Asp.Net Ajax

 

In this example i am searching records of gridview and highlighting the results based on search criteria user enter in textbox .

This example is using AJAX and C# asp.NET



<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Grid Search example</title>
<style type="text/css">
.highlight {
text-decoration:none; font-weight:bold;
color:black; background:yellow;}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1"
runat="server" />

<div>
Enter first name to search:
</div>
<div>
<asp:TextBox ID="txtSearch" runat="server"
AutoPostBack="True"
OnTextChanged="txtSearch_TextChanged">
</asp:TextBox>&nbsp;
</div>
<div>
<asp:UpdatePanel ID="UpdatePanel1"
runat="server">
<ContentTemplate>
<asp:GridView ID="grdSearch"
runat="server"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="FirstName">
<ItemTemplate>
<asp:Label ID="lblFirstName"
runat="server"
Text='<%# Highlight(Eval("FirstName").ToString()) %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LastName">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server"
Text='<%#(Eval("LastName")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server"
Text='<%#(Eval("Location")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txtSearch"
EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>

</div>

</form>
</body>
</html>

And it code behind
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Text.RegularExpressions;

public partial class _Default : System.Web.UI.Page
{
string strConnection =
ConfigurationManager.AppSettings["ConnectionString"];
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}

private DataTable GetRecords()
{
SqlConnection conn = new SqlConnection(strConnection);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * from Employees";
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
DataSet objDs = new DataSet();
dAdapter.Fill(objDs);
return objDs.Tables[0];

}
private void BindGrid()
{
DataTable dt = GetRecords();
if (dt.Rows.Count > 0)
{
grdSearch.DataSource = dt;
grdSearch.DataBind();
}
}
private void SearchText()
{
DataTable dt = GetRecords();
DataView dv = new DataView(dt);
string SearchExpression = null;
if (!String.IsNullOrEmpty(txtSearch.Text))
{
SearchExpression = string.Format("{0} '%{1}%'",
grdSearch.SortExpression, txtSearch.Text);

}
dv.RowFilter = "FirstName like" + SearchExpression;
grdSearch.DataSource = dv;
grdSearch.DataBind();

}
public string Highlight(string InputTxt)
{
string Search_Str = txtSearch.Text.ToString();
// Setup the regular expression and add the Or operator.
Regex RegExp = new Regex(Search_Str.Replace(" ", "|").Trim(),
RegexOptions.IgnoreCase);

// Highlight keywords by calling the 
//delegate each time a keyword is found.
return RegExp.Replace(InputTxt,
new MatchEvaluator(ReplaceKeyWords));

// Set the RegExp to null.
RegExp = null;

}

public string ReplaceKeyWords(Match m)
{

return "<span class=highlight>" + m.Value + "</span>";

}

protected void txtSearch_TextChanged(object sender, EventArgs e)
{
SearchText();
}
}


Download the sample code

Sunday 29 January 2012

Interview questions for WPF and Silverlight


Introduction

This article talks about 21 important FAQ from the perspective of WPF and Silverlight. Both of these technologies are connected to a certain extent. This article not only explains the theory aspect of these technologies, but also shows small samples for each of them.
Here’s a complete free e-book covering 400 FAQ for C#, SQL Server, WPF, WWF, WCF, and a lot more, feel free to download it and enjoy: 

What is the need for WPF when we have GDI, GDI+, and DirectX?

First let’s try to understand how Microsoft display technologies have evolved:
  • User32: This provides the Windows look and feel for buttons and textboxes and other UI elements. User32 lacked drawing capabilities.
  • GDI (Graphics Device Interface): Microsoft introduced GDI to provide drawing capabilities. GDI not only provides drawing capabilities but also a high level of abstraction on hardware display. In other words, it encapsulates all complexities of hardware in the GDI API.
  • GDI+: GDI+ was introduced which basically extends GDI and provides extra functionalities like JPG and PNG support, gradient shading, and anti-aliasing. The biggest issue with the GDI API was it did not use hardware acceleration and did not have animation and 3D support.
  • Note: Hardware acceleration is a process in which we use hardware to perform some functions rather than performing those functions using software running in the CPU.
  • DirectX: The biggest issues with GDI and its extension GDI+ are hardware acceleration and animation support. This came as a big disadvantage for game developers. To answer and serve game developers, Microsoft developed DirectX. DirectX exploited hardware acceleration, had support for 3D, full color graphics, media streaming facility, and lots more. This API did not mature in the gaming industry.
  • WPF: Microsoft had 3 to 4 different APIs for display technologies, so why one more? DirectX had this excellent feature of using hardware acceleration. Microsoft wanted to develop UI elements like textboxes, buttons, grids, etc., using the DirectX technology by which they could exploit the hardware acceleration feature. As WPF stands on top of DirectX, you can not only build simple UI elements but also go one step further and develop special UI elements like GridFlowDocument, and Ellipse. Oh yes, you can go one step further and build animations. WPF is not meant for game development. DirectX still will lead in that scenario. In case you are looking for light animation (not game programming), WPF will be a good choice. You can also express WPF using XML which is also called as XAML. In other words, WPF is a wrapper built over DirectX. Let’s now define WPF.
  • WPF is a collection of classes that simplifies building dynamic user interfaces. Those classes include a new set of controls, some of which mimic old UI elements (such as LabelTextBoxButton), and some that are new (such as GridFlowDocument, and Ellipse).

How does hardware acceleration work with WPF?

Hardware acceleration is a process in which we use hardware to perform some functions rather than performing those functions using software running in the CPU.
WPF exploits hardware acceleration in a two tier manner.
The WPF API first detects the level of hardware acceleration using parameters like RAM of video card, per pixel value, etc. Depending on that, it uses a Tier 0, Tier 1, or Tier 2 rendering mode.
  • Tier 0: If the video card does not support hardware acceleration, then WPF uses the Tier 0 rendering mode. In other words, it uses software acceleration. This corresponds to the working of DirectX versions less than 7.0.
  • Tier 1: If the video card supports partial hardware acceleration, then WPF uses the Tier 1 rendering mode. This corresponds to working of DirectX versions between 7.0 and 9.0.
  • Tier 2: If the video card supports hardware acceleration, then WPF uses the Tier 2 rendering mode. This corresponds to working of DirectX versions equal or greater than 9.0.

Does that mean WPF has replaced DirectX?

No, WPF does not replace DirectX. DirectX will still be needed to make cutting edge games. The video performance of DirectX is still many times higher than the WPF API. So when it comes to game development, the preference will always be DirectX and not WPF. WPF is not an optimum solution to make games. Oh yes, you can make a tic tac toe game with it but not high action animation games.
One point to remember: WPF is a replacement for Windows Forms and not DirectX.

Can we define WPF in a precise way?

Windows Presentation Framework is the new presentation API. WPF is a two and three dimensional graphics engine. It has the following capabilities:
  • Has all equivalent common user controls like buttons, check boxes, sliders, etc.
  • Fixed and flow format documents.
  • Has all of the capabilities of HTML and Flash.
  • 2D and 3D vector graphics.
  • Animation.
  • Multimedia.
  • Data binding.

What is XAML?

XAML (pronounced as Zammel) is a declarative XML-based language by which you can define objects and properties in XML. A XAML document is loaded by a XAML parser. The XAML parser instantiates objects and sets their properties. XAML describes objects, properties, and the relations between them. Using XAML, you can create any kind of objects, graphical or non-graphical. WPF parses the XAML document and instantiates the objects and creates the relations defined by the XAML. So XAML is an XML document which defines objects and properties and WPF loads this document in actual memory.

So is XAML meant only for WPF?

No, XAML is not meant only for WPF. XAML is an XML-based language and it has several variants.
  • WPF XAML is used to describe WPF content, such as WPF objects, controls, and documents. In WPF XAML, we also have XPS XAML which defines an XML representation of electronic documents.
  • Silverlight XAML is a subset of WPF XAML meant for Silverlight applications. Silverlight is a cross-platform browser plug-in which helps us create rich web content with two-dimensional graphics, animation, and audio and video.
  • WWF XAML helps us describe Windows Workflow Foundation content. The WWF engine then uses this XAML and invokes the workflow accordingly.

Can you explain the overall architecture of WPF?

The above figure shows the overall architecture of WPF. It has three major sections: presentation core, presentation framework, and Milcore. In the same diagram, we can see how other sections like DirectX and Operating System interact with the system. So let’s go section by section to understand how everything works.
  • User32: It decides what goes where on the screen.
  • DirectX: As said previously, WPF uses DirectX internally. DirectX talks with drivers and renders the content.
  • Milcore: Mil stands for media integration library. This section is unmanaged code because it acts like a bridge between the WPF managed and the DirectX / User32 unmanaged API.
  • Presentation core: This is a low level API exposed by WPF providing features for 2D, 3D, geometry, etc.
  • Presentation framework: This section has high level features like application controls, layouts, content, etc., which helps you build up your application.

Which are the different namespaces and classes in WPF?

There are ten important namespaces / classes in WPF.

System.Threading.DispatcherObject

All WPF objects derive from DispatcherObject. WPF works on an STA model, i.e., Single Threading Apartment model. The main duty of this object is to handle concurrency and threading. When messages like mouse clicks, button clicks, etc., are initiated, they are sent to the DispatcherObject which verifies whether code is running on the correct thread. In the coming sections, we will look in detail how WPF threading works.

System.Windows.DependencyObject

When WPF was designed, a property based architecture was considered. In other words, rather than using methods, functions, and events, object behavior will interact using properties. For now, we will only restrict ourselves to this definition. In the coming sections, we have dedicated questions for this.

System.Windows.Media.Visual

The Visual class is a drawing object which abstracts drawing instructions, how drawing should be done like clipping, opacity, and other functionalities. The Visual class also acts like a bridge between the unmanagedMilCore.dll and the WPF managed classes. When a class is derived from Visual, it can be displayed on windows. If you want to create your own customized user interface, then you can program using Visual objects.

System.Windows.UIElement

UIElement handles three important aspects: layout, input, and events.

System.Windows.FrameworkElement

FrameWorkElement uses the foundation set by UIElement. It adds key properties likeHorizontalAlignmentVerticalAlignment, margins, etc.

System.Windows.Shapes.Shape

This class helps us create basic shapes such as rectangle, polygon, ellipse, line, and path.

System.Windows.Controls.Control

This class has controls like TextBoxButtonListBox, etc. It adds some extra properties like font, foreground and background colors.

System.Windows.Controls.ContentControl

It holds a single piece of content. This can start from a simple label and go down to a unit level of string in a layout panel using shapes.

System.Windows.Controls.ItemsControl

This is the base class for all controls that show a collection of items, such as the ListBox and TreeView.

System.Windows.Controls.Panel

This class is used for all layout containers—elements that can contain one or more children and arrange them as per specific layout rules. These containers are the foundation of the WPF layout system, and using them is the key to arranging your content in the most attractive and flexible way possible.

The different elements involved in WPF application

In order to understand the different elements of WPF, we will do a small ‘hello world’ sample and in that process, we will understand the different elements of WPF.
Note: For this sample, we have VS 2008 Express edition.
Start VS 2008 Express and from Templates, select WPF Application as show in the figure below.
Once we have created the WPF Application project, you will see two file types: the XAML file and the behind code, i.e., XAML.cs. XAML files are nothing but XML files which have all the elements needed to display the window's UI. Every XAML element maps to some class. For instance, the Window element maps to theWpfApplication1.Window1 class, Button elements in the XAML file map to aSystem.Windows.Control.Button class, and the Grid XAML elements map toSystem.Windows.Control.Grid.
App.XAML and App.XAML.CS are the entry point files. If we you look at the code for App.XAML.CS, you will see a reference to the XAML file which needs to be loaded. The first code which runs in the application is the void main() method from App.XAML.CS which in turn loads the Window1.XAML file for rendering.
We can now connect the behind code method and functions to the events in the XAML file elements.
You can see from the above code snippet how the Button element has the Click event linked to theMyButton_Click function. MyButton_Click is the method which is in the XAML.CS behind code. So now if you run the code, you can see the button and if you click on it, you can see the message box.

What are dependency properties?

Dependency properties belong to one class but can be used in another. Consider the code snippet below:
<Rectangle Height="72" Width="131" Canvas.Left="74" Canvas.Top="77" /> 
Height and Width are regular properties of the Rectangle. But Canvas.Top and Canvas.Left are dependency properties as they belong to the Canvas class. It is used by the Rectangle to specify its position within Canvas.

Are XAML files compiled or built at runtime?

XAML files are usually compiled rather than parsed at runtime. But they also support parsing during runtime. When we build a XAML based project, you will see it creates a g.cs extension in the obi\Debug folder. Therefore, for every XAML file, you will find a g.cs file. For instance, a Shiv.XAML will have a Shiv.g.cs file in the obi\Debugfolder. In short, at runtime, you actually do not see the XAML file. But if you want to do runtime parsing of a XAML file, it also allows that to be done.

Can you explain how we can separate code and XAML?

This is one of the most important features of WPF, separating the XAML from the code to be handled. So designers can independently work on the presentation of the application and developers can actually write the code logic independent of how the presentation is.
Figure 16.1: XAML and behind code in action
Above is a code snippet which shows a XAML file and the code completely detached from the XAML presentation. In order to associate a class with a XAML file, you need to specify the x:Class attribute. Any event specified on the XAML object can be connected by defining a method with sender and event values. You can see from the above code snippet that we have linked MyClickEvent to an event in the behind code.
Note: You can find a simple sample in the WindowsSimpleXAML folder. Feel free to experiment with the code… experimenting will teach you more than reading something theoretical.

How can we access XAML objects in behind code?

To access XAML objects in behind code, you just need to define them with the same name as given in the XAML document. For instance, in the below code snippet, we have named the object as objtext and the object is defined with the same name in the behind code.
Figure 16.2: Accessing a XAML object
Note: You can get the source code from the WindowsAccessXAML folder.

What is Silverlight?

Silverlight is a web browser plug-in by which we can enable animations, graphics, and audio/video. You can compare Silverlight with Flash. We can view animations with Flash and it’s installed as a plug-in in the browser.

Can Silverlight run in other platforms other than Windows?

Yes, animations made in Silverlight can run in other platforms other than Windows. In whatever platform you want to run, you just need the Silverlight plug-in.

Come on, even WPF runs under browser why Silverlight?

Yes, there is something called as a WPF browser application which can run WPF in the browser. For a WPF browser application, you need the .NET Framework to be installed in the client location while for Silverlight, you need only the plug-in. So in other words, WPF browser applications are OS dependent while Silverlight is not. A Silverlight plug-in can run in OSs other than Windows while we all know the .NET Framework only runs in Windows.

What is the relationship between Silverlight, WPF, and XAML?

As explained previously, XAML is an XML file which defines UI elements. This XML file can be read by the WPF framework or Silverlight framework for rendering. Microsoft first developed WPF and they used XAML files to describe UI elements to the WPF framework. Microsoft then extended WPF and made WPF/e which helped to render the UI in the browser. WPF/e was the code name for Silverlight. Later Microsoft launched Silverlight officially. So the XAML just defines the XML structure to represent UI elements. Both the frameworks, i.e., WPF and Silverlight, then read the UI elements and render the UI elements in the respective platform.

Can you explain the Silverlight architecture?

Before we talk about Silverlight architecture, let’s discuss what Silverlight is really made of technically. Silverlight has borrowed a lot of things from existing Microsoft technologies. We can think of the Silverlight plug-in as a combination of some technologies from the core .NET Framework, vector animations, media, and JavaScript.
So we can visualize the Silverlight architecture as a combination of some functionalities from the core .NET framework, AJAX, and some functionalities like animation, media, etc., provided by the core Silverlight framework. We can think of the Silverlight architecture as a combination of four important blocks:
  • Some .NET Framework components: Silverlight uses some components from the .NET Framework. One of the main components is WPF. Many UI components (checkbox, button, textbox, etc.), XAML parsing, etc., are taken from the core WPF system. It also has taken components like WCF to simplify data access. It has CLR for memory management, safety checking, and garbage collection. The base class libraries of .NET are used for string manipulation, algorithms, expressions, collections, and globalization.
  • Presentation core: The core presentation framework has functionalities to display vector 2D animations, images, media, DRM, and handles input like mouse and keyboard.
  • Other technologies: Silverlight interacts with other technologies like AJAX and JavaScript. So it also borrows some functionalities from these technologies.
  • Hosting: Silverlight animations finally run under the browser environment. So it has the hosting functionality which helps to host the application in the browser, expose a DOM by which JavaScript can manipulate the Silverlight components, and it also has an installer functionality which helps install the Silverlight application and plug-in in the browser environment. One of the things which you can notice from the architecture diagram is that the presentation core reads from the XAML file for rendering. XAML is a component which is part of the .NET Framework and the rendering part is done by the presentation core.
The application is a typical HTML which runs under the browser. There are markups which instantiate the Silverlight plug-in. Now when the user interacts with the Silverlight application, it sends an event to the JavaScript system or the .NET system. This depends on which programming language you are using. The program code which is either in JavaScript or .NET can make calls to the Silverlight runtime and achieve the necessary functionalities. XAML will be read and parsed by the Silverlight runtime and then rendered in the browser.

What are the various steps to make a simple Silverlight application?

This sample we are making using VS 2008 Web Express edition and .NET 3.5. It’s a six step procedure to run our first Silverlight application. So let’s go through it step by step.
  • Step 1: The first thing we need to do is install the Silverlight SDK kit fromhttp://www.microsoft.com/downloads/details.aspx?familyid=FB7900DB-4380-4B0F-BB95-0BAEC714EE17&displaylang=en.
  • Step 2: Once you install the Silverlight SDK, you should be able to use the Silverlight template. So when you go to create a new project, you will see a ‘SilverLight Application’ template as shown in the below figure.
  • Step 3: Once you click OK, you will see a dialog box as shown below, which has three options:
    • Add an ASP.NET web project to the solution to host Silverlight: This option is the default option, and it will create a new Web Application project that is configured to host and run your Silverlight application. If you are creating a new Silverlight application, then this is the option to go.
    • Automatically generate a test page to host Silverlight at build time: This option will create a new page at runtime every time you try to debug and test your application. If you want to only concentrate on your Silverlight application, then this option is worth looking at.
    • Link this Silverlight control into an existing website: If you have an existing Silverlight application, then this option helps to link the Silverlight application with the existing web application project. You will not see this option enabled in new projects, you need to have an existing web application.
    For this example, we have selected the first option. Once you click OK, you should see the full IDE environment for Silverlight.
    So let’s run through some basic points regarding the IDE view that we see. You will see there are two projects: your web application and the Silverlight application. In the Silverlight application, we have two XAML files: App.XAML and Page.XAMLApp.XAML has the global level information.
  • Step 4: Now for simplicity's sake, we just use the TextBlock tag to display a text. You can see that as we type in Page.XAML, it is displayed in the viewer.
  • Step 5: Now we need to consume the Silverlight application in an ASPX page. So in the HTML / ASPX page, we need to first refer to the Silverlight namespace using the Register attribute.
  • <%@Register Assembly="System.Web.Silverlight" 
       Namespace="System.Web.UI.SilverlightControls" TagPrefix="asp" %>
    We also need to refer to the ScriptManager from the Silverlight name space. The ScriptManagercontrol is a functionality from AJAX. The main purpose of this control is to manage the download and referencing of JavaScript libraries.
    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    Finally, we need to refer to the Silverlight application. You can see that in the source we have referred to the XAP file. The XAP file is nothing but a compiled Silverlight application which is compressed and zipped. It basically has all the files that are needed for the application in a compressed format. If you rename the file to a ZIP extension, you can open it using WinZIP.
    <asp:Silverlight ID="Xaml1" runat="server" 
       Source="~/ClientBin/MyFirstSilverLightApplication.xap"
       MinimumVersion="2.0.31005.0" Width="100%" Height="100%" />
    So your final ASPX / HTML code consuming the Silverlight application looks something as shown below:
    <%@ Page Language="C#" AutoEventWireup="true" %>
    <%@ Register Assembly="System.Web.Silverlight" Namespace="System.Web.UI.SilverlightControls"
    TagPrefix="asp" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" style="height:100%;">
    <head runat="server">
    <title>MyFirstSilverLightApplication</title>
    </head>
    <body style="height:100%;margin:0;">
    <form id="form1" runat="server" style="height:100%;">
    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    <div style="height:100%;">
    <asp:Silverlight ID="Xaml1" runat="server" 
       Source="~/ClientBin/MyFirstSilverLightApplication.xap" 
       MinimumVersion="2.0.31005.0" Width="100%" Height="100%" />
    </div>
    </form>
    </body>
    </html>
  • Step 6: So finally set the web application as Start up and also set this page as Start up and run it. You should be pleased to see your first Silver light application running.
  • Introduction and Goal
     

    This FAQ is completed dedicated to animations and transformations using SilverLight. The tutorial starts with animation basics like timelines and storyboard. Later the article moves ahead to talk about different animations supported and we finally end the tutorial with a simple rectangle animation.

    I have collected around 400 FAQ questions and answers in WCF, WPF, WWF, SharePoint, design patterns, UML etc. Feel free to download these FAQ PDF’s from my site http://www.questpond.com

    Some news about Silverlight which is floating around
     

    I know I need to concentrate on technical for this article but still I found something interesting to share about achievements and news about SilverLight , just thought it should be shared. If you are still thinking SilverLight is not that worth putting effort then below are some news which can excite you :-

    • 300 Million Installations of SilverLight, not bad as compared to flash which is now there for years. We are not trying to underestimate flash but the start of flash was definitely not so good.
    • Ooooh Silverlight covered the last Olympics and NBC.
    • 3000 developers and designers behind this initiative.
    • Netfix CEO redhastings joins on the Microsoft board of directors

    Still not convinced read detail report at the end of this article here. Ok just that I am not biased I have also covered some bad news of SilverLight.

    What is the definition of animation from Silver light perspective?
     

    Animation is modification of a value over a period of time. Due to the modification of value over a period of time it creates an illusion of animation. For instance you can place a circle and modify the ‘Canvas.Right’ property to create an animation which moves the circle to the right.


    Figure: - Canvas right direction
     

    What is a timeline in Silver light?
     

    Time represents a segment / unit of time on which the animation will move. The unit of time can be in seconds, minutes or hours. The unit depends on the animation nature. ‘System.Windows.Media.Animation.Timeline’ class represents the time line.

    What are the different kinds of animation supported by Silverlight?
     

    As said previously animation is all about a start value and the moving towards some new value and thus providing illusion. Silver light uses three properties for it ‘From’, ‘To’ and ‘By’. ‘From’ specifies the start of the animation and ‘To’ specifies till where the animation should run. ‘By’ is relative animation. When we specify the ‘From’ and “By’ animation progresses from the value specified by the ‘From’ property to the value specified by the sum of the ‘From’ and ‘By’ properties.


    Figure :- Different kind of animations
     

    Now again using ‘From’, ‘By’ and ‘To’ you can have linear animation or you can non-linear animation. In linear animation everything is straight forward while non-linear animation changes as per animation needs.


    Figure :- Linear and Non-linear
     


    Can you explain doubleanimation , coloranimation and pointanimation ?

    As discussed in the previous question silverlight animation is all about specifying ‘From’ ,’To’ and ‘By’ value for a property. Now the property can be a simple double value, can be color or can be a point. Silverlight has categorized these properties in to three sections as explained below.

    ‘DoubleAnimation’ uses properties with double value, for instance Rectangle.Height or width. You can specify double values by using 'From','To' and 'By'.

    ‘PointAnimation’ uses point value i.e. X, Y values for line segments and curves.

    ‘ColorAnimation’ helps to alter the value of color value of an object.

    What is a story board?
     

    Storyboard is sequence of snapshots / sketches which depict changes over a period of time. You can visualize storyboard as a time line which we have discussed in one of our previous questions. Storyboard has collection of animations grouped together. The collection of animation is because storyboard uses sketches to depict changes over a period of time.

    For instance you can see there are four sketches used in the below animation to depict clash of two arrows with a boom boom at the end. So basically storyboard will have collection of four animation objects which will be shown rapidly over a period of time.

    Figure: - Arrow Sketches
     

    Can we see a simple silverlight animation to just get started?
     

    Let’s create a simple animation shown below. We will create a rectangle object whose height will increase in an animated manner. You can see from the below figure how the animation will look like. We will execute this animation using ‘DoubleAnimation’ object

    Figure :- Rectangle height animation
     

    So the first step is to define the rectangle object. Below is the XAML code snippet for which defines the rectangle object with height and width equal to 100 and chocolate background.

    <Grid x:Name="LayoutRoot" Background="White">
    <Rectangle x:Name="RectAnimated" Fill="Chocolate" Stroke="Black"
    Width="100" Height="100">
    
    </Rectangle>
    </Grid> 
    
    As a second step we need to define when the animation will be trigger. You can see from the below code snippet we have defined that the story board will be invoked when the rectangle object is loaded.

    <Grid x:Name="LayoutRoot" Background="White"> 
    <Rectangle x:Name="RectAnimated" Fill="Chocolate" Stroke="Black"
    Width="100" Height="100">
    <Rectangle.Triggers>
    <EventTrigger RoutedEvent="Rectangle.Loaded">
    <BeginStoryboard>
    
    </Storyboard>
    </BeginStoryboard>
    </EventTrigger>
    </Rectangle.Triggers>
    </Rectangle>
    </Grid>
    
    Finally we have put in the ‘DoubleAnimation’ object which uses the ‘Height’ as the target property which will be animated ‘100’ value to ‘300’ value in 5 seconds. Also note that target name is the rectangle object ‘RectAnimated’. We have also define ‘AutoReverse’ as ‘true’ which means once it reaches ‘300’ it will restart from ‘100’.

    <Grid x:Name="LayoutRoot" Background="White"> 
    <Rectangle x:Name="RectAnimated" Fill="Chocolate" Stroke="Black"
    Width="100" Height="100">
    <Rectangle.Triggers>
    <EventTrigger RoutedEvent="Rectangle.Loaded">
    <BeginStoryboard>
    <Storyboard x:Name="myStoryboard">
    <DoubleAnimation
    Storyboard.TargetName="RectAnimated"
    Storyboard.TargetProperty="Height"
    From="100" By="300" Duration="0:0:5" 
    AutoReverse="True" 
    RepeatBehavior="Forever" />
    </Storyboard>
    </BeginStoryboard>
    </EventTrigger>
    </Rectangle.Triggers>
    </Rectangle>
    </Grid>
    

    What are the different ways in which silver light does transformation?
     

    There are times when you want to transform your object in various ways. For example you would like to tilt the object in 45 degree; you would like skew the object or rotate the object. Below are some important transformation example which you can achieve using Silverlight.
    Below is a simple example which uses ‘RotateTransform’ to tilt the text at 45 degree.
    <TextBlock HorizontalAlignment="Center" 
    Text="Text 
    rotated by 45 degree">
    <TextBlock.RenderTransform>
    <RotateTransform Angle="45" />
    </TextBlock.RenderTransform>
    </TextBlock>

                            S
    Below is a simple example which uses ‘ScaleTransform’ to scale the text to ‘2’.
    <TextBlock VerticalAlignment="Center"
     HorizontalAlignment="Center" 
    Text="Text scaled with 2">
    <TextBlock.RenderTransform>
    <ScaleTransform ScaleX="2"/> 
    </TextBlock.RenderTransform>
    </TextBlock>
    Below is a simple example which uses ‘RenderTransform’ to position your text at a particular X and Y position.
    <TextBlock VerticalAlignment="Center" 
    HorizontalAlignment="Center" Text="Text 
    with X/Y values">
    <TextBlock.RenderTransform>
    <TranslateTransform X="-100" Y="-100"/>
    </TextBlock.RenderTransform>
    </TextBlock>
    
    In case you want skew your object, below is a simple XAML code snippet which
    skews you rectangle object at 45 degree.
    <Rectangle Fill="Chocolate" 
    Stroke="Black" Width="100" Height="100">
    <Rectangle.RenderTransform>
    <SkewTransform AngleX="45"/>
    </Rectangle.RenderTransform>
    </Rectangle>
    There situations when you would like to apply two or more transformation types
     on an object. In those scenarios you can use ‘TransformGroup’ to apply multiple transformation.
    Below is a code snippet which shows ‘SkewTransform’ and ‘RotateTransform’ applied in a group to
     the rectangle object.
    <Rectangle Fill="Chocolate" 
    Stroke="Black" Width="100" Height="100">
    <Rectangle.RenderTransform>
    <TransformGroup>
    
    <SkewTransform AngleX="45"/>
    <RotateTransform Angle="45"/>
    
    </TransformGroup>
    </Rectangle.RenderTransform>
    </Rectangle>

    Introduction

    This article discusses 12 FAQ’s which revolve around bindings, layouts, consuming WCF services and how to connect to database through silver light.  Article first starts with bindings and discusses about one way, two way and one time bindings. Article then moves on to discuss three different ways to layout and position silverlight controls. Finally we end up the article talking about how to consume WCF services in Silverlight and how can we do database operations.
    I have collected around 400 FAQ questions and answers in WCF, WPF, WWF, SharePoint, design patterns, UML etc. Feel free to download these FAQ PDF’s from my site http://www.questpond.com 

     

    Can you explain one way and two way bindings?

    One way binding
    As the name so the behavior. In one way bindings data flows only from object to UI and not vice-versa. For instance you can have a textbox called as ‘TxtYear’ which is binded with an object having property ‘Year’. So when the object value changes it will be reflected on the silverlight UI, but the UI cannot update the year property in the object.
    It’s a three step procedure to implement one way binding. First create your class which you want to bind with the silverlight UI.  For instance below is a simple class called as ‘ClsDate’ with a ‘Year’ property.
    public class clsDate
    {
    private int _intYear;
    public int Year
    {
    set
    {
    _intYear = value;
    }
    get
    {
    return _intYear;
    }
    }
    }
    In the second step you need to tie up the ‘Year’ property with a silver light UI text box. To bind the property you need to specify ‘Binding Path=Year’ in the text property of the text box UI object. ‘Year’ is the property which we are binding with the text box UI object.
    <TextBox x:Name="txtCurrentYear" Text="{Binding Path=Year}" Height="30" Width="150" VerticalAlignment="Center" HorizontalAlignment="Center"></TextBox>

    The final step is to bind the text box data context with the date object just created.
    public partial class Page : UserControl
    {
    public Page()
    {
    InitializeComponent();
    clsDate objDate = new clsDate();
    objDate.Year = DateTime.Now.Year;
    txtCurrentYear.DataContext = objDate;
    }
    }
    Two way binding
    Two way binding ensure data synchronization of data between UI and Objects. So any change in object is reflected to the UI and any change in UI is reflected in the object.
    To implement two way binding there are two extra steps with addition to the steps provided for ‘OneWay’.  The first change is we need to specify the mode as ‘TwoWay’ as shown in the below XAML code snippet.
    <TextBox x:Name="txtEnterAge" Text="{Binding Path=Age, Mode=TwoWay}" Height="30" Width="150" VerticalAlignment="Center" HorizontalAlignment="Center"></TextBox>
    Second change is we need to implement ‘INotifyPropertyChanged’ interface. Below is the class which shows how to implement the ‘INotifyPropertyChanged’ interface. Please note you need to import ‘System.ComponentModel’ namespace.
    public class clsDate : INotifyPropertyChanged
    {
    public event PropertyChangedEventHandler PropertyChanged;
    private int _intYear;
    public int Year
    {
    set
    {
    _intYear = value;
    OnPropertyChanged("Year");
    }
    get
    {
    return _intYear;
    }
    }
    private void OnPropertyChanged(string property)
    {
    if (PropertyChanged != null)
    {
    PropertyChanged(this,new PropertyChangedEventArgs(property));
    }
    }}
    The binding of data with data context is a compulsory step which needs to be performed.

     

    Can you explain One time binding?

    In one time binding data flows from object to the UI only once. There is no tracking mechanism to update data on either side. One time binding has marked performance improvement as compared to the previous two bindings discussed. This binding is a good choice for reports where the data is loaded only once and viewed.
    <TextBox x:Name="txtEnterAge" Text="{Binding Path=Age, Mode=OneTime}" Height="30" Width="150" VerticalAlignment="Center" HorizontalAlignment="Center"></TextBox>

     

    Can you demonstrate a Simple example of OneWay and TwoWay?

    Below is a simple sample code where in we have two text boxes one takes in the age and the other text box calculates the approximate birth date.
    Below is a simple class which has both the properties. We have implemented ‘INotifyPropertyChanged’ interface so that we can have two way communication for the year property.
    using System;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Ink;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Shapes;
    //
    using System.ComponentModel;
    namespace SilverLightBinding 
    {
    public class clsDate : INotifyPropertyChanged
    {
    public event PropertyChangedEventHandler PropertyChanged;
    
    private int _intYear;
    private int _intAge;
    public int Year
    {
    set
    {
    _intYear = value;
    OnPropertyChanged("Year");
    
    }
    get
    {
    return _intYear;
    }
    
    }
    public int Age
    {
    set
    {
    _intAge = value;
    Year = DateTime.Now.Year - _intAge;
    }
    get
    {
    return _intAge;
    }
    }
    private void OnPropertyChanged(string property)
    {
    if (PropertyChanged != null)
    {
    PropertyChanged(this,
    new PropertyChangedEventArgs(property));
    }
    }
    
    }
    }
    
    Finally we have also binded the SilverLight UI objects with the class properties. Below is the XAML snippet for the same. One point to be noted is that ‘Age’ is bounded using two way mode as we need to modify the same from the user interface.
    <TextBlock VerticalAlignment="Center" HorizontalAlignment="Center"> Enter your age in the below text box</TextBlock>
    
    <TextBox x:Name="txtEnterAge" Text="{Binding Path=Age, Mode=TwoWay}" Height="30" Width="150" VerticalAlignment="Center" HorizontalAlignment="Center"></TextBox>
    
    <TextBlock VerticalAlignment="Center" HorizontalAlignment="Center">Your approximate birth date</TextBlock>
    
    <TextBox x:Name="txtCurrentYear" Text="{Binding Path=Year}" Height="30" Width="150" VerticalAlignment="Center" HorizontalAlignment="Center"></TextBox>
    
    You can download the source code for the same at the end of this article.

    What are the different ways provided to do layout in SilverLight?

    There are three ways provided by Silverlight for layout management Canvas, Grid and Stack panel. Each of these methodologies fit in to different situations as per layout needs. All these layout controls inherit from Panel class. In the further sections we will go through each of them to understand how they work.

    Can you explain how Canvas layout actually works?

    Canvas is the simplest methodology for layout management. It supports absolute positioning using ‘X’ and ‘Y’ coordinates. ‘Canvas.Left’ helps to specify the X co-ordinate while ‘Canvas.Top’ helps to provide the ‘Y’ coordinates.
    Below is a simple code snippet which shows how a rectangle object is positioned using ‘Canvas’ on co-ordinates (50,150).
    <Canvas x:Name="MyCanvas">
    <Rectangle Fill="Blue" Width="100" 
    Height="100" 
    Canvas.Left="50" 
    Canvas.Top="150"/>
    </Canvas> 
    Below is how the display looks like. When you the run the code the XAML viewer will position the rectangle object on absolute ‘X” and ‘Y’ coordinates.

     

    How can we implement Grid Layout?

    Grid layout helps you position your controls using rows and columns. It’s very similar to table defined in HTML.
    Below is a simple table with two columns and two rows defined using ‘Grid’.  We have shown how the table display looks like. Using the ‘Grid.ColumnDefinition’ we have defined two columns and using ‘Grid.RowDefinition’ we have defined two rows. We have then created 4 text blocks which are then specified in each section using ‘Grid.Column’ and ‘Grid.Row’. For instance to place in the first column we need specify the ‘Grid.Column’ as ‘0’ and ‘Grid.Row’ as ‘0’. We have followed the same pattern for everyone and you can see all the textblocks are placed in the appropriate sections.

    How can we implement Stack Layout?

    As the name so the behavior. Stack allows you to arrange your UI elements vertically or horizontally.
     
    For instance below are 4 elements which are arranged in a stack panel element. You can see how the stack aligns / stacks the elements one above other. You can also stack the UI elements horizontally or vertically depending on your layout nature.
    You can get a simple source code which demonstrates the three layouts at the end of this article.

    What are the different steps involved in consuming WCF service in Silverlight ?

    To consume WCF service is a 4 steps procedure.
    The first step is to create your WCF service. When we create a WCF service by default it creates ‘GetData’ function which takes in a integer value and returns back a string saying “You entered 10” , in case you have passed ‘10’ as value to the function. We will try to consume this service in silverlight in the coming steps.
    public class Service1 : IService1
    {
    public string GetData(int value)
    {
    return string.Format("You entered: {0}", value);
    }
    }
    Step 2 :- Enable cross domain for your WCF service
    For this example our WCF service and the silver light web application will be hosted in different IIS website. In other words they will be hosted in different domains. When we talk about different website in other words they are hosted in different domains. For instance it’s possible that your silver light web application is hosted in one domain like www.xyz.com and your WCF service is hosted in different domain i.e. www.pqr.com .
    The WCF service needs to enable cross domain facility so that other domains can consume the WCF service.
    Figure :- Cross domain
    We need to create two XML files (clientaccesspolicy.xml and crossdomain.xml) in the root directory of the WCF service to enable cross domain functionality.
    Below is the XML code snippet for clientaccesspolicy.xml.
    <?xml version="1.0" encoding="utf-8" ?>
    <access-policy>
    <cross-domain-access>
    <policy>
    <allow-from http-request-headers="*">
    <domain uri="*"/>
    </allow-from>
    <grant-to>
    <resource include-subpaths="true" path="/"/>
    </grant-to>
    </policy>
    </cross-domain-access>
    </access-policy>
    Below is the XML code snippet for crossdomain.xml
    <?xml version="1.0"?>
    <!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
    <cross-domain-policy>
    <allow-http-request-headers-from domain="*" headers="*"/>
    </cross-domain-policy>

    Step 3 :- Add the WCF service reference and call the service
    Create a simple silverlight application and add the service reference to your silverlight project. In order to call the WCF service we need to define event handlers.To consume the WCF service is a three step procedure. In the first step refer the name space. In second step1 create the object of your WCF service. In the final step we need to create a event handler which will get the results sent by the WCF service.
    One of the important points to note is that the function ‘GetData’ is called asynchronously.
    Step 4:- Add the WCF service reference and call the service
    Finally compile the program and enjoy the output.
    You can get this source code at the end of this article.

    Why can’t we consume ADO.NET directly in SilverLight?

    Silverlight does not have ADO.NET

    Below are the different ingredients which constitute SilverLight plugin.  One of the important points to be noted is that it does not consist of ADO.NET. In other words you can not directly call ADO.NET code from SilverLight application. Now the other point to be noted is that it has the WCF component. In other words you can call a WCF service.

    In other words you can create a WCF service which does database operations and silverlight application will make calls to the same. One more important point to be noted is do not return ADO.NET objects like dataset etc because  SilverLight will not be able to understand the same.
     Below are 7 important steps which we need to follow to consume a database WCF service in silverlight.

    How can we do database operation using SilverLight?

    Step 1:- Create the Service and Data service contract
    Below is a simple customer table which has 3 fields ‘CustomerId’ which is an identity column, ‘CustomerCode’ which holds the customer code and ‘CustomerName’ which has the name of the customer. We will fire a simple select query using WCF and then display the data on the SilverLight grid.

    Field
    Datatype
    CustomerId
    int
    CustomerCode
    nvarchar(50)
    CustomerName
    nvarchar(50)

    As per the customer table specified above we need to first define the WCF data contract. Below is the customer WCF data contract.
     
    [DataContract]
        public class clsCustomer
        {
            private string _strCustomer;
            private string _strCustomerCode;
    
            [DataMember]
            public string Customer
            {
                get { return _strCustomer; }
                set { _strCustomer = value; }
            }
    
            [DataMember]
            public string CustomerCode
            {
                get { return _strCustomerCode; }
                set { _strCustomerCode = value; }
            }
        }
    
    We also need to define a WCF service contract which will be implemented by WCF concrete classes.
    [ServiceContract]
        public interface IServiceCustomer
        {
            [OperationContract]
            clsCustomer getCustomer(int intCustomer);
        }
    
    Step 2:- Code the WCF service

    Now that we have defined the data contract and service contract it’s time to implement the service contract. We have implemented the ‘getCustomer’ function which will return the ‘clsCustomer’ datacontract. ‘getCustomer’ function makes a simple ADO.NET connection and retrieves the customer information using the ‘Select’ SQL query.

    public class ServiceCustomer : IServiceCustomer
        {
            public clsCustomer getCustomer(int intCustomer)
            {
                SqlConnection objConnection = new SqlConnection();
                DataSet ObjDataset = new DataSet();
                SqlDataAdapter objAdapater = new SqlDataAdapter();
                SqlCommand objCommand = new SqlCommand("Select * from Customer where CustomerId=" + intCustomer.ToString());
                objConnection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnStr"].ToString();
                objConnection.Open();
                objCommand.Connection = objConnection;
                objAdapater.SelectCommand = objCommand;
                objAdapater.Fill(ObjDataset);
                clsCustomer objCustomer = new clsCustomer();
                objCustomer.CustomerCode = ObjDataset.Tables[0].Rows[0][0].ToString();
                objCustomer.Customer = ObjDataset.Tables[0].Rows[0][1].ToString();
                objConnection.Close();
                return objCustomer;
            }
        }
    

    Step 3:- Copy the CrossDomain.xml and ClientAccessPolicy.XML file

    This WCF service is going to be called from an outside domain, so we need to enable the cross domain policy in the WCF service by creating ‘CrossDomain.xml’ and ‘ClientAccessPolicy.xml’. Below are both the code snippets. The first code snippet is for cross domain and the second for client access policy.

    <?xml version="1.0"?>
     <!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
     <cross-domain-policy>
       <allow-http-request-headers-from domain="*" headers="*"/>
      </cross-domain-policy>

    <?xml version="1.0" encoding="utf-8" ?>
     <access-policy>
       <cross-domain-access>
        <policy>
           <allow-from http-request-headers="*">
             <domain uri="*"/>
           </allow-from>
           <grant-to>
             <resource include-subpaths="true" path="/"/>
           </grant-to>
        </policy>
       </cross-domain-access>
     </access-policy>

    Step 4:- Change the WCF bindings to ‘basicHttpBinding’

    Silverlight consumes and generates proxy for only ‘basicHttpBinding’ , so we need to change the endpoint bindings accordingly.

    <endpoint address="" binding="basicHttpBinding" contract="WCFDatabaseService.IServiceCustomer">

    Step 5:- Add service reference

    We need to consume the service reference in silverlight application using ‘Add service reference’ menu. So right click the silverlight project and select add service reference.
    Step 6 :- Define the grid for Customer  Name and Customer Code

    Now on the silverlight side we will create a ‘Grid’ which has two columns one for ‘CustomerCode’ and the other for ‘CustomerName’. We have also specified the bindings using ‘Binding path’ in the text block.

    <Grid x:Name="LayoutRoot" Background="White">
            <Grid.ColumnDefinitions>
                 <ColumnDefinition></ColumnDefinition>
                 <ColumnDefinition></ColumnDefinition>
             </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                 <RowDefinition Height="20"></RowDefinition>
                 <RowDefinition Height="20"></RowDefinition>
             </Grid.RowDefinitions>
             <TextBlock x:Name="LblCustomerCode" Grid.Column="0" Grid.Row="0" Text="Customer Code"></TextBlock>
             <TextBlock x:Name="TxtCustomerCode" Grid.Column="1" Grid.Row="0" Text="{Binding Path=CustomerCode}"></TextBlock>
             <TextBlock x:Name="LblCustomerName" Grid.Column="0" Grid.Row="1" Text="Customer Name"></TextBlock>
             <TextBlock x:Name="TxtCustomerName" Grid.Column="1" Grid.Row="1" Text="{Binding Path=Customer}"></TextBlock>
     </Grid>

    Step 7:- Bind the WCF service with the GRID

    Now that our grid is created its time to bind the WCF service with the grid. So go to the behind code of the XAML file and create the WCF service object.  There are two  important points to be noted when we call WCF service using from SilverLight:-
    • We need to call the WCF asynchronously, so we have called ‘getCustomerAsynch’. Please note this function is created by WCF service to make asynchronous calls to the method / function.
       
    • Once the function completes its work on the WCF service it sends back the message to silverlight client.  So we need to have some kind of delegate method which can facilitate this communication. You can see we have created a ‘getCustomerCompleted’ method which captures the arguments and ties the results with the grid ‘datacontext’.
       
    public partial class Page : UserControl
          {
              public Page()
              {
                  InitializeComponent();
                  ServiceCustomerClient obj = new ServiceCustomerClient();
                 obj.getCustomerCompleted += new EventHandler<getCustomerCompletedEventArgs>(DisplayResults);
                  obj.getCustomerAsync(1);
              }
              void DisplayResults(object sender, getCustomerCompletedEventArgs e)
              {
                  LayoutRoot.DataContext = e.Result;
                  
              }
         }
    You can now run the project and see how the silverlight client consumes and displays the data.