Navigation

Feed your aggregator (RSS 2.0)   Send mail to the author(s)

Recent Entries
Archives
<July 2010>
SunMonTueWedThuFriSat
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567


Categories
Blogroll
Login

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.


Copyright 2010 Manish Kumar Singh
 Sunday, May 17, 2009
Getting Started with WCF

WCF Kick Start

In this article I would be describing the simplest form of WCF (Windows Communication Foundation) project which would get you started with the WCF concepts and best practices. The purpose is to minimise the confusion from code and configuration and explain the idea along with the best practice. I would also provide description and links to help you move to a more advanced WCF topics as and when required.

For the sake of kick start I would be using basicHttpBinding for the service and consumer, which does not require any kind of authentication when accessing the service. It is kind of open to all.

Below is an overall image of the solution, projects and project files that I have used to demonstrate the simplest form of WCF implementation.

solution

The solution contains a project WcfServiceOne which defines types for contracts exposed by the service. The person class is the data contract, MyService is the service and IMyService is an interface acting as a service contract. This project acts as an API for the services.

The ServiceOneHost is the service exposed to the client. It references the project WcfServiceOne which the actual implementation of the Service as an API. Though, I could have had the service implementation written in the same project, I preferred following the best practices, by implementing the Service and Service API (contracts and its implementation) in a separate project. One advantage of doing this is that, you have decoupled service and Service API, which simplifies using the API in a non-WCF environment by directly referencing it. The web.config file in this project contains the binding information for the service which I will be explaining later in this article.

The ServiceOneConsumer is a simple ASP.Net web application consuming the service exposed by ServiceOneHost. The web.config in this web application contains the binding information defined by the host.

WcfServiceOne

WcfServiceOne project contains:

  • Data Contract - Person.cs
  • Service Contract - IMyService.cs
  • Service Implementation - IMyService.cs
Also notice that the project references System.ServiceModel and System.Runtime.Serialization which are required to assign attributes like ServiceContract, OperationContract, DataContract and DataMember.

Person.cs

using System.Runtime.Serialization;

 

namespace WcfServiceOne

{

    [DataContract]

    publicclassPerson

    {

        [DataMember]

        publicstring FullName { get; set; }

 

        [DataMember]

        publicstring Gender { get; set; }

    }

}

IMyService.cs

using System.ServiceModel;

 

namespace WcfServiceOne

{

    [ServiceContract]

    publicinterfaceIMyService

    {

        [OperationContract]

        string Callme(Person p);

    }

}

MyService

namespace WcfServiceOne

{

    publicclassMyService : IMyService

    {

        publicstring Callme(Person p)

        {

            return"Hello " + p.FullName + "  " + " you are a " + p.Gender;

        }

    }

}

ServiceOneHost

Add a reference to WcfServiceOne and then right click on the project. Select "Add New Item" from the context menu and select "WCF Service" templates. Name the new file ServiceOneHost.svc. The template would also create the code files for you in the App_Code folder. You can delete it, the code file is not required. Open the ServiceOneHost.svc and change the line to:

<% @ ServiceHost Language ="C#" Debug ="true" Service ="WcfServiceOne.MyService" %>

 

Now open the web.config file in this project and add the following block at the last within the closing of configuration tag.

  < system.serviceModel >

    < behaviors >

      < serviceBehaviors >

        < behavior name ="ServiceOneHostBehavior">

          < serviceMetadata httpGetEnabled ="true"/>

          < serviceDebug includeExceptionDetailInFaults ="false"/>

        </ behavior >

      </ serviceBehaviors >

    </ behaviors >

    < services >

      < service behaviorConfiguration ="ServiceOneHostBehavior"name="WcfServiceOne.MyService">

        < endpoint address =""binding="basicHttpBinding"contract="WcfServiceOne.IMyService">

          < identity >

            < dns value ="localhost"/>

          </ identity >

        </ endpoint >

        < endpoint address ="mex"binding="mexHttpBinding"contract="IMetadataExchange"/>

      </ service >

    </ services >

  </ system.serviceModel >

system.servicemodeltag defines how the consumer is going to connect to the service exposed here. When you add a "WCF service" to the project using template, it responds with adding the above system.servicemodel in the web.config, except the following two lines.

      < service behaviorConfiguration ="ServiceOneHostBehavior"name="WcfServiceOne.MyService">

        < endpoint address =""binding="basicHttpBinding"contract="WcfServiceOne.IMyService">

