Silverlight Dashboard


I  have found a dashboard control from Microsoft expression website (created by infragistics.com) which  inspired me to create a  dashboard control.

Click here to watch live   |   Click here to Download

In this article I’m going to explain the types of controls used to create a interactive dashboard.

  1. Grid based layout
  2. Customer Master / Detail  list
  3. Chart control
  4. Bing Map control
  5. Custom Splash screen


Grid based layout

A simple grid  layout with 2/2 row column.

<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="5"/>
<RowDefinition Height="85"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="250"/>
<ColumnDefinition Width="5"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
</Grid>

Customer Master / Detail  list

For master detail scenario ListBox control is the right choice to build.. The control will list the customer name and location, once you click the detail link its going to take you to a popup window for more information.
<ListBox x:Name="lbCustomer" Style="{StaticResource ListBoxBackground}" SelectionChanged="CustomerChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding ImageSource}" Height="73" Width="73" VerticalAlignment="Top" Margin="0,10,8,0"/>
<StackPanel>
<TextBlock Text="{Binding Name}" Foreground="YellowGreen" FontSize="14" />
<HyperlinkButton Content="Detail" Foreground="DarkRed" Name="lnkDetailCustomer" Click="CustomerDetailClick" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

Chart Controls

Bar Chart

<toolkit:Chart Style="{StaticResource ChartBackground}" Name="chartCoulumn" Width="490" Height="290">
<toolkit:Chart.Series>
<toolkit:ColumnSeries SelectionChanged="ColumnSeriesChanged" Name="chart1" Title="Sales" DependentValuePath="Profit"
IndependentValuePath="Month"
AnimationSequence="Simultaneous"
IsSelectionEnabled="True">
<toolkit:ColumnSeries.DataPointStyle>
<Style TargetType="toolkit:ColumnDataPoint">
<Setter Property="Background" Value="YellowGreen"/>
<Setter Property="BorderBrush" Value="YellowGreen"/>
</Style>
</toolkit:ColumnSeries.DataPointStyle>
</toolkit:ColumnSeries>
</toolkit:Chart.Series>
</toolkit:Chart>

Pie chart

<toolkit:Chart Style="{StaticResource ChartBackground}" x:Name="chartPie" VerticalAlignment="Top" Width="340" Height="290">
<toolkit:Chart.Series>
<toolkit:PieSeries Margin="0,0,0,0" Padding="0,0,0,0" IndependentValuePath="Month"
DependentValuePath="Profit" AnimationSequence="Simultaneous"/>
</toolkit:Chart.Series>
</toolkit:Chart>

Map

<bing:Map Width="600" Grid.Row="2" Margin="2,2,2,2" HorizontalAlignment="Center" VerticalAlignment="Stretch"
CredentialsProvider="<Replace your credential here" Name="map" LogoVisibility="Collapsed" Culture="en-US" >
</bing:Map>

Click here to watch live   |   Click here to Download

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

Animation using PathListBox control in Silverlight


The PathListBox is new control introduced in Silverlight 4.0 for listing items in a various shapes like path, circle, arc, rectangle etc. This control is similar to traditional ListBox control which support data binding and display of one or more items at design time or dynamically at run time. The pathlistbox provides many properties like orienation, padding etc.

Watch Video |  Live Demo Download Source Code | Download Presentation


In this tutorial, we’ll create a simple animation using PathListBox Control..

Open Expression Blend Editor & Create a new project in Silverlight Application + Website.

Add a new shape  Ellipse in to the page.

Add a PathListBox control in to the page(PLB).

Drag & drop few images in to PLB control. (Press control to select multiple items from the project properties).

 Select PLB control from object & time line window.

Go to PLB control properties window and find out Layout Paths.

Click on select an object to use as a LayoutPath.

Select Ellipse shape as the LayoutPath


The images should show in circular layout path


Add a Projection for Ellipse  shape called PlaneProjection to rotate the Ellipse.

Add a StoryBoad control from object & time line window.

Switch to XAML version and write few lines of XAML code for animation purpose.

