Three way to form URI for REST Services

Objective

In this article, I will show how we could construct URI in three ways.

Method # 1: Creating URI from string

I am passing string in constructor of URI class, to create new URI.

clip_image002

Output

clip_image004

Method #2 New URI from Component Instance

I am here taking host and path individually and then combining them in constructor of Uri class.

clip_image006

Output

clip_image008

Method #3 Creating URI using Try Pattern validation

In this , I am showing you how could we use Try Pattern method of URI class to construct an URI.

clip_image010

Output

clip_image012

The full source code for your reference is given below

Program.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Net;

namespace ConsoleApplication5

{

class Program

{

static void Main(string[] args)

{

#region Creating URI from string

string url = http://dhananjaykumar.net/feed/”;

Uri uri = new Uri(url);

Console.WriteLine(uri.AbsoluteUri);

Console.Read();

#endregion

#region Creating URI from Component Instance

string host = http://dhananjaykumar.net”;

string path = “/feed”;

Uri uri1 = new Uri(host);

uri1 = new Uri(uri1, path);

Console.WriteLine(uri1.AbsoluteUri);

Console.Read();

#endregion

#region Create New URI Try Pattern Validation

string url = http://dhananjaykumar.net/feed/”;

Uri uri2;

if(Uri.TryCreate(url,UriKind.Absolute , out uri2))

{

Console.WriteLine(uri2);

}

Console.Read();

#endregion

Console.Read();

}

}

}


Report on Community Tech days event Ahmadabad on 24th July 2010

Very first I would thank PINAL DAVE sir and his family  for his great support .  How beautifully and kindly his family supported and welcome me. Thanks is a small word for that.

clip_image002clip_image004

It was a rainy morning and some political problem in Gujarat, so I thought there won’t be many audiences. When, I reached the venue, I got amazed seeing the crowd. It was around 300 to 350 (approximately). People were in queue with their notes and hall tickets. I saw them and I got excited seeing the enthusiasm of the crowd. Even if, I was the first time in Gujarat, I did not feel that I am stranger here. Whoever was meeting saying Hi and greetings?

Key Note: 10.15 am to 10.30 am by Pinal Dave

Welcome and Key note by Pinal Dave.” He is a great speaker and people want to listen him”, I have been listening this since long but first time, I got a chance to listen to him. He just gave a perfect opening to perfect crowd. With his very own style of speaking, he ignited the audience with excitement ahead in the day. Crowd was almost the twice than the seating chairs in the room. But how easily, he managed everything with the event organizers and put more chairs and everyone got seat. He spoke about, how Microsoft technology in changing day to day life of developers and so user also. He spoke about how Ahmadabad user group (SQL Server and .Net) is working to help the community. Then he introduced the agenda of the day and talked about the speakers. By his unique way of explaining the things, audience got very excited and stage was set for the day.

Session #1 Spatial Data Base-The Indexing Story, 10.30 to 11.30 by Pinal Dave

clip_image006

In this session, Pinal Dave talked about Spatial Data Base. If I say he is a great speaker then that would be nothing something new I would be saying. He was the first speaker of the day and as expected he gave a great opening. The way he explained the pronunciation of SPATIAL to drawing Monalisa with spatial type was more than awesome. His way of connecting technology to real time example was very impressive and very effective too. His humors between the sessions were really nice. He is true speaker who can make audience awake for full of the session.

He explained about

1. Spatial database

2. Why we need that?

3. Polygons in Spatial type

4. How to find distance between two cities and many more

Note: He explained many things but since my session was just after him, so I was not very attentive in his session. He explained much more thing than I listed above

Follow Him: http://twitter.com/Pinaldave

Read Him: http://blog.sqlauthority.com/

Session # 2 Introduction to ODATA and WCF Data Service, 11.30 to 12.30 by Dhananjay Kumar

clip_image007

This session delivered by me. You can download the PPT from here

