LA.NET [EN]

SilverlightArchive

Nov 16

Getting started with Silverlight

Posted in Silverlight       Comments Off on Getting started with Silverlight

Last Friday, I’ve decided to start looking at Silverlight. This time, I’ve opted for starting with a book (generally, I prefer to go through the source code and run some tests along the way;). As usual, I’ll be writing a couple of posts to describe my experiences with this platform. Even though I don’t have much to say yet, I thought I’d better start writing about my experiences so that I don’t forget to mention anything along the way.

The first thing I noticed after writing  the “Hello, world!” app was that the contents of my Silverlight app are packaged into a xap file.

xapdeploy

A xap package is just a zipped file with the contents of your Silverlight application. If you open the file with an app like winrar, this is what you’ll see:

xapcontent

As you can see, the xap file contains all the resources of your app +  a manifest file (besides assemblies, you’ll typically end up with other resources like xaml files, images, etc.). Besides simplifying deployment,xap files end up improving the performance of an app. To understand why,just think that with xap, you end up compressing stuff and you’ll get all the stuff your Silverlight app needs in one request. And i guess this is all for this intro post. Stay tuned for more on Silverlight.

Jul 09

Silverlight 3 is out

Posted in Silverlight       Comments Off on Silverlight 3 is out

Incredible…version 3 is out and I still didn’t had the time to look at version 2. I guess I’ll jump write into 3 (or 4, if things keep going this way 🙂 ,,). btw, here’s the link for the VS tools.

Oct 14

Silverlight 2.0 is out

Posted in Silverlight       Comments Off on Silverlight 2.0 is out

I’ve just seen this on Scott Hanselman’s blog. I’ll make an effort to look at it, though I’m still not convinced about it…

Sep 28

Silverlight 2 RC is out

Posted in Silverlight       Comments Off on Silverlight 2 RC is out

I was keen on Silverlight more than a year ago, but unfortunately I”ve stopped studying it since I just had to work in other areas. It seems like now is the time to pick up where I left since Scott has announced the release of SL 2.0 R.

Mar 05

Silverlight 2.0 beta 1 is out

Posted in Silverlight, Trivia       Comments Off on Silverlight 2.0 beta 1 is out

So, while I was busy playing with my new HTC Touch, it seems like MS has presented Silverlight 2.0 beta 1. Now, this is really a tough choice…

Nov 20

Xaml and Media controls: giving them a new chance

Posted in ASP.NET, Silverlight       Comments Off on Xaml and Media controls: giving them a new chance

A long (long) time ago I”ve downloaded one of the ASP.NET future CTPS and was really annoyed with the Xaml and Media controls. Why? simple: they injected object tags on the page instead of generating JS code to perform those operations. The problem: you got one of those nasty “click to activate” messages when the page was hosted on IE.

Now that we know that the “click to activate” will be gone, it”s time to give these controls a second chance. Dave has already written a cool post on it and he promises to return with more Silverlight posts.

Oct 27

Hebrew and Arabic Silverlight support

Posted in Silverlight       Comments Off on Hebrew and Arabic Silverlight support

Justin-Josef has built a new codeplex project that aims to support Hebrew and Arabic text rendering on Silverlight. There are already some support materials over Justin”s site that will help you get started:

Nice work Justin!

Sep 25

Silverlight pages and VS integration

Posted in Silverlight       Comments Off on Silverlight pages and VS integration

Have you noticed that you can navigate from the “code-behind” file (cs file) to the designer by right clicking the page and choosing “View designer” (from the context menu that is shown when you perform right click), but there”s isn”t any option for going from the xaml page to the cs code file associated with it? am I blind?

Sep 25

How to share code between Silverlight and other kinds of applications?

Posted in Silverlight       Comments Off on How to share code between Silverlight and other kinds of applications?

I really haven”t looked at any Silverlight code for at least 2 months. In fact, I haven”t really been around the forums until today. Now that I”ve returned :,,), I”ve noticed that there”s a lot of similar questions around sharing code between .NET and the “mini-CLR” that is used Silverlight.

The first thing you should notice is that you cannot pass .NET components to Silverlight methods! Don”t even try this 🙂 Even though I haven”t looked at it for more than 2 months I”m almost positivethat you cannot even interop with ActiveX controls without going through JS code!

