After upgrading to .Net 4.0, I'm getting the exception "Could not load file or assembly 'System.Windows, Version=2.0.5.0'" - asp.net-4.0

We recently upgraded our web app from 3.5 to 4.0. Now after I login and load a page with Microsoft ScriptManager on it, I get:
Could not load file or assembly 'System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' or one of its dependencies. The system cannot find the file specified.
It only happens the first time, reload the page and everything works.
UPDATE: We have all Silverlight v4 projects.I found the System.Windows.dll in the C:\Program Files\Reference Assemblies\Microsoft\Framework\Silverlight\v4.0 directory. Why would it look for version 2.0?
Here's the entire exception (edited and removed folder paths)
Server Error in '/test' Application.
Could not load file or assembly 'System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' or one of its dependencies. The system cannot find the file specified.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IO.FileNotFoundException: Could not load file or assembly 'System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' or one of its dependencies. The system cannot find the file specified.
Source Error:
Line 450: <UC5:PageTitle ID="PageTitle" runat="server" />
Line 451: <UC2:PageTabs ID="testPageTabs" runat="server" />
Line 452: <asp:ScriptManager ID="ScriptManager1" runat="server"/>
Line 453: <div id="step1Div" style="padding-top: 10px; padding-left: 10px" runat="server">
Line 454: <asp:ValidationSummary ID="displayValidationSummary" ValidationGroup="displayCreateEditValidationGroup" runat="server" />
Source File: c:{directories}\Pages\Administration\DisplayCreateEdit.aspx Line: 452
Assembly Load Trace: The following information can be helpful to determine why the assembly 'System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' could not be loaded.
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
Stack Trace:
[FileNotFoundException: Could not load file or assembly 'System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' or one of its dependencies. The system cannot find the file specified.]
System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken, IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs, Int32 methodInstCount, ObjectHandleOnStack type) +0
System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module, Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext) +180
System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) +192
System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean& isVarArg) +115
System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes, Boolean isDecoratedTargetSecurityTransparent) +426
System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType) +103
System.Reflection.RuntimeAssembly.GetCustomAttributes(Boolean inherit) +33
System.Web.UI.AssemblyCache.GetAjaxFrameworkAssemblyAttribute(Assembly assembly) +76
System.Web.UI.ScriptManager.get_DefaultAjaxFrameworkAssembly() +388
System.Web.UI.ScriptManager..ctor() +26
ASP.pages_administration_displaycreateedit_aspx.__BuildControlScriptManager1() in c:{directories}\Pages\Administration\DisplayCreateEdit.aspx:452
ASP.pages_administration_displaycreateedit_aspx.__BuildControlContent1(Control __ctrl) in c:{directories}\Pages\Administration\DisplayCreateEdit.aspx:9
System.Web.UI.CompiledTemplateBuilder.InstantiateIn(Control container) +12
System.Web.UI.MasterPage.InstantiateInContentPlaceHolder(Control contentPlaceHolder, ITemplate template) +87
ASP.master_master.__BuildControlContentPlaceHolder1() in c:{directories}\Master.master:28
ASP.master_master.__BuildControlmasterForm() in c:{directories}\Master.master:13
ASP.master_master.__BuildControlTree(master_master __ctrl) in c:{directories}\Master.master:1
ASP.master_master.FrameworkInitialize() in c:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\zoning\dff1a5fe\99aa3a7f\App_Web_shgw15qp.4.cs:0
System.Web.UI.UserControl.InitializeAsUserControlInternal() +35
System.Web.UI.MasterPage.CreateMaster(TemplateControl owner, HttpContext context, VirtualPath masterPageFile, IDictionary contentTemplateCollection) +8832342
System.Web.UI.Page.get_Master() +54
System.Web.UI.Page.ApplyMasterPage() +15
System.Web.UI.Page.PerformPreInit() +45
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +328
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1
And the system.web of our web.config:
<system.web>
<pages validateRequest="false" buffer="true" theme="Summer" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
<controls>
<add namespace="AjaxControlToolkit" assembly="AjaxControlToolkit" tagPrefix="ajaxToolkit"/>
</controls>
<tagMapping>
<add tagType="System.Web.UI.WebControls.TextBox" mappedTagType="CleanTextBox"/>
<add tagType="System.Web.UI.HtmlControls.HtmlTextArea" mappedTagType="CleanTextArea"/>
</tagMapping>
</pages>
<compilation debug="true" targetFramework="4.0">
<assemblies>
</assemblies>
</compilation>
<authentication mode="Forms">
<forms requireSSL="false" cookieless="UseDeviceProfile" loginUrl="~/Pages/Authentication/Login.aspx" timeout="60" defaultUrl="~/Pages/Authentication/AccountHome.aspx" slidingExpiration="true" name="sqlAuthCookie" protection="All"/>
</authentication>
<sessionState timeout="60" mode="StateServer" stateConnectionString="tcpip=localhost" stateNetworkTimeout="60" cookieless="false"/>
<customErrors mode="RemoteOnly" defaultRedirect="~/Pages/Global/DefaultError.aspx">
<error statusCode="404" redirect="~/Pages/Global/404.htm"/>
<error statusCode="403" redirect="~/Pages/Global/403.htm"/>
</customErrors>
<httpHandlers>
<add path="*js.axd" verb="*" type="ScriptCompressorHandler"/>
<add path="*css.axd" verb="*" type="CssCompressorHandler"/>
<add path="*css" verb="*" type="CssCompressorHandler"/>
<add verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</httpHandlers>
<httpModules>
<remove name="WindowsAuthentication"/>
<remove name="PassportAuthentication"/>
<remove name="AnonymousIdentification"/>
<remove name="RoleManager"/>
<remove name="Profile"/>
<remove name="ErrorHandlerModule"/>
<add type="ScriptCompressorModule" name="ScriptCompressorModule"/>
<add type="CssCompressorModule" name="CssCompressorModule"/>
</httpModules>
<machineKey validationKey="{key}" decryptionKey="{key}" validation="SHA1"/>
<httpRuntime maxRequestLength="1048576" executionTimeout="3600" requestValidationMode="2.0"/>
</system.web>
See the same problem here and Microsoft Feedback/Bug report
Edit: I'm running VS 2010, XP with IIS 5.0 (I miss Win 7 at work every day :-)). We have the web app running under the local IIS instance, not Cassini. We deployed it to a test server and I did not see the exception. After I installed the C:\Program Files\Reference Assemblies\Microsoft\Framework\Silverlight\v4.0\System.windows.dll to the GAC and then removed it and haven't seen the same exception, though my colleague hasn't done this and still sees it occasionally. I think it only happens when the app is restarted (which happens every time we rebuild the app when developing locally).