Session # 3 File Stream in SQL Server 2008, 12.30 to 1.30 by Jacob Sebastian

I do not have much understanding of SQL Server but after this session, I was clear with why I need file stream. The way he explained, it was like, I was listening some story. The fun part of his session was, he divided audience in 2 groups and then started why we need File Stream and all. His presentation was reaching to all audience regardless of their background. Very slowly, he started and point by point he explained each thing to audience.

He explained

1. Why we need File Stream

2. Difference between Buffering and Streaming

3. Live demo of using File Stream and many more

Follow Him: http://twitter.com/jacobsebastian

Read Him: http://beyondrelational.com/

Lunch Break: 12.30 to 1.30

Very first lunch was awesome. After 3.30 hr of session, people gathered for the lunch. Participant was very curious about knowing the technology. Many participants came and talked to speakers about their queries and questions. People were very lively and enjoying the food.

Session#4 MVVM pattern in Silverlight 4.0, 2.30 to 3.30 by Prabhjot Singh bakshi

clip_image009

His session was just after lunch and his level of energy on dais made the audience like, it was the prime session of the day.

Before attending his session, I had a feeling that Model –View-View –Model pattern is next to impossible to understand in an hour. But he proved my feeling wrong with his great way of explanation and all audience was known to MMVM at the end of his session. He is a story teller. The way he started with “What is SilverLight” to ended with a full application running “without a code behind was awesome “. He is professional and each statement from his mouth was testifying that. He was highly energetic.

He demonstrated

1. How to create your first Silver Light 4.0 application

2. How to achieve two way binding.

3. How to achieve ICommand pattern

4. How to use static resources.

Session #5 MS Office 2010 talking to Windows Azure – Developer paradise, 3.30 to 4.45 by Mahesh Devjibhai Dhola

clip_image011

This session was all about integration between Outlook addin + WCF + Twitter API + Azure. The way Mahesh explained these four very different topics was awesome. What was good about this session was, he wrote each bit of the code in front of the audience. It gave a feeling to audience to connect with such an advance topic. His way of showing latest things of azure in a simple term to audience was really impressive.

He demonstrated,

1. How to write outlook add in

2. How to create WCF Service Web Role and host in Azure

3. How to use Twitter API to post tweets.

4. Calling of WCF Service on event of Outlook add in.

Follow Him: http://twitter.com/dholamahesh

Read Him: http://blog.dotnetdelegate.com/

Thanking notes, 4.45 to 5.00 by Mahesh Devjibhai Dhola

Speaking at Community TechDays, Ahmedabad – July 24, 2010

What is Microsoft Community Tech Days?

This is unique program from Microsoft and local user group to enable developers and IT pro to get information about latest technologies from Microsoft.

clip_image001

As of Community tech days official site,

Dive deep into the world of Microsoft technologies at the Community TechDays and get trained on the latest from Microsoft. Build real connections with Microsoft experts and community members, and gain the inspiration and skills needed to maximize your impact on your organization while enhancing your career. What more… you can watch some of these sessions LIVE online from the comfort of your workstation as well.

Event registration can be done

Here for online participation

Here for in person participation

Ahmedabad Community Tech Days event

I am speaking at Ahmedabad tech day’s event.

Event Detail

When: 24th July 2010

Where: Ahmedabad Management Association, AMA Complex, ATIRA, Dr. Vikram Sarabhai Marg.

Target Audience: IT Professionals and Software Developers

Timing: 9.45 am to 5.00 pm

Find detail agenda here

Speakers

There will be five speakers presenting different topics

Pinal Dave You can see details of his speaking here

Jacob Sebastian

Mahesh Dhola

Prabhjot Singh Bakshi

Dhananjay Kumar

My Speaking detail

When: 4.00 pm to 4.45 pm

Topic: Introduction to ODATA and WCF Data Service

clip_image003

