Read My Tweets
Ever feel like you're not getting the best experience on the web?
Get Silverlight to see the whole site!

TUTORIAL #10: Running a PowerPoint Slideshow From Your Windows Mobile Phone

Wednesday, November 19, 2008

During the recent .NET University, I had my first iPhone envy. Leon Gersing was giving a presentation on the basics of OOP (which was excellent), and I noticed that he was carrying around his iPhone while he talked.

On closer inspection, he was actually using his iPhone as his presentation clicker. He was able to move forward and backward in his presentation, and his phone was actually displaying his speaker notes in his hand! How cool is that?

Frustrated, I was convinced that there must be a way to do this on a Windows Mobile phone. I have given plenty of presentations that sing the praises of my WM6 phone, and have even compiled a list of the things I have used it for in a specific week.



So, you'll notice that "Run a Powerpoint presentation" is not on my list. But today, I have to edit that slide. Here's how you can do it too:

1) Download Windows SideShow for Windows Mobile

Get the files here. This is the first piece of all of this. Windows SideShow is a new technology that delivers information from your PC to a secondary display on two kinds of devices: those that are integrated into a computer, such as a small color display in a laptop lid; and those that are separate from a computer, such as a remote control or mobile phone. With this additional display you can view important information whether your laptop is on, off, or in sleep mode.

2) Install the .CAB file on your phone.

There is an excellent help file in the files you just downloaded, and I will leave it to you to make sure that you get this software installed on your phone. If you're still running Windows Mobile 5, make sure that you get the .NET Compact Framework installed on your phone as well (the installer is also included, for your convenience.)

3) Create a Bluetooth connection to your phone from your Vista PC.

Yes, if I didn't mention it, SideShow is a feature of Windows Vista. This will not work in Windows XP. My apologies. To create the Bluetooth connection, here's the steps:
  1. On your PC, go to Control Panel > Hardware and Sound > Bluetooth devices > Set up a Bluetooth enabled device
  2. On your phone, open your Start menu, choose Bluetooth, and then choose Bluetooth Manager.
  3. Make sure the status is set to "Bluetooth ON", that you have a name for your device that you like (mine is blankenq for my Motorola Q9c), and that the checkbox reading "Allow other Bluetooth devices to see this phone" is checked.
  4. Back on your PC, click the "Add..." button on the Devices tab.
  5. Check the box that reads "My device is set up and ready to be found.", and click Next.
  6. It will search for available Bluetooth devices, and eventually show you a list. Choose the device that has the name you used when you set up your phone, and click Next.
  7. Next, it will ask you "Do you need a passkey to access your device?" The answer is YES. Yes, you do. I prefer using the choice: "Let me choose my own passkey." Then enter a passkey from 8-16 digits long. Remember what you typed, and then click Next.
  8. Look at your phone. It should now be asking you to enter that passkey again. Enter it in the box, and click Accept.
  9. Your PC will then install some device drivers, and you're off and running. Your phone is now paired with your PC!
  10. Click Finish, and you can exit your way though the rest of the Control Panel.

4) Install the Office PowerPoint Remote Gadget

Get the files here.This is the actual "gadget" that you can run in Windows SideShow. This is what you use to manipulate your Powerpoint presentations. To make your life easy, check the box that reads, "Open Windows SideShow in Control Panel when I click Finish." If you forget the box, open the Control Panel, and choose Programs > Windows SideShow. In here, you should see 4 boxes available for checking. Your email, your calendar, Powerpoint, and Windows Media Player. The three that aren't Powerpoint come with SideShow by default. This will allow you to see your email, view your calendar, control Windows Media Player, and run Powerpoint presentations from your PC, even if it is sleeping. Cool, huh? Check the boxes you want access to.

5) Take a look at your Home screen on your phone.

You should now see a new item in your Home screen. This is the Windows SideShow section, and it is how you get to the applications available to you in Windows SideShow. Fire up a PowerPoint presentation on your PC, and it will show up in the PowerPoint remote menu. You can start the slideshow, move from one slide to the next, and the speaker notes for each slide are even shown on your phone's screen!