What you can do is “share” code so that you can build a class and then use that class from your Silverlight code and from other .NET code. Don”t worry: this is a short post 🙂 Instead of giving you several pieces of advice, I”ll just redirect you to a great article by Daniel Moth:

Write code once for both mobile and desktop apps

Don”t let the title fool you! Even though Daniel has written it thinking about mobile apps, the concepts do apply to code that needs to be shared by SL and other kind of .NET apps. Btw, if you”re not subscribed to Daniel”s most excellent blog, then here”s the RSS feed for it. There are really lots of cool posts over there!

Aug 17

Silverlight: understanding namescopes

Posted in Silverlight       Comments Off on Silverlight: understanding namescopes

Today i was starting to write about silverlight namescopes but then I”ve found this cool post which talks about most of the things i was writing about. btw, i”d just like to add that when you use the XamlReader.Load method, you can also create a new namescope by using the overloaded version that receives 2 parameters (the second parameter lets you specify if a new namescope should be created)

Aug 17

How to test your Silverlight quickly

Posted in Silverlight       Comments Off on How to test your Silverlight quickly

When you create a Silverlight project, you”ll automatically get an HTML file that you can open in the browser to run some quick tests. Unfortunately, the file is opened directly from the file system instead of being served from a web server. This means that some things don”t work and you”ll need to create a web site to test them (ex.: getting a video file and making it play on the MediaElement element).

Most of the time, I”m not developing Silverlight applications; i”m just writing some tests to see if something works as expected. in these cases, having to create a web application and adding pages to it might be a little bit overkill. So, instead of creating a web site and adding a Silverlight link to it (and chaning the properties of the HTML/js files  in order to get them automatically on the web site), I just add an existing web site that points to the folder that contains the Silverlight project.

Here”s how you do it:

  1. create a new Silverlight project
  2. go to the file menu and choose add -> existing web site
  3. since you can use the file sytem server for testing these functionalities, just navigate until you get the folder that has the silverlight project created in 1
  4. click open

And that”s it. you”ll get a solution with 2 projects which are just different views of the same project. When I need to write some code, I just open the file from the Silverlight project. When i need to test it, I right click the HTML file on the Web project and choose the view in browser option.

Aug 11

Silverlight: first PT project goes live

Posted in Silverlight       Comments Off on Silverlight: first PT project goes live

I”ve just noticed that the first portuguese Silverlight project has gone live. Media preview.tv was built with Silverlight 1.1 and shows some of the cool things you can do with it. if you have the time, check it out.

Aug 01

Silverlight: working with text

Posted in Silverlight       Comments Off on Silverlight: working with text

In the last days i”ve been busy…thinking about my vacations which are coming :,,)

I thought i”d write an article and submit it to a site, but i wouldn”t have the time to format it. so, i”ve given up on the idea and i”m putting it here instead . The article presents the main features Silverlight gives you for working with text. There”s also a sample that accompanies the article with several XAML pages that illustrate the features described on the docs.

Do notice that i”ve started writing this before the release of the 1.1 alpha refresh, so there may be one or two things which might not work correctly…

Jul 25

Even though the Xaml”s XamlUrl porperty seems to indicate that it can only load XAML from an existing url, the truth is that you can also pass it a reference to a XAML excerpt which is embeded on the page. here”s a quick example of how you can do this:

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default2.aspx.cs” Inherits=”Default2″ %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd“>

<html xmlns=”http://www.w3.org/1999/xhtml” >
<head runat=”server”>
    <title>Untitled Page</title>
</head>
<body>
    <script type=”text/xaml” id=”xamlContent”>
      <Canvas
        x:Name=”parentCanvas”
        xmlns=”http://schemas.microsoft.com/client/2007
        xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml
        Width=”640″
        Height=”480″
        Background=”Wheat”>
        <TextBlock
          Canvas.Left=”20″
          FontSize=”24″
          Text=”Hi”/>
      </Canvas>
    </script>

    <form id=”form1″ runat=”server”>
    <asp:ScriptManager runat=”server” ID=”manager” />
    <div>
        <asp:Xaml runat=”server”
            Height=”400″
            Width=”600″
            XamlUrl=”#xamlContent”
            ID=”myXaml” ></asp:Xaml>
    </div>
    </form>
