Monday, December 20, 2010

Implicitly Typed Local Variables Vs Dynamic Type


Implicitly Typed local variables are declared using “var” keyword. You must need to initialize value at the time of declaring variable. For an example
var counter = 5;
From the above example, Compiler will determine “counter” variable as an int type variable. If you forgot to initialize variable value then compiler will give error (“Implicitly-typed local variables must be initialized”).

Dynamic type is declared using “dynamic” keyword. You don’t require to assign value at the time of declaring variable. Like
dynamic counter;
Compiler doesn’t know about the value but when you set any value to the variable, the variable will hold that type and you can use it. It is similar to Object type. Like
dynamic counter;
counter = 5;
counter++;
counter = new Employee();
counter.Save();

Difference:
  • Developer will get intellisense support with “var” keyword. But you will not get intellisense support with “dynamic” keyword.
  • Implicit local variable give compile type error if any. Dynamic variable gives only runtime error if any.
  • Implicit local variable assign value at the time of declaration only. Developer can change the value but can’t change the type. Dynamic variable gives facility to assign any type of value at anytime. For example if you assign value 5 (numeric) to implicit typed variable then you can’t assign any other type (string, Boolean etc) to that variable. For dynamic type, you can assign any type of value anytime.

Wednesday, November 24, 2010

What is EnableEventValidation


EnableEventValidation attribute is comes with Page directives. EnableEventValidation attribute accept Boolean value i.e. True or False.

When EnableEventValidation is set to True, ASP.Net application will validate the control event generated from the client UI. All ASP.Net control supports the EnableEventValidation features. For an example, If you have one dropdown list which fires page post back and it contains value 1,2 and 3. Now when user select any option then page will get post back and ASP.Net application will validate the request. If ASP.Net gets value 4 in your dropdown box (which is not exists initially) then ASP.Net application will raise the error.

EnableEventValidation have default value “True”. If you required to add some options at runtime using Javascript then you have to set EnableEventValidation=False.

You can also use “RegisterForEventValidation” when adding items at client side.

What is AutoEventWireup


AutoEventWireup is an attribute attached with the Page directives. AutoEventWireup accept Boolean value i.e. True or False.

AutoEventWireup attribute specify that ASP.Net wire up the code behind events with the page automatically or not. I.e. If you set AutoEventWireup = True then ASP.Net will execute code behind events automatically according to the event name. Event names must be predefined name like Page_Init, Page_Load etc… You need not required to attach handler with events. Disadvantage is that you can’t specify event name.

If you set AutoEventWireup = false, then you need to specify handler of event or you have to bind the event with the control.

Default value of AutoEventWireup is true.

Sometime you got a problem of executing any event two times. It is due to the AutoEventWireup attribute.

Sunday, November 21, 2010

WCF Contracts


WCF supports following contracts:
1. Service Contract
2. Operation Contract
3. Message Contract
4. Fault Contract

Service Contract: We can use this service contract attribute on interface which will be exposed to client to consume the WCF service.

[ServiceContract]
public interface IStudentContract
{
[OperationContract()]
List GetStudents();

[OperationContract]
Student GetStudent(int studentId);

}

Here we added “ServiceContract” attribute to IStudentContract interface. So WCF will expose this interface as a WCF service.

Operation Contract: We need to use “OperationContract” attribute to the methods which needs to be exposed as a service method. In above example, We have added “OperationContract” attribute to “GetStudents” and “GetStudent” methods.

Message Contract: Sometime we need to change SOAP message format, then we can use Message contract. We can place some variables in body and some in header part as per requirement.

[MessageContract]
public class Student
{
[MessageHeader]
public int StudentId;

[MessageBodyMember]
public string StudentName;

[MessageBodyMember]
public int Standard;
}

Here, student class is decorated as a MessageContract attribute. When we transfer object of student class between client and service then WCF will include “StudentId” attribute to Message Header and “StudentName” and “Standard” attribute in Message Body.

Fault Contract: Fault contract is used to managing fault (exception) in WCF service. You can decorate any class as a Fault contract and send it as an Exception from service to client.

ABC of WCF


ABC of WCF is “Address, Binding and Contract”. Address part specify where the service is available. Binding part specify which protocol and encoding method, service is using. And Contract specify which message format, service is expected from the client.

Address:
WCF supports many types of addresses to host/consume WCF service like HTTP, HTTPS, Net TCP, Net MSMQ etc... Address gives information where client needs to send message.

Binding:

WCF supports following in-build binding:

1. basicHttpBinding
2. wsHttpBinding
3. wsDualHttpBinding
4. wsFederationHttpBinding
5. netTcpBinding
6. netNamedPipeBinding
7. netMSMQBinding
8. netPeerTcpBinding
9. webHttpBinding
10. msmqIntegrationBinding

Binding gives information about the protocol and encoding method to send the message.

Contract:
Contract expose functionality to client. Contract have message signature so client can send the message to service via consuming service contract.

WCF Hosting Options


WCF gives facility to developer to host their WCF service on following hosting options:

1. IIS
2. Console Application
3. Windows Application
4. Windows Service
5. Self Hosting

IIS:
Developer can host WCF service on IIS. We need to create virtual directory in IIS and create SVC file for exposing WCF service. After doing that, IIS will take care of availability of service. Whenever you will start your machine, WCF service will be available to your customer. You don't required to start any program.

IIS also gives some in-built functionality like web gardening, web farming, recycling etc.

Console application:
Developer can host WCF service on Console application. This option mainly used for testing purpose. You must need to start Console application for service availability. If anybody will close console application then service will not be available to any customer for consumption.

Windows Application:
Developer can host WCF service on Windows application. This option also mainly used for testing purpose. You must need to start Windows application for service availability. If anybody will close windows application then service will not be available to any customer for consumption.

Windows Service:
Developer can also host WCF service in Windows Service. Windows service runs in background. This option is best option to host WCF service if IIS is not available on the server. You can set windows service startup property to Automatic. Windows service will start as soon as machine start so you don't need to start any application for service availability.

Self hosting:
WCF also provides facility to host itself. This used for only testing purpose on developer machine. You can select WCF service project and mark it as startup project. After running the project, Visual Studio IDE will host the WCF service in itself.

WCF Tenets


There are four tenets of WCF:

1. Service boundaries are explicit
In WCF, we must need to expose the service contract to client so client can consume the service and call service method. If we will expose the implemented class then it will mess the boundaries of your service.
2. Service are autonomous
Service must be give full information about itself to client who wants to consume it like address where service is available, which message format service is expected, what transport service is using to receive messages etc.
3. Share Schema not the implementation
Expose only service contract (interface) to client. Never share implemented code to client. It will be very difficult to manage the changes if we will share code with the clients. We need to change code to every place if any change needs into service code.
4. Service Compatibility is Policy based
Service compatibility must be policy based so whenever Admin user will change any policy developer does not required to change accordingly.

What is WCF


WCF stands for Windows Communication Foundation. Foundation means the framework. In short WCF is framework to communicate applications on windows platform.