Change the name, contract and binding information as shown above. The wsHttpBinding is used to provide more secured communication using certificate. Visit The pattern and practices for WCF security at Codeplex for further guidance on how to implement wsHttpBinding using certificates.

ServiceOneConsumer

Before you proceed with consumer, you need to generate a proxy for the service and define how it connects, in the web.config file. To generate the proxy and the configuration block we would use svcutil. Open the Visual studio command prompt from Visual Studio Tools and use the following command to generate the proxy and configuration.

svcutil http://localhost/ServiceOneHost/ServiceOneHost.svc /Language:C# /out:ServiceHostProxy.cs /config:ServiceHost.config

This will create a ServiceHostProxy.cs and ServiceHost.config. Open the ServiceHost.config and copy the block. Now open the web.config file and paste the block at the end before the closing tag of configuration. The endpoint address might differ depending your host and consumer address URL.

    < system.serviceModel >

        < bindings >

            < basicHttpBinding >

                < binding name ="BasicHttpBinding_IMyService"closeTimeout="00:01:00"

                         openTimeout ="00:01:00"receiveTimeout="00:10:00"

                         sendTimeout ="00:01:00"allowCookies="false"

                         bypassProxyOnLocal ="false"

                         hostNameComparisonMode ="StrongWildcard"

                         maxBufferSize ="65536"maxBufferPoolSize="524288"

                         maxReceivedMessageSize ="65536"

                         messageEncoding ="Text"textEncoding="utf-8"

                         transferMode ="Buffered"

                         useDefaultWebProxy ="true">

                    < readerQuotas maxDepth ="32"maxStringContentLength="8192"

                                  maxArrayLength ="16384"

                                  maxBytesPerRead ="4096"

                                  maxNameTableCharCount ="16384" />

                    < security mode ="None">

                        < transport clientCredentialType ="None"proxyCredentialType="None"

                            realm ="" />

                        < message clientCredentialType ="UserName"algorithmSuite="Default" />

                    </ security >

                </ binding >

            </ basicHttpBinding >

        </ bindings >

        < client >

            < endpoint address ="http://localhost/ServiceOneHost/ServiceOneHost.svc"

                binding ="basicHttpBinding"bindingConfiguration="BasicHttpBinding_IMyService"

                contract ="IMyService"name="BasicHttpBinding_IMyService" />

        </ client >

    </ system.serviceModel >

Default.aspx

Now add the following UI in the home page of your consumer site. In this case it is Default.aspx.

< table style =" width: 400px;"cellspacing="0"cellpadding="0">

    <tr>

        <tdstyle="width:100px; vertical-align:top; text-align:left;">

            Your Name

        </td>

        <tdstyle="width:10px; vertical-align:top; text-align:left;">

            :

        </td>

        <tdstyle="width:290px; vertical-align:top; text-align:left;">

            <asp:TextBoxID="txtName"runat="server"Width="200"></asp:TextBox>

        </td>

    </tr>

    <tr>

        <tdstyle="vertical-align:top; text-align:left;">

            Gender

        </td>

        <tdstyle="vertical-align:top; text-align:left;">

            :

        </td>

        <tdstyle="vertical-align:top; text-align:left;">

            <asp:DropDownListID="ddlGender"runat="server">

                <asp:ListItemSelected="True"Text="Male"Value="male"/>

                <asp:ListItemText="Female"Value="female"/>

            </asp:DropDownList>

            <asp:ButtonID="btnSubmit"runat="server"Text="Submit"

                onclick="btnSubmit_Click"/>

        </td>

    </tr>

    <tr>

        <tdcolspan="3">

            <br/>

            <asp:LabelID="lblResult"runat="server"Text=""Font-Bold="true"
                    Font-Size="Large"></asp:Label>

        </td>

    </tr>

</ table >

Default.aspx.cs - Code Behind

using System;

using WcfServiceOne;

 

public partial class _Default : System.Web.UI.Page

{

    protectedvoid Page_Load(object sender, EventArgs e)

    {

        txtName.Text = "Manish Kumar Singh";

    }

    protectedvoid btnSubmit_Click(object sender, EventArgs e)

    {

        var p = newPerson {FullName = txtName.Text, Gender = ddlGender.SelectedValue};

 

        var proxy = newMyServiceClient();

        lblResult.Text = proxy.Callme(p);

    }

}

