Wednesday, April 29, 2009

DataBinding in Blend 3 for Designers

After 8 continuous articles on features of Silverlight 3 Beta, I started now looking at each feature of it and soon will give insight on the same,meanwhile I shifted my focus to Blend 3 which I touch upon only once, so I thought should start looking at it also.

I have already covered some of the new features of Blend 3 in my previous article. Now today I am talking about the features rather only Data feature of Blend 3. Designers always need to work hard to create specific look and feel and give it to developer for development. We know Blend and Visual Studio are tightly coupled, so both can work together. But how about Designer doing POC (Proof of Concept) which will actually show/represent data, Offcourse designers may not able to program it,but from Blend 3 they have few good options.

It is not like that Databinding was impossible in previous version, but now in Blend 3 it is much more friendly.So let talk about that.Please make note that, this is only for “Designers” who are not part of coding, so for developers this post may sound very basic and generic or you may ask what so great in this, but for Designers I am sure it is much more useful.

Open a new project in Blend 3 Preview and look for following “Data” tab.

DataTab

crop1

Right now I have added one XML file by opening this solution in Visual Studio (In Blend 3, if you say add new item, there is no XML document option, so need to do that from Visual Studio)

Employee.xml :

<?xml version="1.0" encoding="utf-8" ?>
<Employees>
  <Employee>
    <EmpId>1</EmpId>
    <EName>Vikram</EName>
    <Sex>Male</Sex>
    <Phone>123-456-7890</Phone>
    <Street>Silverlight Street</Street>
    <City>Pune</City>
    <State>MH</State>
    <Zip>411005</Zip>
    <Country>India</Country>
  </Employee>
  <Employee>
    <EmpId>2</EmpId>
    <EName>Prachi</EName>
    <Sex>Female</Sex>
    <Phone>123-456-7890</Phone>
    <Street>Silverlight Street</Street>
    <City>Pune</City>
    <State>MH</State>
    <Zip>411005</Zip>
    <Country>India</Country>
  </Employee>
  <Employee>
    <EmpId>3</EmpId>
    <EName>Swati</EName>
    <Sex>Female</Sex>
    <Phone>123-456-7890</Phone>
    <Street>Silverlight Street</Street>
    <City>Pune</City>
    <State>MH</State>
    <Zip>411005</Zip>
    <Country>India</Country>
  </Employee>
  <Employee>
    <EmpId>4</EmpId>
    <EName>Anuja</EName>
    <Sex>Female</Sex>
    <Phone>123-456-7890</Phone>
    <Street>Silverlight Street</Street>
    <City>Pune</City>
    <State>MH</State>
    <Zip>411005</Zip>
    <Country>India</Country>
  </Employee>
</Employees>

Now with the “Import Sample Data from XML…” option from Data Tab, you can associate this XML file as datasource like this :

empxml

It will then analyze your XML file and it will generate metadata [ Refer the Sample Data folder it creates, it creates on xaml and xsd file], It will show you the contents in form of Collection and properties, Also you can go ahead and edit those properties like this :

empcollection

We already have some data inside xml tags but you can edit that sample data for display purpose by clickin on small cylindrical symbol in front of Collection generated, so it will throw you a window for editing like this :

EditXML

So, it provide you all the facilities to add and modify properties. Now you just need to simply drag-drop that Collection on Canvas and it will automatically convert that to Grid (Employee.xaml file I was talking before) and then you can simply go ahead and modify that XAML as per look and feel you want, XAML code which is generated and which I edited is like this :

