How to create a Container in Azure Storage from MVC application

I am working on a MVC application in which I need to work with Microsoft Azure storage .I had a requirement to create An Azure storage container from the MVC application. In this post I will share my learning that how I created a container programmatically.

I created the view as shown in below image. User has to enter the azure storage account name, azure storage key and the name of the container to be created.

image

Above View is MVC razor view, and it is created using the cshtml as shown below:

 


@{
    ViewBag.Title = "BLOB Manager";
}
<div class="jumbotron">
    <div class="row">
        <div class="col-md-8">
            <section id="loginForm">
                @using (Html.BeginForm("AzureInfo", "Manage", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
                {
                    @Html.AntiForgeryToken()
                    <h2> Manage BLOB Container</h2>
                    <hr />
                    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                    <div class="form-group">
                        <div class="col-md-10 input-group input-group-lg">
                            @Html.TextBox("AccountName", "", new { @class = "form-control", @placeholder = "Account Name" })
                            @Html.ValidationMessage("AccountName", "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">

                        <div class="col-md-10 input-group input-group-lg">
                            @Html.TextBox("AccountKey", "", new { @class = "form-control", @placeholder = "Account Key" })
                            @Html.ValidationMessage("AccountKey", "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">

                        <div class="col-md-10 input-group input-group-lg">
                            @Html.TextBox("ContainerName", "", new { @class = "form-control", @placeholder = "Container Name" })
                            @Html.ValidationMessage("containername", "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group input-group input-group-lg">
                        <div class="col-md-offset-2 col-md-10">
                            <input type="submit" value="Create Container" class="btn btn-lg btn-success" />
                        </div>
                    </div>

                }
            </section>
        </div>
    </div>
</div>

Above I am creating,

  • Three text boxes with the placeholder and the class set to bootstrap form-control
  • A submit button with the class set to bootstrap btn-lg and btn-success
  • All the controls are inside the form.
  • On form post operation, AzureInfo action of the Manage controller will be called.

Once the View is ready, let us go ahead and create an azure utility class. In this class we will put all the operations related to the azure storage. But before that you need to add Azure storage library to the project. Either you can use NuGet package manager or console to add the library. I am using console to install Azure storage library. I have taken the 4.3 version because at the time of writing this post, this was the latest stable version available.

image

Once package is successfully installed, add following namespaces.

 


using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure;

To create the container in the Azure storage, I have created a function CreateContainer. This function takes three input parameters, account name, account key and the container name.

 


public static class AzureUtility
    {
        public static string  CreateContainer(string AccountName, string AccountKey, string ContainerName)
        {

            string UserConnectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", AccountName, AccountKey);
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(UserConnectionString);
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container = blobClient.GetContainerReference(ContainerName.ToLower());
            if (container.CreateIfNotExists())
            {
                container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
                return container.Name;
            }
            else
            {
                return string.Empty;
            }
        }
    }

Now let us examine the above code line by line.

  • In first line I created the connection string for the azure storage. It takes two parameters, account name and the account key. These values are passed as input parameter to the function. I am using these two parameter to create connection string.
  • Using CloudStorageAccount to parse the connection string from the constructed string.
  • Creating the CloudBlobClient
  • Getting the container reference of the BLOB.
  • If container reference does not exist, creating new container.
  • On successful creation of the container function returns name of the container else empty string.

 


[HttpPost]
        public ActionResult AzureInfo(string AccountName, string AccountKey, string ContainerName)
        {

           var result= AzureUtility.CreateContainer(AccountName, AccountKey, ContainerName);

           if (result != string.Empty)
             {

                 return RedirectToAction("Index", "Home");
             }
             else
             {
                 return RedirectToAction("Index");
             }
        }

In the action we are using the utility class to create the container. In this way an azure container can be created from the MVC application.

I hope it is useful. Thanks for reading. Happy Coding.

Windows Azure Storage Client Library for Windows Phone: Part 1

Windows Azure Storage Client Library allows you to perform operations on Windows Azure storage from Windows Phone. Using Windows Azure Storage Client, you can

  1. Perform operations on Table
  2. Perform operations on Queue
  3. Perform Operations on BLOB

If you are not using Windows Azure Storage Client Library then to work with Windows Azure Storage you may need to create a WCF Service. Windows Phone will make a call to Service and Service will use Windows Azure Storage library to perform operations on Azure Storage. However using Windows Azure Storage Client for Windows Phone, you can directly perform operations on Windows Azure Storage.

You can get Windows Azure Storage Client Library and install it using NuGet. Read more about NuGet here. Once you have installed NuGet go ahead and create a Windows Phone 7.1 application by choosing target Windows Phone Version 7.1

image

After successful creation of project go to Tools then Library Package Manager, you will get option for Package Manager Console. Go ahead and select that option.

image

In bottom of Visual studio you will get Package Manage Console. Go ahead and install Phone.Storage package to the project.

You can install a package with below command

PM> Install-Package Phone.Storage

image

After successful installation of Phone.Storage package, you should have below references and file in solution explorer.

image

StorageInitializer.cs is very important class. In this class you can set whether you want to perform operation on local development fabric storage or on the azure storage. If you closely look into this file, you will find there are three sections.

  1. To configure to connect with local development fabric storage or Windows Azure Storage Emulator.
  2. To configure to connect with Windows Azure Web Role that contains Windows Azure Storage Proxies
  3. To configure to connect with Windows Azure Storage directly.

All the settings are commented but to work with storage of Windows Azure Emulator. If you want to work with Windows Azure Storage directly, you can do that by commenting third section of the file and providing Account Name and Account Key. Below is the uncommented section in file StorageInitalizer.cs. You need to provide your Windows Azure Storage account name and key.

image

Next let us say you want to create a table called Student. For that add a class called Student. Student entity class is inherting TableServiceEntity class.



using Microsoft.WindowsAzure.Samples.Phone.Storage;


namespace PhoneApp9
{
public class Student :TableServiceEntity
{
public string Name { get; set; }
public string RollNumber { get; set; }
public string Grade { get; set; }
}
}


Next as the design of the page, I have put a button and on click event of the button, Student table will get created if not exist and one row will get added.

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="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="page name" 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">
<Button x:Name="btnCreateTable" Height="100" Content="Create Table" Margin="46,254,128,254" Click="btnCreateTable_Click" />
</Grid>
</Grid>


On the click event of the button, first you need to resolve table client as below. Set the table name.

clip_image002

After resolving Table client, you need to create table as below,

clip_image003

Once table is created you need to resolve the context to add rows in the table.

clip_image005

You can very much modify above code by getting value to be inserted from the user. In this case I am hardcoding the vale. On putting all codes together you should have below code behind.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.WindowsAzure.Samples.Phone.Storage;

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

private void btnCreateTable_Click(object sender, RoutedEventArgs e)
{
var tableClient = CloudStorageContext.
Current.Resolver.
CreateCloudTableClient();

var tableName = "Student";

tableClient.CreateTableIfNotExist(
tableName,
p =>
{
var context = CloudStorageContext.
Current.
Resolver.
CreateTableServiceContext();
var sampleData = new Student
{  Grade = "A",
Name="DJ",
RollNumber="1",
PartitionKey="s2",
RowKey="s"
};

context.AddObject(tableName, sampleData);

context.BeginSaveChanges(
asyncResult =>
{
var response = context.EndSaveChanges(asyncResult);

},
null);
});

}
}
}


Once you run on click event of the button you should able to add row in the table. I hope this post is useful. Thanks for reading.

Conditional Reading of Windows Azure BLOB

Conditional reading of BLOB implies, you want to read BLOB only when BLOB is modified. There are scenarios when you need to read BLOB frequently. In that case to avoid network usage and bandwidth, you may consider reading BLOB only when BLOB has been modified since last read or download. This type of BLOB reading is termed as Conditional BLOB reading.

Usually to read or download BLOB, you create reference of BLOB as below

image

In above code snippet

  1. ConnectionString is connection string to your storage account.
  2. Containername is name of the public container.
  3. Doc1.docx is name of the BLOB.

If you want to read it without any condition or in other words you want to read the BLOB regardless of whether it has been modified or not then you can read it in byte array as below,

image

As of now everything is fine for unconditional read but if you want to do Conditional read on the BLOB then you will have to use ,

  • IfNoneMatch
  •  eTag

IfNoneMatch is a static variable of AccessCondition structure. When you download a BLOB you can additionally provide BLOBRequestOptions. Almost all Download functions are overloaded with BlobRequestOptions.

image

If you don’t specify BLOBRequestOptions then you will perform unconditional read.

To perform conditional read, you need to follow below steps,

Step 1

Save ETag value from the server at time of first reading in a local variable

clip_image001

Step 2

Create instance of BLOBRequestOptions with setting AccessCondition as below,

clip_image001[6]

In above code we are passing locally saved ETag value to IfNoneMatch

 

Step 3

At time of making second call onward to download BLOB pass Request Option as below,

clip_image002

If BLOB is not modified then you will get into the Exception

At time of downloading BLOB in above code, server will fist check for the ETatg in IfNoneMatch header. If server don’t find new version, it will send HTTP 304 request to the storage library.

For your reference full source code of conditional BLOB reading is as below,


using System;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;

namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{

CloudStorageAccount account = CloudStorageAccount.
Parse("connectionString");

CloudBlobClient BlobClient = account.CreateCloudBlobClient();

CloudBlobContainer ContainerReference = BlobClient.
GetContainerReference
("dhananjay");

CloudBlob BlobReference = ContainerReference.
GetBlobReference
("Doc1.docx");

byte[] DownloadAsByteArray = BlobReference.DownloadByteArray();

var LastReadETag = BlobReference.Properties.ETag;

BlobRequestOptions RequestOption = new BlobRequestOptions
{ AccessCondition = AccessCondition.IfNoneMatch
(LastReadETag)
};

try
{
byte[] DownloadByteArraySecondTimeOnward = BlobReference.
DownloadByteArray(RequestOption);

}
catch (StorageClientException ex)
{
if (ex.StatusCode == System.Net.HttpStatusCode.NotModified)
{

}
}

}
}

}

&nbsp;

In this way you can perform conditional reading on Windows Azure BLOB. I hope this post is useful. Thanks for reading  Smile

 

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

Inserting Null Value for Integer columns in Windows Azure Table

I recommend to read  below post before you start reading this post

Creating Azure Table using CloudTableClient.CreateTableIfNotExist

There may be requirement when you need to insert null values for values type columns in Azure table. In our recent project, we had a requirement to insert null values for integer columns. Usually if you don’t provide any value to Integer variable, it would get initialized as 0, since they are value type’s variables. This post will focus on providing null values for integer columns

Very first you need to define and entity as below,

image

 

You may have noticed that I am making integer properties as Nullable types

image

Now create Azure table as below,

image

Then you can insert null value for integer columns as below,

image

For your reference full source code to insert null values is as below,


using System;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;

namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
CloudStorageAccount account = CloudStorageAccount.Parse("connectionString");
CloudTableClient tableClient = new CloudTableClient(
account.TableEndpoint.ToString(),
account.Credentials);
string tableName = "School";
tableClient.CreateTableIfNotExist(tableName);
TableServiceContext  context = tableClient.GetDataServiceContext();
SchoolEntity entity = new SchoolEntity
{
Age = null,
Name = "DJ",
PartitionKey = "S",
RollNumber  = null ,
RowKey = Guid.NewGuid().ToString()
};

context.AddObject(tableName, entity);
context.SaveChanges();

Console.WriteLine("Saved");
Console.ReadKey(true);


}
}

