Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand

Posts Tagged ‘programming’

SharePoint 2010 – Create Document Library

Posted by JP on June 4, 2012

In this article we can explore the creation of Document Library through code. Here we are using existing Document Templates inside SharePoint to create a new document library.

Following are the activities involved in Document Library creation:

· Find the List Template

· Find the Document Template

· Create Document Library

Inside Visual Studio

Create a new console application and name it as DocLibCreation. Make sure you change the target framework to .Net 3.5.

Add the following code into the Program.cs file:

using (SPSite site = new SPSite("http://appes-pc/my/personal/dotnet"))

{

using (SPWeb web = site.OpenWeb())

{

SPListTemplate listTemplate = web.ListTemplates["Document Library"];

SPDocTemplate docTemplate = (from SPDocTemplate dt in web.DocTemplates

where dt.Type == 122

select dt).FirstOrDefault();

Guid guid = web.Lists.Add("My Docs", "My Documents", listTemplate, docTemplate);

SPDocumentLibrary library = web.Lists[guid] as SPDocumentLibrary;

library.OnQuickLaunch = true;

library.Update();

}

}

Now run the application and you can see the new Document Library created inside SharePoint.

clip_image002


Document Templates

Following are the SharePoint 2010 document templates available:

Template ID

Description

100

No Template

101

Word 2003 document

103

Excel 2003 document

104

PowerPoint 2003 document

121

Word document

122

Excel document

123

PowerPoint document

111

OneNote Notebook

102

SharePoint Designer HTML document

105

ASPX Web Page

106

ASPX Web Part Page

1000

InfoPath document

Uploading Document

Now we can try uploading a document to the above library programmatically. Use the following code to upload an excel file. Make sure the application bin folder contains a file named sample.xlsx.

using (SPSite site = new SPSite("http://appes-pc/my/personal/dotnet"))

{

using (SPWeb web = site.OpenWeb())

{

SPDocumentLibrary library = web.Lists["My Docs"] as SPDocumentLibrary;

SPFile file = library.RootFolder.Files.Add("sample.xlsx", File.ReadAllBytes("sample.xlsx"));

}

}

You can see that the file is uploaded into SharePoint:

clip_image004

Downloading Document

Now we can try downloading a document from the above library programmatically. Use the following code:

using (SPSite site = new SPSite("http://appes-pc/my/personal/dotnet"))

{

using (SPWeb web = site.OpenWeb())

{

SPDocumentLibrary library = web.Lists["My Docs"] as SPDocumentLibrary;

SPFile file = web.GetFile(library.RootFolder.Url + "/sample.xlsx");

Stream stream = file.OpenBinaryStream();

FileStream fileStream = new FileStream("out.xlsx", FileMode.OpenOrCreate, FileAccess.Write);

int buffer = 4096;

int read = buffer;

byte[] bytes = new byte[buffer];

while (read == buffer)

{

read = stream.Read(bytes, 0, buffer);

fileStream.Write(bytes, 0, read);

if (read < buffer) break;

}

stream.Dispose();

fileStream.Dispose();

}

}

After running the program, you can see that the file is created in the bin folder.

clip_image006

This concludes the following activities:

1. Create Document Library

2. Upload a Document

3. Download a Document

References

http://www.learningsharepoint.com/2010/06/30/programatically-creating-document-sets-in-sharepoint-2010/

Summary

In this article we have the creation of document library through code. Please note that using the Document Type we can create different types of document library.

Advertisements

Posted in C#, SharePoint | Tagged: , , , | 6 Comments »

SharePoint 2010 – Create List Definition using Visual Studio

Posted by JP on June 4, 2012

In this article we can explore the List Definition creation using Visual Studio. Please note that the same can be achieved through SharePoint Designer as well.

Create List Definition Project

For starting use the List Definition project inside New Project dialog.

clip_image002

Enter the name as Coders. Select the site from the wizard as shown below.

clip_image004

Choose Custom List in the next step.

clip_image006

Enter the details as shown above and click the Finish button to close the wizard. Now the Solution Explorer looks like below:

clip_image008

