VB My.Settings Configuration Error Exception - vb.net

I am creating a form where I want to save a list of values to My.Settings. In the form, changes will be made to the list and when I close the form, the updated list will be saved to the settings. The next time I start the form my list will get the values from My.Settings.
This is what I have done so far.
To load the list from the settings:
Dim fl As New List(Of String)
For Each Item As String In My.Settings.foodlist
fl.Add(Item)
Next
And then to save the list into settings on closing the form:
My.Settings.foodlist.Clear()
For Each Item As String In fl
My.Settings.foodlist.Add(Item)
Next
My.Settings.Save()
Form1.Close()
In my project settings, I have defined foodlist as a system.collection.specialized.stringcollection. The scope is set to user, and the value is currently blank.
However, when I run, I receive an error which says System.Configuration.ConfigurationErrorsException: 'Configuration system failed to initialize'
ConfigurationErrorsException: Unrecognized configuration section system.diagnostics. (C:\Users\samsj\Downloads\EatWhat_webversion\WinFormsApp_22Feb\bin\Debug\net6.0-windows\EatWhat_webver.dll.config line 5)
In particular, the line that seems to have an issue is
Return CType(Me("foodlist"), Global.System.Collections.Specialized.StringCollection)
What am I doing wrong?

I managed to solve this after looking through suggestions from another forum. I went to my dll.config file and deleted the entire system.diagnostics code:
<system.diagnostics>
<sources>
<!-- This section defines the logging configuration for My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog"/>
<!-- Uncomment the below section to write to the Application Event Log -->
<!--<add name="EventLog"/>-->
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information" />
</switches>
<sharedListeners>
<add name="FileLog"
type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
initializeData="FileLogWriter"/>
<!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
<!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
</sharedListeners>
</system.diagnostics>
I have absolutely no idea why deleting this code works, since I assumed that this is a default code.

Related

How can read config file in Net5?

I using Vb.net , FW: Net5
This is my app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ConnectString" value="DB/Sample.db3" />
</appSettings>
<system.diagnostics>
<sources>
<!-- This section defines the logging configuration for My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog"/>
<!-- Uncomment the below section to write to the Application Event Log -->
<!--<add name="EventLog"/>-->
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information" />
</switches>
<sharedListeners>
<add name="FileLog"
type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
initializeData="FileLogWriter"/>
<!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
<!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
</sharedListeners>
</system.diagnostics>
</configuration>
I install "System.Configuration.ConfigurationManager" from Nuget
I had try get config as:
Dim str = System.Configuration.ConfigurationManager.AppSettings("ConnectString")
But it occur exception error:
Configuration system failed to initialize
How can read app.config in VB Net5?
I tried using an app.config file in a .NET 5.0 app and I got the same exception. Unlike you, I looked a bit further and saw that it also said that it encountered an unknown section, i.e. system.diagnostics. I then commented out the <system.diagnostics> element in my config file and it worked as expected. I'm not sure what you would do if you actually needed to use that section but it doesn't look like you do so it shouldn't be a problem to comment it out or delete it.

Connection string error between projects with EF

My solution exits out of 3 Projects:
SP_Class_Library contains my EF model
SP_Control_Library is a class library that contains all my custom and
user controls
SP_EF_TEST is my Form Application
I created a custom control cc_User_DropDown with the following code
Protected Overrides Sub OnCreateControl()
MyBase.OnCreateControl()
LoadUsers()
End Sub
Private Sub LoadUsers()
Dim UserList As List(Of SP_User) = Nothing
UserList = (From c In ent.SP_User
Where c.usr_Active = True
Select c
Order By c.usr_Name).ToList
Dim blank As New SP_User
blank.usr_ID = 0
blank.usr_Name = "Please select a user..."
UserList.Insert(0, blank)
Me.DisplayMember = "usr_Name"
Me.ValueMember = "usr_ID"
Me.DataSource = UserList
End Sub
The problem comes when I try and add the custom control to either u_Users or Form1 I get the error:
If I comment the code and build I can add the control, but as soon as I uncomment the code and build I get the following:
I have tried suggestions that say I must add the app.config to all the projects, Copy the connectionstring to all the .config files and remove the .config file from the dll and add it to the Form Application but it does not work.
Here is my app.config file:
<?xml version="1.0" encoding="utf-8" ?>
<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=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<system.diagnostics>
<sources>
<!-- This section defines the logging configuration for My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog" />
<!-- Uncomment the below section to write to the Application Event Log -->
<!--<add name="EventLog"/>-->
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information" />
</switches>
<sharedListeners>
<add name="FileLog" type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" initializeData="FileLogWriter" />
<!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
<!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
</sharedListeners>
</system.diagnostics>
<connectionStrings>
<add name="SPEntities" connectionString="metadata=res://*/SP_Model1.csdl|res://*/SP_Model1.ssdl|res://*/SP_Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost\SPDEV;initial catalog=SP;persist security info=True;user id=sa;password=xxx;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v12.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>

