Wednesday, December 10, 2008

Visual studio Code snippet for Silverlight Dependency Property

For those who don't know what is VS code snippet.

Code snippet is one type of macro which insert a block of code upon activation.ie if we have to use a block of code frequently we could make that as a snippet and insert whenever we want.Here you will get details about the snippets very well.
Dependency property was introducd in WPF which is very useful in so many situations.But it's syntax is little bit big so that we can't remember always.So I usually prefer snippet for creating DPs in WPF.It's very easy
Right click->Insert Snippet->NetFX30->Define a Dependency Property
or
Type 'propdp' ->Tab

After getting the snippet we can change it's parameters according to our requirement.
DP Snippet in Silverlight
It was working well until I used the same in Silverlight.The default dp snippet in VS inserts a DP which uses metadata object of type UIPropertyMetadata.But this class is not available in Silverlight.Compile time error!!!!!
So I modified the dp snippet code to make it compatible with Silverlight.Using this you can insert DPs in silverlight without compilation error.
Steps
  1. Download the snippet file from here.
  2. Open Visual studio
  3. Tools->Code snippet manager
  4. Select language 'C#'
  5. Click 'Import'
  6. Locate the downloaded .snippet file.
  7. Select the folder for storing snippt.
  8. Click Finish.
  9. You can see the snippet in the code snippet manager.
  10. Now in Silverlight project you can use this snippet.

Happy coding!!!

If you are interested in testing more snippets get more from http://gotcodesnippets.com/

Tuesday, December 2, 2008

Deep earth - The open source Silverlight counter part of Google maps

Its a open source silverlight based interactive map like Google maps and wikimapia

Try out here http://deepearth.soulsolutions.com.au/
Source code can be downloaded @ http://www.codeplex.com/deepearth/

Monday, September 1, 2008

Desklighter - The Silverlight to exe converter

Lastweek Identitymine released its new product called Desklighter.It's a tool to convert silverlight application / site to a standalone windows exe application.ie A silverlight to exe converter.One can use this it they are in a situation which demands a standalone silverlight application.


Application areas
  1. Presentations :
    Since Silverlight is a rich presentation technology one can easily create presentations and publish in their sites.But currently that cannot be viewed without an internet connection.But Desklighter allows you to store Silverlight presentations in your hard disk and view it without internet connection.Very much useful in marketing,education..
  2. Games :
    Silverlight games can be played offline.(Unless they are networked to store scores or multiuser)
  3. Offline Silverlight browsing :
    Developers can create entire sites using Silverlight and if they handle the online and offline conditions it can be converted using Desklighter to use it as standalone application.The network operations ie data loading and saving should be programmed to be done whenever the net connection is available.
Currently desklighter is in identitymine blendables labs as a free download.More technical details can be found here.The future releases may extend support on Linux and Mac desktop machines where the current version supports only windows desktop.

Tuesday, August 5, 2008

A Silverlight 2 Beta 2 Bug related to Uri type

Again I struck in a framework bug which doesn't allow us to declare and use a dependency property of Type Uri.ie If you declare a dependency property of type Uri and try to set from xaml , will throw an error at runtime.Here is scenario.

You are creating a custom control and you need to have a dependency of type Uri Named Source.

You declared as follows.