Add a Double Animation inside the StoryBoard control and set Target name & properties.

Add the following line of code in the Page Load method in order to start the animation.

Hit F5 and see the demo.


Watch Video |  Live Demo Download Source Code | Download Presentation

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

Thanks
Deepu

Silverlight Integration in MOSS 2007 with out WebPart


In this article I will walk you through how you can integrate a Silverlight application in Sharepoint with out using any webpart. (Download the STP file)



I will use one of  my existing silverlight slide show application for this demo..

Upload your silverlight related files in the sharepoint repository,  here I  am uploading Silvrlight.js, Silverlight XAP file  and images folder in the Shared Document library


The next step is open the website in  SPD (Sharepoint Designer) and create a aspx page under Shared Documents library and add some markup code inside the content place holder (PlaceHolderMain) and copy paste the silverlight object and javascript code.

Save & preview the page in browser you should be able to see your Silverlight application running inside  Sharepoint..

Download the STP file

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

Thanks
Deepu

Export Data Grid to Excel in Silverlight 4.0


One of the great feature in Silverlight 4.0 is  COM interoperability, now your Silverlight application can talk with Office applications using Com Automation Factory. This feature requires a trusted application (elevated permissions). In this article I am going to explain how you can export your data from datagrid to excel spread sheet as  OOB (Out of browser) application using C# 4.0 magic keyword called “dynamic“.

You can Download the complete source code from here

