Can't insert into SQL Server table with log4net AdoNetAppender - sql-server

I am trying to understand how log4net works so I've added this to my app.config (I should add that Console Appender and FileAppender work perfectly, I only have trouble with the AdoNetAppender).
How can I debug this, to see if at least the connection to db succeeds?
The problem is the INSERT statement isn't executed.
I should add the
Data Source=MyWorkgroup\SQLEXPRESS;Initial Catalog=MyNewDatabase;User ID=juan;password=juan,
works perfectly when I try to connect to SQL Server manually, so not sure if that's the problem.
Also, the ConnectionType was taken from the official site:
https://logging.apache.org/log4net/log4net-1.2.11/release/sdk/log4net.Appender.AdoNetAppender.ConnectionType.html
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net"
type="log4net.Config.log4netConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<appender name="AdoNetAppender"
type="log4net.Appender.AdoNetAppender">
<bufferSize value="10" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="Data Source=MyWorkgroup\SQLEXPRESS;Initial Catalog=MyNewDatabase;User ID=juan;Password=juan;Pooling=False" />
<commandText value="INSERT INTO Logs([logDate],[logThread],[logMessage]) VALUES(getdate(),'1','1')" />
<commandType value="Text" />
</appender>
<root>
<level value="DEBUG"/>
<appender-ref ref="AdoNetAppender"/>
</root>
</log4net>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
Later edit (after using the debug method recommended by David):
haacked.com is indeed extremely interesting, great tip! However, it seems that it's describing what I'm instructing log4net to log, but not the result of those actions(?), if I'm reading this well (no failed/or succeeded?)
e.g.
log4net: Setting Property [ConnectionType] to String value
[System.Data.SqlClien t.SqlConnection, System.Data,
Version=1.0.3300.0, Culture=neutral, PublicKeyToke n=b77a5c561934e089]
log4net: Setting Property [ConnectionString] to String value [Data
Source=MyWorkgroup\SQLEXPRESS; Initial
Catalog=MyNewDatabase;
User ID=juan; Password=juan;
Pooling=False] log4net: Setting Property [CommandText] to String value [INSERT INTO Logs([logDate],[logThread],[logMessage]) VALUES(getdate(),'1','1')] log4net:
Setting Property [CommandType] to CommandType value [Text] log4net:
Created Appender [AdoNetAppender] log4net: Adding appender named
[AdoNetAppender] to logger [root]. log4net: Hierarchy Threshold []
Piece of code that helped me obtain this info (in case the site should become unavailable) is:
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="C:\temp\log4netdiagn.txt" />
</listeners>
</trace>
</system.diagnostics>

Related

RIA Service Error in a Silverlight Application

In a very simple Silverlight Application I have a DomainService Class which has a single method that returns a list of Letter Objects.
The application works fine when I run it in VisualStudio. However, when I publish it to a folder on my Windows 10 local machine and run it using IIS (version 10.0.166299.5) I get the following error:
The remote server returned an error: NotFound.
at System.ServiceModel.DomainServices.Client.OperationBase.Complete(Exception error) at System.ServiceModel.DomainServices.Client.LoadOperation.Complete(Exception error) at System.ServiceModel.DomainServices.Client.DomainContext.CompleteLoad(IAsyncResult asyncResult) at System.ServiceModel.DomainServices.Client.DomainContext.<>c__DisplayClass1b.b__17(Object )
I supect this is due to something being wrong in missing in my WebConfig file. My WebConfig Currently looks like this:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.6" />
<httpRuntime targetFramework="4.6" />
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<add name="DomainServiceModule" preCondition="managedHandler" type="System.ServiceModel.DomainServices.Hosting.DomainServiceHttpModule, System.ServiceModel.DomainServices.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</modules>
</system.webServer>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
</configuration>
The code for my Domain Service Class is like this:
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.DomainServices.Hosting;
using System.ServiceModel.DomainServices.Server;
using SilverData.Web.Models;
namespace SilverData.Web.Services
{
[EnableClientAccess]
public class DrugsRiaService : DomainService
{
public IQueryable<Letter> GetAllLetters()
{
List<Letter> letters = new List<Letter>();
Letter letterA = new Letter { ID = 1, Statement = "Mike" };
Letter LetterB = new Letter { ID = 2, Statement = "Emma" };
Letter LetterC = new Letter { ID = 3, Statement = "Peter" };
letters.Add(letterA);
letters.Add(LetterB);
letters.Add(LetterC);
return letters.AsQueryable();
}
}
}
The error was due to the problem that .svc file wasn't being served.. The problem got solved with the kind help from the Kyle Abraham on Experts Exchange.
https://www.experts-exchange.com/questions/29084691/RIA-Service-Error-in-a-Silverlight-Application.html
The solution was to add the following line to the webserver section of the Webconfig
<handlers>
<add name=".svc" verb="*" path="*.svc" type="System.ServiceModel.Activation.ServiceHttpHandlerFactory, System.ServiceModel.Activation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</handlers>
I'm not sure, its a guess as I have not used RIA for awhile, but I think letters needs to returned as something other than queryable... try ToList() which causes the query to execute, and the payload is complete with the complete enumeration that was retrieved from the database. Remember, this is a remote call from a client, not a local one that can extend the queryable.

