HOSTING WCF IN IIS 6.0 WITH WINDOWS AUTHENTICATION

The scenario is WCF service needs to be hosted in IIS with Windows authentication and anonymous login should be disabled. The challenge will be IIS has it authentication mechanism at the same time WCF has its authentication mechanism. The WCF configuration should be done properly to make sure Windows authentication works for a WCF service.

The problem will be complicated when you want access SQL server using windows authentication using WCF service. The document highlights the setting required to configure WCF service Windows authentication which access SQL server with windows authentication.

Problem Statement


Configuring Windows Authentication and disabling anonymous in IIS will not help to know WCF about Windows Authentication. If you disable anonymous authentication you will get the following error when try to access SVC file.

"Security settings for this service require ‘Anonymous’ Authentication but it is not enabled for the IIS application that hosts this service."

Solution

The issue here is WCF configuration and IIS configuration are not in synch. These two sources must be in agreement about whether anonymous access is expected. To configure your web site to use windows authentication update your Web.Config with Windows authentication.

Web Configuration

In Web.Config make sure you set Authentication mode to Windows.

<system.web>

<compilation
targetFramework="4.0"
debug="true"/>

<authentication
mode="Windows"/>

<customErrors
mode="Off"/>

</system.web>

WCF Service Configuration

Binding Configuration

IIS is already using Windows authentication in this case, so let’s look at what needs to happen to the service configuration file. You need to set the security mode to TransportCredentialOnly in service configuration level.

<bindings>

<basicHttpBinding>

<binding
name="winAuthBasicHttpBinding">

<security
mode="TransportCredentialOnly">

<transport
clientCredentialType="Ntlm"/>

</security>

</binding>

</basicHttpBinding>

</bindings>

NTLM / Windows

Transport clientCredentialType can be NTLM / Windows. If you are using Windows Server 2003 make sure you configure your IIS to use NTLM authentication and configure for NTLM otherwise you can use Windows authentication as well.

Make sure the IIS is configured to NTLM by running following script in IIS Box.

Cmd> cscript //nologo c:\Inetpub\AdminScripts\adsutil.vbs GET /W3SVC/1/NTAuthenticationProviders


You must get the following output. If not you can change the above command to SET instead of GET to set NTLM authentication.


Note that TransportCredentialOnly is not supported for every binding (in this case we’re using BasicHttp). For WSHttp, the only choice is going to be to use HTTPS. To switch off anonymous access with HTTPS, you need to set the security mode to Transport.

serviceHostingEnvironment

By default the when you add a service in Web Project it adds aspNetCompatibilityEnabled true. And it adds the attribute the service declaration as well. Make sure you disable this feature. This settings highlighted in this document are based on the assumption that service hosting environment is not set to aspNetCompatibilityEnabled and no aspcompatibility attribute added to the service declaration.

WCF Service Configuration sample

<system.serviceModel>

<serviceHostingEnvironment
multipleSiteBindingsEnabled="true"/>

<bindings>

<basicHttpBinding>

<binding
name="winAuthBasicHttpBinding">

<security
mode="TransportCredentialOnly">

<transport
clientCredentialType="Ntlm"/>

</security>

</binding>

</basicHttpBinding>

</bindings>

 

<behaviors>

<serviceBehaviors>

<behavior
name="" >

<serviceMetadata
httpGetEnabled="true" />

<serviceDebug
includeExceptionDetailInFaults="false" />

</behavior>

</serviceBehaviors>

</behaviors>

 

<services>

<service
name="YourNamespace.YourServiceName">

<endpoint
address=""


binding="basicHttpBinding"


contract="YourNamespace.YourContractName"


bindingConfiguration="winAuthBasicHttpBinding"

/>

</service>

</services>

 

</system.serviceModel>

 

Client Configuration

If you are using Silverlight you need make sure ServiceReferences.ClientConfig is updated to use TransportCredentialOnly.

<configuration>

<system.serviceModel>

<bindings>

<basicHttpBinding>

<binding
name="basicHTTP"


maxBufferSize="2147483647"


maxReceivedMessageSize="2147483647">

<security
mode="TransportCredentialOnly" />

</binding>

</basicHttpBinding>

</bindings>

 

<client>

<endpoint
address="http://Server:90/ServiceName.svc"


binding="basicHttpBinding"


contract="YourNamespace.YourContractName"


bindingConfiguration="basicHTTP"


name="BasicHttpBinding_CHEFService" />

</client>

 

</system.serviceModel>

</configuration>

IIS Settings

