Skparmar.files.wordpress.com



I am pure .Net guy but recently i have to work on different platforms like iPhone, Android, HTML clients apart from normal WPF, Silverlight kind of .NET clients. For that i need to have Services which can be consumed by all these clients. Because of not having much experience with WCF Rest Services i went for internet resources but i couldn't found any good solution which explains end to end from creation of REST WCF Service to it's consumption on WPF Client. I went through so many different articles. After digging through all, i created my solution which is working finally.?I am sharing that with you! I hope it will be helpful to you.So lets start from scratch.Create Empty VS Solution. And add new WCF Service Application Project called?WcfRestServiceAfter creating this lets start with creating WCF Rest Service. Add DataContract for the WCF use. To reduce the size of the blog i m avoding including namespaces.namespace WcfRestService{ [DataContract] public class BooksDataContract { [DataMember] public int Title { get; set; } [DataMember] public string Author { get; set; } [DataMember] public decimal Price { get; set; } }}Remove existing Methods of the interface and it's implemenation. Now modify your IService1 interface like this.namespace WcfRestService{ [ServiceContract] public interface IService1 { [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, //BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "/")] IList GetBooks(); }}implement the same interface IService1 to your Service1. Our Method will return the Response in XML Format.namespace WcfRestService { public class Service1 : IService1{public IList<BooksDataContract> GetBooks(){ return Service1BusinessManager.GetBooks(); }}}Add Business logic to give data to Service. you can use your Stored Procedures or any kind of data fetching procedures.I am adding Service1BusinessManager.cs Class to my Project. and implementing below codes for giving data to my Service. I am using just 2 Records for demo purpose.namespace WcfRestService{ public static class Service1BusinessManager { internal static IList<BooksDataContract> GetBooks() { IList<BooksDataContract> books = new List<BooksDataContract>(); BooksDataContract book1 = new BooksDataContract(); book1.Author = "Chetan Bhagat"; book1.Title = "Five Point Someone"; book1.Price = 10.00M; BooksDataContract book2 = new BooksDataContract(); book2.Author = "Sandeep Parmar"; book2.Title = "Journey for Love"; book2.Price = 25.00M; books.Add(book1); books.Add(book2); return books; } }}So our Service is ready now. Let's modify the Web.Config file like this below.<?xml version="1.0"?><configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <system.serviceModel> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> <services> <service behaviorConfiguration="ServiceBehaviour" name="WcfRestService.Service1"> <endpoint address="" behaviorConfiguration="web" binding="webHttpBinding" contract="WcfRestService.IService1" /> </service> </services> <behaviors> <endpointBehaviors> <behavior name="web"> <webHttp /> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name="ServiceBehaviour"> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="false" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel></configuration>After doing this your WCFRestService is ready!?Now lets consume it on WPF Client and test whether it is working or not!?Add WPF Application Project to solution called WpfRestServiceWcfClient You can add your any kind of controls according to your requirement but for demo purpose?i am adding one DataGrid to display the list of books which will be return by our WCF Rest Service.?This is the DataGrid in XAML <DataGrid CanUserReorderColumns="True" RowBackground="WhiteSmoke" CanUserSortColumns="True" HorizontalAlignment="Center" Block.TextAlignment="Center" VerticalAlignment="Top" x:Name="BooksDataGrid" AutoGenerateColumns="False" AlternatingRowBackground="LightGray" RowHeight="20" ColumnWidth="100" IsReadOnly="True" HorizontalContentAlignment="Center" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" Margin="71,42,104,0" Width="328"> <DataGrid.Resources> <Style TargetType="{x:Type DataGridColumnHeader}"> <Setter Property="Background" Value="DarkGray" /> <!--<Setter Property="FontWeight" Value="Bold"/>--> <Setter Property="HorizontalContentAlignment" Value="Center"/> </Style> </DataGrid.Resources> <DataGrid.Columns> <DataGridTemplateColumn Header="Title" IsReadOnly="True"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding Title}"/> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Header="Author" IsReadOnly="True"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding Author}"/> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Header="Price" IsReadOnly="True"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding Price}"/> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid>Now add BookDetails.cs Class in your Client Solution.which will be look like this. class BookDetails : INotifyPropertyChanged { #region ProperyChangeEventHandler public event PropertyChangedEventHandler PropertyChanged; // Create the OnPropertyChanged method to raise the event protected void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } #endregion #region Fields private string title; private string author; private decimal price; #endregion #region Properties public string Title { get { return title; } set { title = value; OnPropertyChanged("Title"); } } public string Author { get { return author; } set { author = value; OnPropertyChanged("Author"); } } public decimal Price { get { return price; } set { price = value; OnPropertyChanged("Price"); } } #endregion }Add these Methods to BookDetail Class #region Methods #region XMLParser internal static List ParseBooksXML(Stream bookRespStream) { StreamReader reader = new StreamReader(bookRespStream, Encoding.UTF8); string xml = reader.ReadToEnd(); string XMLPattern = "xmlns=[^\"]*\"[^\"]*\""; Regex regXML = new Regex(XMLPattern); string Results = regXML.Replace(xml, ""); XmlSerializer deserializer = new XmlSerializer(typeof(List)); byte[] byteArray = Encoding.ASCII.GetBytes(Results); MemoryStream stream = new MemoryStream(byteArray); //convert stream to string TextReader textReader = new StreamReader(stream); List books = new List(); books = (List)deserializer.Deserialize(textReader); textReader.Close(); return books; } #endregion #region DataContractToModel internal static ObservableCollection DataContractToModel(List books) { ObservableCollection booksList = new ObservableCollection(); foreach (var contract in books) { BookDetails book = new BookDetails(); book.Author = contract.Author; book.Title = contract.Title; book.Price = contract.Price; booksList.Add(book); } return booksList; } #endregion #endregionOur BookDetail class is ready now, lets consume the Service. Modify your CodeBehind of MainWindow.xaml.csnamespace WcfRestServiceWpfClient{ /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { static ObservableCollection<BookDetails> Books = new ObservableCollection<BookDetails>(); public MainWindow() { InitializeComponent(); LoadBooks(); } private void LoadBooks() { try { WebRequest booksReq = WebRequest.Create(@""); booksReq.Method = "GET"; HttpWebResponse bookResp = booksReq.GetResponse() as HttpWebResponse; if (bookResp.StatusCode == HttpStatusCode.OK) { using (Stream bookRespStream = bookResp.GetResponseStream()) { List<BooksDataContract> books = new List<BooksDataContract>(); books = BookDetails.ParseBooksXML(bookRespStream); Books = BookDetails.DataContractToModel(books); BooksDataGrid.ItemsSource = Books; } } else { MessageBox.Show("Error Occured"); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } }}If you check XMLParserMethod in BookDetails Class. Response of the Rest Service will be in XML Format which will contain two Objects of BooksDataContract. We have to take them out and make PatientDetails Object which we can add to list and bind to BooksDataGrid. The Generated XML contains some namespaces which will fail while XML Serialization Process so we have to remove those namespace before we Proceed. Those namespaces was creating Invalid Characters errors which took a long time for me to figure out. but I was able to resolve it. Now test the RestFul Service. It Should Display the DataGrid having two Books in it.I will update this blog soon once i create iPhone, Android Clients.... Enjoy and Cheers. Happy Programming!!!Find the Source Codes here!!!? ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download