Summary: ODATA is HTTP or web protocol to querying or manipulating data. ODATA uses HTTP, JOSN or ATOM.ODATA can be implemented through any platform supports, HTTP, XML or JSON.ODATA can expose data/information from relational database, File systems, Web sites, services etc.

WCF Data Service is a framework to expose CRUD operation as REST service on a data model.

In session, I will show;

1. How to create WCF Data service on ADO.Net Entity Model.

2. How to create WCF Data service on LINQ to SQL Class.

3. How to consume console application.

4. Paging, URI Options etc.

5. How to consume in Windows 7 Phone application.

So, I welcome you in the session.

Step by Step walkthrough on CRUD Operation on Azure table part # 2: Setting UP storage account for Azure and modifying connection string

Objective

This article is going to explain , how we can use AZURE table. This article will explain how to create a stroage account and then modify the connection string in exsiting azure application using local development storage.

Note : This article is part 2 of series of article , so I recoomend please go through this article before redaing this one.

You can see video of this article here

Step 1

Login to your Azure portal with your live credential. After your successful login , you can see the below screen . Just click on New Service.

clip_image002

Step 2

Then you need to select Storage account from given options. As you going to create account for windows azure storage .

clip_image004

Step 3

In this step , you need to provide service label and service description .

clip_image006

Step 4

You have to provide a unique name here. I am providing debugmode as unique name.

clip_image008

Step 5

In this step you need to set the affinity group. If you don’t want to put your storage account in a particular affinity group, you can select the region of your own.

clip_image010

And now click on Create

Step 6

Once you click create, you can see three end points has been created for you in azure storage.

clip_image012

Note: Primary access key and secondary access key has been blacked out

Accessing Windows Azure table

If you are referring the article here , then navigate to step 5. Step 5 explains how to set the connection string. You will have to modify the connection string to use Azure table.

Step 1

Click on Webrole 1 in solution explorer.

clip_image013

Step 2

Click on the setting in the tab

clip_image014

Step 3

In the top select add setting

clip_image015

Step 4

When you add a setting a setting will get added. Now from drop down , select Connection string as type.

clip_image016

Step 5

When you click to set the value, you will get the below child window. Select Enter storage credentials

clip_image017

Now you need to provide

1. Account name

2. Account Key

Now to provide these two information , copy and paste below two things from your azure portal. In my case account name is debugmode and account key (The blacked out) .

clip_image018

Once you provide these two details, leave the default setting and press ok.

clip_image019

You can see in setting tab a value has been added.

Next and last step , what you need to do is open WebRole.CS file and put the setting name from previous step at these two below places .

clip_image021

After performing above steps, now your application has been modified to use Azure table.

I hope this article was useful. Thanks for reading Happy Coding.

Step by Step walkthrough on CRUD operation on Azure Table Part #1

Objective

In this article, I will show you how we can perform CRUD operation on AZURE table. This article is divided into two parts. In part 1, I am using local development fabric and storage. In next part, I will show you how can use AZURE table from Microsoft data center.

Step 1: Create the project

Open visual studio. Create a new project by selecting New from File menu. Then from AZURE tab select Windows Azure Cloud Service project.

clip_image002

Give a meaningful name and then select a location for your project. After giving name and location click ok. Now select the Role. Select an ASP.Net WEB Role. If you want, you can change the name of selected ASP.Net Web Role but, I am leaving here the default name.

clip_image003

Now in solution explorer, you can see two projects one is cloud service project and other is ASP.Net Web Role project.

clip_image004

Step 2: Add the references

Add the below, references in your web role project. To do that, right click on web role project and select add references from context menu.

clip_image005

Add the below references in the project.

1. System.DataService

2. System.DataService.Client

3. Microsoft.WindowsAzure.Diagnostic

4. Microsoft.WindowsAzure.RunTime

5. Microsoft.WindowsAzure.StorageClient

clip_image006

clip_image007

Step 3: Create Data Model class