Web Site Settings

AppPool Settings

Make sure the AppPool account which you use here has access to SQL Server. Also make sure the account is added to the IIS_WPG

Reference

MSDN Discussion

Double Hop issue

Deep dive on double hop issue

ASP.Net Basics

Whenever the Web application deployed in to IIS, there could be some IIS specific issues which are not observed in Visual Studio.  The following is the most frequent command to reset, reinstall IIS, ASP.Net.

  • aspnet_regiis –i
  • Webservice Extensions – ASP.Net Allow
  • iisreset /start
  • cscript adsutil.vbs set w3svc/NTAuthenticationProviders "NTLM"

Silverlight using WCF – Windows Authentication

Last two days I was fighting with IIS and a Silverlight Web application to make Windows Authentication working for Silverlight application which uses WCF service to get database data.

It was not as simple as I thought when I started it. There is few good articles around it on web. I don’t want to repeat the same here. Refer

  1. WCF Authentication & IIS an Intro: http://msdn.microsoft.com/en-us/library/bb332338.aspx
  2. Direct approach: http://rouslan.com/2009/03/20-steps-to-get-together-windows-authentication-silverlight-and-wcf-service
    Not helped in my case L
  3. Forum Discussion: http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/bf138527-5528-4c9f-82db-861c19040250
  4. Technical Read: http://blogs.msdn.com/b/wenlong/archive/2006/12/01/impersonation-with-double-identities.aspx
  5. CodeProject discussion
  6. Deligation MSDN Article
  7. Pattern & Practice guide

SQL Server Pivot

I was answering a Stack Over flow question regarding Pivot & Unpivot and ended up creating the following sample

CREATE TABLE MyData
(
    ItemDate DATETIME,
    ItemName VARCHAR(200),
    ItemQty  INT
)
GO

DECLARE @I INT
SET @i = 1
WHILE @i < 1000
BEGIN
    INSERT INTO MyData VALUES(GETDATE()-@I, ‘NAME ‘ + CONVERT(VARCHAR(5),@I % 5), RAND()*100)
    SET @I = @I + 1
END
GO

SELECT ItemName, [1] AS ‘WEEK-1’, [2] AS ‘WEEK-2’, [3] AS ‘WEEK-3’, [4] AS ‘WEEK-4’
FROM (SELECT ItemName, DATEPART(wk, ItemDate) WeekNum, ItemQty
        FROM MyData) AS SourceTable
PIVOT
(
    SUM(ItemQty)
    FOR WeekNum IN ([1], [2], [3], [4])
) AS PivotTable;

C# Generics

C# generics are similar to template but the deference are

  1. C++ generates code by replacing the actual type with generic for every type usage in generic.  But C# has native IL support.
  2. When native code generated from IL there are two types.
    1. Value Type: It replaces the generic type with value type and gives the reference.  If such type is already used it just returns the generated version.
    2. Reference Type: It replace the generic type with object and return the reference.  The heap are allocated based on the type used.

Default

When you start using generic you may need to return default value of the type.  You can use return default(T) to do the same.

Constrains

  1. Derivation Constrain: You can specify the types used in generic should be derived from certain Interface or class using where.  For example
    1. class LinkedList<K,T> where K : IComparable
    2. public class LinkedList<K,T> where K : IComparable<K>,IConvertible
    3. public class LinkedList<K,T> where K : IComparable<K> where T : ICloneable
    4. public class LinkedList<K,T> where K : MyBaseClass
    5. public class MyClass<T,U> where T : U
  2. Constructor Constrain: You can force the generic type to expose public constructor.  For example
    1. class Node<K,T> where T : new()
    2. public class LinkedList<K,T> where K : IComparable<K>,new()
  3. Reference or Value type Constrain: You can force the generic type to Reference or Value type.  for example
    1. public class MyClass<T> where T : struct
    2. public class MyClass<T> where T : class

Other Generic usage

  • Generic method – public static T SomeMethod<X>(X x)
  • Generic Delegate – public delegate void GenericDelegate(T t);
  • Generic in Reflection
  • Generic can be used in Attributes

Reference

ForEachTable

There are times we need to execute a statement for all tables in SQL Server DB.  In such cases instead of using sysobjects to generate query we can use a single function call to do the same.

EXEC sp_MSforeachtable "SELECT count(*) from ?"

Refer

Visual Studio Tips & Tricks

Saraford has got lot of tips and tricks for Visual Studio.  I have listed which I liked.

You can also refer Channel 9 Video

Tip #

