Behavior in SILVERLIGHT 3.0

Objective

This article will give a basic introduction of BEHAVIOR feature in SILVERLIGHT3.0. I will also walkthrough to create a custom behavior.

What is Behavior in SILVERLIGHT 3?

According to definition given in the product introduction of SILVERLIGHT3

A Behavior is in essence a reusable piece of interactivity that can be applied directly to user interface elements in Expression Blend. The whole product introduction on behavior can be read here.

I summarized few of the points as below about SILVERLIGHT behavior

  1. Behavior is new feature introduced in SILVERLIGHT 3.0.
  2. Behavior is a reusable piece of code, which can be attached to any object declaratively.
  3. Behavior is the way to allow designer to add functionality to XAML elements without codes.
  4. Behavior allows attaching functionality to an object without writing any code.
  5. Behavior encapsulates the functionality and can be attached to any element.
  6. Behavior can be attach to an element or object through XAML. There is no need to write C# code.
  7. A single behavior can be attached to any number of objects.
  8. Behavior is reusable piece of code can be attached to any object.
  9. Behavior comes with System.Windows.Interactivity.dll

 Creating a Custom Behavior
Step 1
Create a SILVERLIGHT Application. Two projects will get created SilverLightApplication1 and SilverLightApplication1.Web. If you are not, changing the default name. Add reference of System.Windows.Interactivity.dll in SilverLightApplication1 project.

Step 2

Right click on SILVERLIGHT project and add a class. Give any name, for my purpose; I am giving name ImageBehavior.

  1. Add the namespace using System.Windows.Interactivity;
  2. Inherit class from Behavior<T>
  3. Make T as DependencyObject
  4. Override the methods OnAttached and OnDetaching
  5. On MouseEnter
    event and MouseLeave event write the simple logic to rotate the object to which Behavior will be attached.

    ImageBehavior.cs

using System;using System.Net;

using System.Windows;using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Ink;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using System.Windows.Interactivity;

namespace BehaviorSample1

{

public class ImageBehavior : Behavior<DependencyObject>

{

public ImageBehavior()
{
}
protected override void OnAttached()
{
base.OnAttached();
var ad = this.AssociatedObject as
FrameworkElement;
ad.MouseEnter += (sender, args) =>
{
var p = new PlaneProjection();
p.RotationZ = new Random().Next();
ad.Projection = p;
};
ad.MouseLeave += (sender, args) =>
{
ad.Projection = null;
};
}
protected override void OnDetaching()
{
base.OnDetaching();
}}}

Attaching Custom Behavior to object

Step 1

Before adding custom behavior to element, we need to add namespaces. Open the XAML page and add below namespaces.

xmlns:i=”clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity”xmlns:behavior=”clr-namespace:BehaviorSample1″

First namespace is for the System.Windows.Interactivity dll and second one is namespace of the custom behavior class.

Step 2

Since; I am going to attach the custom behavior we created with Image control. So for the source of Image control add an image to SILVERLIGHT project by Add an existing item. I have added an image and gave the name a.jpg.

Step 3

Add an Image control on XAML and attach the behavior like below.

<Image Height=”Auto” Width=”Auto” Source=”a.jpg”> <i:Interaction.Behaviors>
<behavior:ImageBehavior />

</i:Interaction.Behaviors>

</Image>

 Where I isnamespace of dll and behavior is namespace of custom behavior class.

MainPage.Xaml

<UserControl x:Class=”BehaviorSample1.MainPage”
xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation

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

xmlns:i=”clrnamespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity”

xmlns:behavior=”clr-namespace:BehaviorSample1″

xmlns:d=”http://schemas.microsoft.com/expression/blend/2008&#8243; xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006

mc:Ignorable=”d” d:DesignWidth=”640″ d:DesignHeight=”480″>

<Grid x:Name=”LayoutRoot” Height=”Auto” Width=”Auto” Background=”Black”>

<Image Height=”Auto” Width=”Auto” Source=”a.jpg”

<i:Interaction.Behaviors>

<behavior:ImageBehavior />

</i:Interaction.Behaviors>

</Image>

</Grid>
</UserControl>

 Step 4

There is no need of do any coding in MainPage.Xaml.cs

