Ahmadreza's Notes

On .NET Framework and Software Architecture

Value type field members are in heap

leave a comment »

I think developers are a bit confused about the concept of ValueTypes and Reference Type. Often I hear that all primitive data types and value types are in stack. First of all it is thread’s stack and it is not a single stack for application. Secondly, when we say value types are in stack it doesn’t include field members of the class. Only method parameters and local variable which are value type will be in the thread’s stat. Field members, even if they are value type, will be in heap. Consider following example:


using System;

namespace ClassLibrary
{
    public class Foo
    {
	public int number = 0;
        public int Bar(int x, int y)
        {
         	int sum = x + y + number
	 	return sum;
        }
    }
}

In this example, only x, y, sum and return value are in thread’s stack and number variable will be held in heap as part of object instance and is accessible using this keyword (which compiler let you omit that).
In other word when we say object instance is created in the heap, what does really stored there? Field members are object state that needs to be stored in object instance.

Written by Ahmadreza Atighechi

January 31, 2014 at 12:15 am

Posted in Blog

Tagged with , , ,

IL superset of all .net languages

leave a comment »

In .net world you can choose your language and write your application with best language which matches your requirements. Different languages has different paradigm. For example C# started with static/strongly type paragoge  but over years it has been evolved and now it does support functional programming as well as dynamic. There are many other languages like F#, Visual Basic and fortran.

It is compiler responsibility to generate assembly with proper intermediate language so that CLR (Common Language Runtime) would be able to generate native code (using JIT) and run at run time. Each compilers support subset if intermediate language and provide its flavour using syntactic sugars in the language.

.Net Languages

CLR allows language integration as long as written code comply with Common Language Specification. It means because of differences between languages, if you want to use types generated by other languages, you need to use certain feature of language that are guaranteed to be available in other languages. CLS is the lowest common denominator of language features provided by Microsoft.

However, today I don’t want to highlight CLS, instead I want to mentions that Intermediate Language in some cases has more features which languages like C# didn’t bother to implement.

For example we all know about access modifiers in C#. There is public, private, internal and protected

Access Modifiers Description
public public access is the most permissive access level. There is no restrictions on accessing public members
private private access is the least permissive access level, private members are accessible only within the body of the class or the struct in which they are declared
internal internal types or members are accessible only within files in the same assembly
protected A protected member is accessible within its class and by derived class instances
protected internal visible to derived classes and those of the same assembly

 

OK, now lets have a look on access modifiers in IL

IL Access Modifier Description C# equivalent
Private The member is accessible only by other members in the same class or struct private
Family The member is accessible by derived types. protected
famandassem The member is accessible by derived types, but only if the derived type is defined in the same assembly. N/A
Assembly The member is accessible by any code in the same assembly internal
famorassem The member is accessible by derived types in any assembly and also by any types within same assembly protected internal
Public The member is accessible by any code in any assembly public

 

As you might have noticed there is no C# equivalent for family or assembly although IL has this keyword. there is not such a thing in VB.Net as well. Now lets have a closer look on a simple sample and generated IL code.

Assume we have two simple project in a solution. A Console Application and a Class Library which console application referenced that. In the Class Library we have a simple class called Super and in console application, beside Program class we have a class derived from Super class called Sub. Lets have a look on their codes.

 

Super class source code


using System;

namespace ClassLibrary
{
    public class Super
    {
        protected internal void Foo()
        {
            Console.WriteLine("Foo");
        }

        internal void Method()
        {
            
        }
    }
}

Other class in ClassLibrary Project

 

namespace ClassLibrary
{
    public class Other
    {
        public void Test()
        {
            var super = new Super();
            super.Foo();
        }
        
    }
}

 

Sub class in ConsoleApplication

 

using System;
using ClassLibrary;

namespace ConsoleApplication
{
    public class Sub : Super
    {
        public void Bar()
        {
            Foo();
            Console.WriteLine("Bar");
        }
    }
}

 

Program.cs class in ConsoleApplication

using System;

namespace ConsoleApplication
{
    class Program
    {
        static void Main()
        {
            var sub = new Sub();
            sub.Bar();
            Console.ReadLine();
            
        }
    }
}

Sub class simply calls Foo method which is defined as “protected internal” which in C# means family or assembly in IL. If you build and run application you’ll see that Sub class successfully accesses because although it is not in the same assembly but But sub is actually derived from Super class. the output will be

Foo 
Bar