public Uri Source
{
get { return (Uri)GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
public static readonly DependencyProperty SourceProperty =
DependencyProperty.Register("Source", typeof(Uri), typeof(MediaItem), new PropertyMetadata(OnSourceChanged));

static void OnSourceChanged(object sender, DependencyPropertyChangedEventArgs args) { }

Fine.But If you create its instance in xaml as follows and run the application it will throw an error.

<ctrl:MediaItem x:Name="item" Source="dock.jpg" />

The error is AG_E_PARSER_BAD_PROPERTY_VALUE.
Microsoft has identified this error and rectified.Details here
Until the next version change the property type into string and use converters in xaml.

Or in the setter of a dummy property convert the value into Uri and keep in actual property.

Monday, July 28, 2008

MouseWheel support in Silverlight 2.0 without Javascript code

Yes. Its possible eventhough we are using 'onmousewheel' event of Javascript object Document.

The process is simple.Just Subscribe to the onmousewheel event of document and process according to that.

Here I am going to zoom an image with the help of mouse wheel.

Initially there is an Image in the Page.xaml with a ScaleTransform named 'scale'.
<Grid>
<Image x:Name="img" Source="Hand.jpg" Stretch="None" VerticalAlignment="Top" HorizontalAlignment="Left">
<Image.RenderTransform>
<ScaleTransform x:Name="scale" ScaleX="1" ScaleY="1" />
</Image.RenderTransform>
</Image>
</Grid>

Step1:Subscribe to the onmousewheel event

public Page() {
InitializeComponent();
HtmlPage.Document.AttachEvent("onmousewheel", new EventHandler<HtmlEventArgs>(ondown));
}

Step 2 : Handle the ScaleTransform according to the direction

void ondown(object send,HtmlEventArgs arg)
{
object c= arg.EventObject.GetProperty("wheelDelta");
if (c != null)
{
int delta = int.Parse(c.ToString());
if (delta > 0)
{
scale.ScaleX = scale.ScaleX + .1;
scale.ScaleY = scale.ScaleY + .1;
}
else if(scale.ScaleX >.1)
{
scale.ScaleX = scale.ScaleX - .1;
scale.ScaleY = scale.ScaleY - .1;
}
}
}

Happy coding... :-)


Thursday, June 5, 2008

Crossfader Demo at TechEd

Its my proud to announce that my last project Crossfader which is developed fully in Silverlight 2.0 has been showed at Tech-Ed North america 2008 for developers.
The demo was did by S. Somasegar Senior Vice President, Developer Division from Microsoft.

Here are some links to view the demo
http://www.microsoft.com/techedonline/default.aspx
http://msstudios.vo.llnwd.net/o21/presspass/zune/Silverlight_2_Zune.wmv

Crossfader.com is a site for musicians to explore their works which is developed entirely using silverlight.They can share,collaborate and stage their valuable works.

It was great opportunity for me to start with Silverlight 2.0 with WPF Experience in hand.Learned so many technologies such as WCF,JSON LINQ Etc.

Thanks to Identitymine my company for giving such an opportunity.Another one I would like to express my thanks is David J Kelly ,the architect of the project for his valuable support.He was busy writing his first book but he helped us a lot.And to my team Haridas,Vijay,Roby ,Paul Thomas and Sam for their seamless support.
Hope the crossfader would be live soon in the light of Silver.

Monday, May 12, 2008

Inter silverlight communication design

Here is the solution which I promised to give in one of my older posts titled Javascripting silverlight.I delayed because this post needs some prerequisites which I discussed in the below posts.


Inter silverlight communication or cross Silverlight plugin communication means just interaction between 2 or more plugins hosted in same web page.To achieve this we have to write a javascript layer which controls the flow of communication.

It means each plug in will talk to javascript layer if they want to communication to other plug in.The javascript layer is responsible for the routing of these communications.

For 2 way communication we need to make the Page class as Scriptable.The Page class should have methods decorated with ScriptableMember which talk to javascript.

Sample

Lets take the case of Sliders.Our Silverlight page have a slider and there are 2 instances of Plug in the same web page.Our aim is to sync Sliders in these plugins.

Silverlight side

On slider's ValueChanged event handler we tells Javascript to adjust the slider in plugins.The reverse ie setting slider value on valuechange of other plug in is done in some other method which is marked as ScriptableMember.

[ScriptableType]

public partial class Page : UserControl

{

public Page()

{

InitializeComponent();

HtmlPage.RegisterScriptableObject("mainpage", this);

}

private void sldr_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)

{

HtmlPage.Window.Invoke("ValueChanged", sldr.Value);

}

[ScriptableMember]

public void SetValue(double d)

{

sldr.Value = d;

}

}
Javascript side

