Sunday, January 3, 2010

Silverlight and JavaScript interaction

In Silverlight business applications, we may need to pass data to the Silverlight control.  If the volume of data is not big, we can consider using Silverlight HTML Bridge to communicate between JavaScript and Silverlight. This post summarizes how to call JavaScript from Silverlight and vice versa.

Silverlight HTML Bridge is the technology that enables to call 
JavaScript from Silverlight managed code and call Silverlight managed code from JavaScript.  The following example will use some simple code to demonstrate the 2 parts and point out some usual difficulties developers may encounter.

Call Silverlight from JavaScript

In the test.aspx file, I have the following form: 
  
    <form id="form1" runat="server" style="height:100%;">
        <asp:ScriptManager ID="ScriptManager1" runat="server">                          </asp:ScriptManager>
        <div>
            <input type="button" value="Start Silverlight" onclick="startSilverlight();" />
            <input type="hidden" id="hiddenString" value="0.85,0.78,0.10,0.12,0.90" />
        </div>
        <div style="height:100%;">
            <asp:Silverlight ID="Xaml1" Visible="true" runat="server" Source="~/ClientBin/SilverlightTest.xap"                             MinimumVersion="2.0.31005.0" Width="100%" Height="100%" />
        </div>

    </form>

And I also have the following JavaScript in the same page: 
<script type="text/javascript" language="javascript">
    function startSilverlight() {
        var plugin = document.getElementById("Xaml1");
        if (plugin == null) {
            alert("xaml1 is null");
            return;
       
}
        var strControl = document.getElementById("hiddenString");
       
var str = strControl.value;
        plugin.Content.Page.StartShow(str);
    }

</script>

In Silverlight, the code-behind file contains the following code:
    [ScriptableType]
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();
            HtmlPage.RegisterScriptableObject("Page", this);
        } 
        [ScriptableMember]
        public void StartShow(string data)
        {
            char[] charSeparators = { ',' };
            string[] result;
            result = data.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);
            float values[] = new float[result.Length];
            int i = 0;
            foreach (var str in result)
            {
                values[i++] = float.Parse(str);
            } 
            UpdateLayout(values);
        }
    }

When users click the button on test.aspx page, the hidden text can be passed to Silverlight.

Call JavaScript from Silverlight

In test.aspx, I added
<script type="text/javascript" language="javascript">
    function getSilverlightValue(text) {
        alert(text);
    }

</script>

In Silverlight code-behind file, use HtmlPage to call the function: 
    HtmlPage.Window.Invoke("getSilverlightValue", "A test string");

Final Words

This is all the things related with how JavaScript and Silverlight interact. However, what I want to point out here is this convenient method may have some performance issues when you want to pass high volume of data to Silverlight.  In my real project, I passed over 30 Mega pure data to Silverlight and I needed to parse the data, so the data needed over 10 seconds to be fully displayed.  Some users may not want this experience.  If that's the case, you may seek help from WCF to retrieve data in an asynchronous way.


Sunday, October 25, 2009

Set the DefaultFocus and DefaultButton in a master page

From ASP.NET 2.0 it is possible to set the default focus and default button with the DefaultFocus and DefaultButton properties which HtmlForm has.  DefaultFocus sets which control to get the default focus in a form, and DefaultButton decides which button will fire the click event when users hit the enter key.  In a page which uses a master page, you know the control name will be added a prefix string like ctl00_ContentPlaceHolder1_.

My example form has one EditBox named txtName and one Button named btnView.  If I use the following code in the Page_Load event:

Page.Form.DefaultButton = btnView.ID;
or
Page.Form.DefaultButton = "btnView";

I get the following error:
The DefaultButton of 'form1' must be the ID of a control of type IButtonControl.

The reason is the control name is changed in a master page.  So we have to use the following one in this case:
Page.Form.DefaultButton = btnView.UniqueID;

But for DefaultFocus, UniqueID seems not working for me.  I have to use ClientID instead of UniqueID:
Page.Form.DefaultFocus = txtName.ClientID;

An alternative is use Focus() method.  You could use the following to get the same effect as the above one:
txtName.Focus();

Sometimes you may want 2 or more default buttons on one page.  This can be implemented by putting asp:Panel control around the controls.  In the following example, when the cursor is in TextBox1, Button1 is the default button, otherwise when the cursor is in TextBox2, Button2 is the default button. 

