SQL Azure to Developers: Some Basic Concepts

Objective

In this post we will focus on overview of SQL Azure along with a first look on SQL Azure Management Portal. Essentially we will cover in this part

  • What is Cloud Database
  • What is SQL Azure
  • Create and Manage Database in SQL Azure
  • Fire Wall in SQL Azure

What is Cloud Database?

For a developer a better perspective on database is always better and it helps to write different layers of application in effective and efficient way. Database in cloud is new buzz and very much appreciative technology. There are two words constitute CLOUD DATABASE. We are very much aware of term DATABASE whereas CLOUD may be newer or ambiguous to us.

In very broader term, Cloud can be termed as next generation of Internet. On a normal scenario you find on which server your database is residing. You have very minute level administrative control on database server and you have a physical sense of database server. Whereas imagine if you are not aware of where your database is residing? , you access and perform all operation on database via Internet. Scalability, Manageability and all other administration task on database is performed by some third party. You only pay for the amount of data residing on the database provided by third party. You work on use and pay model. In that case you can say database is in cloud.

There are many cloud service providers like Microsoft, Amazon etc. to name a few. All vendors do have their own cloud servicing model and pricing. Microsoft cloud platform is known as Windows Azure. Essentially Windows Azure is cloud operating system offered by Microsoft. As part of Windows Azure, there are five services offered by Microsoft

  1. Windows Azure
  2. SQL Azure
  3. Office 365
  4. App Fabric and Caching services
  5. Marketplace

In this three part article, we are going to focus our discussion to SQL Azure. We will focus on essential aspects need to know about SQL Azure as dot net developer. To be very precise on SQL Azure, we can say “SQL Server in cloud is known as SQL Azure “. When you have chosen to create relational database in Microsoft data center then you can say your database is in cloud or in SQL Azure.

In this article, we will cover

  • What is SQL Azure?
  • A first look on SQL Azure Management portal
  • SQL Azure Database edition
  • Firewall setting for SQL Azure

What is SQL Azure?

 

 

 

SQL Azure is cloud based service from Microsoft. It allows you to create your Database in one of the Microsoft Data center. In a very generic statement we can say SQL Azure allows creating Database on the cloud. It provides highly available database. It is based on SQL Server. It supports built in Fault tolerance and no physical administration is required. It supports TSQL and SSMS.

Advantage of using SQL Azure

  • In built Fault tolerance support
  • No Physical Administration required
  • Very high availability
  • Multitenant
  • Pay as you go pricing
  • Support of TSQL
  • Highly scalable

We have done enough of theoretical discussion, now let us login to SQL Azure portal and create a database in the cloud.

Create and Manage Database in SQL Azure

To create Database in SQL Azure, You need to follow below steps

Step1

Login SQL Azure portal with your live credential

https://sql.azure.com/

Step 2

Click on SQL Azure tab and select Project

image

Step3

Click on the project. In this case project name is debugmode. After clicking on project, you will get listed the entire database created in your SQL Azure account.

Here in this account there are two database already created. They are master and student database. Master database is default database created by SQL Azure.

image

Step 4

Click on Create Database

image

Step 5

Give the name of Database. Select the edition as Web or Business and specify the max size of database.

image

Step 6

After that click on Create you can see on Databases tab that Demo1 database has been created.

image

 

Different types of SQL Azure Database edition

At time of creating Database you might have seen, there were two Database editions

image

Web Edition Relational Database includes:

  • Up to 5 GB of T-SQL based relational database
  • Self-managed DB, auto high availability and fault tolerance
  • Support existing tools like Visual Studio, SSMS, SSIS, BCP
  • Best suited for Web application, Departmental custom apps

Business Edition DB includes:

  • Up to 150 GB of T-SQL based relational database*
  • Self-managed DB, auto high availability and fault tolerance
  • Additional features in the future like auto-partition, CLR, fanouts etc
  • Support existing tools like Visual Studio, SSMS, SSIS, BCP
  • Best suited for Saas ISV apps, custom Web application, Departmental apps