public class SchoolEntity : TableServiceEntity
{
public string Name { get; set; }
public int ? RollNumber { get; set; }
public int ? Age { get; set; }
}

}

&nbsp;

In this way you can insert null values. I hope this post was useful. Thanks for reading Smile

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you

Creating Azure Table using CloudTableClient.CreateTableIfNotExist

I discussed Three simple steps to create Azure table in my last post. Just after submitting the post, I got a comment from Neil Mackenzie that I can avoid creation of context class [Step 2] in last post. He helped me with the link for the best practice on MSDN

This post is to accommodate suggestion given by him and recommendation given on MSDN.

In this post we will see how to create Azure table using CloudTableClient.CreatTableIfNotExist method.

Add References

If you are creating table from a console application then you need to add below references to your project,

System.Data.Service.Client

clip_image001

And Microsoft.WindowsAzure.Serviceruntime.dll

image

Create Entity class

To represent entity class, we need to create a class inheriting from class TableServiceEntity. SchoolEntity class will be as below,

clip_image001[6]

If you notice in above code snippet there is no

  1. Row Key
  2. Partition Key
  3. Calling base class constructor [ As I discussed here ]

Now when you make object of SchoolEntity class, in intellisense you will get RowKey,PartitionKey and TimeStamp to set as below,

