Wednesday, August 19, 2009

Silverlight and Database without LINQ and EDM

 

Hi All,

I am writing this Blog because of one reason. Many people have a question about accessing the data in Silverlight applications without LINQ, LINQ-To-SQL Or EDM (Entity Data Model).

The answer for this question is “Yes, You can!!”. So, to achieve this, there can be multiple ways. I have achieved this by my way.

So, let’s start looking at the Steps-

1) Create a Silverlight project using VS 2008/ VS 2010 and name it as “SLWithoutLINQ”.

2) Design the Page.xaml as per your specifications. I have taken only a single button which will give a call to WCF Service method and that method will return a collection of class called “Students”.

Page.xaml-

<UserControl x:Class="SL3WithoutLINQ.Page"
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="300" d:DesignWidth="400">

      <Grid x:Name="LayoutRoot" Background="Black">
           <Button x:Name="btnShowResult" Content="Show Result" Click="btnShowResult_Click" Height="100" Width="200"/>
      </Grid>
</UserControl>

3) My database description is as below-

Database Name – Sample.

Table Name – Test.

Table structure -

Field Name Data Type
InstID Int
StudID Int
Subject Varchar(50)
Result Varchar(50)
FailedReason Varchar(50)

4) Now, let’s add a class in our web site or web application with name “Students” as shown below-

public class Students
{
      public int InstanceID { get; set; }
      public int StudentID { get; set; }
      public string Subject { get; set; }
      public string Result { get; set; }
      public string FailedReason { get; set; }
}
5) Now, let’s add a simple WCF Service by the name “FetchResults” and write a code as below(Once you add a WCF Service, you will get an Interface and a class which implements that Interface)-
Interface-
[ServiceContract]
public interface IFetchResults
{
[OperationContract]
List<Students> FetchStudentResult();
}
 
Class-
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data;
using System.Data.SqlClient;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "FetchResults" in code, svc and config file together.
public class FetchResults : IFetchResults
{

      public List<Students> FetchStudentResult()
      {
          SqlConnection CN = new SqlConnection(@"Server=.\SQLExpress;Database=Sample;Integrated Security=true");
          SqlCommand CMD = new SqlCommand("Select * from Test",CN);
          CN.Open();

          SqlDataReader DR = CMD.ExecuteReader();
          List<Students> result=new List<Students>();
          while (DR.Read())
          {
               result.Add(new Students() {StudentID=int.Parse(DR[1].ToString()),InstanceID=int.Parse(DR[0].ToString()),Subject=DR[2].ToString(),Result=DR[3].ToString(),FailedReason=DR[4].ToString() });
          }
return result;
      }
}
 
6) Now once you finish your service code, Now the most important thing is change the Web.Config file.
So, When you add a WCF Service, it by default gives binding as wsHttpBinding. Silverlight supports only basicHttpBinding.
So, change it as below-
 
<endpoint address="" binding="basicHttpBinding" contract="IFetchResults">
       <identity>
             <dns value="localhost"/>
       </identity>
</endpoint>
7) The method “FetchStudentResult” returns a collection of “Students” class. Now let’s move to out next step.

8) Now add a WCF Service reference to your Silverlight project. and create a proxy of a class “FetchResultsClient” as shown below-

List<StudentProxy.Students> studCollection;
private void btnShowResult_Click(object sender, RoutedEventArgs e)
{
      StudentProxy.FetchResultsClient proxy = new SL3WithoutLINQ.StudentProxy.FetchResultsClient();
      proxy.FetchStudentResultCompleted += new  EventHandler<SL3WithoutLINQ.StudentProxy.FetchStudentResultCompletedEventArgs>(proxy_FetchStudentResultCompleted);

      proxy.FetchStudentResultAsync();

}
 
void proxy_FetchStudentResultCompleted(object sender, SL3WithoutLINQ.StudentProxy.FetchStudentResultCompletedEventArgs e)
{
      studCollection = e.Result.ToList();
}
 
9) Now put a break point on “proxy_FetchStudentResultCompleted” method. and run your application. Click the button “Show Result”. and when the break point is invoked, you will see the no. of instances in the studCollection as shown below-

 

DebugView

In the above result, I have six rows return from the table called “Test”. Now you can use this collection as a data context for any control !!
10) So, That’s all !! Enjoy.

Thursday, July 30, 2009

Physics Behaviors in Silverlight 3.0

 

Hi All,

From last two days, I was learning about the “Physics Behaviors”. How to Use Them? How to Apply Them? I am not at all good in Physics. But, tried some “Physics Behaviors” in my game. I have seen some “COOOOOOOOOOL” Demos from the below site -

http://www.andybeaulieu.com/Default.aspx?tabid=67&EntryID=165

and I got inspired by “Andy Beaulieu”. Thanks to Andy!!.

I have downloaded a library called “PhysicsHelper 3.0.0.1 Beta”. Below is a link for the same-

http://physicshelper.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=30208

This is Awesome!!

So, just to see some capabilities of “Physics Behaviors” using in Silverlight 3.0, I have designed a simple game. Well, You can “Play” Online. Below is the demo -

Important Note – The above Demonstration is “without writing any Code”. I have used Microsoft Expression Blend 3.0. That’s All!!

But in this Blog I am not writing “How to do that?" Step – By – Step Lab Manual as usual. The reason is I want to understand first How the Physics Works for these behaviors by My Self. Once I am done with that, I will come up with Step By Step Lab Manual.

Till the Time Enjoy !!

Friday, July 24, 2009

30 Transition Effects In Silverlight 3.0

 

Hi All,

The purpose of writing this blog is to show you that now you can apply “30 Transition Effect in Silverlight 3.0”. In my last blog, I have shown “23 Pixel Shader Effects in Silverlight 3.0”. If you have not seen it yet, please have a look at it and then proceed to apply these Transition Effects in your application.

