DCSIMG
February 2008 - Posts - Gady Elkarif's Blog

Gady Elkarif's Blog

February 2008 - Posts

WCF JSON: Sending Complex Type on Query String

WCF Json: Sending Complex Type on Query String

In the previous post HTTP Web Programming with WCF 3.5: Creating a Template based URI I show how to use WebGet and WebInvoke attributes, which makes the operations avaliable via HTTP.GET and HTTP.POST respectively.

In this post I will show how to send a complex type via query string on WCF operation via HTTP.GET

Service Contract

The following code sample define the service contract and the complex type Product which will send.

    [ServiceContract(Namespace="http://ProductService")]

    public interface IProductService

    {

        [OperationContract, WebGet(ResponseFormat = WebMessageFormat.Json)]

        String GetProduct(Product<Int32> product);

    }

 

    [DataContract]

    public class Product<T>

    {

        private Boolean m_boolValue = true;

        private String m_stringValue = "Hello";

        private T m_genericValue;

 

        [DataMember]

        public Boolean BoolValue

        {

            get { return m_boolValue; }

            set { m_boolValue = value; }

        }

 

        [DataMember]

        public T GenericValue

        {

            get { return m_genericValue; }

            set { m_genericValue = value; }

        }

 

        [DataMember]

        public String StringValue

        {

            get { return m_stringValue; }

            set { m_stringValue = value; }

        }

    }

Service Implementation

The service implementation is as follows:

    public class ProductService : IProductService

    {

        public String GetProduct(Product<Int32> product)

        {

            return String.Format("Product Generic Value = {0}", product.GenericValue.ToString());

        }

    }

And the corresponding web.config:

  <system.serviceModel>

    <services>

      <service

          name="ProductService.ProductService"

          behaviorConfiguration="ProductService.ProductServiceBehavior">

        <endpoint

            address=""

            binding="webHttpBinding"

            contract="ProductService.IProductService"

            behaviorConfiguration="jsonBehavior">

          <identity>

            <dns value="localhost"/>

          </identity>

        </endpoint>

        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>

      </service>

    </services>

    <behaviors>

      <serviceBehaviors>

        <behavior name="ProductService.ProductServiceBehavior">

          <serviceMetadata httpGetEnabled="true"/>

          <serviceDebug includeExceptionDetailInFaults="false"/>

        </behavior>

      </serviceBehaviors>

      <endpointBehaviors>

        <behavior name="jsonBehavior" >

          <enableWebScript/>

        </behavior>

      </endpointBehaviors>

    </behaviors>

  </system.serviceModel>

DataContractJsonSerializer

With DataContractJsonSerializer we can serialize objects to JSON (Java Script Object Notation) and deserializes JSON data to objects.

This serializer is in namespace System.Runtime.Serialization.Json of assembly System.ServiceModel.Web.dll.

The following code sample describes how to serialize object into JSON and deserialize back into object.

        static ProductServiceReference.ProductOfint Deserialize()

        {

            DataContractJsonSerializer ser =

                new DataContractJsonSerializer(typeof(ProductServiceReference.ProductOfint));

 

            using (FileStream fs = File.OpenRead(@"d:\jsonObject.txt"))

            {

                var p = ser.ReadObject(fs) as ProductServiceReference.ProductOfint;

 

                return p;

            }

        }

 

        static void Serialize(ProductServiceReference.ProductOfint product)

        {

            DataContractJsonSerializer ser =

                new DataContractJsonSerializer(typeof(ProductServiceReference.ProductOfint));

 

            using (FileStream fs = File.OpenWrite(@"d:\jsonObject.txt"))

            {

                ser.WriteObject(fs, product);

            }

        }

The type ProductServiceReference.ProductOfint wes generated according to the previous web service contract.

The Client Side