Sounds like one of the projects in your solution is referencing the v2 system assemblies. Make sure that all of your projects and application pools are set to use 4.0. You can set this in the project properties in Visual Studio.
(Note that you'll have to rebuild your solution with the new settings if you haven't already).

I have been having the same issues for a long time, but just found some old Silverlight Assemblies in my bin folder, removed those and voila.. error gone

Adding reference to AjaxControlToolkit.dll and adding the header
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
to the aspx that contains the script manager solved the problem for me.

Related

WCF customUserNamePasswordValidatorType error - Could not load file or assembly 'CustomUserNameValidator' or one of its dependencies

I have created a simply WCF web service and require WCF Security with username/password added to the service and have read through the following MS documentation https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-use-a-custom-user-name-and-password-validator to try and do so.
However, I am getting the error below when I run the project and go to http://localhost:50533/Service.svc:
Server Error in '/' Application.
Could not load file or assembly 'CustomUserNameValidator' or one of its dependencies. The system cannot find the file specified.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IO.FileNotFoundException: Could not load file or assembly 'CustomUserNameValidator' or one of its dependencies. The system cannot find the file specified.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Assembly Load Trace: The following information can be helpful to determine why the assembly 'CustomUserNameValidator' could not be loaded.
=== Pre-bind state information ===
LOG: DisplayName = CustomUserNameValidator
(Partial)
WRN: Partial binding information was supplied for an assembly:
WRN: Assembly Name: CustomUserNameValidator | Domain ID: 6
WRN: A partial bind occurs when only part of the assembly display name is provided.
WRN: This might result in the binder loading an incorrect assembly.
WRN: It is recommended to provide a fully specified textual identity for the assembly,
WRN: that consists of the simple name, version, culture, and public key token.
WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue.
LOG: Appbase = file:///C:/Users/xxxx/source/repos/Misc/WCFDummyService/WCFDummyService/
LOG: Initial PrivatePath = C:\Users\xxxx\source\repos\Misc\WCFDummyService\WCFDummyService\bin
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Users\xxxx\source\repos\Misc\WCFDummyService\WCFDummyService\web.config
LOG: Using host configuration file: C:\Users\xxxx\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Users/xxxx/AppData/Local/Temp/Temporary ASP.NET Files/vs/2193ee9a/db4d60f6/CustomUserNameValidator.DLL.
LOG: Attempting download of new URL file:///C:/Users/xxxx/AppData/Local/Temp/Temporary ASP.NET Files/vs/2193ee9a/db4d60f6/CustomUserNameValidator/CustomUserNameValidator.DLL.
LOG: Attempting download of new URL file:///C:/Users/xxxx/source/repos/Misc/WCFDummyService/WCFDummyService/bin/CustomUserNameValidator.DLL.
LOG: Attempting download of new URL file:///C:/Users/xxxx/source/repos/Misc/WCFDummyService/WCFDummyService/bin/CustomUserNameValidator/CustomUserNameValidator.DLL.
LOG: Attempting download of new URL file:///C:/Users/xxxx/AppData/Local/Temp/Temporary ASP.NET Files/vs/2193ee9a/db4d60f6/CustomUserNameValidator.EXE.
LOG: Attempting download of new URL file:///C:/Users/xxxx/AppData/Local/Temp/Temporary ASP.NET Files/vs/2193ee9a/db4d60f6/CustomUserNameValidator/CustomUserNameValidator.EXE.
LOG: Attempting download of new URL file:///C:/Users/xxxx/source/repos/Misc/WCFDummyService/WCFDummyService/bin/CustomUserNameValidator.EXE.
LOG: Attempting download of new URL file:///C:/Users/xxxx/source/repos/Misc/WCFDummyService/WCFDummyService/bin/CustomUserNameValidator/CustomUserNameValidator.EXE.
Stack Trace:
[FileNotFoundException: Could not load file or assembly 'CustomUserNameValidator' or one of its dependencies. The system cannot find the file specified.]
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName, ObjectHandleOnStack type) +0
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName) +71
System.RuntimeType.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark) +41
System.Type.GetType(String typeName, Boolean throwOnError) +35
System.ServiceModel.Configuration.UserNameServiceElement.ApplyConfiguration(UserNamePasswordServiceCredential userName) +356
System.ServiceModel.Configuration.ServiceCredentialsElement.ApplyConfiguration(ServiceCredentials behavior) +128
System.ServiceModel.Configuration.ServiceCredentialsElement.CreateBehavior() +165
System.ServiceModel.Description.ConfigLoader.LoadBehaviors(ServiceModelExtensionCollectionElement`1 behaviorElement, KeyedByTypeCollection`1 behaviors, Boolean commonBehaviors) +204
System.ServiceModel.Description.ConfigLoader.LoadServiceDescription(ServiceHostBase host, ServiceDescription description, ServiceElement serviceElement, Action`1 addBaseAddress, Boolean skipHost) +13502205
System.ServiceModel.ServiceHostBase.LoadConfigurationSectionInternal(ConfigLoader configLoader, ServiceDescription description, ServiceElement serviceSection) +74
System.ServiceModel.ServiceHostBase.ApplyConfiguration() +188
System.ServiceModel.ServiceHost.ApplyConfiguration() +65
System.ServiceModel.ServiceHostBase.InitializeDescription(UriSchemeKeyedCollection baseAddresses) +188
System.ServiceModel.ServiceHost.InitializeDescription(Type serviceType, UriSchemeKeyedCollection baseAddresses) +49
System.ServiceModel.ServiceHost..ctor(Type serviceType, Uri[] baseAddresses) +153
System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(Type serviceType, Uri[] baseAddresses) +34
System.ServiceModel.Activation.ServiceHostFactory.CreateServiceHost(String constructorString, Uri[] baseAddresses) +538
System.ServiceModel.HostingManager.CreateService(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +1489
System.ServiceModel.HostingManager.ActivateService(ServiceActivationInfo serviceActivationInfo, EventTraceActivity eventTraceActivity) +53
System.ServiceModel.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity) +666
[ServiceActivationException: The service '/Service.svc' cannot be activated due to an exception during compilation. The exception message is: Could not load file or assembly 'CustomUserNameValidator' or one of its dependencies. The system cannot find the file specified..]
System.Runtime.AsyncResult.End(IAsyncResult result) +513025
System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) +182
System.ServiceModel.Activation.ServiceHttpHandler.EndProcessRequest(IAsyncResult result) +12
System.Web.CallHandlerExecutionStep.InvokeEndHandler(IAsyncResult ar) +161
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +128
I have noticed this error only appears due to adding the following into my Web.Config file
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WCFDummyService.CustomUserNameValidator, CustomUserNameValidator" />
</serviceCredentials>
I've modified the value in customUserNamePasswordValidatorType numerous times to try and fix it but the error still comes up or a similar one.
See below for the full Web.Config file.
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.6"/>
<httpRuntime targetFramework="4.6"/>
<pages>
<namespaces>
<add namespace="System.Runtime.Serialization"/>
<add namespace="System.ServiceModel"/>
<add namespace="System.ServiceModel.Web"/>
</namespaces>
</pages>
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="Binding1">
<security mode="Transport">
<message clientCredentialType="UserName" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WCFDummyService.CustomUserNameValidator, CustomUserNameValidator" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https"/>
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
The Code is simply the default WCF Service code you get out of the box when creating a new WCF Service project in Visual Studio and I've just added a new CustomUserNameValidator class.
If you want to see this class, here is the code for it:
Imports System.IdentityModel.Selectors
Public Class CustomUserNameValidator
Inherits UserNamePasswordValidator
Public Overrides Sub Validate(ByVal userName As String, ByVal password As String)
If userName Is Nothing OrElse password Is Nothing Then
Throw New ArgumentNullException()
End If
If Not (userName = "user" AndAlso password = "pass123") Then
Throw New FaultException("Unknown Username or Incorrect Password")
End If
End Sub
End Class
Also, this is all that shows in Properties for the file.
If you can please help with the error, that would be very much appreciated.
You must to be sure that the “Build Action” on the “CustomUserNameValidator.vb” Properties is set to “Compile”.
It seems to be set on “Content” based on what you are describing.
The image shows how you can do that or take a look here:
https://learn.microsoft.com/en-us/visualstudio/ide/build-actions?view=vs-2022
The reason I was getting the problem above was because I needed to set this in the web.config
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="CustomUserNameValidator, App_Code" />
</serviceCredentials>
When I went to the following path on my machine, the only dll was App_Code.tjgywzog.dll so figured the assembly is just App_Code and then it just has to use the class name CustomUserNameValidator since my code is not using namespaces.

wcf data service can work on iisexpress, but not in iis

I wrote a very simple WCF data service. But I find that can't work when I deploy on IIS7.5. It just only can work on IIS Express.
[System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class WcfDataService : DataService<ConfigurationDataEntities>
{
// This method is called only once to initialize service-wide policies.
public static void InitializeService(DataServiceConfiguration config)
{
// TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
// Examples:
config.UseVerboseErrors = true;
config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
// config.SetServiceOperationAccessRule("MyServiceOperation", ServiceOperationRights.All);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
}
}
This is webconfig file
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework5" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="ConfigurationDataEntities" connectionString="metadata=res://*/ConfigurationDataModel.csdl|res://*/ConfigurationDataModel.ssdl|res://*/ConfigurationDataModel.msl;provider=System.Data.SqlServerCe.4.0;provider connection string="data source=|DataDirectory|\ConfigurationData.sdf;password=123;persist security info=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5">
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
<httpRuntime targetFramework="4.5" />
</system.web>
<entityFramework5>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework5>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>
</configuration>
This is the error message:
The server encountered an error processing the request. See server logs for more details.
在 System.Data.Entity.DbContext..ctor(String nameOrConnectionString) 在 WcfDataServiceTest.ConfigurationDataEntities..ctor() 位置 c:\Projects\WcfDataServiceTest\WcfDataServiceTest\ConfigurationDataModel.Context.cs:行号 18 在 invoke_constructor() 在 System.Data.Services.DataService1.CreateDataSourceInstance() 在 System.Data.Services.DataService1.CreateMetadataAndQueryProviders(IDataServiceMetadataProvider& metadataProviderInstance, IDataServiceQueryProvider& queryProviderInstance, BaseServiceProvider& builtInProvider, Object& dataSourceInstance) 在 System.Data.Services.DataService1.CreateProvider() 在 System.Data.Services.DataService1.HandleRequest() 在 System.Data.Services.DataService`1.ProcessRequestForMessage(Stream messageBody) 在 SyncInvokeProcessRequestForMessage(Object , Object[] , Object[] ) 在 System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs) 在 System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc) 在 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc) 在 System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc) 在 System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
Anyone can help me?
WCF helps you:
See server logs for more details.
Configure tracing and see where the exception occurs. Since it's happening in the DbContext constructor, I assume there's something with database access. Check the account the application pool runs under and verify this account can access the database.

