473,897 Members | 3,118 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Building A Silverlight (2.0) Multi-File Uploader

Curtis Rutland
3,256 Recognized Expert Specialist
Building A Silverlight (2.0) Multi-File Uploader
All source code is C#. VB.NET source is coming soon.

Note: This project requires Visual Studio 2008 SP1 or Visual Web Developer 2008 SP1 and Silverlight 2.0. To get these tools please visit this page
Get Started : The Official Microsoft Silverlight Site
and follow Step 1.

Occasionally you find the need to have users upload multiple files at once. You could use multiple FileUpload controls, or you could dynamically create them, but if you want a rich client experience, a good way do to this is with Silverlight. This article assumes very little pre-existing Silverlight knowledge.

One important thing to know about Silverlight: it is executed on the client, not the server. This is exactly the opposite of ASP.NET, where all code is executed on the server. So Silverlight can easily get the files, but it can’t save them directly to the webserver. So we need something to bridge the gap.

What we will do is create an ASP.NET Web Service. This web service will expose a method that will allow a client to upload a file with a name. Presumably any client can consume this service, not just your Silverlight application, unless you implement some sort of SOAP Header authentication, but that’s beyond the scope of this article.

So the plan is to use Silverlight as our rich front end, which will connect to our ASP.NET web service backend. In this example, we will be creating a new project. If you have an existing Web Site or Web Application project, the procedures will be slightly different. I’ll explain the differences as we go along.

Let’s create the new project:

Make sure that the dropdown in the top right corner is set to .NET Framework 3.5, otherwise the list of project types will be empty for Silverlight.

Another dialog will pop up asking you if you want to create a new Web Application Project to link this Silverlight project to. Click OK.

If you are creating this Silverlight app for an existing project, you should right-click on the solution file for your project in Visual Studio and select Add New Project.

And add a Silverlight Project. The dialog will now ask if you want to link to the existing project.

Click OK.

Now that we have a Silverlight project and a linked Web Site/Web Application set up, it’s time to create the web service.

Writing the Uploader Service
Begin by adding a web service to our project. Right-Click on the Web Application Project, and Select Add New Item:

Select Web, and Find the Web Service Icon. Name the new file FileUploadServi ce.asmx.

Now the web service has been created. Here's a few setup steps we need to take:
  • Delete the Hello World method that has been automatically created. Remember to delete the [WebMethod] decoration as well.
  • Add this using statement to the top with the rest of the statements:
    Expand|Select|Wrap|Line Numbers
    1. using System.IO;
  • You can leave the namespace definition the same, or you can change it to your own URL. It isn't very important.
  • Lastly, add a folder to your Web Application called upload.

Now that we've set up our web service, let’s examine the logic we will use. All web service calls in Silverlight are asynchronous. Explanation: Instead of calling a method, and having the program wait for it to complete before finishing, you create an event handler to be fired when the method is complete. Then you start the method, and your program continues without it. The processing of that method is done on another thread. When it is finished, the Completed event is fired, and the handler you defined is triggered.

What this means for us is that we can invoke several requests at once…we don’t have to upload a list or array of files, we can make multiple requests to upload single files and they will be processed simultaneously. Knowing this will help us define our service.

We are going to expose just one web method. We’ll call it UploadFile. This method will take two parameters: a byte[], and a string. Here’s the code:

Remember the [WebMethod] decoration. It specifies that this method will be exposed for clients to invoke.

Basically, what this method does is accept an array of bytes and a filename. Then it grabs the server’s path to the upload directory and writes the file to disk. If the method fails, it returns false, otherwise, it returns true. Currently this method will overwrite any file with the same name. Later, you can implement some renaming logic to prevent this.

That’s it! That’s all there is to the web service. Make sure your solution will build and proceeded to creating the Silverlight app.

Creating the Silverlight Frontend
Open the Page.xaml file in your Silverlight project. Silverlight uses a markup language called XAML for layout and content. This is a special variation on XML, so most of the rules of XML apply, such as closing all tags. The root tag is a UserControl tag. This will define your Silverlight control.

The first thing we want to do is redefine the size of our control. For the purposes of this demonstration, we'll use 300 x 150 pixels. So in the root tag, change the Width and Height attributes to match. By default they are the last attributes.

Here's what you should have so far:

The grid will be our layout root. There are other layout containers including StackPanels and Canvases, but for this instance, a Grid will work well.

Let's define our presentation logic. We want to allow users to add several files to a queue, and then upload them all when they have a good list. We should allow them to remove files that they didn't mean to add. So, we will need a ListBox and two Buttons. Let's arrange them on two rows, with the top row holding the ListBox.

So to configure our grid to have two rows, we need to add some RowDefinitions. RowDefinitions can be either absolute or relative. We'll make these relative. Add this code:

Note that the rows will be distributed across the entire size of the grid, with the first being five times larger than the second.

Now that we have defined our grid, let's add some of our controls.

