Window Support

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Saturday, 28 February 2009

Calling RESTful Services using JSON format in Silverlight 2

Posted on 21:40 by Unknown

I have already blogged about integration of ASMX and WCF services with Silverlight 2 in my previous posts, Hope they are helpful to all of you. Now going one step ahead, I am now talking about REST and JSON, you find it alien?

Now the whole world knows that Silverlight don’t support anything beyond basicHttpBinding [ If you have any plans to integrate WF (Workflows), better create wrapper and try it out ]

REST is getting popular today firstly because of integration in various types of Applications, Do SOAP understood by every? how much pain in convert XML response to format which we want, performance, well too many questions arises,I am still not able to comment whether REST is best thing to follow or not, but whatever amount I use it, I find it handy and useful,so thought I should share with you all.

REST by default returns XML if we don’t mention return type format, There are two format as POX [Plain Old XML] form or JSON [JavaScript Object Notation]

If you still want in-depth information about REST, you can visit :

http://en.wikipedia.org/wiki/Representational_State_Transfer

You don’t have any separate template for creating RESTful Services for Silverlight 2 in Visual Studio, same for JSON.So I am going to do this with our normal WCF Template.

XAML Code :

<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="FirstName:"/>
        <TextBox Margin="40,-50,0,30" x:Name="txtFirstName" Height="20" Width="150" Text="{}" />

        <TextBlock Margin="78,-5,25,30">LastName :</TextBlock>
        <TextBox Margin="40,-60,0,10" x:Name="txtLastName" Height="20" Width="150" />

        <Button x:Name="btnSubmit" Height="20" Width="100" Content="Submit" Click="btnSubmit_Click" />
    </StackPanel>

    <TextBlock Width="220" Height="30"  Margin="80,0,100,20" VerticalAlignment="Bottom" x:Name="JsonResult" Foreground="#FF000000"/>
</Grid>

WCF Service Code :

public string ReturnUser(string str1, string str2)
{
     string strtemp;
     strtemp = "Your Complete Name is:" + string.Concat(str1, str2);
     return strtemp;
}

[ServiceContract]
public interface IJsonService
{
    [OperationContract]
    [WebGet(ResponseFormat=WebMessageFormat.Json)] 
    string ReturnUser(string str1, string str2);
}

Note : [WebGet(ResponseFormat=WebMessageFormat.Json)]

Here is the critical step to decide whether the response will be POX or JSON, if you specify nothing,by default it will be XML, if you define as JSON, response will be stream which you need to deserialize where you are managing response.

Web.Config : [You need to make binding as webHttpBinding]

<services>
            <service behaviorConfiguration="SL_JSON.Web.JsonServiceBehavior" name="SL_JSON.Web.JsonService">
                <endpoint address="" binding="webHttpBinding" contract="SL_JSON.Web.IJsonService">
                    <identity>
                        <dns value="localhost"/>
                    </identity>
                </endpoint>
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
            </service>
</services>

Another Important Step is to add Factory Attribute in your svc file markup like this :

<%@ ServiceHost Language="C#" Debug="true" Factory="System.ServiceModel.Activation.WebServiceHostFactory" Service="SL_JSON.Web.JsonService" CodeBehind="JsonService.svc.cs" %>

It will not work unless you add attribute Factory="System.ServiceModel.Activation.WebServiceHostFactory"

Page.xaml.cs :

private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
           WebClient wc = new WebClient();
           string uri = "http://localhost:1603/JsonService.svc/ReturnUser?str1=";
           uri += txtFirstName.Text + "&str2=";
           uri += txtLastName.Text;
           wc.OpenReadAsync( new Uri(uri,UriKind.Absolute));
           wc.OpenReadCompleted+=new OpenReadCompletedEventHandler(wc_OpenReadCompleted);
}

void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
           byte[] stream =new byte[200];
           e.Result.Read(stream,0,(int)e.Result.Length);

           string str = String.Empty;

           for (int i = 0; i < stream.Length; i++)
           {
               str += (char)stream[i];
           }

           JsonResult.Text = str;
}

JSON1

JSON2 

Since we set format as JSON, so it will return you the stream, you can read that stream using e.Result.Read(), then with normal logic of reading stream, we are fetching data from Stream and assigning it to TextBlock and Output will be like :

JSON

One thing you must have observe that I have not created any proxy to consume service and I am simply making use of WebClient given to us by System.Net.

I am also want to encourage you to read more on attributes like WebGet and WebInvoke.

I am sure you must have now got idea about REST, JSON etc. I have written this to get overview and surely I will cover in-depth about REST and JSON in coming days.As always, your feedback most welcome.

Read More
Posted in | No comments

Saturday, 21 February 2009

Silverlight 2 + Ink : Freedom of Drawing on Web !

Posted on 02:01 by Unknown

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"/>

</Grid>

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()
{
     InitializeComponent();
     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;
    inkP.CaptureMouse();
    s = new Stroke();
    s.StylusPoints.Add(e.StylusDevice.GetStylusPoints(inkP));
    switch (mycol)
      {
           case 0: s.DrawingAttributes.Color = Colors.Black;
           break;
           case 1: s.DrawingAttributes.Color = Colors.Blue;
           break;
           case 2: s.DrawingAttributes.Color = Colors.Red;
           break;
           case 3: s.DrawingAttributes.Color = Colors.Green;
           break;
     }          
     inkP.Strokes.Add(s);
}