Access is denied error accessing WCF service

I have a WCF service migrated to .Net framework 4.5 which is installed in IIS 7.0. I am able to browse the service in a browser. But when i refer the service in say a console application and try to call a method in it, i get the error "Access is denied". Below is the stack trace and web.config settings i am using.
System.ServiceModel.Security.SecurityAccessDeniedException was unhandled
HResult=-2146233087
Message=Access is denied.
Source=mscorlib
StackTrace:
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at ConsoleApplication1.sharedservice.IShared.ProcessRequest(ProcessRequestRequest request)
at ConsoleApplication1.sharedservice.SharedClient.ConsoleApplication1.sharedservice.IShared.ProcessRequest(ProcessRequestRequest request) in c:\Users\vijayara\Documents\Visual Studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\Service References\sharedservice\Reference.cs:line 214
at ConsoleApplication1.sharedservice.SharedClient.ProcessRequest(String RuleName, String RequestMessage, Int32 WaitTime, Int32 ChannelID, Int32 PassThruMode, Int32 MaxResponseSize, Int32 MaxErrorText, Int32& ActualResponseSize, String& Response, Int32& ActualErrorTextSize, String& ErrorText) in c:\Users\vijayara\Documents\Visual Studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\Service References\sharedservice\Reference.cs:line 226
at ConsoleApplication1.Program.Main(String[] args) in c:\Users\vijayara\Documents\Visual Studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs:line 22
at System.AppDomain._nExecuteAssembly(RuntimeAssembly 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.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<compilation debug="false" targetFramework="4.5">
<assemblies>
<add assembly="System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</assemblies>
</compilation>
<authentication mode="Windows" />
<pages controlRenderingCompatibilityVersion="4.0">
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</controls>
</pages>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</modules>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</handlers>
</system.webServer>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="false" />
<services>
<service behaviorConfiguration="Access_Shared_WCF.SharedBehavior" name="Access_Shared_WCF.Shared">
<endpoint address="" binding="basicHttpBinding" contract="Access_Shared_WCF.IShared">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http/localhost/Access_Shared_WCF/Shared" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="Access_Shared_WCF.SharedBehavior">
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
I have similiar issue with WCF. The problem was my appPool account doesn't have rights for generated assemblies by IIS which he use for "shadow copy".
I track it down by using procmon http://technet.microsoft.com/cs-cz/sysinternals/bb896645.aspx with filtering to IIS process name "w3wp.exe" and status to "access denied". Then call service again and check procmon output which files have this issue.
I have access deniend at c:\windows\temp\Microsoft.Generated.dll so I have remove it, call again and new one was generated and all works.
Another option is set "stronger" user identntiy to appPool like LocalService ( appPool -> advanced settings -> Indetitiy -> Predefined account -> Local service )
But solution with procmon is more fun :-)
There are many reasons why you can get this error. The times I have encountered it are when the wcf method is secured to a specific AD role:
Setting the ClientCredentials on the web service client. This can be finicky and doing certain things to the client connection can cause you to lose the credentials.
setting the InnerChannel.OperationTimeout before setting the ClientCredentials will wipe out the ClientCredentials (wierd I know, but I tested it many times).
I believe this may be an issue where the service attempts to use event log to record information. The event log doesn't exist, the Application Pool Identity pseudo-user does not have permission to create an event log. So the suggestions to use a high privileged account side step the issue by allowing it to be created. It may be possible to simply swap the user to a high account run and then switch back to regular.
Alternatively using powershell you can directly create the event log if you know what needs to be created (note it is usually very easy to view the source of any .NET application or dll to locate const string names to the usage)
New-EventLog -source "My.Name.Space" -logname "MyApplicationName"
Source: https://robertgreiner.com/wcf-azure-service-bus-access-is-denied-exception/