log4net log file not being written when the app is deployed

I have a WPF app that uses log4net. When I run it in Visual Studio, the log file is created in the Debug or Release folder as expected.
However, when I create an installer and run the installed app, the log file is not created. I added the following lines to the code...
string logFilePath = ((Hierarchy)LogManager.GetRepository())
.Root.Appenders.OfType<FileAppender>()
.FirstOrDefault()?.File;
using (StreamWriter sw = new StreamWriter(#"d:\log.log")) {
sw.WriteLine("Log file: " + logFilePath);
}
...to enable me to check that the log file was being written in the location I expected. It showed me that the log file was supposed to be written to C:\Program Files (x86)\Physio Diary\PhysioDiaryClient.log which is what I expected.
However, the file doesn't exist. Any idea why?
Here is the top of the App.config file...
<?xml version="1.0"
encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net" />
</configSections>
<log4net>
<appender name="RollingFileAppender"
type="log4net.Appender.RollingFileAppender">
<param name="File"
value="PhysioDiaryClient.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="2" />
<maximumFileSize value="1MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-7level %logger - %message%newline%exception" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="RollingFileAppender" />
</root>
</log4net>
The bottom of the file looks like this...
<startup>
<supportedRuntime version="v4.0"
sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
The bits in between are all to do with the WCF services that the app uses.
Anyone any ideas?
Edit: As a test, I tried hard-coding the log file path in App.config to my D: drive (so it's hard-coded, and no question of a permissions issue), but the file still wasn't created.
Thanks to #dymanoid for pointing me in the right direction. The log4net docs are a bit weak in this area, but I found this answer that pointed out that you can use normal environment variables in the config file.
With the aid of this list of environment variables, I ended up with the following...
<param name="File"
value="${LOCALAPPDATA}\Physio Diary\PhysioDiaryClient.log" />
This correctly write the file to C:\Users\MyUsername\AppData\Local\Physio Diary\PhysioDiaryClient.log
Hope this helps someone.

XML Connectionstrings

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="Citrus_Welding.My.MySettings.CitWeldConnectionString"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="C:\Citrus Welding\CitWeld.mdb""
providerName="System.Data.OleDb" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
I am looking at the connection string, I need the Data Source to = a selected file from another page by default... I tried & pagename.openfiledialog.filename & but I keep getting an error. Any ideas?
It appears that you're saying that you want the user to be able to set the Data Source at run time. If so then omit it from the connection string in the config file and set it like this at run time:
Dim builder As New OleDbConnectionStringBuilder(My.Settings.CitWeldConnectionString)
builder.DataSource = newDataSourceValue
Dim connection As New OleDbConnection(builder.ConnectionString)

Using Log4Net and the AdoNetAppender to write an XMLLayout parameter to a DbType XML field

Pretty straightforward question.
I have a table on a SQL Server Database that has an field with a DbType of XML.
I would like to write to that field using the format of Log4Net's XML layout WITHOUT writing a custom appender; using the in-the-box AdoNetAppender.
Below is my current code, however, when it attempts to log, it will insert a record, but the "Exception" field will be blank.
(I've simplified the code for the purpose of this question; it used to write to many other fields using the pattern layout. I've confirmed that the Appender does work and that log4net is configured properly, I'm just trying to log to a dbtype of XML using log4net's included XMLLayout.)
<appender name="AdoNetAppender_SqlServer" type="log4net.Appender.AdoNetAppender">
<bufferSize value="1" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<ConnectionStringName value="CONNECTIONSTRING"/>
<commandText value="dbo.TestLog_Insert #Exception = #Exception" />
<parameter>
<parameterName value="#Exception"/>
<dbType value="XML"/>
<size value="4000"/>
<layout type="log4net.Layout.XMLLayout" value="%exception" />
</parameter>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO"/>
<acceptOnMatch value="true"/>
</filter>
<filter type="log4net.Filter.DenyAllFilter"/>
</appender>

wpf - Get values from App Config file

How to get values from App.Config.
Code:
<configuration>
<appSettings>
<add key="ShowRoomCode" value="1000"/>
<add key="FolderPath" value="D:\\Images\\Book\\"/>
</appSettings>
</configuration>
string imageFolderPath = ConfigurationManager.AppSettings["FolderPath"];
But it returns null value. Config file is in the Same project.
If you expand the Properties section of Visual Studio and double click the settings section, you will be able to add custom settings which end up like so in the config file:
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="WpfApplication1.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<userSettings>
<WpfApplication1.Properties.Settings>
<setting name="FilePath" serializeAs="String">
<value>Thing</value>
</setting>
</WpfApplication1.Properties.Settings>
</userSettings>
</configuration>
Which you can then do this in your code:
string thing = Properties.Settings.Default.FilePath;
Which is nice because it gives you type safety too
The code you wrote should work - make sure you haven't changed 'BuildAction' of the config file.

Resources