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)”.

image

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.

image

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.

Vikram.

Saturday, January 31, 2009

Microsoft Certification - Discount Code for MCTS,MCITP & MCPD – Get 10% discount in just 3 Steps..Hurry up & Register Today !!

Grand News for all students,faculty members and IT professionals in India !!

I am sharing a unique code which is only and only available through Microsoft MVPs and this is only to help out and encourage people in community across India and no other specific intention.We all know, Microsoft Certifications are always a benchmark for anyone working in their respective technology, Also helpful in getting and testing our skills by each unique exams conducted by Microsoft.

So here is your Grand chance to pass Microsoft Certification Exams with 10% discount and free retake offer !!

Don’t worry,if you fail then you can give second attempt for free but before 31 March 2009 [ Both exams to be given before that date,applied to all]

Code is valid for following exams only :

  • Microsoft Certified Technical Specialist (MCTS)
  • Microsoft Certified IT Professional (MCITP)
  • Microsoft Certified Professional Developer (MCPD)

Discount Code : Get the Code

Now what you need to do with this code to get that 10% discount? Once you decided to take exam and avail this discount by code which I have given here, you just need to do following steps :

1. Visit http://www.learnandcertify.com/

2. Click on the Image which you will see on the portal given above

x

3. Enter promotion code [ The one in Red Color above ]

Code is : IN122192 and click Next to claim your exam voucher.

y

..And you done with it !!

So, what are you waiting for? go ahead and grab this unique opportunity and also share the same with your friends, relatives and co-workers in your organization !

Note : This unique opportunity is only for people giving exams in India.

Vikram.

Thursday, January 22, 2009

Lap Around Microsoft Web Platform Installer 1.0 aka Web PI

All Web Developers know that while doing design and development, we need lots of Tools and Technology, Also we need to assure and keep track of versions too. From Admin point of view, its pain to install all the new software and maintain versions on each and every machine.

To avoid this pain and to give lot of ease for installing new and updated tools, Microsoft now came ahead with its new unique tool as “Microsoft Web Platform Installer 1.0” , in short it is also known as “WebPI”.

WebPI is basically a UI where it displays you the latest tools available from Microsoft for Web Development, It is very simple so now even Developers and Designers can also go ahead and do installations without having any great knowledge of IIS tools and other add-ins. It basically includes Visual Web Developer 2008 Express Edition, SQL Server 2008 Express Edition and the .NET Framework along with IIS, and not to surprise, it also now listing the current updated tools like Silverlight Toolkit for Visual Studio and ASP.NET MVC. So now all you need is just to install this WebPI tool and your Computer will be ready for Web Development.

You can download WebPI from :

http://www.microsoft.com/downloads/details.aspx?FamilyID=3a41fac1-ed06-4944-a24d-76c8da31cf7d&DisplayLang=en

Once you install it and run, you will now see the following things :

loading

options

First it will check the latest tools and updates for Web Development and then it will load a window with three options as :

  • Complete
  • ASP.Net Developer
  • Your Choice

Complete will get you the full suit of software offered, like this :

Complete

ASP.Net Developer option will give you tools and updates related to ASP.NET development, like this :

aspnet

Your Choice option will choice to fully customize the download options like this :

YourChoice

Once you click on Install, it will also give you links to check Legal agreements and terms, like this :

AgreeOnTerms

TermsbyMS

Installing

Once you click on “I Accept”, it will start the installation and at the end of Installation it will show you the installation log also, like this :

log

I hope, This will be helpful for dedicated Web Developers and also to those admins who work really hard to keeping and getting these tools, Now with WebPI, there just few clicks away.

Vikram.

Tuesday, January 20, 2009

Silverlight 2 : Maintain data in Session using Silverlight-enabled WCF service.

A piece of paper was thrown in front of me on table by my friend in local coffee shop, that paper was nothing but print out of one already designed ASP.NET site which now he want to convert to Silverlight with few of pages as kind of POC for Silverlight. I just saw “Welcome : <Username>” label on that, and I asked him how he is taking care of Sessions in Silverlight? and a puzzle for him..since he never implemented, there are several solutions on net by many people and enthus, here is my piece of code which I feel simple, offcourse you can try that out and help me improve if there any better way to do so.

To show this particular functionality, I am re-using my old code of Master pages in Silverlight since I need more than one page with navigation which you can find it here :

http://pendsevikram.blogspot.com/2008/11/silverlight-2-master-pages.html

Also, if you are not comfortable with Silverlight-enabled WCF services , you can see my old article :

http://pendsevikram.blogspot.com/2008/10/silverlight-2-grid-with-silverlight.html