<UserControl.Resources>
        <DataTemplate x:Key="EmployeeTemplate1">
            <StackPanel>
                <TextBlock Text="{Binding Path=City}" Margin="1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="150"/>
                <TextBlock Text="{Binding Path=Country}" Margin="1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="150"/>
                <TextBlock Text="{Binding Path=EmpId}" Margin="1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="150"/>
                <TextBlock Text="{Binding Path=EName}" Margin="1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="150"/>
                <TextBlock Text="{Binding Path=Phone}" Margin="1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="150"/>
                <TextBlock Text="{Binding Path=Sex}" Margin="1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="150"/>
                <TextBlock Text="{Binding Path=State}" Margin="1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="150"/>
                <TextBlock Text="{Binding Path=Street}" Margin="1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="150"/>
                <TextBlock Text="{Binding Path=Zip}" Margin="1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="150"/>
            </StackPanel>
        </DataTemplate>
    </UserControl.Resources>

    <Grid x:Name="LayoutRoot" Background="White" DataContext="{Binding Source={StaticResource Employee}}">
        <data:DataGrid
          AlternatingRowBackground="Azure"
          GridLinesVisibility="None"
          SelectionMode="Single"
          ItemsSource="{Binding Mode=OneWay, Path=EmployeeCollection}" AutoGenerateColumns="False" VerticalAlignment="Top" Height="126" Margin="0,22,0,0" >
            <data:DataGrid.Columns>
                <data:DataGridTextColumn Header="EmpId" Binding="{Binding Path=EmpId}"/>
                <data:DataGridTextColumn Header="Name" Binding="{Binding Path=EName}"/>
                <data:DataGridTextColumn Header="Sex" Binding="{Binding Path=Sex}"/>
                <data:DataGridTextColumn Header="City" Binding="{Binding Path=City}"/>
                <data:DataGridTextColumn Header="Country" Binding="{Binding Path=Country}"/>
                <data:DataGridTextColumn Header="Phone" Binding="{Binding Path=Phone}"/>
                <data:DataGridTextColumn Header="State" Binding="{Binding Path=State}"/>
                <data:DataGridTextColumn Header="Street" Binding="{Binding Path=Street}"/>
                <data:DataGridTextColumn Header="Zip" Binding="{Binding Path=Zip}"/>
            </data:DataGrid.Columns>
        </data:DataGrid>
    </Grid>

This way you can see that how it is getting bind by each field, see this :

ItemsSource="{Binding Mode=OneWay, Path=EmployeeCollection}"

Remember Binding Mode by default is “OneWay” and even if you make it “TwoWay” it won’t be updating your original xml,but you can see it reflect in the design. Also beside this pure XML, you can also bind the XML generated from DataSet (Hope you recollect that DataSet provides one method to export schema to XML as WriteXML(),such XML also can be used to represent data), If you feel that you are restricted due to XML then you can go and explore “ObjectDataSource” facility.After doing this,output will be like this :

Grid

This is how you can build full functional POC in Blend 3 by having real data in it, So when Designers will give such inputs to Developers, I am sure sharp developers like you will quickly understand what they need to code.

Let me know your feedback, Soon I will be talking much more better stuff on Blend,Silverlight 3 and offcourse .NET 4.0 and Visual Studio 2010 in coming weeks.

Vikram.

Thursday, April 16, 2009

Overview of Live Smooth Streaming,Live Encoding and Streaming with Expression Encoder 2 – Part 8

This is my last part of Silverlight 3 Lap around Series,It is not that much related to core Silverlight 3 but it share same capabilities which Silverlight provides, I would like to thank you all for your wonderful response and feedback throughout the series, I will surely follow it in my upcoming articles. I know I missed out Deep linking,Effects and few more small things, but I kept it for future discussion.

There is lot of discussion going around in Media Industry about Silverlight Streaming,Recently MIX09 was big example, We all know next Olympics are going to be supported by Silverlight 3, But Olympics and all are big thing, How we can empower our day to day apps which uses streaming that I am touching upon now. I am sure those who are planning for streaming, this will be initial guideline for them. This post will not contain any code,this will be full of screenshots, since everything is getting done via IIS 7.0 and other few tools.

Smooth Streaming :

It is bit hard to represent each and every step here, So I would like to redirect you to IIS Smooth Streaming where you will find step by step guide, Advantages of it etc. [Note : I have use “Big Buck Bunny” example as reference for my “Bear” example and I have use same infra too]. It is necessary to have Live Smooth Streaming Plug-in in your IIS 7.0, once you installed that you find the necessary plug-in inside your IIS like this :

IISStart

After creating Publishing point there, you can import your media in encoder like this :

Bhalu Then in order to create series of “ismv“ files you need to choose following options and do necessary settings like this :

BhaluSettings

You can see that, I have chosen “Adaptive Streaming”  in profile and if you see carefully, Output Mode is IIS Smooth Streaming, so now save this job and encode, then you will have series of ismv files inside job folder, copy those to your wwwroot and you can generate manifest using pushencoder32/64 exe file on command prompt,make sure that time on prompt you fire that command from your virtual directory and use your publishing point like this :

pushencoder32 <Url of Publishing Point> <ism-file>

so it will be like :

pushencoder32 http://localhost/LiveSmoothStreaming.isml “Bear.ism”

Point to be noted here that “isml” is nothing but the publishing point we added on our IIS, So now for output I am using same HTML page of Big Buck Bunny but with different URL so as to display my Bear video like this :

