<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Jeff Wilcox &#187; JavaScript</title>
	<atom:link href="http://www.jeff.wilcox.name/topics/dev/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.jeff.wilcox.name</link>
	<description>Silverlight, rich client apps and web development</description>
	<lastBuildDate>Wed, 18 Aug 2010 01:33:15 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Client-side HTML controls for Silverlight 2</title>
		<link>http://www.jeff.wilcox.name/2008/10/html-controls-for-silverlight/</link>
		<comments>http://www.jeff.wilcox.name/2008/10/html-controls-for-silverlight/#comments</comments>
		<pubDate>Sun, 05 Oct 2008 21:51:10 +0000</pubDate>
		<dc:creator>Jeff Wilcox</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://www.jeff.wilcox.name/2008/10/05/html-controls-for-silverlight/</guid>
		<description><![CDATA[What if you could use and create ASP.NET-like web controls that are 100% client-side, powered by the Silverlight 2 runtime? What if ViewState was a thing of the past? Would you like to cut your web application&#8217;s load on your servers from 50 pageviews down to 0? Wouldn&#8217;t your users love it if your application [...]]]></description>
			<content:encoded><![CDATA[<p>What if you could use and create ASP.NET-like web controls that are 100% client-side, powered by the Silverlight 2 runtime? What if ViewState was a thing of the past? Would you like to cut your web application&#8217;s load on your servers from 50 pageviews down to 0? Wouldn&#8217;t your users love it if your application was always instantly responsive?</p>
<p>A week ago, I posted &quot;<a href="http://www.jeff.wilcox.name/2008/09/28/do-it-in-js-and-cs/">If you can do it in JavaScript, you can do it in managed Silverlight .NET code</a>.&quot; Here&#8217;s proof that the HTML interoperability capabilities in Silverlight are not only world-class, but also amazingly powerful.</p>
<p>This &quot;managed HTML controls&quot; <strong>concept</strong> is a neat idea: something that might whet your appetite to explore the interoperability features and consider using the feature to build sophisticated applications. However, key hurdles leave this as a conversation piece more than a new application platform. At the end of the day, the Silverlight presentation framework as it stands if going to be your best bet for a majority of your applications.</p>
<p>Exploring and thinking about changing the boundaries and status quo of web apps is something that&#8217;s fun and challenging. A client-side implementation of ASP.NET, enabling rich browser apps written in C#, was totally my dream a few years ago. Nikhil&#8217;s <a href="http://projects.nikhilk.net/ScriptSharp/Default.aspx">Script#</a> actually can get you some of the way by letting you write client apps in .NET. </p>
<p>Today, a client-side ASP.NET HtmlControl is interesting, but not a game-changer, given the maturity of JavaScript platform and the richer app platforms out there like Silverlight (that is based on WPF) and Flex.</p>
<h3>What&#8217;s the HtmlControls concept look like?</h3>
<p>Here&#8217;s a look at a few of the types.</p>
<p>By exposing strongly typed properties, methods, and events, your .NET HTML application code will be cleaner, easier to maintain, enable you to use static analysis tools, and even perform unit testing.</p>
<p><img src="http://media.jeff.wilcox.name/blog/dom/SampleClasses.png" /></p>
<p>Although the HtmlControlBase exposes a lot of the sample string-based properties as the standard Silverlight HtmlElement, it adds overloads with enumeration-based parameters (cut down on spelling errors), and stop having to duplicate strings through your app:</p>
<p><img alt="The CssAttribute enum." src="http://media.jeff.wilcox.name/blog/dom/CssAttribute.png" /> </p>
<p>You can set Font properties like you would in ASP.NET, without worrying so much about CSS at the end of the day:</p>
<p><img alt="The FontInfo object." src="http://media.jeff.wilcox.name/blog/dom/FontInfo.png" /> </p>
<p>The same goes for standard HTML properties defined by the W3C &#8211; helpful HtmlProperty enum:</p>
<p><img alt="The HtmlProperty enum." src="http://media.jeff.wilcox.name/blog/dom/HtmlProperty.png" /> </p>
<h3>Thinking about the pros and cons</h3>
<p>Some of what you can do with managed HTML controls:</p>
<ul>
<li>Create strongly typed custom controls: be more efficient, create simpler code, less spaghetti code </li>
<li>Develop rich web applications using Visual Studio, including built-in FxCop, code refactoring, the object browser, XML documentation support, and more </li>
<li>Create sophisticated AJAX-like applications with IntelliSense support </li>
<li>No need for your controls to POST-back to the server or worry about ViewState ~ these are stateful, since they are in memory </li>
<li>Integrate with Silverlight 2 applications, and all the richness it provides in its framework and class libraries </li>
<li>You could move an application like 37signals&#8217; Backpack out of a server farm, store the .Xap on a CDN, and use occassional cross-domain web service calls to store and retrieve data&#8230; imagine, some types of apps could serve a billion application users with only 1 billion .Xap downloads from your CDN, instead of generating tens of billions of web pages on an expensive web farm </li>
</ul>
<p><strong>What&#8217;s so great about it?</strong></p>
<ul>
<li>Replace loosely typed string property setters (spaghetti code) with strongly typed code </li>
<li><a href="http://projects.nikhilk.net/ScriptSharp/Default.aspx">Like Script#</a>&#8230; but with the live .NET Silverlight 2 CLR! </li>
<li>Kind of like a cheap ASP.NET implementation, on the client side, that works on Windows and Mac (IE, Firefox, Safari) </li>
<li>Proves how powerful Silverlight can be, even for out-of-the-box projects </li>
<li>Fun! </li>
</ul>
<p><strong>What are the drawbacks?</strong></p>
<ul>
<li>Silverlight has a much richer presentation story: <em>really</em> rich controls, animations, design tools like Blend, and WPF goodness. Videos. Audio. Full-screen. </li>
<li>Why build effectively an HTML-based AJAX app using Silverlight, and yet require your users to have the Silverlight 2 runtime on their machines? </li>
<li>The memory performance of this concept is probably quite bad: each element is already in the browser; there&#8217;s a pointer to that from the native platform in Silverlight; there&#8217;s the Silverlight HtmlElement object instance; and then there&#8217;s the HtmlControl type. That&#8217;s a lot of duplicated stuff! </li>
<li>The performance of the concept in general isn&#8217;t going to be too awesome: there&#8217;s a lot of interop here between the web browser, JavaScript, the browser&#8217;s plugin APIs (NPAPI or ActiveX), the managed CLR, and back again </li>
<li>All the <a href="http://www.jeff.wilcox.name/2008/09/28/do-it-in-js-and-cs/">points made here to NOT use</a> the HTML DOM bridge </li>
</ul>
<p><strong>What does it give you that you don&#8217;t get with JavaScript?</strong></p>
<ul>
<li>C#, VB, or DLR languages like Ruby running in the browser, client-side, interacting with the HTML page </li>
<li>The ability to use Visual Studio for client web development </li>
</ul>
<p>And, at the end of the day, Script# might get you these things, without the Silverlight dependency.</p>
<p><strong>What does it give you that you don&#8217;t get with Silverlight today?</strong></p>
<ul>
<li>Add managed code to existing AJAX applications and HTML elements by hooking up events and altering properties </li>
<li>Easier way to work with HTML pages than using the functional but basic HTML interop </li>
<li>Create rich HTML text editing controls and web forms; create elements for the browser&#8217;s built-in printing system </li>
</ul>
<h3>Using the HTML control framework</h3>
<p><strong>Example: Setting the width and height</strong></p>
<p>Without this framework, to set the width of an HtmlElement in Silverlight, you&#8217;d need to write this code (assumes you have a regular Silverlight HtmlElement instance called &quot;element&quot;):</p>
<div class="wlWriterSmartContent" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:e8d37199-3177-4bd7-b8ce-4eeb1a8121f8" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre class="c-sharp" name="code">// Setting the height and width - notice the typo you wouldn't know
// about until runtime:
element.SetStyleAttribute("width", "50px");
element.SetStyleAttribute("height", "450ppx");</pre>
</div>
<p>There&#8217;s no type checking: you won&#8217;t know about spelling errors or other problems until runtime, and if you do any CSS manipulation, your code will get very difficult to maintain. Here&#8217;s the same code, with a managed HTML control (using a few different ways of setting the value):</p>
</p>
<div class="wlWriterSmartContent" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:60fdaa87-916b-40b5-afd1-51e0ae4a5ccd" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre class="c-sharp" name="code">// Set the width and height of the control
control.Width = 50;
control.Height = new Unit(450, UnitType.Pixel);</pre>
</div>
<p>Same # of lines of code, but a little more &quot;attractive&quot; API.</p>
<p>You can also wrap existing HtmlElements with a managed control in some cases: either standard parts of your web page, existing AJAX applications. This is possible when the constructor exposes a HtmlElement parameter.</p>
<p><strong>Creating a composite control</strong></p>
<p>Here&#8217;s a simple &quot;user control&quot; that has a link and a button inside of it:</p>
</p>
<div class="wlWriterSmartContent" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:e5fb406f-29ea-46dc-b686-61862b03507a" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre class="c-sharp" name="code">using System;
using WebPage = System.Windows.Browser.HtmlPage;
using Microsoft.Silverlight.Testing.Html;

namespace HtmlControlSample
{
    /// &lt;summary&gt;
    /// A simple managed HTML control.
    /// &lt;/summary&gt;
    public class MyUserControl : HtmlDiv
    {
        /// &lt;summary&gt;
        /// A simple link that is hooked up to the app.
        /// &lt;/summary&gt;
        private HtmlAnchor _appLink;

        /// &lt;summary&gt;
        /// A simple button.
        /// &lt;/summary&gt;
        private HtmlButton _button;

        /// &lt;summary&gt;
        /// Initializes a new instance of the MyUserControl control.
        /// &lt;/summary&gt;
        public MyUserControl()
        {
            InitializeComponent();
        }

        /// &lt;summary&gt;
        /// Initialize composite controls and add them as children.
        /// &lt;/summary&gt;
        private void InitializeComponent()
        {
            // A link that will display the current time
            _appLink = new HtmlAnchor(
                "Click me for the time!",
                (sender, e) =&gt; Alert(DateTime.Now.ToLongTimeString()));

            _button = new HtmlButton();
            _button.InnerText = "Toggle my boldness";
            _button.Click += (sender, e) =&gt; _button.Font.Bold = !_button.Font.Bold;

            Controls.Add(_appLink);
            Controls.Add(_button);
        }

        /// &lt;summary&gt;
        /// Uses the Alert method of the HTML interoperability feature to
        /// display text.
        /// &lt;/summary&gt;
        /// &lt;param name="text"&gt;The text to display.&lt;/param&gt;
        private static void Alert(string text)
        {
            WebPage.Window.Alert(text);
        }
    }
}</pre>
</div>
<p>To hook it up to the application, here is a simple class that shrinks the Silverlight plugin to not occupy any space on the page, that creates a new instance of the MyUserControl type and appends it to the web page body.</p>
<p>The HideSilverlightPlugin function is important because it lets you press F5 while working in a standard Silverlight application project.</p>
</p>
<div class="wlWriterSmartContent" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:d2316b18-4527-4620-8fb6-6c57927ad641" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre class="c-sharp" name="code">using System;
using Microsoft.Silverlight.Testing.Html;
using WebPage = System.Windows.Browser.HtmlPage;

namespace HtmlControlSample
{
    /// &lt;summary&gt;
    /// A sample HTML application.
    /// &lt;/summary&gt;
    public class SampleHtmlApp
    {
        /// &lt;summary&gt;
        /// The application's user interface control.
        /// &lt;/summary&gt;
        private MyUserControl _myUserInterface;

        /// &lt;summary&gt;
        /// Initialize and run the application.
        /// &lt;/summary&gt;
        public static void Run()
        {
            new SampleHtmlApp();
        }

        /// &lt;summary&gt;
        /// Initializes a new instance of the SampleHtmlApp class.
        /// &lt;/summary&gt;
        private SampleHtmlApp()
        {
            HideSilverlightPlugin();

            // Creates a new managed HTML control
            _myUserInterface = new MyUserControl();

            // Appends the control to the web page body
            WebPage.Document.Body.AppendChild(_myUserInterface);
        }

        /// &lt;summary&gt;
        /// Takes the current Silverlight plugin instance and changes its size
        /// to be 0x0 pixels. Makes the same change to the hosting div element.
        /// This enables F5 testing of a managed HTML control app inside Visual
        /// Studio when using the standard TestPage.html in a Silverlight app.
        /// &lt;/summary&gt;
        private void HideSilverlightPlugin()
        {
            HtmlControl plugin = new HtmlControl(WebPage.Plugin);
            HtmlControl host = new HtmlControl(WebPage.Plugin.Parent);
            plugin.Width = 0;
            plugin.Height = 0;
            host.Width = 0;
            host.Height = 0;
        }
    }
}</pre>
</div>
<p>You can call the Run() method from anywhere in your Silverlight application &#8211; both can co-exist without issue. However, I&#8217;ve just replaced the RootVisual call in the Application_Startup method to demonstrate this example:</p>
</p>
<div class="wlWriterSmartContent" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:61ccbf1e-736d-499d-b9a7-6b4c23dd6cf9" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre class="c-sharp" name="code">        public App()
        {
            this.Startup += this.Application_Startup;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            SampleHtmlApp.Run();
        }</pre>
</div>
<p>Here is this simple HTML application (powered by Silverlight) running on OS X 10.5 in the Safari web browser:</p>
<p><img alt="The app running in Safari." src="http://media.jeff.wilcox.name/blog/dom/SafariTime.png" /> </p>
<p><strong>Appending a managed control tree to HtmlElements</strong></p>
<p>Thanks to an extension method, you can append a managed HTML control (that inherits from HtmlControlBase) to the standard HtmlElement inside Silverlight as if the control <em>is </em>an HtmlElement:</p>
<p><img alt="The extension method on HtmlElement::AppendChild." src="http://media.jeff.wilcox.name/blog/dom/ExtensionMethod.png" /></p>
<p>The managed control wrapper actually tracks any changes (styles, properties, child controls) to the control and waits until it is inserted into the live web page tree to apply the properties and create the child elements.</p>
<p>At the end of the day there are a <em>lot</em> of types involved here, bridging several layers of abstraction. This is definitely <em>not</em> a &quot;lightweight&quot; solution.</p>
<p><img alt="Looking at the abstractions." src="http://media.jeff.wilcox.name/blog/dom/HtmlObjectRelationDiagram.png" /></p>
<h3>These bits are in use today</h3>
<p>One of the key features of the in-browser <a href="http://code.msdn.microsoft.com/silverlightut/">Silverlight unit test framework</a> is that it exposes an interactive log inside the browser, using the HTML interoperability feature.</p>
<p>If you&#8217;ve used the Silverlight unit test framework, then you&#8217;ve used this managed HTML controls implementation without knowing it: to move away from &quot;spaghetti-code&quot;, we setup the log to use simple custom controls built on top of this framework.</p>
<p>Here&#8217;s a few screenshots of components, including a ProgressBar control:</p>
<p><img alt="The unit test log, powered by managed HTML controls." src="http://media.jeff.wilcox.name/blog/rc0/new_progress_bar.png" /> </p>
<p>Here&#8217;s the implementation of the ProgressBar:</p>
<div class="wlWriterSmartContent" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:68bd98dd-0560-45ef-8e4e-c10c26651ba0" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre class="c-sharp" name="code">using System;
using Microsoft.Silverlight.Testing.Html;

namespace Microsoft.Silverlight.Testing.UnitTesting.UI
{
    /// &lt;summary&gt;
    /// A control to visualize a test run's progress.
    /// &lt;/summary&gt;
    public partial class TestRunProgress : HtmlDiv
    {
        /// &lt;summary&gt;
        /// The percent of the run that is complete.
        /// &lt;/summary&gt;
        private double _percent;

        /// &lt;summary&gt;
        /// The progress bar.
        /// &lt;/summary&gt;
        private HtmlDiv _progress;

        /// &lt;summary&gt;
        /// Initializes a new progress bar control.
        /// &lt;/summary&gt;
        public TestRunProgress() : base()
        {
            InitializeComponent();
        }

        /// &lt;summary&gt;
        /// Gets or sets the percent complete on a scale from 0 to 100.
        /// &lt;/summary&gt;
        public double PercentComplete
        {
            set
            {
                _percent = value;
                UpdateProgressBar();
            }

            get
            {
                return _percent;
            }
        }

        /// &lt;summary&gt;
        /// Sets the color of the progress bar.
        /// &lt;/summary&gt;
        /// &lt;param name="value"&gt;The color value.&lt;/param&gt;
        public void SetProgressColor(string value)
        {
            _progress.BackgroundColor = value;
        }

        /// &lt;summary&gt;
        /// Updates the progress bar.
        /// &lt;/summary&gt;
        private void UpdateProgressBar()
        {
            double width = (double)GetProperty(HtmlProperty.ClientWidth);
            if (width &lt;= 0)
            {
                return;
            }
            int round = (int) Math.Round(_percent * (width / 100));
            _progress.Width = round;
        }

        /// &lt;summary&gt;
        /// Initializes the web control.
        /// &lt;/summary&gt;
        private void InitializeComponent()
        {
            SetStyleAttribute(CssAttribute.Position, "relative");
            _progress = new HtmlDiv();
            _progress.SetStyleAttribute(CssAttribute.Position, "absolute");
            _progress.Position.Left = _progress.Position.Top = _progress.Position.Bottom = 0;
            SetProgressColor(Color.Black);
            MakeTransparent(_progress, 25);
            Controls.Add(_progress);
        }

        /// &lt;summary&gt;
        /// Makes a control transparent.  Works with several browsers.
        /// &lt;/summary&gt;
        /// &lt;param name="control"&gt;The control.&lt;/param&gt;
        /// &lt;param name="opacity"&gt;The opacity amount.&lt;/param&gt;
        private static void MakeTransparent(HtmlControl control, int opacity)
        {
            control.SetStyleAttribute("filter", "alpha(opacity=" + opacity + ")");
            control.SetStyleAttribute("-moz-opacity", "." + opacity);
            control.SetStyleAttribute("opacity", "." + opacity);
        }
    }
}</pre>
</div>
<p>Clicking on a test method name expands a details drill-down full of stats and information, including links that can be clicked to retry tests and display easy-to-copy details:</p>
<p><img alt="The unit test log with details expanded." src="http://media.jeff.wilcox.name/blog/rc0/new_expander_details.png" /> </p>
<h3>Download the bits</h3>
<p>Since this is only a concept, and not something you would want to use in a production application, the bits are currently only available as part of the <a href="http://code.msdn.microsoft.com/Project/Download/FileDownload.aspx?ProjectName=silverlightut&amp;DownloadId=3274">Silverlight unit test framework download</a> for the Silverlight 2 Release Candidate 0.</p>
<p>The implementation is not a complete framework, but rather a minimal set that enables basic functionality: links, buttons, and displaying and creating HTML elements. It does not contain a rich web forms implementation, cool validation controls, or anything like that.</p>
<p>In the future I may make the concept available as a download separate from the test framework, but today I want to make it clear that it <strong>isn&#8217;t something that is ready to really be used in everyday web applications</strong>&#8230; so hopefully the total size of the test framework assembly will discourage that [81kb]!</p>
<p>It is totally unsupported, to be considered prototype code.</p>
<p>Here&#8217;s the set of types and enums in the namespace today. You&#8217;ll see that it is a minimal set, and isn&#8217;t including a lot of the typical HTML controls like check boxes, forms, or web form controls. There&#8217;s room to innovate, but the value may not be there:</p>
<p><img alt="List of types in the Microsoft.Silverlight.Testing.Html namespace." src="http://media.jeff.wilcox.name/blog/dom/TypeList.png" /> </p>
<p>Do let me know if you like it, or build anything noteworthy, in the comments, and I will post a follow up in the future.</p>
<h3>Other ideas</h3>
<p>There is potential for the concept in some apps, and I&#8217;m sure some really brilliant folks out there could do any of the following things that&#8217;ve come across my mind:</p>
<ul>
<li>Writing an ASP.NET-style XML parser using System.Xml.Linq, enabling you to embed .aspx-like pages inside your application to enable generating managed HTML control trees at runtime </li>
<li>Integrating with XAML, so a XAML page could contain a managed HTML control tree </li>
<li>Writing a compatibility layer that would allow custom ASP.NET controls to run inside Silverlight </li>
<li>Integrating or porting popular AJAX functionality (animations, rich control behaviors) </li>
<li>Writing applications that live as a .Xap file at your CDN or Amazon S3, and access cross-domain web services for any data needs, combined with isolated storage </li>
</ul>
<p>I&#8217;ve built a number of fun applications using this framework and think it&#8217;s a neat concept, I will share those sometime&#8230; </p>
<p><em>Special thanks to Hao Kung, Huangli Wu, Stefan Schackow, and Wilco Bauwer for their excellent work in shipping the amazing HTML DOM feature inside Silverlight 2!</em></p>
<p><em>Hope you find this interesting,<br />
    <br />-Jeff</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeff.wilcox.name/2008/10/html-controls-for-silverlight/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>If you can do it in JavaScript, you can do it in managed Silverlight .NET code</title>
		<link>http://www.jeff.wilcox.name/2008/09/do-it-in-js-and-cs/</link>
		<comments>http://www.jeff.wilcox.name/2008/09/do-it-in-js-and-cs/#comments</comments>
		<pubDate>Sun, 28 Sep 2008 23:23:49 +0000</pubDate>
		<dc:creator>Jeff Wilcox</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://www.jeff.wilcox.name/2008/09/28/do-it-in-js-and-cs/</guid>
		<description><![CDATA[Just because you can do something doesn&#8217;t mean that you should do something. Just because you can get Quake to run on your iPhone doesn&#8217;t mean that&#8217;s the best way to do things. But it&#8217;s pretty cool! Now that we&#8217;re clear on that one, this is the part where I show you that you can [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://media.jeff.wilcox.name/blog/rc0/JSandCSshirt.png" align="right"/> Just because you <em>can</em> do something doesn&#8217;t mean that you <em>should</em> do something. Just because you can get <a href="http://search.live.com/results.aspx?q=quake+iphone&amp;">Quake to run on your iPhone</a> doesn&#8217;t mean that&#8217;s the best way to do things. But it&#8217;s pretty cool!</p>
<p>Now that we&#8217;re clear on that one, this is the part where I show you that you can do a ton of stuff in Silverlight, through the JavaScript interoperability features.</p>
<p>Reaching out to the browser can help you improve the fit and finish of your Silverlight application and to integrate with existing services.</p>
<p>So, if you can do it in AJAX/JavaScript, you can totally do it in your Silverlight application when it is hosted in a web browser.</p>
<p>Reasons not to use the &#8220;HTML DOM bridge&#8221; (JavaScript interoperability features) in Silverlight:</p>
<ul>
<li>Feels &#8220;Hacky&#8221;  </li>
<li>Leads to spaghetti code &#8211; the calls are very procedural and you lose the nice strongly typed features of your .NET language of choice  </li>
<li>One line of JavaScript often takes 3 or 4 lines of managed code to accomplish the same thing via the interop syntax  </li>
<li>The rich presentation framework in Silverlight is pretty awesome &#8211; you should use it!  </li>
<li>Potential performance implications having JavaScript &#8211; native code &#8211; managed code all involved with timers, marshalling, etc.  </li>
<li>Can just use JavaScript without requiring the Silverlight 2 runtime</li>
</ul>
<p>Reasons to use it:</p>
<ul>
<li>Interact with the web browser host: set the page title, alter the plugin, add dynamic HTML content on the fly  </li>
<li>Bridge classic web applications, AJAX apps, and rich Silverlight  </li>
<li>Can replicate the experience of a server-side application, with web forms, HTML elements, and more &#8211; all on the client-side, without having to go back to the server to run an ASP.NET or PHP application  </li>
<li>A lot of analytics and advertising systems are exposed great in JavaScript</li>
</ul>
<p>What follows is a list of some previously covered articles and examples. They may be out of date; for instance, in the Release Candidate of Silverlight, you now use the ScriptObjectCollection instead of the HtmlElementCollection. Mike Snow has a <a href="http://silverlight.net/blogs/msnow/archive/2008/09/25/silverlight-version-2-rc0-release.aspx">nice list of the breaking changes</a>.</p>
<p><strong>Access and create JavaScript arrays from managed code</strong></p>
<p>You <a href="http://www.jeff.wilcox.name/2008/04/10/js-arrays/">can access JavaScript arrays</a>, but because of the loosely-defined, &#8220;do anything you want in JavaScript&#8221; way that things work, it leaves you with pretty unattractive managed code.</p>
<p><a href="http://www.jeff.wilcox.name/2008/04/10/js-arrays/">VB samples are here</a>. Some C# samples:</p>
<div class="wlWriterSmartContent" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:623ebebf-f579-45c6-a719-94dd7706aeda" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre class="c-sharp" name="code">// Create an array
var array = (ScriptObject) HtmlPage.Window.Eval("[10, 9, 8, 7, 6 ];");

// Get the length of an array
int length = (int)((double)array.GetProperty("length"));

// Return a single element by index
var singleElement = array.GetProperty(index.ToString())</pre>
</div>
<p><strong>Resize the Silverlight plugin</strong></p>
<p>You can <a href="http://www.jeff.wilcox.name/2008/08/24/quickzeropixel/">change the size of the plugin and its host element</a>. Here&#8217;s some Visual Basic that makes a &#8220;zero-pixel&#8221; plugin:</p>
<div class="wlWriterSmartContent" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:1caf3e27-9015-4391-904a-71a87666cecd" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre class="vb" name="code">Imports System.Windows.Browser

Namespace System.Windows.Browser
    Public Class ZeroPixelPlugin
        ''' &lt;summary&gt;
        ''' Resizes the Silverlight plugin and its host element to be zero pixels
        ''' in width and height. Only really useful for HTML
        ''' &lt;/summary&gt;
        ''' &lt;remarks&gt;&lt;/remarks&gt;
        Public Shared Sub HideSilverlightPlugin()
            Dim plugin As HtmlElement = HtmlPage.Plugin
            Dim host As HtmlElement = plugin.Parent
            plugin.SetStyleAttribute("width", "0")
            plugin.SetStyleAttribute("height", "0")
            host.SetStyleAttribute("width", "0")
            host.SetStyleAttribute("height", "0")
        End Sub
    End Class
End Namespace</pre>
</div>
<p><strong>Get information about the browser and physical screen</strong></p>
<p>Wondering what the color depth is of your end users? Want to work with the available screen size? All this information is exposed by JavaScript and you can easily read the values in C#.</p>
<p>Here&#8217;s a <a href="http://www.jeff.wilcox.name/2008/06/24/browserscreeninformation/">simple static class</a> that does the work for you. The class takes care of the differences between the NPAPI web browsers and Internet Explorer, so your application doesn&#8217;t need to worry about it so much.</p>
<p><a href="http://www.jeff.wilcox.name/2008/06/24/browserscreeninformation/"><img src="http://media.jeff.wilcox.name/blog/rc0/BrowserScreenInformationDiagram.png"/></a> </p>
<p>&nbsp;<strong>Store text in the clipboard</strong></p>
<p>If you have information that you want your end users to be able to copy into the clipboard, you only have a few options:</p>
<ul>
<li>Place the text in a TextBox control, allowing a user to select and press Control + C or Command + C to copy it into their clipboard
</li>
<li>Use interop features to talk to the web browser, or other plugins</li>
</ul>
<p><a href="http://www.jeff.wilcox.name/2008/05/21/clipboard-access/">Here&#8217;s a solution</a> that uses the browser APIs in IE, and another plugin if you&#8217;re on a non-IE browser. It isn&#8217;t perfect, but it&#8217;s an interesting hack.</p>
<p><strong>Generate an entire HTML/AJAX-style user interface</strong></p>
<p>You can write complete applications, just like an AJAX app, using managed code. Your business logic and other components benefit from strongly typed, easy-to-edit C#. Your application can be delivered through a .Xap, and doesn&#8217;t have any server side dependencies if it is written just right.</p>
<p>Here was a <a href="http://www.jeff.wilcox.name/2008/04/01/link-cloud/">homepage &#8220;link cloud&#8221; app</a>. It hasn&#8217;t been updated in a while, but most of the code should work without changes in the release candidate.</p>
<p><a href="http://www.jeff.wilcox.name/2008/04/01/link-cloud/"><img src="http://media.jeff.wilcox.name/blog/view/apps/home/safari-home.png"/></a> </p>
<p>Some of the things the app and the post show:</p>
<ul>
<li>Creating and managing HTML elements in .NET
</li>
<li>Attaching and working with HTML DOM events
</li>
<li>Using IsolatedStorage for saving information on the local machine</li>
</ul>
<p><strong>Interface with web analytics software</strong></p>
<p>A while back (yeah, Silverlight 1.1 days) I posted about <a href="http://www.jeff.wilcox.name/2007/10/01/google-analytics-with-silverlight/">interfacing with Google Analytics / Urchin</a>. Although the information is still useful, Google did make some major updates to the APIs, so I&#8217;d recommend not using the Urchin implementation in the post.</p>
<p><strong>Anything else cool?</strong></p>
<p>If you&#8217;re using the DOM bridge to do some interesting stuff, feel free to post a link here &#8211; I&#8217;d like to post about the neat uses at some point in the near future.</p>
<p>Well, I hope that gets you started working with the interop features a little more. Done right, you can start wearing a T-shirt the says &#8220;I do it in JavaScript&#8230; <em>AND</em> in .NET!&#8221;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeff.wilcox.name/2008/09/do-it-in-js-and-cs/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Storing text in the clipboard using Silverlight 2</title>
		<link>http://www.jeff.wilcox.name/2008/05/clipboard-access/</link>
		<comments>http://www.jeff.wilcox.name/2008/05/clipboard-access/#comments</comments>
		<pubDate>Wed, 21 May 2008 22:22:14 +0000</pubDate>
		<dc:creator>Jeff Wilcox</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://www.jeff.wilcox.name/2008/05/21/clipboard-access/</guid>
		<description><![CDATA[To provide users the ability to copy permalinks or store other useful information in the clipboard, there aren&#8217;t many options for web developers today.&#160; There&#8217;s no APIs inside JavaScript to access the clipboard.&#160; Here&#8217;s a solution that will at least enable this from your Silverlight 2 app for most of your users. Internet Explorer-only Clipboard [...]]]></description>
			<content:encoded><![CDATA[<p>To provide users the ability to copy permalinks or store other useful information in the clipboard, there aren&#8217;t many options for web developers today.&#160; There&#8217;s no APIs inside JavaScript to access the clipboard.&#160; Here&#8217;s a solution that will at least enable this from your Silverlight 2 app for most of your users.</p>
<h3>Internet Explorer-only Clipboard Access</h3>
<p>IE provides limited <a href="http://msdn.microsoft.com/en-us/library/ms536744(VS.85).aspx" target="_blank">clipboard support</a> in script. Using the interoperability features in Silverlight this data can be accessed.&#160; The user will be prompted to approve the clipboard access using this method.</p>
<p>Open <a href="http://media.jeff.wilcox.name/blog/sampleApps/beta1/ieClipboard/TestPage.html" target="_blank">IE Clipboard demo</a> (133k)     <br /><font color="#808080">Requires Silverlight 2 Beta 1</font></p>
</p>
<p>Here&#8217;s the static clipboard method I created to attempt to write to the clipboard.&#160; If the user denies the request, or the clipboard API is not available, an alert informs the user.&#160; A successful write to the clipboard does not result in any visual confirmation.</p>
<p><strong>Clipboard.cs</strong>:</p>
<div class="wlWriterSmartContent" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:db0442fc-7e67-4a2a-ae1f-9a75afa95f1f" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre name="code" class="c-sharp">using System;
using System.Windows.Browser;

namespace ClipboardDemo
{
    public static class Clipboard
    {
        const string HostNoClipboard = "The clipboard isn't available in the current host.";
        const string ClipboardFailure = "The text couldn't be copied into the clipboard.";

        /// &lt;summary&gt;
        /// Write to the clipboard (Internet Explorer-only)
        /// &lt;/summary&gt;
        public static void SetText(string text)
        {
            // document.window.clipboardData.setData(format, data);
            var clipboardData = (ScriptObject)HtmlPage.Window.GetProperty("clipboardData");
            if (clipboardData != null) {
                bool success = (bool)clipboardData.Invoke("setData", "text", text);
                if (!success) {
                    HtmlPage.Window.Alert(ClipboardFailure);
                }
            }
            else {
                HtmlPage.Window.Alert(HostNoClipboard);
            }
        }

    }
}</pre>
</div>
<p>In the button event handler in my demo app, I simply call the static method to write to the clipboard:</p>
<div class="wlWriterSmartContent" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:9aa0a396-6168-46aa-8356-bdaa97508207" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre name="code" class="c-sharp">        private void Go_Click(object sender, RoutedEventArgs e)
        {
            Clipboard.SetText(ClipboardText.Text);
        }</pre>
</div>
<h3>Cross-browser, cross-platform solution</h3>
<p>Now, this one&#8217;s a little interesting: since Flash does have clipboard access, you can actually use it from the web browser (JavaScript) or even Silverlight 2 (HTML DOM bridge) to enable a cross-browser, cross-platform clipboard copy function.&#160; It&#8217;s a hack, but does get the job done.</p>
<p>I think there&#8217;s enough space in the world&#8217;s hard drives for both Flash and Silverlight on every computer!</p>
<p>Open <a href="http://media.jeff.wilcox.name/blog/sampleApps/beta1/allClipboard/TestPage.html" target="_blank">Cross-browser, Cross-platform Clipboard demo</a> (133k) </p>
<p><font color="#808080">Requires Silverlight 2 Beta 1</font></p>
<p>To do this, I&#8217;ll be using the Flash component that ships with the <a href="http://code.google.com/p/syntaxhighlighter/" target="_blank">syntaxhighlighter</a> tool created by Alex Gorbatchev.&#160; By simply adding a new Flash embed to the page and referencing his clipboard.swf Flash movie file, the Flash API will then attempt to write the proper data into the clipboard.</p>
<p>The implementation I&#8217;ve done here isn&#8217;t super robust: if the user doesn&#8217;t have Flash, there&#8217;s no error message for instance.&#160; If the user&#8217;s browser is Internet Explorer, or implements the clipboardData API, then the Flash workaround will not be used.</p>
<p>Here&#8217;s the expanded Clipboard.cs.&#160; Do note, I&#8217;m hard-coding the clipboard.swf location, so make sure you&#8217;re using a valid path on your server.</p>
<p><strong>Clipboard.swf:</strong></p>
<p>Make sure to download this file (here <a href="http://code.google.com/p/syntaxhighlighter/" target="_blank">syntaxhighlighter</a>) and store it in the same directory as your application.</p>
<p><strong>Clipboard.cs</strong>:</p>
<div class="wlWriterSmartContent" id="scid:887EC618-8FBE-49a5-A908-2339AF2EC720:72e1618b-d3bc-4ac1-afde-0a4cd084352a" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<pre name="code" class="c-sharp">using System;
using System.Windows.Browser;

namespace ClipboardDemo
{
    public static class Clipboard
    {
        const string HostNoClipboard = "The clipboard isn't available in the current host.";
        const string ClipboardFailure = "The text couldn't be copied into the clipboard.";
        const string BeforeFlashCopy = "The text will now attempt to be copied...";
        const string FlashMimeType = "application/x-shockwave-flash";

        // HARD-CODED!
        const string ClipboardFlashMovie = "clipboard.swf";

        /// &lt;summary&gt;
        /// Write to the clipboard (IE and/or Flash)
        /// &lt;/summary&gt;
        public static void SetText(string text)
        {
            // document.window.clipboardData.setData(format, data);
            var clipboardData = (ScriptObject)HtmlPage.Window.GetProperty("clipboardData");
            if (clipboardData != null) {
                bool success = (bool)clipboardData.Invoke("setData", "text", text);
                if (!success) {
                    HtmlPage.Window.Alert(ClipboardFailure);
                }
            }
            else {
                HtmlPage.Window.Alert(BeforeFlashCopy);

                // Append a Flash embed element with the data encoded
                string safeText = HttpUtility.UrlEncode(text);
                var elem = HtmlPage.Document.CreateElement("div");
                HtmlPage.Document.Body.AppendChild(elem);
                elem.SetProperty("innerHTML", "&lt;embed src=\"" +
                    ClipboardFlashMovie + "\" " +
                    "FlashVars=\"clipboard=" + safeText + "\" width=\"0\" " +
                    "height=\"0\" type=\"" + FlashMimeType + "\"&gt;&lt;/embed&gt;");
            }
        }

    }
}</pre>
</div>
<p>Hope this helps!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeff.wilcox.name/2008/05/clipboard-access/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Accessing JavaScript arrays using the HTML DOM interop</title>
		<link>http://www.jeff.wilcox.name/2008/04/js-arrays/</link>
		<comments>http://www.jeff.wilcox.name/2008/04/js-arrays/#comments</comments>
		<pubDate>Fri, 11 Apr 2008 01:07:07 +0000</pubDate>
		<dc:creator>Jeff Wilcox</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://www.jeff.wilcox.name/2008/04/10/js-arrays/</guid>
		<description><![CDATA[The documentation on the HTML DOM interoperability feature is definitely a little sparse today, but with the Beta 1 release of Silverlight 2, the APIs are very useful for getting a lot done.&#160; Since we went for parity with JavaScript, it’s a super rich way to interact with existing AJAX controls and the web browser. [...]]]></description>
			<content:encoded><![CDATA[<p>The documentation on the HTML DOM interoperability feature is definitely a little sparse today, but with the Beta 1 release of Silverlight 2, the APIs are very useful for getting a lot done.&nbsp; Since we went for parity with JavaScript, it’s a super rich way to interact with existing AJAX controls and the web browser.</p>
<p>A very common request I hear is “how in the world do I access elements in a JavaScript array in managed code” ?</p>
<p>Since a JavaScript array is just a JavaScript object, and the array indices are just numbered properties, that means GetProperty is your answer.</p>
<h3>Create a JavaScript array</h3>
<p>Use the Eval method on the window to create a new array in JavaScript.&nbsp; The ScriptObject reference allows you to interact with it:</p>
<p>C# <br /><img src="http://media.jeff.wilcox.name/blog/dom/js1.png"/>&nbsp;</p>
<p>VB <br /><img src="http://media.jeff.wilcox.name/blog/dom/js1vb.png"/> </p>
<h3>Get a JavaScript array’s length</h3>
<p>C# <br /><img src="http://media.jeff.wilcox.name/blog/dom/js2.png"/> </p>
<p>VB <br />&nbsp;<img src="http://media.jeff.wilcox.name/blog/dom/js2vb.png"/> </p>
<h3>Return a single element</h3>
<p>Individual elements are stored as numbered properties, just use GetProperty with the index of interest to retrieve an element:</p>
<p>C# <br /><img src="http://media.jeff.wilcox.name/blog/dom/js3.png"/> </p>
<p>VB <br /><img src="http://media.jeff.wilcox.name/blog/dom/js3vb.png"/> </p>
<p>A key developer in the Silverlight project for bringing this code is <a href="http://www.wilcob.com/">Wilco Bauwer</a>, his first post on the <a href="http://www.wilcob.com/wilco/News/silverlight-interoperability.aspx">HTML DOM interop</a> is <a href="http://www.wilcob.com/wilco/News/silverlight-interoperability.aspx">here</a>.&nbsp; </p>
<p>Hope this helps!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeff.wilcox.name/2008/04/js-arrays/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Homepage &#8220;link cloud&quot; application</title>
		<link>http://www.jeff.wilcox.name/2008/04/link-cloud/</link>
		<comments>http://www.jeff.wilcox.name/2008/04/link-cloud/#comments</comments>
		<pubDate>Wed, 02 Apr 2008 02:38:30 +0000</pubDate>
		<dc:creator>Jeff Wilcox</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[cloud]]></category>
		<category><![CDATA[dom]]></category>
		<category><![CDATA[html dom bridge]]></category>
		<category><![CDATA[link]]></category>
		<category><![CDATA[link cloud]]></category>
		<category><![CDATA[silverlight 2]]></category>

		<guid isPermaLink="false">http://www.jeff.wilcox.name/2008/04/01/link-cloud/</guid>
		<description><![CDATA[My new browser start page uses Silverlight to produce a simple link cloud.&#160; By targeting the rich class libraries of .NET that are available in Silverlight 2, the app loads quicker than a server-based solution, is useful, and very simple.&#160; The app I built is a good demonstration of the “zero pixel” Silverlight plugin concept: [...]]]></description>
			<content:encoded><![CDATA[<p>My new browser start page uses Silverlight to produce a simple link cloud.&nbsp; By targeting the rich class libraries of .NET that are available in Silverlight 2, the app loads quicker than a server-based solution, is useful, and very simple.&nbsp; The <a href="http://media.jeff.wilcox.name/apps/home/index.htm">app</a> I built is a good demonstration of the “zero pixel” Silverlight plugin concept: I’m using the HTML DOM bridge to create and manage all of the elements in the web page document.</p>
<p>The app has some key features:</p>
<ul>
<li>No dependencies on a web server, web service, or database server  </li>
<li>Links are true HTML links that get larger the more often they’re clicked.&nbsp; They can be added, removed, and rearranged  </li>
<li>Stores the link information locally, available to all browsers on the platform  </li>
<li>The data is yours: you can import/export the raw data to easily bring it to another of your computers</li>
</ul>
<p>Special thanks to <a href="http://d-struct.org/">Chris Gansen</a> for letting me borrow the specifics from his <a href="http://www.rubyonrails.org/">RoR</a> implementation of this application, it translated nicely to a client app.</p>
<p><a href="http://media.jeff.wilcox.name/apps/home/index.htm"><strong>Experience this application</strong></a><strong> live.</strong>&nbsp; <br />Since the local isolated storage is used, the links are only on your machine, the first time you use the app it’ll have no links.&nbsp; <a href="http://media.jeff.wilcox.name/apps/home/SampleData.txt">Click here</a> for a text file you can paste in using the import/export feature to load a set of sample links.&nbsp; I store my link cloud in <a href="http://mail.google.com/">GMail</a> so that I can always setup another machine in seconds from my mail account.</p>
<p><a href="http://media.jeff.wilcox.name/apps/home/index.htm"><img src="http://media.jeff.wilcox.name/blog/view/apps/home/safari-home.png"/></a></p>
<p>The .Xap file that represents the app is a miniscule 10kb.&nbsp; By comparison, a server-side version of this app can easily serve 40kb pages once the editing interface is included.&nbsp; The only hard-coded dependency is the stylesheet link that I’m injecting at runtime.</p>
<p>This uses many of the less sexy Silverlight 2 Beta 1 features:</p>
<ul>
<li><a href="http://msdn2.microsoft.com/en-us/library/system.windows.browser(VS.95).aspx">HTML DOM</a> interoperability: the bridge between managed code and the web browser, the entire underlying user interface is generated and managed by managed code  </li>
<li>Local <a href="http://msdn2.microsoft.com/en-us/library/system.io.isolatedstorage(VS.95).aspx">isolated storage</a>: By storing the data on the local machine, there&#8217;s no complex web service or database required  </li>
<li><a href="http://msdn2.microsoft.com/en-us/library/system.io.isolatedstorage.applicationsettings(VS.95).aspx">ApplicationSettings</a>: An easy-to-use way of storing data to the isolated storage area, there&#8217;s no need to deal with StringReaders and Stream manipulation code  </li>
<li>Zero pixel 0&#215;0 plugin: By resizing the Silverlight plugin to occupy no space upon load, the application demonstrates the capabilities of managed code without the use of controls and the rich presentation framework  </li>
<li>.Xap package is easy to deploy and store on a content delivery network, file or web server</li>
</ul>
<p>Although I’m using ApplicationSettings type to store the link cloud data, I just wanted to get this up and running, so I’m not following any best practices, and am actually serializing the cloud data myself into a single string.</p>
<p><strong>Downloads</strong><br /><a href="http://media.jeff.wilcox.name/apps/home/index.htm">Live app</a> (10k) – feel free to use this for your homepage<br /><a href="http://media.jeff.wilcox.name/apps/home/SampleData.txt">Sample data file</a> (2k) – can import for sample data<br /><a href="http://media.jeff.wilcox.name/apps/home/LinkPage.zip">Source code</a> (39k) – Zip file with the Visual Studio project, just barebones code, no good code in here<br /><a href="http://media.jeff.wilcox.name/apps/home/LinkPage.cs.txt">LinkPage.cs</a> (21k) – Primary source file</p>
<p>Briefly jumping into the code, you’ll find that everything’s really contained inside <a href="http://media.jeff.wilcox.name/apps/home/LinkPage.cs.txt">LinkPage.cs</a>.&nbsp; Some of the things inside the file that I’d like to call out:</p>
<h3>Setting the page title</h3>
<p><img src="http://media.jeff.wilcox.name/blog/linkcloud/lc1.png"/> </p>
<p>This updates the title displayed in the browser’s window.&nbsp; It’s equivalent to the simple JavaScript call of setting document.title.&nbsp; The <a href="http://msdn2.microsoft.com/en-us/library/system.windows.browser.htmldocument(VS.95).aspx">HtmlDocument</a> type, in the System.Windows.Browser namespace, maps directly.</p>
<h3>Reading from ApplicationSettings and changing the &lt;body /&gt; element’s CSS class</h3>
<p><img src="http://media.jeff.wilcox.name/blog/linkcloud/lc2.png"/> </p>
<p>The <a href="http://msdn2.microsoft.com/en-us/library/system.io.isolatedstorage.applicationsettings(VS.95).aspx">ApplicationSettings type</a> is a nice shortcut to having to use Isolated Storage, and is used to store two settings for this link cloud application: the color used for the stylesheet (there’s a few themes available), and the actual link cloud data.&nbsp; The data’s updated and saved whenever a change occurs to avoid having to write the changes at one time.</p>
<h3>Injecting a Stylesheet element</h3>
<p><img src="http://media.jeff.wilcox.name/blog/linkcloud/lc3.png"/> </p>
<p>Pretty standard document object model workflow here: the code’s nothing but spaghetti.&nbsp; The new element is created, attributes set, and then appended.&nbsp; There’s no need to keep a reference to the element unless you intend on interacting with it later.</p>
<p>There’s a built-in property HtmlPage.Document.Body that can be used to return the &lt;body /&gt; element on the web page, but not one for the &lt;head /&gt; element.&nbsp; The code above successfully will add to the head of the page, assuming the head exists.</p>
<h3>Prompting the user for confirmation</h3>
<p>A lot of AJAX applications use ‘confirm(…)’ to get quick verification before deleting data permanently.&nbsp; Both <a href="http://msdn2.microsoft.com/en-us/library/system.windows.browser.htmlwindow.alert(VS.95).aspx">Alert</a> and <a href="http://msdn2.microsoft.com/en-us/library/system.windows.browser.htmlwindow.confirm(VS.95).aspx">Confirm</a> are available within the HtmlWindow type in the HTML DOM bridge, so it’s super easy to do the same in managed code:</p>
<p><img src="http://media.jeff.wilcox.name/blog/linkcloud/lc5.png"/> </p>
<h3>Navigating to a new web page</h3>
<p><img src="http://media.jeff.wilcox.name/blog/linkcloud/lc6.png"/> </p>
<p>The links in the link cloud have the href attribute set to point to the destination page – this enables the end user to open the links in a new tab or window easily.&nbsp; However, the click count is only incremented when the link is clicked since the onclick event is used to track and increment the underlying hit data.</p>
<p>The <a href="http://msdn2.microsoft.com/en-us/library/system.windows.browser.htmlwindow.navigate(VS.95).aspx">Navigate</a> method of <a href="http://msdn2.microsoft.com/en-us/library/system.windows.browser.htmlwindow(VS.95).aspx">HtmlWindow</a> is used to go to the requested URI.</p>
<h3>Creating an HTML button and hooking up to its Click event</h3>
<p>The form that’s created on the page uses managed event handlers in C# to process events and read data:</p>
<p><img src="http://media.jeff.wilcox.name/blog/linkcloud/lc4.png"/> </p>
<p>The button above is used to add the form data into the cloud as a new link.&nbsp; If you examine it you’ll also see use of SetProperty, SetStyleAttribute, GetProperty, and more – these are all at parity with traditional AJAX JavaScript coding, so it should be quite familiar.&nbsp; </p>
<p><a href="http://www.wilcob.com/Wilco/News/silverlight-interoperability.aspx">Wilco</a> has a lot <a href="http://www.wilcob.com/Wilco/News/silverlight-interoperability.aspx">more information</a> on the subject of the HTML DOM interoperability feature in Silverlight 2.</p>
<p><a href="http://media.jeff.wilcox.name/apps/home/index.htm"><img src="http://media.jeff.wilcox.name/blog/view/apps/home/ie-home.png"/></a> </p>
<p><em>Hope you find this useful!</em></p>
<p><em>Looking at the spaghetti code, it’s clear that some kind of helpful “managed HTML object” library would make creating this style of application a lot easier in the future.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeff.wilcox.name/2008/04/link-cloud/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Book Review: Pro JavaScript Design Patterns by Harmes and Diaz</title>
		<link>http://www.jeff.wilcox.name/2008/01/book-review-pro-javascript-design-patterns-by-harmes-and-diaz/</link>
		<comments>http://www.jeff.wilcox.name/2008/01/book-review-pro-javascript-design-patterns-by-harmes-and-diaz/#comments</comments>
		<pubDate>Mon, 28 Jan 2008 09:39:37 +0000</pubDate>
		<dc:creator>Jeff Wilcox</dc:creator>
				<category><![CDATA[Books]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[code design]]></category>
		<category><![CDATA[design patterns]]></category>

		<guid isPermaLink="false">http://linux.jeff.wilcox.name/2008/01/28/book-review-pro-javascript-design-patterns-by-harmes-and-diaz/</guid>
		<description><![CDATA[I recently completed a relatively quick read through Pro JavaScript Design Patterns by Ross Harmes and Dustin Diaz (ISDN-13 978-1590599082). It’s definitely one of those books that I’m happy to have read through; I’m always amazed by the flexibility of JavaScript as a language, and believe anyone not familiar with the intricacies of object-oriented JavaScript [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.amazon.com/gp/product/159059908X?ie=UTF8&amp;tag=jwilcoxblog-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=159059908X"><img src="http://media.jeff.wilcox.name/blog/view/books/jsdesignpatterns.png" alt="Pro JavaScript Design Patterns" align="right" border="0" height="240" width="180" /></a>I recently completed a relatively quick read through <a href="http://www.amazon.com/gp/product/159059908X?ie=UTF8&amp;tag=jwilcoxblog-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=159059908X" title="Pro JavaScript Design Patterns at Amazon.com">Pro JavaScript Design Patterns</a> by Ross Harmes and Dustin Diaz (ISDN-13 978-1590599082).  It’s definitely one of those books that I’m happy to have read through; I’m always amazed by the flexibility of JavaScript as a language, and believe anyone not familiar with the intricacies of object-oriented JavaScript should pick this up.  It also doesn’t dive into any AJAX or domain-specific coverage, making this feel a little less like a Web 2.0 book.</p>
<p>For everyone who appreciates the classic <a href="http://www.amazon.com/gp/product/0201633612?ie=UTF8&amp;tag=jwilcoxblog-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0201633612">Gang of Four book</a>, you’ll find helpful and interesting implementations of the basics, such as Observer, Adapter, and even Flyweight, in this book; a way to mimic interfaces for JavaScript, and the best rundown of encapsulation, inheritance, and OOP JS that I’ve seen in a book recently.</p>
<p>The application of the GOF patterns to JS is a sticky subject for many; with the speed that web sites and their software platform are revised, a more dynamic language like JS provides a chance to escape patterns for some.  This book won&#8217;t help you solve that question, but it&#8217;ll give you good implementations and serve as ideal JavaScript code for anyone looking to spruce up their skills.  Unlike a strongly typed language, part of the patterns implementation is going to be you communicating with your peers on how to actually go about consuming and publishing JS components in your product.</p>
<p>This also covers a lot of topics that aren’t stressed to JavaScript and AJAX developers on day one: methods being first class citizens, the importance of closures, and just how amazing JavaScript can be.  I’d have to say that Chapter One, titled “Expressive JavaScript,” but each pattern-oriented chapter does a great job of covering the reasons for its need, multiple implementations, and an honest pro/con comparison.</p>
<p>Sour (stingy me?) point: as this was on my personal weekend reading list, value comes to mind: As with many of the shorter niche tech books these days, I find myself put off some by the $44.99 list price for just under 260 pages of content.  By comparison, the very concise and in-depth <a href="http://www.amazon.com/gp/product/1590598849?ie=UTF8&amp;tag=jwilcoxblog-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=1590598849">Pro C# 2008 and the .NET #.5 Platform</a> by Andrew Troelsen lists at a fair $59.99 for 1,370 pages of awesome content. Granted, both books can be had for less from any book discounter, and Apress offers an eBook format for $23.</p>
<p>Some of the books&#8217; content from the publisher:</p>
<ul>
<li><a href="http://www.apress.com/book/downloadfile/3862">Table of Contents</a> [Apress.com]</li>
<li><a href="http://www.apress.com/book/downloadfile/3861">Chapter 1 &#8211; Expressive JavaScript</a> [Apress.com]</li>
</ul>
<p>Hope this helps!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeff.wilcox.name/2008/01/book-review-pro-javascript-design-patterns-by-harmes-and-diaz/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