That's it. Now run the consumer site and give it a try.

Enjoy!
Manish


.Net
Sunday, May 17, 2009 5:42:17 PM (GMT Standard Time, UTC+00:00)  #  Comments [1] Trackback
 Saturday, May 09, 2009
Compile .NET code on the fly

In this section I would like to demonstrate how to compile a .NET code on the fly. The code has been written in C#. It contains a class "InlineParser" which does the main job. It mainly, defines the class, does in-memory compilation and exposes a method for the execution of an inner method defined in the class. It also supports a choice of language whether C# or VB.NET for compilation.

    1 using System;

    2 using System.Collections.Generic;

    3 using System.Linq;

    4 using System.Text;

    5 using Microsoft.CSharp;

    6 using Microsoft.VisualBasic;

    7 using System.CodeDom.Compiler;

    8 using System.Reflection;

    9 using System.Xml.Linq;

   10 

   11 namespace com.eforceglobal.crux.bre

   12 {

   13     internalclassInlineParser

   14     {

   15         string expression = string.Empty;

   16         string functionArguments = string.Empty;

   17         string language = "CSharp";

   18         XDocument paramList = null;

   19         object objBase = null;

   20 

   21         public InlineParser(string expr, string functionArgs, XDocument parameters, string lang)

   22         {

   23             expression = expr;

   24             functionArguments = functionArgs;

   25             paramList = parameters;

   26             language = lang;

   27         }

   28 

   29         publicbool init()

   30         {

   31             if(language.ToLower().Equals("csharp"))

   32                 return InitCSharp();

   33             else

   34                 return InitVB();

   35         }

   36 

   37         internalbool InitCSharp()

   38         {

   39             // Compile the expression in a class on the fly

   40             CSharpCodeProvider cp = newCSharpCodeProvider(

   41                 newDictionary<string, string>() { { "CompilerVersion", "v3.5" } } );

   42 

   43             //ICodeCompiler ic = cp.CreateCompiler();

   44             CompilerParameters cparam = newCompilerParameters();

   45             cparam.GenerateInMemory = true;

   46             cparam.GenerateExecutable = false;

   47 

   48 

   49             // Reference Assembly

   50             cparam.ReferencedAssemblies.Add( "system.dll" );

   51             cparam.ReferencedAssemblies.Add( "mscorlib.dll" );

   52             cparam.ReferencedAssemblies.Add( "System.Core.dll" );

   53             cparam.ReferencedAssemblies.Add( "System.Xml.dll" );

   54             cparam.ReferencedAssemblies.Add( "System.Xml.Linq.dll" );

   55 

   56 

   57             // Write your code

   58             StringBuilder sb = newStringBuilder();

   59             sb.Append( "using System;\n" );

   60             sb.Append( "using System.Collections;\n" );

   61             sb.Append( "using System.Collections.Generic;\n" );

   62             sb.Append( "using System.Text;\n" );

   63             sb.Append( "using System.Text.RegularExpressions;\n" );

   64             sb.Append( "using System.Reflection;\n" );

   65             sb.Append( "using System.Linq;\n" );

   66             sb.Append( "using System.Xml.Linq;\n" );

   67 

   68             sb.Append( "namespace com.eforceglobal.crux.bre {\n" );

   69             sb.Append( "public class EvalClass {\n" );

   70             sb.Append( "public EvalClass(){}\n" );

   71             sb.Append( "public object Evaluate(\n" );

   72             sb.Append( functionArguments ).Append( " ) {\n" );

   73             sb.Append( expression ).Append("\n");

   74             sb.Append( "}\n}\n}" );

   75 

   76             //Console.WriteLine( sb.ToString() );

   77 

   78             string code = sb.ToString();

   79             CompilerResults cres = cp.CompileAssemblyFromSource( cparam, code );

   80 

   81             // Compilation Unsuccessfull

   82             StringBuilder errors = newStringBuilder();

   83             foreach ( CompilerError cerr in cres.Errors )

   84                 errors.Append( cerr.ErrorText );

   85 

   86             if ( cres.Errors.Count > 0 )

   87                 thrownewException( errors.ToString() );

   88 

   89             // Compilation Successfull

   90             if ( cres.Errors.Count == 0 && cres.CompiledAssembly != null )

   91             {

   92                 Type ClsObj = cres.CompiledAssembly.GetType( "com.eforceglobal.crux.bre.EvalClass" );

   93                 try

   94                 {

   95                     if ( ClsObj != null )

   96                     {

   97                         objBase = Activator.CreateInstance( ClsObj );

   98                     }

   99                 }

  100                 catch ( Exception ex )

  101                 {

  102                     throw;

  103                 }

  104                 returntrue;

  105             }

  106             else

  107                 returnfalse;

  108         }

  109 

  110         internalbool InitVB()

  111         {

  112             // Compile the expression in a class on the fly

  113             VBCodeProvider vb = newVBCodeProvider(

  114                 newDictionary<string, string>() { { "CompilerVersion", "v3.5" } } );

  115 

  116             //ICodeCompiler ic = cp.CreateCompiler();

  117             CompilerParameters cparam = newCompilerParameters();

  118             cparam.GenerateInMemory = true;

  119             cparam.GenerateExecutable = false;

  120 

  121 

  122             // Reference Assembly

  123             cparam.ReferencedAssemblies.Add( "system.dll" );

  124             cparam.ReferencedAssemblies.Add( "mscorlib.dll" );

  125             cparam.ReferencedAssemblies.Add( "System.Core.dll" );

  126             cparam.ReferencedAssemblies.Add( "System.Xml.dll" );

  127             cparam.ReferencedAssemblies.Add( "System.Xml.Linq.dll" );

  128 

  129 

  130             // Write your code

  131             StringBuilder sb = newStringBuilder();

  132             sb.Append( "Imports System\n" );

  133             sb.Append( "Imports System.Collections\n" );

  134             sb.Append( "Imports System.Collections.Generic\n" );

  135             sb.Append( "Imports System.Text\n" );

  136             sb.Append( "Imports System.Text.RegularExpressions\n" );

  137             sb.Append( "Imports System.Reflection\n" );

  138             sb.Append( "Imports System.Linq\n" );

  139             sb.Append( "Imports System.Xml.Linq\n" );

  140 

  141             sb.Append( "Namespace com.eforceglobal.crux.bre \n" );

  142             sb.Append( "Public Class EvalClass \n" );

  143             sb.Append( "Public Function Evaluate ( " );

  144             sb.Append( functionArguments ).Append(" ) As Object\n");

  145             sb.Append( expression ).Append( "\n" );

  146             sb.Append( "End Function\n" );

  147             sb.Append( "End Class\n" );

  148             sb.Append( "End Namespace" );

  149 

  150             //Console.WriteLine( sb.ToString() );

  151 

  152             string code = sb.ToString();

  153             CompilerResults cres = vb.CompileAssemblyFromSource( cparam, code );

  154 

  155             // Compilation Unsuccessfull

  156             StringBuilder errors = newStringBuilder();

  157             foreach ( CompilerError cerr in cres.Errors )

  158                 errors.Append( cerr.ErrorText );

  159 

  160             if ( cres.Errors.Count > 0 )

  161                 thrownewException( errors.ToString() );

  162 

  163             // Compilation Successfull

  164             if ( cres.Errors.Count == 0 && cres.CompiledAssembly != null )

  165             {

  166                 Type ClsObj = cres.CompiledAssembly.GetType( "com.eforceglobal.crux.bre.EvalClass" );

  167                 try

  168                 {

  169                     if ( ClsObj != null )

  170                     {

  171                         objBase = Activator.CreateInstance( ClsObj );

  172                     }

  173                 }

  174                 catch ( Exception ex )

  175                 {

  176                     throw;

  177                 }

  178                 returntrue;

  179             }

  180             else

  181                 returnfalse;

  182         }

  183 

  184         publicstring Evaluate()

  185         {

  186             string result = string.Empty;

  187             Type type = objBase.GetType();

  188             MethodInfo mInfo = type.GetMethod( "Evaluate" );

  189 

  190             if ( mInfo != null )

  191             {

  192                 ParameterInfo[] pInfo = mInfo.GetParameters();

  193                 object[] arguments = null;

  194                 if(pInfo!=null) arguments = newobject[pInfo.Length];

  195                 if ( pInfo != null )

  196                 {

  197                     foreach(ParameterInfo p in pInfo )

  198                         if ( paramList.Element( "arguments" ).Elements( p.Name ) != null )

  199                         {

  200                             arguments[p.Position] = (paramList.Element( "arguments" )

  201                                 .Elements( p.Name ).Single().Value);

  202                         }

  203                     if ( pInfo.Length != arguments.Length )

  204                         thrownewArgumentException( "Insufficient parameters." );

  205                 }

  206 

  207                 result = mInfo.Invoke( objBase, arguments ).ToString();

  208             }

  209 

  210             return result;

  211         }

  212     }

  213 }