clip_image001[8]

 

Creating Account object

image

Pass connection string as of your storage account.

Creating Table Client

image

Creating Table

image

Creating Table Context

image

Creating Object to Insert

image

Adding Object to table

image

Putting all the code together,


using System;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;

namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
CloudStorageAccount account = CloudStorageAccount.Parse("connectionString");
CloudTableClient tableClient = new CloudTableClient(
account.TableEndpoint.ToString(),
account.Credentials);
string tableName = "School";
tableClient.CreateTableIfNotExist(tableName);

TableServiceContext  context = tableClient.GetDataServiceContext();

SchoolEntity entity = new SchoolEntity
{
Age = 9,
Name = "DJ",
PartitionKey = "S",
RollNumber  = null ,
RowKey = Guid.NewGuid().ToString()
};
context.AddObject(tableName, entity);
context.SaveChanges();

Console.WriteLine("Saved");
Console.ReadKey(true);


}
}

public class SchoolEntity : TableServiceEntity
{
public string Name { get; set; }
public int ? RollNumber { get; set; }
public int Age { get; set; }
}

}

In this way you can create a table. I hope this post was useful. Thanks for reading Smile

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you

Three simple steps to create Azure table

Please read post at below link for recommended way to create table,

https://debugmode.net/2011/10/12/creating-azure-table-using-cloudtableclient-createtableifnotexist/