While creating Database in SQL Azure you can choose among either of two options

image

If we choose Web Edition then Maximum size we can choose is 5 GB

image

If we choose Business Edition then Maximum size we can choose is 150 GB

SQL Azure portal is having very effective Silverlight based user interactive UI and many more operations can be performed through the UI. There is new database manager and it allows us to perform operations at table and row level.

Now we can perform many more operations through Database option of new Windows azure portal.

  • Create a database
  • Create/ delete a table
  • Create/edit/delete rows of table.
  • Create/edit stored procedure
  • Create/edit views
  • Create / execute queries etc. . . .

You can manage database using Data Base Manager.

image

Accept given term and conditions and click Ok. you will get popup asking password to connect to database. Provide password and click on Connect.

image

After logon you will get Mange user interface as below,

 

 

image

And in left hand panel you will have options as below,

image

For more on this watch the video of the post.

Firewall in SQL Azure

In this way, you can perform almost all the basic operations from new SQL Azure Data Base Manager.

SQL Azure provides security via Firewall. By default Database created on SQL Azure is blocked by firewall for the security reason. Any try to external access or access from any other Azure application is blocked by firewall.

image

Image taken from MSDN

Connection Strings

You can copy Connection string from SQL Azure portal as well.

image

Connecting from Local system

When we want to connect SQL Azure portal from network system or local system then we need to configure firewall at local system. We need to create an exception for port 1433 at local firewall

Connecting from Internet

The entire request to connect to SQL Azure from Internet is blocked by SQL Azure firewall. When a request comes from Internet

  1. SQL Azure checks the IP address of system making the request
  2. f IP address is in between the range of IP address set as firewall rule of SQL Azure portal then connection get established.

Firewall rules can be Added, Updated and Deleted in two ways

  1. Using SQL Azure Portal
  2. Using SQL Azure API

Manipulating Firewall rules using SQL Azure Portal

After login to Windows Azure portal, click on Database option and select Database server from left tab. You can see firewall rules listed there.

image

A new rule can be added by clicking on Add button.

image

To connect from other Windows Azure application for same subscription check the check box

image

An existing firewall rules can be edited and deleted also by selecting Edit and delete option respectively.

Conclusion

In this part we discussed various elementary concepts of cloud database and SQL Azure. In further part we will go deep to understand other essential concepts needed to know as developer.

Video on How to work with AutoCompleteBox in Windows Phone 7

Video on How to Protect Password in Windows Phone 7 using Data Protection API

Read more here

Video on How to consume WCF REST Service with JSON in Windows Phone 7

 

You can read more here

 

Consuming JSON in Windows 8 Metro style Application using WinJS

In this post I will discuss way of consuming JSON service in Windows 8 metro style application. In this post,

  • Metro app is created using HTML 5 and Service is being consumed using WinJS
  • Service is created service using WCF and REST is on service using webHttpBinding.

Since creating simple REST Service returning JSON is not main focus of this post, so I will show creation WCF REST Service returning JSON in later part of this post.

Consuming JSON using WinJS

We need to consume service in HTML 5 Metro application. Very first let us design HTML page

default.html


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>HelloWorldJavaScript</title>
<!-- WinJS references -->
<link rel="stylesheet" href="/winjs/css/ui-dark.css" />
<script src="/winjs/js/base.js"></script>
<script src="/winjs/js/wwaapp.js"></script>
<!-- HelloWorldJavaScript references -->
<link rel="stylesheet" href="/css/default.css" />
<script src="/js/default.js"></script>
</head>
<body>
<label >First Number</label>
<input id="TextboxFirstNumber" type="text" />
<br/>
<label >Second Number</label>
<input id="TextboxSecondNumber" type="text" />
<br />
<button id="ButtonAdd">+</button>
<br />
<span id="SpanResult" />
</body>
</html>