Earlier, We (Microsoft .Net developer) use different different methodologies to develop application which communicate with different application. For example, If you want to send/receive messages from another application which is developed in Java then you must need to go with ASPX based web service and if you want to communicate application in organization boundary then you can choose .Net remoting. There are lots of way to develop application which can send/receive messages. Some of them are listed below:

• ASPX based Web service
• .Net remoting
• MSMQ based application
• COM+

But when you want to change your application from one method to another then you need to write it from the beginning. Because it is not feasible to migrate from one method to another. So Microsoft have put all those methodologies and create new framework where developer does not required to worry about communication methodologies.

WCF provides most of all the communication methodologies.

WCF is loosely coupled service. You can host your WCF service on any type of applications like

IIS
Console Applications
Windows Application
Windows Service

Saturday, June 26, 2010

Spiral Model


Spiral model is one of SDLC model which is useful to develop application in organised way.

Sprial model is iteration of more than one waterfall model. It means we devide application in small modules.

Follwoing steps will be follow in spiral model

1. We gather requirement for the module
2. We design the module and get approval from the client
3. We implement the module
4. We test that module
5. We deploy that module
6. We will plan for next module and go to step1 for next module.

The above steps will be followed for all the modules while whole application will not complete.



Waterfall Model


Waterfall model is one of SDLC model (Software Development Life Cycle) which helps to develop application in organised way.

In Waterfall model, Application life cycle is devided into following phases:

1. Requirement Gathering
In this phase, We need to gather requirement from the client and create RUD (Requirement Understanding Document) or SRS (Software Requirement specification). We also need to approve those document from Client to move to next phase.

2.Design
In this phase, We need to develop mock-up which will help to client to understand how application will work after development. If there is any change required then client suggest in this phase, so we can save our time in development. After getting approval on design, we need to move to next phase.

3. Implementation
In this phase, we will start implementation. Before going to implement anything, Develop needs to create unit test case document which helps to trace requirement with the SRS or RUD document. Unit testing is part of this phase only.

4. Verification or Testing
In this phase, QA will test the application and check all the requirement is developed as per specification in RUD or SRS. If QA will find any bugs then Developer need to resolve.

5. Deployment
In this phase, We need to deploy application on production machines.

6. Maintenance
In this phase, We need to give support to application on production machines. If any bugs found after deployment then developer needs to solve the bugs.




Different types of SDLC Models


SDLC stands for Software Development Life Cycle. SDLC helps to develop application in organised way.

There are many SDLC models available.

1. Waterfall Model
2. Spiral Model
3. Iterative Model
4. Prototype Model
5. RAD Model
6. COCOMO Model
7. V-Model
8. Fish Model


Interface VS Abstract Class


I tried to find out the difference between Inteface and Abstract class. I have described it blow

1. Methods
In Abstract Class, User can implement method. In Interface, We can't implement any method. (Method signature is not allowed into Interface)

public abstract class TestAbstract
{
public string strProperty { get; set; }

public abstract void abstractMethod();

public string NormalMethod()
{
return "def";
}

}

public interface ITestInterface
{
string stringProperty { get; set; }

void abstractMethod();

}


In above code, NormalMethod is implemented into Abstract class but Interface is not allowed to implement method.

2. Access specifier
We can specify access specifier for property, method. But we cannot specify access specifier in Interface

3. Inheritance
Interface allows multiple inheritance but Abstract class is not allow multiple inheritance.

Thursday, May 27, 2010

SOA Characteristic


SOA characteristics are defined below:

  • Service are discoverable and dynamically bound
  • Service provider use service registry to register service and Service consumer will use Service Registry to find out proper service and consume it. For an example, financial provider gives facility to validate credit card information and register their service with the system registry. They also provide more information like charges to validate credit card information. Service consumer will find all the services which helps to validate the credit card information and choose provider who gave service at lowest price.
  • Services are self contained and modular
  • Most important aspect of SOA is concept of modularity. A service supports a set of interfaces. These interfaces should be cohesive, meaning that they should all relate to each other in the context of a module.
  • Services stress interoperability
  • The ability of system is to be consumed by different platforms and languages to communicate with each other. Services dependencies are loose-coupled means loose-coupled services have a few well known dependencies.
  • Service have a network-addressable interface
  • The role of the network is central to the concept of SOA. A service must have a network-addressable interface. A consumer on a network must be able to invoke a service across the network. The network allows services to be reused by any consumer at any time. The ability for an application to assemble a set of reusable services on different machines is possible only if the services support a network interface.
  • Service have coarse-gained interfaces
  • The concept of granularity applies to services in two ways. First, it is applied to the scope of the domain the entire service implements. Second, it is applied to the scope of the domain that each method within the interface implements. The levels of granularity are relative to each other. For instance, if a service implements all the functions of a banking system, then we consider it coarsegrained. If it supports just credit-card validation, we consider it fine-grained. In addition, if a method for inquiring about a customer returns all customer information, including address, this method would be coarser-grained than a method that does not return the customer’s address.
  • Services are location transparent
  • Location transparency is a key characteristic of service-oriented architecture. Consumers of a service do not know a service’s location until they locate it in the registry. The lookup and dynamic binding to a service at runtime allows the service implementation to move from location to location without the client’s knowledge. The ability to move services improves service availability and performance. By employing a load balancer that forwards requests to multiple service instances without the service client’s knowledge, we can achieve greater availability and performance.
  • Services are composable
  • A service’s composability is related to its modular structure. Modular structure enables services to be assembled into applications the developer had no notion of when designing the service. Using preexisting, tested services greatly enhances a system’s quality and improves its return on investment because of the ease of reuse. A service may be composed in three ways: application composition, service federations, and service orchestration. An application is typically an assembly of services, components, and application logic that binds these functions together for a specific purpose. Service federations are collections of services managed together in a larger service domain. For example, a checking account service, savings account service, and customer service may be composed into a larger banking-account service. Service orchestration is the execution of a single transaction that impacts one or more services in an organization. It is sometimes called a business process. It consists of multiple steps, each of which is a service invocation. If any of the service invocations fails, the entire transaction should be rolled back to the state that existed before execution of the transaction.
  • Service-oriented architecture supports self-healing.
  • With the size and complexity of modern distributed applications, a system’s ability to recover from error is becoming more important. A self-healing system is one that has the ability to recover from errors without human intervention during execution.

Truncate vs Delete


To remove data from database table, we can use Truncate or Delete command on database table.

There are many difference in Truncate and Delete command:

1. Clause:
You can specify where clause to remove some data in Delete command. like:

Delete from Table1 where ID > 20

You can't specify where cluase with Truncate command. Truncate command will remove all the data from table.

2. Transaction:
Delete command is a part of transaction. So you need to commit your transaction to make changes permanent.
Truncate command is not participate in transaction. So you don't required to do anything with transaction.

3. Trigger:
Delete command will fire delete trigger of the table. Truncate command will not fire any trigger.

4. Log:
SQL server logs information regarding delete operation. So everytime log file increased when you will execute delete command. SQL server do not log any information regarding Truncate operation. So Truncate operation is faster than Delete operation.

5. Identity Value:
Truncate reset identity value if table have any identity column. Delete operation not reset any identity value.

Remove duplicate rows in SQL Server


