How to set axis properties programatically for Silverlight charts

by Naveen 7. December 2009 06:23

In my previous post How to hide gridlines in charts, I showed how you can accomplish the task from XAML. This is all good when you know that rendering behavior of you chart is not going to change or you do not have to modify the display at run time based on some computed values curing run time. And works great for design time as well. But a lot of time you want to change the behavior at run time. In that case you need to know how you can change properties of axis programatically.

Each chart has a collection of Axis. By default this collection is empty. Charting controll fills this collection if you do not provide any. And it makes it decision based on the type of values you render on these axis. For example tf you are displaying DateTime type values on an axis, control will add DateTimeAxis to its collection. I have two liner axis in my chart that display simple numeric values. Following code shows how I added two linear axis, X and Y, to my chart. Most important property to set is Orientation. Without it, rendering engine does not know what axis you intend to change.


private void SetYAxis()
{
  var lax = new LinearAxis();
  lax.ShowGridLines = false;
  lax.Orientation = AxisOrientation.Y;
  lax.Title = "Response Time";
  myChart.Axes.Add(lax);
}

private void SetXAxis()
{
   var lax = new LinearAxis()
              {
                ShowGridLines = false,
                Title = "Interval",
                FontWeight = FontWeights.Bold,
                MaxHeight = 1,
                Opacity = 0,
                Orientation = AxisOrientation.X
               };
   myChart.Axes.Add(lax);
}

Give your advice to big bosses and make money

Views: 1988

Tags: , ,

Silverlight | Charting

How to hide grid lines in Silverlight chart?

by Naveen 7. December 2009 05:53

This is one of the thing that is easy to do but no so obvious. I think mostly its lack of complete description of how charting controls provided in Silverlight toolkit work and how to manipulate them. When you draw charts like Line, Column, Bar etc., the grid line on DependentValue are rendered by default. There is a property ShowGridLines available on DisplayAxis class that is base class for axis. You just need to set its value to False. For example in my line chart I did not want to show grid lines on grid lines on Y axis. Following XAML snippets shows how I turned off rendering of grid lines on Y-axis.


<chartingToolkit:Chart Title="Latency" x:Name="latencyChart" BorderThickness="1">
 <chartingToolkit:Chart.Series>
  <chartingToolkit:LineSeries Title="Val 1" 
     DependentValueBinding="{Binding Threshold}"
     IndependentValueBinding="{Binding IndependentValue}" 
     AnimationSequence="Simultaneous" />
  <chartingToolkit:LineSeries Title="Val 2Latency" 
   DependentValueBinding="{Binding Current}" 
   IndependentValueBinding="{Binding IndependentValue}" 
   AnimationSequence="Simultaneous" />
  <chartingToolkit:LineSeries Title="Val 3" 
   DependentValueBinding="{Binding Average}" 
   IndependentValueBinding="{Binding IndependentValue}" 
   AnimationSequence="Simultaneous" />
  </chartingToolkit:Chart.Series>
   <chartingToolkit:Chart.Axes>
    <chartingToolkit:LinearAxis Orientation="Y" ShowGridLines="False"/>
  </chartingToolkit:Chart.Axes>
</chartingToolkit:Chart

Give your advice to big bosses and make money

Views: 2454

Tags: , ,

Charting | Silverlight

Silverlight compile error - The tag 'Label' does not exist in XML namespace

by Viper 8. October 2009 05:55

I was working on a silverlight form in an application. I was trying to add some validations and other related controls on the page. So I had added Label control on the page. I declared the xml namespace and associated tags at the top of the control file as well. When I tried to compile the application, I got the following error. I looked at the declarations, my SDK folder to make sure that I have the required SDK assemblies, I looked in GAC etc. Everything looked good and I still could not figure out what the problem is.

The tag 'Label' does not exist in XML namespace 'clr-namespace:System.Windows.Controls;assembly= System.Windows.Controls.Data.Input'
Could not load type 'Microsoft.Windows.Design.DataContextValueSourceAttribute' from assembly 'Microsoft.Windows.Design.Interaction, Version=3.7.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