I have put a button and two text boxes. User will input number to be added in textboxes and on click event of the button service would get called.

In JS file to make call to REST Service returning JSON, we need to make call using WinJS.xhr.

image

In above snippet

  1. url is URL of REST Service
  2. Using JSON.parse we are parsing returned text
  3. ResultSpan is span in which result is being displayed.

Putting all code together as below,

default.js


(function () {
'use strict';


WinJS.Application.onmainwindowactivated = function (e) {
if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {



Calculator();

}
function Calculator() {
var Number1 = document.getElementById('TextboxFirstNumber');
var Number2 = document.getElementById('TextboxSecondNumber');
var ResultSpan = document.getElementById('SpanResult');
var ButtonToAdd = document.getElementById('ButtonAdd');
ButtonToAdd.addEventListener('click', function () {
var baseURl = "http://test2dj8.cloudapp.net/Service1.svc/rest/add/";
var url = baseURl+Number1.value+"/"+Number2.value;
WinJS.xhr({ url: url }).then(function (r) {
var result = JSON.parse(r.responseText);
ResultSpan.innerHTML = result;
});


});

}




Creating simple Add Service

To start with let us create a WCF REST Service returning JSON as below. There is one operation contact named Add in the service and that is taking two strings as input parameters and returning integer.


[ServiceContract]
public interface IService2
{

[OperationContract]
[WebGet(UriTemplate="/Add/{Number1}/{Number2}",RequestFormat=WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json
)]
int Add(string  Number1, string Number2);


}


Service is implemented as below,


using System;

namespace MultipleBindingWCF
{

public class Service1 : IService2
{


public int Add(string Number1, string Number2)
{
int num1 = Convert.ToInt32(Number1);
int num2 = Convert.ToInt32(Number2);
return num1 + num2;
}


}
}


Next in this section we need to configure service. We need to configure service webHttpBinding to eanble it as REST Service. So in Web.Config we need to do the below changes.


<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name ="servicebehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="restbehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<endpoint name ="RESTEndPoint"
contract ="MultipleBindingWCF.IService2"
binding ="webHttpBinding"
address ="rest"
behaviorConfiguration ="restbehavior"/>
</service>
</services>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>


After configuring, Service is ready for hosting. After hosting consume service in Windows 8 Metro application.

I hope this post is useful. Thanks for reading.

How to consume WCF REST Service with JSON in Windows Phone 7

In this post I will show you the way to consume JSON WCF REST Service in Windows Phone 7. This post is divided into four parts.

  1. Creating simple WCF REST Service for ADD
  2. Consuming JSON REST Service in Windows Phone 7 application.
  3. Creating complex WCF REST Service with custom classes and types.
  4. Consuming complex JSON REST Service in Windows Phone 7 application.

Creating simple Add Service

To start with let us create a WCF REST Service returning JSON as below. There is one operation contact named Add in the service and that is taking two strings as input parameters and returning integer.


[ServiceContract]
public interface IService2
{

[OperationContract]
[WebGet(UriTemplate="/Add/{Number1}/{Number2}",RequestFormat=WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json
)]
int Add(string  Number1, string Number2);

}

Service is implemented as below,


using System;

namespace MultipleBindingWCF
{

public class Service1 : IService2
{

public int Add(string Number1, string Number2)
{
int num1 = Convert.ToInt32(Number1);
int num2 = Convert.ToInt32(Number2);
return num1 + num2;
}

}
}

Next in this section we need to configure service. We need to configure service webHttpBinding to eanble it as REST Service. So in Web.Config we need to do the below changes.


<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name ="servicebehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="restbehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<endpoint name ="RESTEndPoint"
contract ="MultipleBindingWCF.IService2"
binding ="webHttpBinding"
address ="rest"
behaviorConfiguration ="restbehavior"/>
</service>
</services>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>

After configuring, Service ready for hosting. You are free to host it either on Azure, IIS, or Cassini. For local ASP.Net Server hosting press F5. Do a testing of service in browser and if you are getting expected output, you are good to consume it in the Windows Phone 7 application.

Consuming Service in Windows Phone 7

To consume REST Service in Windows Phone 7 and then parse JSON, you need to add below references in Windows Phone 7 project.

 

 

 

As the design of the page I have put two textbox and one button. User will input numbers to be added in the textbox and on click event of button result would get displayed in message box. Essentially on click event of the button we will make a call to the service. Design of the page is as below,


<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>

<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="calling JSON REST" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="JSON REST" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBox x:Name="txtNumber1" Height="100" Margin="-6,158,6,349" />
<TextBox x:Name="txtNumber2" Height="100" Margin="-6,28,6,479" />
<Button x:Name="btnAdd" Height="100" Content="Add" Click="btnAdd_Click"/>
</Grid>
</Grid>

On click event of the button we need to make a call to the service as below,

clip_image002

And ServiceURi is constructed as below,

clip_image004

There is nothing much fancy about above service call. We are just downloading JSON as string using WebClient. However parsing of JSON is main focus of this post. To parse we need to write below code in completed event.

clip_image006

In above code

  • Converting downloaded string as Stream
  • Creating instance of DataContractJsonSerializer. In that we are passing type as string since returned type of service is string.
  • Reading stream into instance of DataContractJsonSerializer
  • Displaying the result.

Putting all code together you should have below code to make a call and parse JSON in windows phone 7


using System;
using System.Net;
using System.Windows;
using Microsoft.Phone.Controls;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;

namespace ConsumingJSON
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}

private void btnAdd_Click(object sender, RoutedEventArgs e)
{

string Number1 = txtNumber1.Text;
string Number2 = txtNumber2.Text;
string ServiceUri = "http://localhost:30576/Service1.svc/Rest/add/"
+ Number1 + "/"
+ Number2;
WebClient proxy = new WebClient();
proxy.DownloadStringCompleted +=
new DownloadStringCompletedEventHandler(proxy_DownloadStringCompleted);
proxy.DownloadStringAsync(new Uri(ServiceUri));

}

void proxy_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
Stream stream = new MemoryStream(Encoding.Unicode.GetBytes(e.Result));
DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(string));
string result = obj.ReadObject(stream).ToString();
MessageBox.Show(result);
}
}
}