Sometime we face problem of duplicate records in SQL server database. In this scenario, we need to remove duplicate rows.

There are many ways available to remove duplicate rows from the database like
  • Using temporary table – In this you have to transfer data into temporary table which have identity column so you can identify record uniquely and remove duplicate rows. But it gives more loads on SQL if you have lots of data in your table.
  • Using adding Identity column into existing database

All above options gives very heavy load to SQL server. You can remove duplicate rows using following method:
You just have to create in-memory table which just create schema of your table and add new row number column. Using row number column, you can remove duplicate rows.

With [Temp_Table_Name] as
(
Select RN = row_number() over (PARTITION by col1, col2, col3 order by col1, col2, col3), * from [Table_Name]
)

delete from [Temp_Table_Name] where RN > 1

The above script add new column of row number in your table. This is just in-memory change. You can remove duplicate rows which actually remove from your table.

Here I used Row_Number function with “Order by” and “Partition by”.

Wednesday, May 26, 2010

Toolbox Item missing for SSRS Reporting project


When you open SSRS reporting project in Business Intelligence studio, you can view different tool available in your toolbox (make sure your report file is open in IDE). Sometime you will get only Textbox control multiple times instead of different controls.

Come out from this problem, you have to remove some temporary files which load Toolbox. You can get these file on following location:

%userprofile%\Local Settings\Application Data\Microsoft\VisualStudio\9.0

You have to remove following files from the above path:

  • toolbox.tbd
  • toolbox_reset.tbd
  • toolboxIndex.tbd
  • toolboxIndex_reset.tbd

After removing files, you have to reset the toolbox. It will take time to reset the Toolbox. After reseting, you will get all the controls available in SSRS project.

Wednesday, April 7, 2010

Get Windows Username in WCF service method


For configuring windows authentication in WCF service, please refer my previous blog Windows Authentication in WCF

In some scenario, we need to find out the user name who calls WCF service method. You can find out current logged in user who called WCF service method using below code:


OperationContext.Current.ServiceSecurityContext.WindowsIdentity.Name


The above property will return logged in user name with domain name. For example, it returns “DOMAIN\USER”.

windows authentication in WCF


WCF stands for Windows Communication Foundation. WCF provides functionality to create service library. Now a day, everyone wants to implement their solution as a service so anybody else can consume it and will use it.

For example, online payment integration software gives functionality to integrate their API with your application like First Data Global gateway, PayPal etc…

WCF use to expose these services so any client can consume those services and use the service. Some services are not required any authorization to use it. But some services needs authentication before using it. We can develop security in many ways in WCF service. Common ways are defined below:

  • Windows Authentication
  • Form Authentication (Custom Authentication)
  • Certificate base authentication

Here I talked about Windows authentication to secure your service. Windows authentication use logged on user for authentication.

Follow below steps to implement Windows authentication in your WCF service.
  • Create new “WCF Service Application” project from File menu and selecting “New Project” option and select “Web” as a project type and “WCF Service Application” as a project template.
  • Update SerivceModel section in web.config which is given below
  • Also check authentication mode is Windows. If not then change it with “Windows”
  • Open IIS and select virtual directory.
  • In virtual directory property windows, Select “Directory Setting” tab and click on Edit button under “Anonymous access and authentication control”.
  • Remove anonymous access and select “Integrated Windows Authentication”.

Snap of updated web.config file:

<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpEndpointBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="WCFWindowsBasicHttpBinding.Service1Behavior" name="WCFWindowsBasicHttpBinding.Service1">
<endpoint address="" binding="basicHttpBinding"
bindingConfiguration="BasicHttpEndpointBinding"
name="BasicHttpEndpoint" contract="WCFWindowsBasicHttpBinding.IService1">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WCFWindowsBasicHttpBinding.Service1Behavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>


We have mentioned security mode in binding section and bind that binding configuration with endpoint. Also remove the “mex” endpoint from the list of end points.

Now service is ready to use. You can consume the service in your client application. You have to pass user credential before calling WCF service. In client application, give following code before calling WCF service method:


Service1 client = new Service1();
client.Credentials = System.Net.CredentialCache.DefaultCredentials;


This will assign current user credential to service object. Now when you will call WCF service method, WCF will execute that method in context of that logged in user.

If user doesn’t have access on this method then WCF service will return with authentication failure exception.

You can download code from here.

Thursday, April 1, 2010

storage modes in ssas


SQL server analysis service uses three different storage modes for storing data into Cube.
  • MOLAP – Multi-dimensional online analytical processing
  • ROLAP – Relational online analytical processing
  • HOLAP – Hybrid online analytical processing
What is MOLAP?
In MOLAP mode, Data will store in multi-dimensional cube. The storage is not relational database but its proprietary format.

Advantage:
  • Excellent performance
  • Can perform complex calculation – All calculation is pre-generated when cube is created.
Disadvantage:
  • Limited data it can handle – All calculation are performed when cube is built. It is not possible to store large amount of data into cube itself.
What is ROLAP?
In this mode, Data is stored in relational database instead of cube itself.

Advantages:
  • Can handle large amount of data
  • Can leverage functionalities inherent in the relational database
Disadvantages:
  • Performance can be slow
  • Limited by SQL functionalities
What is HOLAP?
HOLAP attempts to combine ROLAP and MOLAP. When Data is very large then SSAS use ROLAP and when data is very limited then SSAS use MOLAP.

Monday, March 29, 2010

Debugging Script Component


Last week, I face one problem in SSIS package. I used Script component and it fails in my application. I tried to debug my code but I am not able to debug it. I dig this problem and found that SSIS package not support break points in script component.

Scenario:
I created one data flow task in my SSIS package. This data flow task contains one script component with other component. This script component is used to split one string as per my logic. This script component fails for some defined cases. So I want to debug the code but BIDS (Business Intelligence Development Studio) is not supporting breakpoints in Script Component.

I found this information from Microsoft website. You can get more detail from http://msdn.microsoft.com/en-us/library/ms136033.aspx

You can use following alternate way:
  • Use Message Boxes to print variable values. So you can check the conditions and your logic according to that value.
  • User logging. Log every variable and condition value into file. You can get idea from that log file.

Wednesday, March 24, 2010

Invoke method using reflection


We have find out methods of any class using reflection but sometime we need to execute it using reflection.

For example, it might required that you have one logic for calculating pricing information which change time to time then you have to use reflection to calculate price. You can create one assembly to calculate pricing information. Whenever you need to change logic, you have to put new assembly on the same path with new logic.

Before calling any method you have to declare object of that class. You can use Activator class to create object runtime.


object objClass1 = Activator.CreateInstance(type);


The above code will create Class1 object using Activator class.

After loading class object successfully, you have to find out method from that type and invoke it. Following source code helps you to invoke method.


Assembly assembly = Assembly.Load("TestLibrary1");
Type t = assembly.GetType("TestLibrary1.Class1");
MethodInfo method = t.GetMethod("GetSum");
object objClass1 = Activator.CreateInstance(t);
object[] objParameters = new object[2];
objParameters[0] = 10;
objParameters[1] = 11;
MessageBox.Show(method.Invoke(objClass1, objParameters).ToString());


