Thursday, November 18, 2010

How to implement transaction in WCF client

Here we see how to consume two wcf service from wcf client !

Create a WCF Service :

using System.ServiceModel;
namespace ACWCF
{ [ServiceContract]
public interface ITranService
{

[TransactionFlow(TransactionFlowOption.Allowed)]
[OperationContract]
void UpdateData();
}
}

// Implement the interface
public class TranService : ITranService
{
[OperationBehavior(TransactionScopeRequired = true)]
public void UpdateData()
{
SqlConnection objConnection = new SqlConnection("MyConnectionString");
objConnection.Open();
SqlCommand objCommand = new SqlCommand("insert into Customer(CustomerName,CustomerCode) values('sss','sss')", objConnection);
objCommand.ExecuteNonQuery();
objConnection.Close();
}

// Assuming we are aware of hosting the service on IIS .. so i am not talking about the web.config part of it .



Now lets create a client to consume multiple wcf service

// this is how wcf client can consume multiple wcf service.
using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required))
{
try
{
//ServiceReference1.Service1Client obj = new ServiceReference1.Service1Client();
//obj.UpdateData();
//ServiceReference2.Service1Client obj1 = new ServiceReference2.Service1Client();
//obj1.UpdateData();

ts.Complete();
}
catch (Exception ex)
{
ts.Dispose();
}
}

A great article can be seen on
http://www.c-sharpcorner.com/UploadFile/shivprasadk/436456754708092009145905PM/4364567547.aspx

another good wcf clip can be seen at:

Saturday, November 13, 2010

Entity Framework Sample

You need to install sp1 before you can start with entity framework

If you can't see the framework template, do the following step
Click on Tools => Option => Projects & Solutions ..then
Click on "User item template location" browse button and set the right path
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\
do same for project templets
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ProjectTemplates\
Now click on "ok"
then close the studio and re-open again ..now you will be able to see the entity framework template

some more guide step - by step can be seen on http://www.installationwiki.org/Installing_ADO.NET_Entity_Framework

Getting problem in Connectionstring in Entity framework ?

< add name="HRRPMSContext" providerName="System.Data.EntityClient" connectionString="metadata=res://ETG.Base.Applications.EntityFramework,Culture=neutral,PublicKeyToken=null/HRRPMSContext.csdl|res://ETG.Base.Applications.EntityFramework,Culture=neutral,PublicKeyToken=null/HRRPMSContext.ssdl|res://ETG.Base.Applications.EntityFramework,Culture=neutral,PublicKeyToken=null/HRRPMSContext.msl;provider=System.Data.SqlClient;provider connection string='Data Source=ETG1\SQLEXPRESS;;Initial Catalog=ACSampleDB;User ID=HRRPMS;Password=pass;Integrated Security=True;multipleactiveresultsets=true'"/ >

In the above string ETG.Base.Applications.EntityFramework is my assembly name ETG.Base.Applications.EntityFramework.dll

