Saturday, February 21, 2009

Silverlight 2 + Ink : Freedom of Drawing on Web !

Almost 8-9 months ago, I wrote article on Ink Presenter in Silverlight, After that I got many mails after many people tried out to recreate same demo in Silverlight 2, unfortunately it was broken since I wrote that for Silverlight 1.1. We all know how we spend first few weeks after release of Silverlight 2 RTW by spending and fixing our old applications and reading that “Breaking Changes” document all the time. Well, for this Ink Presenter, whatever I explained in my old article remains same, so I am just now re-writing it in Silverlight 2 with 1-2 new things to make you all comfortable in developing Ink based Silverlight applications.

Unfortunately, despite of spending lot of time and referring with few WPF dll files, still I am not able to recognize the Ink which is very simple to implement in WPF due to presence of InkAnalyzer( )

Remember..all you need is System.Windows.Ink

Basic Layout in XAML :

[ I kept UserControl’s Width="500" Height="350" ]

<Grid x:Name="LayoutRoot" Background="White">        

<InkPresenter Width="500" x:Name="inkP" Background="Pink"  />

<Button Height="37" HorizontalAlignment="Left" VerticalAlignment="Bottom" Width="70" Margin="23,0,0,32" x:Name="btnClear" Content="Clear" Click="btnClear_Click"/>
<Button Height="37" HorizontalAlignment="Left" VerticalAlignment="Bottom" Width="73" Content="Blue" Margin="130,0,0,32" x:Name="btnBlue" Click="btnBlue_Click"/>
<Button HorizontalAlignment="Right" VerticalAlignment="Bottom" Content="Red" Margin="0,0,159,32" Height="37" Width="74" x:Name="btnRed" Click="btnRed_Click"/>
<Button Height="37" HorizontalAlignment="Right" VerticalAlignment="Bottom" Width="75" Content="Green" Margin="0,0,26,32" x:Name="btnGreen" Click="btnGreen_Click"/>


C# Code :

using System.Windows;
using System.Windows.Controls;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;

namespace SL_InkPresenter
public partial class Page : UserControl
     Stroke s;
     int mycol = 0;

public Page()
     inkP.MouseMove += new MouseEventHandler(inkP_MouseMove);
     inkP.MouseLeftButtonDown += new MouseButtonEventHandler(inkP_MouseLeftButtonDown);
     inkP.MouseLeftButtonUp += new MouseButtonEventHandler(inkP_MouseLeftButtonUp);

void inkP_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    s = null;

void inkP_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    inkP.Cursor = Cursors.Stylus;
    s = new Stroke();
    switch (mycol)
           case 0: s.DrawingAttributes.Color = Colors.Black;
           case 1: s.DrawingAttributes.Color = Colors.Blue;
           case 2: s.DrawingAttributes.Color = Colors.Red;
           case 3: s.DrawingAttributes.Color = Colors.Green;

void inkP_MouseMove(object sender, MouseEventArgs e)
    if (s != null)
         inkP.Cursor = Cursors.Stylus;

private void btnClear_Click(object sender, RoutedEventArgs e)
    mycol = 0;

private void btnBlue_Click(object sender, RoutedEventArgs e)
       mycol = 1;

private void btnRed_Click(object sender, RoutedEventArgs e)
      mycol = 2;

private void btnGreen_Click(object sender, RoutedEventArgs e)
     mycol = 3;

Note : I have use that “Switch..Case” for demo purpose, doesn’t mean you should write those many cases for each color, you can implement your own login which will give you best result. I have restricted myself here with only 2-3 colors, so I am making use of Switch.

And output will be like this :


For adding more Jazz to it, you can implement Outer color of brush and can have some height and width to your stroke so as to get different widths of brush which will give different strokes, like we have in calligraphy.

For Outer Color to your Stroke :

s.DrawingAttributes.OutlineColor = Colors.Cyan;

For Different Width and Height of Stroke :

s.DrawingAttributes.Width = 10;
s.DrawingAttributes.Height = 5;

For Various Cursors :

inkP.Cursor = Cursors.Eraser;

Here we obtain Cursors from "System.Windows.Input.Cursors" which will give you various Cursors to display. If you implement above, output may look like following :


Hope this will now work for you in Silverlight 2, instead of wasting time in fixing old code which I have done using Silverlight 1.1, Soon I will put more stuff which I have explore recently about Ink.

At ending note, the major breakup was :

In Silverlight 1.1 it was :


In Silverlight 2.0 RTW is now :


One more thing, For clearing the drawing I have use :


Practically speaking, there are two ways to clear drawing, The one I shown here clears all the ink, other approach is to Erase Ink point by point like we have eraser in our normal MS paint. I am going to cover remaining approach and with many more new things in my future article.

As usual, looking ahead for your suggestions and valuable feedback.


Friday, February 13, 2009

Dynamic Data : Part 2 [ In-Place Editing and Grid Customization ]