</body>
</html>

Jul 25

Silverlight: building a simple progress bar

Posted in Silverlight       Comments Off on Silverlight: building a simple progress bar

When you”re developing a Silverlight application, you”ll surelly be in a situation where you need to download stuff before starting your app. In these cases, you should play nice with the user and give them some indications regarding what”s going on. The most common thing to do in these scenarios is to show a progress bar.

Building a progress bar in silverlight is simple and I”ll try to show you how you can build one quickly. In my example, I”ve built a simple UserControl that you can reuse to show the progress of a task. Here”s what I”ve got in the XAML file:

<Canvas xmlns=”http://schemas.microsoft.com/client/2007″
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
Width=”300″
Height=”22″>
<Rectangle Stroke=”#FF000000″ StrokeThickness=”1″ x:Name=”border”
Canvas.ZIndex=”2″
Width=”298″ Height=”22″ Canvas.Left=”0″ Canvas.Top=”0″ />
<Rectangle Stroke=”#FF000000″ StrokeThickness=”0″ x:Name=”fill”
Width=”298″ Height=”22″ Canvas.Left=”0″ Canvas.Top=”0″>
<Rectangle.Fill>
<LinearGradientBrush EndPoint=”1,0.5″ StartPoint=”0,0.5″>
<GradientStop Color=”#FFDD9090″ Offset=”0″/>
<GradientStop Color=”#FFFFFFFF” Offset=”1″/>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
<TextBlock x:Name=”info” Width=”50″ Height=”19″ Canvas.Left=”125″ Canvas.Top=”3″ FontSize=”9″ Text=”100%” TextWrapping=”Wrap”/>
</Canvas>

Now, the code:

namespace Silverlight.Controls
{
  public class ProgressBar : Control
  {
    private Canvas _root;

    public ProgressBar()
    {
          System.IO.Stream s = this.GetType().Assembly.GetManifestResourceStream(“SilverlightProgressBar.ProgressBar.xaml”);
         _root = (Canvas)this.InitializeFromXaml(new System.IO.StreamReader(s).ReadToEnd());

         UpdateInfoPos();
         UpdateUI(0);
   }

   public double CtlHeight
   {
       get { return _root.Height; }
       set
      {
       _root.Height = value;
       ProgressRect.Height = _root.Height = ProgressRectBorder.Height ;
      }
  }

   public double CtlWidth
   {
      get { return _root.Width; }
      set
      {
           double currentPercentage = Percentage;
           _root.Width = value;
           ProgressRectBorder.Width = _root.Width = ProgressRect.Width = value;
           UpdateInfoPos();
           UpdateUI(currentPercentage);
      }
   }

   public double Percentage
   {
        get { return (ProgressRect.Width / _root.Width) * 100.0; }
        set {  UpdateUI(value > 100 ? 100 : value); }
   }

   private void UpdateInfoPos()
   {
        double leftPos = (_root.Width – Info.ActualWidth) / 2;
        Info.SetValue(Canvas.LeftProperty, leftPos);
   }

   private void UpdateUI(double currentPercentage)
   {
     ProgressRect.Width = (currentPercentage * _root.Width) / 100.0;
     Info.Text = string.Concat(currentPercentage, “%”);
   }

   private Rectangle ProgressRect
   {
     get { return (Rectangle)_root.FindName(“fill”); }
   }

   private Rectangle ProgressRectBorder
   {
      get { return (Rectangle)_root.FindName(“border”); }
   }

   private TextBlock Info
   {
      get { return (TextBlock)_root.FindName(“info”); }
    }
  }
}

Nothing too fancy as you can see, but there are still some observations that need to be made:

  • I”ve added CtlWidth and CtlHeight because newing the Witdh and Height properties doesn”t work from XAML, ie, redefining the width and height properties only lets you define the width/heighr from your codebehind file. If you try to set those properties from your XAML file,it won”t work;
  • I”ve added private fields to simplify access to the named objects defined on the XAML file;
  • The current percentage is calculated by comparing the width of the rectangle against the width of the canvas that hosts it.

As you can see,the code for a progress bar is really simple and you only need to pay attention to some details (like the Width/Height problem i”ve mentioned).