For this demo, you must see the video which is available on “Channel 9”. Below is the link for the Video -

http://channel9.msdn.com/shows/Continuum/WPFFXDemo

To Apply these effects you will have to now download the library called “WPFSLFx” from “CodePlex.com”. It’s a .ZIP file. Below is a link for the same -

http://codeplex.com/wpffx

Unzip the downloaded file at your preferred location. You will see a folder called “WPFSLFx”. If you drill down the folder you will see “SL” folder. Within that folder you will get a library called -

1) SLTransitionEffects.

It contains 30 different Transition effects which you can try out online. Below is a Demo for the same -

The below table shows all the names of the transitions which you can apply in your Silverlight 3 application.

SR.NO. Transition Name
1 Banded Swirl Transition Effect
2 Blinds Transition Effect
3 Blood Transition Effect
4 Circle Reveal Transition Effect
5 Circle Stretch Transition Effect
6 Circular Blur Transition Effect
7 Cloud Reveal Transition Effect
8 Crumble Transition Effect
9 Disolve Transition Effect
10 Drop Fade Transition Effect
11 Fade Transition Effect
12 Least Bright Transition Effect
13 Line Reveal Transition Effect
14 Most Bright Transition Effect
15 Pixelate In Transition Effect
16 Pixelate Out Transition Effect
17 Pixelate Transition Effect
18 Radial Blur Transition Effect
19 Radial Wiggle Transition Effect
20 Random Circle Reveal Transition Effect
21 Ripple Transition Effect
22 Rotate Crumble Transition Effect
23 Saturate Transition Effect
24 Shrink Transition Effect
25 Slide In Transition Effect
26 Smooth Swirl Grid Transition Effect
27 Swirl Grid Transition Effect
28 Swirl Transition Effect
29 Water Transition Effect
30 Wave Transition Effect

Now, to apply above transitions let’s see the step-by-step guide lines-

1) Create a Silverlight 3.0 application using Microsoft Expression Blend 3.0.

2) Once you are done, add a project “SLTransitionEffects” from the location where you have unzipped the “WPSLEfx” zip file. My location is -

C:\WPFSLFx\WPFSLFx\SL\SLTransitionEffects

3) Then compile the SLTransitionEffects Library and add a reference of the same into your Silverlight project as shown below-

AddReference

4) Now, Add at least two images in the Silverlight project and add a “Image Control” on MainPage.xaml file with height and width as per you specifications. Set one image as a source to image control.

5) Now the most important thing, add one “ImageBrush” as a user control resource as shown below-

<ImageBrush ImageSource="Tulips.jpg" x:Key="ImBrush"/>

6) Now, Select a Image control which you have on MainPage.xaml and go to property window.

7) Now, go to “Appearance section” and you will see the “Effect” property and a “New” button. Click that button and then you will see out Transition effect library in a “Select Object” dialog box. And you will see 30 different classes under the “SLTransitionEffects” library. Each class presents a Transition Effect as shown below-

TransitionEffects

8) For this demonstration I will use “DropFadeTransitionEffect” class. So, make a choice of  “DropFadeTransitionEffect class and click “OK” button.

9) Now, you will see three properties-

I) OldImage- This is the property to which we will set the “ImageBrush” we have created in our earlier steps as shown below-

OldImage

II) Progress – This property is the most common property which you will find in almost all the transition classes. Now, Create a “StoryBoard” (Animation) for five seconds. and change the “Progress” property from 0 – 1.

III) RandomSeed – Let it be zero.

So, you are done!! Start the animation on some button click event of the MainPage.xaml file and see the Transition effect applied on your Image. Very Simple !!!

Now you can try applying the Transition Effects on the Silverlight Controls as per your preference.

So, what are you waiting for!! Download the Library and Try all the “30 Transition Effects in Silverlight 3.0 Applications”.

Enjoy!!!

Pravinkumar.

 

Wednesday, July 22, 2009

23 Pixel Shader Effects in Silverlight 3.0

 

Hi All,

Yesterday, I was just going through the Pixel Shader Effects in Silverlight 3.0. and found one interesting video on Channel 9 about WPF Effects library on CodePlex. This library is modified for “Silverlight 3” and contains 23 effects for Silverlight 3 as well. Below is a link for the same-

Video Link- http://channel9.msdn.com/shows/Continuum/WPFFXDemo/

Library Link - http://codeplex.com/wpffx

So, Download this library. It’s a .ZIP file. Extract it as per your preferred location and you will see a Folder SL, which contains a Library -

1) SLShaderEffectLibrary.

To see these effects Live, below is a table which I made with all “23 Pixel Shader Effects” -

List of 23 Pixel Shader Effects-

SR.NO. Pixel Shader Effect Name Snapshot of the Effect
1 Banded Swirl Effect Effect1
2 Bloom Effect Bloom
3 Bright Extract Effect BrightExtract
4 Color Key Alpha Effect ColorKeyAlpha
5 Color Tone Effect ColorToneEffect
6 Contrast Adjust Effect ContrastAdjust
7 Directional Blur Effect DirectionalBlur
8 Embossed Effect EmbossedEffect
9 Gloom Effect GloomEffect
10 Growable Poisson Disk Effect GrowablePoissonEffect
11 Invert Color Effect InvertColor
12 Light Streak Effect LightStreakEffect
13 Magnify Effect MagnifyEffect
14 Monochrome Effect MonochromEffect
15 Pinch Effect PinchEffect
16 Pixelate Effect PixelateEffect
17 Ripple Effect RippleEffect
18 Sharpen Effect sharpenEffect
19 Smooth Magnify Effect SmoothMagnify
20 Swirl Effect SwirlEffect
21 Tone Mapping Effect ToneMappingEffect
22 Toon Shader Effect ToonShaderEffect
23 Zoom Blur Effect ZoomBlurEffect

