Welcome!

Silverlight Authors: Automic Blog, Michael Kopp, Jyoti Bansal, Kaazing Blog, Steven Mandel

Related Topics: Silverlight, Java IoT, Microsoft Cloud, Machine Learning

Silverlight: Article

Getting Started with Silverlight: Zero to Hero

What you need to do to get up and running with Silverlight quickly

Lots of people have been asking about how to get started with Silverlight, and what they need to do to get up and running with Silverlight quickly. Inspired by blog posts such as Jesse Liberty's, I'm going to take this from first principles, with no prior knowledge assumed.

Over the series, we'll look at the following:

  • Your First Silverlight Application
  • Understanding XAML
  • Understanding the Blend series of Products
  • Building Silverlight applications using Aptana on the Mac
  • Building Silverlight applications using Visual Studio Express on the PC
  • Programming Silverlight 1.0 with JavaScript
  • And whatever else you'd like -- send feedback!
So let's get started with the first and most simple application -- a 'Hello World' in Silverlight. You need no special tools for this. Just notepad will do...

Step 1. Silverlight.js
The first thing you'll need is Silverlight.js. This file contains everything that you need to create a silverlight component on your page. Silverlight is a browser plug-in that renders XAML and exposes a JavaScript programming interface. Browser plug-in's are implemented using special HTML tags called <object> and <embed>. Different browsers handle them differently, so instead of having to fiddle with them, it's a lot easier just to use Silverlight.js which handles it all for you.

You can get it here or in the Silverlight SDK, which installs to \PROGRAM FILES\Microsoft Silverlight 1.0 SDK. You'll find Silverlight.js in the 'Resources' directory.

Step 2. XAML
Silverlight UI is defined using XAML - XML Application Markup Language. Some great resources to get you started with XAML can be found in the Silverlight quickstarts here.

Our simple first application will be a XAML Canvas that contains a TextBlock control which, as its name suggests, renders text.

Here it is:

1: <Canvas
2:    xmlns="http://schemas.microsoft.com/client/2007"
3:    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4:    Width="640" Height="480"
5:    Background="White"
6:    x:Name="Page">
7:    <TextBlock Width="195" Height="42" Canvas.Left="28" Canvas.Top="35"
8:       Text="Hello World!" TextWrapping="Wrap" x:Name="txt"/>
9: </Canvas>

Download it here.

This pretty simple piece of XAML contains two components.

The first is the root Canvas which is present in every Silverlight XAML. This defines the overall drawing surface. As you can see we are using a 640x480 Canvas which is white.

The second is the Textblock that we mentioned earlier. It renders the text 'Hello World' on the Canvas.

Remember XAML is just XML, so all of the conventions of XML apply. You can see that the TextBlock is a child node of the Canvas, and that XML attributes are used to define the properties of the nodes. Note that this is can empower some pretty cool scenarios -- such as generating UI on the fly from server applications using ASP.NET, PHP or Java. We'll look more into these scenarios later in the series.

Step 3. CreateSilverlight.js
The XAML document that you created in Step 2 should be saved and named. In this example use the name Page.xaml.

It's good practice to host the code for creating the Silverlight component on your page in a seperate JavaScript file. It's not essential, but for good clean separation of code to make maintenance easier, it's a useful step.

Typically we call this file CreateSilverlight.js, and I'm following that defacto standard here. You can download it from here.

1: function createSilverlight()
2: {
3:   Silverlight.createObjectEx({
4:     source: "Page.xaml",
5:     parentElement: document.getElementById("SilverlightControlHost"),
6:     id: "SilverlightControl",
7:     properties: {
8:       width: "100%",
9:       height: "100%",
10:       version: "1.0"
11:     },
12:     events: {
13:       onLoad: handleLoad
14:     }
15:   });
16: }

This function calls the 'createObjectEx' function which is implemented in Silverlight.js, which you added to your site in Step 1. You'll notice that a 'handleLoad' event has been defined. You'll see how this is implemented in Step 4.

Step 4. Your Application Logic
This simple application allows you to click on the text block, and have the text change from 'Hello World' to 'You Clicked Me'. The code for this application is shown here:

1: var SilverlightControl;
2: var theTextBlock;
3: function handleLoad(control, userContext, rootElement)
4: {
5:    SilverlightControl = control;
6:    theTextBlock = SilverlightControl.content.findName("txt");
7:    theTextBlock.addEventListener("MouseLeftButtonDown", "txtClicked");
8: }
9: function txtClicked(sender, args)
10: {
11:    theTextBlock.Text = "You clicked me!";
12: }

