Getting a strange exception with the MS Exception Handling Block - c#

I've created a very basic Logging block and Exception Handling block. In my code, I went to go test the Exception Handling (I know the Logging block works) with the following:
public void RunScriptClean()
{
try
{
throw new FileNotFoundException();
}
catch (FileNotFoundException ex)
{
var b = ExceptionPolicy.HandleException(ex, "Logging Policy");
if (b)
throw;
}
}
However, on the very first line of the catch block, I get this long winded exception and my application crashes:
Exception occured: The current build operating (build key Build Key [Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicyImpl, Logging Policy]) failed: The type 'Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' cannot be resolved. Please verify the spelling is correct or that the full type name is provided. (Strategy type ConfiguredObjectStrategy, index 2).
I have absolutely no idea what it's referring to when it says the type cannot be resolved. I've added references to Microsoft.Practices.EnterpriseLibrary.Common/ExceptionHandling/Logging and Ms.Practices.ObjectBuilder2. This one class has using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling included at the top.
Added a screenshot of the configuration tool looking at my AppConfig file:
I'm sure I'm missing something basic, but it's tough to find a tutorial for EAB 4.1-- CodeProject has a lot for the original versions but I couldn't make much of them...
Edit I tried creating a new Formatter and naming it TextExceptionFormatter but that didn't change anything. Wasn't sure if maybe some how the FormatterType property on my Logging Handler was tied to that node.
And the actual block of XML from App.config:
<exceptionHandling>
<exceptionPolicies>
<add name="Logging Policy">
<exceptionTypes>
<add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="NotifyRethrow" name="Exception">
<exceptionHandlers>
<add logCategory="General" eventId="100" severity="Error" title="Enterprise Library Exception Handling"
formatterType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.TextExceptionFormatter, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
priority="0" useDefaultLogger="false" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.LoggingExceptionHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="Logging Handler" />
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
</exceptionPolicies>
</exceptionHandling>
I found this SO question: Cannot resolve type runtime error after registering the Enterprise Library into the GAC but even after changing the Version segment of the fullName attribute my app still behaves the same.

Alright, I was able to find a sample application that used the Logging handlers. Turns out I needed a reference to ExceptionHandling.Logging:
Microsoft.Practices.EnterpriseLibrary.Common
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging ****
Microsoft.Practices.EnterpriseLibrary.Logging
Microsoft.Practices.ObjectBuilder2
Where as I only had a references to:
Microsoft.Practices.EnterpriseLibrary.Common
Microsoft.Practices.EnterpriseLibrary.ExceptionHandling
Microsoft.Practices.EnterpriseLibrary.Logging
Microsoft.Practices.ObjectBuilder2

Related

Cannot get NServiceBus to not throw exceptions (MessageQueueException, SqlException, TimeoutPersisterReceiver)

