Quantcast
Channel: Silverlight – Deepu Madhusoodanan's Blog
Viewing all articles
Browse latest Browse all 10

Silverlight: Consume a web service in Silverlight

$
0
0

Silverlight application can talk to the server via web services like ASMX web services or WCF services or REST based services.  (for ex : file uploading to the server or sending emails etc.). In this article I am going to explain how to consume a web service in Silverlight. I am creating a simple contact form in Silverlight 3.0 (see the below image) which sends the contact information as email using ASMX web service. (You can download the entire article from here)

Open VS 2008 (SP 1.0) and create a new project called Contact Form (see the below image) which would be hosting the Silverlight application in a web application project.

Right click the web application project and add a new asmx file for web service (see the below image) and name it as EmailService.ASMX

Copy paste the below code inside the EmailService.asmx file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Net.Mail;

namespace ContactForm.Web
{
 [WebService(Namespace = "http://tempuri.org/")]
 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
 [System.ComponentModel.ToolboxItem(false)]

 public class EmailService : System.Web.Services.WebService
 {
 [WebMethod]
 public bool SendMail(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 = true;

 SmtpClient smtp = new SmtpClient("127.0.0.1"); //replace with your smtp client
 smtp.Send(msg);
 return true;
 }
 catch(Exception exp)
 {
 //log exception here..
 return false;
 }
 }
 }
}

So the next step is creating the contact form interface with xaml markup.

In the xaml page Usercontrol deceleration you may need to include the input control namespace some thing like below and aslo add the reference from the library.

<UserControl x:Class=”ContactForm.MainPage”
xmlns:my=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.Input”

Copy paste the xaml in to the MainPage.xaml page.

<UserControl x:Class=”ContactForm.MainPage”
xmlns:my=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.Input
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;
xmlns:d=”http://schemas.microsoft.com/expression/blend/2008&#8243; xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006&#8243;
mc:Ignorable=”d” d:DesignWidth=”640″ d:DesignHeight=”480″>

<Grid x:Name=”LayoutRoot” Background=”White” Width=”500″>
<Grid x:Name=”contactGrid” Width=”500″>
<Grid.RowDefinitions>
<RowDefinition Height=”50″/>
<RowDefinition Height=”30″/>
<RowDefinition Height=”30″/>
<RowDefinition Height=”30″/>
<RowDefinition Height=”152″/>
<RowDefinition Height=”30″/>
</Grid.RowDefinitions>

<Grid.ColumnDefinitions>
<ColumnDefinition Width=”130″/>
<ColumnDefinition Width=”370″ />
</Grid.ColumnDefinitions>

<my:Label Grid.Column=”0″ FontFamily=”Arial” FontSize=”24″ HorizontalAlignment=”Left” Grid.ColumnSpan=”2″ Grid.Row=”0″ Content=”Contact Me”  />

<my:Label Grid.Column=”0″ HorizontalAlignment=”Right”   FontFamily=”Verdana” FontSize=”13″  Grid.Row=”1″ Content=”*Name : “/>
<TextBox Grid.Column=”1″ FontFamily=”Verdana” Width=”170″ Height=”25″ HorizontalAlignment=”Left” FontSize=”13″ Name=”txtName”  Grid.Row=”1″ Margin=”4,0,0,0″ />

<my:Label Grid.Column=”0″ HorizontalAlignment=”Right”   FontFamily=”Verdana” FontSize=”13″  Grid.Row=”2″ Content=”*Email : “/>
<TextBox Grid.Column=”1″ FontFamily=”Verdana” Width=”170″ Height=”25″ HorizontalAlignment=”Left” FontSize=”13″ Name=”txtEmail”  Grid.Row=”2″ Margin=”4,0,0,0″ />

<my:Label Grid.Column=”0″ HorizontalAlignment=”Right” FontFamily=”Verdana” FontSize=”13″  Grid.Row=”3″ Content=”Subject : “/>
<TextBox Grid.Column=”1″ FontFamily=”Verdana” Width=”170″ Height=”25″ HorizontalAlignment=”Left” FontSize=”13″ Name=”txtSubject”  Grid.Row=”3″ Margin=”4,0,0,0″ />