I have already written about Dynamic Data with ASP.NET 3.5 , that was primarily with LINQ to SQL few months back, Since onwards there are few discussion going around whether LINQ to SQL is scrapped or outdated, well nothing official it seems.

Well in this Part 2, I am here discussing few small things which I skipped in my last article, well this time I am using bit different template as “Dynamic Data Entities Web Site” [ Hope you have necessary .NET 3.5 Service packs and stuff to get these Dynamic Data Templates ]. I am using Entity Data Model here.Starting screen will give you idea and help you to proceed, rest of the steps remains as it is which I have already covered in my last article.


Now we need to Add “ADO.NET Entity Data Model”, since we are now concentrating on Entity Data Model instead of LINQ to SQL.


Now you need to add following line to your Global.asax :             [Note : I am using AdventureWorks Database]

model.RegisterContext(GetType(AdventureWorksModel.AdventureWorksEntities), New ContextConfiguration() With {.ScaffoldAllTables = True})

Then just run your application and you will get output like : [ I did lot of customization in design, you can also go ahead and make changes in Style.css]


In-place editing using Dynamic Data Template :

Usually when we use Dynamic Data Template, and once we start doing CRUD Operations, it usually redirects us to various pages like Insert,Edit etc. So to avoid that navigation and to make those CRUD operations quickly, we just need to uncomment following lines in Global.asax and we will get In-place editing, just uncomment following :

routes.Add(New DynamicDataRoute("{table}/ListDetails.aspx") With { _
           .Action = PageAction.List, _
           .ViewName = "ListDetails", _
           .Model = model})

       routes.Add(New DynamicDataRoute("{table}/ListDetails.aspx") With { _
           .Action = PageAction.Details, _
           .ViewName = "ListDetails", _
           .Model = model})

Basically, above lines supports combined-page mode and routes to corresponding Insert,Edit page etc. These lines are nothing but the routing definitions which decide way to route and perform operation making use same page.Output will look like this :


You can see marking in Red Select,Edit,Delete and New options on same page, Grid on Top and Edit,Delete,New template below that, You just need to click on “Select” to do Edit,Delete and Insert operation.

Customization of Grid :

By default, GridView in Dynamic Data Template will show all the columns available in table, to customize this experience, first you need to go to “ListDetails.aspx” under Page Templates, then you need to locate <asp:GridView> tag and  you need to remove following things :


You need to make AutoGenerateColumns="False" and then need to add columns which you want accordingly in <Columns> template like this :

     <asp:DynamicField DataField="EmployeeID" HeaderText="EmployeeID" />
     <asp:DynamicField DataField="ContactID" HeaderText="ContactID" />
     <asp:DynamicField DataField="Title" HeaderText="Title" />
     <asp:DynamicField DataField="BirthDate" HeaderText="BirthDate" />                  
     <asp:DynamicField DataField="MaritalStatus" HeaderText="MaritalStatus" />
     <asp:DynamicField DataField="Gender" HeaderText="Gender" />
     <asp:DynamicField DataField="HireDate" HeaderText="HireDate" />
     <asp:DynamicField DataField="SalariedFlag" HeaderText="SalariedFlag" /> 

You can see the output in following screen, we can clearly see that we made those Edit and Delete buttons invisible and also we removed unwanted columns, now only the specific columns which we declared in <Columns> template are there.


This is how you can customize columns in GridView, its very straight forward though, especially those who have good exposure on ASP.NET Grid programming.

Hope this will help you to customize your Dynamic Data experience upto certain level, well in upcoming parts, I will show you more way to enhance the same.


Tuesday, February 10, 2009

Silverlight : CoreCLR and Revisiting Fundamentals

Silverlight is now in discussion everywhere since 3D support, Improvements in Controls and its availability on Mobile Devices announced informally by Bloggers across the world as everyone is awaiting for Silverlight 3. I still do find in community around me,many people just pulling out code from blogs/sites/forums without really bothering what’s happening under the hood. I already in my previous article, tried out my best to wipe out misconceptions about Silverlight, Now I am going few step ahead and discussing few Architectural things which I came across in last few days while working on Silverlight. My piece of research you can say.

Silverlight In Short…

Silverlight is technology introduced by Microsoft primarily with extensive usage of JavaScript to design and develop Rich Internet Applications which is also Cross Browser and Cross Platform, further after certain period of time, Microsoft introduce Silverlight programming with Managed environment with coding languages like C# and then they went one more step ahead and made capable people to program Silverlight with IronRuby with making use of DLR [ Dynamic Language Runtime].

Something worth to know about CoreCLR…

Microsoft done enormous efforts to design Silverlight Architecture, I can say best ever I have seen. Real challenge was to keep CLR size minimum which is required to execute Silverlight Applications. Imagine what if Silverlight was dependent on Desktop CLR?, was not a good solution, so Microsoft introduced a compact or subset of Desktop CLR which we call now as “CoreCLR”, which plays a vital role in overall Silverlight application execution and can be download easily even on small bandwidth.