Here we load assembly and find out the class type using “GetType” method of assembly class. After getting class type, we have created class object dynamically using Activator class. Then we find out method which we need to invoke and also create parameter array to pass into method. After creating parameter array, we need to call “Invoke” method of MethodInfo class to invoke the method. Return value of Invoke method is the same which that method returns.

You can download source code from here.

Get Class Members using Reflection


You can find basic information of Reflection from What is Reflection.

You can get members of any class using reflection. Let’s start with constructor.

You can retrieve all constructors using “GetConstructors” method which is available in Type class object. You can get Type class object from loading assembly and find Type using “GetType” method. For loading assembly and find type please click here.

Following code snippet is used to get all constructors from any class.

private void GetConstructors(Type type)
{
ConstructorInfo[] constructors = type.GetConstructors(BindingFlags.CreateInstance | BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
foreach (ConstructorInfo constructor in constructors)
{
string constructorString = "";

if (constructor.IsStatic)
constructorString = "static new(";
else if (constructor.IsPrivate)
constructorString = "private new(";
else if (constructor.IsPublic)
constructorString = "public new(";

ParameterInfo[] parameters = constructor.GetParameters();
foreach (ParameterInfo parameter in parameters)
{
constructorString += parameter.ParameterType.Name + " " + parameter.Name + ", ";
}
if(constructorString.EndsWith(", "))
constructorString = constructorString.Substring(0, constructorString.Length - 2);
constructorString += ")";
listBox2.Items.Add(constructorString);
}
}


Here I have not handling error. You can optimize code. I have just draft the code for demo purpose.

We need to call “GetConstructors” method of Type class object which returns ConstructorInfo class array. You can iterate that array and find out constructor information like parameters.

Same way you can find out variables which are declared into class. Following code snippet is used for that:


private void GetVariables(Type type)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
listBox3.Items.Add(field.FieldType.Name + " " + field.Name);
}
}


GetFields class returns all the available variables declared into that type. Here we mentioned Binding Flags which are used to find out type of variable. If you want to find out only private variables then you have to specify “Instance” and “Private” flag only. Here I need to find out Public, Private, Protected and static variables so I have mentioned all required flags.

GetMethods method used to find out list of methods into type. Following code will help you to find out available methods:


private void GetMethods(Type type)
{
MethodInfo[] methods = type.GetMethods();
foreach (MethodInfo method in methods)
{
string methodString = "";

if (method.IsStatic)
methodString = "static " + method.Name + "(";
else if (method.IsPrivate)
methodString = "private " + method.Name + "(";
else if (method.IsPublic)
methodString = "public " + method.Name + "(";

ParameterInfo[] parameters = method.GetParameters();
foreach (ParameterInfo parameter in parameters)
{
methodString += parameter.ParameterType.Name + " " + parameter.Name + ", ";
}
if (methodString.EndsWith(", "))
methodString = methodString.Substring(0, methodString.Length - 2);
methodString += ")";
listBox4.Items.Add(methodString);
}
}


You can also download source code from here.

What is Reflection


Reflection means to find out metadata information of any modules or assembly. You can also create class using reflection.

Developer can load any assembly runtime and find out metadata information of that assembly. He can also create object of any type which are exist in that assembly and also able to assign value and call any method from that object at runtime.

Let’s take an example, you have to use any third party control (DLL). You can get your requested type dynamically.

Here I explained you how to load any assembly which is added as a reference in your project.

You are getting one Test Library1 (TestLibrary1.dll) and you have to find out “Class1” type. You have to add reference of that class library and call this code snippet to load library:


Assembly assembly = Assembly.Load("TestLibrary1");
Type t = assembly.GetType("TestLibrary1.Class1");


Here we have pass “TestLibrary1” as a parameter of Assembly.Load method is an assembly name. This is same as a namespace name.

Assembly is in-built .net class which has static method “Load” which load assembly so developer can easily find out types.

After loading assembly, you can find out your type using GetType method of assembly object.

Load method of Assembly class has different overloads. You can also pass physical path or Assembly name or byte array of assembly name.

You can download code from here.

Monday, March 15, 2010

First Data Global Gateway API Integration with VB.Net


Introduction


Many payment gateways are available in the market to pay for any product online. Below are some online payment gateways:
  • Your Pay

  • PayPal

  • Authorize.Net

  • First Data Global Gateway


Let’s talk about First Data Global Gateway. First Data Global Gateway gives two ways to integrate payment gateway:
  • Using LinkPoint DLL

  • Using Web service


Here I explained how to integrate using LinkPoint DLL.

Before starting integration you need following things to integrate First Data Global gateway with your application:
  • PEM file

  • Merchant Account Number

  • LinkPointTransaction.dll and lpssl.dll (Ask to provide from First Data)


Download application from here.

Above application is .Net class library project. You have to take reference of class library. Now you are ready to use the Global Data payment gateway with your application. You have to pass following parameters:
  • strType – Type of the payment, It may hold either “Good”, “Decline” or “Duplicate”.

  • strMerchantNumber – You will get this from First Data when you will open your account with them

  • dblAmount – Amount of the transaction

  • strZip – Zip code of the customer who used his/her credit card to do payment

  • strAddNum – Address of the customer

  • strCC – Credit card number

  • strcardexpmonth – Expiry month of credit card

  • strcardexpyear – Expiry year of credit card

  • strKeyFile – PEM file path (full path). You will get PEM file from First Data when you will open account with them

  • strHost – It may hold either “staging.linkpt.net” or “secure.linkpt.net”. For testing purpose you have to pass “staging.linkpt.net”. On server, you have to pass “secure.linkpt.net”.

  • intPort – Port number to connect above host. For now you have to pass “1129”.


Sunday, March 14, 2010

What is fill factor


When you create clustered index, SQL server will create index pages to store the data in order to clustered index. When user will insert new record or update clustered index column data then SQL server will change its index pages data. For example if you will insert new data into table, SQL server will shift its data from one data page to another to make sufficient space to insert new record in correct place. It will decrease your query performance. This also implies with non-clustered index.

Fill factor is used at the time of creating index. Fill factor is percentage value from 0 to 100. Fill factor option will add some spaces in data pages so when user will add new record it will easily manageable for SQL server to insert record in any data page.

Fill factor value 100 means there is no space required in data pages. When your table is read only or you are sure about there is no change in your table in future then you can provide 0 as a fill factor.

Lower fill factor value leaves more spaces in data pages. So whenever user will add new record it will easily manageable for SQL server to make sufficient space to add the record in particular order. It will increase speed of your query.

Fill factor imply only when you will create index. It is not maintained after records are added, updated or deleted.

Wednesday, March 10, 2010

asp.net page life cycle


When user requests any asp.net page, the page goes to asp.net page life cycle in
which it perform a series of processing state. ASP.Net page will execute some methods
in sequence in its life cycle. All those methods are explained below:


Method Name

Description

Pre Initialization

During page initialization, controls on the page are available and Unique id property is set. Theme is also applied in this method. If page is post back then posted data is not loaded in this method and also controls state is not restored from the view state.

Load

During load, if page is post back then controls is restored from the view state or control state

Validation