Eat that, Mr. Gersing. :)

kick it on DotNetKicks.com

Labels: , , , , ,

posted by Jeff Blankenburg, 4:42 PM | link | 5 comments |

TUTORIAL #9: Embedding Fonts In Silverlight 2

Monday, November 10, 2008

Many times when I am creating a Silverlight application, I'm not happy using the default 10 fonts that are part of Silverlight. I've got hundreds of other fonts on my machine that make more sense, but then I need that font on every user's machine that visits my site. Thankfully, Silverlight makes that easy for me.

1) Add a TextBlock to your XAML.


<TextBlock Width="100" Height="100" Text="Jeff Blankenburg"></TextBlock>

2) Add your font to the project.

In Expression Blend and in Visual Studio, this is pretty easy. Right click on your Silverlight project, and choose "Add Existing Item..." From there navigate to your Fonts folder (or where ever you're keeping fonts these days), which in Windows Vista is found at c:\windows\fonts\. Choose the TrueType font you wish to use (that's any font file with a .TTF extension), and add it to your project.

3) Understand what we're actually doing.

In Visual Studio, click on your new font file in your project. In the properties window, one of the items in the list is "Build Action." Make sure that this is set to "Resource." It should be set to that by default, but confirming it never hurts. What we're doing is telling the application that this is a resource that we will need access to when the application runs. Since Silverlight applications run on the client machine, it will be packed inside your .XAP file for the trip across the Internet.

4) Apply your font to your textblock.

You may have noticed, if you were working ahead, that applying a font to your textblock is simple. In Studio, you can just type in the property FontFamily for the TextBlock, and specify the font you want to use. However, the preview window will only respond for the 10 fonts that are native to Silverlight. These are: Arial, Comic Sans, Courier New, Georgia, Lucida Sans Unicode, Portable User Interface, Times New Roman, Trebuchet MS, Verdana, and Webdings.
<TextBlock Width="100" Height="100" Text="Jeff Blankenburg" FontFamily="Times New Roman"></TextBlock>
In Expression Blend, you get a nice dropdown to choose your fonts from. They even have a nice icon system to show you which fonts are actually available. The default fonts have an A with the Silverlight logo next to them, and the new font we have added has an application icon with an A over it. Fonts without an icon need to be included (using this process) before they can be used. You CAN use them, but that font will not be shown on any machine that does not have that font installed.



Here's the tricky part of using a foreign font. We don't just get to reference the name of this font. There's a unique syntax for making sure we get this correct. A font actually has two names: the name of the .ttf file, and the actual name of the font. We will need to know both of these. In my example, I am using the font "Calibri." So in order to use that font, I need my FontFamily property to look like the following line:

<TextBlock Width="100" Height="100" Text="Jeff Blankenburg" FontFamily="calibri.ttf#Calibri"></TextBlock>


What I have done is tell Silverlight that I want my font to come from the file named calibri.ttf, and I want the font from that file named Calibri.

That's all it takes! You should now be able to see that font rendered in the Visual Studio preview pane, as well as Expression Blend and our running application. Just remember that we need to package these external fonts into our application, and then we have to use this alternate syntax to point directly to the font.

I hope this helps you get past the hurdle of using the same 10 fonts over and over and over. Please let me know how this helps you!

kick it on DotNetKicks.com

Labels: , , , , ,

posted by Jeff Blankenburg, 2:23 PM | link | 1 comments |

TUTORIAL #8: Creating An AutoComplete TextBox With AJAX

Monday, October 27, 2008

There's this incredible resource in the AJAX Control Toolkit, and it's about time we started using it. Today I am going to talk about the AutoComplete Extender, and how simple it is to rig up to an existing ASMX web service. As usual, I will provide the code at the end of this post in both C# and VB.NET. Let's start at the beginning:

1) Create a new web site.



2) Create a new ASMX web service.