Notice that the class name of the class to be compiled is "EvalClass" and the inner method of the class is "Evaluate". Calling the "Evaluate()" method requires you to execute the following lines of code.

  1 var parser = newInlineParser(subExpression, funcArgs, Arguments.Document, lang);

  2 parser.init();

  3 retString = parser.Evaluate();

Manish


.Net
Saturday, May 09, 2009 6:21:03 AM (GMT Standard Time, UTC+00:00)  #  Comments [2] Trackback
 Sunday, March 29, 2009
Microsoft Surface ... CLI to GUI and Now NUI (Natural User Interface)

Introduction

Microsoft Surface Touch TableI was hearing about Microsoft Surface far last few months, but did not get much information. Recently, I saw a post "PDC 2008" by Robert Levy and Brad Carpenter having a video session demonstrating the capabilities of Microsoft Session. The demonstrate the unique attributes of Microsoft Surface computing, with a dive into vision-based object recognition and core controls like ScatterView, and how the Surface SDK aligns with the multi-touch developer roadmap for Windows 7 and WPF. The software giant has built a new touch screen computer — a coffee table that will change the world. Forget the keyboard and mouse, the next generation of computer interfaces will be NUI (Natural User Interface) which uses natural motions, hand gesture and real world physical objects. The surface is capable of object recognition, object/finger orientation recognition and tracking, and is multi-touch and is multi-user. Users can interact with the machine by touching or dragging their fingertips and objects such as paintbrushes across the screen, or by placing and moving placed objects. This paradigm of interaction with computers is known as a natural user interface (NUI). Surface has been optimized to respond to 52 touches at a time.