Output1

You can see that I am entering “Bear.ism” as presentation name and I can choose template from Silverlight player option, well this is Smooth Streaming and output is like this :

 Output4

You will now see much more things like Frame Rate and Max Bit Rate which you can adjust too, see this :

Framerate2

FramRate1

This is how you can do Smooth Streaming using IIS 7.0 in easy way, Read more on article given on IIS site.

Live Encoding and Live Streaming : 

You must have seen some Live streaming going on in Silverlight player on several site, I know there are several mechanism to do it, One of which I came across and which I feel simple is now I am sharing with you, For this you need IIS in place with Microsoft Expression Encoder 2 with its Service Pack. Open new job in Encoder and you will find following screen :

Livebutton

Click on “Live encoding” button, you will be then looking at following screen :

LiveConsole1

For this Live streaming, I have used my built-in laptop camera, you have freedom to choose your device from following settings :

LiveConsole3

From Device Configuration you can choose device and from Output options you have either File Archive or Streaming, I have chosen “Streaming”, Right now since I don’t have any server with me so I am using Local IIS, you can choose and give your desired location for live streaming in “Location” option along with the port.Links in output panel will guide you for options, once you done with selecting video device you will see the input from camera like this :

Cam

StreamingOne

So once you select video device and done with necessary audio settings you can click on “Launch Preview” button, which will create a sample HTML page which will host a silverlight player in it and will stream it whatever is input from camera it will stream it and you will be able to see it in your browser, In reality if you choose location it will render in your website like this :

StreamingTwo

Hope you will try this out, I am much into Media and jazzy UI design, so if there any feedback or suggestions from you,please let me know, would like to explore that too.I am sure,those who never look at streaming capabilities of Silverlight, they will surely will try this out.Meanwhile I will soon come with lots of new experiments and stuff in Silverlight, so keep visiting here.

Vikram.

Friday, April 10, 2009

Silverlight 3 : DataGrid Programming – Part 7

I have already discussed about DataForm, its usage and implementation in this series in my 3rd Article, Now today I am shifting my focus to DataGrid control, Those who are not much familiar with DataGrid, I request you to kindly visit my old Silverlight 2 Grid Binding article. Developers who are from ASP.NET background like me, knows the pain and efforts we need to take to customize DataGrid as per clients need, with this small introductory series, I am talking few things from which you will be able to create strong applications on top of that.

For this you need following assemblies mainly as :

  • System.Windows.Controls
  • System.Windows.Controls.Data
  • System.ComponentModel.DataAnnotations
  • System.Collections.Generic

To make this example simple and quick, I am making use of our traditional generics, In reality you can replace that Data part with your Database/Object whatever suits your application.

I am declaring one class with some properties like this :