Here we will accept the value provided by plugin and pass the same to all the plugins by getting their references

<head runat="server">

<title>Test Page For SilverlightApplication1</title>

<script language="javascript">

function ValueChanged(value)

{

var Host1 = document.getElementById("Xaml1");

var Host2 = document.getElementById("Xaml2");

Host1.content.mainpage.SetValue(value);

Host2.content.mainpage.SetValue(value);

}

function clicked()

{

var name=document.getElementById("txt");

var val=parseFloat(name.value);

if(val!=null){

ValueChanged(val);

}

}

</script>

</head>

<body style="height:300;margin:0;">

<form id="form1" runat="server" style="height:300;">

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

<div style="height:300;">

<asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/SilverlightApplication1.xap" Version="2.0" Width="300" Height="300" />

</div>

<br /> <hr />

<marquee> <a href="#">HTML area</a></marquee>

<hr />

<input type="text" id="txt" value="50" />

<button onclick="clicked()">Change value</button>

<div style="height:300;">

<asp:Silverlight ID="Xaml2" runat="server" Source="~/ClientBin/SilverlightApplication1.xap" Version="2.0" Width="300" Height="300" />

</div>

</form>

</body>

Sample available here


Saturday, May 10, 2008

What is ScriptObject?

Simply,this is the managed code representation of complex javascript objects.

Confused?? Here is one scenario.Suppose there is a method in Javascript which returns a string value.We will call that method by simply executing HtmlPage.Invoke() method and process the return value as needed in silverlight.

This is possible because the javascipt function returns string.There is a proper mapping in silverlight to accept the value.What to do if javascript has to return the following object.

function GetDetails()
{
var me={Name:'joy',Company:'identitymine'};
return me;
}

How can silverlight recognize the object type?In this case we have to use ScriptObject.See more details about the class here in msdn

Below is the solution which solves the said scenario

private void btn_Click(object sender, RoutedEventArgs e){
ScriptObject obj = HtmlPage.Window.Invoke("GetDetails", "");
txtName.Text = (string)obj.GetProperty("Name");
}

Sample available here

Thursday, May 8, 2008

Silverlight - Javascript Communication - Part 2

Please have a look at my previous post which handles the communication in a easy way.Better use that technique whenever required.But Of course as per your requirements it may vary.

As I told in the earlier post we need to have understanding about Scriptable attribute,ScriptObject etc.I have listed some links which I feel explains the concept well.

  1. ScriptableType attribute: This tells that the type is accessible from script.Usually we decorate the Page class with this attribute.(See what MSDN tells)
  2. ScriptableMember attribute : Tells that this member is accessible from script.(See what msdn tells)
Well in the C# we had told that these are the types and members which are accessible in script.But how the browser ,HTML ,Javascript or DOM knows that.For that we just have to register the object with HTML DOM.

This uses the RegisterScriptableObject () method of HtmlPage class.(See what msdn says)

HtmlPage.RegisterScriptableObject("mainpage", this);//mainpage is the name in which DOM should access the object

Now we completed works in C#.Lets put that all together
[ScriptableType]
public partial class Page : UserControl {
public Page(){
InitializeComponent();
HtmlPage.RegisterScriptableObject("mainpage", this);
}
[ScriptableMember]
public void SetData(double val){
sldr.Value = val;//sldr is an object of Slider
}
}

At the javascript side we just need to get the object of plug in to invoke the method which is scriptable.

var Host = document.getElementById("Xaml1");//Xaml1 is id of Silverlight Control

Once we get the plug in just call

Host.content.mainpage.SetData(val);

Putting altogether

<head runat="server">
<title>Test Page For SilverlightApplication1title>
<script language="javascript">
   1:     function setvalue() { 
   2:         var v=document.getElementById("txt");
   3:         var val=parseFloat(v.value);
   4:         var Host = document.getElementById("Xaml1");
   5:         Host.content.mainpage.SetData(val);
   6:     }