Right-click on the project, and choose "Add New Item..." From the dialog box, choose Web Service, and name the service NCAA.asmx (I'll explain the name later.) Also, for our demo, we're going to leave the code in one single file. Uncheck the "Place code in a seperate file" box.


3) Write a quick web method.

We'll be making this more complicated later, but for now, we're going to write a simple web service that is meant for the AutoComplete Extender. For this control, our method must have this signature:
public string[] GetTeamList(string text)
So for now, here's the full code to put inside your ASMX file:
using System;
using System.Collections;
using System.Configuration;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;


namespace AutoComplete
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class ncaa : System.Web.Services.WebService
{
[WebMethod]
public string[] getTeamList(string prefixText)
{
string[] teamName = new String[6];
teamName[0] = "Bowling Green State University";
teamName[1] = "Ohio State University";
teamName[2] = "Ohio University";
teamName[3] = "Cleveland State University";
teamName[4] = "University of Cincinnati";
teamName[5] = "University of Dayton";
return teamName;
}
}
}


4) We should verify our web service works.

Right click on your ASMX file, and choose "View in Browser." Clicking on the method name, GetTeamList, will ask you for a "prefixText" value. That value isn't used yet, so just click the Invoke button to see our list of colleges returned in XML.


5) Now we need add a textbox.

We're actually going to add a few things to our Default.aspx page, but the first thing to do is add a standard TextBox control to the page. You should be able to grab that from your toolbox. The other things to add require a potential download first. I'll show you the completed HTML after step #9.


6) Get the ASP.NET AJAX Library.

You only need to do this if you're not using the ASP.NET 3.5 framework. Here is the link to the AJAX library downloads.


7) Get the AJAX Control Toolkit.

The control toolkit is an open source project on CodePlex, and you can download it here. Unless you're really interested in contributing/taking it apart, all you really need is the link to the DLL Only. Save that to your computer, and then you need to add it to your Toolbox.


8) Add it to your VS Toolbox.

Here's the quick way to get those new controls and extenders into your Visual Studio toolbox:
  1. Pin out your toolbox by clicking on the pushpin icon at the top.
  2. Right-click on the toolbox and choose "Add Tab"
  3. Give it a name like "AJAX Control Toolkit."
  4. Drag the toolkit .DLL file from your computer to the new tab you created.
  5. You should now see your new controls in your toolbox.


9) Add our AJAX elements to the page.

Now we need to add an AJAX ScriptManager and a new AutoCompleteExtender to our page. You can either type them, or just drag them from your toolbox. Here's what your Default.aspx file should look now:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AutoComplete._Default" %>
<%
@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

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

<
html xmlns="http://www.w3.org/1999/xhtml" >
<
head runat="server">
<
title>Jeff Blankenburg | AutoCompleteExtender</title>
<
link href="style.css" rel="stylesheet" type="text/css" />
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<
asp:TextBox ID="collegeteam" runat="server"></asp:TextBox>
<
cc1:AutoCompleteExtender ID="collegeteamextender" runat="server" ServicePath="ncaa.asmx" ServiceMethod="getTeamList" MinimumPrefixLength="3" CompletionSetCount="10" TargetControlID="collegeteam">
</
cc1:AutoCompleteExtender>
</
div>
</
form>
</
body>
</
html>


10) Some explanation for the HTML...

You'll notice that I added some properties to the controls that are on our page, so let me explain what they are.
  • Service Path - this is the web service that we are going to call
  • Service Method - this is the method in that web service that we are calling.
  • Minimum Prefix Length - this is the number of characters a user must enter before the extender will start calling the web service. If you've got thousands or millions of possible return values, I'd make this 3 or 4, at a minimum.
  • Completion Set Count - this forces the control to only show a specific number of results (you need to modify your web service for this to work).


11) Run the web site.

At this point, we should have a fully functional AutoComplete extender. You can run the site to check it out. Just start typing in the textbox to see what happens. But we're pulling back a static list of data. That's not very interesting at all. I want to do something realistic with this functionality.

12) Web Service += Usefulness