public class sigheads
    {
        [Required(ErrorMessage = "Field Cannot be left Blank")]
        public string FirstName { get; set; }
        public string LastName { get; set; }
        [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Invalid E-Mail ID")]
        public string Email { get; set; }
        [Range(0, 999, ErrorMessage = "Invalid Age")]
        public int Age { get; set; }
        public string SIG { get; set; }
        public DateTime WebCastDate { get; set; }
   }

If you have read my DataForm in Silverlight 3 article,you must have now drawn a conclusion why those [Required and [Regular like attributes are there and why we have System.ComponentModel.DataAnnotations namespace, This is for validating our data.After few lines I will put screenshot for your better understanding. Now lets write some few lines of code which will bind my this class and members to gird like this :

public List<sigheads> GetSIGHeads()
       {
           List<sigheads> sglst = new List<sigheads>();
           sglst.Add(new sigheads() { FirstName = "Vikram", LastName = "Pendse", Age = 27, Email = "vikram@dotnetcoe.com", SIG = "Silverlight", WebCastDate=Convert.ToDateTime("3/3/2009") });
           sglst.Add(new sigheads() { FirstName = "Mahesh", LastName = "Sabnis", Age = 40, Email = "mahesh@dotnetcoe.com", SIG = "WCF", WebCastDate = Convert.ToDateTime("3/4/2009") });
           sglst.Add(new sigheads() { FirstName = "Manish", LastName = "Sharma", Age = 28, Email = "manish@dotnetcoe.com", SIG = "WPF", WebCastDate = Convert.ToDateTime("3/5/2009") });
           sglst.Add(new sigheads() { FirstName = "Abhijit", LastName = "Gole", Age = 27, Email = "abhijit@dotnetcoe.com", SIG = "VC++", WebCastDate = Convert.ToDateTime("3/6/2009") });
           sglst.Add(new sigheads() { FirstName = "Varun", LastName = "Lokhande", Age = 27, Email = "varun@dotnetcoe.com", SIG = "MOSS-WSS", WebCastDate = Convert.ToDateTime("3/7/2009")});
           return sglst;
       }

Now,this we need to bind to our DataGrid like :

void MainPage_Loaded(object sender, RoutedEventArgs e)
{
      dg.ItemsSource = GetSIGHeads();            
}

Our XAML code will be like this :

<Grid x:Name="LayoutRoot" Background="White" >
        <data:DataGrid x:Name="dg" Width="700" Height="300"
                       AlternatingRowBackground="Azure"
                       GridLinesVisibility="None"
                       SelectionMode="Single"
                       AutoGenerateColumns="False">
            <data:DataGrid.Columns>
                <data:DataGridTextColumn Binding="{Binding FirstName}" Header="FirstName"/>
                <data:DataGridTextColumn Binding="{Binding LastName}" Header="LastName"/>
                <data:DataGridTextColumn Binding="{Binding Email}" Header="Email"/>               
                <data:DataGridTextColumn Binding="{Binding Age}" Header="Age"/>
                <data:DataGridTextColumn Binding="{Binding SIG}" Header="SIG"/>
                <data:DataGridTemplateColumn Header="WebCastDate" >
                    <data:DataGridTemplateColumn.CellTemplate>                      
                        <DataTemplate>
                            <my:DatePicker
                                SelectedDate="{Binding WebCastDate,Mode=TwoWay}">                               
                            </my:DatePicker>
                        </DataTemplate>
                    </data:DataGridTemplateColumn.CellTemplate>
                </data:DataGridTemplateColumn>
               <data:DataGridTemplateColumn Header=”Video”>
                    <data:DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <HyperlinkButton x:Name="btnVideo" Content=" Video" Foreground="DarkBlue" Click="btnVideo_Click" ></HyperlinkButton>
                        </DataTemplate>
                    </data:DataGridTemplateColumn.CellTemplate>
                </data:DataGridTemplateColumn>
                <data:DataGridTemplateColumn>
                    <data:DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <HyperlinkButton x:Name="btnDelete" Content=" Delete" Foreground="DarkBlue" Click="btnDelete_Click" ></HyperlinkButton>
                       </DataTemplate>
                    </data:DataGridTemplateColumn.CellTemplate>
                </data:DataGridTemplateColumn>
            </data:DataGrid.Columns>           
        </data:DataGrid>
    </Grid>

You can clearly see that I am binding columns explicitly with {Binding <Name of Field from sighead class>}, Also I am making use of DataTemplates where I am putting Links and Calendar control, well after few screenshots below you will automatically come to know what those DataTemplate does.So on building this much lines of code output will be :

BasicGrid

I think there is no need to say that sorting is by default and alternate row color is done by setting attribute of Grid as :

AlternatingRowBackground="Azure" 
GridLinesVisibility="None"
SelectionMode="Single"

AlternateRowBackground will set some color to alternate rows, Gridlines visibility can be set-reset and Selection Mode allows user to either select one row or multiple row at a time.

ValidGrid

I have already talked about  System.ComponentModel.DataAnnotations namespace which helps us to set validations over each field, so while editing you can see whether new data is valid or not as shown in above screen and this can be done using attribute over field like this :

[RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage = "Invalid E-Mail ID")]
public string Email { get; set; }

You can see a small Calendar icon in grid which is done using DataTemplate and which helps to select date from calendar, XAML code above is self-sufficient to understand. Once you click on it, it will drop a full functional calendar like this :

CalGrid

Now you can see two links in Grid as “Video” and “Delete”, from Silverlight 2 we have a popup control, but as per tradition of my blog to explore new stuff, I am now making use of “Silverlight Child Window” , This template you will be able to get by Right clicking project ->Add New Item like this :

ChildPopup

This Child Window come with some by default XAML :

<Grid x:Name="LayoutRoot" Margin="2">
       <Grid.RowDefinitions>
           <RowDefinition />
           <RowDefinition Height="Auto" />
       </Grid.RowDefinitions>
       <TextBlock x:Name="Message" TextWrapping="Wrap" />
       <Button x:Name="CancelButton" Content="Cancel" Click="CancelButton_Click" Width="75" Height="23" HorizontalAlignment="Right" Margin="0,12,0,0" Grid.Row="1" />
       <Button x:Name="OKButton" Content="OK" Click="OKButton_Click" Width="75" Height="23" HorizontalAlignment="Right" Margin="0,12,79,0" Grid.Row="1" />
   </Grid>

Here beside <TextBlock> which I added up everything is by default. So by looking at those two buttons you must have guess what’s the use of this child window, I am using this here as some Alert box or it is rather something similar to Model Popup control in Ajax.

C# Code :

public partial class DeleteRecord : ChildWindow
    {
        int index = 0;
        public DeleteRecord(string wtlt,string msg,int idx)
        {
            InitializeComponent();

            index = idx;
            this.Title = wtlt;
            this.Message.Text = msg;
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
            int deli = index;
            //Give a service call to delete record and pass index/you can pass <id> in same manner.
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

You can see that I am passing certain parameters to DeleteRecord() which is my Child window, well I am passing those from MainPage.xaml.cs, before looking at that, you can see from above code that you can freely use those Ok and Cancel button event and can implement whatever logic you want to. I am just declaring one variable i and some string, why I am using “i” is to prove that Data from MainPage.xaml.cs can be pass over here, So in reality you can pass Record’s “id” to do particular DML Operation.

To pass these values to this Child Windows you need to write following code in MainPage.xaml.cs like this :

private void btnDelete_Click(object sender, RoutedEventArgs e)
       {
           int i = dg.SelectedIndex;
           DeleteRecord del = new DeleteRecord("Record Deleting...", "Are you sure you want to Delete Record no." + i, i);
           del.Show();
       }

Where btnDelete is my Hyperlink button which I embeded in DataGrid’s template. I am making instance of DeleteRecord() which is nothing but my child window and passing selected record’s index along with message.It will look like this once you click on Delete link :

DelpopGrid

Once you click on either OK or Cancel, we have their respective events ready to handle. Similarly I did this for URL by passing url of video to a separate child window and embedded Media Element in it, so it looks like this :

VidpopGrid

So this is how you can even play video also from Grid, I know this may be a fast preview, but as I said in my previous articles, more is coming in future,So I am not going to stop on this example only, Soon I will be talking about actual CRUD operations with WCF and LINQ etc.

Hope this will help you to make use of DataGrid control in your Silverlight 3 projects/applications.

Vikram.

Monday, April 6, 2009

Silverlight 3 : Out of Browser Support – Part 6

Some people saying on various blogs and forums that this was the most awaited feature of Silverlight, well I have not contributed there because few questions came to my mind :

  • Why we need such thing when we have capability of creating WPF applications which will run on desktop/out of browser environment ??
  • How they will run? will they need Silverlight Plug-in or will they run as standard exe under windows environment? (Sorry, I said windows environment,because I don’t have Mac and Linux environment with me for testing)
  • If we process some data in Silverlight Out of Browser, will it get store in Isolated Storage? will it be sufficient storage since there is lot craze going on for Silverlight LOB applications.

Well, I started exploring at my best, Some of above are still unanswered questions for me,but I really find Out-of-Browser as an Innovation in Silverlight Technology. Since we are doing a lap around series, right now I will discuss only how to make it out of browser, once I finish this initial series, I will then take each topic in depth.

Requirements for Out of Browser Silverlight Applications :

  • Working Silverlight application.
  • sllauncher.exe file should be available.

Once your Silverlight application is ready, then to make it available out of browser, first you need to go to file “AppManifest.xml” under Properties folder.Then you will find a commented block with following message :

<!-- Uncomment the markup and update the fields below to make your application offline enabled –>

You just need to uncomment it and you are then done with it. Basically it contains :

<Deployment.ApplicationIdentity>
        <ApplicationIdentity
            ShortName="Out of Browser Silverlight Application"
            Title="My Out of Browser Silverlight Application-MVP Vikram Pendse">
            <ApplicationIdentity.Blurb>Out Of Browser Silverlight Application Created by MVP Vikram Pendse</ApplicationIdentity.Blurb>               </ApplicationIdentity>
</Deployment.ApplicationIdentity>

If you observe carefully, there is nothing “great” to understand that piece of xaml, it is pretty self-explanatory. Title attribute will show the Title on your out of browser app and <ApplicationIdentity.Blurb> will hold the description about application. So any more thing can be done with this block?..yes, a lot more can be done. You can customize the experience by adding your own icons to app,but before this, first lets talk how to launch this application out of browser. First run your application in browser, then right click on your application, you will get following context menu :

outb1

 

outb2

In era of Silverlight 2, we use to get only one option in context menu as “Silverlight Configuration” , now with the introduction of Silverlight 3 Out of browser support, we get second option as “Install..<followed by name of application>..onto this computer…”, once you click on this, you will get following message window :

outb3

Well, We have two options now, Start Menu and Desktop but have you read this message above it? as “Please confirm the locations for the shortcuts.” ,see the last word “shortcuts”, so it creates shortcuts for what and whom? Answer is :

C:\Program Files\Microsoft Silverlight\3.0.40307.0\sllauncher.exe

No, I am not saying with no base to you, if you check on Desktop a shortcut will be generated, you double click it, it will run your application as is it runs in browser, if you choose Start Menu, it will add link in Start list and both can be check too.

Well if you right click on that shortcut generated, you will get :

outb4

If you see the Target box it contains :

"C:\Program Files\Microsoft Silverlight\3.0.40307.0\sllauncher.exe" localhost.0

Comment box shows : “Allows saving your tasks offline”

[Try to change Target as “c:\” and see the effect and change in icon, Also try to delete sllauncher.exe or put it at different locations and check then if that out of browser working or not, Also try to run it on Non Silverlight environment,Try to open that offline application in Reflector etc.This will help you more to understand the architecture of this.]

Now see this install application window again :

outb3

If you see this box, you can see a Icon on left side, to customize this experience and to put your own Icon, you need to add following xaml in that uncommented block in AppManifest.xaml like this :

<ApplicationIdentity.Icons>
        <Icon Size="16x16">Images/sls16.png</Icon>
        <Icon Size="32x32">Images/sls32.png</Icon>
        <Icon Size="64x64">Images/sls64.png</Icon>
        <Icon Size="128x128">Images/sls128.png</Icon>
</ApplicationIdentity.Icons>

You can set some images to this screen of install application as well as in your title bar of actual offline application. it can be in different sizes like “16X16”,”32X32”..etc. with embedding path of that image.

So question may to come to your mind that “Can it be done programatically??” ..means can you detach this browser app to out of browser programatically?, answer is “Yes, you can!”.

If you have command button in your browser application, then you can use its click event to detach app like this :

private void Button_Click(object sender, RoutedEventArgs e)       {
          App.Current.Detach();
}

Basically App.Current.Detach(); returns a boolean, so you can check the state whether it is detached or not.

Also with App.Current.RunningOffline you can check whether application is running in browser or out of browser,since it is also returns you boolean.

If you want to remove this application, you can do so by again right clicking on application,like this :

outb5

outb6 

Well, let me make it clear that right now it is not supporting Microsoft Sync Framework, In my upcoming articles I will be talking about handling data and giving calls to services etc. so this out of browser concept will be more clear to you. I know few more things can be talked on this, but I am not doing here since we are in our lap around introductory phase and also we need to learn other features too, so do expect more stuff here in coming days.

Hope this will help you to understand Silverlight Out of Browser.

Vikram.

Friday, April 3, 2009

Silverlight 3 : Creating Ads using Silverlight Advertising Creation Kit aka SACK – Part 5

First of all thank you very much for your wonderful response for my last four articles on basic lap around articles on Silverlight 3 Beta, now today I am going for fifth one.

We all know how Rich UI and amazing animations can be made using Silverlight Technology, Silverlight is all about richness and jazz on web, so how can Ads [Advertising] will left behind?? , Here you can download Silverlight Advertising Creation Kit which is actually targeted to Silverlight 2, but since we already started our journey for Silverlight 3, so I am directly modifying and going to discuss few samples given in that kit. Below is mix application ad where I have mixed “createTAG” and “ExpandAd” projects together from the SACK Kit. Idea behind is not to replicate something is already there, but to make you aware, so that you can implement and give a way to your wild imaginations and create some knock-out Ads.

Download SACK Bits :

http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=0d7c2850-8253-4254-a7c5-214dcfd2768a

Download SACK Publishing and Serving Guide :

http://www.microsoft.com/downloads/details.aspx?FamilyID=5f4e50ec-3923-49f5-9718-bfbcff3c2325&DisplayLang=en

We see few logos or Images everywhere on sites occupying small small sections and are continuously catching our attention, when we click on them, it redirect to us at desired location.To give example, I created small Microsoft MVP ad which redirects me to nomination page and also shows URL on my Page like this :

adck1

Once I click on this Image, it will redirect me to destination URL like this :

adck2

You can see that it redirect me to MVP nomination URL and I have also printed URL on my page in Blue color, looks simple?? yes, it is damm simple, This is what they are calling as SACK ;)

Now lets come to our actual example where I am mixing above example with some animation. I am carrying same bits and images, So I am using some of the images which are already in SACK kit examples like Halo Banner etc.

XAML Code :

<Grid x:Name="LayoutRoot" Background="Transparent" MouseLeave="LayoutRoot_MouseLeave">
        <Grid.Clip>
            <PathGeometry>
                <PathFigure IsClosed="True" StartPoint="0,0">
                    <LineSegment Point="728,0"/>
                    <LineSegment Point="728,90"/>
                    <LineSegment Point="0,90"/>
                </PathFigure>
            </PathGeometry>
        </Grid.Clip>
        <Grid x:Name="Expandable" Height="360" Margin="0,-271,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.5,0.5">
            <Grid.RenderTransform>
                <TransformGroup>
                    <ScaleTransform/>
                    <SkewTransform/>
                    <RotateTransform/>
                    <TranslateTransform/>
                </TransformGroup>
            </Grid.RenderTransform>           
            <Image Source="TechEd.png" MouseLeftButtonUp="SwirledBackground_MouseLeftButtonUp" Width="600" Height="600" Margin="0,90,0,0" Opacity=".50" Stretch="Fill" x:Name="SwirledBackground"  />           
        </Grid> 
        <Image Source="haloBanner.jpg" Margin="0,0,0,270" x:Name="BannerImage" MouseMove="BannerImage_MouseMove"/>

</Grid>

Animation for Expanding image like this :

<UserControl.Resources>
        <Storyboard x:Name="AdExpand">
            <DoubleAnimationUsingKeyFrames Storyboard.TargetName="Expandable" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)" BeginTime="00:00:00">
                <SplineDoubleKeyFrame KeyTime="00:00:00" Value="0"/>
                <SplineDoubleKeyFrame KeyTime="00:00:00.7000000" Value="271">
                    <SplineDoubleKeyFrame.KeySpline>
                        <KeySpline ControlPoint1="1,0" ControlPoint2="1,1"/>
                    </SplineDoubleKeyFrame.KeySpline>
                </SplineDoubleKeyFrame>
            </DoubleAnimationUsingKeyFrames>
            <PointAnimationUsingKeyFrames Storyboard.TargetName="LayoutRoot" Storyboard.TargetProperty="(UIElement.Clip).(PathGeometry.Figures)[0].(PathFigure.Segments)[1].(LineSegment.Point)" BeginTime="00:00:00">
                <SplinePointKeyFrame KeyTime="00:00:00.7000000" Value="728,360">
                    <SplinePointKeyFrame.KeySpline>
                        <KeySpline ControlPoint1="1,0" ControlPoint2="1,1"/>
                    </SplinePointKeyFrame.KeySpline>
                </SplinePointKeyFrame>
            </PointAnimationUsingKeyFrames>
            <PointAnimationUsingKeyFrames Storyboard.TargetName="LayoutRoot" Storyboard.TargetProperty="(UIElement.Clip).(PathGeometry.Figures)[0].(PathFigure.Segments)[2].(LineSegment.Point)" BeginTime="00:00:00">
                <SplinePointKeyFrame KeyTime="00:00:00.7000000" Value="0,360">
                    <SplinePointKeyFrame.KeySpline>
                        <KeySpline ControlPoint1="1,0" ControlPoint2="1,1"/>
                    </SplinePointKeyFrame.KeySpline>
                </SplinePointKeyFrame>
            </PointAnimationUsingKeyFrames>
        </Storyboard>
        <Storyboard x:Name="AdCollapse">
            <DoubleAnimationUsingKeyFrames Storyboard.TargetName="Expandable" Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)" BeginTime="00:00:00">
                <SplineDoubleKeyFrame KeyTime="00:00:00" Value="271"/>
                <SplineDoubleKeyFrame KeyTime="00:00:00.7000000" Value="0">
                    <SplineDoubleKeyFrame.KeySpline>
                        <KeySpline ControlPoint1="1,0" ControlPoint2="1,1"/>
                    </SplineDoubleKeyFrame.KeySpline>
                </SplineDoubleKeyFrame>
            </DoubleAnimationUsingKeyFrames>
            <PointAnimationUsingKeyFrames Storyboard.TargetName="LayoutRoot" Storyboard.TargetProperty="(UIElement.Clip).(PathGeometry.Figures)[0].(PathFigure.Segments)[1].(LineSegment.Point)" BeginTime="00:00:00">
                <SplinePointKeyFrame KeyTime="00:00:00.7000000" Value="728,90">
                    <SplinePointKeyFrame.KeySpline>
                        <KeySpline ControlPoint1="1,0" ControlPoint2="1,1"/>
                    </SplinePointKeyFrame.KeySpline>
                </SplinePointKeyFrame>
            </PointAnimationUsingKeyFrames>
            <PointAnimationUsingKeyFrames Storyboard.TargetName="LayoutRoot" Storyboard.TargetProperty="(UIElement.Clip).(PathGeometry.Figures)[0].(PathFigure.Segments)[2].(LineSegment.Point)" BeginTime="00:00:00">
                <SplinePointKeyFrame KeyTime="00:00:00.7000000" Value="0,90">
                    <SplinePointKeyFrame.KeySpline>
                        <KeySpline ControlPoint1="1,0" ControlPoint2="1,1"/>
                    </SplinePointKeyFrame.KeySpline>
                </SplinePointKeyFrame>
            </PointAnimationUsingKeyFrames>
        </Storyboard>
    </UserControl.Resources>

Right now I have not taken much pain to re-tweak that animation, but yes it can be done as we want it to behave.

C# Code :

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Browser;

namespace SL_ExpandAd
{
    enum ExpandableState { Expanded, Collapsed }; 

    public partial class MainPage : UserControl
    {      
        private int AdState = (int)ExpandableState.Collapsed;

        public String adurl = null;

        public MainPage(StartupEventArgs e)
        {
            InitializeComponent();
            adurl = e.InitParams["TechEdIndia"].ToString();
        }

        private void LayoutRoot_MouseLeave(object sender, MouseEventArgs e)
        {          
            if (AdState == (int)ExpandableState.Expanded)
            {
                AdCollapse.Begin();
                AdState = (int)ExpandableState.Collapsed;
            }
        }      

        private void BannerImage_MouseMove(object sender, MouseEventArgs e)
        {
            if (AdState == (int)ExpandableState.Collapsed)
            {
                AdExpand.Begin();  
                AdState = (int)ExpandableState.Expanded;
            }
        }

        private void SwirledBackground_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (adurl != String.Empty)
            {
                HtmlPage.Window.Navigate(new Uri(adurl), "_blank");
                HtmlPage.Window.Alert(adurl);
            }
            else
            {
                HtmlPage.Window.Alert("Sorry, TechEd 2009 India Registration is closed !!");
            }
        }
    }
}

