Today I thought, Oh, I'll just add some SQL logging to a C# SFTP custom (console) program we have. I didn't write it, and it has perhaps an odd configuration file. It looks like the SQL Performance Counters require a well conformed config file? Add the catch for TypeInitializationException gave some more specific and useful info.
So I am getting the connection string from the app.config file, but to show why I'm frustrated, I hard-coded the connection string below. If I'm providing a full connection string, why would it go to the config file. Apparently SqlPerformanceCounters is picky about these things???
if (!String.IsNullOrWhiteSpace(SqlConnectionString))
{
try
{
WriteLogConsole("SqlConnectionObj - about to open with SqlConnectionString='" +
SqlConnectionString + "'");
//SqlConnection SqlConnectionObj = new SqlConnection(SqlConnectionString);
// Even using a hard-coded connection string I have this issue!
SqlConnection SqlConnectionObj = new SqlConnection("Server=abc;Database=MyDBName;Trusted_Connection=true");
SqlConnectionObj.Open();
WriteLogConsole("SqlConnectionObj - opened successfully");
}
catch (TypeInitializationException ex)
{
WriteLogConsole("TypeInitializationException=" + ex.ToString());
// don't stop, keep going. Logging is nice, but not critical
}
catch (SqlException ex)
{
WriteLogConsole("SqlException=" + ex.ToString());
// don't stop, keep going. Logging is nice, but not critical
}
catch (Exception ex)
{
WriteLogConsole("System.Exception=" + ex.Message);
// don't stop, keep going. Logging is nice, but not critical
}
}
The short version of the error thrown is this:
Unrecognized configuration section
CustomAppSettings/LogExceptionsToFile
Full exception:
SqlConnectionObj - about to open with SqlConnectionString='Server=abc;Database=MyDBName;Trusted_Connection=true'
Exception thrown: 'System.TypeInitializationException' in System.Data.dll
TypeInitializationException=System.TypeInitializationException: The type initializer for 'System.Data.SqlClient.SqlConnection' threw an exception. ---> System.TypeInitializationException: The type initializer for 'System.Data.SqlClient.SqlConnectionFactory' threw an exception. ---> System.TypeInitializationException: The type initializer for 'System.Data.SqlClient.SqlPerformanceCounters' threw an exception. ---> System.Configuration.ConfigurationErrorsException: Configuration system failed to initialize ---> System.Configuration.ConfigurationErrorsException: Unrecognized configuration section CustomAppSettings/LogExceptionsToFile
at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
at System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors)
at System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
--- End of inner exception stack trace ---
at System.Configuration.ConfigurationManager.PrepareConfigSystem()
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at System.Configuration.PrivilegedConfigurationManager.GetSection(String sectionName)
at System.Diagnostics.DiagnosticsConfiguration.GetConfigSection()
at System.Diagnostics.DiagnosticsConfiguration.Initialize()
at System.Diagnostics.DiagnosticsConfiguration.get_SwitchSettings()
at System.Diagnostics.Switch.InitializeConfigSettings()
at System.Diagnostics.Switch.InitializeWithStatus()
at System.Diagnostics.Switch.get_SwitchSetting()
at System.Data.ProviderBase.DbConnectionPoolCounters..ctor(String categoryName, String categoryHelp)
at System.Data.SqlClient.SqlPerformanceCounters..ctor()
at System.Data.SqlClient.SqlPerformanceCounters..cctor()
--- End of inner exception stack trace ---
at System.Data.SqlClient.SqlConnectionFactory..cctor()
--- End of inner exception stack trace ---
at System.Data.SqlClient.SqlConnection..cctor()
--- End of inner exception stack trace ---
at System.Data.SqlClient.SqlConnection..ctor(String connectionString)
at WinSCPWrapperGet.Program.Main(String[] args)
I think it's related to something like this.
What do I have to change to make it happy? I saw other posts about using but I don't have a group. I added everything below in as an attempt to fix the issue. The rest of the program runs fine and uses the config file as desired.
<configuration>
<configSections> <!-- this was not here when I first got the error,
me thinks I need something like to fix this issue -->
<sectionGroup name="CustomAppSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<section name="MyApp.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false"/>
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/>
</startup>
<CustomAppSettings>
<!-- we have many more parms, but here is an example;
each SFTP site can have about 10 config parms -->
<Site1>
<add key="HostName" value="sftp.somesite1.com"/>
<add key="HostPort" value=""/>
</Site1>
<Site2>
<add key="HostName" value="sftp.somesite1.com"/>
<add key="HostPort" value=""/>
</Site2>
... etc...
NOTE: This is in production now, and I am enhancing it. We have maybe a few dozen config files in different scheduled tasks, so I would hate to change all of them, even if they are not designed perfectly.
Found this: https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/performance-counters
It tells us that we can tune the performance counters in the config file:
<system.diagnostics>
<switches>
<add name="ConnectionPoolPerformanceCounterDetail"
value="4"/>
</switches>
</system.diagnostics>
So bottom line, I just need to know how to make my config file work with SQL, even though the connection string in the config is not the issue.
The group is not needed, so far the following has got around the original issue:
<configuration>
<configSections>
<section name="CustomAppSettings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/>
</startup>
<CustomAppSettings>
etc...
Reference: https://blog.ivankahl.com/creating-custom-configuration-sections-in-app-config/
Related
I'm trying new VisualStudio for Mac (Mono 6.0.0.296) with With Microsoft Enterprise Library 6.0.1304. Unfortunatly im not able to use it since an "NotImplementedException" is raised.
I have been using Enterprise Library for many years but in Visual Studio (Windows Env.) and it is great but when i tried to use the same under mono everything seems not working.
After some search i can see that mscorlib.dll for MONO dows not support WindowsIdentity "User" Property.
mscorlib.dll (4.0.0.0 - MONO)
using System.Runtime.InteropServices;
[MonoTODO ("not implemented")]
[ComVisible (false)]
public SecurityIdentifier User {
get {
throw new NotImplementedException ();
}
}
Application:
public static void Main (string [] args)
{
LogWriter logWriter = new LogWriterFactory ().Create ();
Logger.SetLogWriter (logWriter, false);
logWriter.Write ("Application is working", "General", 5, 2000, TraceEventType.Information);
}
App.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
</configSections>
<loggingConfiguration name=""
tracingEnabled="false"
defaultCategory="General"
logWarningsWhenNoCategoriesMatch="false">
<listeners>
<add name="Rolling Flat File Trace Listener"
type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
fileName="RollingFlatFile.log"
footer="----------------------------------"
formatter="Text Formatter"
header="" rollInterval="Day"
traceOutputOptions="DateTime, Timestamp"
filter="All" />
</listeners>
<formatters>
<add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
template="Timestamp: {timestamp(local)}{newline}
Message: {message}{newline}
Category: {category}{newline}
Priority: {priority}{newline}
Severity: {severity}"
name="Text Formatter" />
</formatters>
<categorySources>
<add switchValue="All" autoFlush="true" name="General">
<listeners>
<add name="Rolling Flat File Trace Listener" />
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events">
<listeners>
<add name="Rolling Flat File Trace Listener" />
</listeners>
</allEvents>
<notProcessed switchValue="All" name="Unprocessed Category">
<listeners>
<add name="Rolling Flat File Trace Listener" />
</listeners>
</notProcessed>
<errors switchValue="All" name="Logging Errors & Warnings">
<listeners>
<add name="Rolling Flat File Trace Listener" />
</listeners>
</errors>
</specialSources>
</loggingConfiguration>
</configuration>
Error tracked into the file:
Timestamp: 12/07/2019 16:36:11
Message: Processing of the message failed. See summary information below for more information. Should this problem persist, stop the service and check the configuration file(s) for possible error(s) in the configuration of the categories and sinks.
Summary for Enterprise Library Distributor Service:
-->
Message:
Timestamp: 12/07/2019 14:36:11
Message: Application is working
Category: General
Priority: 5
EventId: 2000
Severity: Information
Title:
Machine: MacBook-Pro-di-John
App Domain: F.B.Library.exe
ProcessId: Unable to read intrinsic property. Error message: GetCurrentProcessId
Process Name: Unable to read intrinsic property. Error message: GetModuleHandle
Thread Name:
Win32 ThreadId:Unable to read intrinsic property. Error message: GetCurrentThreadId
Extended Properties:
--> MachineName: MacBook-Pro-di-John
--> TimeStamp: 12/07/2019 14:36:11
--> FullName: Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
--> AppDomainName: F.B.Library.exe
--> WindowsIdentity: jfk
Exception Information Details:
Exception Type: System.NotImplementedException
Message: The method or operation is not implemented.
Data: System.Collections.ListDictionaryInternal
TargetSite: System.Security.Principal.WindowsIdentity GetCurrent(Boolean)
HelpLink: NULL
Source: mscorlib
HResult: -2147467263
StackTrace Information Details:
at System.Security.Principal.WindowsIdentity.GetCurrent (System.Boolean ifImpersonating) [0x00000] in /Users/builder/jenkins/workspace/build-package-osx-mono/2019-02/external/bockbuild/builds/mono-x64/mcs/class/corlib/System.Security.Principal/WindowsIdentity.cs:165
at Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter.RevertExistingImpersonation () [0x0000f] in :0
at Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter.ProcessLog (Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry log, System.Diagnostics.TraceEventCache traceEventCache) [0x00000] in :0
at Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter+<>c__DisplayClass13.b__12 () [0x0007f] in :0
From The log, you can clearly see that System.Security.Principal.WindowsIdentity.GetCurrent breaks the rule...
Could you Kindly help me on this?
Did anyone try to use Enterprise Library with Mono on MacOS?
Is somewhere present a workaround?
Thanks a lot for your help and time.
Regards,
finally i have managed such situation.
First of all, thanks to all comments, those helped me lot of with resolution.
Basically, i had to change a part of MEL 6 code and then i could use it without issue.
As previously suggested by #SushiHangover, i took MEL 6 source code and i started to analyze... i have fould a part of the code that was calling SecurityIdentifier User inside mscorlib.dll
What i did is:
- download MEL 6 source code
- open it with Visual Studio for MAC
- delete all Test projects and files not supported by the engine
- compile till everything is fine
Once you have your prj compiled, find and comment "Impersonation" section of the below section:
private void ProcessLog(LogEntry log, TraceEventCache traceEventCache)
{
// revert any outstanding impersonation
//using (RevertExistingImpersonation())
//{
var items = new ContextItems();
items.ProcessContextItems(log);
var matchingTraceSources = GetMatchingTraceSources(log);
var traceListenerFilter = new TraceListenerFilter();
foreach (LogSource traceSource in matchingTraceSources)
{
traceSource.TraceData(log.Severity, log.EventId, log, traceListenerFilter, traceEventCache, ReportExceptionDuringTracing);
}
//}
}
Code Sample Image Link
After that, recompile, use compiled dll into your own project and it will finally work.
If you have any further question or dubt, please let me know and i will be happy to reply.
Have a great working day,
Regards,
Florin
I created a SQL Server database in Visual Studio 2013.
I have a problem when I am trying to create a new SqlConnection object. The same code worked yesterday, but now I have some problem. I also added the SQLException but I can't reach this code
try
{
string connectionString = ConfigurationManager.ConnectionStrings["MyKey"].ConnectionString;
SqlConnection sqlConnection = new SqlConnection(connectionString);
sqlConnection.Open();
}
catch (System.Data.SqlClient.SqlException sqlException)
{
System.Windows.Forms.MessageBox.Show(sqlException.Message);
}
Application.Run(new LoginForm());
SqlConnection did not work. This is the exception. I don't know what it is wrong because it did work before
System.TypeInitializationException was unhandled
HResult=-2146233036
Message=The type initializer for 'System.Data.SqlClient.SqlConnection' threw an exception.
Source=System.Data
TypeName=System.Data.SqlClient.SqlConnection
StackTrace:
at System.Data.SqlClient.SqlConnection..ctor(String connectionString)
InnerException: System.InvalidOperationException
HResult=-2146233079
Message=Failed to read the configuration section for enclave providers. Make sure the section is correctly formatted in your application configuration file.
Error Message: Configuration system failed to initialize
Source=System.Data
StackTrace:
at System.Data.SqlClient.SqlConnection..cctor()
InnerException: System.Configuration.ConfigurationErrorsException
HResult=-2146232062
Message=Configuration system failed to initialize
Source=System.Configuration
BareMessage=Configuration system failed to initialize
Line=0
InnerException: System.Configuration.ConfigurationErrorsException
HResult=-2146232062
Message=Root element is missing.
Source=System.Configuration
BareMessage=Root element is missing.
Line=0
InnerException: System.Xml.XmlException
HResult=-2146232000
Message=Root element is missing.
Source=System.Xml
app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="MercazApp.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<connectionStrings>
<add name="MyKey"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\Taekwon-Do\MercazApp\DB\LoginDb.mdf;Integrated Security=True;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<userSettings>
<MercazApp.Properties.Settings>
<setting name="username" serializeAs="String">
<value />
</setting>
<setting name="password" serializeAs="String">
<value />
</setting>
<setting name="name" serializeAs="String">
<value />
</setting>
</MercazApp.Properties.Settings>
</userSettings>
</configuration>
Root element is missing. (C:\Users\alexs\AppData\Local\MercazApp\MercazApp.exe_Url_ka1yz14eyfxx0cttxywliv5ag3ke50uk\1.0.0.0\user.config)
seems relevant. Likely, that file changed to something bad. Inspect it.
I can't believe you! I renamed that folder to old and after building it was created again and now it works!! I spent 4 hours with that. Where did you see the error and why it caused?
I simply read the exception in full. Exceptions contain a lot of information. It is worth acquiring a habit to fully read, understand and interpret it.
try putting the connection string directly into the code in place of the line that says:
string connectionString = ConfigurationManager.ConnectionStrings["MyKey"].ConnectionString;
This will tell you whether it's a web.config issue. Since it started playing up suddenly, its quite likely that some config change in IIS triggered the web config to be updated.
also worth checking whther there are any other .config files in different folders (including app_data) if you find one with no content, just delete it.
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
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
I am trying to create an AppFabric cache client which is a console application. But receives the error Error in client configuration file while creating new instance of DataCacheFactory. Connection settings are provided in App.Config file as described in msdn.
Code
static void Main(string[] args)
{
try
{
DataCacheFactory dFact = new DataCacheFactory();
DataCache myCache = dFact.GetCache("default");
myCache.Remove("pValue");
myCache.Add("pValue", "Test Cache Value");
Console.WriteLine(string.Format("{0}", "Added to cache. Press any key to read...."));
Console.ReadLine();
Console.WriteLine(string.Format("{0}", myCache.Get("pValue").ToString()));
Console.ReadLine();
}
catch (Exception Ex)
{
throw new System.Exception(Ex.ToString());
}
}
}
App.Config file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<configSections>
<section name="dataCacheClient"
type="Microsoft.ApplicationServer.Caching.DataCacheClientSection,
Microsoft.ApplicationServer.Caching.Core,Version=1.0.0.0,Culture=neutral,
PublicKeyToken=31bf3856ad364e35"
allowLocation="true"
allowDefinition="Everywhere" />
</configSections>
<dataCacheClient>
<hosts>
<host name="localhost" cachePort="22233"/>
</hosts>
</dataCacheClient>
</configuration>
Exception
Microsoft.ApplicationServer.Caching.DataCacheException:
ErrorCode<ERRCMC0003>:SubStatus<ES0001>:Error in client configuration file. --->
System.Configuration.ConfigurationErrorsException: Configuration system failed to
initialize --->
System.Configuration.ConfigurationErrorsException:
Only one <configSections> element allowed per config file
and if present must be the first child of the root <configuration> element.
(DistributedInMemory.vshost.exe.Config line 7)
at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
at
System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors)
at System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
--- End of inner exception stack trace ---
at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
at System.Configuration.ClientConfigurationSystem.PrepareClientConfigSystem(String sectionName)
at
System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at Microsoft.ApplicationServer.Caching.ClientConfigReader..ctor()
at Microsoft.ApplicationServer.Caching.DataCacheFactoryConfiguration.Initialize(String path)
--- End of inner exception stack trace ---
at Microsoft.ApplicationServer.Caching.ConfigFile.ThrowException(Int32 errorCode, Exception e)
at Microsoft.ApplicationServer.Caching.DataCacheFactoryConfiguration.Initialize(String path)
at Microsoft.ApplicationServer.Caching.DataCacheFactory..ctor()
at DistributedInMemory.Program.Main(String[] args) in DistributedInMemory\Program.cs:line 16
Any idea why this error happening....Thanks.
You need to put the configSections element immediately after configuration element.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!-- Put config sections here -->
<configSections>
<!-- Put dataCache client section first -->
<section name="dataCacheClient" type="Microsoft.ApplicationServer.Caching.DataCacheClientSection, Microsoft.ApplicationServer.Caching.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" allowLocation="true" allowDefinition="Everywhere" />
<!-- Then other sections... -->
</configSections>