To apply these effects, here is a step-by-step lab manual -

1) Create a Silverlight 3 project using Microsoft Expression Blend 3. Here I took a Sketch Flow project of Silverlight 3.0.

2) Once you are done with this, Add the project “SLShaderEffectLibrary” from the location where you have extracted the .ZIP file. My path where the “SLShaderEffectLibrary” is as below-

C:\WPFSLFx\WPFSLFx\SL\SLShaderEffectLibrary

3) Now compile the project “SLShaderEffectLibrary” and add the reference of this library into our Silverlight project as shown below-

AddRef

4) Now add a Image control in our Silverlight control. Set your favorite picture to the image. Once you are done with this, now let’s add a effect on this image.

5) Find the “Effect” property of the Image under Appearance section, and click the “New” button as shown below-

NewEffect

6) Now, You will see a “Select Object” Dialog box. Within this dialog box drill-down the “SLShaderEffectLibrary” and you will see all the shader classes which you can apply to your Image-

SelectObjectDialogBox

7) Now change the properties as per your requirement and see the effect on your image.

Note-: I have created a StoryBoard for each effect and applied it to different images. If you want to try out the same create a story board and change the properties of each effect.

8) So, what are you waiting for !! Try out all the effects by downloading the Library.

Enjoy!!

Pravinkumar

Friday, July 10, 2009

SketchFlow in Silverlight 3.0 using Microsoft Expression Blend 3

 

Hi All,

What I was waiting for is now Available !!

Silverlight 3.0 RTW and Microsoft Expression Blend 3 with SketchFlow are available for download. Please find the links to download below-

Microsoft Silverlight 3 Runtime
http://www.microsoft.com/silverlight/resources/install.aspx
Microsoft Expression Blend 3 with SketchFlow
http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=92e1db7a-5d36-449b-8c6b-d25f078f3609
Microsoft Silverlight 3 SDK
http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=2050e580-f1d5-4040-bb09-e6185591b6b5
Microsoft Visual Studio 2008 Tools
http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=9442b0f2-7465-417a-88f3-5e7b5409e9dd

Most importantly what I was waiting for is Sketch Flow. So, to show few capabilities of Microsoft Expression Blend 3 SketchFlow, I tried out a very simple demo.

This demo is about customers, products and their orders. So, when customers start the application they will see the Welcome Screen. Then they can see other customers, the available products and their order status. Then they can see the complete report of their own. At the end they can check out their self.

During this demonstration, if customers would like to give few feedbacks on the products which they are purchasing, they can give a feedback. By using this feedback, the company owner can rectify or appreciate the feedback which he can see as a designer.

So, let’s try out this example and see how we can build the White Board kind of Sketch Flow in Silverlight 3.0 using Microsoft Expression Blend 3 with Sketch Flow-

So, install Microsoft Silverlight 3.0 Runtime, Microsoft Silverlight 3.0 SDK and Microsoft Expression Blend with SketchFlow on your machine.

1) First step is to look at how you create a Sketch Flow project by using Microsoft Expression Blend 3. So, just look at the below screen shot-

clip_image001

2) If you observe, you can see that you can create a sketch flow project separately for Silverlight 3.0 applications or WPF application. So, let’s make a choice of “Silverlight 3 SketchFlow Application” and name it as “FirstSketchFlowApplication”.

3) Once you create a project, you will see the window like below which has different sections which we will discuss one by one-

a. Projects Window- this window will show you a structure of Silverlight SketchFlow project. It has several new items added as shown below-

clip_image003

First item is Fonts folder which contains different fonts. Screen 1 is a second item which is the first screen for our project. Third item this is most important item that is Sketch.Flow. This file shows the available screens, their connections with the other screens and lots more. You open this file and see what it shows when we finish our Sketching. Forth item is SketchStyles.xaml which contains bunch of styles and Visual states which will be utilized by our Scetchflow project.

b. Second window is SketchFlow Map. Now this is the window which is going allow you to sketch multiple screens, connect those screens with each other and lots of other functionality. Basically this window is used to Model the Flow, do Navigation and composition.

clip_image005

You will see a small tool box at the bottom of the SketchFlow Map window which will allow you to add screens, map the screens, remove the screens etc.

c. Now if you make a choice of screen shown in Blue rectangle, you will see a small toolbar which is again allow you to add-

i. Connected Screen.

ii. Connect an existing screen.

iii. Create and insert a component screen.

iv. Change visual tag.

clip_image006

4) So, next step is renaming the screen 1 by the name “Start”. And by clicking a small button “Create a Connected screen” just draw the SketchFlow as shown below-

clip_image008

The above Sketch flow shows couple of windows like, Start, WelCome, Customers, Products, Orders, CheckCustomerReport, CheckOut.

5) Now, press “F5” and See the output of your application. The application will look like as shown below-clip_image010

6) If you could see at the left hand of the screen you will see a panel called “SketchFlow Player”. This player has couple of options as described below-

a. The first section is your “start Section”.

b. Second section is your “NAVIGATE Section”. Where it will show all the windows which you can navigate through.

c. Zoom panel.

d. “FEEDBACK section”- This one is great. Your customers now can give a online feed back by using the tools shown in FEEDBACK section. Later, your designer can open the feedback given by the customers and act upon that and do the necessary changes.

e. MAP- your customers can see the entire sketch and flow of the navigation which is available in your application.

f. Try out these few sections from SketchFlow Player.

7) Now as you have seen the first output, let’s use other features which are available with SketchFlow.

8) So, let’s starting designing the screens which are almost empty which we have created in our pervious steps. When you think about designing the screens, you can use all the controls which are there available in Blend. But probably the look and feel which you are looking for while sketching the prototypes for your applications, the regular controls might not give the sketch look and feel.

