Posted on 7/5/2011

Sending an email from a web page using the Silverlight-enabled WCF Service.

CREATE THE PROJECT

First, using Visual Studio 2010, create a new Silverlight Application project and use ContactEmail as the project’s name.

image

When this dialog appears, make sure the checkbox for “Host the Silverlight application in a new Web Site” is checked.

image

 

DESIGN THE EMAIL FORM

Visual Studio will open the MainPage.xaml file in the IDE.

image

Change the MainPage.xaml file to match the one below.

<UserControl x:Class="ContactEmail.MainPage"
     xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="400" d:DesignWidth="600">
    <Grid x:Name="LayoutRoot" Margin="10">
        <StackPanel x:Name="EmailPanel" Width="293" Canvas.Left="529" Canvas.Top="99" Margin="134,0,135,0">
            <TextBlock x:Name="name" HorizontalAlignment="Left" Text="Name:" />
            <TextBox Name="txtName"   />
            <TextBlock x:Name="phone" HorizontalAlignment="Left" Text="Phone:" />
            <TextBox Name="txtPhone"   />
            <TextBlock x:Name="txtemail" HorizontalAlignment="Left" Text="Email:" />
            <TextBox Name=”txtEmail” TextWrapping="Wrap"/>
            <TextBlock x:Name="txtComment" HorizontalAlignment="Left" Text="Comments:" TextWrapping="Wrap" />
            <RichTextBox  Name="txtComments"  Height="95"/>                      
            <Button Height="33" x:Name="btnSumit"   Content="Submit" Width="80" />
        </StackPanel>
    </Grid>
</UserControl>

Click the Design Tab  - bottom of page – to view the MainPage.xaml. The page should look like the one below. Save the MainPage.xaml.

image 

 

CREATE THE WCF SERVICE

Add a new item to the ContactEmail.Web project.

image

In the Installed Templates – left panel – select Silverlight. From the center panel, select Silverlight-enabled WCF Service. Use EmailService.svc for the name of the service.

image

Visual Studio will add the necessary files to the References folder in the ContactEmail.Web project. Visual Studio will also make changes to the Web.config file in the same project.

Open the Web.Config file and notice the following items that have been added.

  <system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior name="">
                    <serviceMetadata httpGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="false" />
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <bindings>
            <customBinding>
                <binding name="ContactEmail.Web.EmailService.customBinding0">
                    <binaryMessageEncoding />
                    <httpTransport />
                </binding>
            </customBinding>
        </bindings>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
            multipleSiteBindingsEnabled="true" />
        <services>
            <service name="ContactEmail.Web.EmailService">
                <endpoint address="" binding="customBinding" bindingConfiguration="ContactEmail.Web.EmailService.customBinding0"
                    contract="ContactEmail.Web.EmailService" />
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
            </service>
        </services>
    </system.serviceModel>

Build the Solution first. Then right click on the EmailService.svc file in the EmailContact.web project. Select "View in Browser" and the following screen should be displayed.

image

 

CREATE A CLIENT FOR THE EMAIL SERVICE

Open the EmailService.svc.cs file and add the following using statement.

Using System.Net.Mail;

Then add the following code:

 [OperationContract]
        public bool SendEmail(String ClientName, String ClientPhone, String ClientEmail, String Comment)
        {
            try
            {
                //////////////////////////////////
                // BUILD EMAIL MESSAGE STRING //
                ///////////////////////////////// 
                string Filler = "";                
                string MsgBody = "";
 
                MsgBody += "Name:" + Filler.PadLeft(5) + ClientName.Trim() + Environment.NewLine + Environment.NewLine;
                MsgBody += "Email:" + Filler.PadLeft(4) + ClientEmail.ToString() + Environment.NewLine + Environment.NewLine;
                MsgBody += "Phone:" + Filler.PadLeft(4) + ClientPhone + Environment.NewLine + Environment.NewLine;
                MsgBody += "Comments:" + Environment.NewLine + Environment.NewLine;
                MsgBody += Comment + Environment.NewLine;

                string txtEmailTo = "webmaster@yourewbsite.com";
                string userName = "UserName";   // WebMaster's user name
                string passWord = "passWord";   // WebMaster's password

                MailMessage msg = new MailMessage();
                msg.From = new MailAddress(ClientEmail);
                msg.To.Add(new MailAddress(txtEmailTo));
                msg.Subject = "*** Contact from Website ***";
                msg.Body = MsgBody;

                SmtpClient smtp = new SmtpClient("smtp.yourwebsite.com");
                smtp.UseDefaultCredentials = false;
                System.Net.NetworkCredential theCredential = new System.Net.NetworkCredential(userName, passWord);
                smtp.Credentials = theCredential;
                smtp.Send(msg);
            }

            catch (Exception ex)
            {
                return false;
            }

            return true;
        }

