MS Test .orderedtest file details - unit-testing

I'm using scaffolding to dynamically generate UI tests with MS Test and Selenium. I've generated the selenium tests just fine and want to generate .orderedtest files to order the test.
The .orderedtest file is xml based:
<?xml version="1.0" encoding="UTF-8"?>
<OrderedTest name="CRUD_VendorRemark" storage="c:\users\mikeb\documents\visualstudio2010\projects\edimanagementqa\edimanagement.uitesting\orderedtests\crud_vendorremark.orderedtest" id="ca31cb3f-6802-46c5-9f17-53c3632b6681" xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010">
<TestLinks>
<TestLink id="d20974aa-59c6-fb5f-2567-dfff025078f2" name="CreateNew_Invalid_ErrorMessagePresent" storage="..\bin\debug\edimanagement.uitesting.dll" type="Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestElement, Microsoft.VisualStudio.QualityTools.Tips.UnitTest.ObjectModel, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<TestLink id="2408cc97-59b6-7344-e5e1-0dd05592a6d8" name="CreateNew_Valid_SuccessMessagePresent" storage="..\bin\debug\edimanagement.uitesting.dll" type="Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestElement, Microsoft.VisualStudio.QualityTools.Tips.UnitTest.ObjectModel, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<TestLink id="02528772-e3b7-3102-893c-808b3b8c50a8" name="Edit_LastItemInvalid_ErrorMessagePresent" storage="..\bin\debug\edimanagement.uitesting.dll" type="Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestElement, Microsoft.VisualStudio.QualityTools.Tips.UnitTest.ObjectModel, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<TestLink id="1c215986-cfd9-9a57-9049-2f203199461f" name="Edit_LastItemValid_SuccessMessagePresent" storage="..\bin\debug\edimanagement.uitesting.dll" type="Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestElement, Microsoft.VisualStudio.QualityTools.Tips.UnitTest.ObjectModel, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<TestLink id="16cd31fb-a73b-75b3-a886-48e4b0e4697b" name="Delete_LastItem_SuccessMessagePresent" storage="..\bin\debug\edimanagement.uitesting.dll" type="Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestElement, Microsoft.VisualStudio.QualityTools.Tips.UnitTest.ObjectModel, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</TestLinks>
</OrderedTest>
It seems the individual test methods are being referenced by the id="guid", but I don't see it anywhere else in the project.
Any insight as to how the tests are being referenced?
Can the .orderedtest file be generated purely by writing xml?

They need to be loaded & resolved inside the test project. The ID is per-test type. if you look at a manual test, or other file based test type, you'll see theres a test ID guid element; it's pretty much a GUID.
However, for unit tests... well, thats a different conversation. I posted details here that should help you get to the end result that you need.

Related

Testhost.exe has exited with code -1 (0xffffffff)