Let us say, we want to create a table in database as of below schema,

Player Table

Column Name Type
PlayerId String
PlayerName String
PlayerSports String
PlayerCountry String

1. Right click on web role project and add a new class. Give a meaningful name to the class. I am giving name here PlayerModel

clip_image008

clip_image010

So, now you can see in solution explorer, you have added a new class PlayerModel.cs.

2. Add the namespaces. Only keep below namespcaes and remove all other namespace.

clip_image012

3. Inherit the class from TableServiceEntity class.

clip_image014

After inheriting class will look like below,

clip_image016

4. Define the constructor . In constructor define the row key and partition key.

clip_image018

You can give any string as partition key. Now model the column of table as properties of the class.

clip_image020

So the full source code for model class can be given as below,

PlayerModel.cs

using System;

using Microsoft.WindowsAzure.StorageClient;

namespace WebRole1

{

public class PlayerModel : TableServiceEntity

{

public PlayerModel()

{

RowKey = string.Format("{0:10}_{1}",

DateTime.MaxValue.Ticks - DateTime.Now.Ticks,

Guid.NewGuid());

PartitionKey = "Player";

}

public string PlayerId { get; set; }

public string PlayerName { get; set; }

public string PlayerSports { get; set; }

public string PlayerCountry { get; set; }

}

}

Step 4: Create the Entity class

1. Right click on web role project and add a new class. Give a meaningful name to the class. I am giving name here PlayerEntity

clip_image008[1]

clip_image022

2. Define the properties

clip_image024

So, the PlayerEntity class will look like

PlayerEntity.cs

namespace WebRole1

{

public class PlayerEntity

{

public string playerId { get; set; }

public string playerName { get; set; }

public string playerSports { get; set; }

public string playerCountry { get; set; }

}

}

Step 5: Create the Context class

3. Right click on web role project and add a new class. Give a meaningful name to the class. I am giving name here PlayerContext

clip_image008[2]

clip_image026

4. Remove all the namespaces and leave the below namespaces

clip_image027

5. Inherit the class from TableServiceContext class.

clip_image029

So, after inheriting class will look like

clip_image031

6. Now in the constructor, pass the base address and credentials.

clip_image033

7. Create a query to return the data from the table. Create a property in the context class for this purpose.

clip_image035

8. Write the function to add players in the table

clip_image037

In this function, you need to pass object of PlayerEntity class. Then using, automatic property initializer, you need to create instance of PlayerModel class.

9. Write a function to edit the player in the table.

clip_image039

Here again, you have to pass as parameter object of PlayerEntity class and then retrieve particular player from the table based on playerId. After retrieving the player modify the particular player and do the update object operation.

10. Write a function to delete a particular Player from the table

clip_image041

Here, again we are passing playerId of the player to be deleted.

So, for your reference the full source code is given below,

PlayerContext.cs

using System.Linq;

using Microsoft.WindowsAzure;

using Microsoft.WindowsAzure.StorageClient;

namespace WebRole1

{

public class PlayerContext : TableServiceContext

{

public PlayerContext(string baseAddress, StorageCredentials credentials)

:base(baseAddress ,credentials)

{

}

public IQueryable<PlayerModel> Players

{

get

{

return this.CreateQuery<PlayerModel>(“Players”);

}

}

public void AddPlayer(PlayerEntity player)

{

this.AddObject(“Players”,new PlayerModel{PlayerId= player.playerId ,

PlayerName = player.playerName,

PlayerCountry = player.playerCountry ,

PlayerSports = player.playerSports });

this.SaveChanges();

}

public void EditPlayer(PlayerEntity player)

{

PlayerModel playerToModify  = (from r in this.Players

where r.PlayerId == player.playerId

select r).First();

playerToModify.PlayerName = player.playerName;

playerToModify.PlayerSports = player.playerSports;

playerToModify.PlayerCountry = player.playerCountry;

this.UpdateObject(playerToModify);

this.SaveChanges();

}

public void DeletePlayer(string playerId)

{

PlayerModel playerToDelete = (from r in this.Players

where r.PlayerId == playerId

select r).First();

this.DeleteObject(playerToDelete);

this.SaveChanges();

}

}

}

