System.TypeInitializationException Error

Jun 4, 2008 at 4:39 PM
Hi all,

Could you please help me to resolve this problem I am having when using Logging block ? Error trace is as below:

System.TypeInitializationException was unhandled
  Message="The type initializer for 'Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry' threw an exception."
  Source="Microsoft.Practices.EnterpriseLibrary.Logging"
  TypeName="Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry"
  StackTrace:
       at Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry..ctor()
       at OFMJobAllocation.FrmLogin.Button1_Click(Object sender, EventArgs e) in C:\Local Development\OFMJobAllocation\OFMJobAllocation\FrmLogin.vb:line 136
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
       at System.Windows.Forms.Form.ShowDialog()
       at OFMJobAllocation.mdlGlobal.Main() in C:\Local Development\OFMJobAllocation\OFMJobAllocation\mdlGlobal.vb:line 17
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()



Many thanks.
Milan G
Jun 4, 2008 at 4:42 PM
Can you post the inner exception for the TypeInitializationException?

milgurung wrote:
Hi all,

Could you please help me to resolve this problem I am having when using Logging block ? Error trace is as below:

System.TypeInitializationException was unhandled
  Message="The type initializer for 'Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry' threw an exception."
  Source="Microsoft.Practices.EnterpriseLibrary.Logging"
  TypeName="Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry"
  StackTrace:
       at Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry..ctor()
       at OFMJobAllocation.FrmLogin.Button1_Click(Object sender, EventArgs e) in C:\Local Development\OFMJobAllocation\OFMJobAllocation\FrmLogin.vb:line 136
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
       at System.Windows.Forms.Form.ShowDialog()
       at OFMJobAllocation.mdlGlobal.Main() in C:\Local Development\OFMJobAllocation\OFMJobAllocation\mdlGlobal.vb:line 17
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()



Many thanks.
Milan G



Jul 9, 2008 at 8:55 PM
I'm having this problem also. I am attempting to use the Enterprise Library 4.0 blocks from an IIS-hosted WCF service. The inner exception is:

-        _innerException    {"Could not load file or assembly 'System.Management, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. Access is denied.":"System.Management, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"}    System.Exception {System.IO.FileLoadException}

This version of System.Management is referenced directly in the web application project and by being listed in the <assemblies> node in the web.config. What am I overlooking?

The complete exception is:

System.TypeInitializationException: The type initializer for 'Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry' threw an exception. ---> System.IO.FileLoadException: Could not load file or assembly 'System.Management, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. Access is denied.
File name: 'System.Management, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
   at System.ModuleHandle.ResolveMethod(Int32 methodToken, RuntimeTypeHandle* typeInstArgs, Int32 typeInstCount, RuntimeTypeHandle* methodInstArgs, Int32 methodInstCount)
   at System.ModuleHandle.ResolveMethodHandle(Int32 methodToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
   at System.Reflection.CustomAttributeData..ctor(Module scope, CustomAttributeRecord caRecord)
   at System.Reflection.CustomAttributeData.GetCustomAttributes(Module module, Int32 tkTarget)
   at System.Reflection.CustomAttributeData.GetCustomAttributes(Assembly target)
   at System.Resources.ResourceManager.GetNeutralResourcesLanguage(Assembly a, UltimateResourceFallbackLocation& fallbackLocation)
   at System.Resources.ResourceManager.InternalGetResourceSet(CultureInfo culture, Boolean createIfNotExists, Boolean tryParents)
   at System.Resources.ResourceManager.GetString(String name, CultureInfo culture)
   at Microsoft.Practices.EnterpriseLibrary.Logging.Properties.Resources.get_DefaultTextFormat()
   at Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter..ctor()
   at Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry..cctor()

=== Pre-bind state information ===
LOG: User = Unknown
LOG: DisplayName = System.Management, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
 (Fully-specified)
LOG: Appbase = file:///C:/dev/ExtranetPortal/Application/Web/
LOG: Initial PrivatePath = C:\dev\ExtranetPortal\Application\Web\bin
Calling assembly : Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=c5033f151b0ba064.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\dev\ExtranetPortal\Application\Web\web.config
LOG: Using host configuration file: \\?\c:\windows\microsoft.net\framework\v2.0.50727\aspnet.config
LOG: Using machine configuration file from C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\config\machine.config.
LOG: Post-policy reference: System.Management, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a

   --- End of inner exception stack trace ---
   at Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry..ctor()
   at Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(Object message, ICollection`1 categories, Int32 priority, Int32 eventId, TraceEventType severity, String title, IDictionary`2 properties)
   at Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(Object message, String category, Int32 priority, Int32 eventId, TraceEventType severity, String title, IDictionary`2 properties)
   at Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(Object message, String category, Int32 priority)
   at Application.Service.Utility.Log.WriteDebugEntry(String message, Priority priority) in C:\dev\ExtranetPortal\Application\Web\Utility\Log.cs:line 40


Jul 9, 2008 at 9:09 PM
Update: I am also having the same (inner) exception when attempting to call:
Database db = DatabaseFactory.CreateDatabase();
That exception is:
{"Could not load file or assembly 'System.Management, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. Access is denied.":"System.Management, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"}
Jul 10, 2008 at 1:18 PM
Can you get the full fusion log for this failure?

Fernando


kalahari875 wrote:
Update: I am also having the same (inner) exception when attempting to call:
Database db = DatabaseFactory.CreateDatabase();
That exception is:
{"Could not load file or assembly 'System.Management, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. Access is denied.":"System.Management, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"}



Jul 10, 2008 at 2:31 PM
Edited Jul 10, 2008 at 2:36 PM
It's odd--I can see other bind failures in the fusion logs, but this exception does not generate any. The only bind failures I see are during application startup (before the exception occurs):
  • VJSharpCodeProvider, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a (from w3wp.exe), and
  • System.Web.Silverlight.resources (also from w3wp.exe, but this is expected as I have no resource files for the loaded language (en)).
If I step into the Ent Lib code for the CreateDatabase call, the exception occurs immediately after the PreBuildUp method seemingly successfully executes and returns:

//===============================================================================
// Microsoft patterns & practices Enterprise Library
// Core
//===============================================================================
// Copyright © Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================

using Microsoft.Practices.ObjectBuilder2;

namespace Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder
{
    /// <summary>
    /// Implementation of <see cref="IBuilderStrategy"/> which maps null instance names into a different name.
    /// </summary>
    /// <remarks>
    /// The strategy is used to deal with default names.
    /// </remarks>
    /// <seealso cref="ConfigurationNameMapperAttribute"/>
    /// <seealso cref="IConfigurationNameMapper"/>
    public class ConfigurationNameMappingStrategy : EnterpriseLibraryBuilderStrategy
    {
        /// <summary>
        /// Override of <see cref="IBuilderStrategy.PreBuildUp"/>. Updates the instance name using a name mapper associated to type
        /// to build so later strategies in the build chain will use the updated instance name.
        /// </summary>
        /// <remarks>
        /// Will only update the instance name if it is <see langword="null"/>.
        /// </remarks>
        /// <param name="context">The <see cref="IBuilderContext"/> that represents the current building process.</param>
        /// <exception cref="System.Configuration.ConfigurationErrorsException"> when the configuration required to do the mapping is not present or is
        /// invalid in the configuration source.</exception>
        public override void PreBuildUp(IBuilderContext context)
        {
            base.PreBuildUp(context);

            NamedTypeBuildKey key = (NamedTypeBuildKey) context.BuildKey;

            if (key.Name == null)
            {
                ConfigurationReflectionCache reflectionCache = GetReflectionCache(context);

                IConfigurationNameMapper mapper = reflectionCache.GetConfigurationNameMapper(key.Type);
                if (mapper != null)
                {
                    context.BuildKey = new NamedTypeBuildKey(key.Type, mapper.MapName(null, GetConfigurationSource(context)));
                }
            }
        }
    }
}


Once this fails, the code falls into the catch block of the T BuildUp<T>() method. The exception is rethrown as-is because it is not a ConfigurationErrorsException:

        /// <summary>
        /// Returns a default instance of type <typeparamref name="T"/> based on configuration information
        /// from <paramref name="configurationSource"/>.
        /// </summary>
        /// <typeparam name="T">The type to build.</typeparam>
        /// <param name="locator">The locator to be used for this build operation.</param>
        /// <param name="lifetimeContainer">The lifetime container to be used for this build operation.</param>
        /// <param name="configurationSource">The source for configuration information.</param>
        /// <returns>A new instance of <typeparamref name="T"/> or any of it subtypes, or an existing instance
        /// if type <typeparamref name="T"/> is a singleton that is already present in the <paramref name="locator"/>.
        /// </returns>
        public static T BuildUp<T>(IReadWriteLocator locator,
                                   ILifetimeContainer lifetimeContainer,
                                   IConfigurationSource configurationSource)
        {
            if (configurationSource == null)
                throw new ArgumentNullException("configurationSource");

            try
            {
                return GetObjectBuilder()
                    .BuildUp<T>(locator,
                                lifetimeContainer,
                                GetPolicies(configurationSource),
                                strategyChain,
                                NamedTypeBuildKey.Make<T>(),
                                null);

            }
            catch (BuildFailedException e)
            {
                // look for the wrapped ConfigurationErrorsException, if any, and throw it
                ConfigurationErrorsException cee = GetConfigurationErrorsException(e);
                if (cee != null)
                {
                    throw cee;
                }

                // unknown exception, bubble it up
                throw;
            }
        }

Jul 10, 2008 at 4:05 PM
What are your environment characteristics? Is this a dev or production server? Is there something special about your ASP.NET account?

Thanks,
Fernando

kalahari875 wrote:
Update: I am also having the same (inner) exception when attempting to call:
Database db = DatabaseFactory.CreateDatabase();
That exception is:
{"Could not load file or assembly 'System.Management, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. Access is denied.":"System.Management, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"}



Jul 10, 2008 at 4:22 PM
Thanks for your reply. This is presently a development server (WS 2003 R2 SP2, IIS 6.0). The application pool identity is Network Service, but I have attempted changing it to Local System--this did not have any effect on the exception.

I included the affected code in a console application on the same machine (not as a service, but just a direct call to fetch the data) and it is able to successfully execute (both logging and database access). Could this have something to do with the fact that the service in question is a WCF service running in ASP.NET compatibility mode?

The service configuration is basic HTTP binding with Windows integrated security:

  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="IntegratedBinding">
          <security mode="TransportCredentialOnly">
            <transport clientCredentialType="Windows" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="workOrderServiceBehavior">
          <serviceMetadata httpGetEnabled="true" httpGetUrl="" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service name="Service.WorkOrderService" behaviorConfiguration="workOrderServiceBehavior">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="IntegratedBinding" name="integratedBasicHttpEndpoint" contract="Service.IWorkOrderService" />
        <endpoint address="mex" binding="mexHttpBinding" name="mexEndpoint" contract="IMetadataExchange" />
      </service>
    </services>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
  </system.serviceModel>

And the service class itself is decorated with the following attribute to force ASP.NET compatibility mode:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public class WorkOrderService : IWorkOrderService
    { ... }

The fact that this is an IIS-hosted service and is executed through the System.ServiceModel.Dispatcher may not be the cause; just grasping for what might be the problem. I did register all Ent Lib services via the InstallServices script. I also attempted to GAC the assemblies (I have signed them) but this did not improve the behavior. I'd greatly appreciate any suggestions.


fsimonazzi wrote:
What are your environment characteristics? Is this a dev or production server? Is there something special about your ASP.NET account?

Thanks,
Fernando

Jul 10, 2008 at 4:54 PM
Edited Jul 10, 2008 at 7:59 PM
I just reconfigured the service to not use ASP.NET compatibility mode, instead impersonating the caller on all calls, but it did not help.

web.config:
<serviceHostingEnvironment aspNetCompatibilityEnabled="false" />

Service class, on each method:
[OperationBehavior(Impersonation = ImpersonationOption.Required)]

It is impersonating the caller just as before, but the error persists.

Jul 10, 2008 at 7:21 PM
Edited Jul 10, 2008 at 7:22 PM
I just remembered: this is running the .NET 3.5 SP1 beta.
Jul 10, 2008 at 7:45 PM
Edited Jul 10, 2008 at 7:58 PM
I have discovered what causes the TypeInitializationException in the Enterprise Library assemblies. If the WCF service is impersonating the caller, the assembly will fail to load System.Management with access denied. I summarized the problem on my blog.

I believe this is a .NET 3.5 SP1 beta issue, as calling Enterprise Library while using impersonation (at least using ASP.NET Compatibility mode) was working prior to applying the .NET 3.5 SP1 beta. Either that, or SP1 brings fundamental security changes that prevents Enterprise Library from loading dependent assemblies. I'd appreciate any other thoughts.

Jul 10, 2008 at 7:54 PM
Thanks for the insight. I'll try to repro it on my end.

Strangely enough, the initial post on this thread referred to a WinForms app.
Milan, are you working with .NET 3.5 SP1 beta?

Fernando

kalahari875 wrote:
I have discovered what causes the TypeInitializationException in the Enterprise Library assemblies. If the WCF service is impersonating the caller, the assembly will fail to load System.Management with access denied. I summarized the problem on my blog.

I believe this is a .NET 3.5 SP1 beta issue, as calling Enterprise Library while using impersonation (at least using ASP.NET Requirements Compatibility mode) was working prior to applying the .NET 3.5 SP1 beta. Either that, or SP1 brings fundamental security changes that prevents Enterprise Library from loading dependent assemblies. I'd appreciate any other thoughts.




Jul 10, 2008 at 8:16 PM
Sure, and thank you for your responses. Here is the code for the simplified WCF service configured for impersonation to demonstrate the failure. I have this hosted in IIS 6.0 with Windows integrated security only enabled. Comment out the  "[OperationBehavior(Impersonation = ImpersonationOption.Required)]" lines in Service1.svc.cs and remove "<serviceAuthorization impersonateCallerForAllOperations="true" />" from web.config to eliminate impersonation, which makes this work on my end.

Jul 10, 2008 at 8:25 PM
Note that the above sample uses Enterprise Library 3.1, but I got the same results with 4.0. In both cases, we have signed the assemblies with our own key, if that matters.
Jul 10, 2008 at 10:39 PM

Hi,

I could repro it on .NET 3.5 RTM, so that rules out changes in .NET 3.5 SP1 Beta.

Fernando


kalahari875 wrote:
Sure, and thank you for your responses. Here is the code for the simplified WCF service configured for impersonation to demonstrate the failure. I have this hosted in IIS 6.0 with Windows integrated security only enabled. Comment out the  "[OperationBehavior(Impersonation = ImpersonationOption.Required)]" lines in Service1.svc.cs and remove "<serviceAuthorization impersonateCallerForAllOperations="true" />" from web.config to eliminate impersonation, which makes this work on my end.




Jul 11, 2008 at 1:12 AM
I think I got it. I had nothing to do with EntLib itself; changing the repro to do a simple new System.Management.Instrumentation.InstrumentationClassAttribute(System.Management.Instrumentation.InstrumentationType.Instance); instead of invoking the logging block triggered the failure when impersonation was enabled.

To repro the issue I used a simple console app as a client (create the service client in a using statement and invoke an operation) using the default configuration generated by svcutil.

Adding this to the client's configuration got rid of the issue in my local repro:

    <client>

      <endpoint address=http://myserver/wcfrepro2/Service1.svc

                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService1"

                behaviorConfiguration="EndpointBehavior"

                contract="IService1" name="BasicHttpBinding_IService1" />

    </client>

    <behaviors>

      <endpointBehaviors>

        <behavior name="EndpointBehavior">

          <clientCredentials>

            <windows allowedImpersonationLevel="Impersonation" />

          </clientCredentials>

        </behavior>

      </endpointBehaviors>

    </behaviors>


Can you please try it on your end?

Fernando
Jul 11, 2008 at 12:54 PM
Thanks again for your efforts. I set up a console application client to call the sample service I linked above, and configured the allowedImpersonationLevel as you suggested, but the failure persists. The client's app.config is as follows:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IService1" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                    messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                    useDefaultWebProxy="true">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <security mode="TransportCredentialOnly">
                        <transport clientCredentialType="Windows" proxyCredentialType="None"
                            realm="" />
                        <message clientCredentialType="UserName" algorithmSuite="Default" />
                    </security>
                </binding>
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://server/WcfService1/Service1.svc"
                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService1"
                contract="ServiceReference2.IService1" name="BasicHttpBinding_IService1"
                      behaviorConfiguration="endpointBehavior"/>
        </client>
        <behaviors>
            <endpointBehaviors>
                <behavior name="endpointBehavior">
                    <clientCredentials>
                        <windows allowedImpersonationLevel="Impersonation"/>
                    </clientCredentials>
                </behavior>
            </endpointBehaviors>
        </behaviors>
    </system.serviceModel>
</configuration>


Jul 11, 2008 at 2:53 PM
Hi,

Can you try again after restarting your web app? I found that I needed to restart the app in order to make it work (don't ask me why).

Fernando

kalahari875 wrote:
Thanks again for your efforts. I set up a console application client to call the sample service I linked above, and configured the allowedImpersonationLevel as you suggested, but the failure persists. The client's app.config is as follows:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IService1" closeTimeout="00:01:00"
                    openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                    allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                    maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                    messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
                    useDefaultWebProxy="true">
                    <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                    <security mode="TransportCredentialOnly">
                        <transport clientCredentialType="Windows" proxyCredentialType="None"
                            realm="" />
                        <message clientCredentialType="UserName" algorithmSuite="Default" />
                    </security>
                </binding>
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://server/WcfService1/Service1.svc"
                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService1"
                contract="ServiceReference2.IService1" name="BasicHttpBinding_IService1"
                      behaviorConfiguration="endpointBehavior"/>
        </client>
        <behaviors>
            <endpointBehaviors>
                <behavior name="endpointBehavior">
                    <clientCredentials>
                        <windows allowedImpersonationLevel="Impersonation"/>
                    </clientCredentials>
                </behavior>
            </endpointBehaviors>
        </behaviors>
    </system.serviceModel>
</configuration>





Jul 11, 2008 at 7:36 PM
I had touched the web.config several times, but I suppose I hadn't reset IIS. That did the trick.

Well... I understand what is happening and how to correct it, but I'm not satisfied as to why this is happening. I shouldn't think WCF would require an IIS reset to respond to client configuration changes. Also, the server side does impersonate the client regardless of the presence of the client's allowedImpersonationLevel configuration, but this clearly prevents the System.Management assembly--but not other assemblies--from loading.

Thanks for your time on this.



fsimonazzi wrote:
Hi,

Can you try again after restarting your web app? I found that I needed to restart the app in order to make it work (don't ask me why).

Fernando

Jul 11, 2008 at 7:58 PM

I agree, this is quite bizarre. In my case I didn't restart IIS itself but I did restart the app pool.

-Fernando


kalahari875 wrote:
I had touched the web.config several times, but I suppose I hadn't reset IIS. That did the trick.

Well... I understand what is happening and how to correct it, but I'm not satisfied as to why this is happening. I shouldn't think WCF would require an IIS reset to respond to client configuration changes. Also, the server side does impersonate the client regardless of the presence of the client's allowedImpersonationLevel configuration, but this clearly prevents the System.Management assembly--but not other assemblies--from loading.

Thanks for your time on this.



fsimonazzi wrote:
Hi,

Can you try again after restarting your web app? I found that I needed to restart the app in order to make it work (don't ask me why).

Fernando




Jul 11, 2008 at 8:50 PM
I guess it's easier to search when you already know the solution :)

http://msdn.microsoft.com/en-us/library/ms730088.aspx
http://agilior.pt/blogs/bruno.camara/archive/2008/02/19/3721.aspx

What bothers me is that svcutil.exe created questionable configuration...

-Fernando



fsimonazzi wrote:

I agree, this is quite bizarre. In my case I didn't restart IIS itself but I did restart the app pool.

-Fernando


kalahari875 wrote:
I had touched the web.config several times, but I suppose I hadn't reset IIS. That did the trick.

Well... I understand what is happening and how to correct it, but I'm not satisfied as to why this is happening. I shouldn't think WCF would require an IIS reset to respond to client configuration changes. Also, the server side does impersonate the client regardless of the presence of the client's allowedImpersonationLevel configuration, but this clearly prevents the System.Management assembly--but not other assemblies--from loading.

Thanks for your time on this.



fsimonazzi wrote:
Hi,

Can you try again after restarting your web app? I found that I needed to restart the app in order to make it work (don't ask me why).

Fernando







Mar 15, 2010 at 4:38 PM

I had the same issue, but my case was with a asmx web-service. Fixed the issue by setting impersonation=true in the web.config file.

HTH,

Gokul