I have a very frustrating NServiceBus problem that I cannot seem to figure out. I am hoping that you guys can shed some light on the situation.
I am currently using NServiceBus.Core v5.0 and NServiceBus.Host v6.0 and running it in Unobtrusive Mode.
It seems that no matter what configuration I use, I always get some kind of error. I will start with the configuration that produces the least problems:
Case 1 - Using custom assembly scanning:
public void Customize(BusConfiguration configuration)
{
var endpointName = typeof(EndpointConfig).Namespace;
configuration.SetUniqueHostId(endpointName);
configuration.UseSerialization<JsonSerializer>();
configuration.UsePersistence<NHibernatePersistence, StorageType.Outbox>();
configuration.AssembliesToScan(new List<Assembly>
{
GetType().Assembly,
typeof(ICustomCommand).Assembly
});
configuration.Conventions()
.DefiningCommandsAs(type => typeof(ICustomCommand).IsAssignableFrom(type));
configuration.EnableDurableMessages();
configuration.EnableInstallers();
var container = ContainerInitializer.Container;
configuration.UseContainer<AutofacBuilder>(c => c.ExistingLifetimeScope(container));
}
The issues I have noticed here are the following:
When starting the NServiceBus host application and the persistence SQL database does not yet exist, no exception is thrown saying that the database cannot be found (it does in case 2).
I keep getting the following exception:
NServiceBus.Timeout.Hosting.Windows.TimeoutPersisterReceiver Failed to fetch timeouts from the timeout storage
Which ultimately results in the application crashing because when this error occurs too many times, ServiceBus decides that enough is enough and just throws a fatal exception.
Besides the issues above, the application runs perfectly receiving and processing messages... until the fatal exception occurs
Now, this one is a bit more difficult:
Case 2 - Using default assembly scanning:
public void Customize(BusConfiguration configuration)
{
var endpointName = typeof(EndpointConfig).Namespace;
configuration.SetUniqueHostId(endpointName);
configuration.UseSerialization<JsonSerializer>();
configuration.UsePersistence<NHibernatePersistence, StorageType.Outbox>();
// !! DISABLED !!
// configuration.AssembliesToScan(new List<Assembly>
// {
// GetType().Assembly,
// typeof(ICustomCommand).Assembly
// });
configuration.Conventions()
.DefiningCommandsAs(type => typeof(ICustomCommand).IsAssignableFrom(type));
configuration.EnableDurableMessages();
configuration.EnableInstallers();
var container = ContainerInitializer.Container;
configuration.UseContainer<AutofacBuilder>(c => c.ExistingLifetimeScope(container));
}
In this case the following issues occur:
When the persistence SQL database does not yet exist:
When starting the NServiceBus host application and the SQL database does not exist, an exception is throw - Expected behavior (This is positive)
After creating the persistence SQL database:
ServiceControl.Plugin.Nsb5.Heartbeat.Heartbeats|Unable to send heartbeat to ServiceControl:
NServiceBus.Unicast.Queuing.QueueNotFoundException: Failed to send message to address: [Particular.ServiceControl#MYPCNAME]
Exception thrown: 'System.Messaging.MessageQueueException' in System.Messaging.dll
Additional information: External component has thrown an exception.
2017-09-15 16:25:45.6743|Warn|NServiceBus.Unicast.Messages.MessageMetadataRegistry|Message header 'SharedTemp.Interfaces.ICustomCommand'
was mapped to type 'SharedTemp.Interfaces.ICustomCommand' but that type was not found in the message registry [...]
Exception thrown: 'System.Exception' in NServiceBus.Core.dll
Additional information: Could not find metadata for 'Newtonsoft.Json.Linq.JObject'.
Now, exceptions 3 and 4 are particularly (no pun intended) odd since the NServiceBus documentation states:
By default all assemblies in the endpoint bin directory are scanned to find types implementing its interfaces so that it can configure them automatically.
And the "Newtonsoft.Json" and my "SharedTemp dll's" are indeed in the BIN folder, but NServiceBus does not seem to find them. As for point 1: NServiceBus does not create that queue for me, but it creates all the other queues that I need.
Finally the always requested app.config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="MasterNodeConfig" type="NServiceBus.Config.MasterNodeConfig, NServiceBus.Core"/>
<section name="MessageForwardingInCaseOfFaultConfig" type="NServiceBus.Config.MessageForwardingInCaseOfFaultConfig, NServiceBus.Core"/>
<section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core"/>
<section name="AuditConfig" type="NServiceBus.Config.AuditConfig, NServiceBus.Core"/>
</configSections>
<appSettings>
<add key="NServiceBus/Persistence/NHibernate/dialect" value="NHibernate.Dialect.MsSql2012Dialect"/>
<add key="NServiceBus/Outbox" value="true"/>
</appSettings>
<MessageForwardingInCaseOfFaultConfig ErrorQueue="error"/>
<UnicastBusConfig>
<MessageEndpointMappings />
</UnicastBusConfig>
<AuditConfig QueueName="audit"/>
<connectionStrings>
<add name="NServiceBus/Persistence" connectionString="Server=(LocalDB)\v11.0;Initial Catalog=NServiceBus;Integrated Security=true"/>
</connectionStrings>
<system.web>
<membership defaultProvider="ClientAuthenticationMembershipProvider">
<providers>
<add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri=""/>
</providers>
</membership>
<roleManager defaultProvider="ClientRoleProvider" enabled="true">
<providers>
<add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400"/>
</providers>
</roleManager>
</system.web>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
</startup>
<MasterNodeConfig Node="localhost"/>
</configuration>
Does anyone have an idea about any of this?
After a lot of searching I finally found the problem!
First of all I was using a in-house NuGet package that was supposed to help me with configuring NServiceBus. The package worked fine for other projects, but for mine not so well, since I was using JsonSerialization instead of the default XML serialization.
The first problem with the package is that it used the "INeedInitialization" interface to configure NServiceBus. In my code I would then call "IConfigureThisEndpoint" to enable the JsonSerialization. The issue here was, that when starting the NServiceBus host, it would fail to find the NewtonSoft.Json library. If I then added custom assembly scanning to my own configuration code, it would not trigger "INeedInitialization", causing an incomplete/incorrect configuration.
I assume it could not load the NewtonSoft.Json library because scanning was triggered in the code/namespace of the package? Maybe #Sean Farmer can answer this?
The second problem with the package is that it would add connection strings to the app.config, one for "NServiceBus/Persistence" and one for "NServiceBus/Persistence/NHibernate/Saga". I am not using Saga, so the connection string for that was not needed. Initially this was not a problem since I caught it the first time, but I completely forgot about it after reinstalling the package. Removing this again also seemed to make NServiceBus happier.
So, what ended up working? I removed the package and did the configuration myself with the following result:
public void Customize(BusConfiguration configuration)
{
var endpointName = typeof(EndpointConfig).Namespace;
configuration.UniquelyIdentifyRunningInstance().UsingCustomIdentifier(endpointName);
configuration.EnableOutbox();
configuration.UsePersistence<NHibernatePersistence>();
configuration.Transactions().DefaultTimeout(TimeSpan.FromMinutes(5.0));
configuration.UseSerialization<JsonSerializer>();
configuration.Conventions()
.DefiningCommandsAs(type => typeof(ICustomCommand).IsAssignableFrom(type));
configuration.EnableDurableMessages();
configuration.EnableInstallers();
var container = ContainerInitializer.Container;
configuration.UseContainer<AutofacBuilder>(c => c.ExistingLifetimeScope(container));
}
#Sean: Thank you for allowing me to contact you. Luckily it was not necessary
#Mike: Thank you for the input

Occasional error: The type 'HttpRequestMessage' is defined in an assembly that is not referenced

I am working on an old WebForms project.
Occasionally it won't build
The type 'HttpRequestMessage' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Net.Http, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
The exception above is thrown on Request on this line
public class MyController : ApiController
{
[System.Web.Http.HttpPost]
public string Test()
{
string data = Request.Content.ReadAsStringAsync().Result;
}
}
To be able to run the website, I simply have to Rebuild Solution (without changing anything at all).
Any idea what may be causing it?
Add below code in you web.config
<configuration>
<system.web>
<compilation>
<assemblies>
<add assembly="System.Net.Http, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</assemblies>
</compilation>
</system.web>
</configuration>

How can I modify the Exception Handling values from Web.config

I'm starting to use the Exception Handling, in my case I use the configuration manager, creating a Null Policie with a Replace Handler, in this case the message that replace to this exception is the next:"Exists some null values: "...my web.config:
<exceptionHandling>
<exceptionPolicies>
<add name="Null Policies">
<exceptionTypes>
<add name="All Exceptions" type="System.Exception, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
postHandlingAction="ThrowNewException">
<exceptionHandlers>
<add name="Replace Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ReplaceHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
exceptionMessage="Exists some null values" replaceExceptionType="System.NullReferenceException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</exceptionHandlers>
</add>
</exceptionTypes>
</add>
</exceptionPolicies>
</exceptionHandling>
In a piece of my code that I know that throw a NullReferenceException I want to add the value that throws this exception, and append to the message previous implemented on the configuration:
try
{
string theValue = anotherThing //this piece of code throw a NullReferenceException
}
catch(Exception ex)
{
if (exManager.HandleException(ex,"Null Policies")) throw; //add 'theValue' to the new Exception
return "";
}
Researching I found about the Configuration class to access to the web.config...and I don't know how to access to this particular piece of the XML -> exceptionPolicies<- and modify the property like: exceptionMessage= "Exists some null values "+ theValue;
Hope you can help me...

Enterprise library exception: Activation error occured while trying to get instance of type ICacheManager, key?

Using .net 3.5 and Enterprise library 5.0.
From my research, I found a similar issue here:
Activation error occured while trying to get instance of type ICacheManager, key "Cache Manager" *** this solution did not fix my issue.
I can't seem to figure it out, my config should be set up correctly, but keep getting the exception? Anyone have similar issues?
I made the suggestion to add cacheManager and reference when I call the cache manager:
using Microsoft.Practices.EnterpriseLibrary.Caching;
using Microsoft.Practices.EnterpriseLibrary.Caching.Expirations;
.....
....
ICacheManager cm = CacheFactory.GetCacheManager("TrackingCacheManager");
The App.config:
<configuration>
<configSections>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
<section name="cachingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.CacheManagerSettings, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
</configSections>
<cachingConfiguration defaultCacheManager="TrackingCacheManager">
<cacheManagers>
<add name="TrackingCacheManager" type="Microsoft.Practices.EnterpriseLibrary.Caching.CacheManager, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
expirationPollFrequencyInSeconds="120" maximumElementsInCacheBeforeScavenging="1000"
numberToRemoveWhenScavenging="10" backingStoreName="NullBackingStore" />
</cacheManagers>
<backingStores>
<add type="Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.NullBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="NullBackingStore" />
</backingStores>
</cachingConfiguration>
<dataConfiguration defaultDatabase="ConnectionString" />
<connectionStrings>
<add name="ConnectionString" connectionString="server=AFS7BCBRNGQ5O0\DEVELOPMENT;database=EITC_RTS;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
My references:
My guess is that you've setup this configuration in an App.config for your Domain project. But your main project has it's own config file which this configuration must be copied into.
So for example, if your main project was a webapp, then it would have a web.config. The caching configuration you have added to the App.config of the Domain project is not used at runtime. The configuration being used is from main project's config, in this example the web.config.
Copy your Caching configuration from the Domain App.Config to the main config file and it will work.
I have done silly mistake, but after read above, understand the issue. This is my vb.net code which give me the above error.
Imports System.Collections
'Imports System.Configuration
Public Class DatabaseLogic
Public ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("db").ToString()
Public Function ServerDataMagic(StoredProcedure As String, PDMdata As Hashtable) As DataSet
Dim db As Database = DatabaseFactory.CreateDatabase(ConnectionString ) 'Here I am getting error.
Using cmd As DbCommand = db.GetStoredProcCommand(StoredProcedure)
Try
db.DiscoverParameters(cmd)
Catch discover_ex As Exception
End Try
and in web.config entry is
<add name="db" connectionString="Database=Dbname;Server=SERVER;uid=sa;pwd=sa#1234" providerName="System.Data.SqlClient" />
After read just get the issue is CreateDatabase method wants a config entry key as a string and I was given the exact connection string via config entry access. This is my updated code.
Dim db As Database = DatabaseFactory.CreateDatabase("db") 'Here I changed the config entry key
I was post to somebody help.

Using a profile property of type List in .NET Membership

I'm working on a C# Webservice that needs to provide authentication as well as roles and profile management. I need each profile to have a property of type List. The profile section in the web.config looks like this:
<profile defaultProvider="MyProfileProvider" enabled="true">
<providers>
<remove name="MyProfileProvider"/>
<add connectionStringName="MySqlServer"
applicationName="MyApp"
name="MyProfileProvider"
type="System.Web.Profile.SqlProfileProvider" />
</providers>
<properties>
<add name="Websites" type="System.Collections.Generic.List<String>" serializeAs="Binary"/>
</properties>
</profile>
However, when I start the webservice and try to access that property it returns the following error:
System.Configuration.ConfigurationErrorsException: Attempting to load this property's type resulted in the following error: Could not load type 'System.Collections.Generic.List<String>'. (C:\Projects\MyProject\web.config line 58) ---> System.Web.HttpException: Could not load type 'System.Collections.Generic.List<String>'.
Is there a way to use a generic collection for this purpose?
After more searching I finally managed to find the answer. The solution is to use the type name qualified by its namespace. This means that for my issue I used:
<add name="Websites" type="System.Collections.Generic.List`1[System.String]" serializeAs="Binary"/>
I also found out that it is also possible to specify classes defined in other assemblies. To use those you need the assembly-qualified name. For example, that would be "System.Collections.Generic.HashSet`1[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" for a Hashset of Strings.

Categories

Resources