Quantcast
Channel: patterns & practices – Enterprise Library
Viewing all 1928 articles
Browse latest View live

New Post: Option to clear log file content needed in RollingFlatFileTraceListener

$
0
0
You should be able to clear the log file. The first thing you need to do is to close the file (and release the lock) so that you can either clear the file or delete it (if the file does not exist then Enterprise Library will create a new file).

You can release the locks by using logWriter.Dispose() or Logger.Reset() if using the static facade class.

One thing to bear in mind is that if you are in a multi-threaded environment (e.g. web application) then you should ensure that no logging occurs between Disposing the LogWriter and any logging re-initialization (e.g. obtain a new LogWriter from the factory). One way to ensure that is to synchronize access to the logWriter.

Updated Wiki: Home

$
0
0

This project is no longer under development.

Unity has new ownership and has relocated to GitHub.
The remainder of the application blocks will no longer be developed. However, the source will continue to be available. We encourage any interested parties to fork the source as desired.

Enterprise Library now accepts community contributions!

Microsoft Enterprise Library is a collection of reusable software components (application blocks) addressing common cross-cutting concerns. Each application block is now hosted in its own repository. This site serves as a hub for the entire Enterprise Library. The latest source code here only include the sample application, which utilizes all of the application blocks.

Enterprise Library Conceptual Architecture

Enterprise Library is actively developed by the patterns & practices team and in collaboration with the community. Together we are dedicated to building application blocks which help accelerate developer's productivity on Microsoft platforms.

 LATEST
 CHANGES

OFFICIAL
RELEASES

  LEARN

GET SUPPORT

 CONTRIBUTE 

ROADMAP

  • See individual blocks' product backlogs

 

New Post: Enterprise Library for .NET 4.6

$
0
0
Hi Siminder,

Randy is correct. We are no longer actively developing Enterprise Library. However, the source will continue to remain available.
This doesn't actually change the support scenario because our support channels have always considered use of Ent Lib to be customer code.

Sincerely,
Christopher Bennage

New Post: Question about Data Access

$
0
0
Hello Folks,

I am new to the Enterprise Library and so I started with the Documentation and the Data Access Example. When I want to build the solution in VS2013 ( Host Windows 7 ) I get the error message : "Error 1 The remote server returned an error: (407) Proxy Authentication Required. DataAccess".
As newbie, I googled but I could not find anything useful. There is no File/Column/Line information provided. Can anyone give me a hint?

Kind regards

New Post: Question about Data Access

New Post: Question about Data Access

$
0
0
Hello reandylevy,

it really seems to be caused by the Proxy Settings. I thank you very much.

New Post: Creating Database connection String for a multi-database N-tier Web App.

$
0
0
Hello,
I m developing a multi-tenancy N-tier web application. I want each tenant to have their own database but share same application code. I am using Microsoft Enterprise Library 5.0 for DAL and the System configuration and log4net for logging. So far so good, if it is a single database, it works great but I want the ability to connect to different tenant databases in real time. To fully implement this, I have created a User database to store all login privileges, tenants database names, and perhaps each tenant's db connection string. Now, when tenant A logs on the system, Tenant A login privileges are retrieved from User db then to tenant A db to fetch data needed. Below is base data access object method that implements common database connection functionality and lots DAL methods derive on it.

I would like to add a constructor that's utilizes a dynamic string parameter. The string Parameter will be the tenant db name queried from User db. I would really appreciate anyone who's accomplished this to share with how s/he did.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Data.Sql;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using Crane_Infrastructure;
using Crane_Infrastructure.Exceptions;
using Crane_Infrastructure.ValueObjects;


namespace CranePMS_DataAccess
{
public class BaseDAO: BaseObject
{
   public BaseDAO() : base(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType) {

   }
   protected BaseDAO(Type loggerClassType) : base(loggerClassType) {

   }

   private Database db;

   private string DataSource = "Database = .\\SQLEXPRESS";
   private string _Server="(local)";
   private string DbName = "defaultdbname";
   private string UserName = "admin";
   private string Password="password";
   private string Security = "SSPI";



   // create DB connection goes to test.dll.config  