</script>
</head>
<body style="height:300;margin:0;">
<form id="form1" runat="server" style="height:300;">
<asp:ScriptManager ID="ScriptManager1" runat="server">asp:ScriptManager>
<div style="height:300;">
<asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/SilverlightApplication1.xap" Version="2.0" Width="300" Height="300" />
</div>
<br />

<a href="#">HTML Areaa><br />
<input type="text" id="txt" /> <button onclick="setvalue()">Update Sliderbutton>
</form>
</body>

Sample available here.

Silverlight - Javascript communication - Part 1

Please don't confuse this with one of my earlier post which described how to do things with javascript without disturbing C#.

Here I am going to say how to accomplish communication between C# code in Silverlight and Javascript in aspx , html or any file which hosts Silverlight plug in.

Simple communication
Here I am using the Invoke() method of HTMLWindow class for communication.
  • Silverlight –> Javascript The data flow here is from Silverlight to Javascript.For accomplishing this we need to entities.
    1. Sender->Silverlight code which initiate the action.This is Invoke() method call now.
    2. Receiver -> Javascript function which is being called by Silverlight's Invoke method
    Silverlight
    private void Button_Click(object sender, RoutedEventArgs e){
    System.Windows.Browser.HtmlPage.Window.Invoke("ShowMsg", txtInput.Text);

    }

    Javascript

    function ShowMsg(msg)
    {
    alert(msg);
    }



  • Javascript -> Silverlight

    Here the data flow is from Javascript to Silverlight.i.e we returns some value from the javascript function to Silverlight .

    Javascript

    function GetData()
    {
    var reply = prompt("What's your name?", "");
    return (reply);
    }


    Silverlight


    private void Button_Click_1(object sender, RoutedEventArgs e){
    string o=(string)System.Windows.Browser.HtmlPage.Window.Invoke("GetData", "");
    txtOutput.Text = o;
    }

Sample here

Here initiator of all the communications is Silverlight.But what to do if Javascript has to start communication.For that we should be familiar with Scriptable attribute,ScriptObject etc..That will discuss later otherwise this post become a story. :-)

Tuesday, May 6, 2008

Run Tag v/s code

As a Silverlight dev or designer, we are all familiar with Run tag which helps us to show multiple text formats in single TextBlock.

Normally we achieve the Run functionality through XAML.But have you think of doing the same from c#?? There is no direct children in TextBlock where we can pump objects of Run.
Then what to do ?

The solution is simple Use the TextBlock.Inlines collection.

Here goes the implementation

Run joy = new Run();

joyr.Text = "joy";

joy.Foreground = new SolidColorBrush(Colors.Blue);

Run george = new Run();

george.Text = "joy";

george.Foreground = new SolidColorBrush(Colors.Blue);


txt.Inlines.Add(joy);

txt.Inlines.Add(george);

Wednesday, April 30, 2008

Color / SolidColorBrush object from color name in silverlight

The situation lead to this post was one of my friend's query.He just wants to set Background of something with a Color name in hand.
Basically string "Green" should be converted into Color object.
It seems like a silly thing as we have enough experience in .net.(I assume that persons wont jump into silverlight without basic skills in .net or jscript).But this becomes complicated when we are not able find out the method 'Color.FromName()'.
We were not able to find out a direct method which meets his requirement.But at last we arrived on the following.

private void Button_Click(object sender, RoutedEventArgs e) { 
string s = "<solidcolorbrush> xmlns='http://schemas.microsoft.com/client/2007'";

s+=" xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'" ;

s+=" Color='Green'/>";

SolidColorBrush brush =(SolidColorBrush) XamlReader.Load(s);

LayoutRoot.Background = brush;

}


It is nothing but creating a SolidColorBrush object from xaml where he can insert the color name in string.

Friday, April 11, 2008