Microsoft Surface applications can be written in Windows Presentation Foundation (WPF) and .Net language like C# or VB.Net. It is nicely integrated with Visual Studio 2008 following the same pattern of programming paradigms the .Net developers are used to. However it has custom WPF controls to allow programming for the unique interface of Surface. Developers already proficient in WPF can utilize the SDK to write Surface apps.

Object Recognition Multi User Application

Microsoft Surface SDK 1.0

Right now, Microsoft Surface SDK is not available for public. It has been distributed only to some of the Microsoft partners. I am eagerly waiting to get my hands on the SDK once it is launched. Since, I have already worked with SilverLight and WPF, I think, it would be quite easy to pick Microsoft Surface. This is true for every developer worked on WPF and used XAML. However, there is a small catch ... Working for surface would require more creativity and unlearning the GUI which we are used to. The new interface requires us to think about the UI from entirely a new perspective ... a 360 degree multi-touch perspective.

I am sure the developers deep in love with .NET programming and having high respect for Microsoft Technologies, would be very excited after seeing the video session of PDC 2008. The features demonstrated, and the ease of programming together with seamless process of learning would make you sit up staright on your seat, open Google to find out whether you can get hold of Microsoft Surface SDK. Hmm! As you might be thinking after watching the video, whether you need the touch screen device which costs $10K-15K, to practice Microsoft Surface? The answer is No! Microsoft has a simulator for Surface which would allow you to deploy and play around with your surface code. Unfortunately, that too is not available to public right now. So you might have to wait a little more, until of course you are working for the company included in the Microsoft's Partner list, currently allowed to download and use Microsoft Surface SDK and Simulator.

It Is Not Just Another Glorified And Hyped Touch Screen Computer

Many had a wrong impression about Microsoft Surface thinking it to be another glorified and hyped touch screen computer. The touch screen computers enable users to do away with keyboard and mouse. They can navigate the menu by touching various options to reach a logical end of viewing data or printing. And there ends the comparison. Microsoft Surface device also known as Microsoft Tabletop can do many more things, which you might think are not possible!

The three main components that differentiates it from a regular Touch-Screen device, Direct interaction, Multi-Touch Contact and Object Recognition.

  Object Recognition
  • Multi-touch contact: User need not use only one finger to manage digital data. If user dips five fingers in five different colors in the on screen paint palette and draws five lines with five fingers, you get five lines with five colors . . .
  • Direct interaction: Facility to manage digital information with hand gestures and touch instead on mouse and keyboard.
  • Object Recognition: This technology allows non-digital objects to be used as input devices. This means that the input source does not necessarily have to be digital in form.