   protected Database Database
   {        


       get
       {
           Database DbConfig = DatabaseFactory.CreateDatabase();
           DbConnectionStringBuilder sb = DbConfig .DbProviderFactory.CreateConnectionStringBuilder();

           // Set the Connection String fields.

           sb["Database"] = DataSource;
           sb["Server"] = _Server;
           sb["Initial Catalog"] = DbName;
           sb["User ID"] = UserName;
           sb["Password"] = Password;
           sb["Integrated Security"] = Security;
           // sb["MultipleActiveResultSets"] = result;

           GenericDatabase newdatabase = new GenericDatabase(sb.ToString(), DbConfig.DbProviderFactory);
           if (db == null)
           {
               try
               {
                   db = newdatabase;

               }
               catch (System.Configuration.ConfigurationException ce)
               {
                   LogError("Couldn't create the database object, caught a ConfigurationException", ce);
                   throw new DBException("Could not obtain a handle to the database", ce);
               }
               catch (System.Reflection.TargetInvocationException tie)
               {
                   LogError("Couldn't create the database object, caught a TargetInvocationException", tie);
                   throw new DBException("Could not obtain a handle to the database", tie);
               }
           }

           return db = newdatabase;

       }

   }



  // close db
   protected void CloseReader(IDataReader reader)
   {
       try
       {

           reader.Close();

       }catch(Exception ex){


           LogWarn("Caught an exception in trying to close the reader, logging only.", ex);

       }


   }//end CloseReader()


}// end DAO class{}
}// End namespace

New Post: EventSourceAnalyzer and Rich Payload Data

$
0
0
.Net 4.6.1

Constructing an EventSource based class with EventSourceSettings.EtwSelfDescribingEventFormat which enables "Rich Payload Data".

When using EventSourceAnalyzer from NuGet/EnterpriseLibrary.SemanticLogging.EventSourceAnalyzer it seems like every event where rich payload is utilized fails the tests (Unsupported type...).
If so, the unit test with the analyzer is useless.

Something I misunderstand ?

New Post: EventSourceAnalyzer and Rich Payload Data

$
0
0
EventSourceSettings.EtwSelfDescribingEventFormat is new for .NET 4.6 and Semantic Logging was developed and built against .NET 4.5. So, EventSourceAnalyzer has no knowledge of the new setting.

What to do about that?

One option is to get the source code and update to use .NET 4.6 and handle the new setting. I haven't looked at it but, depending on the changes, it could be a bit messy.

Another option would be to use the Microsoft.Diagnostics EventSource package since (I think it should still have) its own EventSource validation triggered on compilation. However, if you are using other SLAB features then you would also need to build SLAB against the Microsoft.Diagnostics EventSource package.

There is some discussion about .NET 4.6 support: https://github.com/mspnp/semantic-logging/issues/64

Finally, the Semantic Logging project has moved to github: https://github.com/mspnp/semantic-logging so that would be the best place for SLAB.

New Post: EnterpriseLibrary.SemanticLogging throwing errors

$
0
0
Our application is using SLAB service and in one of our server instance it is not able to write any logs and we are seeing the below error…

ProviderId : d1ed7ec7-5701-5554-2c5e-796dc42511c5
EventId : 400
Keywords : 1
Level : Critical
Message : A rolling flat file sink failed to write an event. Message: System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Practices.EnterpriseLibrary.SemanticLogging.Sinks.RollingFlatFileSink.StreamWriterRollingHelper.PerformRoll(DateTime rollDateTime)
at Microsoft.Practices.EnterpriseLibrary.SemanticLogging.Sinks.RollingFlatFileSink.OnSingleEventWritten(EventEntry entry)
Opcode : Info
Task : 65134
Version : 0
Payload : [message : System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Practices.EnterpriseLibrary.SemanticLogging.Sinks.RollingFlatFileSink.StreamWriterRollingHelper.PerformRoll(DateTime rollDateTime)
at Microsoft.Practices.EnterpriseLibrary.SemanticLogging.Sinks.RollingFlatFileSink.OnSingleEventWritten(EventEntry entry)]
EventName : RollingFlatFileSinkWriteFailedInfo
Timestamp : 2016-02-02T05:14:40.2149222Z
ProcessId : 1388
ThreadId : 2352

I increased size of file to 10MB but still i see issue happening..The rolling file hasnt been updated for a month now..

Created Unassigned: Do not default SmtpServer to "127.0.0.1" in EmailTraceListenerData [33859]

$
0
0
This is a behavior change from the previous version. The better choice (the old way) is to pick the SMTP Server information from the configuration file setting under:

<system.net><mailSettings><smtp>

We want to share the SMTP settings across the application.