I am attempting to override a few variables in my integration test with secrets sourced from KeyVault via a variable group within the build pipeline.
I have added a .runsettings file & I'm able to retrieve the dummy variables when I debug through the test. The test however exits abruptly as soon as the instruction to read the dummy value has been executed with the error below:
Value of CrmClientSecret is JustSomeSecret
Step into: Stepping over non-user code
'IntegrationTests.Helpers.Helper.DeleteUserFromCRM' Step into: Stepping over
non-user code 'IntegrationTests.Helpers.Helper. d__4..ctor' 'testhost.exe'
(CLR v4.0.30319: TestSourceHost: Enumering source
(C:\source\repos\Azure\Integrat ionTests\bin\Debug\Tests.dll)): Loaded
'C:\source\repos\Azure\IntegrationTests\bin\Debug\Utilities.dll'. Symbols
loaded. The thread 0x527c has exited with code 0 (0x0). The program '[26720]
testhost.exe' has exited with code -1 (0xffffffff). The program '[26720]
testhost.exe: Program Trace' has exited with code 0 (0x0).
Any help is appreciated
The solution is hosted in Visual Studio Ent 2017. The test project is net 4.61 & the following Nuget packages are installed:
Microsoft.NET.Test.Sdk v 15.9.0
MSTest.TestAdapter v 1.3.2
MSTest.TestFramework v 1.3.2
NUnit3TestAdapter version 3.11.0
Here are my test results:
<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
<RunConfiguration>
<MaxCpuCount>2</MaxCpuCount>
<ResultsDirectory>.\TestResults</ResultsDirectory>
<TargetPlatform>x64</TargetPlatform>
<TargetFrameworkVersion>Framework45</TargetFrameworkVersion>
<TestAdaptersPaths>%systemdrive%\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO\2017\ENTERPRISE\COMMON7\IDE\EXTENSIONS\TESTPLATFORM\Extensions</TestAdaptersPaths>
<TestSessionTimeout>10000</TestSessionTimeout>
</RunConfiguration>
<DataCollectionRunSettings>
<DataCollectors>
<DataCollector friendlyName="Code Coverage" uri="datacollector://Microsoft/CodeCoverage/2.0" assemblyQualifiedName="Microsoft.VisualStudio.Coverage.DynamicCoverageDataCollector, Microsoft.VisualStudio.TraceCollector, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<Configuration>
<CodeCoverage>
<ModulePaths>
<Exclude>
<ModulePath>.*CPPUnitTestFramework.*</ModulePath>
</Exclude>
</ModulePaths>
<UseVerifiableInstrumentation>True</UseVerifiableInstrumentation>
<AllowLowIntegrityProcesses>True</AllowLowIntegrityProcesses>
<CollectFromChildProcesses>True</CollectFromChildProcesses>
<CollectAspDotNet>False</CollectAspDotNet>
</CodeCoverage>
</Configuration>
</DataCollector>
<DataCollector uri="datacollector://microsoft/VideoRecorder/1.0" assemblyQualifiedName="Microsoft.VisualStudio.TestTools.DataCollection.VideoRecorder.VideoRecorderDataCollector, Microsoft.VisualStudio.TestTools.DataCollection.VideoRecorder, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" friendlyName="Screen and Voice Recorder">
</DataCollector>
</DataCollectors>
</DataCollectionRunSettings>
<TestRunParameters>
<Parameter name="AmbassadorsDbConnectionString"
value="TheConnectionString" />
<Parameter name="CRMClientSecret" value="JustSomeSecret" />
<Parameter name="webAppPassword" value="Password" />
</TestRunParameters>
<MSTest>
<MapInconclusiveToFailed>True</MapInconclusiveToFailed>
<CaptureTraceOutput>false</CaptureTraceOutput>
<DeleteDeploymentDirectoryAfterTestRunIsComplete>False
<DeploymentEnabled>False</DeploymentEnabled>
<AssemblyResolution>
<Directory path="D:\myfolder\bin\" includeSubDirectories="false"/>
</AssemblyResolution>
</MSTest>
</RunSettings>
You can use the blame option to collect the dump and analyze the cause for the crash
https://github.com/Microsoft/vstest-docs/blob/master/RFCs/0024-Blame-Collector-Options.md

impossible to publish artifacts for.... java.io.IOException: missing artifact lib#MyService;1.0!MyService.jar