9) For that in Sketch Flow of Silverlight we have couple of new Sketch controls which you can use in your sketching applications as shown below-

clip_image012

10) In the above figure, click to Asset from the blend toolbox and go to “Styles group” -> “SketchStyles” section. You will see 33 new Sketch controls which are already styled for Sketching. Now you can start using these controls for your screens.

11) So, let’s start designing our first screen called “Start”. Open the screen in the design mode and design the screen as shown below-

clip_image014

12) Here I have used a control from Sketch section called “TitleCenter-sketch” for the titles and drawn the happy faces by using a tool called “Pencil” from the standard control model.

13) Now as you have finished designing “Start” Screen, let’s start designing “WelCome” screen. Open “WelCome” screen in a design mode and design the screen as shown below-

clip_image016

14) While designing the “Welcome” Screen, I have used “Button-Sketch” and “Rectangle-Sketch” controls from the Style group of Asset.

15) Important Point-this small menu will be displayed only on the WelCome screen. What if we would like to display this Menu on all the other screens which we have designed in our previous steps? Yes, we can do that very easily. But How?

16) By making a “Component Screen”. So, for that select “Rectangle-Sketch” and “Button-Sketch” from the objects and Timeline windows, Right Click to the selection and from the context menu click on “Make into Component Screen...” It will show you one dialog box asking the name of the screen. Name the component screen as “ResuableMenu” and click ok button.

clip_image017

17) Now you will see a change in “SketchFlow Map” window as below-

clip_image019

18) Now as you are ready with the reusable component let’s use it on multiple screens. For that Drag and Drop the reusable component on the screen wherever you want to use the menu. Then open those screens and align the menu as per the design specifications.

19) This is how the final “SketchFlow Map” Should look like.

clip_image021

20) Now as we have finished drawing our SketchFlow, let’s design the other screens as shown below-

21) Customers” screen should look like as below- here I have used “ListBox-Sketch” control along with title and reusable component we just created.

clip_image023

22) Orders” screen should look like as below- here I have used “ListBox-Sketch” control along with title and reusable component we just created.

clip_image025

23) Products” screen should look like as below- here I have used “ListBox-Sketch” control along with title and reusable component we just created.

clip_image027

24) Now let’s use some other features of SketchFlow. For example now we will try out setting up navigation to our menu buttons to the respective pages in our application.

25) To do this let’s open the “Reusable Menu” into design mode. Make a choice of a “Customer Details” button, Right Click to the Button and Go To -> Navigate To - > and make a choice of a windows to which you want to navigate as shown below-

clip_image029

26) Repeat the same procedure to other buttons as well. Now press “F5” and test the application by clicking the buttons and navigating to the specific pages.

27) Now let’s try out “States in SketchFlow”. For this you will have to add one simple demo screen in to your existing project by the name “StatesExample” and design the screen as shown below-

28) To add a screen “StatesExample”, “Create a connected Screen” from our existing screen “WelCome”. Then add our reusable component by dragging the “ReusableMenu” on to our “StatesExample” screen. Add title to screen and draw “Rectangle-Sketch control”. Draw few “Button-Sketch” on top of your rectangle. So, your screen should look like below-

clip_image031

29) Now as your design is completed, let’s add few states to our application by defining the transition time by some duration. To do this, go to States window. You can get this window from Windows Menu - > States.

30) Now add the State by the name “SampleStateGrp” and let’s specify the duration to 2 Seconds as shown below-

clip_image032

31) Now add four different states by the name

a. None” which will do nothing.

b. One” – once you add this state draw a rectangle with some colour on the “StateExample” window.

c. Repeat the step “b” for state “Two” and “Three”.

32) Now once you are done with this, let’s attach our states “One”, “Two” and “Three” to the buttons “One”, “Two”, and “Three” respectively by right clicking to each button and going to “ActiveState Menu” from the context menu and make a choice of respective state as shown below-

clip_image033

33) Now Hit “F5” and test your application by navigating to “StateExample” window and click the respective buttons and see the output.

34) Now the most important point, Taking Feedback Online from the Customers and acting on that feedback as a Designer.

35) To do this run your application by pressing “F5” and use the Feedback option from the SketchFlow Player as shown below-

clip_image035

36) If you see there is enable Ink option available. If you click that you can make a choice of the colour and put your feedback on the design as well as you can write comments on the same.

37) Once you are done writing comments and feedback on the design, now export this in form a file. So, if you click the option “Show Feedback option” you will find Export option. Type the Author name and then click OK button. As soon as you click the button, you will see the save dialog box which will asked you to save the feedback. Save it by the name “StartScreenFeedback”.

38) So, now customer has given the feedback. So, let’s act as a Designer and open this feedback in Microsoft expression blend and act on the same. To do this, let’s go back to Blend.

39) Now click on “Window” menu. And click on Feedback submenu.

40) It will show you the Feedback menu at the left hand side of the window. From this window you can load the Feedback file which is send by the customer by browsing it from the given location.

41) Once you load the file, you will see a Bulb icon into “SketchFlow Map” window over the “Start” screen icon as shown below-

clip_image037

42) When you finish your SketchFlow and when your customer would like to have a Design document which they can refer, Microsoft Expression Blend has awesome feature. This has a direct integration with Microsoft Office Word. That feature is “Export To Microsoft Word”.

43) To export the design documentation to Microsoft Word, go to File Menu -> Export to Microsoft Word option.

44) When you click the menu, you will see the dialog box for exporting the design documentation to word. Give a name to the document and export it to a specific location as shown below-

clip_image001[1]

45) Then check the document.

46) Now as we are finished with “Exporting the Design Document to Microsoft Word”, let’s try out the next feature.

47) Next feature is binding data to different “Sketch Controls” using dummy data from Microsoft Expression Blend 3.0.