Jul 24

A cool reference about the errors you might get on silverlight pages can be found here. Enjoy!

Jul 23

Quick tip: if you have this error, then you”ve got the wrong name for your assembly in the xmlns namespace introduced on the xaml file. Quick example:

xmlns:la=”clr-namespace:Silverlight.Controls;assembly=ClentBin/SilverlightProgressBar.dll”

Notice the ClentBin (instead of ClientBin) typo…

Jul 18

Another experience I”ve run today was related with compensating direction changes on animations. Here”s the scenario: suppose you”ve got a rectangle and you want it to move from x to y when something happens and then from y to x when another thing happens. 

The main problem is that the change in direction might happen before the previous running animations ends. If you want to have a cool effect, you”ll have to adjust the duration of the animation so that it looks like its moving smoothly and at the same velocity. Let”s start with the XAML:

<Canvas
  xmlns=”http://schemas.microsoft.com/client/2007″
  xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
  x:Name=”parentCanvas”
  Loaded=”Page_Loaded”
  x:Class=”SilverlightProject2.Page11;assembly=ClientBin/SilverlightProject2.dll”
  Width=”640″
  Height=”480″
  Background=”White”>
  <Canvas.Resources>
    <Storyboard x:Name=”moveright”>
       <DoubleAnimation To=”544″ Duration=”0:0:3″ x:Name=”moverightanim”
           Storyboard.TargetName=”rectangle”
           Storyboard.TargetProperty=”(Canvas.Left)” />
   </Storyboard>
   <Storyboard x:Name=”moveleft”>
       <DoubleAnimation To=”16″ Duration=”0:0:3″ x:Name=”moveleftanim”
           Storyboard.TargetName=”rectangle”
           Storyboard.TargetProperty=”(Canvas.Left)” />
   </Storyboard>
  </Canvas.Resources>
  <Rectangle Fill=”#FFE81E1E”
        Stroke=”#FF000000″ x:Name=”rectangle” Width=”56″ Height=”48″
        Canvas.Left=”16″ Canvas.Top=”64″ />
  <TextBlock Canvas.Left=”10″ Canvas.Top=”200″ Text=”Left”    MouseLeftButtonDown=”StartLeft” />
   <TextBlock Canvas.Left=”100″ Canvas.Top=”200″ Text=”Right” MouseLeftButtonDown=”StartRight” />
</Canvas>

As you can see, nothing too fancy is going on here. I”ve just added two storyboards which use a double animation to change the value of the Canvas.Left property of the rectangle. Notice that I”ve only set the To property of each animation. By doing this i know that when an animation begins, it”ll start from the current X coordinate (and this might not be the leftmost or rightmost X coordinate).

The TextBlocks are there just to control direction changes. When you click on the Right textblock, the square starts moving to the right side; clicking on the left one makes it move in the other direction. My first attempt to make direction changes looked something like this:

void StartRight(object sender, EventArgs e)
{
    moveright.Begin();
}

void StartLeft(object sender, EventArgs e)
{
    moveleft.Begin();
}

If you try to do that, you”ll see that the square changes its moving direction like we want. The problem is that it”ll always take 3 seconds to run. This means that if you click right and then left, you”ll see that it takes 3 seconds to move from its small offset till it reaches the starting position. It”s not what we”re looking for! What we need is to dynamically change the duration of the animation so that it”s adjusted to the space that the square needs to cover (in one direction or another).

To achieve this purpose, I”ve started by adding some constants and read only fields:

const double maxPosX = 544;
const double minPosX = 16;
static readonly TimeSpan duration = new TimeSpan(0,0,3);

Then I”ve build an auxiliary method that calculates the percentage of the distance that the square will cover:

double GetCurrentPercentage(Direction dir)
{
   double currentX = (double)rectangle.GetValue(Canvas.LeftProperty);
   double currentDistance = dir == Direction.ToLeft ? currentX – minPosX : maxPosX – currentX;
   double currentPercentage = currentDistance / (maxPosX – minPosX);
   return currentPercentage;
}

As you can see,we need to know the direction that is being followed. Direction is a simple enumeration that looks like this:

enum Direction
{
  ToLeft,
  ToRight
}