WCF trace logs all exceptions except System.Exception itself

I've made a basic WCF Service Library and created one method called GetResult(). I've set up WCF trace logging to log Warnings to a file. This is correctly logging all exceptions thrown except, for some strange reason, System.Exception itself. For instance, this logs fine:
[OperationContract]
public string GetResult()
{
// exception is logged in file:
throw new DivideByZeroException();
// or
// throw new ApplicationException();
// or
// throw new FileNotFoundException();
// or anything else, it seems
}
But this does not log anything:
[OperationContract]
public string GetResult()
{
// exception is not logged!
throw new Exception();
// or
// throw new Exception("my message");
}
In the latter case, the log file doesn't even get created. If it already exists then it doesn't get written to.
What am I doing wrong?
Here is my app.config setup:
<system.diagnostics>
<sources>
<source name="System.ServiceModel.MessageLogging" switchValue="Warning">
<listeners>
<add name="ServiceModelTraceListener" />
</listeners>
</source>
<source name="System.ServiceModel" switchValue="Warning">
<listeners>
<add name="ServiceModelTraceListener" />
</listeners>
</source>
<source name="System.Runtime.Serialization" switchValue="Warning">
<listeners>
<add name="ServiceModelTraceListener" />
</listeners>
</source>
</sources>
<trace autoflush="true" />
<sharedListeners>
<add initializeData="c:\temp\logs\wcf.svclog"
type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
name="ServiceModelTraceListener"
traceOutputOptions="Timestamp" />
</sharedListeners>
</system.diagnostics>

System.diagnostics logging issue + Wix application name change

In my application i have configured the Trace listener as below
"HelloWorld" is my AssemblyName and Namespace
<system.diagnostics>
<sources>
<source name="DebugCategory" switchName="DebugSwitch" switchType="System.Diagnostics.SourceSwitch">
<listeners>
<remove name="Default"/>
<!-- Add the listeners below -->
<add name="LogFile"/>
</listeners>
</source>
</sources>
<sharedListeners>
<add name="Console" type="System.Diagnostics.ConsoleTraceListener" initializeData="true"/>
<add name="LogFile" type="HelloWorld.Diagnostics.FileLogTraceListener, HelloWorld" initializeData="HelloWorld.log" traceOutputOptions="DateTime" cycle="Month"/>
</sharedListeners>
While creating an installer using WIX, in my WIX file i will make the Target exe file from "HelloWorld.exe" to "MyWorld.exe" as below
<Component Id="MyWorld.exe" Guid="*">
<File Id="MyWorld.exe" Name="MyWorld.exe"
DiskId="1" Source="HelloWorld.exe" />
<Shortcut Id="HelloWorld.menu.exe" Name="Hello world application" Directory="McnMenu" Advertise="yes" WorkingDirectory="INSTAL32LLOCATION" />
</Component>
Since there is change in the EXE name, Tracelistener is not creating a log file.
Target name should be "Myworld.exe", If i revert the File element to
<File Id="HelloWorld.exe" Name="HelloWorld.exe" />
it works well
Can any one help me.
In this line of your .config file:
<add name="LogFile" type="HelloWorld.Diagnostics.FileLogTraceListener, HelloWorld" initializeData="HelloWorld.log" traceOutputOptions="DateTime" cycle="Month"/>
You have type="HelloWorld.Diagnostics.FileLogTraceListener, HelloWorld". That is a reference to a class in an assembly. The assembly name (the name of the file) is the part after the comma. Therefore your .config file requires the assembly (the executable in your case) to be named "HelloWorld".
To fix you can either leave the file name HelloWorld.exe (as you found) or change the .config file like so:
<add name="LogFile" type="HelloWorld.Diagnostics.FileLogTraceListener, MyWorld" initializeData="HelloWorld.log" traceOutputOptions="DateTime" cycle="Month"/>
Notice the MyWorld in the type after the comma.