Here are the changes we need:
In EmailTraceListenerData.cs, remove Default value for SmtpServer:
[ConfigurationProperty(smtpServerProperty)] //changed.
[ResourceDescription(typeof(DesignResources), "EmailTraceListenerDataSmtpServerDescription")]
[ResourceDisplayName(typeof(DesignResources), "EmailTraceListenerDataSmtpServerDisplayName")]
public string SmtpServer
{
get { return (string)base[smtpServerProperty]; }
set { base[smtpServerProperty] = value; }
}

In EmailMessage.cs:
public virtual void SendMessage(MailMessage message)
{
var smtpClient = string.IsNullOrEmpty(configurationData.SmtpServer)? new SmtpClient() : new SmtpClient(configurationData.SmtpServer, configurationData.SmtpPort); //changed.

SetCredentials(smtpClient);
smtpClient.EnableSsl = configurationData.UseSSL;
smtpClient.Send(message);
}
In EmailTraceListener.cs, remove the following:
//Guard.ArgumentNotNullOrEmpty(smtpServer, "smtpServer");

Created Unassigned: Provide an easier way to plug in new variables for email template [33860]

$
0
0
I had to modify about 11 .cs files to add a few variables to EmailTraceListerner and I ended up with a customized version. Wish you can have some way to do automatically pickup the variable implementation from a .Net assembly (IOC?), so that I don't need change the open source code.

New Post: How to use static logger??? Logging Application Block

$
0
0
Hi All,

I am using Ent Lib 6 for logging and got the error: "The LogWriter has not been set for the Logger static class. Set it invoking the Logger.SetLogWriter method.". To fix this, added below code:
IConfigurationSource configurationSource = ConfigurationSourceFactory.Create();
LogWriterFactory logWriterFactory = new LogWriterFactory(configurationSource);
Logger.SetLogWriter(logWriterFactory.Create()); // not new LogWriterFactory().Create();
But, now i get a different error: "Must be implemented by subclasses."
Any idea what needs to be done to fix this?

Thanks,
Sai Abhilash Manikonda

New Post: Issue on Enterprice Logging

$
0
0
Hi Team,
Am using "Enterprice Logging" on my web service project. I added the below two references to capture the custom logs.
"Microsoft.Practices.EnterpriseLibrary.Logging.dll"
"Microsoft.Practices.EnterpriseLibrary.Common.dll"
I deployed my project and while trying to browse my ".svc" file (web service file) am getting the debugger window popup.! if I commented "Logging" functionality it is working fine. Could you please help me on the same.

Thanks

New Post: Enterprise Library for .NET 4.6

$
0
0
Hi Ben:

Two questions:

1) Where can the latest version of the 6.X source be found? The packages available on Nuget look to be later than the source available on the MS Download site.

2) Where can I find the development site for 7.X?

Thanks

marc

New Post: Enterprise Library 6.0 Logging disable/enable dynamically

$
0
0
I have requirement to log the message in Log file and Event Viewer. But I want if I call one method then it should log the message in Log file not in Event Viewer at that time. And, if I call second method then it should log the message in Event Viewer not in Log file at the same time.

Please advise if there is way to do this using Enterprise Library 6.0.

New Post: Enterprise Library 6.0 Logging disable/enable dynamically

$
0
0
Probably the easiest way to do what you want would be drive the conditional logging with categories. Since you seem to know the conditions ahead of time (during development and not at runtime) you can define 3 categories:
  1. One that logs to the Event Log
  2. One that logs to a File
  3. One that logs to both the Event Log and the file in #2
The config would look something like this:
<configuration><configSections><sectionname="loggingConfiguration"type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"requirePermission="true"/></configSections><loggingConfigurationname="" tracingEnabled="true"defaultCategory="EventLog"><listeners><addname="Event Log Listener"type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"source="Enterprise Library Logging"formatter="Text Formatter"log="" machineName="."traceOutputOptions="None"/><addname="Flat File Trace Listener"type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"fileName="trace.log" formatter=""/></listeners><formatters><addtype="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"template="Timestamp: {timestamp}{newline}&#xA;Message: {message}{newline}&#xA;Category: {category}{newline}&#xA;Priority: {priority}{newline}&#xA;EventId: {eventid}{newline}&#xA;Severity: {severity}{newline}&#xA;Title:{title}{newline}&#xA;Machine: {localMachine}{newline}&#xA;App Domain: {localAppDomain}{newline}&#xA;ProcessId: {localProcessId}{newline}&#xA;Process Name: {localProcessName}{newline}&#xA;Thread Name: {threadName}{newline}&#xA;Win32 ThreadId:{win32ThreadId}{newline}&#xA;Extended Properties: {dictionary({key} - {value}{newline})}"name="Text Formatter"/></formatters><categorySources><addswitchValue="All"name="EventLog"><listeners><addname="Event Log Listener"/></listeners></add><addswitchValue="All"name="File"><listeners><addname="Flat File Trace Listener"/></listeners></add><addswitchValue="All"name="EventLogAndFile"><listeners><addname="Event Log Listener"/><addname="Flat File Trace Listener"/></listeners></add></categorySources><specialSources><allEventsswitchValue="All"name="All Events"/><notProcessedswitchValue="All"name="Unprocessed Category"/><errorsswitchValue="All"name="Logging Errors &amp; Warnings"><listeners><addname="Event Log Listener"/></listeners></errors></specialSources></loggingConfiguration></configuration>
Then in code you could do something like:
logWriter.Write("Only to the event log", "EventLog");
logWriter.Write("Only to the file", "File");
logWriter.Write("Write to both", "EventLogAndFile");