Now we just need to apply it to the maximum duration of the animation when the user clicks left or right:

void StartLeft(object sender, EventArgs e)
{
  long adjustedTicks = Convert.ToInt64(duration.Ticks * GetCurrentPercentage(Direction.ToLeft) );
  moveleftanim.Duration = new TimeSpan(adjustedTicks);
  moveleft.Begin();
}

Moving to the right is similar, so I”ll leave it to you :).

Jul 18

Silverlight: the parenthesis () do matter!

Posted in Silverlight       Comments Off on Silverlight: the parenthesis () do matter!

Today I needed to animate a Rectangle so that it moved from left to right. Like all sane people, I”ve right clicked the xaml file and chose open in blend. Building the animation was really a complex operation: I only needed a pair of clicks and the rectangle was moving :,,) . Unfortunately, the code blend generates sucks a lot. In order to build the animation, it adds several unecessary transforms to the rectangle:

<Rectangle RenderTransformOrigin=”0.5,0.5″ Fill=”#FFE81E1E” 
       Stroke=”#FF000000″ x:Name=”rectangle” Width=”56″ Height=”48″
       Canvas.Left=”16″ Canvas.Top=”64″>
      <Rectangle.RenderTransform>
         <TransformGroup>
           <ScaleTransform ScaleX=”1″ ScaleY=”1″/>
           <SkewTransform AngleX=”0″ AngleY=”0″/>
           <RotateTransform Angle=”0″/>
           <TranslateTransform X=”0″ Y=”0″/>
        </TransformGroup>
     </Rectangle.RenderTransform>
</Rectangle>

And then it keeps polluting my XAML code by adding the following storyboard:

<Storyboard x:Name=”moveright”>
    <DoubleAnimationUsingKeyFrames BeginTime=”00:00:00″
            Storyboard.TargetName=”rectangle”
            Storyboard.TargetProperty=”(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)”>
          <SplineDoubleKeyFrame KeyTime=”00:00:00″ Value=”0″/>
          <SplineDoubleKeyFrame KeyTime=”00:00:02″ Value=”544″/>
   </DoubleAnimationUsingKeyFrames>
</Storyboard>

wtf??? Man, i only need a simple animation here! I guess this is what happens when you rely on a tool that has to build all sorts of animations. anyway, this sucked and i though that it was time to clean it up. I started with the xaml for the rectangle:

<Rectangle RenderTransformOrigin=”0.5,0.5″ Fill=”#FFE81E1E”
         Stroke=”#FF000000″ x:Name=”rectangle” Width=”56″ Height=”48″
         Canvas.Left=”16″ Canvas.Top=”64″>

I think we all agree that this is all that is needed, right?

Now, the cool part (which is why i”m writing this post): building the storyboard. When you look at the code blend generates, it”s obvious that it uses a TranslateTransform to change the position of the element. Again,  it”s fair to say that we don”t need that to change the position of the rectangle. The only thing we need is to change its Canvas.Left property. With this in mind, I”ve written the following code (yeah, I”ve also discarded the key frames animation 🙂 ):

<Storyboard x:Name=”moveright”>
   <DoubleAnimation To=”544″ Duration=”0:0:3″
         Storyboard.TargetName=”rectangle”
         Storyboard.TargetProperty=”Canvas.Left” />
</Storyboard>

Surprise! loading it on the browser doesn”t do anything! the rectangle didn”t even move an inch. What was i doing wrong? well, i was missing a pair of parenthesis! Here”s the correct code:

<Storyboard x:Name=”moveright”>
   <DoubleAnimation To=”544″ Duration=”0:0:3″
         Storyboard.TargetName=”rectangle”
         Storyboard.TargetProperty=”(Canvas.Left)” />
</Storyboard>

After all, sometimes the parenthesis do matter!

Jul 16

Protected: We need a new release of Siverlight right now!

Posted in Silverlight       Comments Off on Protected: We need a new release of Siverlight right now!

This content is password protected. To view it please enter your password below:

Jul 16

Today I”ve seen an interesting question on the Silverlight forum. The question was: how to change the MaxJsonLenght property of the JavaScriptSerializer object that is used on the serialization of the objects that are passed to the web service?