48) To use the dummy data from Microsoft Expression Blend, go to “Window Menu->Data” . This window will allow you to either use Live Data or Dummy Data as per the requirement.

49) Data Window has two options-

a. Add Sample Data Source.

b. Add Live Data Source.

50) We will try out “Add Sample Data Source” as shown below-

clip_image002

51) Click on “Define New Sample Data” menu. Give a name as “CustomerDataSource”. You will see by default two properties.

52) Now if you want to add multiple properties, modify the data type of the properties, edit the same data and many other features, you can do that as shown below-

clip_image004

53) So, try out the other options as per your requirement. For our demo, let’s create three data sources with the following specification-

a. CustomerDataSource-

          i. CustomerID.

         ii. CustomerName.

b. OrdersDataSource-

           i. OrderID.

          ii. OrderDate.

c. ProductDataSource-

            i. ProductID.

           ii. ProductName.

          iii. ProductPicture.

54) Once you are done with creating the data source, let’s open “Customer screen” and “Drag & Drop” the “Collection” from the Customer Data Source on Customer’s details List box. Repeat the same steps for other list boxes in our customer’s screen. Your should see the “Customer Screen” output like below-

clip_image006[1]

55) Now open the “Orders Screen” and “Product Screen” and repeat the procedure as above by “Dragging & Dropping” the above data source collections to the respective screens. Then see the output. So, we are almost done with the data binding.

56) So, that’s it from my side for time being. There are whole bunch of features available with SketchFlow for prototyping in Silverlight 3.0 and Microsoft Expression Blend 3.0. I will be coming up with other examples soon.

57) So, what are waiting for!! Download it and try out ASAP.

So, Enjoy!!!

Wednesday, July 8, 2009

Behaviors in Silverlight 3.0 Beta

 

Hi All,

While working with Silverlight 3.0 beta, I have learnt the cool feature which we were coding manually in our early days. But now in Silverlight 3.0 beta, without writing code you can apply some cool behaviors which are shown in MIX.

OR

If you want to build your own behaviors, you can even do the same.

Behaviors are used for designing better interactivity with UX using Microsoft Expression Blend 3.0.

So, I just tried some of them and for that I have downloaded few behaviors from the following URLs-

1) http://gallery.expression.microsoft.com/en-us/SampleSLBehaviors

2) http://gallery.expression.microsoft.com/en-us/MIXBehaviorPack

I tried the behaviors from the first link. Unfortunately I was unable to try out behaviors from the Second link. It might be my mistake.

After downloading the compressed file from the first URL, you can now start applying these behaviors as described below-

1) Let’s create a sample Silverlight 3.0 application by the name “SL3Behaviors” using Microsoft Expression Blend 3.0 and add an existing project “SLPreviewBehaviorsLibrary” which you have just downloaded from the first URL in to our solution as shown below-

clip_image002

2) Once you are finished with step-1, compile your project and add a reference of “SLPreviewBehaviorsLibrary” to the Silverlight application.

3) As well as add an assembly reference named “Microsoft.Expression.Interactivity.dll” from the “Assembly folder” which is there in the downloaded file location.

4) Now, let’s draw a 3- Rectangles on MainPage.xaml design surface as shown below-

clip_image004

5) Once you are done with the above design, let’s apply behaviors for all the above rectangles. For this follow the below steps-

6) Choose the Asset Library and make a choice of Behaviors from the Asset Library section as shown below-

clip_image005

clip_image007

7) You will see couple of behaviors as shown in above figure. All these behaviors are available to you because of the library reference “SLPreviewBehaviorsLibrary” which we have added in our above steps.

8) Now, let’s Drag & Drop a “DragBehavior” on the first Rectangle in our “Objects and Timeline” window as shown below-

clip_image008

9) Repeat the above step for all the other rectangles and Hit “F5”. Now Drag & Drop the Rectangles on the Screen as per your preference. WOW!! So, Easy!!!

10) So, if you are finished with the above demo, let’s try out some other cool behaviors which are available out-of-box from the Library “SLPreviewBehaviorsLibrary”.

11) Now let’s go back to our design view of MainPage.xaml file and click Asset library. Again to back to Behaviors tab and add “FullScreenAction” behavior on first rectangle.

12) This behavior gives you a capability of making your screen as Full Screen. But with that it even gives a capability of on which Event you want to make full screen. In out example we will do full screen when we click LeftMouseButton on our first Rectangle.

13) To do this, make a choice of “FullScreenAction” behavior from Objects and Timeline window and then go to Properties window. Then under Triggers section, make a choice of “LeftMouseButtonDown” event as shown below-

clip_image009

14) Once you are done, let’s Hit “F5” and test the application. When you click Left Mouse Button, you will get Full Screen!! Awesome!!

15) Now let’s try the next behavior. That is “ShowMessageBoxAction”. Drag and drop this behavior from Asset library on our second rectangle.

16) After dropping it on our second rectangle, go to property window and write a customized message as per your requirement as shown below-

clip_image010

17) Then change the trigger from “Loaded” to “MouseLeftBottonDown”.

18) Now Hit “F5” and test the application by clicking left mouse. You will see a Message Box!! Great!!

19) Let’s try out next behavior. That is “HyperlinkAction”.

20) Drag and drop “HyperlinkAction” behavior from Asset library on our third rectangle and go to properties window.

clip_image011

21) From the Trigger section, Change the Event name to “MouseLeftButtonUp” and from Hyperlink Properties section, change URL to http://www.bing.com.

22) Once you are done, Hit “F5” and test your application. When you click third rectangle and when the mouse left button is up, you will see that you are getting redirected to the specified URL!! Nice!!

23) Let try out next behavior. That is “PlayStoryBoardAction”. For this you must have a story board in your Silverlight page. So, what are we waiting for!! Let’s create a small story board which will flip the second and third rectangle by 360 degree.