The handleLoad was defined as an event in the createSilverlight function. When Silverlight renders the control it calls this, passing it a reference to the control, the contents of the 'userContext' variable (which can be set in the createSilverlight), and a reference to the root canvas element.

This function finds the text block (called 'txt') and adds an event listener to it. The event that it is listening for is 'MouseLeftButtonDown', and when this happens the function called 'txtClicked' should be called.

When you implement an event handler, your function should accept parameters for 'sender' (the originator of the event) and 'args' (arguments associated with the event)

In this code you can see that when the user clicks the text block, the text will be changed to "You clicked me!"

Step 5. Your HTML Page
Now you put it all together with an HTML page that references each of the JavaScript files and embeds the Silverlight control. Here's the full HTML markup:

1: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd">
2: <html xmlns="http://www.w3.org/1999/xhtml">
3: <head>
4:   <title>ZeroHero</title>
5:
6:   <script type="text/javascript" src="Silverlight.js"></script>
1:
2:   <script type="text/javascript" src="CreateSilverlight.js">
1: </script>
2:   <script type="text/javascript" src="code.js">
1: </script>
2:   <style type="text/css">
3:     .silverlightHost {
4:       height: 480px;
5:       width: 640px;
6:     }
7:   </style>
8: </head>
9:
10: <body>
11:   <div id="SilverlightControlHost" class="silverlightHost">
12:     <script type="text/javascript">
13:       createSilverlight();
14:     </script>
7:   </div>
8: </body>
9: </html>

Upload all these files to your web server and you're done.

This might have seemed to be a lot just to get a 'Hello World' applicaiton, but it covers the full broad principles of developing a SIlverlight 1.0 application. You saw how to use Silverlight.js and createSilverlight.js, write XAML, load XAML into Silverlight, hook up events and create on-the-fly event handlers.

You can see the application in action here:

In the next part of this series, we'll look at Expression Blend, and how you can use it to design your XAML to make it richer!

More Stories By Laurence Moroney

Laurence Moroney is a senior Technology Evangelist at Microsoft and the author of 'Introducing Microsoft Silverlight' as well as several more books on .NET, J2EE, Web Services and Security. Prior to working for Microsoft, his career spanned many different domains, including interoperability and architecture for financial services systems, airports, casinos and professional sports.

Comments (3) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Ellie's Professional Software Insight 02/18/08 11:14:41 PM EST

Trackback Added: Silverlight ????; ?? ?? ?? Silverlight? ??? ?????? ????? ???? ??

nbl 01/24/08 12:25:18 PM EST

What benefit does this give over using Javascript? Seems like the same amount of code.
some examples of getting started with Silverlight 1.1 please.

William Main 01/23/08 11:36:57 AM EST

I cannot get the silverlight to run on my server, which is at 1and1.com.

I have created a folder off of the root named scripts. Into this folder I have loaded the files

code.js
CreateSilverlight.js
helloworld.htm
page.xaml
Silverlight.js

I have modified the helloworld.htm file so that the scripts are loaded from /scripts for all of the js files.

I have also changed the CreateSilverlight.js file to load the source from the /scripts folder.

source: "/scripts/page.xaml"

There are no error messages. All I get is a blank web page. When I look at the source I get the following.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd">

ZeroHero

.silverlightHost {
height: 480px;
width: 640px;
}

createSilverlight();

Any ideas?