Let's discuss some common attributes for a moment. x:Name is the name that we will refer to our items with in our codebehind file. This is the equivalent of the ID tag in ASP.NET. Also, many controls have Events. For example, the ListBox we just added has several. When you add an event, IntelliSense will prompt you to automatically add the event handler name and definition.

Just press Tab or Return and this will be filled in for you.

So, we've added a ListBox with a KeyDown event. Next we've added a new Grid. You can stack these elements inside each other. Inside the new grid, we've defined two columns and added two Buttons, each with their own Click Event handlers. Just do these like you did for the ListBox, and the handlers will automatically be created on the back end.

Now we need to add some code to the ListBox. A Silverlight DataList has an Item array of objects. The properties of these objects can be bound to Silverlight controls in a ListBox's DataTemplate. In this case, we are going to be using FileInfo objects. So we can use the Name property of the FileInfo to bind to a TextBlock to make up an ItemTemplate. We could make this more intricate, with file sizes or other properties bound to other controls, but we'll keep it simple for now. Here's the code:

We're almost ready to start the real coding. We just need some way to disable the controls and communicate with the users that we are uploading their files. Add this code underneath the Grid holding the Buttons:

Note that we've added a StackPanel on the same row as the ListBox, but we've set its RowSpan attribute to 2. This will effectively make it cover the whole control. We've set the background color to a sort of Gray, and the Opacity to .85 (out of a possible 1).

A StackPanel does exactly what it says...it stacks items inside a panel, either Horizontally or Vertically. By default, it stacks vertically. You could change this by setting the Orientation property.

Notice that we've placed a TextBox and a Button in the StackPanel. Make sure you follow the procedure described earlier on how to add events, as the Button we've added has a Click event.

Also, notice that we've set the Visibility of the StackPanel to "Collapsed. " This way, it will be invisible. If you want to see how it will look when we make it visible, change it to "Visible." When this panel is visible, it is in front of the other controls, so you can't click them.

Now we're ready to start with the codebehind. First, make sure you save the current page. You have to save before the codebehind will recognize the x:Name attributes. Then you can right-click anywhere on the Page.xaml page (editor or preview) and select "View Code."

This will open Page.xaml.cs. Here's what it should have to start with:

The methods you have may not be in this exact order. A few setup items:
  • Add this code to the using statements at the top:
    Expand|Select|Wrap|Line Numbers
    1. using System.IO;
  • Add this code directly above the constructor (the public Page method)
    Expand|Select|Wrap|Line Numbers
    1. private int counter = 0;
And we're ready to start coding.

Let's fill in the code for the event handlers. First, the one called bOpenFileDialog _Click.

This code will open a FileDialog and let the user pick a file. If the user does not select a file or picks cancel, nothing happens. If they do, a FileInfo object is added to our ListBox's Items array. The ?? operator is the null-coalescing operator. What it does is evaluates the left. If it isn't null, it returns the left value. If it is, it returns the right value.

Now for the lbFileList_KeyD own handler:

This will let us delete an item in the list.

Now, the bClear_Click handler:

This will clear the textbox, array, and hide the Uploading screen.

Adding the Service Reference
Now comes the tricky part. You must add a service reference for this next part, but what's the address to your web service? Well, let's find out. Hit F5 to run your app, and navigate to FileUploadServi ce.asmx . Your URL will have a port number on it. Here's an example:

That's the address of your service. This will only work while the development server is running (when Visual Studio is running and you have debugged your project)! So when you shut down Visual Studio, that address is no longer valid, and may not be when you start it up again. So make sure to check that every time you reload this project. Once you publish this project to a web server, you can change that address to point to the permanent address on the web.

Now to add the service reference. Right-Click on the References folder in your Silverlight project, and click "Add Service Reference."

Paste the address in and click Discover. When it finds the service, change the Namespace to FileUploadServi ce, and click OK.

Now we have a reference to our service, let's create a client. Add this code:

in the bSubmit_Click method. The comments explain what is happening. The last line is important: as you type it you will see this:

Hit Tab twice to generate the handler for the FileUploadCompl ete event automatically. This will add another method to the page.

Let's finish out the bSubmit_Click method while we are here. Add this code in below what we just added:

Again, the comments explain what is happening. We increment the counter to note that we've added another async call to our web method.

Now, let's fill in service_UploadF ileCompleted. First delete or comment out the line that says:
Expand|Select|Wrap|Line Numbers
  1. throw new NotImplementedException();
and change it to this code:

You may note that there isn't a method called uploadingComple te(). You are right. It's time to create one:

And that's it! You can test it now by hitting F5.

Sample project and Changing the Service Reference Address
You can download the sample project here:
But you must remember to change the service reference to the correct url. Here's how to change the service reference address. Expand the folder called Service References in your Silverlight application, and right-click on the one called FileUploadServi ce. Click "Configure Service Reference."

And you should get this dialog:

Change the address to the correct one and click OK. Remember, to find the correct address, run your application and look at the port number on the url by localhost. Change this one to the one that shows up when you run the app.

