How can read config file in Net5? - vb.net

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.

Related

VB My.Settings Configuration Error Exception

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.

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>

Web.config jsonSerialization maxJsonLength ignored

I have an MVC3 application running under .NET 4.0 and when I use JavascriptSerializer.Deserialize I'm getting an error.
Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
Reading Can I set an unlimited length for maxJsonLength in web.config I put the jsonSerialization maxJsonLength key in my web.config but it gets ignored. Though I can set the JavaScriptSerializer.MaxJsonLength property in code and it works fine.
I would like to have the value in the Web.config rather than code. Here is how I am using JavaScriptSerializer.
Dim client As New WebClient
...
Dim result = _client.DownloadString("Test")
Dim serializer = New JavaScriptSerializer
Return serializer.Deserialize(Of Foo)(result)
Here is my Web.config
<configuration>
<configSections>
...
</configSections>
<appSettings>
...
</appSettings>
<system.web>
<customErrors mode="On">
<error statusCode="404" redirect="/Http404"/>
<error statusCode="403" redirect="/Http403"/>
<error statusCode="550" redirect="/Http550"/>
</customErrors>
<compilation debug="true" targetFramework="4.0"/>
<pages controlRenderingCompatibilityVersion="4.0">
<namespaces>
<add namespace="System.Web.Helpers"/>
<add namespace="System.Web.Mvc"/>
<add namespace="System.Web.Mvc.Ajax"/>
<add namespace="System.Web.Mvc.Html"/>
<add namespace="System.Web.Routing"/>
<add namespace="System.Web.WebPages"/>
</namespaces>
</pages>
</system.web>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
<system.webServer>
....
</system.webServer>
</configuration>
According to the link you provided (the 2nd most voted answer), your web.config setting will be ignored because you're using an internal instance of the JavaScriptSerializer.
If you need the value to be stored in the web.config, you could add a key in the <appSettings> section called maxJsonLength with a value of 50000000 and then in your code, you could use it like:
var serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = ConfigurationManager.AppSettings['maxJsonLength'];

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.