Step 1 : Create 2 Silverlight Pages

Page.xaml :

<Grid x:Name="LayoutRoot" Background="AliceBlue">
        <TextBlock Height="23" Margin="94,8,116,0" VerticalAlignment="Top" Text="Explore .NET with Vikram Pendse" TextWrapping="Wrap" Foreground="#FF000000"/>
        <StackPanel x:Name="stk" Width="400" Margin="0,66,0,30">
            <TextBlock Margin="78,10,0,30" Text="UserName:"/>
            <TextBox Margin="40,-50,0,30" x:Name="txtuser" Height="20" Width="150" />

<TextBlock Margin="78,-5,25,30">Password :</TextBlock>
            <PasswordBox Margin="40,-60,0,10" x:Name="txtpassword" Height="20" Width="150" />
            <Button x:Name="btnSubmit" Height="20" Width="100" Content="Login" Click="btnSubmit_Click" />
        </StackPanel>
        <TextBlock Height="23" Margin="106,0,104,3" VerticalAlignment="Bottom" Text="Microsoft .NET for everyone!!" TextWrapping="Wrap" Foreground="#FF000000"/>
</Grid>

Welcome.xaml :

<Grid x:Name="LayoutRoot" Background="AliceBlue">
        <StackPanel x:Name="mystk" Width="400" Margin="0,66,0,30">
            <TextBlock Margin="128,-5,0,30" Text="Welcome :"/>
            <TextBlock Margin="196,-46,0,30" x:Name="txtusername" />
        </StackPanel>     
</Grid>

Step 2 : Add a Silverlight-enabled WCF Service and access it in Silverlight application

MyService.svc.cs :

using System.Web;