Run the application

On mouse enter to Image; Image will rotate with random degree of angle. Like below. Thanks for reading.

Dynamic type with Reflection in debug mode

Objective

This article will give simple debug mode explanation on how Reflection and Dynamic type works.

Note: Read my previous article on dynamic type here Dynamic Type

Let us create a very simple class called Student.

public class Student{

public void Print(string Name)
{
Console.WriteLine(“Student Name is “ + Name);
}}

 Now say, you don’t have information about type of the class while creating instance of this class. Or in other words you don’t have type information of the class at the compile time. So how to create instance of this class? Till c# 3.0 ; we had no choice but to take help of Reflection . Code was highly messy. Not very readable and not beautiful either.

Code will look like,

Object student = new Student();

Type studentType = student.GetType();

Object res = studentType.InvokeMember(“Print”, BindingFlags.InvokeMethod,null, student ,new
Object[] {“Dhananjay”});

Console.Read();

 Few points about above code

  1. We are creating instance of the Student class as object type. Since we don’t know type of the class at compile time.

     

 

By running in debug mode, we can see at compile time class is resolving as DynamicReflection.Student.

  1. In 2nd line of code we are finding, type using GetType method of object class.

We can see Compiler is resolving the type as Student. If you remember Student is name of our class.

  1. On the type (StudentType in our case) we are calling the InvokeMember method to call the method on the instance of the class. InvokeMember is overloaded function and we are passing four parameters to this.
  2. Since method of the class is returning void so res is NULL.

Output

 

Now if you see above code, is not it very messy? So in c# 4.0 we do have dynamic type to deal with.

dynamic dynamicStudent = new Student();

dynamicStudent.Print(“Dhananjay With Dynamimc Type “);
Console.Read();

Now again if you run the above code in debug mode, you will see type for dynamic type is getting resolved exactly the same as of reflection.

After type resolving all the other work to call method is done by compiler at the back ground. So simply we need to call the method on the dynamic type and DLR will take care of everything.

 

So, we saw in debug mode how dynamic type and reflection works. Thanks for reading.

Returning Large volume of records from SOAP based WCF service

Objective

In this article I will explain; How to return large volume of data (around 50000 records) from SOAP based WCF service to any client. I will show; what service configuration setting and client configuration setting is needed to handle large volume of data returning for WCF service.

Follow the below steps,

Step 1: Create a WCF service

.To creates WCF service; select File -> New -> Project-> Web -> WCF Application.

Service will contain

  1. One Operation contract. This function will pull large data from database using stored procedure.
  2. One Data Contract. This class will act as Data Transfer object (DTO) between client and service.
  3. basicHttpBinding is being used in the service. You are free to use any binding as of your requirement.

Data Transfer Class

[DataContract]

public class DTOClass
{

[DataMember]
public string SystemResourceId
{
get;set;

}
[DataMember]
public string SystemResourceName
{
get;
set;
}
[DataMember]
public string Created
{
get;
set;}
[DataMember]
public string Creater
{
get;set;
}
[DataMember]
public string Updated
{
get;set;
}
[DataMember]
public string Updater
{
get;
set;
}

  1. Name of DTO class is DTOClass. You can give any name of your choice.
  2. There are 6 string properties.
  3. All properties are attributed with DataMember.

Contract

[ServiceContract]

[ServiceKnownType(typeof(DTOClass))]
public interfaceIService1
{
[OperationContract]
List<DTOClass> GetData();
}

  1. Service is returning List of DTOClass.
  2. To get serialized at run time, making sure Data Contract is known to contract by using known type.

Service Implementation

public class Service1 : IService1{

string cs = @”Data Source=xxxserver;Initial Catalog=Sampledatabase;User=dhananjay;Password=dhananjay”;
List<DTOClass> restDto = new List<DTOClass>();
DTOClass dto;
public List<DTOClass> GetData()
{
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(“GetAllSystemResourceDetails”, con);
cmd.CommandType = CommandType.StoredProcedure;
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
dto = new DTOClass();
dto.SystemResourceId = dt.Rows[i][0].ToString();
dto.SystemResourceName = dt.Rows[i][1].ToString();
dto.Created = dt.Rows[i][8].ToString();
dto.Updated = dt.Rows[i][10].ToString();
dto.Creater = dt.Rows[i][9].ToString();
dto.Updater = dt.Rows[i][11].ToString();
restDto.Add(dto);
}
return restDto; ;
}} }

  1. This is simple implementation. Where ADO.Net is being used to fetch data from Database.
  2. GetAllSystemResourceDetails is name of the stored procedure.