Basically I am exploring IVY, to version my binary artifacts and how to do version control automatically using ivy. I found that publish, pubrevision could help me out.
Hence I am trying to publish my jar through IVY. However I am getting below error and build failed.
impossible to publish artifacts for lib#MyService;working#Localhost java.io.IOException: missing artifact lib#MyService;1.0!MyService.jar
Please find my ivy.xml
<?xml version="1.0" encoding="UTF-8"?>
<ivy-module version="2.0" xmlns:m="http://ant.apache.org/ivy/maven">
<info organisation="lib" module="MyService" />
<configurations defaultconfmapping="default->default;sources->sources;test->default">
<conf name="sources" transitive="false" visibility="private" />
<conf name="test" transitive="false" visibility="private" />
<conf name="default" transitive="false" />
</configurations>
<publications>
<artifact name="MyService" type="jar"/>
</publications>
<dependencies defaultconf="default">
<dependency org="lib" name="commons-logging-1.1" rev="1.1" />
<dependency org="lib" name="commons-collections-3.2" rev="3.2" />
<dependency org="lib" name="commons-beanutils" rev="1.7.0" conf="default" />
</dependencies>
</ivy-module>
Publish task : Note: dist will resolve my dependency and compile and jar
build.xml
<target name="publish" depends="dist">
<ivy:publish resolver="local" pubrevision="1.0" module="MyService" status="release" forcedeliver="true" update="true">
<artifacts pattern="publish/[organisation]-[artifact].[ext]"/>
</ivy:publish>
</target>
MyService.jar is being created in my build folder.
Can you please assist me, what is wrong with my code. I am pretty new to IVY. So any inputs will be appreciated very much.
Thanks.

Tracing to LogSource 'All Events' failed. Enterprise Library logging error

I am getting error. I am unable to understand what causing error. There are no exception on UI.
Category tables has values (Information,Exception,Debug,General). When all events failed error occurs there is no record entered into CategoryLog table. Can someone please help me to understand this error and to fix it.
Tracing to LogSource 'All Events' failed. Processing for other sources will continue.
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: 11/4/2014 9:35:46 PM
Message: 'Some message'.
WebConfig:-
<listeners>
<add name="DatabaseTraceListener" type="Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=6.0.0.0, Culture=neutral, PublicKeyToken=########"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Database.Configuration.FormattedDatabaseTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=6.0.0.0, Culture=neutral, PublicKeyToken=#######"
databaseInstanceName="LoggingDatabase" writeLogStoredProcName="WriteLog"
addCategoryStoredProcName="AddCategory"
formatter="Text Formatter"
traceOutputOptions="LogicalOperationStack, DateTime, Timestamp, ProcessId, ThreadId, Callstack" />
</listeners>
<formatters>
<add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=#####"
template="Timestamp: {timestamp}{newline}
Message: {message}{newline}
Category: {category}{newline}
Priority: {priority}{newline}
EventId: {eventid}{newline}
Severity: {severity}{newline}
Title:{title}{newline}
Machine: {localMachine}{newline}
App Domain: {localAppDomain}{newline}
ProcessId: {localProcessId}{newline}
Process Name: {localProcessName}{newline}
Thread Name: {threadName}{newline}
Win32 ThreadId:{win32ThreadId}{newline}
Extended Properties: {dictionary({key} - {value}{newline})}"
name="Text Formatter" />
</formatters>
<categorySources>
<add switchValue="Error" name="Error">
<listeners>
<add name="DatabaseTraceListener" />
</listeners>
</add>
<add switchValue="Information" name="Information">
<listeners>
<add name="DatabaseTraceListener" />
</listeners>
</add>
<add switchValue="Warning" name="Warning">
<listeners>
<add name="DatabaseTraceListener" />
</listeners>
</add>
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events">
<listeners>
<add name="DatabaseTraceListener" />
</listeners>
</allEvents>
<notProcessed switchValue="All" name="Unprocessed Category">
<listeners>
<add name="DatabaseTraceListener" />
</listeners>
</notProcessed>
<errors switchValue="All" name="Logging Errors & Warnings">
<listeners>
<add name="DatabaseTraceListener" />
</listeners>
</errors>
</specialSources>
Error record in log table looks like this
LogID: ######
EventID : 6352
Priority: -1
Severity: Error
Title :
Timestamp: 2014-11-10 00:55:51.770
MachineName : ########
AppDomainName: /LM/W3SVC/3/ROOT-######
ProcessID: 5272
ProcessName: c:\windows\system32\inetsrv\w3wp.exe
ThreadName: NULL
Win32ThreadId: 8852
Message :Tracing to LogSource 'All Events' failed. Processing for other sources will continue. 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:
FormattedMessage :
You are encountering an error logging to your database. But it seems that it is not totally catastrophic since it seems errors are being logged. This rules out a common cause such as invalid connection string.
You need to find out what the actual error is. To do this change the errors special source to log to a file (in a location with proper permissions). So add a flat file trace listener:
<listeners>
<add name="DatabaseTraceListener" type="Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=6.0.0.0, Culture=neutral, PublicKeyToken=########"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Database.Configuration.FormattedDatabaseTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=6.0.0.0, Culture=neutral, PublicKeyToken=#######"
databaseInstanceName="LoggingDatabase" writeLogStoredProcName="WriteLog"
addCategoryStoredProcName="AddCategory"
formatter="Text Formatter"
traceOutputOptions="LogicalOperationStack, DateTime, Timestamp, ProcessId, ThreadId, Callstack" />
<add name="Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
fileName="trace.log" />
</listeners>
and then set the error special source to use the flat file trace listener:
<specialSources>
<allEvents switchValue="All" name="All Events">
<listeners>
<add name="DatabaseTraceListener" />
</listeners>
</allEvents>
<notProcessed switchValue="All" name="Unprocessed Category">
<listeners>
<add name="DatabaseTraceListener" />
</listeners>
</notProcessed>
<errors switchValue="All" name="Logging Errors & Warnings">
<listeners>
<add name="Flat File Trace Listener" />
</listeners>
</errors>
</specialSources>
With that setting you should hopefully see the full details of the error.
Making the user tries to write the log as admin is the solution for this problem. UAC setting can also be changed to make the IIS user as admin.