Answer: well, you need to use the BrowserHttpWebRequest object and create a custom JavaScriptSerializer object. Here”s a quick example. Lets start by creating a custom class that is used to return the response of an asmx web service:

public class Test
{
     private string _nome;
     private string _morada;

     public string Nome
    {
         get {  return _nome; }
         set { _nome = value; }
    }

    public string Morada
    {
        get { return _morada; }
        set { _morada = value;}
    }
}

Now, the simple web service:

[WebMethod]
[ScriptMethod]
public Test HelloWorld(string info) {
   Test t = new Test();
   t.Nome = “LKLLL”
   t.Morada = info;
   return t;
}

Pretty simple stuff…Now, the interesting stuff: the code you need to use to call the web service:

Test ret;
string path = “WebService.asmx/HelloWorld”
using (BrowserHttpWebRequest request =
       new BrowserHttpWebRequest(new Uri(path, UriKind.Relative)))
{
    request.ContentType = “application/json”
    request.Method = “POST”
    HttpWebResponse response = null;
    using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
    {
         StringBuilder str = new StringBuilder();
         str.Append(“{“);
         str.Append(“”info”:”);
         JavaScriptSerializer converter = new JavaScriptSerializer();
         converter.Serialize(“address”, str);
         str.Append(“}”);
         writer.Write(str.ToString());
         writer.Flush();
         response = request.GetResponse();
   }
   if (response.StatusCode != HttpStatusCode.OK
   {
       //check for error and inform user 
   }
   using (StreamReader reader = new StreamReader(response.GetResponseStream()))
  {
      JavaScriptSerializer converter = new JavaScriptSerializer();
      string json = reader.ReadToEnd();
      ret = converter.Deserialize<Test>(json);
      if (ret != null)
      {
          Debug.WriteLine(ret.Nome);
          Debug.WriteLine(ret.Morada);
      }
      else
     {
         Debug.WriteLine(“ret is null”);
     }
  }

}

Important things to retain from the demo sample:

  • Don”t forget to add the name of the method you”re calling to the url;
  • When you”re using JSON as the serialization format, you must set the  content type to application/json;
  • I really didn”t need to use the serializer to serialize the string; i could simply add it to the string builder but I”ve opted for using the serializer for demonstrating purposes;
  • You really need to get a reference to the response from within the StreamWriter using block;
  • Deserializing the return result is easy: you just need to get the JSON string and pass it to the generic Deserialize method.
Jul 13

In the last days I”ve been working over remote desktop and today i”ve needed to send CTRL+ALT+DEL to the remote machine. I”ve ended up discovering (by pure luck, I must say) that you get the same menu by using the combination CTRL+ALT+END…

Jul 10

Silverlight: Dowloading several images packaged on a ZIP file

Posted in Silverlight       Comments Off on Silverlight: Dowloading several images packaged on a ZIP file

One of the things you can in your Silverlight apps is package several items on a zip file and then download them through the Downloader object. Packaging several files and compressing them might increase your app”s performance, so this is something you should do whenever you can. Let”s run through a custom example. Let”s suppose we”ve got 2 pics called car.jpg and car2.jpg which are packaged on a zip file called test.zip. You can start by downloading the zip file by running the following code:

Downloader d = new Downloader();
d.Open(“GET”, new Uri(“tests.zip”, UriKind.Relative), true);
d.Completed += new EventHandler(d_Completed);
d.Send();

Now, let”s also suppose that our xaml page has an image (called img) and you want it to show the car2.jpg photo. No problem: that”s why you have the SetSource method! This method receives a downloader and a string, which lets you set the part name. The part name is used when you download a zip package and is just the name of the file from within the package you”ve just downloaded:

void d_Completed(object sender, EventArgs e)
{
    img.SetSource((Downloader)sender, “car2.jpg”);
}

Yes, that is really all you have to do!

Jun 23

Silverlight: GOA controls

Posted in Silverlight       Comments Off on Silverlight: GOA controls

A cool pack of 40+ controls for flash and silverlight. Go get them while they”re free :,,)

Jun 22