Tip

Short Cut

Detail

1

Incremental Search

Ctrl + I

 

2

Search Current Selected Item

Ctrl + F3

 

3

Do the last search

F3

 

4

Find In Files & Beyond

 

In Find dialog you can specify file out of solution as well

5

Search Result Hack – Reg edit

 

You can hack Registry to get rid of Path in Search Result

6

No blank line copy

 

Configure in option to avoid blank line copy

7

Cycle clibboard

Ctrl + Shift + V

 

8

Box column selection

Shift + Alt + Selection

 

9

Multiline Edit

Select using Shift + Alt, then start typeing

 

10

Get current document file path

Right click on the Tab Item of Editor

 

11

Open current document path in Explorer

Right click on the Tab Item of Editor

 

12

Open Smart Tag

Ctrl + .

 

13

Move selected code to Tool Box

Ctrl + Alt + X

 

14

Code Snippet

Tab

 

15

Throw temp project

Tools-Options-Proj & Sol – Save new Proj

 

16

Find shortcut

Ctrl + /

 

17

Hide start up

Use Options, Settings

 

18

Open new tab to the right / left of current doc

Tools-Options-Env-Doc, ins files right

 

19

Trace Point log

 

In addition to break point, you can add Trace Point

20

Find Source Dialog

Solu Prop Dialog

 

21

Enable Exception Assistance

Tools – Options – Debugging – General, uncheck Enable the Exception Assistant

 

22

XML Visualization

 

 

23

Auto Highlighting Symbols

Ctrl + Shift + ArrowKeys

 

24

Intellicense substring search

 

Now you can any char, it is not strict to Start with.

25

Intellicense pascal notation typing

 

Also you can type CAPS to specify camel notation to quickly get item

26

Navigate To

Ctrl + ,

 

27

Call Hierarchy

Ctrl + K, T

 

28

Multi Monitor Support

 

You can move a window to diff screen

29

Zoom using mouse wheet

Ctrl + Mouse Wheel

 

30

Move between files

Ctrl + Alt + Arrow Key

 

 

 

 

 

Avoiding WPF / SL Design Time Code Execution

If you have any code in constructor in class that you are trying to use in XAML.  It may cause issue as the code will try to execute at design time itself.  To mark a code that you don’t want to execute at design time.   You can use IsInDesignMode property.

if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(System.Windows.Application.Current.RootVisual))

if (IsInDesignMode)

Cross Domain Access

If you are start working on SilverLight & WCF project the first you issue you end up is Cross Domain Access Error.

I fundamental difference between Silverlight and ASP.NET is Silverlight runs on the client, and ASP.NET runs on the server.  long with this difference is the ability to access data.  ASP.NET applications can use the HttpWebRequest or call a web service not located on the same server.  Since Silverlight runs on the client, it is a potential security risk to access data from a server where the XAP did not originate. 

There is two technique to solve this.

1. So, the introduction (it’s a standard practice for Flash) of the client access policy.  Briefly, create a file named clientaccesspolicy.xml with the xml content below, and your service/data is ready to be consumed by Silverlight.

<?xml version="1.0" encoding="utf-8"?>
<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from http-request-headers="*">
        <domain uri="*"/>
      </allow-from>
      <grant-to>
        <resource path="/" include-subpaths="true"/>
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>
2. You can have Cross Domain Policy file.
You can download the files from here
  1. Cross Domain
  2. Client Access Policy

Refer: MSDN

How to use Vulcan

Note: Vulcan is a framework to dynamically create SSIS packages.

Hello World!

image

The above config creates package with following folder structure

•Folder Structure
••Stage Name
•••Package Name
••••Package Name.dtsx
••••Package Name.dtproj
••PackageConfigurations
•••Package Name.dtsconfig

You can have multiple Package Definition in one XML file

image

Connection details goes Vulcan level and it creates a separate config folder to hold the configurations. 

image

You can define multiple Tasks in a package.

image

You can configure SQL Tasks as below.  There are two types of Queries in Vulcan.  It can be a STANDARD or EXPRESSION.  For Standard the Query Body is placed in .SQL file by Vulcan and it configures File based SQL Task while creating SSIS package.

image

You can have expressions in a Query.  They are resolved while creating the SSIS package.  Remember while the SSIS package will not have these expression, they are static in SSIS. 

image

You can have Variables to Send / Get  data to a SQL task.  For that you have to define a variable at package level.

image

The variable can be used in SQL task or other Tasks as a input or output values

image

image

You can download more config samples