Another way of creating  to connection string for entity framework is

 internal class Util
    {
        public static string EntityFrameworkConnectionString
        {
            get
            {
                SqlConnectionStringBuilder providerCs = new SqlConnectionStringBuilder();
                providerCs.InitialCatalog = CryptoService2.Decrypt(ConfigurationManager.AppSettings["DatabaseName"]);
                providerCs.UserID = CryptoService2.Decrypt(ConfigurationManager.AppSettings["UserId"]);
                providerCs.Password = CryptoService2.Decrypt(ConfigurationManager.AppSettings["Password"]);
                providerCs.DataSource = ConfigurationManager.AppSettings["ServerName"]; //CryptoService2.Decrypt(ConfigurationSettings.AppSettings["ServerName"]);
                providerCs.MultipleActiveResultSets = true;
                providerCs.TrustServerCertificate = false;
               // providerCs.IntegratedSecurity = true;
                EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder();
                ecsb.Provider = "System.Data.SqlClient";
                ecsb.ProviderConnectionString = providerCs.ToString();
                ecsb.Metadata = string.Format("res://{0}/HrModel.csdl|res://{0}/HrModel.ssdl|res://{0}/HrModel.msl", typeof(HRRPMSEntities).Assembly.FullName);
                return ecsb.ToString();
            }
        }


Fetching a collection using entity framework.
public static List< tbCandidate> GetAllCandidates()
{
List< tbCandidate > candidates = new List< tbCandidate>(); ;

using (var hrEntities = new HRRPMSContext())
{
foreach (var candidate in hrEntities.tbCandidate)
{
candidates.Add(candidate);
}
}

return candidates;

}

Adding data example :
public static void SetData()
{
tbCandidate candidate = new tbCandidate();
candidate.Name = "Arindam Chakraborty";
candidate.Phone = "11545645656";
candidate.Qualification = "B.Sc";
candidate.Street = "New Golden Nest";
Add(candidate);

}

public static void Add(tbCandidate obj)
{
using (var hrEntities = new HRRPMSContext())
{
hrEntities.AddTotbCandidate(obj);
hrEntities.SaveChanges();
}
}

Find a candidate by name from database
public static tbCandidate FindCndidateByName(string name)
{
tbCandidate candidate = null;

using (var hrEntities = new HRRPMSContext())
{
candidate = hrEntities.tbCandidate.FirstOrDefault(c => c.Name == name);
}

return candidate;

}

Update a candidate information

public static void Update(tbCandidate updatedCandidate)
{

using (var hrEntities = new HRRPMSContext())
{
tbCandidate candidate = hrEntities.tbCandidate.FirstOrDefault(c => c.CandidateID == updatedCandidate.CandidateID);
candidate = updatedCandidate;
hrEntities.tbCandidate.Context.ApplyPropertyChanges("tbCandidate", candidate);
hrEntities.tbCandidate.Context.SaveChanges();
}
}

Add Data in many tables with transaction scope
public static void AddMultipleRecord(tbInterview interview, tbRequirement requirement)
{

using (TransactionScope scope = new TransactionScope())
{
using (var hrEntities = new HRRPMSContext())
{

hrEntities.AddTotbInterview(interview);
hrEntities.AddTotbRequirement(requirement);

hrEntities.SaveChanges();
scope.Complete();
}
}
}


How to write join and where clause using lambada expression
using (var entities = new MyEntities())
{
var userProfile = from user in entities.UserProfile
join pro in entities.ProductInfo
on user.UserInfoID equals pro.UserInfoID
where pro.ProductInfoId == ProductId
select user;

profile = userProfile.FirstOrDefault();

}

Saturday, October 30, 2010

UML basic overview

Few important keywords in UML.

Generalization:
A generalization is used when two classes or actor are similar, but have some differences, one class shares its structure and/or behavior with one or more other classes. Its more like inheritance.

Dependency :
When behavior of one class/object depends on behavior of another class/object then dependency relation ship applied.

Association, Aggregation, and Composition:


Realization:

Include:
Extends:

Some good UML tool can be seen on http://www.uml-forum.com/tools.htm

Can a class diagram show the dynamic behavior of a system?
No, Class Diagram is static diagram, cant show the dynamic behavior of the system.

What is class diagram ?
The class diagram is used to refine the use case diagram and define a detailed design of the system. The class diagram classifies the actors defined in the use case diagram into a set of interrelated classes. The relationship or association between the classes can be either an "is-a" or "has-a" relationship. Each class in the class diagram may be capable of providing certain functionality. These functionality provided by the class are termed "methods" of the class. Apart from this, each class may have certain "attributes" that uniquely identify the class.


What is association ends ? or role of association ?
Association ends specify the role of the association end, its multiplicity, visibility, navigability, and constraints

Can deployment diagram be used for forward and reverse engineering?

Content of Enterprise Architecting

What is the are of understing one should have while talking about Enterprise Architecting, Yes, that was always a question in my mind. and after going through many defination onweb i am able to come up with the following bullet points. but yes "The TOGAF 9 Training Session" added some value.

• Architecture Frameworks
• Architecture Development Process
• Modeling specification such as UML 2.0, BPMN etc.
• Component Programming Model such as standard .NET
• Pattern and Reusable Assets
• Business Process Management
• Model Driven Architecture
• Service Oriented Architecture
• Legacy transformation, EAI
• Architecture Realization & Assessment Governance capability


Key elements of TOGAF 9
Boundaryless Information Flow is the key driver of "TOGAF 9", and open group has come up with some defination for "Architecture Development Methodology"

Friday, October 8, 2010

How to implement security in WCF service

There are three type of security in WCF
1. Message level Security
2. Transport level Security
3. TransportWithMessageCredential

Here we see how to implement Message Level securtiy in WCF service :


Setp 1 :
Create a class with name "CustomUserNameValidator" and the class should inherit from "System.IdentityModel.Selectors.UserNamePasswordValidator" in wcf service project.

namespace WcfService1
{
public class CustomUserNameValidator :System.IdentityModel.Selectors.UserNamePasswordValidator
{

public override void Validate(string userName, string password)
{
if ((userName != "arindam") && (password != "acpass"))
throw new FaultException("Invalid credentials");
}
}
}

Setp 2 :
Add the folowing tag in your host webconfig file
================================================
< services >
< service behaviorConfiguration="ETG.Base.Applications.EClinic.Services.DoctorServiceBehavior"
name="ETG.Base.Applications.EClinic.Services.DoctorService" >
< endpoint address="http://localhost:50219/DoctorService.svc" binding="wsHttpBinding" contract="ETG.Base.Applications.EClinic.Services.ServiceDefination.IDoctorService" >
< identity >
< dns value="localhost" / >
< /identity >
< /endpoint >
< endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" / >
< /service >
< / services >
< behaviors >
< serviceBehaviors >
< behavior name="WCFSampleServiceBehaviors" >
< serviceMetadata httpGetEnabled="true" / >
< !-- The tag below allow to get the exception details from client -- >
< serviceDebug includeExceptionDetailInFaults="true"/ >

< !-- The tag below allow service to implement securty -- >
< serviceCredentials >
< userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WcfService1.CustomUserNameValidator,WcfService1"/ >
< /serviceCredentials >
< /behavior >

< /serviceBehaviors >
< /behaviors >

< bindings >
< wsHttpBinding >
< binding name ="WCFSampleServiceBinding" >
< security mode="Message" >
< message clientCredentialType ="UserName" / >
< /security >
< /binding >
< /wsHttpBinding >
< /bindings >

now we are done with service seide implementation of message level security. just run the service, make sure it runs properly.

The next step is to see how we can access the wcf service with right credential. also we see if the credential is wrong then what error message we get ?

Open your existing asp.net project or create a new project, add the service reference, open the web config file, now you should see that service reference has been added in < system.serviceModel > section.

we are just one step away from testing .

Setp 3 :

Now set the credential to service client class this way ..
DoctorServiceClient dClient dClient = new DoctorServiceClient();
dClient.ClientCredentials.UserName.UserName = "arindam";
dClient.ClientCredentials.UserName.Password = "acpass";

dClient.CallMyMethod();
this should work fine, to test the credential just change the username/password, you should get error message thrown by service.

Now we see how to create certificate !

Go to Visual Studio Command Prompt


Go to working directory CD E:\Projects\RND2\ETG.CRM2.MVC

Run the following command

makecert -n "CN=RootCRMWCF" -r -sv RootCRMWCF.pvk RootCRMWCF.cer

One window prompt will appear and ask for password

Set some password like “crmpass123” (as you like)

Now check your working folder, you see one certificate and one pvk file has been created.

 
========
How to create certificate on local machine
http://msdn.microsoft.com/en-us/library/ff648498.aspx


How to configure certificate on IIS 7
http://weblogs.asp.net/scottgu/archive/2007/04/06/tip-trick-enabling-ssl-on-iis7-using-self-signed-certificates.aspx