Note: Purpose of this article is to show how to push large volume of data from WCF service. So, I am not emphasizing ADO.Net part here. See the other articles for detail explanation on ADO.Net

Configuration setting at service side

<system.serviceModel><services>

<service name=TestingLargeData.Service1behaviorConfiguration=TestingLargeData.Service1Behavior>                

<endpoint
address=“”
binding=basicHttpBinding
contract=TestingLargeData.IService1
bindingConfiguration=LargeBuffer>
 

<identity>
<dns
value=localhost/>
</identity></endpoint>
<endpoint address=mexbinding=mexHttpBinding contract=IMetadataExchange/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name=TestingLargeData.Service1Behavior>                    
<serviceMetadata httpGetEnabled=true/>                    
<serviceDebug includeExceptionDetailInFaults=false/>
<dataContractSerializer maxItemsInObjectGraph=2147483647/>
</behavior>
</serviceBehaviors>
</behaviors>

<bindings>

<basicHttpBinding><binding name=LargeBuffermaxBufferSize=2147483647maxReceivedMessageSize=2147483647>

<readerQuotas maxDepth=2147483647maxStringContentLength=2147483647maxArrayLength=2147483647
maxBytesPerRead=2147483647maxNameTableCharCount=2147483647 />
</binding>

</basicHttpBinding></bindings></system.serviceModel>

  1. In service behavior, for dataContractSerializer I am increasing the number of object that can be serialized or de serialized at a time. By default it is set to 3565. Since our requirement is to push or return large volume of data, so I am giving value for maxItemsInObjectGraph to maximum integer number.
  2. Since, I am using basicHttpBinding, so I am modifying values for this binding. I am setting all the attributes to maximum integer value.
  3. Binding I am using is basicHttpBinding.

Compile the service and run to test, whether service is successfully created or not?

Step 2: Creating a client and Consuming the service.

Create any type of client. For my purpose I am creating a console client. After creating a console project, right click at Service Reference and add service reference. While adding service reference make sure, in advance setting as collection type System.Collection.Generic.List is selected.

Configuration setting at client side

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

<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name=BasicHttpBinding_IService1closeTimeout=00:01:00
openTimeout=00:01:00
receiveTimeout=00:10:00
sendTimeout=00:01:00
allowCookies=false
bypassProxyOnLocal=false
hostNameComparisonMode=StrongWildcard
maxBufferSize=2147483647
maxBufferPoolSize=2147483647
maxReceivedMessageSize=2147483647
messageEncoding=Text
textEncoding=utf-8
transferMode=Buffered
useDefaultWebProxy=true>
<security mode=None>
<transport clientCredentialType=NoneproxyCredentialType=None
realm=“” />
<message clientCredentialType=UserNamealgorithmSuite=Default />
</security>
</binding>
</basicHttpBinding></bindings>
<client>
<endpoint address=http://localhost:55771/Service1.svc
binding=basicHttpBinding
bindingConfiguration=BasicHttpBinding_IService1
contract=ServiceReference1.IService1
name=BasicHttpBinding_IService1
behaviorConfiguration =r1/>
</client>
<behaviors>
<endpointBehaviors>
<behavior name =r1>

<dataContractSerializermaxItemsInObjectGraph =2147483647/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
</configuration>

  1. Attributes of basicHttpBinding has been modified for the maximum integer values.
  2. In endpoint behavior maxItemsInObjectGraph for dataContractSerializer has been modified to maximum integer value.

Program.cs

class Program{

static void Main(string[] args)
{
Service1Client proxy = new Service1Client();
List<DTOClass> res = new List<DTOClass>();
res = proxy.GetData();
foreach (DTOClass i in res)
{
Console.WriteLine(i.SystemResourceId + i.SystemResourceName + i.Updated + i.Updater);
}
Console.Read();
}}}

 Conclusion