Creating complex Service with custom classes and types

Go back to service and add a custom class as below,

[DataContract]
public class Student
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string RollNumber { get; set; }
[DataMember]
public string Grade { get; set; }
}

And add one more function to service. This operation contract will return List of Students.


[OperationContract]
[WebGet(UriTemplate = "/GetStudents", RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json
)]
List<Student> GetStudents();

Next you need to implement service as below,


public List<Student> GetStudents()
{
List<Student> lstStudent = new List<Student>
{
new Student { Name = "John " ,RollNumber = "1" , Grade = "A"},
new Student { Name = "Dan " ,RollNumber = "2" , Grade = "Q"},
new Student { Name = "Pinal " ,RollNumber = "3" , Grade = "M"},
new Student { Name = "Mahesh " ,RollNumber = "4" , Grade = "Z"},
new Student { Name = "Julie" ,RollNumber = "5" , Grade = "L"},
};
return lstStudent;
}

Configuration will be the same as of simple REST Service returning JSON. Press F5 to host and test the service.

Consuming complex JSON REST Service in Windows Phone 7 application

At the Windows Phone 7 application, you need to create entity class. This class will be representing Student class of service. Add Student class to project as below,


public class Student
{
public string Name { get; set; }
public string RollNumber { get; set; }
public string Grade { get; set; }

}

Design page as below. I have put a button and on click event of the button service will get called and returned data would be bind to the listbox.