During validation, the validate method of all the validation control is executed which set IsValid property of validation control

Post event handling

If page is post back then handle event handling

Rendering

Before rendering, view state data are saved.

Unload

Unload is called after page is successfully rendered, sent to the client and is ready to dispose. At this point Response and Request object are unloaded and any cleanup is performed.

what is multicast delegate?


What is multicast delegate?

Multicast delegate is delegate which holds more than one method reference. When you call delegate, it will execute all the methods which are associated with that delegate.

Sometime we assigned two functions to one delegate it calls multicast delegate. Just take an example, if you have one delegate to transfer fund from one account number to another account. You also want to log every entry into your log system so you can solve any customer query if any.

We have one delegate which is used to transfer funds from one account to another account. Delegate syntax is displayed as below:

delegate void TransferFund(string FromAccountNumber, string ToAccountNumber, decimal Amount);

Now in your class, you can give more than one method reference to this delegate. Code for this is as below:

private void Form1_Load(object sender, EventArgs e)
{
TransferFund transferFundObject = new TransferFund(DoTransferFund);
transferFundObject += new TransferFund(DoTransferFundLog);
transferFundObject("From_Account_No", "To_Account_No", 1000);

}

void DoTransferFund(string FromAccountNumber, string ToAccountNumber, decimal Amount)
{

}

void DoTransferFundLog(string FromAccountNumber, string ToAccountNumber, decimal Amount)
{

}

In above code, In Form load event, I have registered two methods with one delegate. When we call the delegate it will execute both methods one by one.

Tuesday, February 23, 2010

Call Stored Procedure from Entity Framework


Microsoft have introduced entity framework to connect to the database. When you work with the database, you have to call your stored procedure. This blog explain you how to execute your stored procedure from Entity Framework.

Assume that your stored procedure insert/update/delete record into database. It returns nothing just do as per the parameter value.

Follow the below steps:
1. Open Entity Framework Model page in Visual Studio IDE
2. Right click on blank area and choose “Add” -> “Function Import” option
3. In Add Function Import dialog, select your stored procedure, give function name and choose return type
4. Click on Ok button to add the function in Entity Framework
5. In your page, Create instance of entities class and call your function with proper parameter value

If your stored procedure is return multiple record then you have to create one custom entity, which have the same schema as your stored procedure return the data. To create the custom entity, right click on Entity Framework Model page and choose “Add” -> “Entity…” It will open “Add Entity” dialog box where you have to give Entity Information.

You can add/edit/delete properties into custom activity. To add, Select “Scalar Properties” section under custom activity, right click and choose “Add” -> “Scalar Property”.

Just create custom entity. After creating custom entity, Add Function Import to your entity framework model.

Follow the below steps:
1. Open Entity Framework Model page in Visual Studio IDE
2. Right click on blank area and choose “Add” -> “Function Import” option
3. In Add Function Import dialog, select your stored procedure, give function name and choose return type as Entities and select your custom entity from dropdown list.
4. Click on Ok button to add the function in Entity Framework
5. In your page, Create instance of entities class and call your function with proper parameter value


TestDBEntities1 testdb = new TestDBEntities1();
var p = from d in testdb.GetOrderInfo() select d;

Friday, February 19, 2010

Entity Framework Stored Procedure mapping


Introduction



Now days, Microsoft have changed lots of thing in accessing database from .Net application. Microsoft has introduced Entity Framework to access database from the application. Entity framework is just a small wizard which helps to create classes to access the database. To know basic of Entity Framework please click on here.

In Part 1, I explained you how to create entity framework class in your project and how to insert, update or delete the record. Now in part 2, I explain you how to map your stored procedure with insert, update and delete functionality.

If you will not map your stored procedure then Entity Framework will create concrete SQL statement for insert, update and delete. If you will map your stored procedure then Entity Framework will execute your stored procedure with parameter value.

Let take an example of contact table which I explained schema in part 1.

After creating entity framework file (.edmx), Select “Contact” entity and open “Mapping Details” window. In Mapping Details window, click on “Map Entity to Function” button on left side. Refer below screen shot:




In Insert/Update/Delete function, Select your stored procedure and map your parameter value. Refer image below:



Now you have to just add/update/remove data using Entity Framework and It will execute your mapped stored procedure.

Following code is used to add new record into Contact table. When user will execute the code below, Entity Framework will execute “SPE_ContactInsert” stored procedure to insert contact information.

TestEntityEntities testEntityEntities = new TestEntityEntities();
Contact contact = new Contact();
contact.FirstName = "test1";
contact.LastName = "test2";
contact.Title = "Mr.";
testEntityEntities.AddToContact(contact);
testEntityEntities.SaveChanges();

As the same way you can update or delete the record. For more information please refer Entity Framework part 1 here.

Sunday, February 14, 2010

Register .net assembly as COM


Introduction
We have used VB6.0 DLL or OCX component in our .Net application. But sometime we need to use our .Net DLL into VB6.

In the following scenario you need to use .Net DLL into VB6.
  • Any third party module is available in .Net and you need to integrate it with your VB6.0 application

  • Your some modules are already developed into .Net and you have to integrate it with VB6.0 application


This blow will explain you how to create COM compatible .Net assembly step by step.

First we need to create one class library project. Open Visual Studio and create new Class Library project. Give “DemoClassLibrary1” name to your class library.

Create new class which needs to be expose as a COM object. Just add new class into your class library project. Give “DemoClass1” to your class name.


Public Class DemoClass1

Public Function GetWelcomeString(ByVal name As String) As String
GetWelcomeString = "Welcome " + name
End Function

End Class

Now to create it COM compatible, you have to add ComClass attribute on your class definition. So updated code will look like below:



Public Class DemoClass1

Public Function GetWelcomeString(ByVal name As String) As String
GetWelcomeString = "Welcome " + name
End Function

End Class

I have created one method which will be exposed as a COM method.

You also need to set your project as a Com compatible. To configure it, open project property. Right click on project in solution explorer and select properties option. In compile tab, select checkbox “Register for COM Interop”.

Now when you will build your project, project will create DLL as well as TLB file. This TLB file needs to use your .Net DLL into VB6.

Let’s use this DLL into VB6. Open your VB6 project and open reference dialog to add your .Net class reference. You will get option for “DemoApplication1”, select the option and click on ok.

Now you can create object of “DemoClass1” and use your function “GetWelcomeString”.

If you want to use this component on another machine then you have to copy the DLL file on that machine and register your DLL file to the registry so your VB6 application can find your component.

To register the component, Open Visual Studio 2008 command prompt and execute following command.


Regasm <<DLL file full path>> /tlb:<<tlbfilename>> /codebase

Regasm command generate TLB file and also register it with the system. Codebase option also set the code base with the registry.

Friday, February 12, 2010

SQL Server 2005 Integration Service Basic


Introduction

SQL Server Integration service is mainly used to transfer data from one database to another in different format. Also it is used to manipulate data before storing on destination.

SSIS (SQL server Integration Service) is specially designed for ETL process. ETL stands for Extract, Transform and Loading.

SSIS create package which you can execute from the SQL server management studio, stored procedure or SQL server job which extract data from one database, manipulate it and store it in another database. Here both databases may be different.