WCF tracing in code does not follow MessageLogging settings

I need to use WCF tracing in my application but it needs to be controlled from code as much as possible.
IT was suggested that I install the following sections in my app.config file:
<configuration>
<system.serviceModel>
<diagnostics>
<messageLogging
maxMessagesToLog="100"
logEntireMessage="true"
logMessagesAtServiceLevel="true"
logMalformedMessages="true"
logMessagesAtTransportLevel="true">
</messageLogging>
</diagnostics>
</system.serviceModel>
<system.diagnostics>
<sources>
<source name="System.ServiceModel" >
<listeners>
<add type="System.Diagnostics.DefaultTraceListener" name="dummy"/>
</listeners>
</source>
</sources>
</system.diagnostics>
</configuration>
Then the following code could be used to get the trace running as needed:
BindingFlags privateMember = BindingFlags.NonPublic | BindingFlags.Instance;
BindingFlags privateStaticMember = privateMember | BindingFlags.Static;
Type type = Type.GetType("System.ServiceModel.DiagnosticUtility, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
MethodInfo[] mi = type.GetMethods(privateStaticMember);
// invoke InitializeTracing
object diagnosticTrace = mi.FirstOrDefault(e => e.Name == "InitializeTracing").Invoke(null, null);
if (diagnosticTrace != null)
{
// get TraceSource
Type type2 = Type.GetType("System.ServiceModel.Diagnostics.DiagnosticTrace, SMDiagnostics, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
PropertyInfo pi = type2.GetProperty("TraceSource", privateMember);
TraceSource traceSource = pi.GetValue(diagnosticTrace, null) as TraceSource;
// clear all listeners in the trace source
traceSource.Listeners.Clear();
// add listener to trace source
XmlWriterTraceListener listener = new XmlWriterTraceListener("mylogfile".svclog");
listener.TraceOutputOptions = TraceOptions.Timestamp | TraceOptions.Callstack;
traceSource.Attributes["propagateActivity"] = "true";
traceSource.Switch.ShouldTrace(TraceEventType.Verbose | TraceEventType.Start);
traceSource.Listeners.Add(listener);
// enable tracing
type.GetProperty("Level", privateStaticMember).SetValue(null, SourceLevels.All, null);
Trace.AutoFlush = true;
This works fine up to a point, the main problem being that the messagelogging settings in the system.servicemodel section of the app.config file are being ignored.
Is there anything that can be done to solve this problem?
I can't comment on all of your code because I have not used System.Diagnostics in this way before (programmatically configuring the WCF communication tracing), but if your intent on this line:
traceSource.Switch.ShouldTrace(TraceEventType.Verbose | TraceEventType.Start);
Is to set the level of tracing that you want, I think that you should be using the Switch.Level property instead. ShouldTrace is for asking if a given TraceSource would trace, given the input flags.
traceSource.Switch.Level = SourceLevels.Verbose | SourceLevels.ActivityTracing;
Note that according to this link, it is possible to configure apparently reasonable settings and yet the activity id might not be propogated correctly. Read it carefully. It may or not apply to your situation.
You need to enable MessageLogging by defining a trace source as indicated in this MSDN Library page. So, you need this extra bit in your app.config in the sources section:
<source name="System.ServiceModel.MessageLogging">
<listeners>
<add type="System.Diagnostics.DefaultTraceListener" name="dummy"/>
<remove name="Default" />
</listeners> </source>
The message logging settings don't apply to the System.ServiceModel trace source.