Cool, now let mess around with the IL and see that would happen if we change that.

If you want to dump the IL of an assembly you can simply open a Visual Studio Command and then go to the folder your assembly exist and run ildasm with following parameters


ildasm ConsoleApplication.exe /out:ConsoleApplication.il

ildasm ClassLibrary.dll /out:ClassLibrary.il

Now, you can open ClassLibrary.il and have a look into generated code. Actually it is a bit long so I just copied part that I’m interested in which is Foo method

  .method famandassem hidebysig instance void 
          Foo() cil managed
  {
    // Code size       13 (0xd)
    .maxstack  8
    IL_0000:  nop
    IL_0001:  ldstr      "Foo"
    IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
    IL_000b:  nop
    IL_000c:  ret
  } // end of method Super::Foo

You see that protected internal compiled to famorassem. What would happen if we change this to famandassem and assemble this IL again? Answer is CLR will prevent calling this method and will raise MethodAccessException exception when we call this from console application. But let put this into action and actually test this. So, change the famorassem to famandassem and save the file and use ilasm.exe from Visual Studio Command to assemble this code again. Before assembling this you can delete current ClassLibrary.Dll. To assemble use following command parameters:

 

ilasm ClassLibrary.il /out:ClassLibrary.dll /dll

If you get Operation completed successfully at the end new class library is generated. If you run ConsoleApplication.exe you’ll get following exception because of violating the access level defined in the IL

 

Unhandled Exception: System.MethodAccessException: Attempt by method 'ConsoleApp
lication.Sub.Bar()' to access method 'ClassLibrary.Super.Foo()' failed.
   at ConsoleApplication.Sub.Bar() in f:\Users\ara\Documents\Visual Studio 2013\
Projects\ConsoleApplication3\ConsoleApplication3\Sub.cs:line 10
   at ConsoleApplication.Program.Main() in f:\Users\ara\Documents\Visual Studio
2013\Projects\ConsoleApplication3\ConsoleApplication3\Program.cs:line 10

 

famandassem means that only derived class within same assembly will have access to that member. Just for the sake of testing lets Super to the ConsoleApplication and see if it works.

Open ClassLIbrary.il in a text editor. Copy following IL code which is Super class il code

// =============== CLASS MEMBERS DECLARATION ===================

.class public auto ansi beforefieldinit ClassLibrary.Other
       extends [mscorlib]System.Object
{
  .method public hidebysig instance void 
          Test() cil managed
  {
    // Code size       15 (0xf)
    .maxstack  1
    .locals init ([0] class ClassLibrary.Super super)
    IL_0000:  nop
    IL_0001:  newobj     instance void ClassLibrary.Super::.ctor()
    IL_0006:  stloc.0
    IL_0007:  ldloc.0
    IL_0008:  callvirt   instance void ClassLibrary.Super::Foo()
    IL_000d:  nop
    IL_000e:  ret
  } // end of method Other::Test

  .method public hidebysig specialname rtspecialname 
          instance void  .ctor() cil managed
  {
    // Code size       7 (0x7)
    .maxstack  8
    IL_0000:  ldarg.0
    IL_0001:  call       instance void [mscorlib]System.Object::.ctor()
    IL_0006:  ret
  } // end of method Other::.ctor

} // end of class ClassLibrary.Other

.class public auto ansi beforefieldinit ClassLibrary.Super
       extends [mscorlib]System.Object
{
  .method famandassem hidebysig instance void 
          Foo() cil managed
  {
    // Code size       13 (0xd)
    .maxstack  8
    IL_0000:  nop
    IL_0001:  ldstr      "Foo"
    IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
    IL_000b:  nop
    IL_000c:  ret
  } // end of method Super::Foo

  .method assembly hidebysig instance void 
          Method() cil managed
  {
    // Code size       2 (0x2)
    .maxstack  8
    IL_0000:  nop
    IL_0001:  ret
  } // end of method Super::Method

  .method public hidebysig specialname rtspecialname 
          instance void  .ctor() cil managed
  {
    // Code size       7 (0x7)
    .maxstack  8
    IL_0000:  ldarg.0
    IL_0001:  call       instance void [mscorlib]System.Object::.ctor()
    IL_0006:  ret
  } // end of method Super::.ctor

} // end of class ClassLibrary.Super


// =============================================================

Now open ConsoleApplication.il and paste this code at the end after end of Class ConsoleApplication.Sub.