And now, creating a product, and sending him over HTTP.GET:

        var product = new ProductServiceReference.ProductOfint();

        product.BoolValue = false;

        product.StringValue = "Product String";

        product.GenericValue = 123;

 

        // Serialize the product to file system as JSON object

        // Result: {"BoolValue":false,"GenericValue":123,"StringValue":"Product String"}

        Serialize(product);

 

        WebClient client = new WebClient();

 

        client.QueryString["product"] =

            "{\"BoolValue\":false,\"GenericValue\":123,\"StringValue\":\"Product String\"}";

 

        String response =

            client.DownloadString(http://localhost:50304/ProdyctService.svc/GetProduct);

 

        Console.WriteLine(response);

The response from the ProductService is:

WCF JSON

Download the WCF JSON Sample.

Posted: Feb 25 2008, 09:59 AM by egady | with 1 comment(s)
תגים:,

Creating Silverlight Controls and Web Service with ASP.NET Futures

Creating Silverlight Controls and Web Service with ASP.NET Futures

In this post I will demonstrates how Silverlight 1.1 can received and display data from a web service using the controls from ASP.NET Futures package.

Microsoft ASP.NET Futures July 2007

The Microsoft ASP.NET Futures July 2007 release contains an early developer preview of features providing new functionality for ASP.NET and Silverlight.

There are two new ASP.NET server controls: a Media server control for integrating media sources into your web application, such as audio (WMA) and video (WMV), and a XAML server control that enables you to reference your own XAML and associated JavaScript files.

Creating the Web Application

After installing the Microsoft ASP.NET Futures July 2007, open Visual Studio 2008, and create new project of type ASP.NET Ajax Futures Web Application or of type ASP.NET Futures Ajax Web Site.

ASP.NET Futures Enabled Web Application

Add new service which the Silverlight control can get the data from. Lets call it HelloService.asmx.

ASP.NET Futures Enabled Web Application: Add new Web Service

To allow this web service to be called from script using ASP.NET Ajax, uncomment the ScriptService attribute which allowed us to interact with the Xaml object that is going to display the result from this service.

The following sample code describes the web service:

    [WebService(Namespace = "http://tempuri.org/")]

    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

    [ToolboxItem(false)]

    [System.Web.Script.Services.ScriptService]

    public class HelloService : System.Web.Services.WebService

    {

        [WebMethod]

        public String HelloWorld(String name)

        {

            return String.Format("Hello World {0}", name);

        }

    }

Add Silverlight Project

To display the result from the web service inside a Silverlight control, lets add Silveright Project called SilverlightControlDisplay as showing in the following image:

ASP.NET Futures Enabled Web Application: Add new Silverlight Project

Page.Xaml

Add to Page.Xaml file a background color and a text block as showing in the following sample code:

<Canvas x:Name="parentCanvas"

        xmlns="http://schemas.microsoft.com/client/2007"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Loaded="Page_Loaded"

        x:Class="SilverlightControlDisplay.Page;assembly=ClientBin/SilverlightControlDisplay.dll"

        Width="640"

        Height="480"

        >

  <Canvas.Background>

    <LinearGradientBrush>

      <GradientStop Color="Blue" Offset="0" />

      <GradientStop Color="Orange" Offset="1" />

    </LinearGradientBrush>

  </Canvas.Background>

  <TextBlock

    x:Name="tb"

    Text="Hello World!"

    FontSize="36"

    Canvas.Left="10"

    Canvas.Top="10" />

</Canvas>

Add a Web Reference inside the Silverlight Project to the service HelloService.asmx:

ASP.NET Futures Enabled Web Application: Add Web Reference

Page.Xaml.cs

Add MouseLeftButtonDown event lestener to the Silverlight Control, retrieve the data from the web service and display it:

    public partial class Page : Canvas

    {

        public void Page_Loaded(object o, EventArgs e)

        {

            // Required to initialize variables

            InitializeComponent();

 

            tb.MouseLeftButtonDown += new MouseEventHandler(tb_MouseLeftButtonDown);

        }

 

        void tb_MouseLeftButtonDown(object sender, MouseEventArgs e)

        {

            // var - C# 3.0 - The compiler infered the type.

            var svc = new localhost.HelloService();

 

            // Get the data from the Web Service

            String result = svc.HelloWorld(new Random().Next());

 

            // Set the width of the text block

            tb.Width = this.Width;

 

            tb.Text = result;

        }

    }

The asp:Xaml Control

The asp:Xaml control enables the page Default.aspx do display Xaml like any other ASP control. The content of Default.aspx:

<form id="form1" runat="server">

    <asp:ScriptManager ID="ScriptManager1" runat="server" />

    <asp:Xaml runat="server" Width="640" Height="240" XamlUrl="~/Page.Xaml" />

<div>

In order to the Web Application to recognize the Page.Xaml we can right click on the Web Application and select 'Add Silverlight Link...' which add a Page.Xaml copy into the Web Application, and ClientBin folder, which contains the assembly of the Silverlight Project.

ASP.NET Futures Enabled Web Application: Add Silverlight Link...

Select the Silverlight Project...

ASP.NET Futures Enabled Web Application: Add Silverlight Link...

 And the result is...

 ASP.NET Futures Enabled Web Application: Add Silverlight Link...

Now lets start the application, by right click on Default.aspx and select 'View in Browser'. The result is as follows:

ASP.NET Futures Enabled Web Application

After clicking on the text...

ASP.NET Futures Enabled Web Application

After another clicking on the text...

ASP.NET Futures Enabled Web Application

You can download the source code of the Silverlight Control Sample.

CsvReader and Linq

CsvReader and Linq

 In the previous post about My new Innovative project, I introduced a financial personal project that I will develop.

The first problem I want to solve is how to read CSV files, since all the data in are stored in CSV's.

 I develop simple generic CsvReader which helps me to read this data, before I view it in the graph.

The CSV file is looked something like this (I download S&P for the last 5 years from Yahoo):

Yahoo Finance CSV Data


The CSV file can be downloaded from here

CsvReader Usage:

 First define an interface IMarketEntity that the generic reader will fill automatically:

    public interface IMarketEntity

    {

        DateTime Date { get; set; }

        Double Open { get; set; }

        Double High { get; set; }

        Double Low { get; set; }

        Double Close { get; set; }

        Double Volume { get; set; }

        Double AdjClose { get; set; }

    }

The the usage of the CsvReader is very simple: 


        String fileName = "S_and_P_2000_2008_Daily.csv";

 

    CsvReader<MarketEntity> reader = new CsvReader<MarketEntity>(fileName);

 

    ICollection<MarketEntity> data = reader.Parse();

Class MarkerEntity is the implementation of interface IMarketEntity.

 

The CsvReader source code:

    public class CsvReader<T> where T : new()

    {

        private String m_path;

 

        public CsvReader(String path)

        {

            m_path = path;

        }

 

        public ICollection<T> Parse()

        {

            if (File.Exists(m_path) == true)

            {

                using (StreamReader reader = new StreamReader(m_path))

                {

                    String str = reader.ReadToEnd();

 

                    Int32 idx = str.IndexOf("\n");

                    String header = str.Substring(0, idx - 1);

                    String[] headers = header.Split(new Char[] {','} );

 

                    List<PropertyInfo> properties = new List<PropertyInfo>();

                    foreach (String h in headers)

                    {

                        PropertyInfo propertyInfo = typeof(T).GetProperty(h.Replace(" ", ""));

                        properties.Add(propertyInfo);

                    }

 

                    String data = str.Substring(idx + 1);

 

                    return Parse(properties, data);

                }

            }

 

            return null;

        }

 

        private ICollection<T> Parse(List<PropertyInfo> properties, String str)

        {

            ICollection<T> result = new List<T>();

 

            String[] data = str.Split(new Char[] { '\n' });

 

            foreach (String row in data)

            {

                if (String.IsNullOrEmpty(row))

                {

                    break;

                }

                T item = new T();

 

                String[] rowData = row.Substring(0, row.Length - 1).Split(new Char[] { ',' });

 

                Int32 ii = 0;

                foreach (PropertyInfo propertyInfo in properties)

                {

                    Object obj = rowData[ii++];

 

                    switch (propertyInfo.PropertyType.ToString())

                    {

                        case "System.DateTime":

                            obj = DateTime.Parse((String)obj);

                            break;

 

                        case "System.Double":

                            obj = Double.Parse((String)obj);

                            break;

                    }

 

                    propertyInfo.SetValue(item, obj, null);

                }

                result.Add(item);

            }       

 

            return result;

        }

    }

 And now for the Linq part:

 After the CsvReader return me a collection of MarketEntity, I can use Linq to make queries on this collection, here are some samples:

1) Get all the days with value between 1274 to 1416 

    var res1 =

        from e in data

        where (e.Low > 1375 && e.High < 1416)

        select new { Low = e.Low, High = e.High };