<asp:Panel ID="Panel1" DefaultButton="Button1" runat="server">
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</asp:Panel>
<br />
<asp:Panel ID="Panel2" DefaultButton="Button2" runat="server">
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
    <asp:Button ID="Button2" runat="server" Text="Button" onclick="Button2_Click" />
</asp:Panel>

Tuesday, October 13, 2009

Tech Days Toronto 2009

Tech Days Toronto came again. This year it was held one month early, on Sep. 29 and 30, 2009 at Metro Toronto Convention Centre, Downtown Toronto. It's said there were more people (1200 comparing to 1000 last year) attending the conference. It looks like the recession didn't affect companies' budget. :) I like the time and venue of this year. I didn't have to drive in the highway in the rush hour as last year. The time was one month earlier than last year, and Toronto was still warm.

Again this year all the presenters were from the partners of Microsoft, many of which had direct development and project experience. Several of them also presented in last year's Tech days. The good thing is the overall presentation skills of speakers are better than last year. In all 8 sessions (plus one bonus session) I attended, the speakers all had good presentation skills, and the materials were well prepared.

Let's talk about the sessions. In my opinion, this year is better than last year. Especially I like the added Developer Foundations track, which they said is coming from the feedback of many developers. This track was talking about some topics which could bring the developers to another level. One example was the five OO design principles. Of course we cannot expect too much from just 1 hour and 15 minutes (the total time of a session). The thing is you could get some ideas from other developers, and grasp a chance to practice in your own software development.

Except the Developer Foundations track, I mainly took some sessions for developers on Microsoft-based platform, such as Silverlight 3, Expression Blend for Developers and Prism. What I got from the sessions can be summarized as follows:
  1. As Silverlight or WPF developers, we have to use Expression Blend in design time. It's impossible to write complex XAML tags in Visual Studio. Although developers usually don't like the design work, Expression Blend can save you tons of time when you need a complex XAML file, i.e. a multi-dimension animation.
  2. Silverlight 3 adds some new features, one of which is mouse wheel event support. Previously I created my own mouse wheel event handler. I need to check if the new features make the development easier.
  3. I heard several times about Prism and ASP.NET MVC, but I just don't know if they are practical and effective in real business projects. I will spend some time to investigate these frameworks and see if they can improve my projects.
  4. The best practise for developers is to get to know broadly any relative technologies. Some Java techniques could help .NET developers create a good design. Although I had experience in some other fields (except .net and c++) like Java, Mobile development, BI, I need some time to update my knowledge.

Wednesday, January 14, 2009

Using XSLT to display XML files in a rich way

Recently I worked on several projects related with XML and created several XSLT files to display the XML files. In this article I will summarize a variety of ways to render XML files using XSLT.

XSL stands for eXtensible Stylesheet Language, which includes 3 interrelated parts: XSLT, XPath, and XSL-FO. The reason W3C separated XSL to 3 parts is users can re-use some parts with other technologies. For example, XPath can work together with XPointer syntax, while XSLT can be used in Microsoft Office suite to represent data.

XSLT is XSL transformation, a language for transforming XML documents. In the transformation process, XSLT uses XPath to navigate through the XML files. So in order to write XSLT code, you have to know XPath syntax first.

This article will focus on how XSLT can help display XML files in browsers and other applications, and how XSLT can help display the XML files in a rich way.


Open XML files in Browsers directly


When you want to open a XML file in browsers directly, probably you just can view the tree structure of the XML file. However, if you add the following reference in the XML file, the XML file can use the test.xsl file to display itself.
<?xml-stylesheet type="text/xsl" href="test.xsl"?>

You have to create your xslt file test.xsl to let browsers know how to present the xml data.

Open XML files in Microsoft Excel

When you open a XML file which doesn’t have a XSLT file related with in Microsoft Excel, Excel will pop up a dialog to provide 3 options to choose the way to open. In my case, all the 3 options are not good for me. I preferred to open the XML file with a XSLT file. When the above “xml-stylesheet” statement is added to the original XML file, Excel will pop up a dialog to ask if you want to open the XML file with the specified stylesheet. When you click “OK”, Excel can display the XML file in a way similarly with a browser.

You can add more than one “xml-stylesheet” statement in a XML file. When you do this, Excel will ask which XSLT file you will use while opening. You can create several XSLT files, and give users more options. In my case, I created one xslt file which can provide colourful layout, and another one which can separate the data to different tables.