You can use any of the following database connection with SSIS package:

  • SQL Server

  • Flat File

  • OLEDB

  • ADO.Net

  • Analysis Service


Prerequisite:
We need SQL Server Business intelligence development studio (BIDS) tool to develop SSIS package. BIDS tools come with Microsoft SQL Server Installation. Installing Microsoft SQL Server, Please check “Analysis Service” and “Integration Service” option.

In this blog, I will explain you how to create simple SSIS package and execute it from the SQL Server Business Intelligence development studio.

Open SQL Server Business Intelligence Development studio. Follow the following steps to create new SSIS package.

  • Create new project from “File” menu -> “New Project”.

  • Select “Business Intelligence Projects” from Project types in New Project dialog box

  • On right side, you can see different Template available for “Business Intelligence Projects” type. Select “Integration Service Project” template from the available template.

  • Give appropriate project name. Here I am giving “DemoIntegrationProject”

  • Select Location where you want to save the file. And also give solution name. I am giving “DemoIntegrationSolution”.

  • Click on Ok button to create new SSIS project.


The New project dialog box will display as below:



BIDS creates new project and open that project. You can see the available files and objects in Solution explorer. Open solution explorer if it is not opened.

You get four folder in solution explorer included into the project.

  • Data Sources: This folder contains information about all data source used into the project.

  • Data Source Views: This folder contains the views (UI) of used schema from the data sources.

  • SSIS Packages: This folder contains all SSIS packages.

  • Miscellaneous


Projects template add one blank SSIS package “Package.dtsx” into the project. We will first understand “Data sources” and “Data Source Views” to understand SSIS package.

Data Sources:
Select “Data Sources” folder in solution explorer. Right click on that. You will get “New Data Source…” option to create new data source. Just click on “New Data Source…” option.

“New Data Source…” option open wizard to create and add new data source into project. Follow the below steps to create new data source:

  • On welcome screen, click on Next button

  • On “Select how to define the connection” screen, you can see existing data connections (if you used SSIS before and added into any project). Refer screen below



  • Select data connection if exist in the list. If your required connection is not available then you can create new connection using “New…” button.

  • If connection is not already exist then click on “New…” button. It will open connection manager dialog. On Connection Manager dialog, select appropriate provider. Provide information necessary to create new data connection. Test your input information using “Test Connection” button. If your connection test successfully then Click on Ok to create new connection. Refer screen below



  • You will get your connection on “Select how to define the connection” dialog. Select your connection and click on Finish button

  • Give your connection name and click on Finish button.


Now you will get new data source file under “Data Sources” folder in solution explorer.

Data Source Views:
You have to create data source views before using data source into SSIS package. To create new “data source view”, select “Data Source Views” folder in solution explorer and right click on it. Select “New Data Source View…” option.

New Data Source View dialog open. Follow the below steps create new data source view:

  • On welcome screen, click on Next button

  • On “Select a data source” screen, select the data source which you have created. You can create new data source using “New Data Source…” button.

  • After selecting data source, click on next button

  • On “Select Tables and Views” dialog box, Add required tables to Included objects list box. You can add related objects using “Add Related Tables” button. You can also filter available objects using Filter text box. Add all required tables and views and click on Next button. Refer screen below:



  • On “Completing the wizard” screen, give “Data source view” name (Here I gave it to “Test DB”) and click on Finish button.

  • It will add new data source view file in the project.





Data Source View editor have three panes: Diagram Organizer, Tables, and Diagram.

Diagram Organizer: Diagram organizer pane allows you to create new Diagram and organize table into sub set. If you have 500 tables/views on Data Source view, then it will be difficult to refer any particular table or related tables. So you can make different Diagram using Diagram organizer pane. Just right click on “” and select “New Diagram” option. It will open new diagram where you can add only your required tables from “Tables” pane.

Tables: Tables pane contains all tables and views selected while creating data source view. After creating data source view, you can add/remove any objects. To add new table/view, just click on “Add/Remove objects” button in tool bar. It is displayed just above Diagram organizer pane.

Diagram: Diagram pane displays all tables and views schema and relation between them.

You can rename table/view and your field name. Sometime your database table/view name is not user friendly like the above diagram “tblProducts” table name is not user friendly. To rename table/view/field name, just select it in Diagram pane and open properties windows. In properties window, change FriendlyName property to give some meaningful name. I have change table names and the updated diagram is displayed as below:



SSIS Package:
You can create new SSIS package using right clicking on “SSIS Packages” folder in Solution explorer and select “New SSIS Package” option.

After package file is added into the solution you can rename to give proper name. When you will rename the package, it gives message to open the SSIS package click on yes to open the package.

SSIS package editor have four tabs:

  • Control Flow

  • Data Flow

  • Event Handlers

  • Package Explorer



Control Flow: You can add any number of control flows on your SSIS package. Control flow is just like a one task which you want to accomplish using SSIS package. BIDS tool have many integrated tools available to work with your project. Following are the most usable control flow tasks:

  • Bulk Insert Task

  • Data Flow Task

  • Data Mining Query Task

  • Execute Package Task

  • Execute Process Task

  • Execute SQL Task

  • For loop container

  • Foreach loop container

  • FTP Task

  • Script Task

  • Send Mail Task

  • Web service Task

  • Xml Task



There are many other tasks available to create SSIS package as per your requirement.

Data Flow: Data flow is detailed definition of “Data Flow Task” which is available to add in Control Flow. You have seen “Data Flow Task” item available in above list to add into Control Flow tab. When you will add Data Flow Task, you can see those data flow task name in “data flow task” combo box in Data Flow tab.





Now we will create one sample SSIS package, deploy it and execute it from Business Intelligence development studio.

  • Open your SSIS Package and open “Control Flow” tab.

  • In Control Flow tab, Right click in “Connection Managers” pane and select “New Connection from Data Source…”

  • It will open “Select Data Source” dialog box where you can see the Data sources added in your project.

  • Select the proper data source and click Ok button. It will add that data connection into your SSIS package. Refer screen below:





  • After successfully adding connection manager, Add Data Flow task control on your control flow.

  • Right click on Data Flow Task in Control Flow tab and select Property. Change name property from “Data Flow Task” to “Export Customer Data”

  • Go to Data Flow Tab

  • Add “OLE DB Source” Task on “Data Flow” tab

  • Double click on “OLE DB Source” task to open OLE DB Source Editor

  • In editor, Select Connection Manager, Data Access mode and other required items. For demo purpose select “Test DB” as a connection manager, “Table or View” as a data access mode and select tblCustomers as a table.

  • Click on Ok button.

  • Now drag and drop “Flat File Destination” control on Data Flow tab

  • Select “Ole Db Data Source” control, you can see green and red arrow. Just hold green arrow and put it on “Flat file destination” control.

    Green arrow – Green arrow is used to follow the process if preceding task is completed successfully. In our case, if we get customer data successfully then only go to flat file destination to export it.

    Red arrow – Red arrow is used to follow the process if preceding task is completed with error. You can use “Send Mail” task to send the error information or save those error in another destination.







  • Double click on “Flat File Destination” control to open control editor

  • Create new connection for Flat file. Click on New button to create new connection.

  • Select “Delimited” option to generate Flat file connection manager.

  • Give proper name and browse the file path

  • Click on Ok to add connection manager to your project.

  • Click on ok in “Flat File destination editor”