This Is The Future

Companies are putting in millions of dollar in research for NUI. There is a nice video "TED: Sixth Sense" from Pattie Maes' lab at MIT, spearheaded by Pranav Mistry. It's a wearable device with a projector that paves the way for profound interaction with our environment. It demonstrates a device which responds to natural gestures of hand which is read by a camera. The UI is developed and projected using a small projector fitted in the same device. If you guys have seen movies like "Minority Report", see these technologies nearing to the imaginations.

The NUI immensely increases interaction with digital contents in a more simplified manner. One does not need to practice with mouse. It won't be a single user interface anymore. Two users can open two different menus at the same time .... (Right now your application would open one menu at a time). A 360 degree interaction, with each person using the same application independently. Surely, we need to think and see the UI very differently now and you are bound only by your imaginations.

So friend's start unlearning the GUI you are accustomed to, and buckle your seat belts for the next gen -- NUI.

Manish


.Net | Thoughts
Sunday, March 29, 2009 9:26:22 AM (GMT Standard Time, UTC+00:00)  #  Comments [6] Trackback
 Monday, February 23, 2009
Interactive Video Advertising With Silverlight 2

Introduction

Rich media advertisement is a buzz word today. Organizations are spending a huge amount to move out from a traditional banner advertisement approach, booklets and television to a more effective tactics where they can reach out to a wider mass through internet. Rich media advertisement forms a basis of wider coverage at less cost together with a wonderful user experience.

Macromedia Flash, already provides a state-of-art solution for it. However, it is mostly tied to its proprietary engine for shock wave and interaction. Flash are further, required to be embedded as a compiled unit. Besides all, it requires you to learn Flash an extra skill.

Something I like about silverlight is that it supports XAML based platform with language support for programming. EXtensible Application Markup Language (XAML) which is pronounced as Zamel, is used to define your canvas and storyboard, which are easy to manipulate at runtime using languages like C# or VB.Net. These are further deployed as a compressed unit rather than a compiled unit. This is no doubt a step further than what Flash has achieved. One drawback, however, is, adoption among wide number of serious users. I don't see it as a big drawback as long as Microsoft is serious about this product.

Silverlight Kickstart

My silverlight development environment includes VS2008 with SP1, Framework 3.5, Silverlight SDK and Microsoft Expression Encoder. I would not get into these details for the scope of this article. You may refer to Getting Started article for Silverlight, to setup your development environment. Further, if you donot want to get into the intrecacies of XAML, then you might also require Microsoft Expression Blend.

WMV for streaming Video with Silverlight

Silverlight supports WMV format for videos. Using Microsoft Expression Encoder these WMV files can be encoded to have markers on their timelines. These markers can be used by siliverlight for interaction. The markers are simply names given to a time in the video's timeline. Silverlight raises MarkerReached event (if registered) when a marker is reached while playing the video. This forms the basis of interaction between silverlight and streaming videos. There is a nice video tutorial explaining, how to add a marker using Microsoft Expression Encoder.

Silverlight UI

XAML in Silverlight allows you to do a lot of stuffs with the UI using its declarative tags. Few, real interesting things you can do, without any extra skill required, includes, drawing a curve, masking, controlling opacity, define animation ... all through XML like declarative tags ... Wow!. In this tutorial, I will be showing you how to create an interactive overlay on a running video. For this, I have a video with three markers defined on it (using Encoder). Now let us first examine the UI.

The UI

Few things, I would like to explain here, before we proceed to next step, since they have been referred ahead. Take a sneak into the code for things, I have marked in bold. Notice that:

  • Movie name is "MainMovieStream" defined as an attribute "x:Name".
  • The "MarkerReached" event is registered for the movie as "MainMovieStream_MarkerReached".
  • Canvas with a name "TopOverlay" which is placed -325 pixels on the left.
  • "TopOverlay" canvas has an inner element "TopText" with an event "MouseLeftButtonDown" handled by "TopText_MouseLeftButtonDown" function
  • A Canvas "BottomOverlay" is defined in a similar faishon except its top is "131".
Silverlight Story Board

