Silverlight 2 series (33): Silverlight 2 Application Web Service

Source: Internet
Author: User
Tags mailmessage smtpclient
Overview

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 use Web Service in Silverlight 2 to upload files and send emails.

Use Web Service to upload files

I will use an example to demonstrate how to use Web Service to upload files to the server. 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:

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;    }}

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:

<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 = "Upload" 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>

Upload a file by calling Web Service. The OpenFileDialog object dialog box is used to select a file. This object returns the selected file as Stream, the following code converts Stream into a byte and passes it to 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. selectedFil E. 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 = "File Uploaded! ";}}

After running the program, select a file and upload it, as shown in:

So far, we have completed an example of using Web Service to upload files.

Use Web Service to send emails

As we all know, sending emails requires the SMTP protocol. Silverlight does not support SMTP communication, but we can use Web Service to send emails. This section uses an example to explain the final effect of this content, as shown in:

First, add an ASP. NET Web Service and implements WebMethod. This method accepts four parameters: sender, recipient, subject, and content, and uses the SmtpClient object to send emails, you can refer to MSDN, which is located in System. net. under the Mail namespace. The following code is used:

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;        }       }}

To use SmtpClient, You need to configure the email server in the Web. config file. Here, Google's server is used. You can use your Gmail account, as shown in the code below:

<system.net>  <mailSettings>    <smtp>      <network host="smtp.gmail.com" port="587" userName="terrylee1218@gmail.com" password="password"/>    </smtp>  </mailSettings></system.net>

Test the Web Service in the browser to ensure that it can send emails correctly. Compile a simple user interface, as shown in the following code:

<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" Grid. columnSpan = "2"> </local: TitleControl> <TextBlock Text = "recipient" Grid. row = "1" Style = "{StaticResource textBlockStyle}"> </TextBlock> <TextBlock Text = "main question" 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 = "Courier" Style = "{StaticResource buttonStyle}" Width = "120" Height = "30" Click = "OnSendClick"> </Button> </Grid>

Add a Web Service reference in the Silverlight project and write code to call the Web Service. I believe everyone is familiar with how to call the Service, as shown in the following code:

Void OnSendClick (object sender, RoutedEventArgs e) {// send email address String fromAddress = "terrylee1218@gmail.com"; EmailServiceSoapClient client = new EmailServiceSoapClient (); client. sendCompleted + = new EventHandler <SendCompletedEventArgs> (OnSendCompleted); client. sendAsync (fromAddress, this.txt ToEmailAddress. text, this.txt Subject. text, this.txt Body. text);} void OnSendCompleted (object sender, SendComple TedEventArgs e) {if (e. Result) {HtmlPage. Window. Alert ("email sent successfully! ");} Else {HtmlPage. Window. Alert (" email sent successfully! ");}}

Enter relevant information and send an email after running, as shown in:

So far, we have completed an example of sending an email in Silverlight. If you are interested, you can add more features to it, such as adding CC users, BCC, and attachments.

This article first IT168: http://tech.it168.com/msoft/2008-05-30/200805301124268.shtml

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.