Step 5: Working with Connection strings

clip_image043

Either you can use local development fabric storage or the real azure table you create at Microsoft data center.

Connection string in Using Local development

1. Click on the Web Role in Cloud project

clip_image044

2. Click on the Setting in the tab.

clip_image046

3. The from top click on the Add Settings.

clip_image047

4. When you click on Add Setting, a setting will get added. From the drop down select Connectin string as the type.

clip_image049

5. After selecting the type. Click on the Value tab. If you are going to use development storage, you do not need to do anything. If you are using storage credentials from azure table then you have to provide the credential of azure table.

Note: I will explain about using credentials of real azure table from Microsoft data center in later articles and video

clip_image050

So, after this step you can see that we have added a connection string. This connection string is going to use the local development storage. We have given name of this connection string as LocalDevConnectionString. So we will be using LocalDevConnectionString (Connection string name, if you want you can change it) in order to connect to DB.

clip_image052

If you can notice in value column that UseDevelopmentStorage=true value is there. It says, we are going to use local dev storage.

Step 6: Modifying WebRole class to create table in the storage.

1. Click on WebRole.cs class in ASP.Net Web Role Project.

clip_image053

2. You need to modify this class , first add the below code

clip_image055

You need to create the table using the below code. Make sure that, you are providing the same connection string name, which you created in previous step. [In our case it is LocalDevConnectionString]

clip_image057

So after doing above steps, the WebRole.cs class will look like

WebRole.cs

using System.Linq;

using Microsoft.WindowsAzure.Diagnostics;

using Microsoft.WindowsAzure.ServiceRuntime;

using Microsoft.WindowsAzure.StorageClient;

using Microsoft.WindowsAzure;

namespace WebRole1

{

public class WebRole : RoleEntryPoint

{

public override bool OnStart()

{

DiagnosticMonitor.Start(“DiagnosticsConnectionString”);

// For information on handling configuration changes

// see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

RoleEnvironment.Changing += RoleEnvironmentChanging;

CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>

{

configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));

RoleEnvironment.Changed += (anotherSender, arg) =>

{

if (arg.Changes.OfType<RoleEnvironmentConfigurationSettingChange>()

.Any((change) => (change.ConfigurationSettingName == configName)))

{

if (!configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)))

{

RoleEnvironment.RequestRecycle();

}

}

};

}

);

var account = CloudStorageAccount.FromConfigurationSetting(“LocalDevConnectionString”);

CloudTableClient.CreateTablesFromModel(typeof(PlayerContext ),

account.TableEndpoint.AbsoluteUri,

account.Credentials);

return base.OnStart();

}

private void RoleEnvironmentChanging(object sender, RoleEnvironmentChangingEventArgs e)

{

// If a configuration setting is changing

if (e.Changes.Any(change => change is RoleEnvironmentConfigurationSettingChange))

{

// Set e.Cancel to true to restart this role instance

e.Cancel = true;

}

}

}

}

Step 7: Designing the default.aspx page.

1. I have added four buttons for add, edit and delete operations.

2. I have added a grid view to show all the players.

