I know this question may be ridiculous but I could not find the answer. The Post sharp writes the logs in console by System.Diagnostics but I need to write the logs in a separate file. Is there any way to do so?
Thanks in advance
I found also I can do this in the app.config as the following:
<system.diagnostics>
<trace autoflush="true" indentsize="4">
<listeners>
<add name="myListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="C:\\log.txt" />
<remove name="Default" />
</listeners>
</trace>
</system.diagnostics>
You need to use System.Diagnostics.Trace.Listeners property to register your own listener. You would need code like this in your app's entry point:
using (StreamWriter sw = new StreamWriter("file.txt"))
using (TextWriterTraceListener tl = new TextWriterTraceListener(sw))
{
Trace.Listeners.Add(tl);
try
{
// execute your program here
}
finally
{
Trace.Listeners.Remove(tl);
}
}
Related
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.
We use the EnterpriseLibray to log error in our application. For some reason the log file stay locked until the pplication service is stopped.
Is there any option to leave the file unlocked when it's not in use? My goal is to create an external process (a kind of watchdog) that copy and zip the log file....but it's locked.
Any idea ?
This is what my app.config look like :
<loggingConfiguration name="" tracingEnabled="true" defaultCategory="General">
<listeners>
<add name="Rolling Flat File Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Culture=neutral, PublicKeyToken=31bf3856ad364e35" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Culture=neutral, PublicKeyToken=31bf3856ad364e35" fileName="Server.log" rollSizeKB="2024" footer="----------------------------------------" formatter="NovaLogFormatter" header="- NEW TRACE ----------------------------------------" rollFileExistsBehavior="Increment" maxArchivedFiles="20" />
</listeners>
<formatters>
<add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Culture=neutral, PublicKeyToken=31bf3856ad364e35" template="Timestamp: {timestamp(local)}{newline}
Message: {message}{newline}
Category: {category}{newline}
Severity: {severity}{newline}
Title: {title}{newline}
Machine: {localMachine}{newline}
App Domain: {localAppDomain}{newline}
Extended Properties:{newline}{dictionary({key}{newline}{value}{newline})}" name="NovaLogFormatter" />
</formatters>
<categorySources>
<add switchValue="All" name="General">
<listeners>
<add name="Rolling Flat File Trace Listener" />
</listeners>
</add>
<add switchValue="All" name="Data" />
<add switchValue="All" name="Security" />
</categorySources>
<specialSources>
<allEvents switchValue="All" name="All Events" />
<notProcessed switchValue="All" name="Unprocessed Category" />
<errors switchValue="All" name="Logging Errors & Warnings" />
</specialSources>
</loggingConfiguration>
The locking behavior is by design and inherited from the TraceListener base class.
There are a few options available to you:
Read through the lock
Since you are using RollingFlagFileTraceListener you could operate on archived files (which are no longer locked)
You could release the file lock after every write
Read Through the Lock
You can use code like this to read the contents of the file even though it's locked:
using(var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using(var sr = new StreamReader(fs))
{
while(!sr.EndOfStream)
{
Console.WriteLine(sr.ReadLine());
}
}
This should allow the watchdog to copy the file contents but you may have to manage state so that the same log entries are not copied multiple times (if that's important to you).
Copy Archived Files
Another idea is to only zip files that have been archived by the RollingFlatFileTraceListener. These files will not be locked. However, archiving does not occur at regular intervals so this may not be a good fit.
Release Lock
Another option is to release the lock by disposing of the LogWriter after writing a LogEntry. This will work but has a performance overhead (opening and closing the file) and requires you to manage concurrency (to avoid closing the LogWriter when another thread is using it).
Bonus
I hesitate to mention it but you could write a custom trace listener that does whatever you want. Probably not a great use of time but it is an option.
I developing an mvc web app with Entity Frame]work. I've enabled database migration so that i can add some seed data on each update.
More specifically, i want to add two users and two roles; so the configuration file looks like this:
var roles = (SimpleRoleProvider)Roles.Provider;
var membership = (SimpleMembershipProvider)Membership.Provider;
//// create two roles
if (!roles.RoleExists("Admin"))
{
roles.CreateRole("Admin");
}
if (!roles.RoleExists("User"))
{
roles.CreateRole("User");
}
However there seems to be a problem during the casting; it throws an exception
Unable to cast object of type 'System.Web.Security.SqlRoleProvider' to type 'WebMatrix.WebData.SimpleRoleProvider'.
I suspect that this might be a configuration issue, but i'm not really sure. Does anyone stumbled across the same problem?
That's because SqlRoleProvider does not inherit SimpleRoleProvider. However, you can try using SimpleRoleProvider Constructor (RoleProvider):
var roles = new SimpleRoleProvider(Roles.Provider);
I sorted this out. The problem apparently was related to web configuration. I added the following lines to the web.config file:
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
<providers>
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
</providers>
</roleManager>
to explicitly set the role provider. So now the Roles.Provider returns an instance of WebMatrix.WebData.SimpleRoleProvider; thus i don't need to cast any more
I solved this by placing below code in web.config between
<roleManager enabled="true" defaultProvider="simple">
<providers>
<clear />
<add name="simple" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
</providers>
</roleManager>
<membership defaultProvider="simple">
<providers>
<clear />
<add name="simple" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
I have dotless installed on my website and it's running perfectly on my local machine and on the companys testserver but when deploying on production server it always returns 404 and I can't figure out why.
This is what I've done so far to get it to work:
Added the section
<section name="dotless" type="dotless.Core.configuration.DotlessConfigurationSectionHandler, dotless.Core" />
Added the mimeMap
<staticContent>
<mimeMap fileExtension=".less" mimeType="text/css" />
</staticContent>
Added the handler
<add name="dotless" path="*.less" verb="GET" type="dotless.Core.LessCssHttpHandler,dotless.Core" resourceType="File" preCondition="" />
And added the dotless element
<dotless minifyCss="true" cache="true" />
Did you add the handler at the correct place?
IIS6: under system.web\httpHandlers
IIS7: under system.webServer\handlers
Also make sure you have all less files in place. If you import other less files, all those files must be available. If a file is missing, dotless throws 404.
i would like to set up an external configuration file that I can store in a directory for my WPF app, not necessarily the directory of my exe when I create my program either.
I created an App.Config file and added System.Configuration to my assembly. My App.Config has:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings file="sd.config">
<add key="username" value="joesmith" />
</appSettings>
</configuration>
and my sd.config (external file) which is in the root of my project for now, has
<?xml version="1.0"?>
<appSettings>
<add key="username1" value="janedoe" />
</appSettings>
in my MainWindow cs class I used
string username = ConfigurationManager.AppSettings.Get("username1");
which returns a null string. when i just retrieve the username field from App.Config it works. What did i miss? Thanks so much!
See the documentation on ConfigurationManager:
The AppSettings property:
Gets the AppSettingsSection data for the current application's default
configuration.
You need to do a little extra work to get data that isn't in your application's default configuration file.
Instead of using the file= attribute, add a key to your <appSettings> that defines the location of the secondary config file, like so:
<add key="configFile" value="sd.config"/>
Then, in order to use ConfigurationManager to pull settings from the secondary config file, you need to use its OpenMappedExeConfiguration method, which should look a little something like this:
var map = new ExeConfigurationFileMap();
map.ExeConfigFilename = Path.Combine(
AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
ConfigurationManager.AppSettings["configFile"]
);
//Once you have a Configuration reference to the secondary config file,
//you can access its appSettings collection:
var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
var userName1 = config.AppSettings["username1"];
That code might not be dead-on for your example, but hopefully it gets you on the right track!