Silverlight: Consume a web service in Silverlight


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

31 thoughts on “Silverlight: Consume a web service in Silverlight

  1. Thanks for your article. I had no trouble from VS2008 localHost, but I am having difficulty with my deployed solution, consuming emailserv.asmx from mYDomain.com. Any suggestions would be appreciated.

    Regards, cj

    • Can I know what problem exactly you are facing…. I mean any error screen / error message can you show me.. so that I can help you..
      also make sure you have changed your web service url in the web.config file

      Thanks
      Deepu

  2. Thanks Deepu , this article was very helpful in getting me started with using webservices with silverlight , keep the good work going

  3. Thanks Deepu, on localhost it works, but, on real www, no, i changed “localhost” with my site, but, nothing … where did i go wrong ? can u halp me ?, or anyone ?

  4. did you get my message ?
    you have my e-mail (from post), send my empty message and i’ll return the code, because i did know your e-mail

    • Abdull, Can you make sure you have entered a valid SMTP name on the following line

      SmtpClient smtp = new SmtpClient(“127.0.0.1”);

      Also trying throwing exception from the SendMail method..

      try
      {

      }
      catch(Exception exp)
      {
      throw exp;
      }

      Hope this helps
      Thanks
      Deepu

  5. Thank you for the article,

    unfortunately I got message

    “sorry,, unable to send email”

    If I look into the output window in visual studio on local I can see the excepion “System.FormatException’ occurred in System.dll”

    If I try to host the solution in a WebSite if I click on send button, nothing happens

    Maybe there is some error in the code.

    I use Visual Studio 2010 NetFramework 4 (and Silverlight 4)

  6. Hi Deepumi, I am trying to learn about this sending email via SL4 and i am totally new to this. Please could you explain what to put where and which is which such as the e.g (url), smtpclient (127.0.0.1), txtEmail(“from@email”), mailAddress(fromAddress) && (toAddress). I need to understand it clearly and i would be very appreciated if you help me with this. Please let me know if you have a book about SL then i would like to buy it. Thanks very much!

  7. Hi, how do we configure the webconfig file please? I have an interior error message from the client server need urgent help please! thanks

    • No web configuration required but in the ASMX file you have to replace the SMTP Server name like below

      SmtpClient smtp = new SmtpClient(“127.0.0.1”);

      Thanks
      Deepu

  8. I just need a help how to obtain senders Name? it’s so different than asp.net or others. I would be so appreciated if you just give us a hint thanks!

    • Yes it is possible to pass the sender name by adding a parameter in the web method..

      [WebMethod]
      public bool SendMail(string senderName, string fromAddress, string toAddress, string subject, string body)
      {

      }

      From silverlight you need modify the below line..

      EmailServiceSoapClient emailService = new EmailServiceSoapClient(bind, endpoint);

      emailService.SendMailAsync(txtName.Text,txtEmail.Text, “from@emailid.com”, txtSubject.Text, txtMessage.Text);

      That’s all.

      Hope this helps

      Thanks
      Deepu

  9. All i am trying to do is, get additional info from sender, basically i am trying to get sender name or telephone number may be fax or anything.
    I have already tried what you told me but something somewhere is wrong, e.g. i have created a tbx and declared it in .cb page(txtSenderName.Text) where the emailservice.SendMailAsy…. then in the eServ page i am trying to adding it as string as the name you refer i get an error but i managed to add it as like txtSenderName. After i add in Try{ msg.BODY = txtSernderName; and I get absolutely nothing when i fill the email form and click send button. I only get Subject, Email and Message(body) thats it.
    Hope i managed to explain. Thanks again!

  10. Thanks for you post..slowly makes more sense of things. I am however trying to build a contact form using Blend for VS for the windows 8 phone. If you have any advice on this I would be appreciative since at this stage I am getting no where.
    Thanks

Leave a reply to belangermichel Cancel reply