Styling and Templating in Silverlight 2.0

There is no easy method to edit Styles or Templates of Silverlight 2.0 controls eventhough there is Style and Templating support.The actual problem is we can't find out the default Style or Template in ordre to edit.In WPF applications it's possible by opeing Application in Expression Blend.But we should alter the templates in order to get full strength Silverlight .ie the GREAT next generation look and FEEL.

Here you can found one tool which displays default style and template of Silverlight controls.just copy the style from the tool then alter and apply to your controls and have the power of Templating and Styling.
Hope in future versions of Blend there would be support to edit templates as we are doing for WPF application.Anyway thanks to Delay for providing such a tool.

The default styles are available in MSDN also.

Wednesday, April 9, 2008

Multiline TextBox in Silverlight 2.0

Its set of workarounds only.There is no support in silverlight 2.0 to have a multiline textbox.But we should accomplish as we might be in deadline :-).It leads to workarounds.
What I did ,was to set AcceptsReturn property of TextBox.Now it will accept Returns ie EnterKey and create one more line by increasing its' Height.
Now the next problem came.ScrollBars..
I tried setting ScrollViewer.VerticalScrollBarVisibility="Visible".But it gave me runtime error.(Dont know why VS2008 showed intellisense to add ScrollViewer.VerticalScrollBarVisibility="Visible").
Again workaround.Put this TextBox in a ScrollViewer.
Finally it looks like




<ScrollViewer Height="100" Width="100" HorizontalScrollBarVisibility="Visible">

<TextBox Text="Javascripting Silverlight 2.0"

AcceptsReturn="True"

/>

ScrollViewer>



Sample located here

Tuesday, April 8, 2008

Javascripting Silverlight 2.0

As the heading implies ,here I am going to explain about "Using Javascript with Silverlight 2.0".

Importance
Silverlight 2.0 has got so many exciting features/controls like Calendar,MultiScaleImage etc along with c# support.But what can a javascript developer do?
He can still code in javascript itself and make use of these new things.

Here goes some guidelines to start javascripting in Silverlight 2.0
  1. Since we don't have a built-in Visual studio template for creating Silverlight2.0 application using Javascript ,we have to use the available Template of either C# or VB.Net
  2. Getting reference to Plugin and other objects
<asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/SilverlightApplication2.xap" Version="2.0" Width="100%" Height="100%" OnPluginLoaded="plloaded" />


plloaded is a javascript function where we are going to code rest.
3 . Subscribing to events

<script language="javascript">
   1: function grd_MouseLeftButtonDown(sender,args){
   2:     alert("Clicked on " + sender.name);
   3: }
   4: function plloaded(sender,th)
   5: {
   6:     var i=sender.get_element();
   7:     var grd=i.Content.findName("LayoutRoot");//LayoutRoot is the Grid Present in Page.Xaml 
   8:     grd.AddEventListener("MouseLeftButtonDown", "grd_MouseLeftButtonDown")
   9: }
</script>


Its done this will invoke the grd_MouseLeftButtonDown function on mouse click of Grid present in Xaml.

A sample which implements this method is located here

Friday, April 4, 2008

Silverlight 2.0 crossdomain programming

'Crossdomain' is a common word in Silverlight programming from the days of wpf/e itself.Actually what is 'crossdomain' ?
It's nothing but trying to access something located at different domains other than the silverlight application's domain.

These calls are blocked in silverlight.But we can't create a complete application without making these calls.for eg: if we need to access a database ,we should make these types of calls since Silverlight dont have direct database suppport.In such situations we do the following.

Create a proxy in the same domain of Silverlight application and route calls through that proxy.Proxy usually be a webservice or WCF service which dont have the crossdomain limitation.

There are so many things which we should take care of when using these methods.Some links are given below which helps you to improve your application's communication skill.