Now you simple package is ready. This package will read customer data from the database and put it in Flat file (Comma separated). You can also use another controls to process the data. You can also filter the data in OLEDB Source control.

When you will execute SSIS package, Business Intelligence development studio will execute your task and transfer customer data from database to your flat file.

Still you have not deployed SSIS package. You can deploy it in SQL server. Follow the below steps:

  • Open SQL Server and login on server using Integration service. (In login dialog box, you have to select server type as a Integration service)

  • After successfully connecting, expand “Stored Packages” in object explorer.

  • Expand “File System”.

  • Right click on “File System” and choose “Import Package”

  • In Import package dialog, Select “File System” as a Package location

  • Select the Package path. Browse to the path where we have created the above SSIS package project and select DTSX file.

  • Give the package name and click on ok button to create the package.






You can see your SSIS package under “File System” node in object explorer of SQL server management studio.

You can execute SSIS package from SQL server management studio. Right click on “OrderSSIS” package and choose “Run Package” option. It will open “Execute Package Utility” dialog. Click on Execute button to run the package.

Wednesday, February 10, 2010

Implementing Singleton Design Pattern in C# application


Introduction

Sometime we need to create only one object of any class in our application then we need to implement Singleton design pattern to achieve this.

For an example, you have logging functionality which takes value as a parameter and store information in external device (like database or xml file or flat file). This logging class doesn’t have any state value. You can design that class using singleton design pattern.

Problem and solution

First problem is that you need to be sure that your class must be initializing once and the reference is available at anytime so your application can use that reference to use singleton class method.

You can solve the above problem using private constructor. When you define private constructor then nobody can initialize object of that class. (Make sure that singleton class doesn’t have any public constructor).

public class SingletonTest
{

private SingletonTest()
{

}

}


Second problem, if you create private constructor then how can we initialize the class first time when we need it?

We can create and initialize object of singleton class (which have only private constructor) within that class. To achieve this we need to implement one public static method which will return object of Singleton class.

public class SingletonTest
{

private static SingletonTest singletonTest = null;

private SingletonTest()
{

}

public static SingletonTest RetrieveObject()
{
if (singletonTest == null)
singletonTest = new SingletonTest();
return singletonTest;
}

}

Now, we can create and initialize object of our singleton class using below code:


SingletonTest singletonTest = SingletonTest.RetrieveObject();

When user will call this method first time, this method will create new object of SingletonTest class and assign it to private static variable and return that variable.

When user will call the same method again, this method will check that the private static variable is initialized. If private static variable is initialized then it will return it. In our case it initialized already when user called this first time.

So it confirms that our SingletonTest class has only one reference during whole application life cycle.

Tuesday, February 9, 2010

.Net Remoting


Introduction

Sometime we need to call method on remote machine or on the same machine but in different Application Domain. In this scenario, we need to implement Remoting.

We can also use the following options in behalf of Remoting:
  • Web service

  • MSMQ

  • WSE


Remoting is faster than the above things. MSMQ is depended on Microsoft Message Queue. Web service and WSE is slower than .Net Remoting. But Remoting have also some constraint:

  • You can use Remoting only when both side application is develop using .Net Framework

  • Remoting uses binary serialization. Microsoft has changed their binary serialization in 2003 and 2005. So your both application must be developed using same version of .Net Framework.


Example
Let’s take an example.

To implement Remoting service in your application, you have one common contract for both client and server application. So first we create one class which will be shared on both client and server application.

Open Visual Studio and create one class library. Create one class. For demo purpose I have created one class “CommonClass”.


public class CommonClass : MarshalByRefObject
{

public string FirstName;

public string LastName;

public string GetWelcomeString()
{
Console.WriteLine("Welcome " + FirstName + " " + LastName);
return "Welcome " + FirstName + " " + LastName;
}

}


Please note that, this class must be derived from MarshalByRefObject class. If you will forget to derive your class from MarshalByRefObject class then you will get runtime error “Trying to create a proxy to an unbound type.”


In the above class, I just declared two public variables, FirstName and LastName and add one public method “GetWelcomeString” which return welcome string with first name and last name.

In GetWelcomeString function, we have writes welcome string on console and also return the same string. This method will execute on server side so it will display text on server side and return value to client side.

Now let’s implement server application. Open visual studio and create one console application.

Add following reference in server application project:
  • CommonClass library project

  • System.Runtime.Remoting


Add the following code into Program.cs file in main method:


static void Main(string[] args)
{
TcpChannel tcpChannel = new TcpChannel(8084);
ChannelServices.RegisterChannel(tcpChannel);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(ClassLibrary1.CommonClass), "testRemoting", WellKnownObjectMode.Singleton);
Console.WriteLine("Server is ready");
Console.ReadLine();
}


In the above code, first we create TcpChannel class object which will be registered with appropriate port number. Please don’t use the currently used port. If you will use the port number which is already used with another application then you will get runtime error.

After registering TcpChannel, We need to just register our class using RemotingConfiguration. First parameter is which type you want to register; give our class type. Second parameter is URI which is used to communicate with server from client application. And last parameter is WellKnownObjectMode.

WellKnownObjectMode is ENUM and contains two values:
  • Singleton – which create only one object of our common class and serve all the request using that object only

  • SingleCall – which create object every time when user will send a request to server



Now let’s create client application. Open Visual Studio and create new console application.

Add following reference in server application project:
  • CommonClass library project

  • System.Runtime.Remoting



Add the following code into Program.cs file in main method:


static void Main(string[] args)
{
CommonClass c = (CommonClass)Activator.GetObject(typeof(CommonClass), "tcp://localhost:8084/testRemoting");
Console.WriteLine("Client is ready");
c.FirstName = "Hardik";
c.LastName = "Patel";
Console.WriteLine("Return string: " + c.GetWelcomeString());
Console.ReadLine();
}


First we create object of our CommonClass but we use Activator.GetObject method to get object from the server.

This method has two parameters, first is type of object which you need to get, pass our CommonClass class type.

Second parameter is URL from which we need to get object.

The URL is: tcp://localhost:8084/testRemoting

We used TCP as a channel service so we need to use TCP protocol.
Server is running on the same machine so I have used “localhost”. If you server application is running on different machine then please use that machine name/IP address instead of localhost.
testRemoting is a URI which is defined in server application when we register our class using RemotingConfiguration (Second parameter).

Now execute server application first. After getting “server is ready” message in server application console, execute client application. Server application will display “Welcome Hardik Patel” message and return the same message to client application. Client application also displays the message “Return string: Welcome Hardik Patel”. Please refer screen below:


Monday, February 8, 2010

Workflow Custom Activity – Part 2


Introduction

Windows Workflow foundation gives many activities to use in workflow like code, delay, IfElse, Listen, Parallel etc. But in some scenario, those activities will not work as per our requirement. So we need to implement custom activity which will work as per our requirement.