In this post I will show you three simple steps to create Azure Table.

Let us say you want to create Azure table called Employee with following columns

  1. EmployeeID
  2. EmployeeName
  3. EmployeeSalary

Step 1: Create Entity class

First step is to create entity class representing employee.

Each row of azure table contains at least below columns

  1. Row key
  2. Partition Key
  3. Time Stamp

And custom columns along with above columns. So Employee table will be having all together below columns

  1. Row Key
  2. Partition Key
  3. Time Stamp
  4. EmployeeID
  5. EmployeeName
  6. EmployeeSalary

To represent entity class, we need to create a class inheriting from class TableServiceEntity. EmployeeEntity class will be as below,


using System;
using Microsoft.WindowsAzure.StorageClient;

namespace Test
{
public class EmployeeEntity : TableServiceEntity
{
public EmployeeEntity(string partitionKey, string rowKey)
: base (partitionKey,rowKey )
{

}
public EmployeeEntity()
: base()
{
PartitionKey = "test";
RowKey = String.Empty;
}

public string EmployeeID { get; set; }
public string EmployeeName { get; set; }
public int EmployeeSalaray { get; set; }
}
}

&nbsp;

There is couple of points worth discussing about above class.

  1. It inherits from TableServiceEntity class
  2. It is having two constructors
  3. Passing rowkey and partitionkey as string value to base constructor
  4. Custom columns are as the public property of the class.