When you look at the MediaElement object, it”s obvious that it”s really easy to use when you need to play a file and you know the location of that file. When you think about it, you have several options when you want to open a movie: you can download the movie before starting to play it (using a downloader and passing it to the media element object) or you can just hook up the Source property with a specific URI. Now the problem is when you want to play a local file. Yeah, Silverlight shouldn”t let me access the user files. The problem is that you cannot get a path when you use the OpenFileDialog. You can get the name of the file or you can get the file”s contents. However, you cannot get the path to it (and I”ve even tried using reflection over it, but it failed with an exception).

Now, the problem is that the MediaElement doesn”t have any property or method that receives a stream. Now doesn”t it look like something is missing here?

Jun 21

More tutorials on Silverlight and blend

Posted in Silverlight       Comments Off on More tutorials on Silverlight and blend

Man, these topics are hot! Here”s another cool site that has some tutorials on these technologies.

Jun 21

Adding glyths to your silverlight apps

Posted in Silverlight       Comments Off on Adding glyths to your silverlight apps

Well, it ended up being easier than I though. You have two options: use the glyphs object or download the font using a downloader object and then associate it with the TextBlock object that has the text you want to show. There are already two excellent posts that show these options:

Converting the samples to managed code is so easy that I won”t put it here :,,)

Jun 20

Getting your initParams from managed code

Posted in Silverlight       Comments Off on Getting your initParams from managed code

You can use the initParams property of the Siverlight control to pass aditional infomation during the creation of the control. There”s already a property which should let you get it from managed code:StartupArguments. Unfortunately, it wil always return an empty string in the current release:

WebApplication.Current.StartupArguments

Yasser suggested a workaround for the current version untill we get a new release that lets us get the value correctly. His idea was to call a javascript method that will return that value (you need this because the InitParams is a property of the Silverlight control and in the current release there isn”t a way to get a reference to that control from managed code). Doing this means that you”ll have to:

  • build a new EventArgs class and annotate it with the Scriptable attribute
  • build a new event based on a new delegate and annotate it with the Scriptable attribute
  • annotate the class that exposes the event with the Scriptable attribute
  • register that class by calling the RegisterScriptableObject method

Lots of things for getting a string from JS code (btw, i”ve already talked about this sort of code here). So, why not simplify? I suggest just adding a string property to the class which will get called from the page. You get a little more coupling with this approach, but you reduce the code (and when you think about it, you have coupling in  both cases since things won”t work if you”re exposing an event and it doesn”t get handled by the page!). Here”s some managed demo code:

[Scriptable]
public partial class Page2 : Canvas
{
  public void Page_Loaded(object o, EventArgs e)
  {
     // Required to initialize variables
     InitializeComponent();
     WebApplication.Current.RegisterScriptableObject(“SL”, this);
  }

  private string _initParams; 
  [Scriptable]
  public string InitParams
  {
     get{return _initParams;}
     set { _initParams = value; info.Text = _initParams; }
  }
 

}

As you can guess by looking, the top canvas has a TextBlock inside that is used to show the values passed to the InitParams property. To test the page, lets o write the following JS code:

function createSilverlight()
{
     Sys.Silverlight.createObjectEx({
           source: “Page2.xaml”,
           parentElement: document.getElementById(“SilverlightControlHost”),
           id: “SilverlightControl”,
           properties: {
               width: “100%”,
               height: “100%”,
               version: “0.95”,
               background: “#ffffffff”,
               isWindowless: false,
               enableHtmlAccess: true
          },
          events: {onLoad:handleLoad},
         initParams:”testing”
      });
}

And from the handleLoad method we initialize the InitParams property:

function handleLoad(sender){
   sender.content.SL.InitParams = sender.InitParams;
}

And that”s it! Oh, there”s a small gotcha: the InitParams isn”t initialized during the load event of the top canvas object. So, if you have aditional logic that depends on that value, don”t put it on a method that handles that event. In those cases, you”ll have to tweak your code so that it”ll only run after getting a valid value for the property.

Jun 20

Cool workaround for "complex" parsing in the current Silverlight alpha version

Posted in Silverlight       Comments Off on Cool workaround for "complex" parsing in the current Silverlight alpha version

In the current alpha version you can only have “simple” properties exposed by your controls. Trying to expose a complex property ends up generating a parsing exception. This limitation has been ackowledged by the team. Here”s a cool workaround which you can use when you need to add collections of items in your control.