What is the problem?

After spending good bit of time, I decided to look at one of the sample in SDK. I still could not figure out the issue. Then I decided to copy and paste the xml namespace and tags from the sample to my XAML file. Now everything worked fine. When I closely looked at the declaration, I saw the issue. See below, the one in red is wrong and one in green is good.

xmlns:dataInput="clr-namespace:System.Windows.Controls;assembly= System.Windows.Controls.Data.Input"

xmlns:dataInput="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.Input"

You can see I had an extra white space after assembly=. It seems that compiler is literally parsing the string and trying to look for assembly file with name as is in the statement. Instead of giving error message that some namespace or control does not exist in the assembly, the correct error message should have been that assembly with name or path could not be found. I could not complain much either because I am using Visual Studio 2010 Beta and beta version has lot of room for improvement.

Give your advice to big bosses and make money

Views: 2867

Tags:

Silverlight | Visual Studio

How to implement OWA style new message notifier poup using Silverlight and javascript

by Viper 6. October 2009 14:06
OWA style new message notification popup

Download Demo Projects

This is one of the projects I have been planning to work on for some time. I was looking into building an event notifier in one of my ASP.Net application. I wanted it to be more like Outlook Web Access (OWA) new email notifier pop-up. It is the one that slides up from bottom right corner of your browser when there is a new email in your inbox. I had built it in the past using all javascript solution. Yes, this Microsoft is one of the earliest implementation of so called AJAX applications. I did not want to deal with all the javascript code related to setting up HTTP calls and then dealing with response and rendering the results.

I wanted to leverage Silverlight to do all the heavy lifting. And use light weight javascript implementation on client to do animated sliding and positioning of the popup notifier box. At the end it turned out be quite an elegant solution that worked on major browsers like Internet Explorer, FireFox and Chrome. This article is an attempt to describe How to implement OWA style new email notifier popup using Silverlight and Javascript.

The implementation involved the following technologies and I will describe how each component was implemented

  • ASP.Net web application
  • ASP.Net web service
  • Silverlight application

ASP.Net Web Service

Let's start with discussion of the component that is responsible for communication of data between client and server application. The client requests data from server at certain frequency to check if there are any new messages. So I implemented as simple ASP.Net web service application with few web methods. For this demo I had a simple method with following signature.


[WebMethod]
public string GetGlobalMessages()
{
 List msgs = MockData.GetGlobalMessages();
 return msgs.ToJson();
}

For demo application, I implemented a MockData class that creates a random list of messages and then serializes that collection as JSON and sends it in response. I implemented ToJson as an extension method on List<StatusMessage> object. You will find it in Extension.cs file in ActivityData project.


public static string ToJson(this List<StatusMessage> msgs)
{
 var ser = new DataContractJsonSerializer(msgs.GetType());
 var ms = new MemoryStream();
 ser.WriteObject(ms, msgs);
 var serializedData = System.Text.UTF8Encoding.UTF8.GetString(ms.ToArray());
 return serializedData;
}

You can see there is nothing fancy about this whole implementation to make it work with a Silverlight client. A very simple ASP.Net web service.

Silverlight Application

This is where all the action happens. There are few components of this application, rendering and data access. Lets us first discuss data access. The client application is to talk to server at certain frequency. That means I need some kind of timer going in the application. When this timer ticks at specified interval of time, it send asynchronous request to server to get new messages. I have implemented this whole mechanism in MessageMonitor application. When this class is constructed, it creates an instance of DispatchTimer. You may be asking why DispatchTimer and why not simple Timer application. The problem is that when you are dealing with user interface application, you can only update the controls on the thread on which they were dispatched. Regular timer does not executes on that dispatcher thread. So if you will try to update your user interface on that thread you will get exception complaining about cross threaded access. Here is the code that created DispatcherTimer for my application.


private void CreateMessagePollTimer()
{
 _messagePollTimer = new DispatcherTimer();
 _messagePollTimer.Tick += new EventHandler(MessagePollTimer_Tick);
 _messagePollTimer.Interval = new TimeSpan(0, 0, MessagePollInterval);
}