Step 2: Create Data Context class

Once Entity class is in place, we need to create DataContext class. This class will be used to create the table.


using System;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure;
using System.Linq;

namespace Test
{
public class EmployeeContext : TableServiceContext
{
internal EmployeeContext(string baseAddress, StorageCredentials credentials)
:
base(baseAddress, credentials)
{

}

internal const string EmployeeTableName = "Employee";
public IQueryable<EmployeeEntity> Employee
{
get
{
return this.CreateQuery<EmployeeEntity>(EmployeeTableName);
}
}
}
}

There are couples of points worth discussing about above code

  • It inherits from TableServiceContext class
  • In constructor we are passing credentials
  • In constructor we are passing base address to create the table.

clip_image002

  • Table name is given inline in the code as below; Employee is name of the table we want to create.

clip_image003

  • We need to add IQueyable property to create query.

clip_image004

Step 3: Creating Table

To create table we need a very simple code.

  1. Create the account. In below code DataConnectionString is name of the connection string. This could be pointing to local storage or Azure Tables.
  2. We are creating table from Data Model. Passing EmployeeContext class as parameter.

using System;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure;
using System.Linq;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace Test
{
public class CrudClass
{
public class CrudClass
{
public void CreateTable()
{
CloudStorageAccount account = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("DataConnectionString"));
CloudTableClient.CreateTablesFromModel(typeof(EmployeeContext
), account.TableEndpoint.AbsoluteUri, account.Credentials);

}

}
}

&nbsp;

When you call CreateTable() method of CrudClass , it will create Employee table for you in Azure table.

I hope this post was useful. Thanks for reading Smile

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you

Adding message in a Windows Azure Queue

In this post I will show you code snippet to add message in azure queue. I have written a function returning Boolean value and taking string input parameter to add as message in queue.

Create instance of cloud storage account

image

Create a client of azure queue

image

Get the reference of particular queue. Create queue if does not exist

image

Add message to queue

image

For your reference full source code is given below,


public bool AddMessageinQueue(string MessageToAdd, string QueueName)
{
try
{
CloudStorageAccount account = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("DataConnectionString"));
CloudQueueClient queueClient = account.CreateCloudQueueClient();
CloudQueue queue = queueClient.GetQueueReference(QueueName);
queue.CreateIfNotExist();

CloudQueueMessage m = new CloudQueueMessage(MessageToAdd);
queue.AddMessage(m);


return true;


}
catch (Exception ex)
{
return false;
}
}

&nbsp;

 

In this way you can add message in azure queue. I hope this post was useful. Thanks for reading Smile

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

Upload Image from Silverlight to Azure BLOB using WCF

Working with Azure Blob is very common task you must be doing. Sometime you may come with requirement to upload an image from Silverlight client to Azure BLOB. In this post I am trying to help you in achieving this.

In this post I will show you below three stuffs.

  1. Uploading Image to Azure BOLB
  2. Abstracting BLOB upload code in WCF service
  3. Using WCF Service in Silverlight client to upload the image.

Expected Output

image

Flow of application

Step 1: On click event of Button File Dialog will open

Step 2: User will select Image and on selection Image will get uploaded in Azure Blob.

Step 3: On successful uploading URI of image will be returned from the service. Source property of Image control would be set to the returned URL.

Creating Service

Service Contract will have an function expose as operation contract as below,


[ServiceContract]
public interface IBLOBImageUpload

{

[OperationContract]
string UploadImage(byte[] Image);

}

Service is implemented as below,

  • We are creating a new GUID to set as file name of the image
  • Converting input byte array to stream
  • Calling a function to upload stream to blob
  • And returning URL of uploaded image
