NLog not writing in Asp.Net Web Api App - visual-studio

I have been trying to implement NLog as a trace writer in an Asp.Net Web Api 2.2 app. This is my web.config:
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
<nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.nlog-project.org/schemas/NLog.xsd" throwExceptions="true" internalLogFile="c:\file.txt">
<targets>
<target name="logfile" xsi:type="File" fileName="${basedir}/Logs/log.txt"/>
<rules>
<logger name="*" minlevel="Info" writeTo="logfile"/>
</rules>
</targets>
During debugging this works fine if I am using IIS Express as the host, but If I set the project to use Local IIS it fails with a System.UnauthorizedAccessException. I am running VS 2013 as an administrator too.

You should check whether the user, which is configured in the Local IIS to be used to run the appdomain of your web application, have the sufficient access rights to write to the ${basedir}/Logs directory.
Please, ensure that you can run this code from your application:
File.WriteAllText(
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs\test.txt"),
"Some content");
When you are able to do this, you'll also would be able to do the logging

Related

Deploy Azure App Service with multiple Virtual Applications using Visual Studio 2022

I currently am using Azure Cloud Service (classic) and am able to effectively deploy a WebApp that contains 4 virtual applications using an Azure Cloud Service project. My ServiceDefinition.csdef file looks like:
<?xml version="1.0" encoding="utf-8"?>
<ServiceDefinition name="My.Azure.Web.API" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition" schemaVersion="2015-04.2.6">
<WebRole name="My.Web.API" vmsize="Small">
<Sites>
<Site name="Web" physicalDirectory="{path to My.Web.API}">
<VirtualApplication name="webapp1" physicalDirectory="{path to My.Web.WebApp1}" />
<VirtualApplication name="webapp2" physicalDirectory="{path to My.Web.WebApp2}" />
<VirtualApplication name="webapp3" physicalDirectory="{path to My.Web.WebApp3}" />
<VirtualApplication name="webapp4" physicalDirectory="{path to My.Web.WebApp4}" />
<Bindings>
<Binding name="Endpoint1" endpointName="Endpoint1" />
<Binding name="HttpsIn" endpointName="HttpsIn" />
</Bindings>
</Site>
</Sites>
<Endpoints>
<InputEndpoint name="Endpoint1" protocol="http" port="80" />
<InputEndpoint name="HttpsIn" protocol="https" port="443" certificate="{certname}" />
</Endpoints>
<Imports>
<!--<Import moduleName="Diagnostics" />-->
<Import moduleName="RemoteAccess" />
<Import moduleName="RemoteForwarder" />
</Imports>
<ConfigurationSettings>
</ConfigurationSettings>
<Certificates>
<Certificate name="{certname}" storeLocation="LocalMachine" storeName="My" />
</Certificates>
</WebRole>
</ServiceDefinition>
I am working on migrating to Azure App Service and despite some significant digging I can not seem to find an equivalent/similar deployment process in Visual Studio for multiple Virtual Applications in Azure App Service.
I have found numerous posting that indicate using the publish function in the actual WebApp projects, but I would have to perform 4 separate deployments instead on one. And need to pre-define the virtual directories in the App Service configuration. Under the current approach, virtual applications/directories are defined during the deployment.
I plan to eventually move to Azure DevOps Pipelines for CI/CD and hope there is a mechanism to achieve this, but for now would just like something functional from Visual Studio.
Is there an equivalent/similar deployment process in Visual Studio for multiple Virtual Applications in Azure App Service? If not, what are the options?
Apologies if this a re-tread. I did my due diligence with no definitive answers. Unless of course the answer is right in front of me!?
Thanks for your time!
Eric
Check the below steps to deploy multiple Virtual Applications to Azure App Service from Visual Studio 2022.
Create a new App Service in Azure Portal.
In App Service Overview, click on the Download publish profile.
In VS 2022, create Applications of your desired framework. I have taken .NET Core Apps as an example.
Visual Studio Project Folder Structure
The option to create Virtual Directories in Azure Portal is available only for Azure Windows App Service.
In Azure Portal => App Service => Configuration => Path mappings => Under Virtual applications and directories create New Virtual application.
Make sure the Virtual Path is same as Web App Name in VisualStudio.
Publish each Application in VS to Azure App Service using the Downloaded Publish Profile.
Right click on the 1st WebApp Project => Publish => Add a publish profile => Import Profile.
Browse and upload the Publish Profile which we have downloaded from Azure Portal App Service.
Change the settings of the Application.
The site name must be the App Service name/VirtualPathName which we have created in portal.
Ex: Here it is VirtualApps29Dec/WebApp1.
Save and continue with next steps to publish the App.
Follow the same steps with the same Publish Profile for WebApp2, WebApp3 and WebApp4 as well.
Deployed Azure App Service Structure in KUDU Console
The Url's for the Applications will be
https://virtualapps29dec.azurewebsites.net/WebApp1
https://virtualapps29dec.azurewebsites.net/WebApp2
https://virtualapps29dec.azurewebsites.net/WebApp3
https://virtualapps29dec.azurewebsites.net/WebApp4
Initially When I tried to access the Applications, I got the below error.
When I check the Web.config of the deployed Applications, I can see the below code.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\WebApp2.dll" stdoutLogEnabled="false" stdoutLogFile="\\?\%home%\LogFiles\stdout" hostingModel="inprocess" />
</system.webServer>
</location>
</configuration>
<!--ProjectGuid: c238430b-40de-45d7-bbb7-ad96da7c4dc4-->
AspNetCoreModuleV2 will not allow multiple In-process virtual apps within the same app service plan.
I have resolved the issue by changing AspNetCoreModuleV2 to AspNetCoreModule
Edit all the Web.config files under the deployed Applications.
Output :