We need to do one more thing and get rid off reference to ClassLibrary.il which we don’t need anymore. So right in the beginning there is some code for that. Delete that piece of code and save the file.

.assembly extern ClassLibrary
{
  .ver 1:0:0:0
}

One more thing to do and it is replacing all [ClassLibrary] with empty string.

Delete console application and assemble the il to make new ConsoleApplication.exe using following command

ilasm ConsoleApplication.il /exe /out:ConsoleApplication.exe

Now we have new ConsoleApplication which doesn’t have reference to ClassLibrary. Run ConsoleApplication.exe you see it runs successfully.

Written by Ahmadreza Atighechi

January 22, 2014 at 11:14 pm

Posted in Blog

Tagged with ,

Quick Note: Memory Leak Or Missing Configuration

leave a comment »

Imagine you have multiple instances of SQL server on your server and one of them is using almost all of available memory and second one is facing memory shortage. What are possible Cause for this symptom. Does one of application have memory leak?

The answer is NO, When you install multiple instances of SQL server on a single server you have to consider memory allocation for each instances because windows does not balance memory across applications with the memory notification.

The first instance with a work load will  used huge portion of memory (Especially when you have actual data – not testing – on that instance).

Three approaches are available for Server Memory Option documented in the section “Sunning Multiple Instances of SQL server” and if you have selected third one which is “Do nothing”, you might have same problem.

  • Do nothing (not recommended). The first instances presented with a workload will tend to allocate all of memory. Idle instances or instances started later may end up running with only a minimal amount of memory available. SQL Server makes no attempt to balance memory usage across instances. All instances will, however, respond to Windows Memory Notification signals to adjust the size of their buffer pools. As of Windows Server 2003 SP1, Windows does not balance memory across applications with the Memory Notification API. It merely provides global feedback as to the availability of memory on the system.

Written by Ahmadreza Atighechi

November 14, 2011 at 5:24 pm

Posted in Blog

Tagged with

How to sign the XBAP with your own certificate

with 5 comments

I am writing a series of posts about WPF Browser Application, XBAP  and configuration tips. I’m going to host this application in IIS 5.1 and I developed them in .Net 3.5. The reason I have chosen IIS5.1 and .Net 3.5 is because of challenges I had in one of my recent projects. Configuring this type of projects is different in other versions of IIS and .Net frameworks and they are not is subject of this post series.

  1. How to create a simple Browser Enables WPF application
  2. How to host a windows form application inside XBAP
  3. How to sign the XBAP with your own certificate
Note: Making a browser enabled application as full trust according to this method is not completely secured. This can be used for testing purposes in testing environments. Please select proper certificates and known trusted root certification authorities.

Before starting I think its better to have same understanding of file extension that we are going to talk about.

.cer file: Apublic key which is given by Certificate Authority

.pvk file: This file is your private key and should keep it confidential

.pfx file: This is a Personal Information Exchange file and again you should keep it confidential because it contains

We have created a simple WPF Browser application and a simple windows application which is hosted inside the XBAP application. When we created WPF application Visual Studio automatically create a .pfx (Which is used for signing ClickOnce manifest).

To create your own certificate you need to follow these steps:

Step 1: Creating your key pairs (Public and Private)

open Visual Studio Command Prompt (2010) and then goto your application path and type following command


makecert -n "CN=Your Company Name" -r -sv Key.pvk Key.cer

A password dialog box will be displayed and you set your own password. This command creates two files one private key and one certificate.

Step2: Then you need to create PFX file which is used for signing ClickOnce manifest and contains both private and public key.


pvk2pfx.exe -pvk Key.pvk -spc Key.cer -pfx KeyPFX.pfx -po [password]

Put your own password as [password] and this command will create a PFX file

Step 3: Back to the solution explorer delete “SimpleBrowserApplication_TemporaryKey.pfx” and goto Application property page and select signing tab. Click on “Select from file” and select the PFX file you have just created.

Step 4: Just like before  publish it to you server.

Step 5: Give certificate to the client and register the certificate on the client machine. To do this double-clicking on .cer file. You will see following window. Click on Install Certificate button.

Follow installation wizard and click Next on the first window.

In this window select “Place all certificates in the following store”  and then select “Browse…” button.

In this window select “Trusted Publishers” and then click Ok. Select “Next” previous windows and then select finish.

Step 6: Redo the step 5 but this time select “Trusted Root Certification Authorities” as the certificate store.

Now you have enabled your client to accept this XBAP application as full-trust application.