public string  UploadImage(byte[] Image)
{
string rowKeynFileName = Guid.NewGuid().ToString();
System.IO.Stream stream = new System.IO.MemoryStream(Image);
string imageUri= UploadImageinBlob(stream, rowKeynFileName );
return imageUri;

}

Function to upload Image in BLOB is as below

  • It is taking stream as input to upload
  • It is taking filename to be given to upload image
  •  DataConnectionString is connection string to Azure storage.
  •  urlContainer is name of the public container
  • Creating blob name by appending .jpg extension
  • Returning URL of uploaded image.

public string UploadImageinBlob(Stream Streams,string FileName)
{
CloudStorageAccount account = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue("DataConnectionString"));
CloudBlobClient blobClient = account.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("urContainer");
string uniqueBlobName = string.Format("{0}.jpg", FileName);
CloudBlob blob = container.GetBlobReference(uniqueBlobName);
blob.Properties.ContentType = "image\\jpeg";
Streams.Seek(0, SeekOrigin.Begin);
blob.UploadFromStream(Streams);
string url = blob.Uri.OriginalString;
Streams.Close();
return url;

}

Configuring Service EndPoint

There are many points you need to put in mind while configuring the service end point.

  • Change maxReceivedMessageSize to 2147483647
  • Change maxBufferSize to 2147483647
  • Change maxArrayLength to 2147483647
  • Change maxBytePerRead to 2147483647
  • Change maxDepth to 2147483647
  • Change maxTableCharCount to 2147483647
  • Change maxStringContentLength to 2147483647
  • In Service behavior change data contract serliazer max object graph value to 2147483647

<system.serviceModel>

<bindings>

<basicHttpBinding>

<binding name="ServicesBinding"

maxReceivedMessageSize="2147483647"

maxBufferSize="2147483647">

<readerQuotas

maxArrayLength="2147483647"

maxBytesPerRead="2147483647"

maxDepth="2147483647"

maxNameTableCharCount="2147483647"

maxStringContentLength="2147483647" />

</binding>

</basicHttpBinding>

</bindings>

<services>
<service name="Service.BLOBImageUpload" behaviorConfiguration="ServiceData.Service1Behavior">

<endpoint address="" binding="basicHttpBinding" contract=" Service.IBLOBImageUpload " bindingConfiguration ="ServicesBinding" />

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

</service>

</services>

<behaviors>

<serviceBehaviors>

<behavior name ="ServiceData.Service1Behavior">

<serviceMetadata httpGetEnabled="true"/>

<serviceDebug includeExceptionDetailInFaults="false"/>

<dataContractSerializer maxItemsInObjectGraph ="2147483647"/>

</behavior>

</serviceBehaviors>

</behaviors>

<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

</system.serviceModel>

&nbsp;

Now your service is written. You can choose service to host anywhere you want.

Creating UI

I have kept UI as sweet and simple as possible. There is just a button and image control. On click of button FileDialogBOX will open and user can select an image to upload. After successful uploading, URL of uploaded image in Azure blob will be returned and that will be set as source of Image control


<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>

<RowDefinition Height="100" />
<RowDefinition Height="*" />

</Grid.RowDefinitions>

<Button x:Name="btn" Height="100" Width="100" Click="btn_Click" Content="Upload Image" />
<Image Grid.Row="1" x:Name="img" Height="auto" Width="auto" />
</Grid>

&nbsp;

Calling Service

You need to make a normal service call

  • On click event of the button opening the file dialog
  • Converting stream to byte array
  • Passing byte array as input to the function.
  • GetImageSource function is converting given string URL as image source to be set as source of image control