24) To do this, follow below steps-

25) Create a story board by the name “FlipRectangle” and let’s make the duration 4 Seconds.

26) Then change second rectangle’s “ X coordinate” “Projection” which is there under “Transform” section in the properties window to 360 degree and third rectangle’s “ Y coordinate” “Projection” to 360 degree.

27) Now you are done with the story board, drag and drop the “PlayStoryBoardAction” on first rectangle and go back to properties window.

28) From the properties section, make a choice of event name “MouseEnter” from Trigger section and enter a story board name which we have just created “FlipRectangle” in to StoryBoardName property box from “PlayStoryBoard”.

29) Hit “F5” and test the application. When you move your mouse over first rectangle, you will see the nice animation got started!! Fantastic!!

30) That’s it!! Now you can try out some other Behaviors which you have downloaded or you can create your own as well.

You can try this application below-

So, Enjoy!!

Tuesday, July 7, 2009

Silverlight 3 DataFrom Control

Hi All,

As I have create a small Lab Manual for Changes in Accessing WCF Service in Silverlight 3.0 , I am starting with DataForm Control introduced in Silverlight 3.0 Beta to design a Rich Data Forms for Business applications.

So Let’s get started then !!

1) Create a Silverlight Application with the Name “SL3DataForm_CompleteDemo”.

2) To work with DataForm control we will have to add few references to our Silverlight Project as shown bellow-

System.ComponentModel
System.ComponentModel.Annotation
System.Windows.Controls.Data.DataForm

3) Once you add a the references, let’s add a Class in Silverlight Project with the name “Customer.cs” and add few properties as shown bellow-

public class Customer
{
public string CustomerID { get; set; }
public string CustomerName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string DOB { get; set; }
public string ContactName { get; set; }
public int ContactNo { get; set; }
public string State { get; set; }
public string Country { get; set; }
public string WebSiteURL { get; set; }
}





4) Now we will have to make few changes in MainPage.xaml file in order to call our Customer class in XAML as well as use the DataForm control as shown bellow-




1: xmlns:dataFrm="clr-namespace:System.Windows.Controls;
assembly=System.Windows.Controls.Data.DataForm"
2: xmlns:local="clr-namespace:SL3DataForm_CompleteDemo"





Add the above two namespaces in the UserControl Element. First namespace will allow us to use DataForm control and Second namespace will allow us to use Customer class as a resource in our MainPage.xaml.



5) Now let’s add the code in MainPage.xaml file as shown bellow-




<UserControl x:Class="SL3DataForm_CompleteDemo.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="400"
xmlns:dataFrm="clr-namespace:System.Windows.Controls;
assembly=System.Windows.Controls.Data.DataForm"

xmlns:local="clr-namespace:SL3DataForm_CompleteDemo">
<UserControl.Resources>
<local:Customer x:Key="myCustomerDetails"
CustomerID="PRAV"
CustomerName="Pravinkumar R. D."
Address="Sinhgad Road,Pune"
DOB="21/Oct/1977"
ContactName="Pravin"
ContactNo="828992892"
City="Pune"
State="Maharashtra"
Country="India"
WebSiteURL="http://pkrd.blogspot.com"/>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White">
<dataFrm:DataForm x:Name="CustomerForm"
CurrentItem="{StaticResource myCustomerDetails}"
Background="Black"
Header="Customer Entry Form"
CommitButtonContent="Save This Customer"/>
</Grid>
</UserControl>









In the above code, Customer class is getting utilized as Resource and DataForm control is using this resource by a property called “CurrentItem”. So, If you observe, you will see the current item of the resource is getting displayed in the DataForm.



6) Hit F5 and see the result.



clip_image002



7) Click the Edit Button highlited by RED colour and make changes.



8) Now let’s make few changes in a class called “Customer” as shown bellow-




a. First import a namespace as shown bellow-





using System.ComponentModel





b. This namespace will provide an attribute which will decide wherther the class is Bindable or not. As well if the class is Bindable, then what kind of binding it should support? It is decided by BindingDirection. By default it is OneWay-





          i. OneWay.





         ii. TwoWay.





c. When you don’t want your class to be Bindable with DataForm Control, apply attribute to a class called [Bindable(false)].



d. When you want to bind your class to be Bindable with DataForm and it should be in ReadOnly format, then apply attribute to a class called [Bindable(true,BindingDirection.OneWay)].



e. You can apply the same attrtibute to the properties of your class with all above parameters as shown bellow-



f. Apply [Bindable(false)] attribute to the property called Country in our customer class. Hit F5 and you will see that the Country is not shown in our DataForm.



g. Now, Apply [Bindable(true,BindingDirection.OneWay)] attribute to the property called Country in our customer class and [Bindable(true,BindingDirection.TwoWay)] to the class. Hit F5 and you will see that the Country is not Editable in our DataForm.



h. Now you got an idea how this can be used, please try out with multiple combinations.




9) Now as you have tried possible options, let move ahead and see some other options which are available with DataForm.



10) One thing if you observe, when you Edit the form, you can not see the “Cancel Button”. So the question is what if I want to give Save as well as Cancel option? So, let’s give both the options.



11) In order to get Cancel functionality, you will have to implement an Interface called, “IEditableObject”.



IEditableObject : This interface provides the functionality to either Save the changes or Rollback the changes to the object which is used as a Data Source.



12) So, Let’s implement the interface called “IEditableObject” in our Customer class and write a code for the same-



Now, let’s see the class code -



i) I have added one property to my Customer Class by the Name “Status”. This will show the status of the record whether it is “Edited” Or “Committed” Or “Roll backed”.



So, the class code after implementing IEditableObject Interface will look like bellow-