Open the ListDefinition1>ListInstance1>Elements.xml (Please note that there are 2 Elements.xml inside the Solution Explorer)

Change the Title and Url attributes as following:

<?xml version="1.0" encoding="utf-8"?>

<Elements xmlns="http://schemas.microsoft.com/sharepoint/"&gt;

<ListInstance Title="Coders"

OnQuickLaunch="TRUE"

TemplateType="10000"

Url="Lists/Coders"

Description="My List Instance">

</ListInstance>

</Elements>

Now click the Build button and on succeed, right click the Project and click Deploy. If no error messages are there, the Deployment succeeded and you can see the new List inside SharePoint.

clip_image010

On clicking the Coders list you can see the new list opened in SharePoint.

Now we need to add a custom column to the List Definition. Our column is of Single line and name as CoderName. Following are the activities included in the Column Creation.

· Create a new Field

· Specify the properties like ID (GUID), Name etc.

· Add the Field Reference inside Default View

Inside the Fields section of Schema.xml add the following Field definition

<Field Type="Note" Name="CoderName" DisplayName="CoderName" Required="FALSE" ID="{1D54AAC6-DBB8-4454-91B7-E2FAE7697D6A}"></Field>

Inside the ViewFields section of the second View, add the following FieldRef node.

<FieldRef Name="CoderName"></FieldRef>

You can go back to SharePoint and Refresh the Coders List. The changes are visible there:

clip_image012

The new CoderName property is visible now. This concludes our List creation using Visual Studio. For adding more columns, use the Schema.xml file.

References

http://msdn.microsoft.com/en-us/library/ms466023.aspx

http://onlinecoder.blogspot.com/2011/03/simple-way-of-creating-sharepoint-2010.html

Summary

In this article we have explored the List Definition creation using Visual Studio. The attached source code contains the example we discussed. You can try building and deploying it.

Posted in C#, SharePoint | Tagged: , , , | Leave a Comment »

SharePoint 2010 – List – Add, Edit, Delete using code

Posted by JP on June 4, 2012

In this article we can experiment List manipulations through code. Following are the list operations to perform:

1. Add

2. Edit

3. Delete

Pre-Requisite

For proceeding with we need to create a List named Tasks using template Tasks.

clip_image002

Now create a new SharePoint Console Application project inside Visual Studio.

clip_image004

Make sure you changed the Application Target Framework to .Net 3.5 version.

Adding an Item

For adding a new Task Item execute the following code:

using (SPSite site = new SPSite("http://appes-pc&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["Tasks"];

SPListItem item = list.Items.Add();

item["Title"] = "New Task";

item["Description"] = "Description of Task";

item.Update();

}

}

Now you can check the Tasks list inside SharePoint and you can see the new item there.

clip_image006

Editing an Item

For editing an existing Task use the following code. Here we are changing the first item Title and Description.

using (SPSite site = new SPSite("http://appes-pc&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["Tasks"];

SPListItem item = list.Items[0];

item["Title"] = "Edited Task";

item["Description"] = "Description of Task (edited)";

item.Update();

}

}

Going back to SharePoint you can see the Edited Task

clip_image008

Deleting an Item

For deleting an item use the following code.

using (SPSite site = new SPSite("http://appes-pc&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["Tasks"];

SPListItem item = list.Items[0];

item.Delete();

}

}

Now you can go back to SharePoint and see that the item was deleted.

clip_image010

References

http://suguk.org/blogs/tomp/archive/2006/09/28/Adding_SPListItems.aspx

Summary

In this article we have experimented List manipulations Add, Edit, Delete through code. In real life we will be needed to automate List manipulations and programming will be a help in this regard.

Posted in C#, SharePoint | Tagged: , , , | Leave a Comment »

SharePoint 2010 – List – Add, Edit, Delete using code

Posted by JP on June 2, 2012

In this article we can experiment List manipulations through code. Following are the list operations to perform:

1. Add

2. Edit

3. Delete

Pre-Requisite

For proceeding with we need to create a List named Tasks using template Tasks.

clip_image002

Now create a new SharePoint Console Application project inside Visual Studio.

clip_image004