Written by Ahmadreza Atighechi

May 20, 2011 at 9:30 am

Posted in Blog

Tagged with

How to host a windows form application inside XBAP

with 4 comments

I am writing a series of posts about WPF Browser Application, XBAP  and configuration tips. I’m going to host this application in IIS 5.1 and I developed them in .Net 3.5. The reason I have chosen IIS5.1 and .Net 3.5 is because of challenges I had in one of my recent projects. Configuring this type of projects is different in other versions of IIS and .Net frameworks and they are not is subject of this post series.

  1. How to create a simple Browser Enables WPF application
  2. How to host a windows form application inside XBAP
  3. How to sign the XBAP with your own certificate
Imagine we have an existing windows form application or you are developing a windows form application. The question is how you can make your windows application browser enabled. The answer is Browser Enabled WPF application. But usually when we create a WPF application we have to use WPF elements inside Xaml. “WindowsFormsIntegration” will help you to host your windows form application inside your WPF.
For rest of this post I consider you already have previous post sample, because I’m going to update the same project. Lets open the SimpleBrowserApplication and add a reference to “WindowsFormsIntegration”. As the second step I want to add new project to our solution of type “Windows Form Application” and I call it “WinFormSample”.
Note: Make sure when you are creating windows form application you selected .Net 3.5 because we are going to reference this project inside WPF project and they should be compatible.
That is how our solution looks like after adding windows form application and couple of simple controls on it. Next step we have to reference WinFormSample in SimpleBrowser application. Now our WPF application has got two more references which are “WindowsFormsIntegrations” and “WinFormSample”. Now we have to change Page1.xaml and put the following StackPanel instead of previous <Grid>
<StackPanel x:Name="stackPanel">
</StackPanel>

Actually this is a place holder for WindowsFormsHost that we are going to place in main form. For next step we need add System.Windows.Froms reference to WBP project. Then  we have to change page1.xaml code as follow.

public partial class Page1 : Page
{
	private readonly Form1 mainForm = new Form1();
	WindowsFormsHost windowsFormsHost;

	public Page1()
	{
		InitializeComponent();
		AddWindowsForm();
	}
	private void AddWindowsForm()
	{
		windowsFormsHost = new WindowsFormsHost();

		stackPanel.Children.Add(windowsFormsHost);

		// If you don't write this line you'll get "The child control cannot be a top-level form" exception
		mainForm.TopLevel = false;
		windowsFormsHost.Child = mainForm;
	}

}

We created a WindowsFormHost and added this control into stackPanel Child list and set the child property of windowsFormsMost to mainForm which is already instantiated of Form1.

One of important thing is setting mainForm.TopLevel to false. Because if you don’t do that you will get an exception and if you dive into innerexeptions you will find out that main reason is System.ArgumentException: The child control cannot be a top-level form.

If you run this application you’ll see following browser window which hosts Form1.

The point is when you run this application from visual studio it runs in My Computer Zone so there is no problem for security. According Microsoft document “WPF Partial Trust Security” section “Partial Trust Programming” when you run WPF application which requires full trust and current zone is “My Computer” behavior is “Automatic full trust” and for getting full trust no action is required.

But if you publish this project and try to browse this application you will get Trust Not Granted error. Because application will request for full trust and it fails with “Trust Not Granted”. In order to get full trust is signing XBAP with certificate.

In the next post we will see how to sign XBAP with your own certificate and make it work.

The source code of this application is also available you can download it here

Written by Ahmadreza Atighechi

May 17, 2011 at 9:29 am

Posted in Blog

Tagged with

How to create a simple Browser Enabled WPF application

with one comment

I am writing a series of posts about WPF Browser Application, XBAP  and configuration tips. I’m going to host this application in IIS 5.1 and I developed them in .Net 3.5. The reason I have chosen IIS5.1 and .Net 3.5 is because of challenges I had in one of my recent projects. Configuring this type of projects is different in other versions of IIS and .Net frameworks and they are not is subject of this post series.

  1. How to create a simple Browser Enables WPF application
  2. How to host a windows form application inside XBAP
  3. How to sign the XBAP with your own certificate

Firstly run Visual Studio 2010 and select new project from file menu

To create simple WPF browser application you need to select “WPF Browser Application” template from project templates. Once project template is created open Page1.xaml Xaml code and change Grid into following code

    <Grid>
        <Rectangle
            Fill="#33CC66"
            Width="2in"       Height="1in"
            Canvas.Top="25"          Canvas.Left="50"
            StrokeThickness="6px" Stroke="Orange" />
    </Grid>