Create a new Silverlgiht 4.0 project using VS 2010 and add Microsoft.CSharp as reference (for C# 4.0 dynamic keyword) and also the add the name space System.Runtime.InteropServices.Automation for  com interoperability

I am using a customer class with some getter and setter properties to bind the datagrid.

Customer Class


using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Runtime.InteropServices.Automation;

 public class Customer
 {
 public string FirstName { get; set; }
 public string LastName { get; set; }
 public int Age { get; set; }
 public bool IsSubscribed { get; set; }
 }

Method for Binding customer list to the Data Grid

 public ExportToExcel()
 {
 InitializeComponent();
 BindDataGrid();
 }

 void BindDataGrid()
 {
 int count = 10;
 List<Customer> customers = new List<Customer>();
 for (int i = 0; i < count; i++)
 {
 customers.Add(new Customer()
 {
 FirstName = "First Name " + i,
 LastName = "Last Name " + i,
 Age = i + 10,
 IsSubscribed = (i % 2 == 0)
 });
 }
 dgCustomers.ItemsSource = customers;
 }

Method for exporting data from data grid to excel spread sheet

 void GenerateSpreadSheet(object sender, RoutedEventArgs e)
 {
 int rowIndex = 1;
 int coulmnIndex = 1;

 try
 {
 dynamic excel = AutomationFactory.CreateObject("Excel.Application");

 excel.workbooks.Add();

 dynamic sheet = excel.ActiveSheet;

 for (int i = 0; i < dgCustomers.Columns.Count; ++i)
 {
 dynamic headerCell = sheet.Cells[rowIndex, coulmnIndex + i];
 headerCell.Value = dgCustomers.Columns[i].Header;
 headerCell.Font.Bold = true;
 headerCell.Interior.Color = 0xFF00;
 }

 foreach (Customer customer in dgCustomers.ItemsSource)
 {
 rowIndex++;

 //column 1
 dynamic cellFirstName = sheet.Cells[rowIndex, 1];
 cellFirstName.Value = customer.FirstName;
 cellFirstName.Font.Color = 003399;

 //column 2
 dynamic cellLastName = sheet.Cells[rowIndex, 2];
 cellLastName.Value = customer.LastName;
 cellLastName.Font.Color = 003399;

 //column 3
 dynamic cellAge = sheet.Cells[rowIndex, 3];
 cellAge.Value = customer.Age;
 cellAge.Font.Color = 003399;

 //column 4
 dynamic cellSubscribed = sheet.Cells[rowIndex, 4];
 cellSubscribed.Value = customer.IsSubscribed ? "Yes" : "No";
 cellSubscribed.Font.Color = 003399;
 }
 excel.Visible = true;
 }
 catch (Exception ex)
 {
 MessageBox.Show("Error generating excel: " + ex.Message);
 }
 }

The xaml code creates a data grid and a button

<Grid x:Name="LayoutRoot" Background="White">
 <Grid.RowDefinitions>
 <RowDefinition Height="350"></RowDefinition>
 <RowDefinition Height="5"></RowDefinition>
 <RowDefinition Height="25"></RowDefinition>
 <RowDefinition Height="*"></RowDefinition>
 </Grid.RowDefinitions>
 <my:DataGrid x:Name="dgCustomers" Grid.Row="0" AutoGenerateColumns="True" HeadersVisibility="All"
 RowBackground="Azure" AlternatingRowBackground="LightSteelBlue" ColumnWidth="85" RowHeight="30">
 </my:DataGrid>
 <Button  Grid.Row="2" Content="Export To Excel" Height="25" Width="120" Name="btnExportExcel" Click="GenerateSpreadSheet"  />
 </Grid>

Out of Browser set up

It is really easy to make a Silverlight applicaton as run out of browser mode. Right click the Silverlight project, select properties and check the ENABLE RUNNING APPLICATION OUT OF THE BROWSER.

Elevated permissions (Trusted Application)

Right click Silverlight Project – > Select Properties – > Click Out-Of-Browser Settings

You can Download the complete source code from here

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

Thanks
Deepu

Simple Image Scroller Slide Show using Silverlight ListBox control


Last week I was working on a image scroll-er slide show using silverlight listbox control and it worked great and I thought I’d  share this.

Click here to view the live demo (images may take a while to load)
Click here to download the article

If you find the Image Scroller code library useful, please consider donating

Xaml C# Code

public class ImageScroller
 {
 public string Url { get; set; }
 }

 public partial class ImageGallery : UserControl
 {
 int index = 0;

 void StartSlideShow()
 {
 DispatcherTimer timer = new DispatcherTimer();
 timer.Interval = TimeSpan.FromMilliseconds(2500); //delayed for 2.5 seconds
 timer.Tick += (sender, e) =>
 {
 lbScrollGallery.ScrollIntoView(lbScrollGallery.Items[index]); //scroll to the current item
 lbScrollGallery.SelectedIndex = index; //highlight the selected item in the list box scroller
 ImageScroller item = (ImageScroller)lbScrollGallery.Items[index]; // getting the current item
 imgPreview.Source = new BitmapImage(new Uri(item.Url, UriKind.Relative));
 if (index < lbScrollGallery.Items.Count - 1)
 {
 index++;
 }
 else
 {
 lbScrollGallery.ScrollIntoView(lbScrollGallery.Items[0]); //scroll to the first item
 index = 0; //reset the index when it reaches to the last item
 }
 };
 timer.Start();
 }

 public ImageGallery()
 {
 InitializeComponent();
 LoadImages();
 StartSlideShow();
 }

 void LoadImages()
 {
 lbScrollGallery.ItemsSource = new List<ImageScroller>
 {
 new ImageScroller
 {
 Url = "images/Chrysanthemum.jpg"
 },
 new ImageScroller
 {
 Url = "images/Desert.jpg"
 },
 new ImageScroller
 {
 Url = "images/Hydrangeas.jpg"
 },
 new ImageScroller
 {
 Url = "images/Jellyfish.jpg"
 },
 new ImageScroller
 {
 Url = "images/Koala.jpg"
 },
 new ImageScroller
 {
 Url = "images/Lighthouse.jpg"
 },
 new ImageScroller
 {
 Url = "images/Penguins.jpg"
 },
 new ImageScroller
 {
 Url = "images/Tulips.jpg"
 }
 };

 imgPreview.Source = new BitmapImage(new Uri("images/Chrysanthemum.jpg", UriKind.Relative)); //load default image while page loads
 }

 void ScrollerSelectionChanged(object sender, SelectionChangedEventArgs e)
 {
 ListBox listbox = (ListBox)sender;
 ImageScroller item = (ImageScroller)listbox.SelectedItem;
 if(item != null && ! string.IsNullOrEmpty(item.Url))
 {
 imgPreview.Source = new BitmapImage(new Uri(item.Url, UriKind.Relative));
 index = listbox.SelectedIndex;
 lbScrollGallery.ScrollIntoView(lbScrollGallery.Items[index]);
 }
 }
 }

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

Click here to view the live demo (images may take a while to load)

You can download the entire article from here

If you find the Image Scroller code library useful, please consider donating

Thanks
Deepu

Loading User Controls Dynamically in Silverlight


When you develop Silverlight web sites you may need to change the content that’s shown in the Silverlight page programmatically, normally changing the layout controls or child controls etc..

In the above image you can see three navigation button’s and when you press each button the content will load dynamically from each separate user control XAML file (shown right side of the image) and render the content inside the canvas.

The below few lines of code which loads the control loading  dynamically and render in to the canvas control

 Type type = this.GetType();
 Assembly assembly = type.Assembly;
 UserControl newPage = (UserControl)assembly.CreateInstance(type.Namespace + "." + "ControlName"); //replace with your user control class name
 canvasBody.Children.Clear();
 canvasBody.Children.Add(newPage);

In the each  button control I am setting the datacontext attribute value as the User Control Class Name ie DataContext=”HomeControl”

XAML Markup

<Canvas Grid.Row="0" Grid.Column="0" Background="Black">
<Button Width="100" DataContext="HomeControl" Canvas.Top="50" Click="Navigation_Click" Canvas.Left="25" Content="Home"/>
<Button Width="100" DataContext="AboutControl" Canvas.Top="50" Click="Navigation_Click" Canvas.Left="140" Content="About"/>
<Button Width="100" DataContext="ContactControl" Canvas.Top="50" Click="Navigation_Click" Canvas.Left="255" Content="Contact"/>
</Canvas>

<Canvas Name="canvasBody" Grid.Row="1"  Grid.Column="0" Background="Black" />

Code behind

 public DefaultPage()
 {
 InitializeComponent();
 RenderControl("HomeControl"); //load default control for home page.
 }

 private void Navigation_Click(object sender, RoutedEventArgs e)
 {
 Button btn = sender as Button;
 if (btn != null && btn.DataContext != null)
 {
     RenderControl(btn.DataContext.ToString());
 }
 }

 void RenderControl(string currentControl)
 {
 Type type = this.GetType();
 Assembly assembly = type.Assembly;
 UserControl newPage = (UserControl)assembly.CreateInstance(type.Namespace + "." + currentControl);
 canvasBody.Children.Clear();
 canvasBody.Children.Add(newPage);
 }

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

Thanks
Deepu

Multiple file uploading in Silverlight


In this article I am going to explain how we can upload multiple files in Silverlight 3.0 using OpenFileDialog class

Click here to download the article

Open VS 2008 and create a new Xaml file called MultiFileUploader.xaml. Copy paste the below markup.

<Canvas Width=”640″>

<TextBlock Canvas.Left=”300″ HorizontalAlignment=”Center” Canvas.Top=”150″ x:Name=”txtProgress”  Foreground=”Green” Width=”120″/>

<Button Canvas.Left=”300″ HorizontalAlignment=”Center” Canvas.Top=”180″ Click=”FileUpload_Click” Width=”100″ Height=”25″ Content=”Select Files”/>

</Canvas>

In above Xaml I have placed two controls ie Button and Textbox.  Button control for selecting files and Texbox control,
shows the total file count which is uploaded in the server.

Code behind for MultiFileUploader.xaml.cs

int totalFilesToUpload = 0;
int totalFilesUploaded = 0;

private void FileUpload_Click(object sender, RoutedEventArgs e)
 {
 this.txtProgress.Text = string.Empty;

 OpenFileDialog oFileDialog = new OpenFileDialog();
 oFileDialog.Filter = "All Image Files ( JPEG,GIF,BMP,PNG)|*.jpg;*.jpeg;*.gif;*.bmp;*.png|JPEG Files ( *.jpg;*.jpeg )|*.jpg;*.jpeg|GIF Files ( *.gif )|*.gif|BMP Files ( *.bmp )|*.bmp|PNG Files ( *.png )|*.png";
 oFileDialog.FilterIndex = 1;
 oFileDialog.Multiselect = true;

 string data = string.Empty;

 if (oFileDialog.ShowDialog() == true)
 {
 foreach (var file in oFileDialog.Files)
 {
 using (System.IO.Stream fileStream = GetFileData(file.OpenRead()))
 {
 StreamResourceInfo oStreamResource = new StreamResourceInfo(fileStream, null);

 byte[] array = new byte[oStreamResource.Stream.Length];

 oStreamResource.Stream.Read(array, 0, (int)oStreamResource.Stream.Length);

 data = Convert.ToBase64String(array);

 WebClient oWebClient = new WebClient();

 string fileName = Guid.NewGuid().ToString().Replace("-", "") + file.Extension;

 oWebClient.UploadStringAsync(new Uri("http://localhost:50848/FileUpload.ashx?file=" + fileName), null, data, fileName);

 oWebClient.UploadProgressChanged += new UploadProgressChangedEventHandler(oWebClient_UploadtxtProgressChanged);

 totalFilesToUpload += 1;

 data = string.Empty;
 }
 }
 }

 }

 System.IO.MemoryStream GetFileData(System.IO.Stream oFileStream)
 {
 oFileStream.Seek(0, System.IO.SeekOrigin.Begin);
 byte[] data = new byte[oFileStream.Length];
 oFileStream.Read(data, 0, (int)oFileStream.Length);
 return new System.IO.MemoryStream(data);
 }

 void oWebClient_UploadtxtProgressChanged(object sender, UploadProgressChangedEventArgs e)
 {
 totalFilesUploaded += 1;

 txtProgress.Text = !string.IsNullOrEmpty(txtProgress.Text) ? (int.Parse(txtProgress.Text) + e.BytesSent).ToString() : e.BytesSent.ToString();

 if (totalFilesUploaded == totalFilesToUpload)
 {
 txtProgress.Text = totalFilesUploaded + " files uploaded successfully (" +  txtProgress.Text + " bytes sent )";
 }
 }

The next step I am going to create a receiver application which can convert the stream object to image file and save to server. I am creating a GenericHandler  file to achieve this task (You can do it in Aspx page also).

using System;
using System.Web;
using System.IO;

namespace SilverlightApplicationDemo.Web
{
    public class FileUpload : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            var fileName = context.Request["file"];
            string data;
            using (StreamReader sr = new StreamReader(context.Request.InputStream))
            {
                data = sr.ReadToEnd();
                byte[] array = Convert.FromBase64String(data);
                using (FileStream fs = new FileStream(context.Server.MapPath("~/images/") + fileName, FileMode.Create))
                {
                    fs.Write(array, 0, array.Length);
                }
            }

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

Note :  I have hard-coded the FileUpload url as (http://localhost:50848/FileUpload.ashx). Don’t forget to replace with your file  upload URL.

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

You can download the entire article from here

Thanks
Deepu

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

Silverlight:A Simple Image ZoomIn Animation


The article describes how we can create a simple Image zoom in and zoom out animation using Silverlight. The interesting thing in Silverlight is most of the animation control we can handle from markup language called XAML.  In order to achieve this we  have to use the StoryBoard & DoubleAnimation class. I am going to write a little XAML code on below.  You can download the  article source code from the bottom of the page.

Click here to view the “Live Demo”

<UserControl.Resources>
<Storyboard x:Name=”storyboard” Storyboard.TargetName=”image1″>
<DoubleAnimation Storyboard.TargetProperty=”Width” To=”600″ Duration=”0:0:2″></DoubleAnimation>
<DoubleAnimation Storyboard.TargetProperty=”Height” To=”600″ Duration=”0:0:5″></DoubleAnimation>
</Storyboard>
</UserControl.Resources>

In the Storyboard mark up you can see a attribute called Storyboard.TargetName which is the target control name. Here I am going to use the Image control because that is the target control which we are doing the animation.  The next markup is DoubleAnimation we should mention what attribute we want to animate may be width or height or opacity that depends on the Target Control attributes. Here I am going to ZoomIn  the Image so I have to use width and height properties and finally duration will control the time delay.

<Grid x:Name=”LayoutRoot” Width=”610″ Height=”610″>
<Image Height=”40″ Source=”Tulips.jpg” HorizontalAlignment=”Left”   Name=”image1″  VerticalAlignment=”Top” Width=”50″ />
<Button Content=”Zoom In” Height=”23″ HorizontalAlignment=”Left” Margin=”12,469,0,0″ Name=”btnZoomIn” VerticalAlignment=”Top” Width=”75″ Click=”ZoomIn_Click” />
<Button Content=”Zoom Out” Height=”23″ HorizontalAlignment=”Left” Margin=”97,468,0,0″ Name=”btnZoomOut” VerticalAlignment=”Top” Width=”75″ Click=”ZoomOut_Click” />
</Grid>

The above XAML has a Image cotrol which simply binds the Image name to the source attribute and two buttons for zoomIn and zoomOut functionaly.

XAML code behind

private void ZoomIn_Click(object sender, RoutedEventArgs e)
{
storyboard.Begin();
}

private void ZoomOut_Click(object sender, RoutedEventArgs e)
{
storyboard.Stop();
}

=====
The above method will have the functionality to start and stop the story board class.

That’s all we are ready to go now.. Live Demo

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

http://www.4shared.com/file/231292567/f6cf7ffe/ImageZoonInAnimations.html  in to your browser.

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

Thanks
Deepu

Silverlight:Change Button Background color


It is really hard when you want to remove the gradient effect in silverlight button control using designer mode.
I have struggled a lot to achieve this and finally I could solve this issue and thought of sharing this to every one.
By Default the if you try to create a button control and change the background color it look some thing like below

<Button x:Name=”btnTest” Content=”Default Background Color” Background=”Orange” Width=”170″ Height=”30″ HorizontalAlignment=”Left”>

I was expecting a orange color as the background of the button and I got in gradient effect..

So how do I get rid of this gradient effect.. The Below code resolve this issue

<Button Width=”100″ Height=”30″ Content=”Click Me !!!” Foreground=”White” >
<Button.Template>
<ControlTemplate TargetType=”Button”>
<Border x:Name=”Border” Background=”Orange”>
<ContentPresenter VerticalAlignment=”Center” HorizontalAlignment=”Center” />
</Border>
</ControlTemplate>
</Button.Template>
</Button>

and produces the following output.

Again if you want to customize some thing like rounded curve button you may need to add a attribute called CornerRadius.

<Button Width=”100″ Height=”30″ Content=”Click Me !!!” Foreground=”White” >
<Button.Template>
<ControlTemplate TargetType=”Button”>
<Border x:Name=”Border” Background=”Orange”
CornerRadius=”4″>
<ContentPresenter VerticalAlignment=”Center” HorizontalAlignment=”Center” />
</Border>
</ControlTemplate>
</Button.Template>
</Button>

and produces the following output.

Create button background from codebehind

StringBuilder sb = new StringBuilder();
sb.Append( "<ControlTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' 
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' ");
sb.Append("xmlns:data='clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data'
xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006' ");
sb.Append("TargetType='Button' >");
sb.Append("<Border x:Name=\"Border\" Background=\"Orange\" CornerRadius=\"4\"><ContentPresenter VerticalAlignment=\"Center\" HorizontalAlignment=\"Center\" /></Border> ");
sb.Append("</ControlTemplate> ");

Button btn = new Button();
btn.Width = width;
btn.Height = height;
btn.Content = content;
btn.Foreground = new SolidColorBrush(Colors.White);

ControlTemplate ct = XamlReader.Load(sb.ToString()) as ControlTemplate;
btn.Template = ct;
cnvParent.Children.Add(btn);

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

Thanks
Deepu