I have a windows service that I am converting from my own logging to NLog. I have used NLog in a previous windows service application and felt that I knew what I was doing. But it isn't logging :(
I have the following NLog Configuration:
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="On" internalLogFile="c:\temp\nlog-internal.log" >
<variable name="DebugInfoLayout" value="[${date:format=MM/dd/yyyy h\:mm\:ss tt}] [${gdc:item=location}] | ${level} | ${message}" />
<variable name="InfoLayout" value="[${date:format=MM/dd/yyyy h\:mm\:ss tt}] ${gdc:item=SoftwareName} Version ${gdc:item=SoftwareVersion} - ${message}" />
<variable name="LogLayout" value="[${date:format=MM/dd/yyyy h\:mm\:ss tt}] ${message}" />
<variable name="logDir" value="${basedir}/LogFiles" />
<variable name="ArchiveDir" value="${basedir}/LogFiles/Archive" />
<targets async="true">
<target name="Errors" xsi:type="File" fileName="${logDir}/errors.log" layout="${LogLayout}" keepFileOpen="false" archiveFileName="${ArchiveDir}/errors_${shortdate}.{##}.log" archiveNumbering="Sequence" archiveEvery="Day" maxArchiveFiles="30" archiveOldFileOnStartup="true" />
<target name="Info" xsi:type="File" fileName="${logDir}/info.log" layout="${InfoLayout}" keepFileOpen="false" archiveFileName="${ArchiveDir}/info_${shortdate}.{##}.log" archiveNumbering="Sequence" archiveEvery="Day" maxArchiveFiles="30"/>
<target name="Debug" xsi:type="File" fileName="${logDir}/debug.log" layout="${DebugInfoLayout}" keepFileOpen="false" archiveFileName="${ArchiveDir}/debug_${shortdate}.{##}.log" archiveNumbering="Sequence" archiveEvery="Day" maxArchiveFiles="30" />
</targets>
<rules>
<logger name="Errors" minlevel="Trace" maxlevel="Fatal" writeTo="Errors" />
<logger name="Info" minlevel="Trace" maxlevel="Warn" writeTo="Info" />
<logger name="Debug" minlevel="Trace" maxlevel="Fatal" writeTo="Debug" />
</rules>
</nlog>
To me, this looks correct. And it is the same as in my other application. From the code perspective, I have this in my service.vb file:
'NLog Instances
Dim errorLogger As NLog.Logger = NLog.LogManager.GetLogger("Errors")
Dim infoLogger As NLog.Logger = NLog.LogManager.GetLogger("Info")
Dim debugLogger As NLog.Logger = NLog.LogManager.GetLogger("Debug")
Then lower in the subroutines:
Try
Catch ex As Exception
WritetoNLog(errorlogger, NLog.LogLevel.Error, System.Reflection.MethodInfo.GetCurrentMethod.Name, ex.Message)
WritetoNLog(errorlogger, NLog.LogLevel.Error, System.Reflection.MethodInfo.GetCurrentMethod.Name, ex.InnerException.ToString)
End Try
And then for that simple routine:
Public Sub WritetoNLog(ByRef logger As NLog.Logger, ByVal nlogtype As NLog.LogLevel, ByVal location As String, message As String)
NLog.GlobalDiagnosticsContext.Set("location", String.Format("{0,-35}", location))
Select Case nlogtype
Case NLog.LogLevel.Trace
logger.Trace(message)
Case NLog.LogLevel.Fatal
logger.Fatal(message)
Case NLog.LogLevel.Info
logger.Info(message)
Case NLog.LogLevel.Debug
logger.Debug(message)
Case NLog.LogLevel.Error
logger.Error(message)
Case NLog.LogLevel.Warn
logger.Warn(message)
End Select
NLog.LogManager.Flush()
End Sub
This was a mistake internalLogLevel="On" should have been internalLogLevel="Trace" (or similar).
Related
I´ve a Windows Service and I want to log some information with NLog. My NLog file looks like:
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<time type="AccurateUtc" />
<targets>
<target name="debug-logfile" xsi:type="File" fileName="${specialfolder:folder=ApplicationData}/log/${date:format=yyyy-MM}.log" layout="${longdate} | ${level} | ${message}" />
<target name="trace-logfile" xsi:type="File" fileName="${specialfolder:folder=ApplicationData}/log/trace/${date:format=yyyy-MM-dd}.log" layout="${date:format=yyyy-MM-dd HH\:mm\:ss.fffffff} | ${level} | ${message}" />
<target name="errorfile" xsi:type="File" fileName="${specialfolder:folder=ApplicationData}/log/Error.log" layout="${longdate} | ${level} | ${message}" />
<target name="console" xsi:type="Console" layout="${longdate} | ${level} | ${callsite} | ${message}"/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="trace-logfile" />
<logger name="*" minlevel="Debug" writeTo="debug-logfile" />
<logger name="*" minlevel="Error" writeTo="errorfile" />
</rules>
</nlog>
Now the problem is, the %appdata% folder for my service is: C:\Windows\System32\config\systemprofile\AppData\Roaming and NLog can´t write into this folder. May someone tell me how to get access to this folder or change it to default ServiceProfile folder? (C:\Windows\ServiceProfiles\LocalService\AppData\Roaming\ATLED\log\trace)
I think it´s possible to change it when I give the service the local service user but it´s installed with WIX so may the problem be there. Here the WIX code sample:
<Component Id="CMP_Service" Feature="Core">
<File Source="$(var.Servie.TargetPath)" KeyPath="yes"/>
<ServiceInstall Id="ServiceInstallELS"
Name="Service"
Description="..."
Start="auto"
Account="[SERVICEACCOUNT]"
ErrorControl="normal"
Type="ownProcess"
Vital="no" />
<ServiceControl Id="ServiceControllELS"
Name="Service"
Start="install"
Stop="both"
Remove="uninstall"
Wait="no" />
</Component>
EDIT
With installutil.exe the service writes it´s logs into: C:\Windows\ServiceProfiles\LocalService\AppData\Roaming\ATLED\log\trace
I am new to NLog. But i faced similar issues when i used Log4Net with windows service . I was setting "appdata" path manually from the code. There must be a way in NLog also to set this path manually from code.
However when windows service runs as you mentioned it will take "appdata" path as the one you have mentioned.
To overcome this, i have used WMI windows API's. Please refer the below example.
Idea here is to get the UserName from WMI API's and construct the path manually .
private string GetWindowsUserAccountName()
{
string userName = string.Empty;
ManagementScope ms = new ManagementScope("\\\\.\\root\\cimv2");
ObjectQuery query = new ObjectQuery("select * from win32_computersystem");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(ms, query);
foreach (ManagementBaseObject mo in searcher?.Get())
{
userName = mo["username"]?.ToString();
}
userName = userName?.Substring(userName.IndexOf(#"\",StringComparison.InvariantCulture) + 1);
FCLogger.Logger.LogDebug("[ReturnWindowsUserAccountName]UserName Fetched:" + userName);
return userName;
}
You can construct path by your own , because only the UserName is unknown field here .
var userName = GetWindowsUserAccountName();
var appDataPath = Path.Combine(LoggerConstants.C, LoggerConstants.USERS, userName, LoggerConstants.APP_DATA, LoggerConstants.ROAMING);
//Ex: "C:\\Users\\" + userName from WMI +"\\AppData"+"\\Roaming" ;
I've set up NLog in an ASP.NET Core MVC application using the examples in the documentation. Logging to a file (target=file) works without any problems.
However, logging to the Sqlite database results in an exception:
2018-10-30 20:04:41.4394 Error DatabaseTarget(Name=db): Error when
writing to database. Exception: System.InvalidOperationException: Must
add values for the following parameters: #MachineName, #Logged,
#Level, #Message, #Logger, #Callsite, #Exception at
Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior
behavior) at Microsoft.Data.Sqlite.SqliteCommand.ExecuteNonQuery()
at NLog.Targets.DatabaseTarget.WriteEventToDatabase(LogEventInfo
logEvent) at NLog.Targets.DatabaseTarget.Write(LogEventInfo
logEvent)
Any ideas why the values of these parameters are empty? Or maybe the parameters are not passed at all?
NLog configuration file:
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target xsi:type="File" name="file" fileName="nlog-${shortdate}.log"
layout="${longdate}|${machinename}|${level:upperCase=true}|${logger}|${callsite}|${message} ${exception:tostring}" />
<target xsi:type="Database"
name="db"
dbProvider="Microsoft.Data.Sqlite.SqliteConnection, Microsoft.Data.Sqlite"
connectionString="Data Source=database.db;">
<commandText>
INSERT INTO Log (MachineName, Logged, Level, Message, Logger, CallSite, Exception)
VALUES (#MachineName, #Logged, #Level, #Message, #Logger, #Callsite, #Exception);
</commandText>
<parameter name="#MachineName" layout="${machinename}" />
<parameter name="#Logged" layout="${longdate}" />
<parameter name="#Level" layout="${level:upperCase=true}" />
<parameter name="#Message" layout="${message}" />
<parameter name="#Logger" layout="${logger}" />
<parameter name="#CallSite" layout="${callsite}" />
<parameter name="#Exception" layout="${exception:tostring}" />
</target>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="file" />
<logger name="*" minlevel="Info" writeTo="db" />
</rules>
</nlog>
Unable to fix the issue using Microsoft.Data.Sqlite I switched to using System.Data.SQLite (NuGet) instead, which fixed the issue right away.
Remove the Microsoft.Data.Sqlite reference and add a reference System.Data.SQLite (1.0.109.2 at the time of writing) in your .csproj file. Update the dbProvider attribute value in nlog.config to System.Data.SQLite.SQLiteConnection, System.Data.SQLite and you're set.
nlog.config snippet:
<target xsi:type="Database"
name="db"
dbProvider="System.Data.SQLite.SQLiteConnection, System.Data.SQLite"
connectionString="Data Source=database.db;">
...
</target>
I need invoke msbuild task with properties, whats name can be calculated only in runtime. I try do it by this scripts
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="14.0" DefaultTargets="Build">
<UsingTask TaskName="GetVars" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
<ParameterGroup>
<Result ParameterType="System.String" Output="true"/>
</ParameterGroup>
<Task>
<Code Type="Fragment" Language="cs">
<![CDATA[
this.Result = "AAA=123;BBB=456;";
]]>
</Code>
</Task>
</UsingTask>
<PropertyGroup>
<Vars></Vars>
</PropertyGroup>
<Target Name="Make">
<GetVars>
<Output TaskParameter="Result" PropertyName="Vars"/>
</GetVars>
<MSBuild Projects="Proj.xml" Targets="make" Properties="$(Vars)"/>
</Target>
</Project>
Proj.xml
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build">
<Target Name="Make">
<Message Text="AAA = $(AAA)"/>
<Message Text="BBB = $(BBB)"/>
</Target>
</Project>
This script give this output:
AAA = 123;BBB=456;
BBB =
I expected this output:
AAA = 123;
BBB = 456;
If you want the inline task to produce several items (the msbuild equivalent of an array or list in other languages), you should state it like that instead of using a property (which is a single key/value pair). This is covered in some of the Inline Task documentation - however that uses full-blown ITaskItems whereas just using a String array will do. So:
output a System.String[] from the inline task
assign it to an Item instead of Property using ItemName =
pass the Item to the MSbuild task (which is what it expects anyway), using #() notation
In code:
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="14.0" DefaultTargets="Make">
<UsingTask TaskName="GetVars" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
<ParameterGroup>
<Result ParameterType="System.String[]" Output="true"/>
</ParameterGroup>
<Task>
<Code Type="Fragment" Language="cs">
<![CDATA[
this.Result = new System.String[]{"AAA=123", "BBB=456"};
]]>
</Code>
</Task>
</UsingTask>
<Target Name="Make">
<GetVars>
<Output TaskParameter="Result" ItemName="Vars"/>
</GetVars>
<MSBuild Projects="$(MSBuildThisFile)" Targets="Show" Properties="#(Vars)"/>
</Target>
<Target Name="Show">
<Message Text="AAA = $(AAA)"/>
<Message Text="BBB = $(BBB)"/>
</Target>
</Project>
Output:
Show:
AAA = 123
BBB = 456
We have an (old) build definition is using the UpgradeTemplate.xaml on TFS 2015 (and an underlying TFSBuild.proj which has a heap of custom actions). As such, the task of properly modernising the build is going to take time.
I'd like to hack the UpgradeTemplate to add in C#6/VB14 support without requiring a full re-write of the build definition, in order to keep the devs happy.
I attempted to edit the UpgradeTemplate.xaml to add a ToolPath property on the TfsBuild. However, now that I have done this, I get the following error on nearly all my projects:
ArgumentOutOfRangeException: Index and length must refer to a location within the string. Parameter name: length
On investigation, the lines of code in these projects all look like this:
<MSBuild.ExtensionPack.VisualStudio.TfsVersion TaskAction="GetVersion"
BuildName="$(BuildDefinition)" TfsBuildNumber="$(BuildNumber)"
VersionFormat="DateTime" DateFormat="MMdd" Major="$(MajorVersion)"
Minor="$(MinorVersion)">
The values of these variables as set printed out by Message tasks on the vbproj:
BuildDefinition: MyBuild-Testing
BuildNumber: 57902
MajorVersion: 43
MinorVersion: 2
The Build server has version 3.5.10 on the MSBuild ExtensionPack installed.
How do I resolve this issue? I'm testing this with a new build definition to allow devs to continue working while I get this set up, so I don't want to replace the ExtensionPack with the latest release (if possible) if it is likely to break the existing build.
Upgrade Template
<Activity mc:Ignorable="sad" x:Class="TfsBuild.Process" xmlns="http://schemas.microsoft.com/netfx/2009/xaml/activities" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mtbc="clr-namespace:Microsoft.TeamFoundation.Build.Client;assembly=Microsoft.TeamFoundation.Build.Client" xmlns:mtbw="clr-namespace:Microsoft.TeamFoundation.Build.Workflow;assembly=Microsoft.TeamFoundation.Build.Workflow" xmlns:mtbwa="clr-namespace:Microsoft.TeamFoundation.Build.Workflow.Activities;assembly=Microsoft.TeamFoundation.Build.Workflow" xmlns:mtbwt="clr-namespace:Microsoft.TeamFoundation.Build.Workflow.Tracking;assembly=Microsoft.TeamFoundation.Build.Workflow" xmlns:mtvc="clr-namespace:Microsoft.TeamFoundation.VersionControl.Client;assembly=Microsoft.TeamFoundation.VersionControl.Client" xmlns:mva="clr-namespace:Microsoft.VisualBasic.Activities;assembly=System.Activities" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:sad="http://schemas.microsoft.com/netfx/2009/xaml/activities/presentation" xmlns:sad1="clr-namespace:System.Activities.Debugger;assembly=System.Activities" xmlns:scg="clr-namespace:System.Collections.Generic;assembly=mscorlib" xmlns:this="clr-namespace:TfsBuild;" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<x:Members>
<x:Property Name="ConfigurationFolderPath" Type="InArgument(x:String)" />
<x:Property Name="AgentSettings" Type="InArgument(mtbwa:AgentSettings)" />
<x:Property Name="MSBuildArguments" Type="InArgument(x:String)" />
<x:Property Name="MSBuildPlatform" Type="InArgument(mtbwa:ToolPlatform)" />
<x:Property Name="DoNotDownloadBuildType" Type="InArgument(x:Boolean)" />
<x:Property Name="LogFilePerProject" Type="InArgument(x:Boolean)" />
<x:Property Name="SourcesSubdirectory" Type="InArgument(x:String)" />
<x:Property Name="BinariesSubdirectory" Type="InArgument(x:String)" />
<x:Property Name="TestResultsSubdirectory" Type="InArgument(x:String)" />
<x:Property Name="RecursionType" Type="InArgument(mtvc:RecursionType)" />
<x:Property Name="Verbosity" Type="InArgument(mtbw:BuildVerbosity)" />
<x:Property Name="Metadata" Type="mtbw:ProcessParameterMetadataCollection" />
<x:Property Name="SupportedReasons" Type="mtbc:BuildReason" />
</x:Members>
<this:Process.ConfigurationFolderPath>
<InArgument x:TypeArguments="x:String" />
</this:Process.ConfigurationFolderPath>
<this:Process.AgentSettings>[New Microsoft.TeamFoundation.Build.Workflow.Activities.AgentSettings() With {.MaxWaitTime = New System.TimeSpan(4, 0, 0), .MaxExecutionTime = New System.TimeSpan(0, 0, 0), .TagComparison = Microsoft.TeamFoundation.Build.Workflow.Activities.TagComparison.MatchExactly }]</this:Process.AgentSettings>
<this:Process.MSBuildArguments>
<InArgument x:TypeArguments="x:String" />
</this:Process.MSBuildArguments>
<this:Process.MSBuildPlatform>[Microsoft.TeamFoundation.Build.Workflow.Activities.ToolPlatform.Auto]</this:Process.MSBuildPlatform>
<this:Process.DoNotDownloadBuildType>[False]</this:Process.DoNotDownloadBuildType>
<this:Process.LogFilePerProject>[False]</this:Process.LogFilePerProject>
<this:Process.SourcesSubdirectory>
<InArgument x:TypeArguments="x:String" />
</this:Process.SourcesSubdirectory>
<this:Process.BinariesSubdirectory>
<InArgument x:TypeArguments="x:String" />
</this:Process.BinariesSubdirectory>
<this:Process.TestResultsSubdirectory>
<InArgument x:TypeArguments="x:String" />
</this:Process.TestResultsSubdirectory>
<this:Process.RecursionType>[Microsoft.TeamFoundation.VersionControl.Client.RecursionType.OneLevel]</this:Process.RecursionType>
<this:Process.Verbosity>[Microsoft.TeamFoundation.Build.Workflow.BuildVerbosity.Normal]</this:Process.Verbosity>
<this:Process.Metadata>
<mtbw:ProcessParameterMetadataCollection />
</this:Process.Metadata>
<this:Process.SupportedReasons>All</this:Process.SupportedReasons>
<mva:VisualBasic.Settings>Assembly references and imported namespaces serialized as XML namespaces</mva:VisualBasic.Settings>
<Sequence mtbwt:BuildTrackingParticipant.Importance="None">
<Sequence.Variables>
<Variable x:TypeArguments="mtbc:IBuildDetail" Name="BuildDetail" />
</Sequence.Variables>
<mtbwa:GetBuildDetail DisplayName="Get the Build" Result="[BuildDetail]" />
<mtbwa:InvokeForReason DisplayName="Update Build Number for Triggered Builds" Reason="Triggered">
<mtbwa:UpdateBuildNumber BuildNumberFormat="["$(BuildDefinitionName)_$(Date:yyyyMMdd)$(Rev:.r)"]" DisplayName="Update Build Number" />
</mtbwa:InvokeForReason>
<mtbwa:AgentScope DisplayName="Run On Agent" MaxExecutionTime="[AgentSettings.MaxExecutionTime]" MaxWaitTime="[AgentSettings.MaxWaitTime]" ReservationSpec="[AgentSettings.GetAgentReservationSpec()]">
<mtbwa:AgentScope.Variables>
<Variable x:TypeArguments="x:String" Name="buildDirectory" />
</mtbwa:AgentScope.Variables>
<mtbwa:GetBuildDirectory DisplayName="Get the Build Directory" Result="[buildDirectory]" />
<If Condition="[Not String.IsNullOrEmpty(ConfigurationFolderPath)]" DisplayName="If Not String.IsNullOrEmpty(ConfigurationFolderPath)">
<If.Then>
<mtbwa:TfsBuild BinariesSubdirectory="[BinariesSubdirectory]" BuildDirectory="[buildDirectory]" CommandLineArguments="[MSBuildArguments]" ConfigurationFolderPath="[ConfigurationFolderPath]" DisplayName="Run TfsBuild for Configuration Folder" DoNotDownloadBuildType="[DoNotDownloadBuildType]" LogFilePerProject="[LogFilePerProject]" RecursionType="[RecursionType]" SourcesSubdirectory="[SourcesSubdirectory]" TestResultsSubdirectory="[TestResultsSubdirectory]" ToolPath="C:\Program Files (x86)\MSBuild\12.0\Bin\" ToolPlatform="[MSBuildPlatform]" Verbosity="[Verbosity]" />
</If.Then>
</If>
<If Condition="[BuildDetail.CompilationStatus = Microsoft.TeamFoundation.Build.Client.BuildPhaseStatus.Unknown]" DisplayName="If CompilationStatus = Unknown">
<If.Then>
<mtbwa:SetBuildProperties CompilationStatus="[Microsoft.TeamFoundation.Build.Client.BuildPhaseStatus.Succeeded]" DisplayName="Set CompilationStatus to Succeeded" PropertiesToSet="CompilationStatus" />
</If.Then>
</If>
<If Condition="[BuildDetail.TestStatus = Microsoft.TeamFoundation.Build.Client.BuildPhaseStatus.Unknown]" DisplayName="If TestStatus = Unknown">
<If.Then>
<mtbwa:SetBuildProperties DisplayName="Set TestStatus to Succeeded" PropertiesToSet="TestStatus" TestStatus="[Microsoft.TeamFoundation.Build.Client.BuildPhaseStatus.Succeeded]" />
</If.Then>
</If>
</mtbwa:AgentScope>
<mtbwa:InvokeForReason Reason="CheckInShelveset">
<mtbwa:CheckInGatedChanges DisplayName="Check In Gated Changes" />
</mtbwa:InvokeForReason>
</Sequence>
</Activity>
In Particular, I added ToolPath="C:\Program Files (x86)\MSBuild\12.0\Bin\" to line 58.
TFSBuild.proj
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="DesktopBuild" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<Import Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\TeamBuild\Microsoft.TeamFoundation.Build.targets" />
<Import Project="$(MSBuildExtensionsPath)\Microsoft\SDC\Microsoft.Sdc.Common.tasks" />
<Import Project="$(MSBuildExtensionsPath)\ExtensionPack\MSBuild.ExtensionPack.tasks"/>
<ProjectExtensions>
<!-- Team Foundation Build Version - DO NOT CHANGE -->
<ProjectFileVersion>2</ProjectFileVersion>
</ProjectExtensions>
<PropertyGroup>
<RunCodeAnalysis>Never</RunCodeAnalysis>
<UpdateAssociatedWorkItems>false</UpdateAssociatedWorkItems>
<AdditionalVCOverrides></AdditionalVCOverrides>
<CustomPropertiesForClean></CustomPropertiesForClean>
<CustomPropertiesForBuild></CustomPropertiesForBuild>
<SkipGetChangesetsAndUpdateWorkItems>False</SkipGetChangesetsAndUpdateWorkItems>
<SkipWorkItemCreation>true</SkipWorkItemCreation>
<BuildConfigurationsInParallel>true</BuildConfigurationsInParallel>
<SkipDropBuild>false</SkipDropBuild>
</PropertyGroup>
<ItemGroup>
<SolutionToBuild Include="$(BuildProjectFolderPath)/SolutionsToBuild/Common.sln">
<Targets></Targets>
<Properties></Properties>
</SolutionToBuild>
</ItemGroup>
<ItemGroup>
<ConfigurationToBuild Include="Release|Any CPU">
<FlavorToBuild>Release</FlavorToBuild>
<PlatformToBuild>Any CPU</PlatformToBuild>
</ConfigurationToBuild>
</ItemGroup>
<PropertyGroup>
<SkipClean>false</SkipClean>
<SkipInitializeWorkspace>true</SkipInitializeWorkspace>
<ForceGet>true</ForceGet>
<IncrementalBuild>false</IncrementalBuild>
</PropertyGroup>
</Project>
Update
I think it might be something to do with running a private build (Latest + Shelveset). When I run a normal build, the BuildNumber variable is MyBuild-Testing_20170328.1. This appears to be working fine.
This issue is due to a difference between Private and Public builds. With Public Builds, the build is immediately numbered as BuildName_DateFormat.BuildNumber. Private builds however, are just numeric (e.g. 57902 above).
The Code in the extension does the following:
string buildstring = this.TfsBuildNumber.Replace(string.Concat(this.BuildName, "_"),
string.Empty);
char[] chrArray = new char[] { '.' };
string[] buildParts = buildstring.Split(chrArray, StringSplitOptions.RemoveEmptyEntries);
DateTime t = new DateTime(Convert.ToInt32(buildParts[0].Substring(0, 4),
CultureInfo.CurrentCulture),
Convert.ToInt32(buildParts[0].Substring(4, 2),
CultureInfo.CurrentCulture),
Convert.ToInt32(buildParts[0].Substring(6, 2),
CultureInfo.InvariantCulture));
Are you can see, its substringing on the build name, assuming it's been stripped down to the date component (20170328). Private builds aren't this long, and so fail.
This build works fine when running as a public build - basically it means that private builds on this definition are not available until an upgrade takes place.
I am using Nlog for Error loggin. I have configured the Nlog using the following code in web.config but the programs throws error "Unable to find the requested .Net Framework Data Provider. It may not be installed."
<nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" throwExceptions="true" internalLogFile="c:\nlog.txt" internalLogLevel="Debug">
<extensions>
<add assembly="NLog.Extended" />
</extensions>
<targets>
<target name="Console" xsi:type="Console" layout="${level:uppercase=true} ${message}"/>
<target name="DelivrosLogFile" xsi:type="File" fileName="C:\DelivrosLogs\Delivros.log" layout="${longdate} |${message}| ${stacktrace}"/>
<target xsi:type="Database" name="DelivrosDatabaseLogging" connectionStringName="DelivrosEntities"
commandText="INSERT INTO tbl_ErrorLogIn( Event_ID,Priority,Severity,Title,Timestamp,MachineName,AppDomainName,PocessID,ProcessName,ThreadName,Win32ThreadId,Message,FormattedMessage) VALUES (#Event_ID,#Priority,#Severity,#Title,#Timestamp,#MachineName,#AppDomainName,#PocessID,#ProcessName,#ThreadName,#Win32ThreadId,#Message,#FormattedMessage)">
<parameter name="#Event_ID" layout="0"/>
<parameter name="#Priority" layout="3"/>
<parameter name="#Severity" layout="${level}"/>
<parameter name="#Title" layout="Journal API"/>
<parameter name="#Timestamp" layout="${date}"/>
<parameter name="#MachineName" layout="${machinename}"/>
<parameter name="#AppDomainName" layout="Journal API"/>
<parameter name="#PocessID" layout="${processid}"/>
<parameter name="#ProcessName" layout="${processname}"/>
<parameter name="#ThreadName" layout="${threadname}"/>
<parameter name="#Win32ThreadId" layout="${threadid}"/>
<parameter name="#Message" layout="${exception}"/>
<parameter name="#FormattedMessage" layout="${message} "/>
</target>
</targets>
<rules>
<logger name="*" levels="Info,Warn,Error,Fatal" writeTo="Console"/>
<logger name="*" levels="Info,Warn,Fatal" writeTo="DelivrosLogFile"/>
<logger name="*" levels="Error" writeTo="DelivrosDatabaseLogging"/>
</rules>
I stuck with this for Four days...is there any one out there who can help me....
It was given providerName="System.Data.EntityClient" in connection string and i changed that to providerName="System.Data.SqlClient"
I can just add that if you already used EntityFramework you cannot simply change the provider in your connection string, as your Entity will not work. You can add another connection string for your error logging with providerName="System.Data.SqlClient".