When the timer ticks it calls MessagePollTimer_Tick method. And that method makes async request to server to get new messages.


void MessagePollTimer_Tick(object sender, EventArgs e)
{
 if (Stopping || MessagePollInProgress) return;
 GetMessages();
}

When async request to server completes, the following method gets called. You can see that now it uses the same JsonSerializer class to de-serialize the response into list of StatusMessage objects. And then it raises event for objects that have subscribed to the event.


void GetGlobalMessagesCompleted(object sender, 
  SiteMessagePanel.ActivityDataServices.GetGlobalMessagesCompletedEventArgs e)
{
if (e.Error != null)
{
 return;
}
 var msgsData = e.Result as String;
 var msgs = msgsData.FromJson();
 System.Diagnostics.Debug.WriteLine(msgs);
 StatusMessageEventArgs args = new StatusMessageEventArgs(msgs);
 OnStatusMessageReceieved(args);
}

Page class that implements user interface for popup, handles this event and renders all the messages.


void Monitor_StatusMessageReceieved(object sender, 
 ByteBlocks.ActivityData.StatusMessageEventArgs arg)
{
 if (arg.Messages.Count == 0)
 {
 msgTextBlock.Text = "No messages received";
 ShowClientPanel(false);
 return;
 }

 msgTextBlock.Text = string.Empty;
 messagesPanel.Children.Clear();
 foreach (var msg in arg.Messages)
 {
  StackPanel sp = new StackPanel();
  TextBlock tb = new TextBlock();
  tb.Text = msg.Title;
  tb.TextWrapping = TextWrapping.Wrap;
  sp.Children.Add(tb);
  messagesPanel.Children.Add(sp);
 }
 ShowClientPanel(true);
}

ASP.Net application and javascript

ASP.Net application acts as a host for the silverlight control that I created to render messages. I have implemented a simple Server Control that hosts it. Then I added that control inside a simple div on the master page. And I have very simple vanilla implementation of the server control. It does not have very complicated implementation. I simply copied the code generated by silverlight wizard for test page into that control


<div id="statusslideup">
<ByteBlocks:StatusPanel runat="server" id="statusPanel" />
</div>

Calling Javascript Method From Silverlight

So far we have implemented two pieces of the application that drive the data and render it. Now comes the fun part. How are we going to trigger the client to show the popup and animate it to come up from bottom. First, it is Silverlight application that is running the timer. So it is the one that has to trigger the client. I implemented some java script code that shows the DIV that hosts silverlight client component. And then small piece of code that implements animation. Silverlight framework provides a very simple mechanism to invoke any Javascript method that is implemented on client side. I implemented a very simple method in silvelight application to call my JS method whenever there are new messages for the user.


private void ShowClientPanel(bool show)
{
 HtmlPage.Window.Invoke("_showStatusPanel", show);
}

It could not be any simpler. And the following Javascript function implements small piece of code that calculates position of popup notifier window based on browser height and height of element containing silverlight control.


setStatusPanelPosition = function() {
 if (_statusdiv) {
 _maxPanelPos = document.body.scrollTop + ($(document).height() - _statusdiv.clientHeight);
 _curPanelPos = $(document).height();
 if (!_isStatusVisible) {
  _sliderInterval = setInterval("_slidePanel()", 5);
 }
 else {
  _statusdiv.style.top = _maxPanelPos + "px";
 }
 _isStatusVisible = true;
 }
}

Demo Project

Attached demo project is a collection of Visual Studio 2010 projects and solution. If you do not have VS2010, you can simply create a new solution and projects in VS2008 and copy the source files in there. You are also going to need to download Silverlight 3 Toolkit because I use theming controls from that toolkit to give some zing to the UI.

I hope this demo project helps you in building cooler implementations of OWA like message and event notifier windows.

Give your advice to big bosses and make money

Views: 5748

Tags: , ,

ASP.Net | Javascript | JQuery | Silverlight