2) Get the days with volume > 5700000000

    var res2 =

        from e in data

        where e.Volume > 5700000000

        select e;

3) Get the days with volume > 5700000000

    IEnumerable<MarketEntity> res3 = data.Select(e => e).Where(e => e.Volume > 5700000000);

4) Get the days with volume > 5700000000 - Return only the volume

        var res4 = data.Select(e => new { Volume = e.Volume }).Where(e => e.Volume > 5700000000);

5) Group by days high value / 100

    var res5 =

        from e in data

        where e.High > 1500

        group e.High by e.High / 100 into g

        select new { High = g.Key, Numbers = g };


 The source code can be founded here.


 

Posted: Feb 06 2008, 02:17 PM by egady | with 3 comment(s)
תגים:

My new Innovative Project

My new Innovative Project

Hey Guys,

I realy excited about this post, because I'm starting a new personal innovative development idea!!

Just to give you some hints about this product:

1) It will include some of the most newest Microsoft technologies:

.NET Framework 3.5
IIS 7.0
Silverligth
Entity Framework and Linq
SQL Server
Visual Studio 2008
WCF
ASP.NET Ajax

2) It will combine two of my greates passions: Finance and Technology, towards the goal of simplifying technical analysis for everyone.

More details will follow in my next posts :)
                              Finance

                 Visual Studion 2008           WCF

                                  ASP.NET Ajax

Sql Server     Silverlight      http://blogs.microsoft.co.il/blogs/egady/Images/Finance/IIS7.JPG

              Entity Framework & Linq

               .NET Framework 3.5