一步一步学Silverlight 2系列(33):Silverlight 2应用Web Service两例
概述
我們知道,在Silverlight 2中提供了豐富的網絡通信API,包括支持SOAP服務、REST服務、基于HTTP通信、Socket通信等。本文我將通過幾個示例來演示如何在Silverlight 2中應用Web Service實現文件上傳和電子郵件發送。
使用Web Service上傳文件
我將通過一個示例來展示如何使用Web Service向服務器上傳文件,首先創建Silverlight項目,并在Web測試項目中添加一個ASP.NET Web Service文件。現在來實現相關的WebMethod,在此方法中,將會接收兩個參數:字節數組和文件擴展名,并會在服務器上創建文件,如下代碼所示:
public class FileService : WebService {[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;} }添加一個簡單的界面,供用戶選擇本地文件,我們將在按鈕單擊單擊事件中調用Web Service,如下代碼所示:
<Canvas Background="#FF333333"><TextBox x:Name="txtFile" Height="30" Width="300" Canvas.Top="120"Canvas.Left="30" Style="{StaticResource textBoxStyle}"></TextBox><Button x:Name="btnUpload" Width="60" Content="上 傳" Height="30"Canvas.Left="340" Canvas.Top="120" Style="{StaticResource buttonStyle}"Click="OnUploadClick"></Button><TextBlock x:Name="tblStatus" Canvas.Left="30" Canvas.Top="160"FontSize="14" Foreground="White" Text=""></TextBlock> </Canvas>調用Web Service上傳文件,此處使用了OpenFileDialog對象彈出擇窗口以便選擇文件,此對象將選擇的文件作為Stream返回,我們把Stream轉換為一個字節數據傳遞給Web Service,如下代碼所示:
void OnUploadClick(object sender, RoutedEventArgs e) {OpenFileDialog openFile = new OpenFileDialog(); if (openFile.ShowDialog() == DialogResult.OK) {String fileName = openFile.SelectedFile.Name;FileServiceSoapClient client = new FileServiceSoapClient();client.UploadFileCompleted += new EventHandler<UploadFileCompletedEventArgs>(OnUploadFileCompleted);Stream stream = (Stream)openFile.SelectedFile.OpenRead();stream.Position = 0;byte[] buffer = new byte[stream.Length + 1];stream.Read(buffer, 0, buffer.Length);String fileExtention = fileName.Substring(fileName.IndexOf('.') + 1);client.UploadFileAsync(buffer, fileExtention);} }void OnUploadFileCompleted(object sender, UploadFileCompletedEventArgs e) {if (e.Error == null){tblStatus.Text = "上傳文件成功!";} }運行程序后,選擇一個文件并上傳,如下圖所示:至此,我們就完成了一個使用Web Service上傳文件的示例。
使用Web Service發送電子郵件
眾所周知,發送電子郵件需要使用SMTP協議,Silverlight中并不支持SMTP通信,但是我們可以借助于Web Service來發送電子郵件。本節將通過一個示例講解這一內容,最終完成的效果如下圖所示:
我們首先添加一個ASP.NET Web Service,并實現WebMethod,此方法將接受四個參數:發件人、收件人、郵件主題以及郵件內容,并使用SmtpClient對象發送郵件,關于SmtpClient的使用,大家可以參考MSDN,它位于System.Net.Mail命名空間下。如下代碼所示:
public class EmailService : WebService {[WebMethod]public bool Send(String fromAddress,String toAddress,String subject,String body){try{MailMessage msg = new MailMessage();msg.From = new MailAddress(fromAddress);msg.To.Add(new MailAddress(toAddress));msg.Subject = subject;msg.Body = body;msg.IsBodyHtml = false;SmtpClient smtp = new SmtpClient();smtp.EnableSsl = true;smtp.Send(msg);return true;}catch{return false;} } }使用SmtpClient需要在Web.config文件中配置一下郵件服務器,這里使用Google的服務器,大家可以使用自己的Gmail帳號,如下代碼所示:<system.net><mailSettings><smtp><network host="smtp.gmail.com" port="587" userName="terrylee1218@gmail.com" password="password"/></smtp></mailSettings> </system.net>在瀏覽器中測試Web Service,確保它可以正確的發送郵件。編寫一個簡單用戶界面,如下代碼所示:
<Grid x:Name="LayoutRoot" Background="#333333"><Grid.RowDefinitions><RowDefinition Height="70"></RowDefinition><RowDefinition Height="50"></RowDefinition><RowDefinition Height="50"></RowDefinition><RowDefinition Height="200"></RowDefinition><RowDefinition Height="50"></RowDefinition></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition Width="100"></ColumnDefinition><ColumnDefinition Width="*"></ColumnDefinition></Grid.ColumnDefinitions><local:TitleControl Grid.Row="0" Margin="8,8,8,8" Grid.ColumnSpan="2"></local:TitleControl><TextBlock Text="收件人" Grid.Row="1" Style="{StaticResource textBlockStyle}"></TextBlock><TextBlock Text="主 題" Grid.Row="2" Style="{StaticResource textBlockStyle}"></TextBlock><TextBox x:Name="txtToEmailAddress" Grid.Row="1" Grid.Column="1" Width="440" Height="30" HorizontalAlignment="Left"></TextBox><TextBox x:Name="txtSubject" Grid.Row="2" Grid.Column="1" Width="440" Height="30" HorizontalAlignment="Left"></TextBox><TextBox x:Name="txtBody" Grid.Row="3" Grid.ColumnSpan="2" Width="500" HorizontalAlignment="Left" Height="200" Margin="100 0 0 0"></TextBox><Button x:Name="btnSend" Grid.Row="4" Grid.Column="1" HorizontalAlignment="Left" Content="發 送"Style="{StaticResource buttonStyle}" Width="120" Height="30"Click="OnSendClick"></Button></Grid>在Silverlight項目中添加Web Service引用,并編寫代碼來調用Web Service,相信大家都已經熟悉了該如何調用,如下代碼所示:
void OnSendClick(object sender, RoutedEventArgs e) {// 發送郵件地址String fromAddress = "terrylee1218@gmail.com";EmailServiceSoapClient client = new EmailServiceSoapClient();client.SendCompleted += new EventHandler<SendCompletedEventArgs>(OnSendCompleted);client.SendAsync(fromAddress,this.txtToEmailAddress.Text,this.txtSubject.Text,this.txtBody.Text); }void OnSendCompleted(object sender, SendCompletedEventArgs e) {if (e.Result){HtmlPage.Window.Alert("發送郵件成功!");}else{HtmlPage.Window.Alert("發送郵件成功!");} }運行后輸入相關信息,并發送郵件,如下圖所示:
至此我們就完成一個在Silverlight中發送電子郵件的示例,大家如果有興趣,還可以為其加上更加豐富的功能,如添加抄送人、密送人以及附件等。
本文首發IT168:http://tech.it168.com/msoft/2008-05-30/200805301124268.shtml
轉載于:https://www.cnblogs.com/Terrylee/archive/2008/06/15/using-web-servic-in-silverlight-2.html
總結
以上是生活随笔為你收集整理的一步一步学Silverlight 2系列(33):Silverlight 2应用Web Service两例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [导入]Linux下载工具利器ProZi
- 下一篇: 项目总结之业务规则