<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="110" />
</Grid.RowDefinitions>
<ListBox x:Name="lstStudents" Height="auto" Width="auto" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Name}" Style="{StaticResource PhoneTextTitle2Style}"  />
<TextBlock Text="{Binding RollNumber}" Style="{StaticResource PhoneTextTitle3Style}" />
<TextBlock Text="{Binding Grade}" Style="{StaticResource PhoneTextAccentStyle}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

<Button Grid.Row="1" x:Name="btnAdd" Height="100" Content="Add" Click="btnAdd_Click"/>
</Grid>

In the code behind on click event of the button we need to make call using WebClient again


private void btnAdd_Click(object sender, RoutedEventArgs e)
{
WebClient proxy = new WebClient();
proxy.DownloadStringCompleted += new DownloadStringCompletedEventHandler(proxy_DownloadStringCompleted);
proxy.DownloadStringAsync(new Uri("http://localhost:30576/Service1.svc/rest/getstudents"));

}

And need to parse the returned JSON as below. In parameter to create instance of DataContractJsonSrrializer we are passing List of Student.


void proxy_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
Stream stream = new MemoryStream(Encoding.Unicode.GetBytes(e.Result));
DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(List<Student>));
List<Student> result = obj.ReadObject(stream) as List<Student>;
lstStudents.ItemsSource = result;
}

On running you should be getting output as below.

image

In this way you can work with WCF REST with JSON Data and Windows Phone 7. I hope this post is is useful. Thanks for reading

How to enable REST and SOAP both on the same WCF Service

In this post I will show you, how to create a WCF Service with both flavor of SOAP and REST paradigm . For purpose of this post , I am going to create a Calculator Service with following characteristics

  • Serivice will have both SOAP and REST enabled
  • REST Service will have JOSN Message format

In later part of the post , I will show you the way to consume both types of Service in a managed (console) client.

Idea

  • There would be two ServiceContract . One ServiceContract for SOAP and one for REST.
  • There would be one Service Defintion file
  • There would be two bindings enabled on the service. One binding corrosponds to SOAP and other to REST
  • For SOAP , basicHttpBinding would be used and for REST webHttpBinding would be used
  • Both SOAP and REST will have same base address

Note : I have taken different Service Contract for REST and SOAP. However you can have it on same ServiceContract also.

Create Service

Let us create two service contracts . One for SOAP and one for REST Service. I have created a Service Contract IService1 for SOAP as below,

IService1.cs


[ServiceContract]
public interface IService1
{
[OperationContract]
int Add(int Number1, int Number2);
[OperationContract]
int Sub(int Number1, int Number2);
[OperationContract]
int Mul(int Number1, int Number2);
[OperationContract]
int Div(int Number1, int Number2);
}


 

Next I have created a Service Contract IService2 for REST as below,

IService2.cs

[ServiceContract]
public interface IService2
{

[OperationContract]
[WebGet(UriTemplate="/Add/{Number1}/{Number2}",RequestFormat=WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json
)]
int AddRest(string  Number1, string Number2);
[OperationContract]
[WebGet(UriTemplate="/Sub/{Number1}/{Number2}",RequestFormat=WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json
)]
int SubRest(string  Number1, string  Number2);
[OperationContract]
[WebGet(UriTemplate="/Mul/{Number1}/{Number2}",RequestFormat=WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json
)]
int MulRest(string  Number1, string Number2);

[OperationContract]
[WebGet(UriTemplate="/Div/{Number1}/{Number2}",RequestFormat=WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json
)]
int DivRest(string  Number1, string  Number2);


}



In above service explictly I am setting message format to JSON. So above service is JSON enabled REST Service. Since REST based service does not take input parameter but string type so input parameters to functions is of string type.

Implementing Service

Service is implemented in simple way. All the operation contracts from the service are performing trivial calculating functions.

Service1.svc.cs



using System;