How to send data from Javascript to Silverlight control to render charts

by Viper 31. July 2009 15:09

Download Demo Project

I have been discussing use of jQuery to send AJAX request to server to get some data every X number of seconds to get server time and calculate some latency numbers. Now it is time to add some color to it. The numbers that I am getting is great and provide some useful information. But having a visual of how these numbers are varying with time will enhance utility of these statistics. So I decided to add some charts to show these latency numbers are varying with time. In this article I am going to show how you can pass the data obtained from server using AJAX request to a Silverlight application hosted on the page. This silverlight application uses charting control from Silverlight toolkit. Lets see how all this fits together to get this to work.

Bridge between Javascript and Silverlight component

In one of earlier posts, How to setup communication between silverlight applications, I discussed how you set this bridge up. The sample project for that article was done using Silverlight 2. The mechanism to set up the communication bridge has not changed in Silverlight 3. So all those concepts still apply for this project as well. The following code snippets shows declaration of a method decorated with ScriptableMember attribute to let silverlight framework know that this methos is to be exposed to javascript. And in constructor of the page, HtmlPage.RegisterScriptableObject method is called to register the class to be exposed to javascript. I do not want to expose all my properties, fields and methods to javascript. So I have not added scriptable attribute on class itself. I want to control what is exposed and what is not.


public MainPage()
{
	InitializeComponent();
	HtmlPage.RegisterScriptableObject("ClockDataClient", this);
	SetupChartDisplay();
}
		
[ScriptableMember]
public void PutNewClockData(string xtx, string data)
{
	AddDataPointToPlot(data);
}

This completes what needed to be done from silverlight application to expose its end points to javascript. Now we are going to see what is done on pages to communicate to silverlight control.

Setting up the page

First thing you need on the page is to include your Silverlight control. On Default.aspx you will find the following declaration of object tag that will host the control.


<object id="clockDisplayPlugin" data="data:application/x-silverlight-2," 
  type="application/x-silverlight-2" width="100%" height="100%">
<param name="source" value="ClientBin/ClockLatency.xap"/>
<param name="onError" value="onSilverlightError" />
<param name="onLoad" value="onLoadClockDisplay" />
<param name="background" value="white" />
<param name="minRuntimeVersion" value="3.0.40624.0" />
<param name="autoUpgrade" value="true" />
<a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40624.0" style="text-decoration:none">
  <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="" style="border-style:none"/>
</a>
</object>

All this code was generated by wizard when I added test paste to my project. I added a new param declaration to handle load event. This event is fired when Silverlight control has been loaded. On lets see what all javascript is required to send message to silverlight control.


function onLoadClockDisplay(sender, args) {
 objClockDisplay = sender.getHost();
}

function sendLatencyData(data) {
 if (null != objClockDisplay) {
  objClockDisplay.Content.ClockDataClient.PutNewClockData("", data);
 }
}

As you can see, in load event handler I saved the reference to Silverlight control object. Then from my ajax request code, every time I got the data from server, I call sendLatencyData method. This method calls PutNewClockData method that I exposed from control using ScriptableMember attribute. This call constitutes of four parts.

objClockDisplay.Content.ClockDataClient.PutNewClockData

objClockDisplay is reference to our silverlight plugin. Content is the property on plugin object through which control's methods are exposed. ClockDataClient is the key that was used to register the class as scriptable in our control. PutNewClockData is the name of the method.

Setting up charting control in Silverlight component

I used charting control from Silverlight Toolkit for my project. I decided to use column chart to display latency numbers over time. In silverlight application project, I added the following XAML on MainPage.


<chartingToolkit:Chart Title="Clock Latency" x:Name="latencyChart" BorderThickness="2">
 <chartingToolkit:Chart.Series>
  <chartingToolkit:ColumnSeries Title="Latency" DependentValueBinding="{Binding Latency}" AnimationSequence="Simultaneous" />
 </chartingToolkit:Chart.Series>
</chartingToolkit:Chart>

In codebehind i created a collection to save data sent from javascript and attached the column series to that collection. I only keep last 11 entries in the collection.