[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class MyService
    {
        HttpContext myctxt = HttpContext.Current;

        [OperationContract]
        public string Login(string username, string password)
        {
            //Validate Username and Password against the Database.
            myctxt.Session["Uname"] = username;
            return username;
        }

        [OperationContract]
        public string ReturnUser()
        {
            string user;
            user = (string)myctxt.Session["Uname"];
            return user;
        }

Note : For demo purpose, I have not validated User-id and Password against database, please refer comment.

Step 3 : Consume SL-enabled WCF service in each page and pass the corresponding parameters.

First we need to send username and password from Page.xaml.cs to Service, Then Login() will maintain that particular username in session, Then we will again call the service and access that particular username which is in session by ReturnUser()

Page.xaml.cs :

private void NavigateRequest(int w)
{
     if (w > 0)
     {
         stk.Children.Clear(); 
         stk.Children.Add(new Welcome());
      }
      else
      {
          this.Content = new Page();
      }            
}

private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
    Srvc.MyServiceClient proxy = new SL_SessionMgmt.Srvc.MyServiceClient();
    proxy.LoginAsync(txtuser.Text,txtpassword.Password);
    NavigateRequest(1);
}                

Here we are switching among the pages by NavigateRequest(), you can write Switch-case if there are multiple pages.

Welcome.xaml.cs :

public Welcome()
{
    InitializeComponent();
    this.Loaded += new RoutedEventHandler(Welcome_Loaded);
}

void Welcome_Loaded(object sender, RoutedEventArgs e)
{
     Srvc.MyServiceClient proxy = new SL_SessionMgmt.Srvc.MyServiceClient();
     proxy.ReturnUserCompleted += new EventHandler<SL_SessionMgmt.Srvc.ReturnUserCompletedEventArgs>(proxy_ReturnUserCompleted);
     proxy.ReturnUserAsync();
}

void proxy_ReturnUserCompleted(object sender, SL_SessionMgmt.Srvc.ReturnUserCompletedEventArgs e)
{
      txtusername.Text = e.Result;
}

And here we are getting username which is in session by e.Result, This will display the username in session on Textblock on second page, it will look like this.

SLSession1

Here you can see whatever we pass as username, we place it in session by WCF service and get that data from session via service again and bind it to another control on another page.

SLSession2

Hope this will useful for you, if you are planning to implement Sessions in your Silverlight applications.

Vikram. 

Monday, January 12, 2009

Microsoft Tag : New way to go Online !!

“Barcode” is something which we come across day to day especially while we do shopping, “RFID” is bit more advance, where you can really track down items within some specific range and process information.

Imagine..A simple small fuzzy and colorful picture full of small triangle of different colors, If I say you just take picture of that on your Windows Mobile phone and once you do that, it will take you here..to my blog..!! Sounds funny..but its not ! This is what Microsoft Tag all about.

As per the information given by Microsoft, Tag works with the fixed-focus camera lenses common in most mobile devices.So you just aim your camera phone at a Tag and instantly access mobile content, videos, music, contact information, maps, social networks, promotions, and more.Nothing to type, no browsers to launch.

login

Above screen you will get once you visit http://tag.microsoft.com and you can learn more about Tag Technology on http://www.microsoft.com/tag , You will need to sign up there or you can login using Live ID, It is free to log into Tag site.

Once you login, you will find console like I have shown in following screen, you will find a Create Tag Button on Top side of grid, by which you will be thrown to Tag Creation page. On this page you will be able to do all managerial tasks like Edit,Delete,Export and do reporting about the usage of the same.

TagExplorer

Once you click on “Create Tag” button,it will allow you to create different types of Tags, something here to make note that, It will ask you to give details according to the “Tag Type” you set.

ManageTags

Once you create Tag successfully and come back to Main window with Grid, you will find a Export option for the Tag you created, it will basically ask you for type and the way to display it, it export it into either pdf,wmf or xps format.

RenderTag

Below is the sample Export in PDF which I took out from the pdf generated by Tag export option.

FinalCaptcha

I hope you will find this new innovation bit of technology interesting and sooner or later you will start using it too. Below is my Tag for my browser, just click snap of it and come here.

MyBlogInfo

Vikram.

Sunday, January 4, 2009

Lap around Report Builder 2.0

Report Builder 2.0 is basically used for Designing the Reports which we incorporate in applications using SSRS [SQL Server Reporting Services], You do have one separate template to design and develop Reports using a commonly known tool “SQL Server Business Intelligence Development Studio”. Report Builder 2.0 is independent tool for designing the reports which you can download from :

http://www.microsoft.com/downloads/details.aspx?familyid=9f783224-9871-4eea-b1d5-f3140a253db6&displaylang=en

After installation, you can Run Report Builder 2.0 from Start-> All Programs –> Microsoft SQL Server 2008 Report Builder 2.0

RB1

You will then get following Console :

RB2

If you observe carefully, Top menu is now got replaced by “Ribbon” [ Refer Top Menu in any MS Office 2007 Application ] which adds ease for finding functionality smoothly and fast since they are categorized.

Left side panel usually contains your Built-in Fields which are provided by default by Report Viewer 2.0, that contains fields like Page numbers, DateTime, Report URL and name and much more.

Middle panel is layout window where you actually place the things like table/matrix/graphs/gauges etc and design report.

Right side panel usually contains properties of respective elements which we have on layout.

RB4

If you see the above picture carefully, You will find that now SSRS Report Builder 2.0 enables you to put on Graphs and Gauges on your Report [ Hope you aware of .NET Dundas Control, Now they are here ] , I personally have not seen such wonderful facility of graphs and gauges in crystal reports, even such rich GUI to design reports is not given for the same in Crystal Reports,well I think its totally user choice what to go for.

RB8

RB7

Inside View Menu you can set and reset Ruler for layout and other windows like Properties and Grouping.

Also do observe on bottom side, same like in MS Office applications, you can now Zoom your layout to a great extend with the zoom scroll given at the bottom side, Also similar to run slides option in PowerPoint at bottom side, now you have Run report option at bottom. This is basically quick way to run reports.

Once you design and develop report, you need to upload the corresponding report files to Report Server Directory on Report Server. For those who are new one, here I am showing you how that window looks like where you can configure your Reporting Server settings. You will find that at Start-> All Programs-> Microsoft SQL Server 2008->Configuration Tools-> Reporting Services Configuration

RB9

I hope this will give you overall idea about what is new in Report Builder 2.0, I am not stopping here with this post, I will soon share with you all , how we can actually design report, That I am planning to do with real case base scenario soon which will talk about parameterized reports and graphs also with some Report UI tips and tricks etc.

Vikram.

Silverlight 2 : Using Magnifier to Zoom contents on Canvas

First of all wish all my blog readers very Happy New Year ! , Thanks for your continuous feedback and support all the time. Some people given me feedback in 2008 that I wrote some article too basic and not to the level which they expect, frankly speaking , I wrote here what comes to my mind, what I see and what I feel difficult to understand to others, so I always try my best to keep things simple and quick.But I will do follow your feedback so be with me in year 2009 since lots new on this blog going to be there in coming few months !

There are several post on usage of Magnifier in Silverlight 1.1 as well as in 2.0, Some have done with Images and some with Videos. I am re-making this code snippet which is already published by Jeff Prosise’s blog and code snippet which I am going to share here is already available on one of the PDC 2008 snippet at : http://www.wintellect.com/Downloads/PDC_2008_Demos.zip

Idea of doing this again re-work and twick the already written source code is to create awareness about the Magnifier which can be use efficiently for zooming part of image or video.

Step 1 : Create a Layout which will hold 3 Canvas.

<Grid x:Name="LayoutRoot" Background="Black" MouseLeftButtonDown="OnMouseLeftButtonDown" MouseMove="OnMouseMove" MouseLeftButtonUp="OnMouseLeftButtonUp">

Note that, for Zooming particular portion of Canvas, we are suppose to handle mouse events on all over base canvas which you can see from above events.

<Canvas x:Name="CoreCanvas" Width="800" Height="530">
            <!-- Base canvas -->
            <Canvas x:Name="BaseCanvas" Canvas.Left="0" Canvas.Top="0" Width="800" Height="400" Background="Black">
                <Canvas Canvas.Left="90" Canvas.Top="30" Width="620" Height="470">
                    <Rectangle Canvas.Left="0" Canvas.Top="0" Width="620" Height="470" Fill="White" />
                    <MediaElement Canvas.Left="10" Canvas.Top="10" Width="600" Height="450" Source="Bear.wmv" />
                </Canvas>
            </Canvas>

Above is the Canvas which will hold Video / Image file on which we will put magnifier for zooming.

<!-- Magnify canvas -->
<Canvas x:Name="MagnifyCanvas" Canvas.Left="0" Canvas.Top="0" Width="800" Height="400" Background="Black" Visibility="Collapsed">
                <Canvas.RenderTransform>
                    <ScaleTransform CenterX="0" CenterY="0" ScaleX="4" ScaleY="4"/>
                </Canvas.RenderTransform>
                <Canvas.Clip>
                    <EllipseGeometry x:Name="Lens" Center="0,0" RadiusX="40" RadiusY="40" />
                </Canvas.Clip>
                <Canvas Canvas.Left="90" Canvas.Top="30" Width="620" Height="470">
                    <Rectangle Canvas.Left="0" Canvas.Top="0" Width="620" Height="470" Fill="White" />
                    <MediaElement Canvas.Left="10" Canvas.Top="10" Width="600" Height="450" Source="Bear.wmv" />
                </Canvas>
                <Path Canvas.Left="0" Canvas.Top="0" StrokeThickness="0">
                    <Path.Data>
                         <EllipseGeometry x:Name="LensBorder" Center="0,0" RadiusX="40" RadiusY="40" />
                    </Path.Data>
                </Path>
            </Canvas>
        </Canvas>
      </Grid>

Above code will add another Canvas with Ellipse which is our circular magnifier for zooming, you can try out with RectangleGeometry.

Step 2 : Create a general method as AdjustLens() for maitaining the Magnifier value and position.

Variables declare for drag and scale which keep tracks whether drag by mouse for Magnification or not.

private bool drag = false;
private const double scale = 4.0;

private void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
            double x = e.GetPosition(CoreCanvas).X;
            double y = e.GetPosition(CoreCanvas).Y;
            AdjustLens(x, y);

            MagnifyCanvas.Visibility = Visibility.Visible;
            ((FrameworkElement)sender).CaptureMouse();
            drag = true;
}