namespace MultipleBindingWCF
{

public class Service1 : IService1,IService2
{


public int Add(int Number1, int Number2)
{
return Number1 + Number2;
}

public int Sub(int Number1, int Number2)
{
return Number1 - Number2;
}

public int Mul(int Number1, int Number2)
{
return Number1 * Number2;
}

public int Div(int Number1, int Number2)
{
return Number1 / Number2;
}

public int AddRest(string Number1, string Number2)
{
int num1 = Convert.ToInt32(Number1);
int num2 = Convert.ToInt32(Number2);
return num1 + num2;
}

public int SubRest(string Number1, string Number2)
{
int num1 = Convert.ToInt32(Number1);
int num2 = Convert.ToInt32(Number2);
return num1 - num2;
}

public int MulRest(string Number1, string Number2)
{
int num1 = Convert.ToInt32(Number1);
int num2 = Convert.ToInt32(Number2);
return num1 * num2;
}

public int DivRest(string Number1, string Number2)
{
int num1 = Convert.ToInt32(Number1);
int num2 = Convert.ToInt32(Number2);
return num1 / num2;
}
}
}

Configuring Service

This section is very important. We need to configure service for both basicHttpBinding and webHttpBinding .

Very first we need to set the service beahavior as below ,

clip_image002

After setting Service behavior , we need to set EndPoint behavior for REST enabled EndPoint as below,

clip_image003

Next we need to create EndPoints , SOAP EndPoint with basicHttpBinding would get created as below,

clip_image005

In above configuration ,

  1. Name of the endpoint is SOAPEndPoint. You are free to give any name. Howevere at time of consuming the service this endpoint name is required.
  2. This endpoint will be available at baseaddress/soap address.
  3. Binding used in endpoint is basicHttpBinding
  4. Contract is IService1. If you remember , we created this contract for the SOAP .

Now we need to create REST EndPoint as below,

clip_image002[8]

In above configuration ,

  1. Name of the endpoint is RESTEndPoint.
  2. REST Service will be called at the URL baseaddress/rest/add/parameter1/parameter2
  3. Binding used is webHttpBinding
  4. Endpoint configuration is restbehavior .We set endpoint behavior with this name previously.

Putting all together service configuration will look like as below,


<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name ="servicebehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="restbehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name ="MultipleBindingWCF.Service1"
behaviorConfiguration ="servicebehavior" >
<endpoint name ="SOAPEndPoint"
contract ="MultipleBindingWCF.IService1"
binding ="basicHttpBinding"
address ="soap" />

<endpoint name ="RESTEndPoint"
contract ="MultipleBindingWCF.IService2"
binding ="webHttpBinding"
address ="rest"
behaviorConfiguration ="restbehavior"/>

<endpoint contract="IMetadataExchange"
binding="mexHttpBinding"
address="mex" />
</service>
</services>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>


Now service is ready to be hosted. For purpose of this post I am hosting it Cassini server.

Consuming Service

Service is enabled for both SOAP and REST version. So consumption of service needs to be done accordingly.

Consumption of SOAP Service can be done in usual way in .Net client by adding Service Reference and making a call to the service as below,


static void CallingSOAPfunction()
{
Service1Client proxy = new Service1Client("SOAPEndPoint");
var result = proxy.Add(7, 2);
Console.WriteLine(result);

}

If you notice, I am providing endpoint name to explicitly say which endpoint of the service need to be called.

REST Service is working on JSON message format. For deserlization of the message, I am using DataContractJsonSerializer. This class is in the namespace System.Runtime.Serialization.Json.


static void CallingRESTfunction()
{


WebClient RESTProxy = new WebClient();
byte[] data=  RESTProxy.DownloadData(new Uri("http://localhost:30576/Service1.svc/Rest/add/7/2"));
Stream stream = new MemoryStream(data);
DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(string));
string result = obj.ReadObject(stream).ToString();
Console.WriteLine(result);

}


In above code I am downloading data from REST Uri using WebClient and deserlaizing that using DataContractJsonSerializer.

Now you know how to enable REST and SOAP on same WCF Service. I hope this post is useful. Thanks for reading