Invalid value for key 'attachdbfilename'. setting up a Twitter login for website

Hi I am using Visual studio ultimate 2012 VB.NET
I am trying to set up a new part of my website using Visual studio web forms. I want users to be able to login using there Twitter id. So I created my Twitter login app and inserted my 2 keys "Consumer key" & "Consumer secret" key in to my "AuthConfig.vb" file
I then setup my database using Visual studios "Connect to Database" It connected to my database successfully. I know this because after a message popped up telling me "connection was successful". I was then able on to use visual studio to setup a table on my database.
I confirmed the table was created by logging in to my GoDaddy server and checking the database table was showing, and it was. (So this confirms VS can connect to database.
So this is what happens,
I go to my new page I just created in VS which is this one
http://mastersworldofcomputing.com/basic-learning/Default.aspx
I then click on "Log in" which takes me to this page below.
http://mastersworldofcomputing.com/basic-learning/Account/Login.aspx
I then click on the "Twitter button" we just created (which should let me log in with Twitter id)
I am then taken to the Twitter login page, so I put username and password in and click on "Sign in".
I then get a flash screen come up telling me it is redirecting me to my page but after a couple of seconds it takes me to an error page. Showing info below.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Invalid value for key 'attachdbfilename'.
Source Error:
Line 90: ' User has logged in with provider successfully
Line 91: ' Check if user is already registered locally
Line 92: If OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie:=False) Then
Line 93: RedirectToReturnUrl()
Line 94: End If
Source File: D:\hosting\7560507\html\basic-learning\Account\RegisterExternalLogin.aspx.vb Line: 92
Stack Trace:
[ArgumentException: Invalid value for key 'attachdbfilename'.]
System.Data.SqlClient.SqlConnectionString.VerifyLocalHostAndFixup(String& host, Boolean enforceLocalHost, Boolean fixup) +907262
System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) +4116
System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous) +24
System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(String connectionString, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions) +150
System.Data.SqlClient.SqlConnection.ConnectionString_Set(String value) +59
System.Data.SqlClient.SqlConnection.set_ConnectionString(String value) +4
System.Data.Entity.Internal.LazyInternalConnection.InitializeFromConnectionStringSetting(ConnectionStringSettings appConfigConnection) +122
System.Data.Entity.Internal.LazyInternalConnection.TryInitializeFromAppConfig(String name, AppConfig config) +32
System.Data.Entity.Internal.LazyInternalConnection.Initialize() +131
System.Data.Entity.Internal.LazyInternalConnection.get_ProviderName() +13
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +332
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +18
System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +56
System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() +15
System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +37
System.Linq.Queryable.Where(IQueryable`1 source, Expression`1 predicate) +63
Microsoft.AspNet.Membership.OpenAuth.EFOpenAuthMembershipDatabase.GetMembershipUserName(String providerName, String providerUserId, Boolean updateLastUsed) +891
Microsoft.AspNet.Membership.OpenAuth.OpenAuthManager.Login(HttpContextBase context, String providerName, String providerUserId, Boolean createPersistentCookie) +105
Microsoft.AspNet.Membership.OpenAuth.OpenAuth.Login(String providerName, String providerUserId, Boolean createPersistentCookie) +95
Account_RegisterExternalLogin.ProcessProviderResult() in D:\hosting\7560507\html\basic-learning\Account\RegisterExternalLogin.aspx.vb:92
Account_RegisterExternalLogin.Page_Load(Object sender, EventArgs e) in D:\hosting\7560507\html\basic-learning\Account\RegisterExternalLogin.aspx.vb:48
System.Web.UI.Control.OnLoad(EventArgs e) +91
System.Web.UI.Control.LoadRecursive() +74
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2207
My web.config file look like
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-WebSite17-20121215190635;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-WebSite17-20121215190635.mdf" />
</connectionStrings>
<system.web>
<compilation debug="true" strict="true" explicit="true" targetFramework="4.0" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>
<profile defaultProvider="DefaultProfileProvider">
<providers>
<add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</profile>
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<roleManager defaultProvider="DefaultRoleProvider">
<providers>
<add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</roleManager>
<sessionState mode="InProc" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
</providers>
</sessionState>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
<entityFramework>.
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
Is there anyone who can put me on the right track here so I can get past this. I must of read a hundred threads and got no where. If there is some other info that might be of use let me know
Thanks for reading.