<my:Label Grid.Column=”0″ HorizontalAlignment=”Right” FontFamily=”Verdana” FontSize=”13″  Grid.Row=”4″ VerticalAlignment=”Top” Content=”*Message : “/>
<TextBox Grid.Column=”1″ FontFamily=”Verdana” Width=”350″ Height=”150″ HorizontalAlignment=”Left” VerticalAlignment=”Top” FontSize=”13″ Name=”txtMessage”  Grid.Row=”4″ Margin=”4,0,0,0″ />

<Button Grid.Column=”0″ Grid.ColumnSpan=”2″ HorizontalAlignment=”Center” Height=”25″ Grid.Row=”5″ Width=”75″ Content=”Send” Name=”btnSend” />

</Grid>
</Grid>
</UserControl>

So the next step is add reference to the web service in the silverlight app.Right click the Silverlight project and add a Service reference (see the below image)

Click the discover button in the image below and get the web service url (if you know the url you can copy paste directly).

In the codebehind page of the xaml file please paste the below code.


using System;
using System.Windows;
using System.Windows.Controls;
using ContactForm.EmailServiceReference;
using System.ServiceModel;
using System.Windows.Browser;

namespace ContactForm
{
 public partial class MainPage : UserControl
 {
 public MainPage()
 {
 InitializeComponent();

 btnSend.Click += new RoutedEventHandler(sendButton_Click);
 }

 private void sendButton_Click(object sender, RoutedEventArgs e)
 {
 if (txtName.Text.Length == 0 || txtEmail.Text.Length == 0 || txtMessage.Text.Length == 0)
 {
 MessageBox.Show("Required fields are missing");
 return;
 }
 string url = HtmlPage.Document.DocumentUri.ToString();

 url = url.Substring(0, url.LastIndexOf("/")) + "/EmailService.asmx";

 BasicHttpBinding bind = new BasicHttpBinding();

 EndpointAddress endpoint = new EndpointAddress(url);

 EmailServiceSoapClient emailService = new EmailServiceSoapClient(bind, endpoint);

 emailService.SendMailAsync(txtEmail.Text, "from@emailid.com", txtSubject.Text, txtMessage.Text);

 emailService.SendMailCompleted += new EventHandler<SendMailCompletedEventArgs>(emailService_Completed);
 }

 private void emailService_Completed(object sender, SendMailCompletedEventArgs e)
 {
 if (e.Result)
 {
 MessageBox.Show("You email has sent successfully");
 }
 else
 {
 MessageBox.Show("Sorry !!! unable to send email");
 }

 }
 }
}

Code Explanation

Once you have completed with add service reference you must include the following namespace in the MainPage.xaml.cs code behind

using ContactForm.EmailServiceReference;    (contact form web service namespace).

using System.ServiceModel; (system web service namespace).

using System.Windows.Browser; (Html Dom namespace).

In the page default constructor I am creating event handler for send button click.

btnSend.Click += new RoutedEventHandler(sendButton_Click);

BasicHttpBinding bind = new BasicHttpBinding();  // initializes http binding to configure endpoints that can communicate ASMX based web service.

EndpointAddress endpoint = new EndpointAddress(url); //provide a unique network address and you can replace with your web service url.

EmailServiceSoapClient emailService = new EmailServiceSoapClient(bind, endpoint);

emailService.SendMailAsync(txtEmail.Text, “from@email.com”, txtSubject.Text, txtMessage.Text); // sending email in Asynchronous method with the some simple parameter  to address, from address, subject and body of the email.

Once the web service method completed emailService_Completed method get fired

emailService.SendMailCompleted += new EventHandler<SendMailCompletedEventArgs>(emailService_Completed);

You can download the entire article from here or copy paste the URL

http://www.4shared.com/file/247655657/750739e9/ContactForm.html

Hope this help and If you have any comments, please feel free to write your feedback.

Thanks
Deepu


Viewing all articles
Browse latest Browse all 10

Trending Articles