http://blogs.msdn.com/silverlightws/archive/2008/03/30/some-tips-on-cross-domain-calls.aspx
http://community.irritatedvowel.com/blogs/pete_browns_blog/archive/2008/03/19/WCF-Integration-in-Silverlight-2-Beta-1.aspx

Wednesday, March 26, 2008

Silverlight Spy - Debug any silverlight application

http://www.silverlightspy.com/silverlightspy/

Check it out.Its an great tool to know what is inside Silverlight applications like
Snoop for WPF.

Saturday, March 15, 2008

What is the purpose of .xap file in Silverlight 2.0?

Normally when you start with Silverlight 2.0, you may notice the .xap file which is present in the ClientBin folder.(Eg if you create a project called TextSL,it will create a .xap file named testSL.xap).Since this is new to us ,we will wonder ,what that file contains..

Also this prevent us from getting the reflected code.(Currently the reflector accepts only dlls & exes I think).

Actually what is .xap files?or what is the format of .xap files?
Answer is simple
.xap files are zip files.ie just a zipped and renamed as .xap .Served as application/octet-stream or application/x-silverlight.

Why they (MSFT) introduced this new format..Here are my assumptions.

  1. Now the silverlight application starts only after downloading all the assets(Images videos etc in the project) and dlls.So downloading would be faster ,if these required files are in a zip file since zip employe a good compression.
  2. Just to get rid of reflection.(May this come from my reflecting mind.MSFT may have some other thoughts.They might not think of this reflection:-) )
  3. .......(MSFT can only fill,if there are any other reasons)

How to reflect

  1. Just rename .xap file as .zip file
  2. Decompress the .zip file
  3. Now you got the dlls and images.Enjoy reflecting.

Thursday, March 13, 2008

Silverlight 2.0 Class / Control hierarchy

This diagram helps very much to design our classes.ie from which class we have inherit
Find it here http://advertboy.wordpress.com/2008/03/13/silverlight-control-hierarchy/

Tuesday, March 11, 2008

Switch Silverlight 2.0 applications into FullScreenMode

Its too lengthy than the old procedure which we were doing in Silverlight 1.0 and Silverlight 1.1

Application.Current.Host.Content.IsFullScreen = true;

MessageBox in Silverlight 2.0

One more interesting features in Silverlight 2.0 due to browser interaction support ,is the "ability to use alert method of javascript"

Syntax
System.Windows.Browser.HtmlPage.Window.Alert(xaml);

I found it very useful to deal with exceptions..

Passing values from website to Silverlight control

Here is one simple technique to pass values from website (aspx page where Silverlight control resides) to silverlight control.
This employes the InitParameters property of silverlight control to hold the values.

<asp:Silverlight ID="Xaml1" 

runat="server"

Source="~/ClientBin/MySilverlight.xap"

Version="1.1"

Width="1024px" Height="768px"

PluginBackColor="#0C0C0C"

InitParameters="Name=Joy"/>

In Silvelight application (App.xaml.cs)



private void OnStartup(object sender, StartupEventArgs e)

{

Page p = new Page();

p.UserName = e.InitParams["Name"];//Accessing initParams

this.RootVisual = p;


}

Thursday, March 6, 2008

Silverlight 2.0 release

It finally arrived .Now I am free to blog on it...
Download links are posted here.
http://blogs.msdn.com/tims/archive/2008/03/05/download-links-for-mix08-announcements.aspx
Some key features I noticed in Silverlight 2.0 are

  1. Databinding
  2. Templating support
  3. Styling
  4. New controls such as Calendar ,DataGrid.(even WPF dnt have native grid)
  5. 2 layout panels Grid & StackPanel
  6. ArrangeOverride and MeasureOverride on FrameworkElements :-)
  7. Linq
  8. Easy integration into ASP.NET using <asp:silverlight/> tag without script.Dont know how to integrate in php or jsp sites since there is no <asp:silverlight/> control.

And lot of new features which will be discussing in subsequent posts.

So welcome Silverlight 2.0 and hope MSFT will make it stable in order to use it in production environment.