In this article, I explained how we can return large volume of data from WCF service and how at client side large volume of data can be consumed. This article explained on WCF SOAP based service. Next article I will explain how to achieve same for WCF REST service. Thanks for reading.

CRUD Operations on Windows Azure table and Azure Storage

Objective

This article will give a walkthrough on how to perform a CRUD operation on Azure table.

Step 1

Creating the

Create a new Cloud Service Application. To create, File -> New -> Projects -> Cloud Services. Select ASP.Net Web Role. I am giving CRUDSample to the name of the project and CRUDWebRole to the name of the Web Role. After adding project, in solution explorer you can see two projects. One is project to publish in azure and other is simple asp.net project. In our case CRUDSample is project which contains configuration settings for azure and CRUDWebRole is asp.net project for development.

Step 2

Make sure below references are added CRUDWebRole projects.

System.Data.Service

System.Data.Service.Client

Microsoft.WindowsAzure.Diagnostics

Microsoft.WindowsAzure.ServiceRunTime

Microsoft.WindowsAzure.StorageClient.

Step 3

Creating Entity class

Now right click to asp.net project add a class which will model the table in azure. Give any name to this class. This class will act as entity table.

Inherit the class from
Microsoft.WindowsAzure.StorageClient.TableServiceEntity

  1. Add a default constructor
  2. In Default constructor initialize the Row key and Partition key
  3. Properties of the class define columns of the table.

 

Row Key and Partition key

These two keys uniquely define a table and row in azure storage.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Data.Services;

namespace CRUDWebRole

{


public
class
USTEntity : Microsoft.WindowsAzure.StorageClient.TableServiceEntity

{


public USTEntity()

{

RowKey = String.Format(“{0:10}_{1}”, (DateTime.MaxValue.Ticks – DateTime.Now.Ticks), Guid.NewGuid());

PartitionKey = “UST”;

}


public
String Name { get; set; }


public
String Id { get; set; }


public
String Manager { get; set; }


public
String Experience { get; set; }


public
String Technology { get; set; }


public
String Location { get; set; }
}}

Step 4

Creating Context class.

Now right click on asp.net project and add a new class as context class. This class will contain function to perform all the CRUD operation. This class is inherited from TableServiceContext class.

  1. In default constructor passes the base address and storage credentials to base class.
  2. Since TableServiceContext
    class performs the operations against a class which is implementing IQueryable interface, so we will implement the interface for the entity class.
  3. Just write simple LINQ for other CRUD functions.

 Entire class is as below

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using Microsoft.WindowsAzure;

using Microsoft.WindowsAzure.StorageClient;

namespace CRUDWebRole

{


public
class
USTContext : TableServiceContext

{


public USTContext(string baseAddress, StorageCredentials credentials)

: base(baseAddress, credentials)

{

}

public IQueryable<USTEntity> USTEntities
{
get
{
return this.CreateQuery<USTEntity>(“USTEntities”);
}}

public void ADDUSociate(USTClientEntity entity)
{
this.AddObject(“USTEntities”, new
USTEntity {Name = entity.Name ,Manager =entity.Manager,Id =entity.Id,Location=entity.Location,Technology=entity.Technology,Experience=entity.Experience});
this.SaveChanges();
}
public
void DELUSociate(string id)

{


USTEntity res = (from r in USTEntities where r.Id == id select r ).First();


this.DeleteObject(res);

this.SaveChanges();
}

public void UPDATEUSociate(USTClientEntity entity){
USTEntity res = (from r in USTEntities where r.Id == entity.Id select r).First();
res.Technology = entity.Technology;
res.Location = entity.Location;
res.Manager = entity.Manager;
res.Experience = entity.Experience;
this.UpdateObject(res);
this.SaveChanges();
}}}

In above code I have used USTClientEntity class. This class is mapping of Entity class. This class is as below

USTClientEntity.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

namespace CRUDWebRole

{


public
class
USTClientEntity

{


public String Name { get; set; }


public String Id { get; set; }


public String Manager { get; set; }


public String Experience { get; set; }


public String Technology { get; set; }


public String Location { get; set; }

}}

Step 5

Working with connection strings