New Post: Enterprise Library 6.0 Logging disable/enable dynamically

$
0
0
Thank you so much. It worked. :)

One more thing if you could tell me -
I would like to give name to Log file on date basis. For ex for today's file name should be - 20160307_exception.log. What is the easiest way to do it.
I'm doing with below code. is there any other way you can tell me?
            string path = @"C:\misc\";
            string filename = path + DateTime.Now.ToString("yyyyMMdd") + "_Exception.txt";

            Configuration xmlConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            LoggingSettings setting = (LoggingSettings)xmlConfiguration.GetSection(LoggingSettings.SectionName);
            RollingFlatFileTraceListenerData flatFile = setting.TraceListeners.Get(1) as RollingFlatFileTraceListenerData;
            flatFile.FileName = filename;
            xmlConfiguration.Save();
            ConfigurationManager.RefreshSection(LoggingSettings.SectionName);
            IConfigurationSource configurationSource = ConfigurationSourceFactory.Create();
            LogWriterFactory logWriterFactory = new LogWriterFactory(configurationSource);
            Logger.SetLogWriter(logWriterFactory.Create(), false);

            Logger.Write(messagebody, "File");

New Post: Enterprise Library 6.0 Logging disable/enable dynamically

$
0
0
Unfortunately, there really isn't a great way of doing this. Another option would be programmatic configuration. Also, every day you need to re-configure the block in order to change the date of the log file.

New Post: Enterprise Library 6.0 in Web Service - Where to instantiate?

$
0
0
Where do I put the statements that instantiate the Enterprise Library 6.0 factories when used with a web service? Should they go in the Class constructor, keeping the factories with class level scope, or do I include all that in each web service function keeping all the scopes local?

I have an old web service that I'm upgrading from .NET 2.0 and Enterprise Library 2.0 to .NET 4.6.1 and Enterprise Library 6.0. We still use the web.config for declaring the libraries, and I have added code required to make it work with 6.0.

The initial approach has been to have the factories configured in the constructor.

The first call to the web service works fine, but on subsequent calls I get errors on Logger.SetLogWriter and DatabaseFactory.SetDatabaseProviderFactory statements ("The LogWriter is already set." and "The static DatabaseFactory already has a database provider factory or custom methods set.").

I know I can include throwIfSet:=false, but found a mention that this may cause some unwanted behavior.

Also - do I need to add any Finalize logic for these?

I have the following:
<WebService(Namespace:="MyWebService")>
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)>
Public Class MyWebServiceInterface
    Inherits System.Web.Services.WebService


    ' ELib 6.0
    Dim config As IConfigurationSource = ConfigurationSourceFactory.Create()
    Dim factory As ExceptionPolicyFactory = New ExceptionPolicyFactory(config)
    Dim logFactory As LogWriterFactory = New LogWriterFactory(config)
    Dim dbfactory As DatabaseProviderFactory = New DatabaseProviderFactory()

``
Public Sub New()

    Try
        ' ELib 6.0
       Logger.SetLogWriter(logFactory.Create(), True)
        Dim exMgr As ExceptionManager = factory.CreateManager()
        ExceptionPolicy.SetExceptionManager(exMgr, True)
    Catch ex As Exception
        ' Simply Ignore
        ' We cannot log or handle Exceptions until LogWriter and ExceptionPolicy is set up...!
    End Try
    Try
        DatabaseFactory.SetDatabaseProviderFactory(New DatabaseProviderFactory(), True)
        ...
    Catch ex As Exception
        'Log exceptions.
        ExceptionPolicy.HandleException(ex, "Log Only Policy")
    End Try
```
Viewing all 1928 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>