The reason that I called my web service NCAA is because I want to allow my users to choose from a list of colleges as they are typing. The first thing we'll need then, is a database of colleges. Here's my database of all of the Division I schools, with their names, mascots, and hex colors. Now we need to modify our web service so that we're pulling results out of the database based on our text typed in the TextBox. Here's my new web service code (you can just copy and paste over the old stuff.)

using System;
using System.Collections;
using System.Configuration;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;


namespace AutoComplete
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class ncaa : System.Web.Services.WebService
{
[WebMethod]
public string[] getTeamList(string prefixText)
{
DataSet teams = new DataSet();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string sql = "SELECT team_name FROM team WHERE team_name LIKE '" + prefixText + "%'";
SqlCommand sqlCmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataAdapter sqlAdpt = new SqlDataAdapter();
sqlAdpt.SelectCommand = sqlCmd;
sqlAdpt.Fill(teams);
string[] teamName = new String[teams.Tables[0].Rows.Count];
int i = 0;
try
{
foreach (DataRow row in teams.Tables[0].Rows)
{
teamName.SetValue(row["team_name"].ToString(), i);
i++;
}
}
catch { }
finally
{
conn.Close();
}
return teamName;
}
}
}


You'll notice that without modifying our .aspx file, we can completely update the functionality behind our web service. This seperation can be invaluable when building applications from web services, because you don't want a change in one thing to potentially break another.

13) What about that CompletionSetCount?

So I mentioned earlier that you can set the number of results you want returned so that you don't end up with a huge, unmanageable list. This will require a small change to your web service, but nothing significant. Without these changes, your CompletionSetCount value will just be ignored. The first change is that we need to receive a second parameter (an integer) in our WebMethod. That's right, the extender just sends it as a second parameter to your method. The second change, then, is just to modify your method to utilize that value. Here's my final web service source code, using this added feature:

using System;
using System.Collections;
using System.Configuration;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;


namespace AutoComplete
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class ncaa : System.Web.Services.WebService
{
[WebMethod]
public string[] getTeamList(string prefixText, int count)
{
DataSet teams = new DataSet();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string sql = "SELECT TOP " + count + " team_name FROM team WHERE team_name LIKE '" + prefixText + "%'";
SqlCommand sqlCmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataAdapter sqlAdpt = new SqlDataAdapter();
sqlAdpt.SelectCommand = sqlCmd;
sqlAdpt.Fill(teams);
string[] teamName = new String[teams.Tables[0].Rows.Count];
int i = 0;
try
{
foreach (DataRow row in teams.Tables[0].Rows)
{
teamName.SetValue(row["team_name"].ToString(), i);
i++;
}
}
catch { }
finally
{
conn.Close();
}
return teamName;
}
}
}


Demo

Here's a link to the active demo. Because my hosting provider does not support SQL Express (we can talk about CrystalTech later), I am actually running it from a full SQL 2005 database, but the MDB I provided is merely a copy of the table I am using.

Click to see the AutoComplete demo.

Source Code

Click to download the AutoComplete demo in C#. Click to download the AutoComplete demo in VB.NET.

kick it on DotNetKicks.com

Labels: , , , , , ,

posted by Jeff Blankenburg, 12:16 PM | link | 2 comments |

Blankenthoughts: A Popular History Tour

Wednesday, October 22, 2008

Inspired by the most recent post over at Advergirl (a friend of mine), I have decided to list out links to the 10 most popular posts from the entire 2+ year history of my blog. The reason for this is to introduce some of my older (but still useful) articles to some of my newer readers. So here goes:

10) Calling Javascript From Silverlight 2

This is another in my series of tutorial posts, which walks you through creating a Silverlight application that can both call, pass values to, and retrieve values from a Javascript method in the web page host. An invaluable read for any Silverlight developer.

9) Extraordinary Nut Snack

This is a commentary on the commercials from Frito-Lay on their new line of snacks. It includes a video of their first try at commercials. Beautifully done in CGI, the almonds fall like dominoes. And then they say the title of this post. Your mind will wander.

8) CAPTCHA the Flag

