We know that Silverlight 2 provides a wide range of network communication APIs, including support for SOAP services, REST services, HTTP-based communication, and Socket communication. This article uses several examples to demonstrate how to upload files and send emails in Silverlight 2.
ASP. NET uploads files using Web Service
I will use an example to demonstrate how to use Web Service to upload files. First, I will create a Silverlight project and add an ASP. NET Web Service file to the Web test project. Now we can implement the relevant WebMethod. In this method, we will receive two parameters: byte array and file extension, and create a file on the server, as shown in the following code:
- C#
- [WebMethod]
- public int UploadFile(byte[] FileByte, String FileExtention)
- {
- FileStream stream = new FileStream(String.Format(@"D:\example.{0}",
FileExtention),FileMode.CreateNew);
- stream.Write(FileByte, 0, FileByte.Length);
- stream.Close();
- return FileByte.Length;
- }
Add a simple interface for users to select a local file. We will click the button to call Web Service in the event, as shown in the following code:
XAML
- <Canvas Background="#FF333333">
- <TextBox x:Name="txtFile"></TextBox>
- <Button x:Name="btnUpload" Click="OnUploadClick"></Button>
- <TextBlock x:Name="tblStatus"></TextBlock>
- </Canvas>
ASP.. NET calls Web Service to upload files. The OpenFileDialog object pop-up window is used to select files. This object returns the selected files as Stream, the following code converts Stream into a byte and passes it to Web Service:
- VoidOnUploadClick (objectsender, RoutedEventArgse)
- {
- OpenFileDialogopenFile=NewOpenFileDialog();
-
- If (openFile. ShowDialog () = DialogResult. OK)
- {
- StringfileName=OpenFile. SelectedFile. Name;
-
- FileServiceSoapClientclient=NewFileServiceSoapClient();
- Client. UploadFileCompleted + = newEventHandler<UploadFileCompletedEventArgs>
(OnUploadFileCompleted );
-
- Streamstream= (Stream) openFile. SelectedFile. OpenRead ();
- Stream. Position=0;
- Byte []Buffer=Newbyte[Stream. Length + 1];
- Stream. Read (buffer, 0, buffer. Length );
- StringfileExtention=FileName. Substring (fileName. IndexOf ('.') + 1 );
-
- Client. UploadFileAsync (buffer, fileExtention );
- }
- }
-
- VoidOnUploadFileCompleted (objectsender, UploadFileCompletedEventArgse)
- {
- If (E. Error= Null)
- {
- TblStatus. Text="File Uploaded! ";
- }
- }
- XML and ASP. NET
- Java script in ASP. NET calls the c # Method
- Process of processing ASP. NET Postback Program
- ASP. NET Server-side control CheckBoxList
- Analysis of ASP. NET Membership