void SetupChartDisplay()
{
 ColumnSeries cs = latencyChart.Series[0] as ColumnSeries;
 foreach(var lItem in cs.LegendItems)
 {
  lItem.Visibility = System.Windows.Visibility.Collapsed;
 }

 latencyChart.Width = 500;
 (latencyChart.Series[0] as DataPointSeries).ItemsSource = DynamicCollectionItemsSource;
}

You can see it was pretty simple to set this whole up and get javascript to send data to silverlight control and render the charts using those numbers.

Click to see demo

Feel free to send any comments or suggestions.

Give your advice to big bosses and make money

Views: 4073

Tags:

HTMLParser | JQuery | Silverlight

Could not load file or assembly 'System.Web.Silverlight' or one of its dependencies

by Viper 30. July 2009 11:41

This morning I was working on a prototype Silverlight application that I developed with Silverlight 2. I copied the project to my new shiny Dell XPS with GTX280 video card. Moment i hit F5 to debug the application, i get the following exception.

Could not load file or assembly 'System.Web.Silverlight' or one of its dependencies. The system cannot find the file specified
Line 2: <%@ Register Assembly="System.Web.Silverlight" Namespace="System.Web.UI.SilverlightControls" TagPrefix="asp" %>

It just took me by surprise. I was like, I did not change anything in the project in couple of months and I have new installation of all visual studio tools. After digging through release notes and documentation of Silverlight 3 SDK and tools, i found out that Microsoft has decided to get rid of ASP.Net Silverlight server control that was part of Silverlight 2 SDK. Since I have fresh install of Visual Studio 2008 and tool and I never installed Silverlight 2 SDK on this workstation, I did not have that server control.

Microsoft is recommending to use object tag to insert Silverlight components on the pages now. It is not big deal but it was nice having that server control do all the dirty work behind the scene for you and add object with appropriate parameters and other values. If you still want to continue using that Silverlight server control, you can copy System.Web.Silverlight assembly from other machine or you can install Silverlight 2 SDK.

There seem to be few issues with that ASP.Net server control but none are serious that you could not keep the control and use workaround to get over the issues.

Give your advice to big bosses and make money

Views: 8942

Tags:

Silverlight

Navigation frame in Silverlight applications

by Viper 19. May 2009 14:37

In silverlight versions prior to 2, we all were setting up navigation for application using work arounds like setting up a layout on a page that will look like a application frame then provide some links etc. on that page to mimic behavior of a navigation system. Well now you do not have to do that any more. Silverlight 3 has included Frame UI element that provides all the navigation facilities. This control is included in System.Windows.Controls.Navigation assembly. You will also notice new namespace System.Windows.Navigation in documentation that provides all the support needed for navigation features.

silverlight navigation pages

When you choose to add a new project to IDE, you will notice a new template for adding Silverlight Navigation Application to your solution. The wizard will generate all the necessary XAML and code to include a navigation frame and include three pages as part of the application. This will give you a good starting point to build a navigtion type Silverlight application.

Give your advice to big bosses and make money

Views: 1000

Tags: ,

Silverlight

Error: ServiceHost only supports class service Types

by Viper 17. March 2009 11:53

While adding service reference to a IIS hosted WCF service in Silverlight application, I ran into the following error.

ServiceHost only supports class service Types

In your WCF service if you look at markup .svc file of your service, you will notice from where reference to ServiceHost came. In my service, it looks like as below.


<%@ ServiceHost Language="C#" Debug="true" 
Service="SearchService.SearchServer" CodeBehind="SearchServer.svc.cs" %>

You can see that there are only 2 things that can go wrong in this declaration. One, the service class that implements your service does not match with the declaration in this mark up. This is usually the cause of this error because most of the time you modify the wizard generated interface and service class names and you forget to modify the declarations in this SVC file. Make sure that all entries in mark up file match with actual class and interface names.

Give your advice to big bosses and make money

Views: 3595

Tags: ,

Silverlight | WCF