This Xaml code will create a simple rectangle with border and if you run this application, It will show following shape inside your browser.

Deploying a WPF application

There are multiple ways to do that. Simply you can publish your application using visual studio. Right-click on project and select publish menu. Publish wizard is displayed. Follow the steps until the end of publish steps.

You must follow Microsoft instruction for How to: Configure IIS 5.0 and IIS 6.0 to Deploy WPF Applications to configure your server and client requires Internet Explorer plus .Net Framework to run this application.

Basically internet application which runs inside the browsers should have restricted access to critical resources. It means WPF browser application -By default- should respect to these restrictions so that client can make sure there is no harm to execute this application. Browser Enabled application by default is marked as partially trusted and ClickOnce security setting is set to Internet Zone so that your application will be running on the client browser without any problem.

As you see “Enable ClickOnce security settings” and “This is a partial trust application” are ticked by default and and ClickOnce manifests is signed by a temporary key. Which means on one your application will be restricted to security permission which is fully described in this document. On the other hand your application will be executed on client browser without any other additional configuration.

Above picture shows that you can run This simple WPF Browser Enabled application in “Internet Zone”.

The main reason of writing this post series for me is hosting windows form application inside XBAP application and running inside browser. In next post we will see how to host an existing windows form application within a WPF Browser application.

Sample project is also available you can download it here

Written by Ahmadreza Atighechi

May 12, 2011 at 2:59 pm

Posted in Blog

Tagged with

HOW TO propagate WCF Impersonation to COM objects

with 16 comments

I was working on a project to write a wrapper on a COM component in WCF. The COM object needs impersonation in some levels to provide certain functionalities to impersonated user. Basically impersonation in .Net application doesn’t propagate COM calls. I’ve seen following sentence in How To: Use Impersonation and Delegation in ASP.NET 2.0

The impersonation token does not propagate across threads if you use COM interop with components that have incompatible threading models, or if you use unmanaged techniques to create new threads

Actually I have a COM component and I want to use this component in my WCF Services. One of classes in COM object has got a property which returns current user. I wrote a console application to test impersonation and see if impersonation does propagate to COM object or not. I wrote a class for impersonation and  it has a method called “ImpersonateUser” that impersonates to passed username and password.  Following code returns different username for .net and COM object. It means it doesn’t propagate to COM object.

static void Main(string[] args)
{
	DoWork();
	Console.ReadLine();
}

private static void DoWork()
{
	ImpersonateClass impersonate = new ImpersonateClass();
	using (impersonate.ImpersonateUser("AnotherUser",
					"Domain",
					"passw0rd"))
	{
		COMTESTLib.TestClass obj = new COMTESTLib.TestClass();
		Console.WriteLine(string.Format("COM:{0} .Net:{1}", obj.CurrentUserName,
			System.Security.Principal.WindowsIdentity.GetCurrent().Name));
	}
}
//Returns:COM:DOMAIN\CurrentUser .Net:DOMAIN\AnotherUser</pre>

But I used CoInitializeSecurity to initialize security with impersonation and cloaking. CoInitializeSecurity should be called before any marshalling so I called CoInitializeSecurity as first function call.

[DllImport("ole32.dll")]
public static extern int CoInitializeSecurity(IntPtr pVoid, int
cAuthSvc, IntPtr asAuthSvc, IntPtr pReserved1, RpcAuthnLevel level,
RpcImpLevel impers, IntPtr pAuthList, int dwCapabilities, IntPtr
pReserved3);

static void Main(string[] args)
{
	int result = CoInitializeSecurity(IntPtr.Zero, -1,
	IntPtr.Zero, IntPtr.Zero,
	RpcAuthnLevel.Connect, RpcImpLevel.Impersonate,
	IntPtr.Zero, Convert.ToInt32(EoAuthnCap.DynamicCloaking), IntPtr.Zero);

	DoWork();
	Console.ReadLine();
}

private static void DoWork()
{
	ImpersonateClass impersonate = new ImpersonateClass();
	using (impersonate.ImpersonateUser("AnotherUser",
					"domain",
					"passw0rd"))
	{
		COMTESTLib.TestClass obj = new COMTESTLib.TestClass();
		Console.WriteLine(string.Format("COM:{0} .Net:{1}", obj.CurrentUserName,
			System.Security.Principal.WindowsIdentity.GetCurrent().Name));
	}
}
//Returns:COM:DOMAIN\AnotherUser .Net:DOMAIN\AnotherUser</pre>