Default.aspx

   1: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebRole1._Default" %>

   2:

   3: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

   4:

   5: <html xmlns="http://www.w3.org/1999/xhtml">

   6:

   7: <head runat="server">

   8:

   9: <title></title>

  10:

  11: </head>

  12:

  13: <body>

  14:

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

  16:

  17: <div style="height: 614px">

  18:

  19: <asp:Button ID="btnAddPlayer" runat="server" Text="Add Player" Width="175"

  20:

  21: onclick="btnAddPlayer_Click" />

  22:

  23: <asp:Button ID="btnEditPlayer" runat="server" Text="Edit Player" Width="175px"

  24:

  25: onclick="btnEditPlayer_Click" />

  26:

  27: <asp:Button ID="btnDeletePlayer" runat="server" Text="Delete Player"

  28:

  29: Width="175px" onclick="btnDeletePlayer_Click" />

  30:

  31: <asp:Button ID="btnDisplayPlayer" runat="server" Text="Display Player"

  32:

  33: Width="175px" onclick="btnDisplayPlayer_Click" />

  34:

  35: <asp:GridView ID="grdPlayers" runat="server">

  36:

  37: </asp:GridView>

  38:

  39: </div>

  40:

  41: </form>

  42:

  43: </body>

  44:

  45: </html>

  46:

Step 8

To add a Player

clip_image059

a. First need to create account reading connection string.

b. Create object of PlayerContext .

c. Call AddPlayer method passing object of PlayerEntity class.

Step 9

To edit a player

clip_image061

a. First need to create account reading connection string.

b. Create object of PlayerContext .

c. Call EditPlayer method passing object of PlayerEntity class.

Step 10

To delete a player

clip_image063

a. First need to create account reading connection string.

b. Create object of PlayerContext .

c. Call DeletePlayer method passing object playerID.

Step 11

clip_image065

Here, we are fetching the data and binding the grid view.

So when you run, you will get the below output.

clip_image067

For your reference the source code is below

Default.aspx.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using Microsoft.WindowsAzure;

using Microsoft.WindowsAzure.StorageClient;

using Microsoft.WindowsAzure.ServiceRuntime;

using Microsoft.WindowsAzure.Diagnostics;

using System.Data.Services;

using System.Data.Services.Client;

namespace WebRole1

{

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

}

protected void btnAddPlayer_Click(object sender, EventArgs e)

{

var account = CloudStorageAccount.FromConfigurationSetting(“LocalDevConnectionString”);

var playerContext = new PlayerContext(account.TableEndpoint.ToString(), account.Credentials);

playerContext.AddPlayer(new PlayerEntity { playerId = “1”,

playerCountry = “India “,

playerSports = “Cricket”,

playerName = “Sachin Tendulakr” });

playerContext.AddPlayer(new PlayerEntity { playerId = “2”,

playerCountry = “Argentina “,

playerSports = “Football”,

playerName = “Messy” });

}

protected void btnEditPlayer_Click(object sender, EventArgs e)

{

var account = CloudStorageAccount.FromConfigurationSetting(“LocalDevConnectionString”);

var playerContext = new PlayerContext(account.TableEndpoint.ToString(), account.Credentials);

playerContext.EditPlayer(new PlayerEntity

{ playerId = “1”,

playerCountry = “India “,

playerSports = “Cricket”,

playerName = “Sachin Ramesh Tendulakr” });

}

protected void btnDeletePlayer_Click(object sender, EventArgs e)

{

var account = CloudStorageAccount.FromConfigurationSetting(“LocalDevConnectionString”);

var playerContext = new PlayerContext(account.TableEndpoint.ToString(), account.Credentials);

playerContext.DeletePlayer(“1”);

}

protected void btnDisplayPlayer_Click(object sender, EventArgs e)

{

List<PlayerEntity> players = new List<PlayerEntity>();

var account = CloudStorageAccount.FromConfigurationSetting(“LocalDevConnectionString”);

var playerContext = new PlayerContext(account.TableEndpoint.ToString(), account.Credentials);

var res =  playerContext.Players ;

foreach(var r in res )

{

players.Add(

new PlayerEntity

{

playerId = r.PlayerId,

playerName = r.PlayerName,

playerCountry = r.PlayerCountry,

playerSports = r.PlayerSports

}

);

}

grdPlayers.DataSource = players;

grdPlayers.DataBind();

}

}

}

I hope this article was useful. Thanks for reading. Happy Coding.