Csla4 and Net4 - ASPNET permission denied on the client

My application works beautifully when the Net version was not Net4. It continues to work perfectly if I create a new Windows 7 based server from scratch. Configure the permissions and away you go.
But (and there is always a but...), my customer has an existing server where the application does not even start when I move to Csla4 and Net4. All the permissions seem to be identical on my "clean" server and on his "legacy but upgraded" server. But the client gets a security error:
System.Security.SecurityException: Request failed.
at System.RuntimeMethodHandle.PerformSecurityCheck(Object obj, RuntimeMethodHandleInternal method, RuntimeType parent, UInt32 invocationFlags)
at System.RuntimeMethodHandle.PerformSecurityCheck(Object obj, IRuntimeMethodInfo method, RuntimeType parent, UInt32 invocationFlags)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.ConstructorInfo.Invoke(Object[] parameters)
at System.Configuration.TypeUtil.InvokeCtorWithReflectionPermission(ConstructorInfo ctor)
at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSectionImpl(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSectionWithRestrictedPermissions(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
at System.Configuration.RuntimeConfigurationRecord.CreateSection(Boolean inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
at System.Configuration.BaseConfigurationRecord.CallCreateSection(Boolean inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader, String filename, Int32 line)
The action that failed was:
Demand
The type of the first permission that failed was:
System.Security.PermissionSet
The demand was for:
<PermissionSet class="System.Security.PermissionSet"
version="1"
Unrestricted="true"/>
The only permitted permissions were:
<PermissionSet class="System.Security.NamedPermissionSet"
version="1"
Name="Internet"
Description="Default rights given to Internet applications">
<IPermission class="System.Security.Permissions.FileDialogPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Access="Open"/>
<IPermission class="System.Security.Permissions.IsolatedStorageFilePermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Allowed="ApplicationIsolationByUser"
UserQuota="1024000"/>
<IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Flags="Execution"/>
<IPermission class="System.Security.Permissions.UIPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
version="1"
Window="SafeTopLevelWindows"
Clipboard="OwnClipboard"/>
<IPermission class="System.Drawing.Printing.PrintingPermission, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
version="1"
Level="SafePrinting"/>
<IPermission class="System.Security.Permissions.MediaPermission, WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
version="1"
Audio="SafeAudio"
Video="SafeVideo"
Image="SafeImage"/>
<IPermission class="System.Security.Permissions.WebBrowserPermission, WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
version="1"
Level="Safe"/>
</PermissionSet>
The method that caused the failure was:
System.Object CreateSectionWithRestrictedPermissions(System.Configuration.RuntimeConfigurationRecord, System.Configuration.FactoryRecord, System.Configuration.SectionRecord, System.Object, System.Configuration.ConfigXmlReader)
I am studying the changes to ASPNET security in Net4, and am thorougly confused.
Has anyone else come across this problem and can point me in the right direction? To repeat, the application works perfectly in a remote environment which I create from scratch, but not in an updated legacy server.
I think that the server is configured for "Medium Trust" in the web.config or so. As far as i know CSLA requires "Full Trust" to clone the business objects.
If that's not the issue u can try to add the server to the client's trusted zone in the windows registory under
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap]
for more information u can browse to http://blogs.technet.com/b/heyscriptingguy/archive/2005/05/02/how-can-i-add-a-site-to-internet-explorer-s-restricted-sites-zone.aspx