Take a sneak into the code for things, I have marked in bold. Notice that:

  • Storyboard "TopOverlayIn" targets the canvas "TopOverlay".
  • The "Storyboard.TargetProperty" tells us that the "Left" property has to be changed.
  • The "SplineDoubleKeyFrame" defines, that after every 1 sec the target property moves near to the "Value=0". Hence, the Canvas.Left moves from -325 to 0
  • The Storyboard "TopOverlayOut" does exactly the opposite of "TopOverlayIn".

MediaControl.xaml

The Storyboards are treated as Canvas resource which would be used when required. Let us see the complete XAML for our tutorial.

C# Code

When you add a XAML file into your solution, visual studio responds with adding an associated code behind file for the XAML. Besides, you would also find a App.xaml and its code behind file with same name. While doing any development on Silverlight, most of the time you would ask "How can I pass values to Silverlight application at runtime" or in another way "How can I make it as a component to be used in other projects?". This is done through parameter passing at the time of initialization.

App.xaml.cs

Let us sneak into App.xaml.cs file where the necessary changes has been made for the same. The only changes required in the App.xaml.cs file are:

  • Declare an "IDictionary" object for paramters as a class variable

    public partial class App : Application {

        private IDictionary<string, string> initParams;


    ...

  • Initialize it in the "Application_Startup"

    private void Application_Startup(object sender, StartupEventArgs e)

    {

        this.RootVisual = new MediaControl();

        InitParams = e.InitParams;

    }

MediaControl.xaml.cs

Now let us sneak into the MediaControl.xaml.cs file to see how we collect the parameters and how we handle the animation and events.

In the code above we get the reference of the Silverlight application using "Application.Current as App" (marked in bold) in the "Page_Loaded" event. Once we have got the handle of the application we can access its public properties. In this case the parameters. As you can see, I am iterating through each parameters and storing the values into my local variables. The marker parameters here contains the storyboard names that we would see in the next section. Also notice, how I am handling the "MarkerReached" event and the "MouseLeftButtonDown" events. The actions are self explanatory here.

Embedding Silverlight RichMediaAd Control

Once you have done with this code, your control is ready to be used. When you compile a Silverlight application, you would notice that it generates a RichMediaAd.xap file under ClientBin folder of your web application which references the Silverlight application. This .xap file is nothing but a compressed file containing your application manifest and the DLL. You can use a simple un-zip command to view the files inside. In the page

Now let us see the code where we embed this Silverlight control we made.

Once you have embedded the XAP file. It is ready to run. Notice, that I am sending all necessary parameters at runtime, including the media I want to use.

Happy Silverlight Programming !!


.Net
Monday, February 23, 2009 2:14:53 PM (GMT Standard Time, UTC+00:00)  #  Comments [3] Trackback
 Friday, November 07, 2008
Getting Started with LINQ - Part I

Few months back while upgrading my project to .NET Framework 3.5 for using LINQ, I had conducted a knowledge sharing session for LINQ. The piece of code and explanation are the parts taken from the knowledge sharing session.

Before we start off with "Getting started with LINQ - Part I", I would like to explain few good things I learnt while working with LINQ. Also I would assume that you are familiar with the Generics, C# 3.0 language enahancements and basics of SQL. If you are unaware of the language enhancement, I would like to recommend visiting MSDN where you wouldfind some good videos about Visual C# 3.0 enahancements. You can also visit a nice blog by Mike Hanley where he quickly reviews most of the C# 3.0 Language enhancements with examples and comparison to C# 2.0. For Genrics you can visit MSDN article "An Introduction to C# Generics".

Introduction

LINQ is not just a query, it stands for "Language Integrated Query" and more than that it is a data iteration engine applied to the language. The iteration engine is inbuilt in the language. LINQ uses mainly IEnumerable<T> for iteration and IQueryable<T> for querying. C# 3.0 enhancements introduced the "var" keyword which is an anonymous type.

var m = new { FirstName = "Manish", LastName = "Singh" };

Notice the use of "var keyword" and "anonymous class". The first thing that should strike in your mind is - "Hey! Is C# still doing the type checking here?" The answer is YES! C# is still doing the type checking here. The first time you use "var" type, it gets intialized with the type inferred from RHS. If you try to change the type of the variable later in the code, C# complains with an error. The CLR is clever enough to shoot off an error message like "Cannot implicitly convert type 'X' to 'Y'." at the design time itself. However, you must be careful in using "var" keyword or else, very quickly you can land up in a mess, with lots of anonymous variable, making it difficult to debug and maintain. The best is, use it when you know the return type can vary and would be decided at runtime. In short, use "var" when you are confused about the return type :-).

LINQ uses deferred query. This means that the query is not performed when the line containing the query is executed. It is performed during the actual enumeration of the object. However, methods like ToList(), ToArray(), Sum(), Max(), Count(), First(), Last() etc is called immediately and are also known as Non-Deferred queries. The advantage of deferred query is that it executes when required and does not apply any extra overload to your code. Non-Deferred queries execute immediately returning an instance of the IEnumerable<T> list. Why? Because C# 3.0 language enhancement allows you to change the data while iterating using the iterator (Not allowed in C# 2.0).

I would show you LINQ using Lamda expressions. Thus, let us have a little introduction to Lamda expression. Lamda expressions are coma-delimited parameter(s) followed by lambda operator "=>", followed by an expression or statement block. e.g. [(param-1, param-2,..., param-N) => expr]. Example: x => x.FirstName.Equals("Manish"). This lambda expression can be read as "x goes to x" or "input x returns x".

For using LINQ for entities your project must be running on framework 3.5, must reference System.Core and you must be having the using directive "System.Linq". Normally, if you use VS 2008 with Framework 3.5 installed, while creating a new project, VS 2008 does all the work for you.

LINQ Console Program
To start add a new project "Sample Data" of type class library in your solution. This is where all our object declaration and initialization takes place. The following image shows the solution explorer with a project "SampleData" in it.

solution explorer

The "SampleData.cs" int the "SampleData" project includes a classical example of Customer, Product, Order and OrderItem. For the sake of simplicity, I have declared the properties as "public".

SampleData.cs
  The "DataContext.cs" int the "SampleData" project includes the initialization code for Customer, Product, Order and OrderItem. For the sake of simplicity, I have declared all methods static for the sake of simplicity. This method is required from my console program to collect some meaningful data for "Customer", "Product", "Order" and "OrderItem". The next section shows you a sample initialization.

DataContext.cs

To initialize the entities with some sample data you may create the object with fictitious but meaningful data and assign it to a list as shown in the image below. Later we will query these data and check the output.

DataContext.cs

Next, we add a new console project into your solution say "LINQ-Object". Add Reference to "SampleData" project. In the "Program.cs" file that is created by VS 2008 for you, go ahead and declare a bunch of static methods as explained below. After that you can call each of these from the "static void Main(string[] args) " method and check the output. Also try to use break point and see what is displayed.

LINQ: Select
Select Most of the extension methods of LINQ applied on IQueryable<T> or IEnumerable<T> returns another IQueryable<T> or IEnumerable<T>. This allows you to nest the methods in progressive manner like "Append()" method of "StringBuilder" class. I have purposefully applied nested select to explain this. Select is a deferred query and parsing is done at the runtime.

Output

LINQ: Where Clause
Where In this part of the code I have explained a simple "where" clause using LINQ. The query simply returns all customer who belong to "category", "A". If you see the declaration of "Customer" entity explained earlier, you would see that it has an attribute "category" to help categorize the customers into groups depending on their importance.

Output

LINQ: Join
Join In this part of the code "Customer" and "Order" to see the customer's full name, order name and order date. When you run the program the output (see image below) would be shown, depending on your data.

Output

LINQ: Group Join
Group Join In this part "Customer", "Order" and "OrderItem" is joined to see the customer full name, customer category, order name and order details like product name, quantity and price. When you run the program the output (see image below) would be shown, depending on your data.

Output

LINQ: Group By
Group By This part of the code, returns the customers grouped by their category. When using "Group By" extension method in LINQ, it returns a two dimensional list. Each elements of the outer list contains a list of customers belonging to the same group.

Output

LINQ: Order By
Order By This section explains the "Order By" clause as seen in SQL. You can have multiple attributes in the "Order By" clause and also provide sorting direction.

Output

LINQ: TakeWhile
TakeWhile "Take" extension method allows you to select items from top while the TakeWhile extension method allows you to select items based on certain condition. The code selects items whose string length is below six.

Output

LINQ: Skip
Skip "Skip" extension method allows you to skip items from top while the SkipWhile extension method allows you to skip items based on certain condition. The code skips five items from the top.

Output

There are several more methods defined in LINQ. I would encourage you to apply more of these extension menthods for practice and clarity.


.Net
Friday, November 07, 2008 1:30:05 PM (GMT Standard Time, UTC+00:00)  #  Comments [3] Trackback