void inkP_MouseMove(object sender, MouseEventArgs e)
{
    if (s != null)
   {
         inkP.Cursor = Cursors.Stylus;
         s.StylusPoints.Add(e.StylusDevice.GetStylusPoints(inkP));
    }
}

private void btnClear_Click(object sender, RoutedEventArgs e)
{
    inkP.Strokes.Clear();
    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 :

ink1

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 :

ink2

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 :

s.StylusPoints.AddStylusPoints(e.GetStylusPoints(inkP));

In Silverlight 2.0 RTW is now :

s.StylusPoints.Add(e.StylusDevice.GetStylusPoints(inkP));

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

inkP.Strokes.Clear();

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.

Vikram.

Read More
Posted in | No comments

Friday, 13 February 2009

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

Posted on 03:46 by Unknown

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.

Screen0

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

Screen05

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]

Screen1

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 :

Screen2

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 :

AutoGenerateEditButton="True" 
AutoGenerateDeleteButton="True"

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

<Columns>                    
     <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" /> 
</Columns>

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.

Screen3

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.

Vikram.

Read More
Posted in | No comments

Tuesday, 10 February 2009

Silverlight : CoreCLR and Revisiting Fundamentals

Posted on 02:32 by Unknown

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.

Read More
Posted in | No comments
Newer Posts Older Posts Home
Subscribe to: Comments (Atom)

Popular Posts

  • First Windows Phone 7 update February 2011 - Small update but Big start
    After tons of rumors and set of predictions on Windows Phone 7 all over Internet, Microsoft came up with first Windows Phone 7 minor update ...
  • The little Story of “I Unlock Joy” event by Microsoft and Pune User Group
      This post is about recent “I Unlock Joy” event happened in Pune which was conducted by Microsoft and Pune User Group. Little History : ...
  • Silverlight On Mobile : Windows Phone 7 Splash Screen and Customization
    After talking about 3D capabilities on Windows Phone 7 using Silverlight in last article , Now I am moving ahead with small but equally impo...
  • Silverlight 5 : Platform Invoke (PInvoke) in Silverlight
      Two days back Microsoft announced availability of Silverlight 5 RC,I encourage you to download bits from here , My friend Pete Brown alr...
  • Introduction to Speech Capabilities in Windows Phone 8 – Part 1
    After a long..I am writing blog, I hope and I wish I will resume blogging like I use to in past. Lots of things happened in past few months....
  • MCTS : Microsoft Silverlight 4 Development Exam Guide (70-506) by Packt Publishing
      Hello, After a long time I got chance to come back here.I will soon resume blogging in month of August. Last 4-5 months were horrible due...
  • Introduction to Speech Capabilities in Windows Phone 8 – Part 2
    Hope you enjoyed my last article on Speech Capability in Windows Phone 8, Today I am posting another part or you can say little extension t...
  • Silverlight 3 : Insert & Update Data using WCF Service with DataForm and DataGrid
    In my Lap around Silverlight 3 series, I have written a separate article on DataForm in Silverlight 3, This article is a basic extension to ...
  • Mango : Using DeviceStatus in Windows Phone 7.1
    First of all “Thank You” for your wonderful response and comments on my last article on Silverlight Vs HTML5 ,I hope you like the points I ...
  • Silverlight, HTML5 & Windows 8 : Where we are heading to ?
    This is not the post or yet another post on most happening debate of Silverlight and HTML5, This is just a visit to all of them to realize t...

Blog Archive

  • ►  2013 (4)
    • ►  August (1)
    • ►  April (3)
  • ►  2012 (4)
    • ►  July (1)
    • ►  March (2)
    • ►  January (1)
  • ►  2011 (24)
    • ►  December (1)
    • ►  September (4)
    • ►  August (2)
    • ►  July (1)
    • ►  June (4)
    • ►  May (3)
    • ►  April (3)
    • ►  March (1)
    • ►  February (4)
    • ►  January (1)
  • ►  2010 (21)
    • ►  December (1)
    • ►  November (2)
    • ►  October (3)
    • ►  September (2)
    • ►  August (4)
    • ►  July (5)
    • ►  May (1)
    • ►  April (1)
    • ►  March (1)
    • ►  January (1)
  • ▼  2009 (49)
    • ►  December (1)
    • ►  November (5)
    • ►  October (2)
    • ►  September (1)
    • ►  August (5)
    • ►  July (5)
    • ►  June (1)
    • ►  May (5)
    • ►  April (5)
    • ►  March (9)
    • ▼  February (4)
      • Calling RESTful Services using JSON format in Silv...
      • Silverlight 2 + Ink : Freedom of Drawing on Web !
      • Dynamic Data : Part 2 [ In-Place Editing and Grid ...
      • Silverlight : CoreCLR and Revisiting Fundamentals
    • ►  January (6)
  • ►  2008 (43)
    • ►  December (3)
    • ►  November (9)
    • ►  October (7)
    • ►  September (4)
    • ►  August (2)
    • ►  July (3)
    • ►  June (4)
    • ►  May (3)
    • ►  March (3)
    • ►  February (5)
Powered by Blogger.

About Me

Unknown
View my complete profile