When you are ready to publish this to a web server, you will want to change the address of the service reference to the permanent address. Publish it first as-is, and navigate to the .asmx file in your browser. Copy the URL, and follow the steps above to change the reference address. Then publish the application again.

You may have to configure IIS to serve Silverlight apps properly, but that is out of the scope of this article.

I hope you enjoyed reading this and found it helpful.

Article also available on my blog. Check it out!
Dec 20 '08 #1
7 7164
4,059 Recognized Expert Specialist
I found 26 errors in your article. It is poorly written and appears to not work properly.

OK...... not really. Awesome article. You might consider working for a site that pays for quality articles like that.
Dec 20 '08 #2
Curtis Rutland
3,256 Recognized Expert Specialist
Thanks Kevin :) I tried to think of a sarcastic way to say that I thought the sarcasm was funny, but I'm far too tired, so I'll just say that I truly appreciate the compliment.
Dec 20 '08 #3
4,059 Recognized Expert Specialist
I'm curious, how long did it take you to write the article? I know you will have to make a guess, but I am just curious, a ball park figure if possible and if you wish to say.
Dec 20 '08 #4
Curtis Rutland
3,256 Recognized Expert Specialist
No guess required. If you only count the writing time, not the coding, about 3.5-4 hours. I made a lot of screenshots. If you do count the time it took to write the project first, probably about 10 hours.
Dec 20 '08 #5
4,059 Recognized Expert Specialist
I would have guessed higher. I would count the time from start to finish, which would include graphics and code and editing. 10 hours is very fast for an article of that length and quality. Superb job.
Dec 20 '08 #6
Curtis Rutland
3,256 Recognized Expert Specialist
I've moved this to the insights area. I can't believe I let it sit in editors corner for so long.
Jun 16 '09 #7
9,735 Recognized Expert Moderator Expert
Before you try to install SilverLight you're going to have to first install Service Pack 1 for Visual Studio.

You can find this service pack here.
Jun 16 '09 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

by: Jenta | last post by:
A World Beyond Capitalism 2005, An Annual International Multiracial Alliance Building Peace Conference Is Accepting Proposals... ...and Online Registration is now available if you plan to table and participate in the International Grassroots Exhibition: http://www.lfhniivaaaa.info/awbcgrassrootsofpeace We would greatly like some proposals from all people worldwide, especially
by: Michel Claveau | last post by:
Hi! SilverLight ("MS flash killer"), is a plug-in for InternetExplorer (Win), FireFox (Win), and Safari (Mac). The release 1.1-Alpha come with JScript & Python (or ironPython?) See : http://www.microsoft.com/silverlight/default.aspx http://www.microsoft.com/silverlight/why-compelling.aspx http://silverlight.net/Default.aspx
by: Ronald S. Cook | last post by:
I'm a Visual Studio developer confused by seeing these new products coming out... Expression and Silverlight. Is Expression maybe a successor to FrontPage and is Silverlight maybe something to compete with Flash? Are Visual Studio, Expression, and Silverlight expected to exists together (and in some sort of harmony) in a development shop, or is something else going on.
by: Vinnie | last post by:
ok, thanks for the help. Some of you, was right: too many words, to much marketing without identifying the final user. Smithers gave the easiest answer. Now, as i wasn't enough confused, on the Microsoft web site i found these: Microsoft Expression Web Microsoft Expression Design Microsoft Expression Media
by: Abbas | last post by:
Does anyone know how to utilize a C# class within a silverlight project? I was trying to add a reference to my non-silverlight Class Library and the VS 2008 IDE told me "You can only add project references to other Silverlight projects in the solution".
by: m.a | last post by:
Hello, I have MSVC 2005 and I like to learn Silverlight. What do I need and can I get them free (It is just for learning so any restriction is acceptable)? is there any newsgroup about Silverlight?
by: m.a | last post by:
Hello, I installed MSVC 2008 express and I like to install silverlight. Can I do this? Thenone that I got from silverlight web site, complain about msvc version. Regards
by: Artificer | last post by:
Any idea if MS will try to promote Silverlight over ASP.NET for web development or will silverlight remain just as a adobe's flash like tecnology?
by: Ken Fine | last post by:
I know about this: http://silverlight.net/forums/14.aspx and this: http://forums.asp.net/1127.aspx Silverlight Beta 2 was announced at TechEd. I was impressed. When does Silverlight get a first-class newsgroup? -KF
by: =?Utf-8?B?TWFyYw==?= | last post by:
Dear all have a msdn subsciption and was wondering if I can post a Silverlight question here. I was wondering if Silverlight gives webcam support like flash does this. With this, it is possible to make conferencing solutions. As far as I read in ohter posts Silverlight 2 is not able to do this unless you use a McGyver style (http://jonas.follesoe.no/PermaLink,guid,7f8857dc-5f37-4a8a-bd35-fd4b624af45b.aspx).
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.