This is a complete walkthrough on implementing Asirra, a new CAPTCHA control (of sorts) from Microsoft Research. It's incredibly easy to add to your application, and might even result in an adoption!

7) 6 Tips For Making Website Registration User Friendly

There are a million different websites out there, and there's a million different ways to register for an account on them. This is a list of simple suggestions for the next time you head down the "registration" path. Best tip? Make it easier for your users, not for the developer building the pages.

6) Top 10 Things New Twitter Users Need To Know To Get Followers

You only get one real chance to impress upon someone why they should follow you on Twitter. Following these rules will help you immensely.

5) Simple Resizing In Silverlight

One of the beauties of Silverlight is that it is based on vector graphics. This means that no matter what size you display them, they don't get pixelated and blurry. Vector graphics can grow or shrink to any size, and this tutorial shows you the simple way to make it happen.

4) Creating A Simple Silverlight Animation

As the creator of the CodeMash logo, I was excited when I found out I could convert my Adobe Illustrator file to XAML. Once that was completed, the next logical step was to animate the gears. This tutorial shows you how to do that, as well as a quick tour around Expression Blend.

4) Left Outer Join In LINQ

As someone who has a hard time getting out of a traditional SQL mindset, when I started using LINQ, the question of how to emulate a left outer join immediately confronted me. This outlines the simple way to do just that.

3) I Hate Windows, I'm Moving To Windows Mojave

This was briefly written to announce the Windows Mojave website and advertising campaign. It has certainly has its praises and criticims, but this post got more traffic in one day than any other post has ever gotten.

2) TUTORIAL: Creating a WCF Service for Silverlight 2 and SQL

One of my first "tutorial" posts, this hit the ground running, and hasn't looked back. It's an excellent beginning example of how to get Silverlight talking to a web service that accesses a SQL database.

1) General Ionics: Fake or Fab?

This article was written while I was buying a water filtration system for my home. While not technical in nature, this has been, by far, my most popular post to date.

Labels: , , , ,

posted by Jeff Blankenburg, 8:35 PM | link | 0 comments |

TUTORIAL #7: Downloading Videos From YouTube

Wednesday, October 08, 2008


I've done a ton of presentations over the years. Sometimes there's a video on YouTube or some other streaming video site that would complement my presentation. (Like this one.) But many places that I present at don't have Internet access readily available. So those videos go unplayed, and my presentation just doesn't have the pizazz I was hoping for.

I have finally found a way to get those videos, in any format I want, thanks to a few tools. Now I can save those videos to my Zune/iPod/other device. Now I can embed those videos right inside my Powerpoint presentations. Here's how I do it:

1) Find a video you want to download.

Just cpoy the URL of the page the video is shown on. I'm going to use this one as my example. It's an interpretation of Daft Punk's "Harder Better Faster Stronger." The person in the video wrote the lyrics to the song (there's only like 12 words, over and over) on their hands, and shows those words at the appropriate times. Highly entertaining, I promise.

2) Download that video.

Here's the first tool we need to use. Open a new browser window and go to http://www.savevid.com. Near the top of the page is a textbox for you to paste your URL into. Do that, and then click the download button. After a few seconds (or minutes, depending on the length of your video), it will present you with a few links. One of those links is to "Download MP4." Do this, and save the file to your hard drive.

3) That's IT? No, there's more.

That's only half the task. MP4 files can be added to your media player of choice, but they're not used many other places. What if my device doesn't support MP4, or I want to embed this file in a presentation? There's gotta be a simple way to convert this video to another format. And there is.

4) Get Expression Media Encoder 2.

This was the first time I had used Expression Encoder, but it is SUPER easy. Download it here. During the install, it will ask you if you want to install Quicktime too. YES. Yes you do. You need it to work with MP4 files. (Thanks Apple, for your wall.)

5) Import your new MP4 file.

Once you've got Expression Media Encoder installed, open it up, and from the File menu, choose Import. Choose your MP4 file from earlier, and open it up. By default, all of the settings are preset to create a high-res WMV file.

6) Export your new WMV file.