Custom tool warning: No endpoints compatible with Silverlight 2 were found

by Viper 10. March 2009 18:40

When you use Add Service Reference wizard to add a reference to existing WCF service to your silverlight application, you may run into this warning. The description of the warning has all the details about the issue and also tells you what to do to fix it. Now you are wondering why this happened. When you use Visual Studio to create WCF project, you will notice that it generates a configuration file for your service as well where you can configure endpoint, bindings etc. for your WCF service. If you have not modified your configuration file, you may notice something like below set as endpoint.

<endpoint address="" binding="wsHttpBinding" 
contract="ByteBlocks.ForExService.ICurrencyService">

Notice that binding is set to wsHttpBinding. This is the binding that provides you connectivity over HTTP/HTTPS with features like reliability, security etc. as specified in WS* protocol. The problem is that Silverlight 2 applications can only connect with ASMX-based web services or services that conform to WS-I Basic Profile 1.1. What that means is that Silverlight applications can only create BasicHttpbinding. So if you modify your service to expose an endpoint that implements basicHttpBinding you are good to go. If your existing WCF service is not tightly coupled with any of WS* features then you can change the existing configuration file as below.

<endpoint address="" binding="basicHttpBinding" 
contract="ByteBlocks.ForExService.ICurrencyService">

Now if you try Add Service Reference tool to add reference to your WCF service, you will not see such warning and a nice set of proxy classes will be created for you to start communicating with WCF service.

Give your advice to big bosses and make money

Views: 7498

Tags: ,

Silverlight | WCF

How to supply start parameters for Silverlight application in querystring

by Viper 18. January 2009 20:21

In my article Supply Parameters in InitParams I explained how you can make use of InitParams. But a lot of time, like traditional web applications, we want to specify start parameters or want to drive behavior of page based on some parameters specified in query string. Silverlight application does allow you to do so. Well it is not something specific to Silverlight application. You can access query string any time in your application using Document object of HtmlPage. Following code snippet shows how in my application I switch initial navigation of my application to specific page based on nav query string parameter.


private void Application_Startup(object sender, StartupEventArgs e)
{
if (HtmlPage.Document.QueryString.ContainsKey("nav"))
{
 string navAction = HtmlPage.Document.QueryString["nav"];
 switch(navAction)
 {
  case "Products":
  // Switch navigation to Products page
  break;
  case "Service":
  // SWitch navigation to Services page.
  break;
  default:
  // Switch navigation to default page
  break;
 }
}
this.RootVisual = new Page();
}

Unlike QueryString property in ASP.Net, you can not access querystring parameters by Item accessor. If you will try to access a querystring parameter using following code snippet, KeyNotFoundException exception will be thrown if that parameter is not present in query string.

Give your advice to big bosses and make money

Views: 1045

Tags:

ASP.Net | Silverlight

How to display row number in Row header of DataGrid

by Viper 12. January 2009 08:17

Lot of time you want to display line number (row index) of rows in DataGrid in Row header of your grid very much like how each row in Microsoft Excel displays line number. One dirty solution is to add a new column in the grid at first position and then display its text as row number. There is more elegant solution available. You can actually set the Row.Header value to Row index in LoadingRow event of your grid.

protected GridRowLoading(object sender, DataGridRowEventArgs arg)
{
  arg.Row.Header = arg.Row.GetIndex();
}

Make sure that you set HeaderVisibility property of your grid to "Row" or "All". By default row header is not visible.

Give your advice to big bosses and make money

Views: 3246

Tags:

ASP.Net | Silverlight | DataGrid

ADO.Net Dataservice Error: Request Error Server Encountered an error processing request

by Viper 5. January 2009 09:03

I was working on a silverlight application that was connecting to an ADO.Net dataservice on my server. All of a sudden I started getting following error.

Request Error: The server encountered an error processing the request. See server logs for more details