Somebody suggested using built-in impersonation method for WCF so I changed my service to following code by setting [OperationBehavior(Impersonation = ImpersonationOption.Required)] and some changes in Web.Congif to make it work.

[OperationBehavior(Impersonation = ImpersonationOption.Required)]
public string GetUserNames()
{
	return DoWork();
}

private string DoWork()
{
	string result;

	COMTESTLib.TestClass obj = new COMTESTLib.TestClass();
	result = string.Format("COM:{0} .Net:{1}", obj.CurrentUserName,
		System.Security.Principal.WindowsIdentity.GetCurrent().Name);

	return result;
}

I passed user credentials from client for impersonation.

static void Main(string[] args)
{
	ServiceReference.ServiceImpersonateClient client = new ServiceReference.ServiceImpersonateClient();
	client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Delegation;
	client.ClientCredentials.Windows.ClientCredential.Domain = "Domain";
	client.ClientCredentials.Windows.ClientCredential.UserName = "AnotherUser";
	client.ClientCredentials.Windows.ClientCredential.Password = "Passw0rd";

	string str = client.GetUserNames();
	Console.WriteLine(str);
	Console.ReadLine();
	client.Close();
}
// Returns COM:DOMAIN\CurrentUser .Net:DOMAIN\AnotherUser

But it returns different usernames which means impersonation of WCF does not propagate to COM object.

Ok I posted this issue in WCF Forum and I’ve got a simple response but it gave me a good clue. Allen Chen (The moderator) suggested me to use self-hosting for WCF instead of IIS hosting.

Self-hosted WCF was great idea!  Actually it works on self-hosted. But my WCF service should be unattended so that I created a managed service for WCF hosting. To make it work I’ve created three projects. One WCF service library which is used in managed service application. And the third one is a console application for testing. I’ve called CoInitializeSecurity on constructor of my service class as following

private ServiceHost serviceHost;
 public WCFServiceHost()
 {
  int result = CoInitializeSecurity(IntPtr.Zero, -1,
  IntPtr.Zero, IntPtr.Zero,
  RpcAuthnLevel.Connect, RpcImpLevel.Impersonate,
  IntPtr.Zero, Convert.ToInt32(EoAuthnCap.DynamicCloaking), IntPtr.Zero);
  //EventLog.WriteEntry(result.ToString());
  InitializeComponent();
 }

 protected override void OnStart(string[] args)
 {
  if (serviceHost != null)
  {
  serviceHost.Close();
  }

  // Create a ServiceHost for the CalculatorService type and
  // provide the base address.
  serviceHost = new ServiceHost(typeof(ServiceImpersonate));

  // Open the ServiceHostBase to create listeners and start
  // listening for messages.

  serviceHost.Open();

 }

 protected override void OnStop()
 {
  if (serviceHost != null)
  {
  serviceHost.Close();
  serviceHost = null;
  }
 }

It doesn’t work with built in WCF impersonation. But I used my impersonation class inside the service class to impersonate to desired user and it works.

public string GetUserNames()
 {
  ImpersonateClass impersonate = new ImpersonateClass();

  using (impersonate.ImpersonateUser("AnotherUser",
         "Domain",
          "passw0rd"))
  {
   return DoWork();
  }
 }

 private string DoWork()
 {
  string result;

   COMTESTLib.TestClass obj = new COMTESTLib.TestClass();
   result = string.Format("COM:{0} .Net:{1}", obj.CurrentUserName,
       System.Security.Principal.WindowsIdentity.GetCurrent().Name);
  return result;
 }

In the console application I simply called my service like following code:

ServiceReference.ServiceImpersonateClient client = new ServiceReference.ServiceImpersonateClient();
  string str = client.GetUserNames();
  Console.WriteLine(str);
  client.Close();
  Console.ReadLine();
// Returns COM:DOMAIN\ AnotherUser .Net:DOMAIN\AnotherUser

When you host WCF in IIS the process is spawned by IIS and before your code running code managed by IIS will be run in the process, which is almost out of your control. CoInitializeSecurity thus might be called before you calling it.

Written by Ahmadreza Atighechi

September 16, 2010 at 5:19 pm

Posted in Blog

Tagged with , ,

Follow

Get every new post delivered to your Inbox.