December 2007 - Posts
Workflow Logging in WWF
By : Kasim Wirama, MCDBA
Many aspects you need to consider when you will deploy your workflow. Faced by diverse possibility of user interaction in real world, you need to consider some aspects. They are workflow logging , workflow scheduling, how to save the last state before the workflow go idled because it is left by user for a long time, how to track steps in workflow. Let’s see each of them below.
Sometimes, some problem arise on your workflow in production environment, in this case you need to know what things cause the problem, so you turn on tracing facility on workflow configuration file with one of these value : All, Critical, Warning, Error, Off, for example :
<configuration>
<system.diagnostics>
<switches>
<add name=”System.Workflow.Runtime” value =”All” />
<add name=”System.Workflow.Activities” value =”Critical” />
<add name=”System.Workflow LogToFile” value = “1”/>
<switches>
</system.diagnostics>
</configuration>
From this sample application configuration above, it instructs workflow to log all activities resulted from workflow runtime object, and only records error raised from activities inside the workflow instance.
When you set value 1 to LogToFile, all logging activities will be written to file, named WorkflowTrace.log, this log will be in same folder with your workflow assembly.
Run your workflow, after you ends your workflow client, you will find new workflow trace on your workflow client assembly’s folder.
SQL Server 2005 Query Hints
By : Kasim Wirama, MCDBA, MVP SQL Server
In general, without hints SQL Server performs best, but in some cases default execution plan is not so appropriate, if you are sure that uses of query hints will have control over query optimizer to produce proper execution plan, uses of hints could be considered. Below I give you some information about hints in from previous version of SQL Server 2005 to SQL Server 2005 version.
If you need to force execution with predictable execution strategies and choose to navigational behavior of query optimizer you can use SET FORCEPLAN ON. This example below gives clue to query optimizer to navigate from customer to orders based on their order.
SET FORCEPLAN ON
Select ordered
From customer as c, orders as o
Where c.customerid = o.orderid and c.lastname=’smith’;
If you don’t want your query block to other executing transaction for higher consistency with lower concurrency such as REPEATABLE READ or SERIALIZABLE isolation level, you can issue NOLOCK with your query like sample below:
SELECT CustomerName FROM Customer WITH (NOLOCK) where CustomerID = ‘ALFKI’;
If you want to force particular index usage on a query you can issue hint WITH (INDEX = <index name>), for example :
SELECT CustomerName FROM Customer WITH (INDEX = IX_CustomerID) where CustomerID = ‘ALFKI’;
Sometimes, you want to force internal join operation (HASH, MERGE, LOOP) like this example below :
select o.customerid,companyname
from orders as o inner MERGE join customers as c
on o.customerid = c.customerid
select o.customerid,companyname
from orders as o inner HASH join customers as c
on o.customerid = c.customerid
select o.customerid,companyname
from orders as o inner LOOP join customers as c
on o.customerid = c.customerid
sometimes, you need to force group operation with hash aggregation, with note your tempdb database follows best practice, compare this execution below :
select city, count(*)
from customers
group by city
OPTION (HASH GROUP)
select city, count(*)
from customers
group by city
first query uses hash match instead of Stream Aggregate operator of second query, with using OPTION (HASH GROUP) hints.
If you need to force order of execution based on order in query, use hints OPTION (FORCE ORDER) as sample shown below :
select o.customerid,companyname, o.employeeid,lastname
from customers as c
inner join orders as o
on c.customerid = o.customerid
inner join employees as e
on o.employeeid = e.employeeid
OPTION (FORCE ORDER)
if you want to limit parallelism to produce only serial execution plan, issue hint OPTION (MAXDOP 1), for example
select customerid, count(*)
from orders
group by customerid
OPTION (MAXDOP 1)
if your application just really need few rows from a bunch of rows, you can instruct query optimizer to generate plan based on these few rows, although you will get entire results, the results still do not affected with hints OPTION (FAST n).
select *
from orders
OPTION (FAST 2)
if you do not reuse query plan issue hints OPTION (RECOMPILE) on your query, for example
select *
from orders
where orderdate between ‘20060101’ and ‘20060128’
OPTION (RECOMPILE)
if you want your query give optimal balance upon nonuniform data distribution, you can issue hints OPTION (OPTIMIZE FOR (<parameter name> <operator> <value>)), for example :
select o.customerid, companyname
from customers as c join orders as o
on c.customerid =o.customerid
where c.city = @city
OPTION (OPTIMIZE FOR (@city = ‘Jakarta’));
Condition and Rule Activities in Workflow
By : Kasim Wirama, MCDBA, MVP SQL Server
On my previous article (implement multiple activities in workflow), on last passage, I talk a bit about Condition property on IfElse and While activities. Not only these 2 activities implement this, but also another activity, they are ConditionedActivityGroup and PolicyActivity. Let’s take a look each of them.
ConditionedActivityGroup (CAG) enable you put multiple activities, if you put container-type activity, you can put activiti(es) inside the activity, for example, drag CAGto IDE of Visual Studio designer. First drag SequenceActivity into upper box of CAG, turn on edit mode by pressing button below upper text box, and drag several code activity group into it. Next you drag While activity into upper text box, put it beside SequenceActivity, and add new code activity group inside the While activity, then put code activity beside While activity in upper text box. You see that CAG could contain both container type activities and non-container type activities.
Moreover notice that each member of activities inside upper text box of CAG, each of them has WhenCondition property. And CAG contains UntilCondition property. Both UntilCondition and WhenCondition property contains options to specify condition declaratively (by putting it into separate readable rule file) or imperatively (by code embedded in WWF assembly). Each of member of activities in upper box is executed until each of them returns to false condition while CAG’s UntilCondition property will determine execution looping until it is evaluated as true for each execution completion of each of activities inside upper text box. If you do not specify WhenCondition in member activities inside the upper textbox, it will be executed once, if you do not specify UntilCondition, all member will be executed until value of WhenCondition is evaluated as false for all of them.
PolicyActivity enables you declare business rule that compose a rule set. A rule set is a series of rule. And each of them contains conditions and actions for true condition and false condition. you can specify them in Rule Set Editor window.
Implement Multiple Activities in Workflow
By : Kasim Wirama, MCDBA, MVP SQL Server
It is seldom to find single activity inside a workflow. More often than not, you will find multiple activities inside a workflow. Generally you can straight away drag and drop multiple activity workflow components into designer. But some container acts as container of component doesn’t directly permit you to do that. This article, I would like to explore possibility composing multiple components inside container component.
First, I discuss about putting multiple workflow component inside While conditional looping component, then how to put make series of single steps that are committed/rollback as one unit of action through TransactionScopeActivity, other component is IfElse activity. Let’s look at them.
While activity only permits one and only one activity inside it, try to create more than one Code Activity inside the While Activity, I am sure that Visual Studio doesn’t allow you to do that, instead, you should put Sequence Activity inside While Activity, then just put some component activities inside the Sequence Activity.
If you would like to implement transaction activity, WWF provides TransactionScopeActivity. This activity component allows you put multiple activities inside it. This transaction activity give you options of transactions through TransactionOptions.IsolationLevel and TransactionOptions.TimeoutDuration. you can specify transaction to Serializable (default), Repeatable read, read committed, read uncommitted, snapshot or chaos. Actually TransactionScope activity implements .NET base classes in System.Transactions namespace.
Similar to TransactionScopeActivity, you will find CompensatableTransactionScopeActivity, this activity implements ICompensatableActivity interface, in designer, this component has hidden container for compensationHandler. To show the handler, right click on the component and choose View Compensation Handler. You can drop activity inside the compensation handler. This compensation word means that you can do some additional activities (as compensation word implies) for exception raised within the transaction scope.
Other type of activity is branching activity, WWF provide IfElse activity. The similarity to While activity is that both have Condition property. You can define Rule Condition or Code Condition for Condition property. If you choose Rule Condition, you define condition declaratively, so WWF will put it to separate file with rule extension, so you can modify the rule file without having to compile WWF assembly.
Happy exploring.
Create Simple Workflow
By : Kasim Wirama, MCDBA, MVP SQL Server
Workflow is series of activities that are linked one another. You can see many samples about workflow. For me, workflow looks like procedures that I should follow from beginning until the end. There is 2 kinds of workflow, sequential workflow and state machine workflow.
Sequential workflow is workflow based on step completion, and tends to move forward to the end of workflow, whereas state machine workflow is workflow based on state triggered to move from one state to another state, it can move backwards or forwards, and there are one or more state that completes the workflow.
If you run Visual Studio 2005, you need to install Windows Workflow Foundation (WWF) extension as add-on and .NET framework 3.0, or it is already bundled in Visual Studio 2008.
I will give you simple example how easy to create workflow. I create this sample in Visual Studio 2008. first create workflow project type, there are several kinds of WWF project, choose Sequential Workflow Console Application, name it SimpleWorkflow, and click OK.
By default, workflow projects include System.Workflow.Activities, System.Workflow.ComponentModel, System.Workflow.Runtime, and System.WorkflowServices. The project has also included Program.cs file and Workflow1.cs, instance of Workflow1.cs class will be called in main method of Program.cs.
I rename Workflow1.cs to TestWorkflow1.cs, double click and you will have workflow designer, drag CodeActivity from WindowsWorkflow v3.0 into designer, double click on the component, visual studio will add event handler of the component, this event of the component is ExecuteCode, it will get triggered when the workflow is invoked from workflow client (main method of Program.cs class), type inside the handler this code below.
Console.WriteLine (“message from workflow”);
Now you need to change a bit workflow invocation in workflow client (main method of Program.cs) with this code below :
static AutoResetEvent waitHandle = new AutoResetEvent(false); static void Main(string[] args) { using(WorkflowRuntime workflowRuntime = new WorkflowRuntime()) { workflowRuntime.WorkflowCompleted +=new EventHandler<WorkflowCompletedEventArgs>(workflowRuntime_WorkflowCompleted); workflowRuntime.WorkflowTerminated += new EventHandler<WorkflowTerminatedEventArgs>(workflowRuntime_WorkflowTerminated); WorkflowInstance instance = workflowRuntime.CreateWorkflow(typeof(simpleWorkflow.testWorkflow)); instance.Start(); waitHandle.WaitOne(); Console.ReadLine(); } } static void workflowRuntime_WorkflowCompleted(object sender, WorkflowCompletedEventArgs e) { Console.WriteLine("workflow completed"); waitHandle.Set(); } static void workflowRuntime_WorkflowTerminated(object sender, WorkflowTerminatedEventArgs e) { Console.WriteLine(e.Exception + " on workflow instance : " + e.WorkflowInstance.InstanceId.ToString()); waitHandle.Set();
}
Let’s go through the code one by one from main method as entry point of execution.
workflowRuntime object is created, it will host my workflow. My workflow is instantiated by WorkflowInstance. WorkflowRuntime object has several event, mainly when workflow is completed without error (i.e.: Workflow completed), and workflow is completed with error (i.e.:Workflow terminated). Then the workflow instance is started, when it is started, another thread is spawn, so thread execution is executed separately from main thread, and give opportunity for another workflow thread to run. Each method, I issue waithandle.Set(), means that I signal to main thread that spawned thread (for the workflow) has finished, and control execution is handed over to main thread to continue the execution of main thread.
I move AutoResetEvent object from main method to member of Program.cs class. The code waitHandle.WaitOne(); in main method means that main method is waiting signal from workflow thread, then continue its execution. I add Console.ReadLine(); so that I can see the message on the screen, otherwise my console window is close immediately after waitHandle.WaitOne(); is invoked by workflow thread.
Run it, and that’s it! You will begin to build workflow with Windows Workflow Foundation (WWF).
How to Read Execution Plan
By : Kasim Wirama, MCDBA, MVP SQL Server
Many of you have ever read execution plan, and some of you get confused how to gather information from existing execution plan. I would like to give some practical guidance how to read execution plan. It is important that you will understand physically how SQL Server implements its algorithm for query. From here you begin to know query processor behaviour.
Execution plan consists of several operators, such as inner loop join , merge join, hash match, and many more. Each of the operators joins together each others to form execution plan. It is convenient to read graphical execution plan, so turn on toolbar relating to produce graphical execution plan. Choose your query and you will have third tab that produces graphical execution plan.
Let’s look into it. Some guidance is given here how to read this :
- read it from right to left, as data flow comes from right to left side.
- if you see nested loop, the upper side is the outer query, the lower side is inner query, inner query is executed once for each outer query.
- execution cost of inner side for nested loop is per execution of outer side.
- if you see hash join, it means that hash table is built for upper (outer) query, then for each rows in lower (inner) query, query processor will look into the hash table to find match value.
There is cost (in percentage) for each of operators, the most expensive is the biggest cost. From this you need to analyse why the cost is expensive.
Examining Query Plan from Plan Cache
(SQL Server 2005)
By : Kasim Wirama, MCDBA, MVP SQL Server
I would like to show you about examining plan cache and how you get insight after examining this plan. In SQL Server versions before SQL Server 2005, I could only see plan reuse by querying to syscacheobjects system table in master database. In SQL Server 2005, I can get information not only about plan reuse but also execution plan in plan cache, something that is interesting to get to know further. Moreover, with this execution plan get from plan cache, you will have less likely to execute the query to get the execution plan.
SQL Server 2005 save execution plan for queries, and will parameterized the “safe” query so it could be reuse for same query request but different only in parameter value. What is “safe” query? Safe query is a query that has only 1 definite execution plan for any value of query column, so I can say safe query is a consistent query. You will identify safe query when its execution plan is parameterized in default environment setting (simple parameterized).
To get query plan from plan cache in SQL Server 2005, just query to metadata dynamic management view below :
select usecounts,cacheobjtype,objtype,query.text,executionplan.query_plan from sys.dm_exec_cached_plansouter apply sys.dm_exec_sql_text(plan_handle) as queryouter apply sys.dm_exec_query_plan(plan_handle) as executionplanwhere text not like '%sys%'and cacheobjtype ='compiled plan'
first clean up procedure cache with Dbcc freeproccache or dbcc flushprocindb(database id), then query to AdventureWorks with query below :
select * from sales.salesorderheader where salesorderid = 43659
query to the DMV will have these 2 entries :
select * from sales.salesorderheader where salesorderid = 43659
(@1 int)SELECT * FROM [sales].[salesorderheader] WHERE [salesorderid]=@1
First one is Adhoc plan, second one is Prepared plan, if you issue other value of salesorderid, this Prepared plan will be reused with usecounts column value changes from 1 to 2. further more try to click one of Adhoc link in query_plan column.
You will have execution plan in XML format, compared to execution plan in Prepared plan, you will more complete execution plan with more elements, I can say first execution plan is in truncated format, what is the difference between truncated format, and complete format? I notice that truncated format doesn’t have QueryPlan as root element compared to execution plan of complete format.
Another sample query is below :
select * from humanresources.employee where title like 'Production Technician%'
Compare its execution plan, this time you will get complete execution plan instead of truncated one, I conclude that SQL Server consider the query is not safe query, so it will generate plan for that value, if you issue another value, SQL Server will generate other execution plan associated to that value.
If you explore around this SQL Server engine behaviour, you will get insight how it behaves for different situation.
Detecting Locking and Transaction Conflict with Begin Try Handler in SQL Server 2005
By : Kasim Wirama, MCDBA, MVP SQL Server
SQL Server 2005 introduces new error handling construct, it is more robust compare to previous version of SQL Server. The error handling construct is BEGIN TRY…END TRY/BEGIN CATCH…END CATCH; Regarding to error caused by locking, deadlock or update conflict that happen in snapshot transaction isolation level, it is very relevant to implement.
Error number for locking is 1222, for deadlock is 1205 and for update conflict is 3960. With new error handling construct, it is now possible to retry transaction inside TSQL code without round trip to application code outside database, so it is more efficient.
I will show you sample of database transaction retries by implementing new error handling construct below :
set lock_timeout 30000;
declare @retry int, @cnt int, @maxretries int, @j int, @errmsg varchar(200);
select @retry = 1, @cnt =0, @maxretries = 3;
while @retry = 1 and @cnt <= @maxretries
begin
set @retry = 0;
begin try
begin tran;
do some activities on first table
do some activities on second table
commit tran;
end try
begin catch
if error_number() = 1222
begin
if xact_state() <> 0 rollback tran;
set @errmsg = 'error 1222-locking';
raiserror(@errmsg, 16,1);
end
else if error_number() in (1205, 3906)
begin
if xact_state() <> 0 rollback tran;
select @retry = @retry + 1;
if @retry <= @maxretries
waitfor delay '00:00:05';
end
else
begin
if xact_state() <> 0 rollback tran;
set @errmsg = left(error_message(),200);
raiserror( @errmsg , 16,1);
end
end catch;
end
by default lock timeout is indefinite, it’s good practice to specify lock timeout to particular value, for example set lock timeout to 30 second, so transaction will not wait indefinitely when waiting for some resource that is held by other connection longer than 30 second.
Other thing you should be aware, that before you rollback transaction, it’s better you check condition XACT_STATE function, if it is -1 means that transaction is opened, and the only option is to rollback, if it is 1 means that transaction is opened, the you have option to commit or rollback, if it is 0 then there is no opened transaction.
Running Your Workflow in MOSS 2007
By : Kasim Wirama, MCDBA, MVP SQL Server
After I share how to create workflow from existing Approval workflow template (see my article : http://geeks.netindonesia.net/blogs/kasim.wirama/archive/2007/12/26/create-workflow-in-microsoft-office-2007-sharepoint-server.aspx), now I show you how to get your workflow up and running.
Actually workflow in MOSS 2007 integrated with Microsoft Office particularly Office 2007. People involved in workflow will receive email informing that new task is assigned to him/her and they can approve, reject or request change on the document inside the workflow. Or workflow user can check to MOSS 2007 web site, and the user will get link that refer to task assigned to him. I will show you how workflow works by checking MOSS 2007 website.
I have scenario here, help desk support made word document, and assigns the document to workflow that you have created in my article above. 2 people will receive assignment serially, first is director, second is directory secretary. One director has approved, the next task will flow to director secretary. Director secretary request changes on the document, so workflow flows back the document to workflow creator (help desk support). Help desk support get notification through MOSS 2007 site, correct the document and workflow will automatically flows back to director secretary for approval, after director secretary approves it, the workflow completes and notifies its completed status on MOSS 2007 screen.
That’s the scenario, now you create windows user for director and secretary director. From IE, launch MOSS’ site (for example in my local computer browse to http://mylocalcomputer:39473/sites/myworkflow) . click Site Actions tab > Site Settings. Add those users through link People and groups. After adding, click Advanced permissions, to assign those users into group called my workflow site collection Members by clicking New > Add Users. Before doing that, tick my workflow site collection Members. Currently I login as System Account (see word on top right conner – Welcome System Account).
In home of the site, click my document library link (if you do not find the link, it means you need to create custom document library see my article http://geeks.netindonesia.net/blogs/kasim.wirama/archive/2007/12/26/create-workflow-in-microsoft-office-2007-sharepoint-server.aspx) upload word document by clicking Upload > Upload Document. Click the document choose Worflow. And select your workflow, then it will associate to your document by clicking Start button.New new link created, see the rightmost column, the column name is workflow name, with status In Progress.
Change login from system account to Director account, by clicking Welcome system account > Sign in as different login. Director will get new entry in Upcoming Tasks. Click on it, and Director reviews the document and approve by clicking approve button with optional comments. Now Director has no task assigned to him, because workflow will update status Completed for Director, and Not Started to Director Secretary when you click details of status. So next task is to get approval from Director Secretary.
Change login to Directory Secretary, similar to Directory, Director Secretary review the document, and request changes by clicking Request a change link, and click send button. Now workflow flows back to task creator (help desk support).
Change login to help desk support, now he will get new entry for Upcoming Tasks section. Do changes as requested on document below section Relevant Documents. And click response button on tasks so workflow will direct the document to Secretary Director.
Secretary Director will review the document, and Approve, when it is approved, workflow completes, workflow could see it right away.
Create Workflow in Microsoft Office 2007 SharePoint Server
By : Kasim Wirama, MCDBA, MVP SQL Server
Workflow has been implemented by most organizations for a long time, and before .NET era, workflow was a custom made application with all custom workflow possibility scenarios and their complex exception handlings. Workflow features are presented by .NET framework 3.0 with Windows Workflow Foundation (WWF). Another technology that deals with workflow is MOSS 2007 (Microsoft Office 2007 SharePoint Server). MOSS is built on top of Windows SharePoint Service 3.0, one of service available in Windows 2003 Server.
With MOSS 2007, workflow creation is much simpler and easier. In SharePoint 3.0, there is one workflow template, i.e: Three state worklow. MOSS 2007 add more workflow templates such as Approval template (regarding to document approval), Collect Feedback template, Collect Signature template, and Disposition Approval template. MOSS 2007 allows you to create custom workflow template with WWF and Visual Studio 2005 installed with minimal .NET framework is 3.0.
This article will show you how to configure MOSS 2007 to create first workflow using Approval workflow template.
First, you need to install Windows SharePoint 3.0 as one of windows components in Windows Server 2003, then followed by installation of MOSS 2007. From Microsoft Office Server program group (opened from Start menu), choose SharePoint 3.0 Central Administration.
In Application Management tab, you enable search service by clicking Manage Search Service in Search section. You will be presented search items with their status (started or not started), you select search services that are not yet started, to make it started.
Back to Application Management tab, create new web application by selecting Create or extend Web application in SharePoint Web Application Management. Choose Create a new Web application. Apply all settings in Create New Web Application by clicking OK. Now you have a new web application with particular port (for example : http://yourcomputername:39473), you can create multiple sites below this new web application.
In Home tab, select Shared Services Administration link to create new Shared Service Provider.
Back to Application Management tab, choose Create site collection in SharePoint Site Management section. In Template Selection, I choose Enterprise tab, and select Document Center option in a list box under the tab. I named my site is myworkflow. Now in Application Management tab, I select Site Collection List under SharePoint Site Management, and choose /sites/myworkflow link, copy the URL (in my computer, it is http://delta:39473/sites/myworkflow), and paste onto new IE windows.
Workflow creation
Now you are ready to create new workflow. This article gives sample how to create workflow from existing template provided by MOSS 2007, in this case (document) Approval workflow template. From Site Action tab menu (upper right side), choose Create link, and click Document Library link in Library section. Select yes options and provide email address for incoming e-mail. I named new document library is my document library, you can name it whatever you like.
in my document library entered from myworkflow site , select Settings > Document Library Settings, and choose Workflow Settings in Permissions and Management section. Click Add a workflow link. Now you can specify items for your new document approval workflow. Here is my workflow sample, choose Approval in Workflow section, give name (my first workflow) in Name section, choose Tasks in Task List and Workflow History in History List section, tick Allow this workflow to be manually started….. in Start Options then click Next.
In next screen, at Workflow Tasks section, select One participant at a time (serial), tick Request a change before completing the task. Define Approvers in Default Workflow Start Values and specify messages that will be included in your workflow request (optional), and due date is set to 2 days. In Complete the Workflow section, uncheck all, and in Post-completion Workflow Activities section, tick Update the approval status (use this workflow to control content approval).
These are my configured workflow, you need to understand option you choose, and try to experiment with different options than mine.
Last mandatory step is to enable document library versioning setting, by clicking Settings > Document Library Settings > Versioning Settings, and select Yes in Content Approval section.
Now your workflow is ready to be run.
Wait for my next sharing about workflow in MOSS 2007.
Authorization in WCF
By : Kasim Wirama, MCDBA, MVP SQL Server
Authorization is action to verify authenticated user whether to allow on requested operation. It is no exception in WCF. In WCF service, user gets authenticated, once authenticated, WCF service will do authorization what operations user can do based on roles the user belongs to. Authorization could be in windows authentication through Windows Token Role provider, SQL authentication or other store provider such as user roles provided through XML file.
This article I share my exploration about authorization in WCF through https with Windows Token Role provider.
- Create user and assign user to role in windows local user/group or Active directory
- Enable Windows role token provider in WCF service’s application configuration file.
Create new service behaviour (if not exists) and add serviceAuthorization element, in the element, set PrincipalPermissionMode to UseWindowsGroup
And this behaviour to service level in Service directory.
- apply appropriate roles to method(s) in class that implements service contract with attribute : PrincipalPermission with constructor input parameter to SecurityAction.Demand and role name, for example :
[PrincipalPermission(SecurityAction.Demand, Role = “role name”)].
Void methodName() {……………}
This way of assign role to an operation through attribute is called declarative role assignment. Another way is imperative role assignment within role checking inside implementation of a method, for example :
Void methodName()
{
WindowsPrincipal authenticatedUser = new WindowsPrincipal
(
(WindowsIdentity)Thread.CurrentPrincipal.Identity
);
If (authenticatedUser.IsInRole(“role name”))
{
//allowed operation is do here
}
}
Compile, and run WCF client, this time WCF client not only get authenticated, but also get authorized to allow call operations on WCF service.
WCF service accesses outside resource such as access to file or access to database. By default WCF service give its credential (not wcf client’s credential) to access a resource. If you want to access a resource with wcf client’s credential you need to enable impersonation on WCF service. Follow below steps to enable it
- you can impersonate individually some operation contract in implementation class of service contract interface by adding attribute OperationBehaviour with Impersonation property like this one below:
[OperationBehaviour (Impersonation = ImpersonationOption.Required)]
Public void aMethod() {……}
Or
You can enable impersonation for all member of implementation class by edition application configuration, add serviceAuthorization item under item of ServiceBehaviour folder. Set ImpersonateCallerForAllOperation property to true and PrincipalPermissionMode property to UseWindowsGroups. And add the service behaviour on BehaviourConfiguration of service item under Services folder.
- In wcf client, edit application configuration, add new item under Advanced/Endpoint Behaviors folder, add clientCredential item, and set AllowedImpersonationLevel to Impersonation, allowNtlm and SupportInteractive properties to true. Don’t forget to attach this configuration to BehaviorConfiguration property of item under Endpoints folder at Clients folder.
That’s it, compile WCF client and WCF service, run your WCF service, this time your WCF service has authentication, authorization and impersonation working on it to provide security in windows domain environment.
Authentication with HTTPS in WCF
By : Kasim Wirama, MCDBA, MVP SQL Server
Message encryption should be combined with authentication and authorization wcf client by wcf service. Usually message level security provides authentication, so wcf service can authenticate user by getting result from Thread.CurrentPrincipal, let say you want to get username of wcf client, you can get information from Thread.CurrentPrincipal.Identity.Name.
This article will give idea how to configure authentication with https with basicHttpBinding. Https works over transport mode. When you configure configuration for basic http binding, on security tab, you set TransportClientCredentialType property from None to one of this options, Windows, Basic, Digest, Ntlm, or Certificate. For intranet environment, Windows credential type is preferred to, and for internet environment, Certificate credential type is suitable and most secure one.
If you configure TransportClientCredentialType to Windows, wcf client will provide its identity to wcf service for authentication purpose, or alternatively wcf client will provide different identity to wcf service by setting up windows username, password, and domain through .NET windows identity on proxy object below :
<object proxy>.ClientCredentials.Windows.ClientCredentials.UserName
<object proxy>.ClientCredentials.Windows.ClientCredentials.Password
<object proxy>.ClientCredentials.Windows.ClientCredentials.Domain
If you configure TransportClientCredentialType to Basic authentication, wcf client explicitly provide user name and password through command line below :
<object proxy>.ClientCredentials.UserName.UserName
<object proxy>.ClientCredentials.UserName.Password.
Implementing WCF Message Level Security over HTTP
By : Kasim Wirama, MCDBA, MVP SQL Server
You can secure your message confidentiality by encryption either in transport level security or message level security. For transport level security, you can set up SSL over Http. And for message level security, you have more options to implement encryption algorithm through any protocols available such as http or tcp.
This article I would like share my exploration configure message level security over HTTP. You can set up new HTTP protocol binding configuration with Service Configuration Editor program, you try create 2 protocol binding configuration ws2007HttpBinding and basicHttpBinding. Notice MessageClientCredentialType property as Security tab. On basicHttpBinding, there are only 2 options available, i.e UserName and Certificate. Certificate in this case will be used to prove client identity to WCF service, so WCF service could make sure that the real client gets connected to. In windows domain environment, windows security implementation using basicHttpBinding is not possible. If you want to use windows integrated security, I suggest you use ws2007HttpBinding or wsHttpBinding, besides that ws2007HttpBinding and wsHttpBinding provides more options besides windows authentication, they are UserName, Certificate, and IssuedToken. As far as I know, encryption with wsHttpBinding is based on WS-Security specification where WS-Security spec is one of WS*-specification standard pillars.
So this article, I give you some basic idea how to implement message level security using ws2007HttpBinding. Similar configuration of ws2007HttpBinding will also apply to wsHttpBinding as well.