[Bindable(true, BindingDirection.TwoWay)]
public class Customer:IEditableObject
{
public string CustomerID { get; set; }
public string CustomerName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string DOB { get; set; }
public string ContactName { get; set; }
public int ContactNo { get; set; }
public string State { get; set; }
public string Country { get; set; }
public string WebSiteURL { get; set; }
[Bindable(true,BindingDirection.OneWay)]
public string Status { get; set; }

#region IEditableObject Members

public void BeginEdit()
{
Status = "Customer is in Edit Mode !!";
}

public void CancelEdit()
{
Status = "Edit has been cancelled??";
}

public void EndEdit()
{
Status = "Customer Record is Commited";
}

#endregion
}





13) Now One more change which we will do is instead of binding single item we will bind collection of customers with our DataForm and will see how DataForm can handle it implicitly. For that let Write a code in MainPage.xaml.cs file as follows-




public partial class MainPage : UserControl
{
ObservableCollection<Customer> customerCollection;
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}

void MainPage_Loaded(object sender, RoutedEventArgs e)
{
customerCollection = new ObservableCollection<Customer>()
{
new Customer()
{
CustomerID="PRAV",
CustomerName="Pravinkumar R. D.",
Address="Sinhgad Road,Pune",
DOB="21/Oct/1977",
ContactName="Pravin",
ContactNo=828992892,
City="Pune",
State="Maharashtra",
Country="India",
WebSiteURL="http://pkrd.blogspot.com"
},
new Customer()
{
CustomerID="YASH",
CustomerName="Yash P. D.",
Address="Sinhgad Road,Pune",
DOB="22/Sept/2005",
ContactName="Yash",
ContactNo=828996792,
City="Pune",
State="Maharashtra",
Country="India",
WebSiteURL="http://www.yash.com"
},
new Customer()
{
CustomerID="MAND",
CustomerName="Mandar M.",
Address="Karve Road,Pune",
DOB="21/Aug/1979",
ContactName="Mandar",
ContactNo=828994592,
City="Pune",
State="Maharashtra",
Country="India",
WebSiteURL="http://www.mandar.com"
},
new Customer()
{
CustomerID="PRIT",
CustomerName="Priti P. D.",
Address="Sinhgad Road,Pune",
DOB="06/Mar/1980",
ContactName="Priti",
ContactNo=828923892,
City="Pune",
State="Maharashtra",
Country="India",
WebSiteURL="http://priti.blogspot.com"
},
new Customer()
{
CustomerID="AVIN",
CustomerName="Avinash D.",
Address="Baner Road,Pune",
DOB="1/Jun/1977",
ContactName="Avinash",
ContactNo=828992892,
City="Pune",
State="Maharashtra",
Country="India",
WebSiteURL="http://avi.blogspot.com"
},
};
LayoutRoot.DataContext = customerCollection;
}
}







14) Once you are done, let’s make a small change to access this customers collection in our DataForm as follows-




<dataFrm:DataForm x:Name="CustomerForm" 
ItemsSource="{Binding}"
Background="Black"
Header="Customer Entry Form"
CommitButtonContent="Save This Customer"
CancelButtonContent="Cancel This Save" />







In the above code, instead of CurrentItem property we are using ItemSource property to be Bindable with the DataContext which we have set to our LayoutRoot that is Grid Panel.



15) Now as you have finished with changes, let’s Hit F5 and see the result !!



OutPut2



If you see the output,



i) DataForm will automatically provide a navigation facility for collection of records.



ii) As you Edit the Record, “BeginEdit” method will get fired where we have written our logic for notification.



iii) And now you can see the “Cancel” Button which will allow us to Rollback the changes.



16) Now Let’s see other features. Let’s open Customer class and give some nice titles to our Fields as shown bellow-



To do this first import a namespace -




using System.ComponentModel.DataAnnotations;





To give titles to our fields we are going to use an attribute called “Display”You can pass multiple parameters to this attributes. We will try to use few of them here-




[Display(Name="Customer ID",
Description="This is for Customer ID",Order=1)]
public string CustomerID { get; set; }
[Display(Name = "Customer Name",
Description = "This is for Customer Name", Order = 2)]
public string CustomerName { get; set; }
[Display(Name = "Customer Address",
Description = "This is for Customer Address", Order = 3)]
public string Address { get; set; }
[Display(Name = "Customer City",
Description = "This is for Customer City", Order = 4)]
public string City { get; set; }
[Display(Name = "Date of Birth",
Description = "This is Customer ID", Order = 7)]
public string DOB { get; set; }
[Display(Name = "Contact Name",
Description = "This is for Customer Contact Person", Order = 5)]
public string ContactName { get; set; }
[Display(Name = "Contact No.",
Description = "This is for Customer Contact No.", Order = 6)]
public int ContactNo { get; set; }
[Display(Name = "State",
Description = "This is for Customer State", Order = 8)]
public string State { get; set; }
[Display(Name = "Country",
Description = "This is for Customer Country", Order = 9)]
public string Country { get; set; }
[Display(Name = "Customer WebSite",
Description = "This is for Customer Web Site", Order = 10)]
public string WebSiteURL { get; set; }
[Display(Name = "Record Status",
Description = "This is for Customer Record Status", Order = 11)]
[Bindable(true,BindingDirection.OneWay)]
public string Status { get; set; }





17) Attributes which we are using are-



i) Name – To display title of the field.



ii) Description – Details description about the field.



iii) Order – In which order the Form should display fields.



18) Hit F5 and see the result-



OutPut3



19) Now let’s Validate our field data by different ways provided by different attributes like-



i) RegularExpression – Can be used to validate formats for string, integer, date, time and many more  Let’s apply this Validator to our property called WebSiteURL as shown bellow-