Open XML files on the client

The previous examples use “xml-stylesheet” reference line to tell the applications where the xslt file is. It is applications that do the transformation, that is, browsers and Excel. The disadvantage of this approach is you have to add this reference line to the destination XML file by yourself. Another disadvantage is sometimes the application is non XSLT aware.

You can write some JavaScript code to do the transformation on the client. The following is a very simple test html file which can only be used for Microsoft IE. For other browsers, you can easily find some examples from internet.

<html>
<body>
<script type="text/javascript">
// Load XML
var xml = new ActiveXObject("Microsoft.XMLDOM")
xml.async = false
xml.load("test.xml")
// Load XSL
var xsl = new ActiveXObject("Microsoft.XMLDOM")
xsl.async = false
xsl.load("test.xsl")
// Transform
document.write(xml.transformNode(xsl))
</script>
</body>
</html>

Open XML files on the server

If you have experience working on server to send back HTML to client, you must know the famous Response.Write() function. In order to open XML files on the server, what you need to do is to write back the transformed XML file to client. The following is a simple example:

xml = Server.CreateObject("Microsoft.XMLDOM")
xml.async = false
xml.load(Server.MapPath("test.xml"))

xsl = Server.CreateObject("Microsoft.XMLDOM")
xsl.async = false
xsl.load(Server.MapPath("test.xsl"))

Response.Write(xml.transformNode(xsl))

ASP.Net has a new class library to do the transformation, but it is very similar to this code.

Add styles to a XSLT file

Since a XSLT file transforms a XML file to a XHTML file, you can use any XHTML style in the XSLT file. The following is an example to display a XML file in a customized table and add color property to cells.
<table style="border: 1px solid #000000; font-family: Tahoma; font-size: 9pt; width: 100%">
<tr style="color:#333333;background-color:#cccccc;">
<td style="background-color:{Book[1]/@color}">
<xsl:value-of select="Book[1]"/>
</td>
</tr>
</table>

Other XSLT techniques

XSLT has a powerful function called document(), which can combine several documents together to display in one page. In my project, I used this function to display a tabbed page which had the paging feature. The layout is like the following:


Then you can switch among 4 views. The 4 views display different content from the same XML document. Within one view, users can navigate through all the pages. Of course if you are a JavaScript guru, you can construct more compelling layout and different paging style.

Sunday, November 2, 2008

Microsoft Tech Days Toronto 2008

Microsoft Tech Days 2008 Toronto was held on Oct. 29 and 30 at Toronto Congress Center. Toronto is the first stop of this Microsoft Canada’s technical education conference series, which will go on to Montreal, Ottawa, etc across Canada in the next 3 months. As a developer working with Microsoft technologies, I had a chance to participate in this 2-days event and attended several training sessions for Windows developer and Web developer, even one for database.

The big difference for this event was that it was no longer for free. You need to pay $499.99 (early bird discount $249.99) for the admission. Microsoft said it was not free because this event targeted at education not marketing purpose. Moreover, attendees can get a Tech Days learning kit worth about $1000 (if it is really valuable for you), including a full version of Visual Studio 2008 Professional.

Although Microsoft stated that this event was not a marketing tour, most of the sessions were about new technologies, even some latest versions being launched 2 days ago. From my communication with other developers, I could see most of the developers and companies were just watching those new stuff. Companies are very carefully to take a stand on a new technology because that means a lot of investments and less support, and you cannot rely on a stable version in quite a while.

The good thing for Microsoft was although this was not a free event, it still allured so many people, over one thousand by estimate, to flock together to enjoy the new technologies and collect new information.

Let’s talk about the sessions. Among the 8 sessions I attended, including 4 for Windows development, 3 for Web development and 1 for data management, some of them were pretty impressive. For instance, “Mastering Your Samurai Skills of Silverlight” not only showed the great features of the latest version of Silverlight and what beautiful stuff the tools could build, but demonstrated the simple start-up process a beginner can take. Some sessions about WPF, such as one from MVP Barry Gervin, were attractive as well. The presentations were well prepared and most of the speakers had rich experience and good presentation skills.

As it was told, most of the speakers were not from Microsoft, but from other companies. That is good in that it could bring the audience real experience. However, this cannot guarantee good quality. To be honest, not all presentations were worth the money and time you spent.

Later on we will plan our next software version. I hope what we got from the conference could help us make a good choice.