Now lets understand C# code, firstly enum ExpandableState { Expanded, Collapsed };  will maintain state whether it is collapsed or not and that is passed as initial values to another variable AdState like this :

private int AdState = (int)ExpandableState.Collapsed;

Then, public String adurl = null;  which is right now null, basically it will hold URL which are passing through “initParams” [Hope you all aware of usage of initParams and how to set it in HTML test page of Silverlight application.], Right now I have declared it like this :

<param name="initParams" value="TechEdIndia=http://www.microsoft.com/india/teched2009/" />

This basically holds like KV pair, you have “TechEdIndia” as key and url is value. we are then fetching that URL like this :

adurl = e.InitParams["TechEdIndia"].ToString();

Remember, I made some changes in Page constructor and in App.xaml.cs like :

private void Application_Startup(object sender, StartupEventArgs e)
       {
           this.RootVisual = new MainPage(e);
       }

I am passing “e” as argument and in MainPage.xaml.cs it is changes to :

public MainPage(StartupEventArgs e) { … }

Using statement

HtmlPage.Window.Navigate(new Uri(adurl), "_blank"); I am redirecting user to the url which we got from initParam and also throwing the same in alert box, as far as pulling that image down and stuff, will be taken care by animation. So final output will be like this :

exad2

Above is the first initial screen once I start my Ad, when I take mouse over that Halo image, by animation given above, it will pull another image like this :

exad1

You can see that “TechEd” image is now rolled down from top Halo image on mouse over.Now I have set URL of TechEd Portal using initParam in my HTML and I have already given explanation about it above, so after clicking on this image it will redirect me to TechEd portal and also will throw an alert like this :

exad3

You can see a small alert showing url below the instance of IE and in IE Instance you can clearly see the TechEd portal. Well thats all about Ads in Silverlight from me, soon I am ending this series with Effects and Deep linking, then I will start with other untalked scenarios. Hope you will find this useful.

Vikram.