[Display(Name = "Customer WebSite",
Description = "This is for Customer Web Site", Order = 10)]
[RegularExpression(@"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?",
ErrorMessage="URL of the site is not valide?")]
public string WebSiteURL { get; set; }





ii) Range – Can be used to specify range between. For example, Age should be between 1 to 99 or Salary should be between 3000-10000. Let’s apply this Validator to our ContactNo (Just to show example!!) as shown bellow-



[Display(Name = "Contact No.", 
Description = "This is for Customer Contact No.", Order = 6)]
[Range(1,50000,ErrorMessage="No. should not be more than 50000??")]
public int ContactNo { get; set; }





iii) Required – To make fields Mandatory.  Let’s apply this Validator to multiple fields as shown bellow-




[Display(Name="Customer ID",Description="This is for Customer ID",Order=1)]
[Required(ErrorMessage="CustomerID is a required field")]
public string CustomerID { get; set; }
[Required(ErrorMessage = "Customer Name is a required field")]
[Display(Name = "Customer Name",
Description = "This is for Customer Name", Order = 2)]
public string CustomerName { get; set; }





iv) StringLength- Can be applied to string for checking the length.  Let’s apply this validator to CustomerID property as shown bellow-




[Display(Name="Customer ID",Description="This is for Customer ID",Order=1)]
[Required(ErrorMessage="CustomerID is a required field")]
[StringLength(4,ErrorMessage="Customer ID should
not exceed more than 4 charaters"
)]
public string CustomerID { get; set; }





v) Enum Datatype-



vi) CustomValidator – You can apply this to a complete class or a specific field. Let’s apply this validator to City property as shown bellow-



First write a Customer Validator class as bellow-




public class CustomerValidation
{
public static bool ValidateCity(string City)
{
return true;
}
}



Then Apply this to City Property



[Display(Name = "Customer City",
Description = "This is for Customer City", Order = 4)]
[CustomValidation(typeof(CustomerValidation), "ValidateCity")]
public string City { get; set; }





OR you can do it Normal way also. Look at the bellow code-




[Display(Name = "Contact No.", 
Description = "This is for Customer Contact No.", Order = 6)]
[Range(1, 5000, ErrorMessage = "Telephone No. should not cross 10 digits??")]
public int ContactNo
{
get
{
return _ContactNo;
}
set
{
if (value <= 0)
throw new ArgumentException("Contact No.
must be greater than Zero"
);
_ContactNo = value;
}
}





DataForm will capture the above exception as well.



20) Hit F5 !! and test the result !!



OutPut4



21) Now as we are done with Validation, Let’s do few Customization with DataForm. The code is as bellow-




<Grid x:Name="LayoutRoot" Background="White">
<StackPanel Orientation="Vertical">
<dataFrm:DataForm x:Name="CustomerForm"
ItemsSource="{Binding}"
Background="Pink"
Header="Customer Entry Form"
CommitButtonContent="Save This Customer"
CancelButtonContent="Cancel This Save"
Foreground="Black"
AutoGenerateFields="False"
>
<dataFrm:DataForm.Fields>
<dataFrm:DataFormTextField FieldLabelContent="Customer ID"
Binding="{Binding CustomerID}"/>
<dataFrm:DataFormTextField FieldLabelContent="Customer Name"
Binding="{Binding CustomerName}"/>
<dataFrm:DataFormTextField FieldLabelContent="Customer Address"
Binding="{Binding Address}"/>
<dataFrm:DataFormTemplateField FieldLabelContent="Birth Date" >
<dataFrm:DataFormTemplateField.DisplayTemplate>
<DataTemplate>
<TextBlock Text="{Binding DOB}"/>
</DataTemplate>
</dataFrm:DataFormTemplateField.DisplayTemplate>
<dataFrm:DataFormTemplateField.EditTemplate>
<DataTemplate>
<TextBox Text="{Binding DOB}"/>
</DataTemplate>
</dataFrm:DataFormTemplateField.EditTemplate>
</dataFrm:DataFormTemplateField>
<dataFrm:DataFormTextField FieldLabelContent="Contact Name"
Binding="{Binding ContactName}"/>
<dataFrm:DataFormTextField FieldLabelContent="Contact No."
Binding="{Binding ContactNo}"/>
<dataFrm:DataFormTextField FieldLabelContent="City"
Binding="{Binding City,Mode=TwoWay}"/>
<dataFrm:DataFormTextField FieldLabelContent="State"
Binding="{Binding State,Mode=TwoWay}"/>
<dataFrm:DataFormTextField FieldLabelContent="Country"
Binding="{Binding Country,Mode=TwoWay}"/>
<dataFrm:DataFormTextField FieldLabelContent="WebSite URL"
Binding="{Binding WebSiteURL}"/>
<dataFrm:DataFormTextField FieldLabelContent="Notification"
Binding="{Binding Status}"/>
</dataFrm:DataForm.Fields>
</dataFrm:DataForm>
</StackPanel>
</Grid>





22) Too Many things !! So, Let’s start looking at each thing one by one-















1) If you want, you can customize the complete DataForm Template as per you specifications. For that DataForm will give you couple of controls. You can even change/Customize the Edit, Insert templates as well.



So, to generate your own fields you have to set DataForm property called “AutoGenerateFields=False”. Once you do that, DataForm will not not show the default template with default fields.



Now, you can use bellow listed fields for designing your own template or you can use standard Silverlight controls as a “Data template”.



1) DataFormTextField- This field will render a TextBox under DataForm.



2) DataFormCheckBoxField – This field will render a CheckBox under DataForm.



3) DataFormComboBoxField – This field will render a ComboBox under DataForm.



4) DataFormDateField – This field will render a calendar under DataForm.



5) DataFormTemplateField – This field will allow you to design your template.



There are many more features available in DataForm.



I will try to capture these features and will come back with other set of labs-



Till the time Enjoy!!