ADO.NET EF - can't connect to my DB (using Visual Studio 2010)

So I'm struggling with this problem for more than 4 hours and I don't know where to look at any more. I follow this tutorial for absolute beginners in ADO.NET Entity Framework - [See The tutorial][1] [1]: http://msdn.microsoft.com/en-us/data/jj193542
I'm using Microsoft SQL Server 2012 and I'm using this App.Config file for my project :
<?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=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=sqlserver2012; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
But I keep getting errors and when I use this code the error is : **An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string.**
I'm totally new to ADO.NET Entity Framework but as I see it the problem maybe is in defaultConnectionFactory configuration. But anyways I can't find out how to keep on and how to solve this problem.
if you in fact have SQL Server instance named sqlserver2012 on your localhost zour connectionString should look like this
<parameter value="Data Source=localhost\sqlserver2012; Integrated Security=True; MultipleActiveResultSets=True" />
Cheers,
T.

ADO.NET EF - can't establish DB connection using VS2010

I'm following this tutorial : http://msdn.microsoft.com/en-us/data/jj193542 for Code First basics using ADO.NET EF. The problem is that when executing the code the DataBase is not created automatically and I think that this is because the configurations in my app.config but it's my first day with real code and I can't figure out how to adjust my config file so I can connect to my server and use a created DataBase if neccessary or let the program from the tutorial create new database as expected from what is written.
This 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=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<!-- <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory> -->
<connectionStrings>
<add name="BloggingContext"
providerName="System.Data.SqlClient"
connectionString="server=milka-pc\sqlserver2012;Database=Panorama;user id=MyID;password=MyPass;port=3333;Integrated Security=True;"/>
</connectionStrings>
<!--<contexts>
<context type=" Blogging.BloggingContext, MyAssembly">
<databaseInitializer type="Blogging.MyCustomBlogInitializer, MyAssembly" />
</context>
</contexts>-->
</entityFramework>
</configuration>
As you can see some parts are commented as I tried a various things to make it work.
This is how y server explorer looks like while I'm trying to connect:
Also since I have zero experience with ViasualStudioXXXX and connecting to DataBases this is what I see and how I select my server:
There in milka-pc\sqlserver2012 I have a DB named Panorama which I can use or better follow the tutorial step by step and leave the program to create my new DB. For now I can't neither of these two. And to connect to milka-pc\sqlserver2012 I need to provied UserName and Password which I did in App.config. I say this just to know that these fields are not blank
If you are sure that milka-pc\sqlserver2012 is in fact working on port 3333 as you suggested
change your connectionstring to this:
<add name="BloggingContext"
providerName="System.Data.SqlClient"
connectionString="server=milka-pc\sqlserver2012,3333;Database=Panorama;user id=MyID;password=MyPass;Integrated Security=True;"/>
Just to make sure try that connection string in you SQL management studio with provided credentials.
If that doesnt work consult your sql server configuration manager, specifically under SQL server Network configuration make sure that your instance has enabled TCP/IP pipe with appropriate port enabled.
Cheers.

Error Debugging MVC 3 after Publish