@ThingsExpo Stories
SYS-CON Events announced today that Secure Channels, a cybersecurity firm, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Secure Channels, Inc. offers several products and solutions to its many clients, helping them protect critical data from being compromised and access to computer networks from the unauthorized. The company develops comprehensive data encryption security strategie...
SYS-CON Events announced today that App2Cloud will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct. 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. App2Cloud is an online Platform, specializing in migrating legacy applications to any Cloud Providers (AWS, Azure, Google Cloud).
WebRTC is the future of browser-to-browser communications, and continues to make inroads into the traditional, difficult, plug-in web communications world. The 6th WebRTC Summit continues our tradition of delivering the latest and greatest presentations within the world of WebRTC. Topics include voice calling, video chat, P2P file sharing, and use cases that have already leveraged the power and convenience of WebRTC.
Internet-of-Things discussions can end up either going down the consumer gadget rabbit hole or focused on the sort of data logging that industrial manufacturers have been doing forever. However, in fact, companies today are already using IoT data both to optimize their operational technology and to improve the experience of customer interactions in novel ways. In his session at @ThingsExpo, Gordon Haff, Red Hat Technology Evangelist, shared examples from a wide range of industries – including en...
Detecting internal user threats in the Big Data eco-system is challenging and cumbersome. Many organizations monitor internal usage of the Big Data eco-system using a set of alerts. This is not a scalable process given the increase in the number of alerts with the accelerating growth in data volume and user base. Organizations are increasingly leveraging machine learning to monitor only those data elements that are sensitive and critical, autonomously establish monitoring policies, and to detect...
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. Jack Norris reviews best practices to show how companies develop, deploy, and dynamically update these applications and how this data-first...
Intelligent Automation is now one of the key business imperatives for CIOs and CISOs impacting all areas of business today. In his session at 21st Cloud Expo, Brian Boeggeman, VP Alliances & Partnerships at Ayehu, will talk about how business value is created and delivered through intelligent automation to today’s enterprises. The open ecosystem platform approach toward Intelligent Automation that Ayehu delivers to the market is core to enabling the creation of the self-driving enterprise.
"We're a cybersecurity firm that specializes in engineering security solutions both at the software and hardware level. Security cannot be an after-the-fact afterthought, which is what it's become," stated Richard Blech, Chief Executive Officer at Secure Channels, in this SYS-CON.tv interview at @ThingsExpo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
Consumers increasingly expect their electronic "things" to be connected to smart phones, tablets and the Internet. When that thing happens to be a medical device, the risks and benefits of connectivity must be carefully weighed. Once the decision is made that connecting the device is beneficial, medical device manufacturers must design their products to maintain patient safety and prevent compromised personal health information in the face of cybersecurity threats. In his session at @ThingsExpo...
SYS-CON Events announced today that Massive Networks will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Massive Networks mission is simple. To help your business operate seamlessly with fast, reliable, and secure internet and network solutions. Improve your customer's experience with outstanding connections to your cloud.
The question before companies today is not whether to become intelligent, it’s a question of how and how fast. The key is to adopt and deploy an intelligent application strategy while simultaneously preparing to scale that intelligence. In her session at 21st Cloud Expo, Sangeeta Chakraborty, Chief Customer Officer at Ayasdi, will provide a tactical framework to become a truly intelligent enterprise, including how to identify the right applications for AI, how to build a Center of Excellence to ...
From 2013, NTT Communications has been providing cPaaS service, SkyWay. Its customer’s expectations for leveraging WebRTC technology are not only typical real-time communication use cases such as Web conference, remote education, but also IoT use cases such as remote camera monitoring, smart-glass, and robotic. Because of this, NTT Communications has numerous IoT business use-cases that its customers are developing on top of PaaS. WebRTC will lead IoT businesses to be more innovative and address...
Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution and join Akvelon expert and IoT industry leader, Sergey Grebnov, in his session at @ThingsExpo, for an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
Because IoT devices are deployed in mission-critical environments more than ever before, it’s increasingly imperative they be truly smart. IoT sensors simply stockpiling data isn’t useful. IoT must be artificially and naturally intelligent in order to provide more value In his session at @ThingsExpo, John Crupi, Vice President and Engineering System Architect at Greenwave Systems, will discuss how IoT artificial intelligence (AI) can be carried out via edge analytics and machine learning techn...
SYS-CON Events announced today that GrapeUp, the leading provider of rapid product development at the speed of business, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Grape Up is a software company, specialized in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market acr...
SYS-CON Events announced today that Datera, that offers a radically new data management architecture, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Datera is transforming the traditional datacenter model through modern cloud simplicity. The technology industry is at another major inflection point. The rise of mobile, the Internet of Things, data storage and Big...
In his opening keynote at 20th Cloud Expo, Michael Maximilien, Research Scientist, Architect, and Engineer at IBM, discussed the full potential of the cloud and social data requires artificial intelligence. By mixing Cloud Foundry and the rich set of Watson services, IBM's Bluemix is the best cloud operating system for enterprises today, providing rapid development and deployment of applications that can take advantage of the rich catalog of Watson services to help drive insights from the vast t...
SYS-CON Events announced today that CA Technologies has been named "Platinum Sponsor" of SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CA Technologies helps customers succeed in a future where every business - from apparel to energy - is being rewritten by software. From planning to development to management to security, CA creates software that fuels transformation for companies in the applic...
Recently, IoT seems emerging as a solution vehicle for data analytics on real-world scenarios from setting a room temperature setting to predicting a component failure of an aircraft. Compared with developing an application or deploying a cloud service, is an IoT solution unique? If so, how? How does a typical IoT solution architecture consist? And what are the essential components and how are they relevant to each other? How does the security play out? What are the best practices in formulating...
In his session at @ThingsExpo, Arvind Radhakrishnen discussed how IoT offers new business models in banking and financial services organizations with the capability to revolutionize products, payments, channels, business processes and asset management built on strong architectural foundation. The following topics were covered: How IoT stands to impact various business parameters including customer experience, cost and risk management within BFS organizations.