Make sure you changed the Application Target Framework to .Net 3.5 version.

Adding an Item

For adding a new Task Item execute the following code:

using (SPSite site = new SPSite("http://appes-pc&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["Tasks"];

SPListItem item = list.Items.Add();

item["Title"] = "New Task";

item["Description"] = "Description of Task";

item.Update();

}

}

Now you can check the Tasks list inside SharePoint and you can see the new item there.

clip_image006

Editing an Item

For editing an existing Task use the following code. Here we are changing the first item Title and Description.

using (SPSite site = new SPSite("http://appes-pc&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["Tasks"];

SPListItem item = list.Items[0];

item["Title"] = "Edited Task";

item["Description"] = "Description of Task (edited)";

item.Update();

}

}

Going back to SharePoint you can see the Edited Task

clip_image008

Deleting an Item

For deleting an item use the following code.

using (SPSite site = new SPSite("http://appes-pc&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["Tasks"];

SPListItem item = list.Items[0];

item.Delete();

}

}

Now you can go back to SharePoint and see that the item was deleted.

clip_image010

References

http://suguk.org/blogs/tomp/archive/2006/09/28/Adding_SPListItems.aspx

Summary

In this article we have experimented List manipulations Add, Edit, Delete through code. In real life we will be needed to automate List manipulations and programming will be a help in this regard.

Posted in C#, SharePoint | Tagged: , , , | 2 Comments »

SharePoint 2010 – LINQ and SPMetal

Posted by JP on June 1, 2012

In this article we can explore some of the advanced programming areas.

· LINQ to SharePoint

· SPMetal

LINQ to SharePoint is a new feature of SharePoint 2010. LINQ stands for Language Integrated Query which is a part of .NET Language. The aim of LINQ is to support different data sources using the same Typed Query Syntax. Presently it supports Objects, Datasets, SQL, Entities, XML etc.

Why we need LINQ?

You might have noted that the previous List Programming examples did not used proper column name access. LINQ allows us to access the List in a Typed manner. Adding more clarity we can access the list items based on the column names which we usually do with the databases.

Example: var result = from c in Citizen where c.Name == “John” select c;

What is SPMetal?

As we will be creating custom lists having custom column names, we need to generate the Entity Model. The SPMetal.exe is the tool which helps in generating the Model classes.

Although we can create the Model classes manually, it will be a tedious job and error prone. Using SPMetal would be the right approach to model classes.

Activities

Following are the activities performed in this article:

1. Manager List Creation

2. Entity Creation

3. Read using LINQ

4. Insert Entity

5. Update Entity

6. Delete Entity

Experimenting with LINQ and SPMetal

To start with create a custom list inheriting from Custom List and name it as Manager. Add the following custom columns and data:

clip_image002

Generating the Entity Models

Now we can generate the Entity Model for the above List.

You can get the SPMetal.exe inside the following folder:

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN

Open a command prompt and go to the specified folder:

clip_image004

Now run the following command:

SPMetal.exe /web: http://YOURSITE /code: SiteEntities.cs

Wait for a while and you will be ready with the new file. Open the file SiteEntities and you can see the Manager class is contained inside.

clip_image006

Create Application

Create a new SharePoint > 2010 > Console Application (targeting .Net 3.5 framework) and add the SiteEntities.cs file into it.

clip_image008

Add reference to the following assembly:

clip_image010

You can try with the following operations Read, Insert, Update, Delete using LINQ to SharePoint

 

Selecting an Item

Now we are trying to select the managers with country as USA:

using (SiteEntitiesDataContext context = new SiteEntitiesDataContext(“http://appes-pc&#8221;))

{

var result = context.Manager.Where(m => m.Country == “USA”);

foreach (ManagerItem manager in result)

{

Console.WriteLine(manager.Name);

}

}

Note: You can use LINQ or Lambda Expression to do the query. In the above example I have used Lambda.

On executing the application you can see the following results.

clip_image012

Inserting an Item

For inserting a new item into the Manager list, use the following code:

using (SiteEntitiesDataContext context = new SiteEntitiesDataContext(“http://appes-pc&#8221;))

{

ManagerItem manager = new ManagerItem();

manager.Name = “New Manager”;

manager.Address = “New Address”;

manager.Country = “New Country”;

context.Manager.InsertOnSubmit(manager);

context.SubmitChanges();

}

After executing the application, open the Manager list inside SharePoint as shown below:

clip_image014

Updating an Item

For updating an item inside SharePoint use the following code:

using (SiteEntitiesDataContext context = new SiteEntitiesDataContext(“http://appes-pc&#8221;))

{

ManagerItem manager = context.Manager.Where(m =>

string.IsNullOrEmpty(m.Title)).FirstOrDefault();

if (manager != null)

manager.Title = “New Title”;

context.SubmitChanges();

}

You can see the updated entity inside SharePoint:

clip_image016

Deleting an Item

For deleting an item inside SharePoint use the following code:

using (SiteEntitiesDataContext context = new SiteEntitiesDataContext(“http://appes-pc&#8221;))

{

ManagerItem manager = context.Manager.Where(m => m.Title.Length > 3).FirstOrDefault();

if (manager != null)

context.Manager.DeleteOnSubmit(manager);

context.SubmitChanges();

}

You can see that the item is deleted inside SharePoint:

clip_image018

This concludes our Read, Insert, Update, Delete operations using LINQ to SharePoint. Hope the topics are understood by the reader.

References

http://msdn.microsoft.com/en-us/library/ee535491.aspx

http://msdn.microsoft.com/en-us/library/ee538255.aspx

Summary

In this article we have explored LINQ and SPMetal tool. This information is necessary in the real world programming scenarios. The attachment contains the source code we discussed.

Posted in C#, SharePoint | Tagged: , , , , | 2 Comments »

Windows Azure – AppFabric Access Control Service Portal

Posted by JP on December 31, 2011

As part of the Access Control Service, we are performing the following in this article.

  • Create new Namespace
  • Using the Access Control Service Portal
  • Create new Identity Provider
  • Create new Rule Group

Creating the Namespace

For creating the namespace, sign in to the Windows Azure Management Portal. Open the Service Bus, Access Control & Caching item as shown below. (You can also use the previous namespace if it exists)

clip_image002

In the appearing window select the Access Control item from the left pane.

clip_image004

In the appearing dialog enter the required details. Please ensure the namespace is unique.

clip_image006

After entering the details click on the Create Namespace button to create the namespace. Wait for a few minutes and you will be ready with the new namespace Active as shown below.

clip_image008

The namespace accesscontrol2011 can be used in our next Access Control article involving programming.

Using the Access Control Service Portal

You can open the Access Control Service Portal by selecting the namespace and clicking on the Access Control Service button from the header panel as shown below.

clip_image010

(You can also access it using the url https://namespace.accesscontrol.windows.net)

On clicking the button we will get the window shown below:

clip_image012

We can configure the Identity Providers using the link on left. There is a default created Windows Live ID item inside it.

clip_image014

Create new Identity Provider

Now we can add a new identity provider Google. Click on the Add button to continue. The following page appears.

clip_image016

Select the option Google and click Next to continue.

clip_image018

Leave the default options and click Save to create the provider.

We can configure the Relying party applications using the link on left. There are no default entries inside it.

clip_image020

Now you can see the new identity provider in the list as shown below.

clip_image022

Create new Rule Group

Now we have to create a new rule group for our application. At least one rule group is needed for getting valid token from ACS.

Click on the Rule Groups item from the left pane and you will see the following screen.

clip_image024

Click on the Add button from the above screen.

clip_image026

In the above screen enter a name for the rule group and click the Save button and you will be getting the following screen.

clip_image028

Click on the Generate button to generate the rules automatically. The following screen will appear.

clip_image030

Select (check) the items Google and Windows Live ID and click the Generate button. You will get the following screen.

clip_image032

Check all the items as shown above and click the Save button. Your rule group will be created in the list as shown below.

Summary

In this article we have seen creation of namespace, adding identity providers and rule groups using the Access Control Service Portal. In the next article we can create a web role and test the providers.

Posted in C# | Tagged: , , , | Leave a Comment »

Windows Azure – AppFabric Access Control Service – Introduction

Posted by JP on December 21, 2011

In this article we can explore the Access Control service of Windows Azure AppFabric. As you know the services provided by AppFabric are shown below.

clip_image002

Theory on Access Control

The Access Control Service (ACS) provides a flexible way of authentication and authorization in the cloud premises. The ACS extracts out the authentication and authorization code outside the application.

We can use ACS along with:

  • Web Applications
  • Web Services

Simply, the Access Control Service 2.0 allows us to integrate single sign on (SSO) and centralized authorization into the web applications.

In the old applications we need to incorporate the authentication and authorization code inside our applications. This will lead to mixing of business logic with the security overheads. The PrincipalPermission attribute, Cookie Presence Checking etc. are some of the ways of doing it. AppFabric through ACS provides a better way of dealing with security aspects.

Protocols: The following protocols are supported by ACS 2.0

  • WS-Trust
  • WS-Federation
  • OAuth

Identity Providers: The identity providers supported by ACS include:

  • Windows Live ID
  • Facebook
  • Google
  • Yahoo
  • WS-Federation Identity Providers

Compatibility: ACS is compatible with web platforms including:

  • .Net
  • PHP
  • Java
  • Ruby
  • Python

Difference between Old Application and Azure Application Security Aspects

clip_image004

Service Namespace: Like the Service Bus, we need to create a service namespace for the Access Control Service too. The services in a particular namespace share the same DNS name. The Service Namespace acts as a top level partition around the end points.

There are different endpoints inside the namespace:

  • Security Token Service
  • Management Service
  • Management Portal
  • Service Metadata

The format of the end point will be:

https://<servicenamespace&gt;.accesscontrol.windows.net/mgmt

Managed Namespace: A managed namespace is partially managed by another service. The Service Bus and Cache services uses managed namespaces characterized by –sb and –cache respectively.

Relying Party: In the context of ACS, relying party is an application for which we are implementing federated authentication. The configuration includes a term Realm which acts as the URI. There is a Return Url which is invoked to provide the token when the invoker is valid.

Example of Realm are: http://contesso.com. Any request with Realm prefix with http://contesso.com will be gaining valid tokens. We can also include http://localhost/ as a valid realm.

We can also configure an Error url which will be invoked during any problems in the login process. Eg: http://www.yourdomain/error.htm

The configuration of relying party application can be manual or through program. The relying party control flow is depicted below.

clip_image006

Rule Groups: A relying party application should be associated with at least one rule group. If the Real match one configured application which is not associated with any of the rule groups, the token will not be issued.

We can associate one rule group with more than one application and one application with more than one rule group.

Summary

In this article we have learnt about the AppFabric Access Control Service. It provides a better way of authentication and authorization. In the next article we can see how to create a service namespace and using the Access Control Service Portal.

Posted in Azure | Tagged: , , , | Leave a Comment »

Windows Azure – WCF in Worker Role

Posted by JP on November 29, 2011

In this article I am going to demonstrate the creation of WCF service in Worker Role and deployment to the cloud.

The attributes of WCF service on Worker role are:

  • Self Hosted
  • More Flexibility Attained
  • More Configurations Needed

Following are the steps involved.

Step 1: Create the WCF Service

Create a new Windows Azure project in Visual Studio 2010 and name it as WCFInWorkerRole as shown below

clip_image002

In the appearing dialog add one Worker Role project as shown below.

clip_image004

Add reference to the System.ServiceModel assembly.

clip_image006

Add the following 2 files

  • Interface named IMessengerService
  • Class named MessengerService

Replace the contents of above files with the following:

// IMessengerContract.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

namespace WorkerRole1

{

[ServiceContract]

public interface IMessengerService

{

[OperationContract]

string SendMessage(string name);

}

}

// MessengerService.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

namespace WorkerRole1

{

public class MessengerService : IMessengerService

{

public string SendMessage(string name)

{

return “Hello ” + name + “. How do you do?”;

}

}

}

Remove the app.config from the worker role project as we are going to do manual configuration of WCF service. Now the solution explorer looks like below:

clip_image008

In the case of web role, the context and port was automatically identified. But in the worker role, we need to update the properties manually. The host name will be different in the development and deployment servers.

Modify the ServiceDefinition.csdef file as below.

<?xml version=”1.0″ encoding=”utf-8″?>

<ServiceDefinition name=”WCFInWorkerRole” xmlns=”http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition”&gt;

<WorkerRole name=”WorkerRole1″ vmsize=”Small”>

<Imports>

<Import moduleName=”Diagnostics” />

</Imports>

<Endpoints>

<InputEndpoint name=”port” protocol=”tcp” port=”9001″ />

<InputEndpoint name=”mexport” protocol=”tcp” port=”8001″ />

</Endpoints>

</WorkerRole>

</ServiceDefinition>

The content defines the port and metadata port for our WCF service. Now we can modify the OnStart() method of the Worker role class as given below.

public override bool OnStart()

{

// Set the maximum number of concurrent connections

ServicePointManager.DefaultConnectionLimit = 12;

// Create the host

ServiceHost host = new ServiceHost(typeof(MessengerService));

// Read config parameters

string hostName = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints[“port”].IPEndpoint.Address.ToString();

int port = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints[“port”].IPEndpoint.Port;

int mexport = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints[“mexport”].IPEndpoint.Port;

// Create Metadata

ServiceMetadataBehavior metadatabehavior = new ServiceMetadataBehavior();

host.Description.Behaviors.Add(metadatabehavior);

Binding mexBinding = MetadataExchangeBindings.CreateMexTcpBinding();

string mexendpointurl = string.Format(“net.tcp://{0}:{1}/MessengerServiceMetadata”, hostName, 8001);

host.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, mexendpointurl, new Uri(mexendpointurl));

// Create end point

string endpointurl = string.Format(“net.tcp://{0}:{1}/MessengerService”, hostName, 9001);

host.AddServiceEndpoint(typeof(IMessengerService), new NetTcpBinding(SecurityMode.None), endpointurl, new Uri(endpointurl));

// Open the host

host.Open();

// Trace output

Trace.WriteLine(“WCF Listening At: ” + endpointurl);

Trace.WriteLine(“WCF MetaData Listening At: ” + mexendpointurl);

return base.OnStart();

}

The code performs the following:

  • Create Service Host
  • Read the Port number
  • Add the Metadata behaviour
  • Add the endpoints
  • Opens the Host

Note: The attached source code contains the working application.

Step 2: Test the application

Now we can test the application by executing it. If successfully executed we can see the trace from the Output window.

clip_image010

You can see two addresses from the above screen:

  • The actual service end point
  • The metadata end point

We can also see the trace from the load development machine. The Windows Azure Compute Emulator can be used for this purpose.

clip_image012

On invoking the Show Computer Emulator UI we can see the following window.

clip_image014

The above window contains the same trace output with the end point urls. You may try adding reference to the metadata end point using the metadata url. We are going to deploy the service to cloud and test it.

Step 3: Deploy to the cloud

Now our application is working fine and we can deploy it to the online cloud. For this right click on the project and click Package menu item.

clip_image016

In the appearing dialog box, choose the default options and click the Package button.

clip_image018

Now sign in to the Windows Azure portal and click on the New Hosted Service button from the top ribbon.

clip_image020

In the appearing dialog box enter the details as shown below.

clip_image022

Choose the option “Deploy to production environment”

Locate the package and configuration files from your application bin folder.

(Eg: ..\WCFInWorkerRole\bin\Debug\app.publish)

Please note that the URL prefix should be a unique name. If the URL prefix entered is already in use you need to change it.

After that click the Ok button of the dialog box. (You have to scroll down to see the button)

If any warning box appears, click Yes button to continue. Wait for a few minutes and your deployment will be ready in a few minutes as shown below.

clip_image024

Select the Deployment 2 row and from the properties window you can get the url of the worker role. Now we just need the host name. In this case wcfinworkerrole.cloudap.net

clip_image026

Step 3: Create the Client

Now we are ready to create the client application and test the deployed online cloud WCF service.

Create a new console application into the existing Azure project and name it as TestClient.

Use the add service reference option of the console application and in the appearing dialog enter the constructed service url as shown below.

Constructed Url: net.tcp://wcfinworkerrole.cloudapp.net:8001/MessengerServiceMetadata

Please note that we added the following:

  • Protocol as net.tcp
  • Host Name from previous step
  • Port number as 8001
  • Metadata Context Name

clip_image028

Click the Go button and after seeing the MessengerService item populated, Click the Ok button to continue.

Modify the main method in the Program.cs as following:

static void Main(string[] args)

{

ServiceReference1.MessengerServiceClient client = new ServiceReference1.MessengerServiceClient();

string result = client.SendMessage(“Kent”);

Console.WriteLine(string.Format(“Invoking WCF Service Result: {0}”, result));

Console.ReadKey(false);

}

Modify the configuration file with the url of the Messenger Service. Please note that the messenger service url is having different port number and context.

<client>

<endpoint

address=”net.tcp://wcfinworkerrole.cloudapp.net:9001/MessengerService

binding=”netTcpBinding”

bindingConfiguration=”NetTcpBinding_IMessengerService”

contract=”ServiceReference1.IMessengerService”

name=”NetTcpBinding_IMessengerService” />

</client>

Now set the console application as the start project and execute the application.

You can see the following results.

clip_image030

You can see the result Hello Kent. How do you do? from the WCF service.

This concludes our article on WCF service deployment as worker role and the testing.

Multiple End Point

I would like to add a note on the 2 end points we created for the WCF service.

net.tcp://wcfinworkerrole.cloudapp.net:8001/MessengerServiceMetaData

net.tcp://wcfinworkerrole.cloudapp.net:9001/MessengerService

You can see that there are 2 differences in the above urls:

  • Port
  • Context

Note: WCF with HTTP Port 80 endpoint configuration done as explained here.

Summary

In this article, we have seen how to host a WCF service using the Worker Role and deploy it to the cloud. This service is self hosted and experiments the service creation, hosting, metadata end point adding, deploying and testing with the client. The source code is attached and the application name in the url has to be changed according to your application name.

Posted in Azure | Tagged: , , , | Leave a Comment »

Windows Azure – WCF in Web Role

Posted by JP on November 29, 2011

In this article I would like to demonstrate the creation and deployment of WCF service in a Web Role.

The attributes of WCF service on Web role are:

  • IIS Hosted
  • IIS features like pooling and caching availability
  • Less Configurations Needed

Following are the steps involved.

Step 1: Create the WCF Service

Create a new Windows Azure project in Visual Studio 2010 and name it as WCFInWebRole as shown below

clip_image002

In the appearing dialog add one Web Role project as shown below.

clip_image004

Add a new WCF Service into the project. Name it as MessengerService.

clip_image006

Now the Solution Explore will look like below with the newly added contracts and service files.

clip_image008

Modify the DoWork() method in the interface IMessengerService as given below.

string SendMessage(string name);

Modify the DoWork() method in the interface IMessengerService as given below.

public string SendMessage(string name)

{

return “Hello ” + name;

}

Step 2: Test the application

Make the MessengerService.svc file as the start page as shown below.

clip_image010

Press F5 to execute the application and you can see the service opened in the browser as shown below.

clip_image012

Now are have tested the application and it is ready to be deployed to the cloud.

Step 3: Deploy to the cloud

Right click on the Web Role project and click package menu item as shown below.

clip_image014

In the appearing dialog select the default option and click the Package button.

clip_image016

Now sign in to the Windows Azure portal and click on the New Hosted Service button from the top ribbon.

clip_image018

In the appearing dialog box enter the details as shown below.

clip_image020

Choose the option “Deploy to production environment”

Locate the package and configuration files from your application bin folder.

(Eg: ..\WCFInWebRole\bin\Debug\app.publish)

Please note that the URL prefix should be a unique name. If the URL prefix entered is already in use you need to change it.

After that click the Ok button of the dialog box. (You have to scroll down to see the button)

If any warning box appears, click Yes button to continue. Wait for a few minutes and your deployment will be ready in a few minutes as shown below.

clip_image022

Select the Deployment 1 row and from the properties window you can get the url of the web role.

clip_image024

Click on the url and your application will get opened in the browser. Add the suffix MessengerService.svc to get the messenger service.

clip_image026

Step 3: Create the Client

Now we are ready to create the client application and test the deployed online cloud WCF service.

Create a new console application into the existing Azure project and name it as TestClient.

Use the add service reference option of the console application and in the appearing dialog enter the service url as shown below.

clip_image028

Click Ok button to continue.

Modify the main method in the Program.cs as following:

static void Main(string[] args)

{

ServiceReference1.MessengerServiceClient client = new ServiceReference1.MessengerServiceClient();

string result = client.SendMessage(“Ian”);

Console.WriteLine(string.Format(“Invoking WCF Service Result: {0}”, result));

Console.ReadKey(false);

}

Now set the console application as the start project and execute the application.

You can see the following results.

clip_image030

You can see the result Hello Ian from the WCF service.

This concludes our article on WCF service deployment as web role and the testing.

Summary

In this article we have seen how to deploy a WCF service to cloud platform. The WCF service inside the Web role will be hosted in IIS. The source code is attached and the application name in the url has to be changed according to your application name.

Posted in C# | Tagged: , , , | Leave a Comment »

Windows Azure – WCF Hosting Methods

Posted by JP on November 29, 2011

In the previous article we have experimented the ways of WCF hosting in Windows Azure. In this article I would like to summarize the important points of WCF service exposing in Windows Azure.

There are multiple ways of hosting WCF service in Windows Azure.

WCF Hosting

Description

Web Role

Hosted inside IIS with pooling and caching facilities

Worker Role

Self Hosted with more control

AppFabric

Self Hosting, Relayed connectivity through Service Bus

Let us examine them closely.

clip_image002

Method 1: Web Role Hosting

In the Web Role hosting, the WCF service is hosted inside IIS. This will give the advantages of IIS to the WCF service.

  • Identity Management
  • Recycling
  • Caching
  • Pooling
  • Logging


The Service creation will be much easier in this method as Visual Studio provides the templates for Service (.svc files). We need to create a new .svc file and place it in the web role project. The host names and ports are configured by the deployment and we can access the service through a browser.

The metadata end points are also automatically added. This saves a lot of amount of work from the developer side.

Method 2: Worker Role Hosting

Here the developer has to perform more work in creating the service contracts by defining the attributes in the contracts and implementation.

This method is advised if more control is needed over the service. We can easily configure the protocols in this way. In this case a corporate port has to be opened to expose the service while using the worker role.

Method 3: Hosting through AppFabric

In this method the WCF service is exposed through the Service Bus service feature of Windows Azure AppFabric. We can choose this option if we need to connect two disconnected applications.

This method is self hosted and more configurations needed. Here we can connect two disconnected applications using the Service Bus namespace. The namespace identifies the subscription and will be used for billing purposes on the cloud.

The Service Bus provides the following features:

  • Connectivity between disconnected applications
  • Higher Availability

Relay Service

There are two modes of connectivity in the Relay Service.

· TcpRelayConnectionMode.Relayed

· TcpRelayConnectionMode.Hybrid

The default mode is Relayed and here the service and client is connected through the relayed service.

Relayed Mode Connectivity

The following picture depicts the process in the Relayed mode.

clip_image004
The steps involved are following:

Step 1: The WCF Service authenticates and registers with the Relayed Service using the namespace and Provider keys.

Step 2: The Client authenticates with the Relay Service

Step 3: Client invokes a method using the Relay Service

Step 4: The Relay Service redirects the call to the registered WCF service.

Hybrid Mode Connectivity

In the Hybrid way of connectivity the client can communicate directly to the service. First the client connectivity starts as Relayed as usual and then if there is possibility of connecting directly to the service it will be provided.

Summary

In this article we have discussed the various WCF exposing methods in Windows Azure like web role, worker role and through AppFabric Service Bus.

Posted in Azure | Tagged: , , , | Leave a Comment »