I had done one publish to my MVC application. After that, I cannot debug it anymore!
This is the error. It seems that my visual studio web server is loading machine.config
Server Error in '/' Application.
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: The connection name 'LocalSqlServer' was not found in the applications configuration or the connection string is empty.
Source Error:
Line 255:
Line 256:
Source File: C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\machine.config Line: 257
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.237
This is how my web.config looks like, and there is nothing in my code that uses ASP.Net Membership as my authentication mode is "Windows".
I did manage to run it again in Visual Studio once, after I set the build mode from "Release" to "Debug" vice versa, but after I published again today.. The problem came back.
<configuration>
<connectionStrings>
<clear/>
<add name="ApplicationServices" connectionString="Data Source=SCG1SQL-64;Initial Catalog=Metallurgy;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="mandb100ConnectionString" connectionString="Data Source=scg1sql-64;Initial Catalog=mandb100;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="1.0.0.0" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<authentication mode="Windows"/>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</configuration>
Well, it is using the machine.config. There is a hierarchy of configuration. In other words, if you don't explicitly specify (or remove or clear) in your web.config, the base defaults will be pulled from the machine.config.
What your ASP.NET application will do is look for a web.config in the current directory for configuration. If that isn't found, or the desired configuration isn't found, it'll look to the application's web.config. Then for defaults, or uncleared or nonremoved items it'll also pull configuration from the machine.config.
But to the problem. What your error message is saying is that it can't find the LocalSqlServer connection string name anywhere. Are you sure that conn string name exists in your web.config?
Edit: Check your web.release.config file. You can find it in your Solution Explorer if you drop down the web.config file. Does that perhaps contain LocalSqlServer connection string?
This link might be of help: http://msdn.microsoft.com/en-us/library/webmatrix.webdata.preapplicationstartcode(v=vs.99).aspx
That's how I solved my problem. Apparently, this WebMatrix SimpleMembership is enabled by default. So I added this line in my web.config, and the problem disappeared!!!
<add key="enableSimpleMembership" value="false"/>
I know this is an old post, and as both these answers are correct to point you in the right direction to solve the issue, I'd like to add another solution if it might help anyone.
In my application an error occurred after I used the "Add Deployable Dependencies..." item in Solution Explorer, project context menu (right click on a project). This added a directory called _bin_deployableAssemblies with dlls needed to deploy your application on a server if it doesn't have some of them added to GAC. The dlls in the _bin_deployableAssemblies are copied to the bin directory of your application.
There were two dlls of interest that I wasn't using WebMatrix.Data and WebMatrix.WebData. Their presence in the bin directory of my application somehow messes the default membership provider resolving (correct me if I'm wrong, or add an explanation to what really happens :) ). The solution was to simply remove the offending dlls from the bin directory and from the _bin_deployableAssemblies as well.

nLog and TransactionScope

I have an ASP.NET MVC 3 (using Entity Framework 4.2) application that uses transactions as follows:
using (var transaction = new TransactionScope())
{
// Database action 1
// Database action 2
context.SaveChanges();
Logger.Info("Record X updated");
transaction.Complete();
}
I get no errors, but no data is written to the database. However, the log file target (there just for testing purposes) works fine. Here is my nLog (I'm using v2) config:
<?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"
throwExceptions="true"
internalLogToConsole="true"
internalLogToConsoleError="true" >
<targets>
<target name="logfile" xsi:type="File" fileName="${basedir}app_data\file.txt" />
<target xsi:type="Database" name="database">
<commandText>INSERT INTO [LogEntries] (TimeStamp, Message, Level, Logger) VALUES(GETDATE(), #msg, #level, #logger)</commandText>
<parameter name="#msg" layout="${message}" />
<parameter name="#level" layout="${level}" />
<parameter name="#logger" layout="${logger}" />
<dbProvider>System.Data.SqlServerCe.4.0</dbProvider>
<connectionString>Data Source=${basedir}app_data\Logger.sdf</connectionString>
</target>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="logfile" />
<logger name="*" minlevel="Trace" writeTo="database" />
</rules>
</nlog>
If I move the Logger line outside of the transactionscope it works fine. So I think it's something to do with this. I'm using SQL Server 2008 r2 for my main database and SQL Compact 4 for my logging database. Also, I've tried adding useTranscations="true".
Any ideas what I'm doing wrong?
Thanks
Alan
You are trying to have the transaction span two different servers, which is a distributed transaction. Unfortunately, SQLCE does not support distributed transactions (from the documentation):
Distributed transactions are not supported in SQL Server Compact. Therefore, a local transaction will not be automatically promoted to a fully distributable transaction.
I am curious why you don't log to the SQL 2008 R2 database, but if you must log to SQLCE, I think you'll have to track whether the transaction is committed and then determine whether to call NLog after the the TransactionScope block completes.

Resources