To create a custom activity, Please visit http://dotnet-codeguru.blogspot.com/2010/02/windows-workflow-foundation-custom.html

In some scenario, you have to create some dynamic property in custom activity. For an example you are creating custom activity for Order Search. In this activity, User can search order by order id or customer id. So you want to give filter where user can select either “Order ID” or “Customer ID”. If user will select Order ID then new property Order Number will display in property window. And if user will select Customer ID then new property Customer Number will display in property window.

It is similar to IfElse Branch condition property. You get two options “Code Condition” and “Declarative Rule Condition”. As per your selection, you will get sub properties.



Let’s implement same thing in custom activity:

To support sub property for Order Search type we need to implement two classes “OrderSearchByOrderID” and “OrderSearchByCustomerID” which are derived from “ActvityCondition” class.

In the above classes, we need to override “Evaluate” method. In this simple scenario, we always return true from the above classes.

In OrderSearchByOrderID class, we need to add one property for OrderID which will display when user select “OrderSearchByOrderID” option from the selection box. The code for the OrderSearchByOrderID class is look like below:


public class OrderSearchByOrderID : ActivityCondition
{
public override bool Evaluate(Activity activity, IServiceProvider provider)
{
return true;
}

private string orderID;

[Browsable(true)]
public string OrderID
{
get
{
return orderID;
}
set
{
orderID = value;
}
}

}


Code for OrderSearchByCustomerID is similar and looks like below:


public class OrderSearchByCustomerID : ActivityCondition
{
public override bool Evaluate(Activity activity, IServiceProvider provider)
{
return true;
}

private string orderID;

[Browsable(true)]
public string OrderID
{
get
{
return orderID;
}
set
{
orderID = value;
}
}
}


We need to develop “TypeConvertor” which helps to display the option in dropdown box in property window.


public class CustomOrderSearchTypeConverter : TypeConverter
{

private Hashtable _conditionDecls = new Hashtable();

public CustomOrderSearchTypeConverter()
{
try
{
AddTypeToHashTable(typeof(OrderSearchByCustomerID));
AddTypeToHashTable(typeof(OrderSearchByOrderID));
}
catch (Exception ex)
{
throw;
}
}

private void AddTypeToHashTable(Type typeToAdd)
{
string key = typeToAdd.FullName;
object[] attributes = typeToAdd.GetCustomAttributes(typeof(DisplayNameAttribute), false);
if (attributes != null && attributes.Length > 0 && attributes[0] is DisplayNameAttribute)
key = ((DisplayNameAttribute)attributes[0]).DisplayName;
this._conditionDecls.Add(key, typeToAdd);
}

public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
try
{
if (sourceType == typeof(string))
{
return true;
}
return base.CanConvertFrom(context, sourceType);
}
catch (Exception ex)
{

throw;
}
}

public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
try
{
string strVal = value as string;
if (strVal != null)
{
if (strVal.Length == 0 || strVal == "")
return null;
else
return Activator.CreateInstance(this._conditionDecls[value] as Type);
}
return base.ConvertFrom(context, culture, value);
}
catch (Exception ex)
{

throw;
}
}

public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
try
{
if (destinationType == typeof(string))
{
return true;
}
else
{
return base.CanConvertTo(context, destinationType);
}
}
catch (Exception ex)
{

throw;
}
}

public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
try
{
if (value == null)
return "";
object convertedValue = null;
if (destinationType == typeof(string) && value is ActivityCondition)
{
foreach (DictionaryEntry conditionTypeEntry in this._conditionDecls)
{
if (value.GetType() == conditionTypeEntry.Value)
{
convertedValue = conditionTypeEntry.Key;
break;
}
}
}
if (convertedValue == null)
convertedValue = base.ConvertTo(context, culture, value, destinationType);
return convertedValue;
}
catch (Exception ex)
{

throw;
}
}

public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
try
{
ArrayList conditionDeclList = new ArrayList();
conditionDeclList.Add(null);
foreach (object key in this._conditionDecls.Keys)
{
Type declType = this._conditionDecls[key] as Type;
conditionDeclList.Add(Activator.CreateInstance(declType));
}
return new StandardValuesCollection((ActivityCondition[])conditionDeclList.ToArray(typeof(ActivityCondition)));
}
catch (Exception ex)
{

throw;
}
}

public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
try
{
// Always return true.
return true;
}
catch (Exception ex)
{

throw;
}
}

public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
try
{
// Always return true.
return true;
}
catch (Exception ex)
{

throw;
}
}

public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
{
try
{
PropertyDescriptorCollection props = new PropertyDescriptorCollection(new PropertyDescriptor[] { });
TypeConverter typeConverter = TypeDescriptor.GetConverter(value.GetType());
if (typeConverter != null && typeConverter.GetType() != GetType() && typeConverter.GetPropertiesSupported())
{
return typeConverter.GetProperties(context, value, attributes);
}
return props;
}
catch (Exception ex)
{

throw;
}
}

public override bool GetPropertiesSupported(ITypeDescriptorContext context)
{
try
{
// Always return true.
return true;
}
catch (Exception ex)
{

throw;
}
}

}


Now we need to use these classes in our custom activity. Just create a new class “OrderSearchActivity” and derive it from “Activity” class.

To give support, we need to implement one dependency property which is ActivityCondition type. Here we declared “OrderSearchTypeProperty” dependency property.

And also implement property for the same “OrderSearchType”.


public static DependencyProperty OrderSearchTypeProperty = DependencyProperty.Register("OrderSearchType", typeof(ActivityCondition), typeof(OrderSearchActivity));

[Description("Order Search Type")]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[TypeConverter(typeof(CustomOrderSearchTypeConverter))]
public ActivityCondition OrderSearchType
{
get
{
return ((ActivityCondition)(base.GetValue(OrderSearchTypeProperty)));
}
set
{
base.SetValue(OrderSearchTypeProperty, value);
}
}


Now when you will use this OrderSearchActivity in your workflow then you will see option for OrderSearchType.




If you select “OrderSearchByCustomerID” then you will see “+” sign in front of “OrderSearchType” property which indicate that you have some sub properties. When you click on “+” sign you will get “Customer ID” as a sub property.





Now let’s see how we can use the above property in your custom activity. For this I have override Execute method in OrderSearchActivity.


protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
{

if (OrderSearchType.GetType() == typeof(OrderSearchByCustomerID))
{
OrderSearchByCustomerID orderSearchByCustomerID = (OrderSearchByCustomerID)OrderSearchType;
string CustomerID = orderSearchByCustomerID.CustomerID;
// User CustomerID variable to search orders
}
else if (OrderSearchType.GetType() == typeof(OrderSearchByOrderID))
{
OrderSearchByOrderID orderSearchByOrderID = (OrderSearchByOrderID)OrderSearchType;
string OrderID = orderSearchByOrderID.OrderID;
// User OrderID variable to search orders
}

return base.Execute(executionContext);
}


In Execute method, we first check OrderSearchType property value type, if it is OrderSearchByCustomerID then we convert it in that and find customer id which is assigned by user. If type is OrderSearchByOrderID then we convert it in that and find order id which is assigned by user.


DotNet Code Guru