VS 2012 MultiProject Template will NOT Correctly Reference EF 5

I have 3 Projects in my solution template (Model, DataAccess and Service.) More than one of them need to reference EF 5. When I initially created the first Template Service) the EF.dll was in the references list but had the yellow "can't find it" icon on it. I read that I could put the following XML at the bottom of the .vstemplate file and that took care of that problem:
<WizardExtension>
<Assembly>NuGet.VisualStudio.Interop, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</Assembly>
<FullClassName>NuGet.VisualStudio.TemplateWizard</FullClassName>
</WizardExtension>
<WizardData>
<packages repository="registry" keyName="AspNetMvc4VS11" isPreunzipped="true">
<package id="EntityFramework" version="5.0.0" skipAssemblyReferences="true" />
</packages>
</WizardData>
I then figured out how to create a MultiProject .vstemplate and each of my three SubProjects get created exactly how I want them. However, each of the projects that reference EF 5 are failing to hook up the reference. Each of the sub .vstemplate files has the above XML in it but no luck. I even tried to put that XML in the root .vstemplate with no success. Here is my root .vstemplate:
<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="ProjectGroup">
<TemplateData>
<Name>CCISC WCF Service Template - Empty</Name>
<Description>This is the multi-project template for creating a WCF Service at the county that contains EF 5 and Elmah.</Description>
<ProjectType>CSharp</ProjectType>
<ProjectSubType>
</ProjectSubType>
<SortOrder>1000</SortOrder>
<CreateNewFolder>true</CreateNewFolder>
<DefaultName>MyService</DefaultName>
<ProvideDefaultName>true</ProvideDefaultName>
<LocationField>Enabled</LocationField>
<EnableLocationBrowseButton>true</EnableLocationBrowseButton>
<Icon>__TemplateIcon.png</Icon>
</TemplateData>
<TemplateContent>
<ProjectCollection>
<ProjectTemplateLink ProjectName="Model">Model\Model.vstemplate</ProjectTemplateLink>
<ProjectTemplateLink ProjectName="DataAccess">DataAccess\DataAccess.vstemplate</ProjectTemplateLink>
<ProjectTemplateLink ProjectName="Service">Service\Service.vstemplate</ProjectTemplateLink>
</ProjectCollection>
</TemplateContent>
</VSTemplate>
And here is just the Service.vstemplate file. No need to give you the rest since they are similar and yet all have the same issue with the reference:
<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Project">
<TemplateData>
<Name>CCISC Service Template - Empty</Name>
<Description>This is the Service project for the CCISC WCF Service Template that contains EF 5 and Elmah.</Description>
<ProjectType>CSharp</ProjectType>
<ProjectSubType>
</ProjectSubType>
<SortOrder>1000</SortOrder>
<CreateNewFolder>true</CreateNewFolder>
<DefaultName>CCISC Service Template - Empty</DefaultName>
<ProvideDefaultName>true</ProvideDefaultName>
<LocationField>Enabled</LocationField>
<EnableLocationBrowseButton>true</EnableLocationBrowseButton>
<Icon>__TemplateIcon.png</Icon>
</TemplateData>
<TemplateContent>
<Project TargetFileName="Service.csproj" File="Service.csproj" ReplaceParameters="true">
<Folder Name="App_Data" TargetFolderName="App_Data" />
<Folder Name="App_ReadMe" TargetFolderName="App_ReadMe">
<ProjectItem ReplaceParameters="true" TargetFileName="County.txt" OpenInEditor="true">County.txt</ProjectItem>
<ProjectItem ReplaceParameters="true" TargetFileName="Elmah.txt">Elmah.txt</ProjectItem>
</Folder>
<ProjectItem ReplaceParameters="true" TargetFileName="IService1.cs">IService1.cs</ProjectItem>
<ProjectItem ReplaceParameters="true" TargetFileName="packages.config">packages.config</ProjectItem>
<Folder Name="Properties" TargetFolderName="Properties">
<ProjectItem ReplaceParameters="true" TargetFileName="AssemblyInfo.cs">AssemblyInfo.cs</ProjectItem>
</Folder>
<ProjectItem ReplaceParameters="false" TargetFileName="Service1.svc">Service1.svc</ProjectItem>
<ProjectItem ReplaceParameters="true" TargetFileName="Service1.svc.cs">Service1.svc.cs</ProjectItem>
<ProjectItem ReplaceParameters="true" TargetFileName="Web.config">Web.config</ProjectItem>
<ProjectItem ReplaceParameters="true" TargetFileName="Web.Debug.config">Web.Debug.config</ProjectItem>
<ProjectItem ReplaceParameters="true" TargetFileName="Web.Release.config">Web.Release.config</ProjectItem>
</Project>
</TemplateContent>
<WizardExtension>
<Assembly>NuGet.VisualStudio.Interop, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</Assembly>
<FullClassName>NuGet.VisualStudio.TemplateWizard</FullClassName>
</WizardExtension>
<WizardData>
<packages repository="registry" keyName="AspNetMvc4VS11" isPreunzipped="true">
<package id="EntityFramework" version="5.0.0" skipAssemblyReferences="true" />
</packages>
</WizardData>
</VSTemplate>
If it helps, the Path property of the EntityFramework reference is blank.
In the case of the Service project, in the .csproj file, the following XML is in there:
<Reference Include="EntityFramework">
<HintPath>..\packages\EntityFramework.5.0.0\lib\net45\EntityFramework.dll</HintPath>
</Reference>
Which I understand would look at the root of the solution for a packages folder and go from there. I suspect the above element was somewhat successful because it does create a Packages folder at the root of the new solution. It just does not seem to update the reference to that.
I even tried to change skipAssemblyReferences to false and that had no change. It seems like I am so close.
As it turns out, once the projects were saved to the HDD, the "packages" folder was up one level higher. So to take care of this, I changed the following from this:
<Reference Include="EntityFramework">
<HintPath>..\packages\EntityFramework.5.0.0\lib\net45\EntityFramework.dll</HintPath>
</Reference>
To this:
<Reference Include="EntityFramework">
<HintPath>..\..\packages\EntityFramework.5.0.0\lib\net45\EntityFramework.dll</HintPath>
</Reference>
Note the extra ..\ to go up one more level.
Sadly that did NOT take care of it right away. I had to clear the Visual Studio Template cache. So I had to run the Visual Studio Command Prompt as an Administrator and run the following command:
devenv /installvstemplates
It takes a few minutes but once it was done, everything worked as expected!