OnMouseLeftButtonDown basically pass the position of CoreCanvas to AdjustLens() which keep tracks of all the movements on Canvas.Same for rest of the events.

        private void OnMouseMove(object sender, MouseEventArgs e)
        {
            if (drag)
            {
                double x = e.GetPosition(BaseCanvas).X;
                double y = e.GetPosition(BaseCanvas).Y;
                AdjustLens(x, y);
            }
        }

        private void OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (drag)
            {
                MagnifyCanvas.Visibility = Visibility.Collapsed;
                ((FrameworkElement)sender).ReleaseMouseCapture();
                drag = false;
            }
        }

AdjustLens() helps to position Magnifier as per mouse movements and position of Canvas.

private void AdjustLens(double x, double y)
        {
            Lens.Center = LensBorder.Center = new Point(x, y);
            MagnifyCanvas.SetValue(Canvas.LeftProperty, (1 - scale) * x);
            MagnifyCanvas.SetValue(Canvas.TopProperty, (1 - scale) * y);
        }
  So build the project, you will get output as follows.

mag1

After applying Magnifier by dragging mouse, it will look like..

mag3

If you notice, you can see a Big Ellipse on right corner of the screen which shows a Bird is zoomed up, you can implement Magnifier while Video is in Run mode and it will not disturb the execution of video neither it will break any frame, It will run as smooth as it runs normally.

Hope this post will give you idea about implementation of Magnifier in Silverlight application and inspire you to implement it like I inspired and remake it from Jeff’s blog.

Vikram.