Remember to change the values in the txtEmailTo, userName, passWord variables. Also, change the line SmtpClient smtp = new SmtpClient(“smtp.yourwebsite.com”) to your web site.

Save the EmailService.svc.cs file and then Build the project. Now right click in References in the ContactEmail Silverlight project and choose Add Service Reference.

image

Click the Discover button and select the EmailService.svc. Use the Namespace Services and click the OK button.

image

Visual Studio will add the necessary files to the References folder in the ContactEmail Silverlight project.

 

CALL THE EMAIL SERVICE FROM MainPage.Xaml

Open the MainPage.xaml file and click the Design tab at the bottom of the page.  Right click on the Submit button and select properties from the context menu.

Click on Events – at the top of the properties window – and double click on the Click event.

image

Add the following using statement in the MainPage.xaml.cs file

using ContactEmail.EmailServiceReference;

Then add the following code:

private void btnSumit_Click(object sender, RoutedEventArgs e)
        {
            txtComments.SelectAll();

            Services.EmailServiceClient client = new Services.EmailServiceClient();
            client.SendEmailAsync(txtName.Text, txtPhone.Text, txtEmail.Text, txtComments.Selection.Text);
            client.SendEmailCompleted += new EventHandler<Services.SendEmailCompletedEventArgs>(client_SendEmailCompleted);                                
        }

        
        void client_SendEmailCompleted(object sender, Services.SendEmailCompletedEventArgs e)
        {
            if (e.Result == true)
            {
                new messageWindow("Title Information", "Email Successfully Sent.").Show();
            }
            else
            {
                new messageWindow("Title Information", "Email Not Sent.").Show();
            }
        }

 

CREATE THE CHILD WINDOW

From the ComtactEmail Silverlight project select Add, New Item.

image

In the Installed Templates – left panel – select Silverlight. From the center panel, select Silverlight Child Window. Use messageWindow.xaml for the name. Click the Add button to continue.

image

Add the following code to the messageWindow.xaml file.

<controls:ChildWindow x:Class="ContactEmail.messageWindow"
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
           xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
           Width="400" Height="300" 
           Title="messageWindow">
    <Grid x:Name="LayoutRoot" Margin="2">
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>      
        <TextBox Height="21" HorizontalAlignment="Center" Margin="12,108,20,0" Name="Caption" VerticalAlignment="Top" Width="325" BorderThickness="0" Background="Transparent" />
        <Button x:Name="CancelButton" Content="Cancel" Click="CancelButton_Click" Width="75" Height="23" HorizontalAlignment="Right" Margin="0,12,0,0" Grid.Row="1" />
        <Button x:Name="OKButton" Content="OK" Click="OKButton_Click" Width="75" Height="23" HorizontalAlignment="Right" Margin="0,12,79,0" Grid.Row="1" />
    </Grid>
</controls:ChildWindow>

Open the MessageWindow.xaml.cs file and add the following code:

 public MessageWindow(string title, string caption)
        {
            InitializeComponent();
            this.Title = title;
            this.Caption.Text = caption;

            // OkButton properties
            this.OKButton.Width = 75;
            this.OKButton.Height = 30;
            this.OKButton.HorizontalAlignment = HorizontalAlignment.Center;

            // Use OK button only
            this.CancelButton.Visibility = Visibility.Collapsed;
        }

Build the solution and hit F5 to run.

 

PUBLISHING

Before publishing to a web site, open the ServiceReferences.ClientConfig file – in the ContactEmail Silverlight project – and change the endpoint address to your web site’s address.

Change From:

<client>
      <endpoint address="http://localhost:49472/EmailService.svc" binding="customBinding"
       bindingConfiguration="CustomBinding_EmailService" contract="Services.EmailService"
       name="CustomBinding_EmailService" />
</client>

Change To:

<client>
      <endpoint address="http://www.YourWebSite.com/EmailService.svc" binding="customBinding"
       bindingConfiguration="CustomBinding_EmailService" contract="Services.EmailService"
       name="CustomBinding_EmailService" />
</client>

 

Build, Publish, and Run!!!