public partial class MainPage : UserControl
{

public OpenFileDialog fileDialog = null;
public MainPage()
{
InitializeComponent();
}

private void btn_Click(object sender, RoutedEventArgs e)
{
Stream strm;
byte[] buffer = null; ;
fileDialog = new OpenFileDialog();
fileDialog.Multiselect = false;
fileDialog.Filter = "All Files|*.*";
bool? retval = fileDialog.ShowDialog();
if (retval != null && retval == true)
{
strm = fileDialog.File.OpenRead();
buffer = new byte[strm.Length];
strm.Read(buffer, 0, (int)strm.Length);
}

BLOBImageUploadClient proxy = new BLOBImageUploadClient ();

proxy.UploadImageAsync(buffer);
proxy.UploadImageAsync += new EventHandler<UploadImageCompletedEventArgs>(proxy_UploadImageCompleted);
}

void proxy_UploadImageCompleted (object sender, UploadImageCompletedEventArgs e)
{

img.Source = GetImageSource(e.Result.ToString());
}

private ImageSource GetImageSource(string fileName)
{
return new BitmapImage(new Uri(fileName, UriKind.Absolute));
}

}
}

&nbsp;

This is what all you need to do as far as coding is concern. Yes you may need to put clientacccesspolicy.xml at the root location of server where you are hosting WCF service to avoid cross domain problem.

I hope this post was useful. Thanks for reading Smile

If you find my blogs useful you may like to,

Follow me on twitter http://twitter.com/debug_mode

Like Facebook page of this blog http://www.facebook.com/DebugMode.Net

If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

CRUD operation on Windows Azure table storage as WCF Service

You may have come across requirement of performing CRUD operation on Windows Azure table storage many times. If you have encapsulated functions performing CRUD operation on Azure Table Storage as operation contract of WCF Service then any type of client can work against azure table storage.

You may always want to architecture your application as below,

image

Assume we have Azure table called Student as below,

image

There are 5 columns

  1. Partition Key
  2. Row Key
  3. Timestamp
  4. Name
  5. RollNumber

We need to perform CRUD operation on Student table.

Creating Data Contract

Very first let us create a DataContract representing Azure table.


[DataContract]
    [DataServiceEntity]
    public class Student
    {
        [DataMember]
        public string RollNumber { get ; set;}
        [DataMember]
        public string Name { get ; set;}
        public string PartitionKey { get; set; }
        public string RowKey { get; set; }
    }



There is two of points to be noted in above Data Contract

  1. Student class is attributed with DataServiceEntity
  2. Partitionkey and Rowkey are not exposed as Data Member. At the service side only we will set its values with random string values.

Creating Operation Contract


    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        List<Student> GetStudents();
        [OperationContract]
        bool InsertStudent(Student s);
        [OperationContract]
        bool DeleteStudent(string RollNumber);
        [OperationContract]
        bool UpdateStudent(string RollNumber);

    }



We have created four operation contract for corresponding CRUD operation.

Implementing Service

Before implementing the service add below references to project,

  1. Microsoft.WindowsAzure.DevelopmentStorage.Store.dll
  2. Microsoft.WindowsAzure.StorageClient.dll
  3. System.Data.Services.Client.dll

Make sure to put your own connection string to azure storage to parse.

image

Include below namespaces,

image

Retrieving records




 public List<Student> GetStudents()
        {
            CloudStorageAccount account = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=uraccount;AccountKey=abcdefgh=");
            DataServiceContext context = account.CreateCloudTableClient().GetDataServiceContext();
            var result = from t in context.CreateQuery<Student>("Student") select t;
            return result.ToList();
        }



This is simple LINQ retrieving all the records

Insert Entity

</span>
<pre>

 public bool InsertStudent(Student s)
        {

            try
            {
                CloudStorageAccount account = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=uraccount;AccountKey=abcdefgh=");
                DataServiceContext context = account.CreateCloudTableClient().GetDataServiceContext();
                s.PartitionKey = RandomString(9, true);
                s.RowKey = RandomString(9, true);
                context.AddObject("Student", s);
                context.SaveChanges();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }

        }



