Search Results

Search found 58 results on 3 pages for 'enterpriselibrary'.

Page 2/3 | < Previous Page | 1 2 3  | Next Page >

  • Enterprise Library Logging / Exception handling and Postsharp

    - by subodhnpushpak
    One of my colleagues came-up with a unique situation where it was required to create log files based on the input file which is uploaded. For example if A.xml is uploaded, the corresponding log file should be A_log.txt. I am a strong believer that Logging / EH / caching are cross-cutting architecture aspects and should be least invasive to the business-logic written in enterprise application. I have been using Enterprise Library for logging / EH (i use to work with Avanade, so i have affection towards the library!! :D ). I have been also using excellent library called PostSharp for cross cutting aspect. Here i present a solution with and without PostSharp all in a unit test. Please see full source code at end of the this blog post. But first, we need to tweak the enterprise library so that the log files are created at runtime based on input given. Below is Custom trace listner which writes log into a given file extracted out of Logentry extendedProperties property. using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration; using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners; using Microsoft.Practices.EnterpriseLibrary.Logging; using System.IO; using System.Text; using System; using System.Diagnostics;   namespace Subodh.Framework.Logging { [ConfigurationElementType(typeof(CustomTraceListenerData))] public class LogToFileTraceListener : CustomTraceListener {   private static object syncRoot = new object();   public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data) {   if ((data is LogEntry) & this.Formatter != null) { WriteOutToLog(this.Formatter.Format((LogEntry)data), (LogEntry)data); } else { WriteOutToLog(data.ToString(), (LogEntry)data); } }   public override void Write(string message) { Debug.Print(message.ToString()); }   public override void WriteLine(string message) { Debug.Print(message.ToString()); }   private void WriteOutToLog(string BodyText, LogEntry logentry) { try { //Get the filelocation from the extended properties if (logentry.ExtendedProperties.ContainsKey("filelocation")) { string fullPath = Path.GetFullPath(logentry.ExtendedProperties["filelocation"].ToString());   //Create the directory where the log file is written to if it does not exist. DirectoryInfo directoryInfo = new DirectoryInfo(Path.GetDirectoryName(fullPath));   if (directoryInfo.Exists == false) { directoryInfo.Create(); }   //Lock the file to prevent another process from using this file //as data is being written to it.   lock (syncRoot) { using (FileStream fs = new FileStream(fullPath, FileMode.Append, FileAccess.Write, FileShare.Write, 4096, true)) { using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8)) { Log(BodyText, sw); sw.Close(); } fs.Close(); } } } } catch (Exception ex) { throw new LoggingException(ex.Message, ex); } }   /// <summary> /// Write message to named file /// </summary> public static void Log(string logMessage, TextWriter w) { w.WriteLine("{0}", logMessage); } } }   The above can be “plugged into” the code using below configuration <loggingConfiguration name="Logging Application Block" tracingEnabled="true" defaultCategory="Trace" logWarningsWhenNoCategoriesMatch="true"> <listeners> <add listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.CustomTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" traceOutputOptions="None" filter="All" type="Subodh.Framework.Logging.LogToFileTraceListener, Subodh.Framework.Logging, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" name="Subodh Custom Trace Listener" initializeData="" formatter="Text Formatter" /> </listeners> Similarly we can use PostSharp to expose the above as cross cutting aspects as below using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using PostSharp.Laos; using System.Diagnostics; using GC.FrameworkServices.ExceptionHandler; using Subodh.Framework.Logging;   namespace Subodh.Framework.ExceptionHandling { [Serializable] public sealed class LogExceptionAttribute : OnExceptionAspect { private string prefix; private MethodFormatStrings formatStrings;   // This field is not serialized. It is used only at compile time. [NonSerialized] private readonly Type exceptionType; private string fileName;   /// <summary> /// Declares a <see cref="XTraceExceptionAttribute"/> custom attribute /// that logs every exception flowing out of the methods to which /// the custom attribute is applied. /// </summary> public LogExceptionAttribute() { }   /// <summary> /// Declares a <see cref="XTraceExceptionAttribute"/> custom attribute /// that logs every exception derived from a given <see cref="Type"/> /// flowing out of the methods to which /// the custom attribute is applied. /// </summary> /// <param name="exceptionType"></param> public LogExceptionAttribute( Type exceptionType ) { this.exceptionType = exceptionType; }   public LogExceptionAttribute(Type exceptionType, string fileName) { this.exceptionType = exceptionType; this.fileName = fileName; }   /// <summary> /// Gets or sets the prefix string, printed before every trace message. /// </summary> /// <value> /// For instance <c>[Exception]</c>. /// </value> public string Prefix { get { return this.prefix; } set { this.prefix = value; } }   /// <summary> /// Initializes the current object. Called at compile time by PostSharp. /// </summary> /// <param name="method">Method to which the current instance is /// associated.</param> public override void CompileTimeInitialize( MethodBase method ) { // We just initialize our fields. They will be serialized at compile-time // and deserialized at runtime. this.formatStrings = Formatter.GetMethodFormatStrings( method ); this.prefix = Formatter.NormalizePrefix( this.prefix ); }   public override Type GetExceptionType( MethodBase method ) { return this.exceptionType; }   /// <summary> /// Method executed when an exception occurs in the methods to which the current /// custom attribute has been applied. We just write a record to the tracing /// subsystem. /// </summary> /// <param name="context">Event arguments specifying which method /// is being called and with which parameters.</param> public override void OnException( MethodExecutionEventArgs context ) { string message = String.Format("{0}Exception {1} {{{2}}} in {{{3}}}. \r\n\r\nStack Trace {4}", this.prefix, context.Exception.GetType().Name, context.Exception.Message, this.formatStrings.Format(context.Instance, context.Method, context.GetReadOnlyArgumentArray()), context.Exception.StackTrace); if(!string.IsNullOrEmpty(fileName)) { ApplicationLogger.LogException(message, fileName); } else { ApplicationLogger.LogException(message, Source.UtilityService); } } } } To use the above below is the unit test [TestMethod] [ExpectedException(typeof(NotImplementedException))] public void TestMethod1() { MethodThrowingExceptionForLog(); try { MethodThrowingExceptionForLogWithPostSharp(); } catch (NotImplementedException ex) { throw ex; } }   private void MethodThrowingExceptionForLog() { try { throw new NotImplementedException(); } catch (NotImplementedException ex) { // create file and then write log ApplicationLogger.TraceMessage("this is a trace message which will be logged in Test1MyFile", @"D:\EL\Test1Myfile.txt"); ApplicationLogger.TraceMessage("this is a trace message which will be logged in YetAnotherTest1Myfile", @"D:\EL\YetAnotherTest1Myfile.txt"); } }   // Automatically log details using attributes // Log exception using attributes .... A La WCF [FaultContract(typeof(FaultMessage))] style] [Log(@"D:\EL\Test1MyfileLogPostsharp.txt")] [LogException(typeof(NotImplementedException), @"D:\EL\Test1MyfileExceptionPostsharp.txt")] private void MethodThrowingExceptionForLogWithPostSharp() { throw new NotImplementedException(); } The good thing about the approach is that all the logging and EH is done at centralized location controlled by PostSharp. Of Course, if some other library has to be used instead of EL, it can easily be plugged in. Also, the coder ARE ONLY involved in writing business code in methods, which makes code cleaner. Here is the full source code. The third party assemblies provided are from EL and PostSharp and i presume you will find these useful. Do let me know your thoughts / ideas on the same. Technorati Tags: PostSharp,Enterprize library,C#,Logging,Exception handling

    Read the article

  • Autoscaling in a modern world&hellip;. Part 3

    - by Steve Loethen
    The Wasabi Hands on Labs give you a good look at the basic mechanics, but I don’t find the setup too practical.  Using a local console application to host the Autoscaler and rules files is probably the (IMHO) least likely architecture.  Far more common would be hosting in a service on premise (if you want to have the Autoscaler local) or most likely, host it in a Azure role of it’s own.  I chose to go the Azure route. First step was to get the rules.xml and the services.xml files into the cloud.  I tend to be a “one step at a time” sort of guy, so running the console application with the rules sitting in a Azure hosted set of blobs seemed to be the logical first step.  Here are the steps: 1) Create a container in the storage account you wish to use.  Name does not matter, you will get a chance to set the container name (as well as the file names) in the app.config 2) Copy the two files from where you created them to your  container.  I used the same files I had locally.  I made the container public to eliminate security issues, but in the final application, a bit of security needs to be applied (one problem at a time).  The content type was set to text/xml.  I found one reference claiming the importance of this step, and it makes sense. 3) Adjust the app.config to set the location of the files.  This will let you set all the storage account and key information needed to reach into the cloud form your console application.  The sections of your app.config will look like this: <rulesStores> <add name="Blob Rules Store" type="Microsoft.Practices.EnterpriseLibrary.WindowsAzure.Autoscaling.Rules.Configuration.BlobXmlFileRulesStore, Microsoft.Practices.EnterpriseLibrary.WindowsAzure.Autoscaling, Version=5.0.1118.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" blobContainerName="[ContainerName]" blobName="rules.xml" storageAccount="DefaultEndpointsProtocol=https;AccountName=[StorageAccount];AccountKey=[AccountKey]" monitoringRate="00:00:30" certificateThumbprint="" certificateStoreLocation="LocalMachine" checkCertificateValidity="false" /> </rulesStores> <serviceInformationStores> <add name="Blob Service Information Store" type="Microsoft.Practices.EnterpriseLibrary.WindowsAzure.Autoscaling.ServiceModel.Configuration.BlobXmlFileServiceInformationStore, Microsoft.Practices.EnterpriseLibrary.WindowsAzure.Autoscaling, Version=5.0.1118.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" blobContainerName="[ContainerName]" blobName="services.xml" storageAccount="DefaultEndpointsProtocol=https;AccountName=[StorageAccount];AccountKey=[AccountKey]" monitoringRate="00:00:30" certificateThumbprint="" certificateStoreLocation="LocalMachine" checkCertificateValidity="false" /> </serviceInformationStores> Once I had the files up in the sky, I renamed the local copies to just to make my self feel better about the application using the correct set of rules and services.  Deploy the web role to the cloud.  Once it is up and running, start the console application.  You should find the application scales up and down in response to the buttons on the web site.  Tune in next time for moving the hosting of the Autoscaler to a worker role, discussions on getting the logging information into diagnostics into storage, and a set of discussions about certs and how they play a role.

    Read the article

  • Multiple Exception Handlers for one exception type

    - by danish
    I am using Enterprose Library 4.1. I have created a custom exception handler called CustomHandler. This is how the configuration section would look like: <exceptionHandling> <exceptionPolicies> <add name="Exception Policy"> <exceptionTypes> <add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" postHandlingAction="NotifyRethrow" name="Exception"> <exceptionHandlers> <add type="WindowsFormsApplication1.CustomHandler, WindowsFormsApplication1" name="Custom Handler" /> <add exceptionMessage="Some test mesage." exceptionMessageResourceName="" exceptionMessageResourceType="" replaceExceptionType="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionHandlingException, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ReplaceHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling" name="Replace Handler" /> </exceptionHandlers> </add> </exceptionTypes> </add> </exceptionPolicies> </exceptionHandling> There are two handlers for same exception type. What I want is that based on a certain condition one of the handlers should handle the exception. Any ideas how that can be done? Is there a way to call the other handler from inside the HandleException method of the custom handler based on some condition?

    Read the article

  • Upgrading EntLib 4.1 to 5 with Oracle.DataAccess.Client

    - by mlk
    Hello, I am upgrading a project from EntLib 4.1 to EntLib 5. I've skimmed through the Migration Guide, changed all the references and updated all the config files to point to EntLib 5. All worked fine accept Oracle database access. With the config file: <configuration> <configSections> <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" /> </configSections> <dataConfiguration defaultDatabase="prod"> <providerMappings> <add databaseType="Microsoft.Practices.EnterpriseLibrary.Data.Oracle.OracleDatabase, Microsoft.Practices.EnterpriseLibrary.Data" name="Oracle.DataAccess.Client" /> </providerMappings> </dataConfiguration> <connectionStrings> <add name="prod" connectionString="Data Source=dev;User Id=dev;Password=dev;" providerName="Oracle.DataAccess.Client" /> </connectionStrings> </configuration> which worked with 4.1 all calls to DatabaseFactory.CreateDatabase() fails with: System.InvalidOperationException: The type Database cannot be constructed. You must configure the container to supply this value. If I replace Oracle.DataAccess.Client with the Microsoft System.Data.Oracleclient it all works again, but is not full of ODP.net lovelyness. Does anyone know how to get this to work with EntLib 5? Cheers, Mlk

    Read the article

  • Modify loggingConfiguration Programmatic (enterprise library)

    - by alhambraeidos
    Hi all, I have app.config in m win application, and loggingConfiguration section (enterprise library 4.1). I need do this programatically, Get a list of all listener in loggingConfiguration Modify property fileName=".\Trazas\Excepciones.log" of several RollingFlatFileTraceListener's Modify several properties of AuthenticatingEmailTraceListener listener, Any help, please, I havent found any reference or samples Thanks in advanced. Greetings <listeners> <add name="Excepciones RollingFile Listener" fileName=".\Trazas\Excepciones.log" formatter="Text Single Formatter" footer="&lt;/Excepcion&gt;" header="&lt;Excepcion&gt;" rollFileExistsBehavior="Overwrite" rollInterval="None" rollSizeKB="1500" timeStampPattern="yyyy-MM-dd" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" traceOutputOptions="None" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> <add name="AuthEmailTraceListener" type="zzzz.Frk.Logging.AuthEmailTraceListener.AuthenticatingEmailTraceListener, zzzz.Frk.Logging.AuthEmailTraceListener" listenerDataType="zzzz.Frk.Logging.AuthEmailTraceListener.AuthenticatingEmailTraceListenerData, zzzz.Frk.Logging.AuthEmailTraceListener" formatter="Exception Formatter" traceOutputOptions="None" toAddress="[email protected]" fromAddress="[email protected]" subjectLineStarter=" Excepción detectada - " subjectLineEnder="incidencias" smtpServer="smtp.gmail.com" smtpPort="587" authenticate="true" username="[email protected]" password="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" enableSsl="true" />

    Read the article

  • 640 enterprise library caching threads - how?

    - by JohnW
    We have an application that is undergoing performance testing. Today, I decided to take a dump of w3wp & load it in windbg to see what is going on underneath the covers. Imagine my surprise when I ran !threads and saw that there are 640 background threads, almost all of which seem to say the following: OS Thread Id: 0x1c38 (651) Child-SP RetAddr Call Site 0000000023a9d290 000007ff002320e2 Microsoft.Practices.EnterpriseLibrary.Caching.ProducerConsumerQueue.WaitUntilInterrupted() 0000000023a9d2d0 000007ff00231f7e Microsoft.Practices.EnterpriseLibrary.Caching.ProducerConsumerQueue.Dequeue() 0000000023a9d330 000007fef727c978 Microsoft.Practices.EnterpriseLibrary.Caching.BackgroundScheduler.QueueReader() 0000000023a9d380 000007fef9001552 System.Threading.ExecutionContext.runTryCode(System.Object) 0000000023a9dc30 000007fef72f95fd System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object) 0000000023a9dc80 000007fef9001552 System.Threading.ThreadHelper.ThreadStart() If i had to give a guess, I'm thinkign that one of these threads are getting spawned for each run of our app - we have 2 app servers, 20 concurrent users, and ran the test approximately 30 times...it's in the neighborhood. Is this 'expected behavior', or perhaps have we implemented something improperly? The test ran hours ago, so i would have expected any timeouts to have occurred already.

    Read the article

  • .NET Single Line Logging (ala Trace.Write/WriteLine) using Instrumentation.Logging

    - by KnownColor
    Hello Everyone, My question is whether it is possible to get line/multiline (very unsure of correct term for this) behaviour of the Trace.Write and Trace.WriteLine methods but using the Microsoft Instrumentation Logging framework in .NET 2.0. Desired Output Hello World! Oh Hai. What I Currently Have Trace.Write("Hello "); Trace.WriteLine("World!"); Trace.Write("Oh Hai."); I would prefer to use instrumentation to log rather than writing to a log file using Debug.Trace. EDIT: By Instrumentation Logging I mean using a 'loggingConfiguration' block in my App.config and writing Log Entries using using Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(LogEntry logEntry); Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=2.0.0.0 for example. Ta, KnownColor

    Read the article

  • How to create a new WCF/MVC/jQuery application from scratch

    - by pjohnson
    As a corporate developer by trade, I don't get much opportunity to create from-the-ground-up web sites; usually it's tweaks, fixes, and new functionality to existing sites. And with hobby sites, I often don't find the challenges I run into with enterprise systems; usually it's starting from Visual Studio's boilerplate project and adding whatever functionality I want to play around with, rarely deploying outside my own machine. So my experience creating a new enterprise-level site was a bit dated, and the technologies to do so have come a long way, and are much more ready to go out of the box. My intention with this post isn't so much to provide any groundbreaking insights, but to just tie together a lot of information in one place to make it easy to create a new site from scratch. Architecture One site I created earlier this year had an MVC 3 front end and a WCF 4-driven service layer. Using Visual Studio 2010, these project types are easy enough to add to a new solution. I created a third Class Library project to store common functionality the front end and services layers both needed to access, for example, the DataContract classes that the front end uses to call services in the service layer. By keeping DataContract classes in a separate project, I avoided the need for the front end to have an assembly/project reference directly to the services code, a bit cleaner and more flexible of an SOA implementation. Consuming the service Even by this point, VS has given you a lot. You have a working web site and a working service, neither of which do much but are great starting points. To wire up the front end and the services, I needed to create proxy classes and WCF client configuration information. I decided to use the SvcUtil.exe utility provided as part of the Windows SDK, which you should have installed if you installed VS. VS also provides an Add Service Reference command since the .NET 1.x ASMX days, which I've never really liked; it creates several .cs/.disco/etc. files, some of which contained hardcoded URL's, adding duplicate files (*1.cs, *2.cs, etc.) without doing a good job of cleaning up after itself. I've found SvcUtil much cleaner, as it outputs one C# file (containing several proxy classes) and a config file with settings, and it's easier to use to regenerate the proxy classes when the service changes, and to then maintain all your configuration in one place (your Web.config, instead of the Service Reference files). I provided it a reference to a copy of my common assembly so it doesn't try to recreate the data contract classes, had it use the type List<T> for collections, and modified the output files' names and .NET namespace, ending up with a command like: svcutil.exe /l:cs /o:MyService.cs /config:MyService.config /r:MySite.Common.dll /ct:System.Collections.Generic.List`1 /n:*,MySite.Web.ServiceProxies http://localhost:59999/MyService.svc I took the generated MyService.cs file and drop it in the web project, under a ServiceProxies folder, matching the namespace and keeping it separate from classes I coded manually. Integrating the config file took a little more work, but only needed to be done once as these settings didn't often change. A great thing Microsoft improved with WCF 4 is configuration; namely, you can use all the default settings and not have to specify them explicitly in your config file. Unfortunately, SvcUtil doesn't generate its config file this way. If you just copy & paste MyService.config's contents into your front end's Web.config, you'll copy a lot of settings you don't need, plus this will get unwieldy if you add more services in the future, each with its own custom binding. Really, as the only mandatory settings are the endpoint's ABC's (address, binding, and contract) you can get away with just this: <system.serviceModel>  <client>    <endpoint address="http://localhost:59999/MyService.svc" binding="wsHttpBinding" contract="MySite.Web.ServiceProxies.IMyService" />  </client></system.serviceModel> By default, the services project uses basicHttpBinding. As you can see, I switched it to wsHttpBinding, a more modern standard. Using something like netTcpBinding would probably be faster and more efficient since the client & service are both written in .NET, but it requires additional server setup and open ports, whereas switching to wsHttpBinding is much simpler. From an MVC controller action method, I instantiated the client, and invoked the method for my operation. As with any object that implements IDisposable, I wrapped it in C#'s using() statement, a tidy construct that ensures Dispose gets called no matter what, even if an exception occurs. Unfortunately there are problems with that, as WCF's ClientBase<TChannel> class doesn't implement Dispose according to Microsoft's own usage guidelines. I took an approach similar to Technology Toolbox's fix, except using partial classes instead of a wrapper class to extend the SvcUtil-generated proxy, making the fix more seamless from the controller's perspective, and theoretically, less code I have to change if and when Microsoft fixes this behavior. User interface The MVC 3 project template includes jQuery and some other common JavaScript libraries by default. I updated the ones I used to the latest versions using NuGet, available in VS via the Tools > Library Package Manager > Manage NuGet Packages for Solution... > Updates. I also used this dialog to remove packages I wasn't using. Given that it's smart enough to know the difference between the .js and .min.js files, I was hoping it would be smart enough to know which to include during build and publish operations, but this doesn't seem to be the case. I ended up using Cassette to perform the minification and bundling of my JavaScript and CSS files; ASP.NET 4.5 includes this functionality out of the box. The web client to web server link via jQuery was easy enough. In my JavaScript function, unobtrusively wired up to a button's click event, I called $.ajax, corresponding to an action method that returns a JsonResult, accomplished by passing my model class to the Controller.Json() method, which jQuery helpfully translates from JSON to a JavaScript object.$.ajax calls weren't perfectly straightforward. I tried using the simpler $.post method instead, but ran into trouble without specifying the contentType parameter, which $.post doesn't have. The url parameter is simple enough, though for flexibility in how the site is deployed, I used MVC's Url.Action method to get the URL, then sent this to JavaScript in a JavaScript string variable. If the request needed input data, I used the JSON.stringify function to convert a JavaScript object with the parameters into a JSON string, which MVC then parses into strongly-typed C# parameters. I also specified "json" for dataType, and "application/json; charset=utf-8" for contentType. For success and error, I provided my success and error handling functions, though success is a bit hairier. "Success" in this context indicates whether the HTTP request succeeds, not whether what you wanted the AJAX call to do on the web server was successful. For example, if you make an AJAX call to retrieve a piece of data, the success handler will be invoked for any 200 OK response, and the error handler will be invoked for failed requests, e.g. a 404 Not Found (if the server rejected the URL you provided in the url parameter) or 500 Internal Server Error (e.g. if your C# code threw an exception that wasn't caught). If an exception was caught and handled, or if the data requested wasn't found, this would likely go through the success handler, which would need to do further examination to verify it did in fact get back the data for which it asked. I discuss this more in the next section. Logging and exception handling At this point, I had a working application. If I ran into any errors or unexpected behavior, debugging was easy enough, but of course that's not an option on public web servers. Microsoft Enterprise Library 5.0 filled this gap nicely, with its Logging and Exception Handling functionality. First I installed Enterprise Library; NuGet as outlined above is probably the best way to do so. I needed a total of three assembly references--Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging, and Microsoft.Practices.EnterpriseLibrary.Logging. VS links with the handy Enterprise Library 5.0 Configuration Console, accessible by right-clicking your Web.config and choosing Edit Enterprise Library V5 Configuration. In this console, under Logging Settings, I set up a Rolling Flat File Trace Listener to write to log files but not let them get too large, using a Text Formatter with a simpler template than that provided by default. Logging to a different (or additional) destination is easy enough, but a flat file suited my needs. At this point, I verified it wrote as expected by calling the Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write method from my C# code. With those settings verified, I went on to wire up Exception Handling with Logging. Back in the EntLib Configuration Console, under Exception Handling, I used a LoggingExceptionHandler, setting its Logging Category to the category I already had configured in the Logging Settings. Then, from code (e.g. a controller's OnException method, or any action method's catch block), I called the Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ExceptionPolicy.HandleException method, providing the exception and the exception policy name I had configured in the Exception Handling Settings. Before I got this configured correctly, when I tried it out, nothing was logged. In working with .NET, I'm used to seeing an exception if something doesn't work or isn't set up correctly, but instead working with these EntLib modules reminds me more of JavaScript (before the "use strict" v5 days)--it just does nothing and leaves you to figure out why, I presume due in part to the listener pattern Microsoft followed with the Enterprise Library. First, I verified logging worked on its own. Then, verifying/correcting where each piece wires up to the next resolved my problem. Your C# code calls into the Exception Handling module, referencing the policy you pass the HandleException method; that policy's configuration contains a LoggingExceptionHandler that references a logCategory; that logCategory should be added in the loggingConfiguration's categorySources section; that category references a listener; that listener should be added in the loggingConfiguration's listeners section, which specifies the name of the log file. One final note on error handling, as the proper way to handle WCF and MVC errors is a whole other very lengthy discussion. For AJAX calls to MVC action methods, depending on your configuration, an exception thrown here will result in ASP.NET'S Yellow Screen Of Death being sent back as a response, which is at best unnecessarily and uselessly verbose, and at worst a security risk as the internals of your application are exposed to potential hackers. I mitigated this by overriding my controller's OnException method, passing the exception off to the Exception Handling module as above. I created an ErrorModel class with as few properties as possible (e.g. an Error string), sending as little information to the client as possible, to both maximize bandwidth and mitigate risk. I then return an ErrorModel in JSON format for AJAX requests: if (filterContext.HttpContext.Request.IsAjaxRequest()){    filterContext.Result = Json(new ErrorModel(...));    filterContext.ExceptionHandled = true;} My $.ajax calls from the browser get a valid 200 OK response and go into the success handler. Before assuming everything is OK, I check if it's an ErrorModel or a model containing what I requested. If it's an ErrorModel, or null, I pass it to my error handler. If the client needs to handle different errors differently, ErrorModel can contain a flag, error code, string, etc. to differentiate, but again, sending as little information back as possible is ideal. Summary As any experienced ASP.NET developer knows, this is a far cry from where ASP.NET started when I began working with it 11 years ago. WCF services are far more powerful than ASMX ones, MVC is in many ways cleaner and certainly more unit test-friendly than Web Forms (if you don't consider the code/markup commingling you're doing again), the Enterprise Library makes error handling and logging almost entirely configuration-driven, AJAX makes a responsive UI more feasible, and jQuery makes JavaScript coding much less painful. It doesn't take much work to get a functional, maintainable, flexible application, though having it actually do something useful is a whole other matter.

    Read the article

  • ASP.NET Sql Timeout

    - by Petoj
    Well we have this Asp.Net application that we installed at a customer but now some times we get a SqlException that says "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding." now the wired thing is that the exception comes instantly when i press the button, this does not happen every time i press the button so its random.. any idea what i could try to pinpoint the problem? We are using the EnterpriseLibrary Database block if that matters... Stack trace: at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlDataReader.ConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) at Microsoft.Practices.EnterpriseLibrary.Data.Database.DoExecuteReader(DbCommand command, CommandBehavior cmdBehavior) at Microsoft.Practices.EnterpriseLibrary.Data.Database.ExecuteReader(DbCommand command)

    Read the article

  • Can expiration policies be configured in entlib caching application block?

    - by stesoc
    Hi, Is there a way to tell a CacheManager that every item added will have the same expiration policy? For example in: <cachingConfiguration defaultCacheManager="DefaultCacheManager"> <cacheManagers> <add name="TestCM" expirationPollFrequencyInSeconds="60" maximumElementsInCacheBeforeScavenging="1000" numberToRemoveWhenScavenging="10" backingStoreName="Null Storage" type="Microsoft.Practices.EnterpriseLibrary.Caching.CacheManager, Microsoft.Practices.EnterpriseLibrary.Caching, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> I expected to have some attribute like expirationPolicy="AbsoluteTime" or "SlidingTime" and a expirationValue="..." for specifying the timespan to use. Thanks, s.

    Read the article

  • System.IO.FileLoadException

    - by Raj G
    Hi All, I have got this error when using Enterprise Library 3.1 May 2007 version. We are developing a product and have a common lib directory beneath the Subversion Trunk directory <\Trunk\Lib\ into which we put all the third party DLLs. Inside this we have Microsoft\EnterpriseLibrary\v3.1 in which we have copied all the dlls from \Program Files\Microsoft Enterprise Library May2007\bin. Everything was working properly until one of the developers installed the source code on this machine. There were some dlls copied at the end of the source code installation and once that was done, he is not able to run the project anymore. He always gets this error 'Microsoft.Practices.EnterpriseLibrary.Data, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)' What is the problem here? I thought that when the source code was installed it was just supposed to build everything and copy in the bin directory within the source code parent directory. Also we have copied the Dlls from Microsoft Enterprise Library May 2007\bin directory into our product development directory and references into our project with a copylocal flag set to true. Can anyone help me out here RK

    Read the article

  • How to reproduce System.Security.Cryptography.SHA1Managed result in Python

    - by joetyson
    Here's the deal: I'm moving a .NET website to Python. I have a database with passwords hashed using the System.Security.Cryptography.SHA1Managed utility. I'm creating the hash in .NET with the following code: string hashedPassword = Cryptographer.CreateHash("MYHasher", userInfo.Password); The MYHasher block looks like this: <add algorithmType="System.Security.Cryptography.SHA1Managed, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=blahblahblah" saltEnabled="true" type="Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.HashAlgorithmProvider, Microsoft.Practices.EnterpriseLibrary.Security.Cryptography, Version=3.0.0.0, Culture=neutral, PublicKeyToken=daahblahdahdah" name="MYHasher" /> So for a given password, I get back and store in the database a 48 byte salted sha1. I assume the last 8 bytes are the salt. I have tried to reproduce the hashing process in python by doing a sha1(salt + password) and sha1(password + salt) but I'm having no luck. My question to you: How are the public keys being used? How is the password rehashed using the salt. How is the salt created? (e.g., When I say saltEnabled="true", what extra magic happens?) I need specific details that don't just reference other .NET libraries, I'm looking for the actual operational logic that happens in the blackbox. Thanks!

    Read the article

  • HTTP Error 500.19 Internal Server Error

    - by Attilah
    I created and deployed a pretty simple WCF Service. but when accessing it from IE, I get this : HTTP Error 500.19 - Internal Server Error Description: The requested page cannot be accessed because the related configuration data for the page is invalid. Error Code: 0x80070005 Notification: BeginRequest Module: IIS Web Core Requested URL: http://localhost:80/ProductsService/ProductsService.svc Physical Path: C:\Users\Administrator\Documents\Visual Studio 2008\Projects\ProductsService\ProductsService\ProductsService.svc Logon User: Not yet determined Logon Method: Not yet determined Handler: Not yet determined Config Error: Cannot read configuration file Config File: \\?\C:\Users\Administrator\Documents\Visual Studio 2008\Projects \ProductsService\ProductsService\web.config Config Source: -1: 0: More Information... This error occurs when there is a problem reading the configuration file for the Web server or Web application. In some cases, the event logs may contain more information about what caused this error. here is the content of my web.config file : <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> </configSections> <dataConfiguration defaultDatabase="AdventureWorksConnection" /> <connectionStrings> <add name="AdventureWorksConnection" connectionString="Database=AdventureWorks; Server=(localhost)\SQLEXPRESS;Integrated Security=SSPI" providerName="System.Data.SqlClient" /> </connectionStrings> <system.serviceModel> <services> <service name="Products.ProductsService"> <endpoint address="" binding="basicHttpBinding" contract="Products.IProductsService" /> </service> </services> </system.serviceModel> </configuration>

    Read the article

  • Set the property hibernate.dialect error message

    - by user281180
    I am having the following error when configuring mvc3 and Nhibernate. Can anyone guide me what I have missed please. the dialect was not set. Set the property hibernate.dialect. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: NHibernate.HibernateException: The dialect was not set. Set the property hibernate.dialect. Source Error: Line 16: { Line 17: NHibernate.Cfg.Configuration configuration = new NHibernate.Cfg.Configuration(); Line 18: configuration.AddAssembly(System.Reflection.Assembly.GetExecutingAssembly()); Line 19: sessionFactory = configuration.BuildSessionFactory(); Line 20: } My web.config is as follows: <configSections> <section name="cachingConfiguration"type="Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.CacheManagerSettings,Microsoft.Practices.EnterpriseLibrary.Caching"/> <section name="log4net"type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/> <section name="hibernate-configuration"type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/ <appSettings> <add key="BusinessObjectAssemblies" value="Keeper.API"></add> <add key="ConnectionString" value="Server=localhost\SQLSERVER2005;Database=KeeperDev;User=test;Pwd=test;"></add> <add key="ClientValidationEnabled" value="true"/> <add key="UnobtrusiveJavaScriptEnabled" value="true"/> </appSettings> <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"> <session-factory> <property name="dialect">NHibernate.Dialect.MsSql2000Dialect</property> <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property> <property name="connection.connection_string">Server=localhost\SQLServer2005;Database=KeeperDev;User=test;Pwd=test;</property> <property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property> </session-factory> </hibernate-configuration>

    Read the article

  • How to not specify ruleset name when reading from config file?

    - by user102533
    When I read rules from a configuration file, I do something like this: IConfigurationSource configurationSource = new FileConfigurationSource("myvalidation.config"); var validator = ValidationFactory.CreateValidator<Salary>(configurationSource); The config file looks like this: <ruleset name="Default"> <properties> <property name="Address"> <validator lowerBound="10" lowerBoundType="Inclusive" upperBound="15" upperBoundType="Inclusive" negated="false" messageTemplate="" messageTemplateResourceName="" messageTemplateResourceType="" tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.StringLengthValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=4.1.0.0, Culture=neutral, PublicKeyToken=null" name="String Length Validator" /> </property> </properties> </ruleset> My question is - is there a way to not specify the ruleset name? It's not required for me to specify a ruleset name if I am using the attribute approach and I can validate using: ValidationResults results = Validation.Validate(salary); Now when reading from config files, I have to specify the ruleset name. There is no overload of the CreateValidator method that accepts the configuration source without specifying the ruleset name. Also, the xml in the config file requires a name attribute for ruleset

    Read the article

  • how can i learn Enterprise library 4.0 ?

    - by ykaratoprak
    I try to learn Enterprise Library. i find these useful codes to get data from sql. But i try to send data via parameter. also use UPDATE, DELETE, SAVe method. Do you give sama sample? i'm using enterprise 4.0 !!! using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using Microsoft.Practices.EnterpriseLibrary.Common; using Microsoft.Practices.EnterpriseLibrary.Data; namespace WebApplicationForEnterpirires { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Database objdbase = DatabaseFactory.CreateDatabase("connectionString"); DataSet ds = objdbase.ExecuteDataSet(CommandType.StoredProcedure, "sp_GetProducts"); GridView1.DataSource = ds; GridView1.DataBind(); } } }

    Read the article

  • wpf & validation application block > message localization > messageTemplateResource Name&Type

    - by Shaboboo
    I'm trying to write validation rules for my data objects in a WPF application. I'm writing them in the configuration file, and so far they are working fine. I'm stumped on how to localize the messages using messageTemplateResourceName and messageTemplateResourceType. What I know is that the strings can be writen in a resource file, given a name and referenced by that name. I get the idea, but i haven't been able to make this work. <ruleset name="Rule Set"> <properties> <property name="StringValue"> <validator lowerBound="0" lowerBoundType="Ignore" upperBound="25" upperBoundType="Inclusive" negated="false" messageTemplate="" messageTemplateResourceName="msg1" messageTemplateResourceType="Resources" tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.StringLengthValidator, Microsoft.Practices.EnterpriseLibrary.Validation" name="String Length Validator" /> </property> </properties> </ruleset> Where is the resource file and what value do I pass to messageTemplateResourceType? I have tried writing the messages in the shell project's resource file but no sucess trying to retrieve the value. I only get the default built-in message. I've tried messageTemplateResourceType="typeof(Resources)" messageTemplateResourceType="Resources" messageTemplateResourceType="Resources.resx" messageTemplateResourceType="typeof(Shell)" messageTemplateResourceType="Shell" messageTemplateResourceType="Shell, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" I've also tried adding a new resource file in the shell project, and adding a resource file to the data object's library. I'm all out of ideas Does anyone have any suggestions? I'm not even married to the idea of resource files, so if there are other ways to localize these messages I'd love to know! thanks

    Read the article

  • Section or group name 'cachingConfiguration' is already defined - but where?

    - by Richard Ev
    On Windows XP I am working on a .NET 3.5 web app that's a combination of WebForms and MVC2 (The WebForms parts are legacy, and being migrated to MVC). When I run this from VS2008 using the ASP.NET web server everything works as expected. However, when I host the app in IIS and try to use it, I see the following error Section or group name 'cachingConfiguration' is already defined. Updates to this may only occur at the configuration level where it is defined. Source Error: Line 24: </sectionGroup> Line 25: <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> Line 26: <section name="cachingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.CacheManagerSettings,Microsoft.Practices.EnterpriseLibrary.Caching, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> Line 27: </configSections> Line 28: Sure enough, if I remove the offending line (line 26 in the error message) from my web.config then the app runs correctly. However, I really need to find out where the duplicate definition of this is. It's nowhere in my solution. Where else could it be?

    Read the article

  • could not execute a stored procedure(using DAAB) from a client(aspx page) to a wcf service

    - by user1144695
    i am trying to store data to sql database from a asp.net client website through a stored procedure(using DAAB) in a wcf service hosted in a asp.net empty website.When i try to store data to the DB i get the following error: ** - The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework SDK documentation and inspect the server trace logs. ** When i try to debug i get the following exception: Activation error occured while trying to get instance of type Database, key "" in the code-- Database db = EnterpriseLibraryContainer.Current.GetInstance<Database>("MyInstance"); where my app.config is <?xml version="1.0"?> <configuration> <configSections> <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true"/> </configSections> <dataConfiguration defaultDatabase="MyInstance"/> <connectionStrings> <add name="MyInstance" connectionString="Data Source=BLRKDAS307581\KD;Integrated Security=True;User ID=SAPIENT\kdas3;Password=ilove0LINUX" providerName="System.Data.SqlClient" /> </connectionStrings> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> </startup> </configuration> Can anyone help me with it? Thanks in advance...

    Read the article

  • A C# app that references a C# dll which uses Enterprise Library is throwing an error

    - by Matt
    I have a C# app that references another C# dll which in turn uses Enterprise Library. Because my app has no config xml file for setting the Enterprise Library settings, it is throwing an error, specifically: "The configuration section for Logging cannot be found in the configuration source." "Microsoft.Practices.EnterpriseLibrary.Logging" I would rather not add an XML config file to my app to just turn off Enterprise Library. Is there a code way to do so in my the source for my app? EDIT: I'm on EL 4.1

    Read the article

  • Custom validator not invoked when using Validation Application Block through configuration

    - by Chris
    I have set up a ruleset in my configuration file which has two validators, one of which is a built-in NotNullValidator, the other of which is a custom validator. The problem is that I see the NotNullValidator hit, but not my custom validator. The custom validator is being used to validate an Entity Framework entity object. I have used the debugger to confirm the NotNull is hit (I forced a failure condition so I saw it set an invalid result), but it never steps into the custom one. I am using MVC as the web app, so I defined the ruleset in a config file at that layer, but my custom validator is defined in another project. However, I wouldn't have thought that to be a problem because when I use the Enterprise Library Configuration tool inside Visual Studio 2008 it is able to set the type properly for the custom validator. As well, I believe the custom validator is fine as it builds ok, and the config tool can reference it properly. Does anybody have any ideas what the problem could be, or even what to do/try to debug further? Here is a stripped down version of my custom validator: [ConfigurationElementType(typeof(CustomValidatorData))] public sealed class UserAccountValidator : Validator { public UserAccountValidator(NameValueCollection attributes) : base(string.Empty, "User Account") { } protected override string DefaultMessageTemplate { get { throw new NotImplementedException(); } } protected override void DoValidate(object objectToValidate, object currentTarget, string key, ValidationResults results) { if (!currentTarget.GetType().Equals(typeof(UserAccount))) { throw new Exception(); } UserAccount userAccountToValidate = (UserAccount)currentTarget; // snipped code ... this.LogValidationResult(results, "The User Account is invalid", currentTarget, key); } } Here is the XML of my ruleset in Validation.config (the NotNull rule is only there to force a failure so I could see it getting hit, and it does): <validation> <type defaultRuleset="default" assemblyName="MyProj.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" name="MyProj.Entities.UserAccount"> <ruleset name="default"> <properties> <property name="HashedPassword"> <validator negated="true" messageTemplate="" messageTemplateResourceName="" messageTemplateResourceType="" tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.NotNullValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="Not Null Validator" /> </property> <property name="Property"> <validator messageTemplate="" messageTemplateResourceName="" messageTemplateResourceType="" tag="" type="MyProj.Entities.UserAccountValidator, MyProj.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" name="Custom Validator" /> </property> </properties> </ruleset> </type> </validation> And here is the stripped down version of the way I invoke the validation: var type = entity.GetType() var validator = ValidationFactory.CreateValidator(type, "default", new FileConfigurationSource("Validation.config")) var results = validator.Validate(entity) Any advice would be much appreciated! Thanks, Chris

    Read the article

  • C# Windows Service Multiple Config Files

    - by Goober
    Quick Question Is it possible to have more than 1 config file in a windows service? Or is there some way I can merge them at run time? Scenario Currently I have two config files containing the below contents. After I build and install my Windows Service, I can't get my custom XML Parser class to read the content because it keeps pointing to the wrong config file, even though I am using a few lines of code to ensure it gets the right name of the config file I need to access. ALSO When I navigate to the folder in which the service is installed, there is only sign of the normal APP.Config file, and no sign of the custom config file. (I have even set the normal ones properties to "Do Not Copy" and the custom ones properties to "Copy Always"). Config File Determination Code string settingsFile = String.Format("{0}.exe.config", System.AppDomain.CurrentDomain.BaseDirectory + Assembly.GetExecutingAssembly().GetName().Name); CUSTOM CONFIG File <?xml version="1.0" encoding="utf-8" ?> <configuration> <servers> <SV066930> <add name="Name" value = "SV066930" /> <processes> <SimonTest1> <add name="ProcessName" value="notepad.exe" /> <add name="CommandLine" value="C:\\WINDOWS\\system32\\notepad.exe C:\\WINDOWS\\Profiles\\TA2TOF1\\Desktop\\SimonTest1.txt" /> </SimonTest1> </processes> </SV066930> </servers> </configuration> NORMAL APP.CONFIG File <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxx" /> </configSections> <connectionStrings> <add name="DB" connectionString="Data Source=etc......" /> </connectionStrings> </configuration>

    Read the article

  • C# Windows Service XML

    - by Goober
    Scenario I have a windows service written in C# that performs some processing based on parsing an XML file and use that data to carry out various tasks. The service also does various bits of logging - which uses settings from an APP.Config file. The Problem When the service is compiled, installed and run, the XML file seems to disappear. I'm getting the impression that it is just ignored or something like that. So far I've tried using TWO App.Config files, one named App.Config that contains settings for the service, and the other called MyService.exe.config that contains all of the data that was used in the XML file (the idea being that I can parse the XML from a config file that actually gets compiled and appears in my installation directory. However When I do this, all that happens is that ONE config file appears (with the name MyService.exe.config), but it contains the contents of the App.Config file and not the XML data that I want to parse. What I need All I want is to have a config file for my settings, and an XML file for my data. Question Is this possible? I know the application works as it was originally built as a console application that ran fine. Other The application has to be designed this way (as in, I need my data stored as XML, and my settings stored in a config file). Thoughts If I could somehow combine the contents of the two files into ONE config file, that would be one way of solving the problem. However, I have tried this and of course I get a "Type Initialisation Exception", as the config file cannot interprate the XML data (probably because the tags are custom and do not form any part of the config schema - or something like that). Ideas Please could someone explain to me if it is possible for me to have an XML file AND a config file that will actually be compiled and stored in my installation directory for the service when it is run? CODE Custom XML/Data Config File <?xml version="1.0" encoding="utf-8" ?> <configuration> <servers> <SV066930> <add name="Name" value = "SV066930" /> <processes> <SimonTest1> <add name="ProcessName" value="notepad.exe" /> <add name="CommandLine" value="C:\\WINDOWS\\system32\\notepad.exe C:\\WINDOWS\\Profiles\\TA2TOF1\\Desktop\\SimonTest1.txt" /> </SimonTest1> </processes> </SV066930> </servers> </configuration> APP.Config Settings File <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxx" /> </configSections> <connectionStrings> <add name="DB" connectionString="Data Source=etc......" /> </connectionStrings> </configuration> Help greatly appreciated.

    Read the article

< Previous Page | 1 2 3  | Next Page >