I looked at event logs and sql server logs. I could not find anything wrong in the logs. Then I started thinking back to figure out what did I change in service that may have caused anything to break. Only thing I remember changing was that sql connection was changed from windows authentication to sql authentication. I looked at connection string and everything looked fine there as well. I tested the credentials and they were fine. After banging my head for few minutes I tried couple of URL in service and nothing worked. I fired up SQL profiler and started monitoring the requests. I did not see a single query making into it from ADO.Net data service. I looked at connection string again and there you go. There was typo. Instead of "User ID" I had typed "UserID" to provide login name. After I fixed that, everything worked like a charm.

You can see that error message from data service was not very helpful. So every time you run into this obscure error, make sure that you check names in query strings etc. to make sure there are no typos.

Give your advice to big bosses and make money

Views: 4114

Tags: ,

ASP.Net | Silverlight | ADO.Net | DataService

Silverlight support in FireFox is not very stable

by Viper 1. January 2009 10:34

This morning I was trying to set up a new web site to host some silverlight applications. I went through all the steps to set up the site and then fired up the demo page in FireFox 3.0.5. To my surprise page kept coming back empty all the time. When I looked at the source of the page, I could see all the markup and JavaScript that was required to run silverlight applications. I thought that I forgot something to do on web server to support silverlight applications. I went through my check list and saw i have done all the things. Then I fired up web site in Chrome. The application came up nicely and same thing in Internet Explorer. I looked at the plugin lists in FireFox and saw that Silverlight is installed. So much for cross-browser/cross-platform framework. From what I could see that behavior of silverlight applications is very flaky in Firefox. Oh well!

You can try the following demo application I created for another article on silverlight communication between plugins.

Silverlight Cross-plugin communication

Give your advice to big bosses and make money

Views: 1337

Tags:

ASP.Net | Silverlight | Visual Studio

How to supply startup parameters to Silverlight applications using InitParams

by Viper 31. December 2008 09:03

Lets talk about how you can pass some start up parameters to your silverlight application. In this post I will talk about how you can do it with ASP.Net Silverligh control. The control allows passing start up parameters through InitParamaters property. You can specify the parameters as commans separated key-value pair string. So you can pass values as described below.

    
    InitParameters="key1=value1,key2=value"
    

So a simple definition of asp:Silverlight may look like the snippet below. You can see that it is specifying two initial parameters k1 and k2 with value. And if you put a break point in Application_Startup event of your silverlight application, you can see two parameters as show in image.


<asp:Silverlight ID="Xaml1" runat="server" 
    Source="~/ClientBin/InitParamsMgr.xap" 
    MinimumVersion="2.0.31005.0" Width="100%" Height="100%"
    InitParameters="k1=v1,k2=v2" />

This look all well and good. Problem comes when you have one or more values that have commas embedded in it. If you pass those value as such, framework is going to treat occurance of comma as separator and going to present you with parameters that are not parameters. Look at the code snippet below where value for k2 key has comma in it. And look at the screen shot showing how the parameters look like in debugger in application.


<asp:Silverlight ID="Xaml1" runat="server" 
    Source="~/ClientBin/InitParamsMgr.xap" 
    MinimumVersion="2.0.31005.0" Width="100%" Height="100%"
    InitParameters="k1=v1,k2=v2,vx" />

Clearly you can see that application thinks that there are 3 parameters. Somebody suggested how about repalcing comma in the value with some special character. Then I was like, what if that special character is part of value as well. I was looking for a solution that is generic and would not require any custom parsing in silverlight application. So I came up with solution of replacing comma with URL encoded value %2C. And then in application I can use Uri.UnescapeDataString to decode the value. So now the mark up looks as follows and in snapshots you can see that application treats two values correctly.


<asp:Silverlight ID="Xaml1" runat="server" 
    Source="~/ClientBin/InitParamsMgr.xap" 
    MinimumVersion="2.0.31005.0" Width="100%" Height="100%"
    InitParameters="k1=v1,k2=v2%2cvx" />


private void Application_Startup(object sender, StartupEventArgs e)
{
 if (e.InitParams.Count != 0)
 {
  string k2val = e.InitParams["k2"];
  k2val = Uri.UnescapeDataString(k2val);
 }
 this.RootVisual = new Page();
}