How it differs CoreCLR and Desktop CLR ?

Sometime its like puzzle, we have template of Silverlight in Visual Studio, we use C#, then why there is nothing called like scsc.exe etc., Well Visual Studio while compiling Silverlight application uses the same C# compiler which is getting use to develop full fledge C# based application, If you observe carefully on .NET command prompt by typing csc/? , you will find an attribute as “/nostdlib[+|-]”,yes, Visual Studio make use of same argument “nostdlib” to instruct Compiler to not to use the libraries of Desktop CLR and to refer Core CLR, like it is written in the description of nostdlib attribute “Do not reference standard library (mscorlib.dll)”.


This is how CoreCLR comes into picture, so we can say that if someone want to develop or Run Silverlight application, then he/she can move ahead without having Desktop CLR, If someone have Desktop CLR, in that case both CLRs will be parallel to each other.

What’s inside CoreCLR ?

I said in above para that, it is subset of Desktop CLR, that doesn’t mean CoreCLR will give each and every features of main CLR, Those Libraries are re-written for Silverlight so as to make CoreCLR size as compact as possible, so you may not find namespaces like System.Data or some generic collections like ArrayList etc., So to overcome these and give developers all facilities so that he/she can relate with ASP.NET and use full features for Data driven and other applications, Service model was put ahead to address these kind of issues, so now like ASP.NET, you can maintain session,implement caching, Bind controls with data and do all CRUD operations with Grid using Web Services, You can do this with ASMX services,WCF or Silverlight enabled WCF services.


Coming back to fundamental again, like main CLR, in CoreCLR you have JIT, BCL and CLR Execution Engine, Yes you have all those basic dlls which you need to program Silverlight are now available including mscorlib.dll at location :

C:\Program Files\Microsoft Silverlight\2.0.31005.0

A question may arise, how I get this CoreCLR on my machine, you remember when you don’t have Silverlight then you download a small plugin, Well..this is it, Runtime for Silverlight.

Web Browser makes it happen…

We all feel that our IE/Mozilla or any other, just render the pages and their duty is over, Well for Silverlight, Browsers have vital role to play.Once you request ASP.NET or HTML page which hosts Silverlight, Browser makes a GET request for initial XAP and Silverlight Runtime Control downloads it. ( I recommending you to read more on “WebClient”, will make sense). Browser hosts Silverlight using our traditional mechanism of ActiveX. What is then exact role of agcore,coreclr,npctrl.dll files?

What is the role of npctrl.dll ?

When Browser host Silverlight using ActiveX mechanism. npctrl.dll which is nothing but Browser Plug-in co-ordinates with agcore.dll file [ Hope you all remember agcore.dll is with us from first version of Silverlight, when there was no concept of CoreCLR ], agcore.dll then coreclr.dll [ CoreCLR just for your awareness, is combination of Managed Code + Unmanaged Code ], so now CoreCLR does all management work for Silverlight application like memory management and other resources usage, since the native code of CoreCLR is capable of talking directly with Operating System, This is how due to its existence in Browser process, CoreCLR and Desktop CLR can go parallel to each other.

What if Browser process goes down??

By closing Browser process or getting it shutdown accidently will release all resources hold by CoreCLR, In overall process, one thing may come to your mind, what happens to XAML then?, Like we all know for WPF, XAML is converted into appropriate BAML for better understanding by Browser. 

Something more to talk…

Silverlight defined as Cross browser and Cross platform, above few lines says CoreCLR is combination of Managed and Unmanaged Code, so how then it works on Linux and Mac platforms?, Well as far as Linux environment is concern, you have some fundamental framework as Project Mono with Silverlight’s implementation as Moonlight. For Mac, you have a component in CoreCLR known as PAL [Platform Adaptation Layer] which is responsible to communicate between Mac and Silverlight.

What is possible in Silverlight?

Like ASP.NET, Database Connectivity and Operations, Session Management, Caching, Socket Programming, Streaming of Media and Images,Usage of Generics up to some level, ADO.NET/Entity Framework incorporation etc. now possible with usage of Web Services.

Few unanswered questions…

Is Silverlight Secure? especially if someone dissects the XAP to ZIP and reuse some unique logic? Is Code obfuscation with tools will really make it secure?,since XAP exposes some resources and even Service configuration files. Will Silverlight run on Mobile Devices with same CoreCLR? or the CoreCLR for mobile devices will be subset of Compact Framework?..Interesting to know in coming future..

On ending note..

My this article is motivation given to me by one MSDN Magazine article, Hope my this little effort will help you to have better in-depth vision on Silverlight & CoreCLR. Intention of re-writing all the stuff again and derive it from various sources available on net is to make all people comfortable on Silverlight and not to just blindly compare it with Flash.

All information I am sharing here is part of my research and references taken from MSDN Magzine article, might not be accurate in some area but I did tried out my best to make it exact and to the point and specific with the topic.Let me know your feedback and suggestions on this.