We are putting random string as value of partition key and row key.

Random string function is taken from Mahesh Chand article and it is as below,

</span>
<pre>

 private string RandomString(int size, bool lowerCase)
        {
            StringBuilder builder = new StringBuilder();
            Random random = new Random();
            char ch;
            for (int i = 0; i < size; i++)
            {
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                builder.Append(ch);
            }
            if (lowerCase)
                return builder.ToString().ToLower();
            return builder.ToString();
        }





Update Entity

 


public bool UpdateStudent(string RollNumber)
        {
            try
            {
                CloudStorageAccount account = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=uraccount;AccountKey=abcdefgh=");
                DataServiceContext context = account.CreateCloudTableClient().GetDataServiceContext();
                Student result = (from t in context.CreateQuery<Student>("Student") select t).FirstOrDefault();
                result.Name = "UpdatedName";
                context.UpdateObject(result);
                context.SaveChanges();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }




We are passing roll number to update. First we are fetching the entity to be updated and then updating it.

Delete Entity

 

 

public bool DeleteStudent(string RollNumber)
        {
            try
            {
                CloudStorageAccount account = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=uraccount;AccountKey=abcdefgh=");
                DataServiceContext context = account.CreateCloudTableClient().GetDataServiceContext();
                Student result = (from t in context.CreateQuery<Student>("Student") select t).FirstOrDefault();
                context.DeleteObject(result);
                context.SaveChanges();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }


        }



We are passing roll number to delete. First we are fetching the entity to be deleted and then deleting it.

Consuming at managed client

Get the Students

</span><span class="Apple-style-span" style="color: #222222; font-size: 15px; line-height: 21px; white-space: pre; background-color: #eeeeee;">Service1Client proxy = new Service1Client();</span>
<pre>            var result = proxy.GetStudents();
            foreach (var r in result)
            {
                Console.WriteLine(r.Name);
            }



Insert Student

</span>
<pre>
Service1Client proxy = new Service1Client();
 bool b = proxy.InsertStudent(new Student { RollNumber = "34", Name = "DK" });
            if (b)
                Console.WriteLine("Inserted");
            else
                Console.WriteLine("Sorry");



Update Student

</span>
<pre>
Service1Client proxy = new Service1Client();
bool b2 = proxy.UpdateStudent("34");
            if (b2)
                Console.WriteLine("Updated");
            else
                Console.WriteLine("Sorry");


Delete Student


Service1Client proxy = new Service1Client();
bool b1 = proxy.DeleteStudent("34");
            if (b1)
                Console.WriteLine("Deleted");
            else
                Console.WriteLine("Sorry");



This is all you have to do to perform CRUD operation on Azure Table. In next post we will consume WCF Service from a Silverlight client.

I hope this post was useful. Thanks for reading Smile

Uploading Stream in AZURE BLOB

In this post I will show you to upload stream to Azure BLOB.

Set the Connection String as below,

image

 

Function is as below,

 


public void UploadBlob(Stream s, string fileName, string containerName, string connectionString )
        {
            account = CloudStorageAccount.Parse(RoleEnvironment.GetConfigurationSettingValue(connectionString));
            blobClient = account.CreateCloudBlobClient();
            container = blobClient.GetContainerReference(containerName);
            blob = container.GetBlobReference(fileName);

            s.Seek(0, SeekOrigin.Begin);
            // set the required content type
            blob.Properties.ContentType = "image/jpeg";
            blob.SetProperties();
            BlobRequestOptions options = new BlobRequestOptions();
            options.AccessCondition = AccessCondition.None;
            blob.UploadFromStream(s, options);

        }


You need to set required content type. If you are uploading image then content type would be like below,

 

image

To use this function you need to pass ,

  1. Public container name
  2. BLOB name as filename
  3. Data connection string

I hope this quick code snippet was useful. Thanks for reading. Smile