Here is the list of URL encodings for special characters.

  • Space  %20
  • "  %22
  • #  %23
  • %  %25
  • &  %26
  • (  %28
  • )  %29
  • +  %2B
  • ,  %2C
  • /  %2F
  • :  %3A
  • ;  %3B
  • <  %3C
  • =  %3D
  • >  %3E
  • ?  %3F
  • @  %40
  • \  %5C
  • |  %7C
Give your advice to big bosses and make money

Views: 5119

Tags:

ASP.Net | Silverlight | Visual Studio

How to get notified in silverlight application when size of browser changes

by Viper 26. December 2008 09:13

A lot of time we develop content for silverlight applications that depend on size of browser or host application. Silverlight framework exposes some of host application's settings through System.Windows.Interop.SilverlightHost object which are accessible through Host property of Application class of your silverlight application. One of the properties of System.Windows.Interop.SilverlightHost object is System.Windows.Interop.Content. You can subscribe to Resized event of this object to be notified whenever there is a change in browser window.

You can find the value of browser window size from ActualWidth and ActualHeight property of Content object. When host application resizes, silverlight application gets notified through Resized event. You can subscribe to this event when application startup completes. Always access these size values in Resized event because this is time in rendering workflow when these values are actually known. These values are not known before this event. Silverlight framework uses two step process to resize UI elements. In first pass it calculates the sizes and positions. And in second step it actually positions the elements based on calculated sizes. And then final calculations have completed, then actual sizes are known.


private void Application_Startup(object sender, StartupEventArgs e)
{
startPage = new HostInfomation();
this.RootVisual = startPage;
this.Host.Content.Resized += new EventHandler(Content_Resized);
}

private void Content_Resized(Object sender, EventArgs e)
{
 HostInfomation hostInfoPage = this.startPage as HostInfomation;
 hostInfoPage.LayoutRoot.Children.Clear();
 StackPanel stackPanel = new StackPanel();
 stackPanel.Orientation = Orientation.Vertical;
 TextBlock heightBlock = new TextBlock();
 heightBlock.Text = string.Format("Height = {0}", this.Host.Content.ActualHeight);
 TextBlock widthBlock = new TextBlock();
 widthBlock.Text = string.Format("Width = {0}", this.Host.Content.ActualWidth);
 stackPanel.Children.Add(heightBlock);
 stackPanel.Children.Add(widthBlock);
 hostInfoPage.LayoutRoot.Children.Add(stackPanel);
}

Give your advice to big bosses and make money

Views: 9601

Tags:

ASP.Net | Silverlight

How to set attributes to autoresize width and height of silverlight control/page

by Viper 26. December 2008 07:02

When you add a new Silverlight User control (as new page) to your application, you get the following autogenerated shell for your page.


<UserControl x:Class="SilverDragon.HostInfomation"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="300" Height="400">
<Grid x:Name="LayoutRoot" Background="CadetBlue"></Grid>
</UserControl>


You will notice that Width and Height property has been set to an absolute value. Your immediate reaction is to change these values to some relative value like "100%" to auto resize to 100% of container. When you run the application you get run time error telling you that you have specified invalid value for Width/Height property. If you look at declaration of these property, you will find that data type for these properties is Double. The way to specify Auto value for these properties is to set these values to Double.Nan. That is microsoft way of saying that set these properties to unspecified and framework will take care of resizing this control with respect to the container. And if you want to specify this unspecified value in declaration of control, then its simple. Leave it unspecified. What this means is that remove declaration of these attributes in control declaration. Do not set these values to empty strings otherwise you will get a page or control with 0 size. So your declaration of page will look like following.


<UserControl x:Class="SilverDragon.HostInfomation"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid x:Name="LayoutRoot" Background="CadetBlue"></Grid>
</UserControl>
Give your advice to big bosses and make money

Views: 3529

Tags:

Silverlight | ASP.Net | Silverlight

Powered by BlogEngine.NET 1.5.1.7
Theme by Naveen Kohli

By Categories