We have two options to work with

  1. Use local development center
  2. Use Azure table from Windows azure

Use Local Development center

This option will use the local storage created by development fabric controller when you install Azure SDK.

  1. Go to Azure Project. In this case it is , CRUDSample
  2. Click on Roles folder
  3. Then click on CRUDWebRole
  4. Click on setting tab and add connection string
  5. Click on Add Setting
  6. Make sure while adding connection string, you are choosing connection string from the drop down. Give any name to the string setting.
  7. Now click on left corner button
  8. To use local storage select the radio button Use Development Storage and click on OK button.
  9. To use AZURE table setting

Account Name: Give Azure storage account name

Account Key: Give Primary key from azure storage

Leave other setting as default and press ok.

For My purpose I have two connection strings in my application.

DiagnosticConnectionString

And

CrudString 

Step 6

Creating table

  1. To create table in ASP.net project click on WebRole.cs class
  2. And add below line of code to create class.
var account = CloudStorageAccount.FromConfigurationSetting(“CrudString”);

CloudTableClient.CreateTablesFromModel(typeof(USTContext), account.TableEndpoint.AbsoluteUri, account.Credentials);
 

 Whole WebRole.Cs class will look like below ,

WebRole.cs

using System.Linq;

using Microsoft.WindowsAzure.Diagnostics;

using Microsoft.WindowsAzure.ServiceRuntime;

using System.Data.Services.Client;

using Microsoft.WindowsAzure;

using Microsoft.WindowsAzure.StorageClient;

namespace CRUDWebRole

{

public class WebRole : RoleEntryPoint
{
public override bool OnStart()
{
DiagnosticMonitor.Start(“DiagnosticsConnectionString”);

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(“CrudString”);
CloudTableClient.CreateTablesFromModel(typeof(USTContext), account.TableEndpoint.AbsoluteUri, account.Credentials);
return base.OnStart();
}
private void RoleEnvironmentChanging(object sender, RoleEnvironmentChangingEventArgs e)

{


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

{


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

e.Cancel = true;

}}}}

 

Here CrudString is name of the connection string.

Step 7

CRUD Operations

  1. To add a record
var account = CloudStorageAccount.FromConfigurationSetting(“CrudString”);

var context = new
USTContext(account.TableEndpoint.ToString(), account.Credentials);

USTClientEntity entity = new
USTClientEntity(){Id= txtEmployeeID.Text.ToString(),Name = txtEmployeeName.Text.ToString(),Manager=txtManagerName.Text.ToString(),Experience=ddlExperience.Text.ToString(), Technology = ddlTechnology.Text.ToString(),Location = ddlCurrentLocation.Text.ToString()};

context.ADDUSociate(entity);

 

  1. To update a record
entity = new
USTClientEntity() {Id=ddlEmployees.SelectedItem.Text , Manager = txtManagerName.Text, Location = ddlCurrentLocation.SelectedItem.Text, Technology = ddlTechnology.SelectedItem.Text, Experience = ddlExperience.SelectedItem.Text };

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

var context = new
USTContext(account.TableEndpoint.ToString(), account.Credentials);

context.UPDATEUSociate(entity);

 

  1. To Delete a record
var account = CloudStorageAccount.FromConfigurationSetting(“CrudString”);


var context = new
USTContext(account.TableEndpoint.ToString(), account.Credentials);


if(!string.IsNullOrEmpty(ddlEmployees.Text.ToString()))

{

context.DELUSociate(ddlEmployees.Text.ToString());

}

 

  1. To View all records

     

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


var context = new
USTContext(account.TableEndpoint.ToString(), account.Credentials);


List<USTClientEntity> lst = new
List<USTClientEntity>();


foreach (USTEntity u in context.USTEntities)

{


if (!string.IsNullOrEmpty(u.Id))

{

lst.Add(new
USTClientEntity() { Id = u.Id, Name = u.Name, Manager = u.Manager, Experience = u.Experience, Location = u.Location, Technology = u.Technology });

}

}


this.grdViewAll.DataSource = lst;


this.grdViewAll.DataBind();


 

 

In all above cases drodownlist , Textboxes and GridView has been used as input and output control.

Now your application Is ready to run. Thanks for reading.