Log4Net "Could not find schema information" messages

I decided to use log4net as a logger for a new webservice project. Everything is working fine, but I get a lot of messages like the one below, for every log4net tag I am using in my web.config:
Could not find schema information for
the element 'log4net'...
Below are the relevant parts of my web.config:
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="C:\log.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="100KB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level: %message%newline" />
</layout>
</appender>
<logger name="TIMServerLog">
<level value="DEBUG" />
<appender-ref ref="RollingFileAppender" />
</logger>
</log4net>
Solved:
Copy every log4net specific tag to a separate xml-file. Make sure to use .xml as file extension.
Add the following line to AssemblyInfo.cs:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "xmlFile.xml", Watch = true)]
nemo added:
Just a word of warning to anyone
follow the advice of the answers in
this thread. There is a possible
security risk by having the log4net
configuration in an xml off the root
of the web service, as it will be
accessible to anyone by default. Just
be advised if your configuration
contains sensitive data, you may want
to put it else where.
#wcm: I tried using a separate file. I added the following line to AssemblyInfo.cs
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
and put everything dealing with log4net in that file, but I still get the same messages.
You can bind in a schema to the log4net element. There are a few floating around, most do not fully provide for the various options available. I created the following xsd to provide as much verification as possible:
http://csharptest.net/downloads/schema/log4net.xsd
You can bind it into the xml easily by modifying the log4net element:
<log4net
xsi:noNamespaceSchemaLocation="http://csharptest.net/downloads/schema/log4net.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
I had a different take, and needed the following syntax:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.xml", Watch = true)]
which differs from xsl's last post, but made a difference for me. Check out this blog post, it helped me out.
Just a word of warning to anyone follow the advice of the answers in this thread. There is a possible security risk by having the log4net configuration in an xml off the root of the web service, as it will be accessible to anyone by default. Just be advised if your configuration contains sensitive data, you may want to put it else where.
I believe you are seeing the message because Visual Studio doesn't know how to validate the log4net section of the config file. You should be able to fix this by copying the log4net XSD into C:\Program Files\Microsoft Visual Studio 8\XML\Schemas (or wherever your Visual Studio is installed). As an added bonus you should now get intellisense support for log4net
In Roger's answer, where he provided a schema, this worked very well for me except where a commenter mentioned
This XSD is complaining about the use of custom appenders. It only allows for an appender from the default set (defined as an enum) instead of simply making this a string field
I modified the original schema which had a xs:simpletype named log4netAppenderTypes and removed the enumerations. I instead restricted it to a basic .NET typing pattern (I say basic because it just supports typename only, or typename, assembly -- however someone can extend it.
Simply replace the log4netAppenderTypes definition with the following in the XSD:
<xs:simpleType name="log4netAppenderTypes">
<xs:restriction base="xs:string">
<xs:pattern value="[A-Za-z_]\w*(\.[A-Za-z_]\w*)+(\s*,\s*[A-Za-z_]\w*(\.[A-Za-z_]\w*)+)?"/>
</xs:restriction>
</xs:simpleType>
I'm passing this back on to the original author if he wants to include it in his official version. Until then you'd have to download and modify the xsd and reference it in a relative manner, for example:
<log4net
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../../../Dependencies/log4net/log4net.xsd">
<!-- ... -->
</log4net>
Actually you don't need to stick to the .xml extension. You can specify any other extension in the ConfigFileExtension attribute:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", ConfigFileExtension=".config", Watch = true)]
#steve_mtl: Changing the file extensions from .config to .xml solved the problem. Thank you.
#Wheelie: I couldn't try your suggestion, because I needed a solution which works with an unmodified Visual Studio installation.
To sum it up, here is how to solve the problem:
Copy every log4net specific tag to a separate xml-file. Make sure to use .xml as file extension.
Add the following line to AssemblyInfo.cs:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "xmlFile.xml", Watch = true)]
For VS2008 just add the log4net.xsd file to your project; VS looks in the project folder as well as the installation directory that Wheelie mentioned.
Also, using a .config extension instead of .xml avoids the security issue since IIS doesn't serve *.config files by default.
Have you tried using a separate log4net.config file?
I got a test asp project to build by puting the xsd file in the visual studio schemas folder as described above (for me it is C:\Program Files\Microsoft Visual Studio 8\XML\Schemas) and then making my web.config look like this:
<?xml version="1.0"?>
<!--
Note: As an alternative to hand editing this file you can use the
web admin tool to configure settings for your application. Use
the Website->Asp.Net Configuration option in Visual Studio.
A full list of settings and comments can be found in
machine.config.comments usually located in
\Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration>
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<appSettings>
</appSettings>
<connectionStrings>
</connectionStrings>
<system.web>
<trace enabled="true" pageOutput="true" />
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<compilation debug="true" />
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<authentication mode="Windows" />
<customErrors mode="Off"/>
<!--
<customErrors mode="Off"/>
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
<customErrors mode="On" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
</system.web>
<log4net xsi:noNamespaceSchemaLocation="http://csharptest.net/downloads/schema/log4net.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<!-- Please make shure the ..\\Logs directory exists! -->
<param name="File" value="Logs\\Log4Net.log"/>
<!--<param name="AppendToFile" value="true"/>-->
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c %m%n"/>
</layout>
</appender>
<appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
<to value="" />
<from value="" />
<subject value="" />
<smtpHost value="" />
<bufferSize value="512" />
<lossy value="true" />
<evaluator type="log4net.Core.LevelEvaluator">
<threshold value="WARN"/>
</evaluator>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%newline%date [%thread] %-5level %logger [%property] - %message%newline%newline%newline" />
</layout>
</appender>
<logger name="File">
<level value="ALL" />
<appender-ref ref="LogFileAppender" />
</logger>
<logger name="EmailLog">
<level value="ALL" />
<appender-ref ref="SmtpAppender" />
</logger>
</log4net>
</configuration>
Without modifying your Visual Studio installation, and to take into account proper versioning/etc. amongst the rest of your team, add the .xsd file to your solution (as a 'Solution Item'), or if you only want it for a particular project, just embed it there.
I noticed it a bit late, but if you look into the examples log4net furnishes you can see them put all of the configuration data into an app.config, with one difference, the registration of configsection:
<!-- Register a section handler for the log4net section -->
<configSections>
<section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
</configSections>
Could the definition it as type "System.Configuration.IgnoreSectionHandler" be the reason Visual Studio does not show any warning/error messages on the log4net stuff?
I followed Kit's answer https://stackoverflow.com/a/11780781/6139051 and it didn't worked for AppenderType values like "log4net.Appender.TraceAppender, log4net". The log4net.dll assembly has the AssemblyTitle of "log4net", i.e. the assembly name does not have a dot inside, that was why the regex in Kit's answer didn't work. I has to add the question mark after the third parenthetical group in the regexp, and after that it worked flawlessly.
The modified regex looks like the following:
<xs:pattern value="[A-Za-z_]\w*(\.[A-Za-z_]\w*)+(\s*,\s*[A-Za-z_]\w*(\.[A-Za-z_]\w*)?+)?"/>