All you need to do now is go back up to the File menu and choose "Encode." It will create a new WMV file for you that can be used in just about every application that uses video on Windows. (If you're on a Mac, that MP4 file should be the one you use.) Voila! You've downloaded a movie from YouTube, and now you can do anything you want with it!

kick it on DotNetKicks.com

Labels: , , , , ,

posted by Jeff Blankenburg, 4:23 PM | link | 4 comments |

TUTORIAL #4: Showing Non-Silverlight Content To Users Without The Plugin

Monday, September 22, 2008


I just recently updated the navigation on my blog (http://www.jeffblankenburg.com) to be a nice Silverlight control, and realized that I was not really providing an optimal experience for those people that don't have the plugin installed. So since I had to go through it, I thought I would share with you how simple this actually is.

When you add a new Silverlight control to your page, this is what the code will look like:


<div id="silverlightControlHost">
     <object data="data:application/x-silverlight," type="application/x-silverlight-2-b2" width="880" height="60">
          <param name="source" value="ClientBin/JeffBlankenburg.com.xap"/>
          <param name="onerror" value="onSilverlightError" />
          <param name="background" value="white" />
     </object>
</div>


How To Add Your Non-Silverlight Content

Here's all you need to do to get it to work. Inside the <object> tag, after all of the <param> tags, just add your HTML. In my example, I have a different navigation in HTML for non-Silverlight users. It will display this content when the Silverlight plugin is absent.

Here's the new example, with my content included:


<div id="silverlightControlHost">
     <object data="data:application/x-silverlight," type="application/x-silverlight-2-b2" width="880" height="60">
          <param name="source" value="ClientBin/JeffBlankenburg.com.xap"/>
          <param name="onerror" value="onSilverlightError" />
          <param name="background" value="white" />
          <div id="sitetitle"><h1><a href="http://www.jeffblankenburg.com" class="style3">Blankenthoughts</a</h1><p class="style4"><strong>These are my thoughts. Nothing more.</strong></p></div><div id="menu"><a href="http://go.microsoft.com/fwlink/?LinkID=115261" style="text-decoration: none;"><img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style: none"/></a></div>
     </object>
</div>


How do I test this? I have the plugin installed!

That's easy in IE8. Just go to:

Tools > Internet Options > Programs > Manage Add-ons

and choose the Silverlight plugin. You can temporarily disable it there. Great new feature. Here's a picture of the screen (click to enlarge).



There you go. You can now create custom HTML to display for your users that have not yet installed the Silverlight plugin. I'd recommend letting them know they're missing out on the full experience, however, or they will never find your cool Silverlight control.

kick it on DotNetKicks.com

Labels: , , , ,

posted by Jeff Blankenburg, 11:41 AM | link | 2 comments |

TUTORIAL #1: Creating a WCF Service For Silverlight 2 and SQL

Thursday, June 19, 2008

Today I'm going to show how to create a simple WCF service, and consume it from a Silverlight application. This is something you are going to need to do quite often, and if for no other reason, I am documenting this here so that I have it as a reference.

The first thing we need to do is create a Silverlight application. (In order to have all of the Silverlight 2 prerequisites, make sure you visit this page.)

1) I'm going to start from the beginning. First, we need to create a new Silverlight project. I'm naming mine JBWCFService.

Creating a new Silverlight project

2) We will then be prompted to create a web project to accompany our Silverlight project. I choose a Web Application Project from the dropdown.



3) Here is a view of what my solution explorer looks like after the projects are created. I have a Silverlight project called JBWCFService and a Web Application project called JBWCFServiceWeb, not surprisingly.



4) Next, I want to create a SQL database from which to get my data from. I'm not going to walk through all the steps of adding tables, columns, and data. You can certainly find that elsewhere. Here's my adding the SQL database to my project though...



5) OK, it's time to create our service. I'm naming my service MyNewService. It's just another thing to add to our project, so here we go:



6) Once the new service has been created, you will have a few new files in your project. In my case, they are named IMyNewService.cs, MyNewService.svc, and its code-behind, MyNewService.svc.cs. By default, the interface (IMyNewService.cs) will be open and ready for editing. They create a DoWork() method for you, but we're going to delete that and do something more interesting in a little while. First, we need to get LINQ up and running against our data. I am naming mine LINQClasses.



7) In addition to adding the class files necessary, this will also open the LINQ design surface by default. We can just drag items from our data structure right to the left half of the surface, creating ORM class structures that represent our data. In my example, I only have one table, profile, but we can do this for all of our tables, and stored procedures can be dragged to the right half of the surface, creating methods. I have already dragged my table over in the next screenshot (click to enlarge).



8) We also want to make sure that our data is unidirectionally serializable (I like big words). By clicking on the design surface (not one of the table boxes), you can get to the properties of the DataContext, and change the Serialization Mode to "Unidirectional."



9) Now we need our Silverlight project to become aware of our WCF service running in the web application project. To do this, we just need to add a new service reference to the Silverlight project. Click the "Discover" button to find it automatically. This will also automatically spin up a web server for your service to run in. I named my service reference MyNewServiceReference.



10) Ready to write some code? To this point, everything has been handled automatically for us. Now we have to get our hands dirty. Let's go back to our Service interface (IMyNewService.cs). In there, let's get rid of that DoWork() method. Instead, our method is going to return a List of profiles from the database, based on our new classes that were created for us. Because this is an interface, we don't define the actual functionality of the method here, just it's signature. I named my method GetProfilesByLastName.



11) Ok, that was exhausting. Let's have the IDE write some more code for us now. Let's open the code-behind file for MyNewService.svc (MyNewService.svc.cs). You can see that it inherits from the interface we just defined, so right click on the name of the interface, and have it implement the interface for you.



12) Now you've got the shell for the method. We just need to tell this method what to do. Here's where the LINQ comes into play. We need to get a reference to our DataContext from earlier, and then I wrote a simple query to retrieve names from the database based on a last name query. Finally, we return our list of data.



13) Each time we update our service, we will need to update our service reference in the Silverlight project, so that it sees our new methods. Just right click on the service reference and choose "Update Service Reference." Also, we have one small change we need to make to our web.config file as well. If you've been following the instructions, then you can scroll down to the bottom of your web.config and look for the <endpoint binding="wsHttpBinding" /> property. Silverlight only currently supports basicHttpBinding, so we need to change it to that.



14) Next, we need to add one more reference to our Silverlight project before we can finally start working with the XAML. We need to add a reference to System.Windows.Controls.Data so that we can use the DataGrid control in our interface.



15) XAML time. Kinda. We need to include that reference as a namespace in our Page.xaml document. OK, now we can add some controls to our page. I also added a Button, a TextBox, and a DataGrid, inside a couple of StackPanels, for layout purposes.



16) Now, we need to call that method in our service and populate that grid. The first thing we need to do is instantiate our ServiceClient. Now, since we are calling this service asynchronously, we also need to set up an event handler to know when our data has returned so that we can update the DataGrid. There's an excellent bit of shorthand for creating this code automatically. My screenshot shows all of the code I will need, but for the line that starts:

sc.GetProfilesByLastName +=

I only actually typed what is above. After that, I pressed the Tab key twice. The first press of Tab actually finishes out my EventHandler statement. The second Tab press creates my EventHandler method, so that I can add the guts. Finally in my Button_Click method, I need to call the GetProfilesByLastName asynchronously, passing in the value from my TextBox, named DataEntry.



17) The last little touch we need to put on this application is the actual binding of the data to our DataGrid, and we'll do that in the new EventHandler method that was created for us. There's just one line of code in the method:

DataGrid.ItemsSource = e.Result;



So, there you have it. We've created a WCF service that uses LINQ to talk to a SQL server, and a Silverlight 2 application that consumes that service and renders the result. Not bad for 17 steps, and only a few lines of code.

Click here to download the solution files.

Labels: , , , , , , ,

posted by Jeff Blankenburg, 11:34 AM | link | 8 comments |