Exemplo n.º 1
0
 public void LogError(string message)
 {
     LogEntry entry = new LogEntry();
     entry.Message = message;
     entry.Categories.Add("Error");
     Logger.Write(entry);
 }
Exemplo n.º 2
0
        public ProductInfo(string id)
        {
            _id = id;
            DataFactory df = new DataFactory();
            DataSet ds = new DataSet();
            try
            {
                string sql = "select * from productinfo where productId=" + id;
                ds = df.DataBind(sql);
            }
            catch (Exception ex)
            {
                LogEntry entry = new LogEntry();
                entry.Severity = System.Diagnostics.TraceEventType.Error;
                entry.Message = string.Format("Exception:{0}, Inner Exception:{1}", ex.Message, ex.InnerException.Message);
                entry.Categories.Add(Category.Exception);
                entry.Priority = Priority.High;
                logwrite.Write(entry);
                throw;
            }

            DataRow row = ds.Tables[0].Rows[0];
            _name = row["productName"].ToString().Trim();
            _mainInfo =NoHTML(row["maininfo"].ToString().Trim());
            _picURL = HttpContext.Current.Request.Url.Host.ToString().TrimEnd('/') +"/productPic/" + row["pic"].ToString().Trim();
            _pdfURL =string.IsNullOrEmpty(row["pdf"].ToString().Trim())==true? "" : HttpContext.Current.Request.Url.Host.ToString().TrimEnd('/')+ "/productPdf/" + row["pdf"].ToString().Trim();
            _price = row["price"].ToString().Trim() == "0" ? "" : row["price"].ToString().Trim();
            _isNew = row["isNew"].ToString().Trim();
            _isPromotion = row["isPromotion"].ToString().Trim();
        }
        public void RedirectsToCommonLogging()
        {
            CapturingLoggerFactoryAdapter testLoggerFactoryAdapter = new CapturingLoggerFactoryAdapter();
            LogManager.Adapter = testLoggerFactoryAdapter;

            // force entlib logging init
            Logger.SetLogWriter(new LogWriterFactory().Create());
            Logger.Write("init");

            // ensure external configuration didn't change
            LogEntry logEntry = new LogEntry();
            logEntry.Categories.Add("mycategory");
            logEntry.Message = "testmessage";

            // Change to EL 6 (no longer uses Unity) so need to get listener via LogWriter
            var allEventsSource = Logger.Writer.GetMatchingTraceSources(logEntry).First(source => "All Events".Equals(source.Name));
            var listener = (CommonLoggingEntlibTraceListener) allEventsSource.Listeners.First(l => l is CommonLoggingEntlibTraceListener);
            Assert.IsTrue(listener.Name.StartsWith("Test Capturing Listener"));

            ILogFormatter formatter = listener.Formatter;
            string s = formatter.Format(logEntry);
            Assert.AreEqual("Category: mycategory, Message: testmessage", s);

            // note that output depends on the formatter configured for the entlib listener!
            Logger.Write("message1");
            Assert.AreEqual("Category: General, Message: message1", testLoggerFactoryAdapter.LastEvent.RenderedMessage);
            Assert.AreEqual(LogLevel.Info, testLoggerFactoryAdapter.LastEvent.Level);

            Logger.Write("message2", "custom category", -1, -1, TraceEventType.Warning);
            Assert.AreEqual("Category: custom category, Message: message2", testLoggerFactoryAdapter.LastEvent.RenderedMessage);
            Assert.AreEqual("Test Capturing Listener/All Events", testLoggerFactoryAdapter.LastEvent.Source.Name);
            Assert.AreEqual(LogLevel.Warn, testLoggerFactoryAdapter.LastEvent.Level);
        }
        public static void WriteLog(string message, string category, string status, System.Diagnostics.TraceEventType eventType, string name, string filename, int priority)
        {
            //DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory());
            //DatabaseProviderFactory factory = new DatabaseProviderFactory();
            //Database db = factory.Create("Logging");
               //DatabaseFactory.SetDatabaseProviderFactory(factory, true);
            DatabaseProviderFactory factory = new DatabaseProviderFactory(new SystemConfigurationSource(false).GetSection);
            DatabaseFactory.SetDatabaseProviderFactory(factory, false);
            LogWriterFactory logWriterFactory = new LogWriterFactory();

            Logger.SetLogWriter(logWriterFactory.Create());

            LogEntry log = new LogEntry();
            log.Categories.Add(category);
            log.Message = status + " : " + message;
            log.EventId = 1;
            log.Priority = priority;

            if (!string.IsNullOrEmpty(name.Trim()))
                log.ManagedThreadName = name;

            log.TimeStamp = System.DateTime.Now;
            log.Severity = eventType;

            if (!string.IsNullOrEmpty(filename.Trim()))
                log.Title = category + " : " + filename + " : " + message;
            else
                log.Title = category + " : " + message;

            Logger.Write(log);

            Logger.Reset();
        }
Exemplo n.º 5
0
        public static void WriteActivity(string functionName, string message)
        {
            var logEntry = new LogEntry();
            logEntry.Message = message;

            Logger.Write(logEntry);
        }
Exemplo n.º 6
0
 public static void LogEntry(string message)
 {
     LogEntry log = new LogEntry();
     log.Message = message;
     MessageBox.Show(message);
     //Logger.Write(log);
 }
        public void RedirectsToCommonLogging()
        {
            CapturingLoggerFactoryAdapter testLoggerFactoryAdapter = new CapturingLoggerFactoryAdapter();
            LogManager.Adapter = testLoggerFactoryAdapter;

            // force entlib logging init
            Logger.Write("init");

            var listener =(CommonLoggingEntlibTraceListener) ((TraceListenerWrapper)EnterpriseLibraryContainer.Current.GetInstance<TraceListener>("Test Capturing Listener")).InnerTraceListener;

            // ensure external configuration didn't change
            // change to starts with because entlib now wraps all listeners and changes the name
            Assert.IsTrue(listener.Name.StartsWith("Test Capturing Listener"));
            LogEntry logEntry = new LogEntry();
            logEntry.Categories.Add("mycategory");
            logEntry.Message = "testmessage";
            ILogFormatter formatter = listener.Formatter;
            string s = formatter.Format(logEntry);

            Assert.AreEqual("Category: mycategory, Message: testmessage", s);
                // note that output depends on the formatter configured for the entlib listener!
                Logger.Write("message1");
                Assert.AreEqual("Category: General, Message: message1", testLoggerFactoryAdapter.LastEvent.RenderedMessage);
                Assert.AreEqual(LogLevel.Info, testLoggerFactoryAdapter.LastEvent.Level);

                Logger.Write("message2", "custom category", -1, -1, TraceEventType.Warning);
                Assert.AreEqual("Category: custom category, Message: message2", testLoggerFactoryAdapter.LastEvent.RenderedMessage);
                Assert.AreEqual("Test Capturing Listener/All Events", testLoggerFactoryAdapter.LastEvent.Source.Name);
                Assert.AreEqual(LogLevel.Warn, testLoggerFactoryAdapter.LastEvent.Level);
        }
Exemplo n.º 8
0
        public ActionResult CampaignSetup(CampaignSetupModel cs, string command)
        {

            if (command == "") command = "";

            var logEnty = new LogEntry {ActivityId = Guid.NewGuid(), Message = "Loading CampaignSetup Controller"};
            Logger.Write(logEnty);
            //var logService = new LogService();
            //logService.AddToLog(1, "Campaign Setup Accessed", "CampaignSetup//CampaignSetup//CampaignSetup", 1);
            //var scw = new ServiceClientWrapper();
            //scw.SendEmail("subject", "*****@*****.**", "*****@*****.**", "test mail");

            //var campaignSetupModel = new CampaignSetupModel();
            Session["SiteLinks"] = null;
            Session["NegativeKeywords"] = null;
            Session["NegativeKeywordsText"] = null;
            Session["CampaignSetupModel"] = cs;
            Session["AllCategories"] = null;
            ViewBag.IsLaunched = false;
            ViewBag.IsCompleted = false;
            ViewBag.IsLaunchedAndCompleted = false;
            cs.AdModelProp.IsNew = true;
            var dbContext = new SemplestModel.Semplest();
            var userid =
                ((Credential)System.Web.HttpContext.Current.Session[SharedResources.SEMplestConstants.SESSION_USERID]).
                    UsersFK;
            cs.BillType = dbContext.Users.First(key => key.UserPK == userid).Customer.BillTypeFK;
            return View(cs);
        }
Exemplo n.º 9
0
 public static void SetLogFormatter(LogEntry logEntry, ILogFormatter logFormatter)
 {
     if (logEntry != null)
     {
         _logFormatter = logFormatter;
     }
 }
 private static void LogMessageAsync(LogEntry log)
 {
     using (TransactionScope transScope = new TransactionScope(TransactionScopeOption.Suppress))
     {
         Logger.Write(log);
     }
 }
Exemplo n.º 11
0
        static private void LogEntry(string title, string message, Exception exc, Category category, System.Diagnostics.TraceEventType severity, int priority, int eventid)
        {
            var entry = new Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry
            {
                Title    = $"({AppDomain.CurrentDomain.Id} - {Thread.CurrentThread.ManagedThreadId}) {title}",
                Message  = message,
                Severity = severity,
                Priority = priority,
                EventId  = eventid
            };

            if ((category & Category.General) != 0)
            {
                entry.Categories.Add(nameof(Category.General));
            }

            if ((category & Category.Audit) != 0)
            {
                entry.Categories.Add(nameof(Category.Audit));
            }

            if (exc != null)
            {
                entry.ExtendedProperties.Add("Exception", exc);
            }

            _resourceLocker.Resources.Writer.Write(entry);
        }
Exemplo n.º 12
0
        public void AddNewItemToTraceList(TraceEventType eventType, string message)
        {
            LogEntry leNewTraceItem = new LogEntry();
            leNewTraceItem.Message = message;
            leNewTraceItem.Severity = eventType;
            leNewTraceItem.TimeStamp = DateTime.Now;

            lock (lockObject)
            {
                lstFreshTrace.Add(leNewTraceItem);

                if ( eventType == TraceEventType.Critical || eventType == TraceEventType.Error || eventType == TraceEventType.Warning )
                {
                    lstFreshTraceErrors.Add(leNewTraceItem);
                }

                if ( lstFreshTraceErrors.Count > errorsNumber )
                {
                    lstFreshTraceErrors.RemoveAt(0);
                }
                if (lstFreshTrace.Count > infoNumber)
                {
                    lstFreshTrace.RemoveAt(0);
                }
            }
        }
Exemplo n.º 13
0
        static private void LogEntry(string title, string message, Exception exc, Category category, System.Diagnostics.TraceEventType severity, int priority, int eventid)
        {
            var entry = new Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry();

            // TODO: refactor this code
            entry.Title    = string.Format("({0} - {1}) {2}", AppDomain.CurrentDomain.Id, Thread.CurrentThread.ManagedThreadId, title);
            entry.Message  = message;
            entry.Severity = severity;
            entry.Priority = priority;
            entry.EventId  = eventid;

            if ((category & Category.General) != 0)
            {
                entry.Categories.Add("General");
            }

            if ((category & Category.Audit) != 0)
            {
                entry.Categories.Add("Audit");
            }

            if (exc != null)
            {
                entry.ExtendedProperties.Add("Exception", exc);
            }

            _resourceLocker.Resources.Writer.Write(entry);
        }
Exemplo n.º 14
0
        public CampaignSetupModel GetCategories(CampaignSetupModel model)
        {
            var scw = new ServiceClientWrapper();

            // create AdCopy array

            // get categories or classifications
            var categories = scw.GetCategories(null, model.ProductGroup.ProductPromotionName,
                                               model.ProductGroup.Words,
                                               model.AdModelProp.Ads.Select(
                                                   pad => pad.AdTitle + " " + pad.AdTextLine1 + " " + pad.AdTextLine2).
                                                   ToArray(), model.AdModelProp.LandingUrl);

            // create categories list that will be displayed in a multiselect list box
            if (categories != null && categories.Count > 0)
            {
                for (var i = 0; i < categories.Count; i++)
                {
                    var cm = new CampaignSetupModel.CategoriesModel {Id = i, Name = categories[i]};
                    model.AllCategories.Add(cm);
                }
            }
            else
            {
                var logEnty = new LogEntry
                                  {ActivityId = Guid.NewGuid(), Message = "Could not get Categories from web service"};
                Logger.Write(logEnty);
            }
            return model;
            // save this some how while getting the keywords this is becoming null
        }
Exemplo n.º 15
0
 void IDnaLogger.Write(LogEntry log)
 {
     lock (_locker)
     {
         Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(log);
     }
 }
Exemplo n.º 16
0
        /// <summary>
        /// Creates a preconfigured instance of a LogEntry.
        /// </summary>
        /// <param name="severity">Severity of the log entry.</param>
        /// <param name="message">Error message</param>
        /// <param name="title">Title of the log entry</param>
        /// <param name="includeSecurityDetail">if set to <c>true</c> security information is included in the log.</param>
        /// <returns>Configured LogEntry instance</returns>
        public LogEntry CreateInstance(
            TraceEventType severity, string message, string title, bool includeSecurityDetail)
        {
            LogEntry le = new LogEntry();

            if (string.IsNullOrEmpty(title))
            {
                le.Title = "Untitled";
            }
            else
            {
                le.Title = title;
            }

            le.Message = message;
            le.Severity = severity;

            Dictionary<string, object> dictionary = new Dictionary<string, object>();

            if (includeSecurityDetail)
            {
                ManagedSecurityContextInformationProvider informationHelper = new ManagedSecurityContextInformationProvider();
                informationHelper.PopulateDictionary(dictionary);

                UnmanagedSecurityContextInformationProvider unmanagedHelper = new UnmanagedSecurityContextInformationProvider();
                unmanagedHelper.PopulateDictionary(dictionary);
            }

            le.ExtendedProperties = dictionary;

            return le;
        }
Exemplo n.º 17
0
        /// <summary>
        /// Throws a new WebProtocalException. Debug builds throw the exception along with the description and inner exception, release builds
        /// only throw the StatusCode.
        /// </summary>
        /// <param name="StatusCode">The status code you want the exception to contain</param>
        /// <param name="statusDescription">The description of the exception</param>
        /// <param name="innerException">The origninal exception you caught if any</param>
        public DnaWebProtocolException(HttpStatusCode statusCode, string statusDescription, Exception innerException)
            
        {
            StatusCode = statusCode;
            StatusDescription = statusDescription;
            if (String.IsNullOrEmpty(statusDescription))
            {
                if(innerException != null)
                {
                    statusDescription = innerException.Message;
                }
                else
                {
                    statusDescription = "";
                }
            }
            

            LogEntry entry = new LogEntry()
            {
                Message = String.Format("{0}-{1}", StatusCode, statusDescription),
                Severity = System.Diagnostics.TraceEventType.Error,
            };

            Logger.Write(entry);


            this.detailWriter = new StringDetailWriter() { Detail = statusDescription, StatusCode = StatusCode, innerException = innerException, ErrorCode = ErrorType.Unknown.ToString() };

        }
Exemplo n.º 18
0
		public LogEntry Create(TraceEventType severity, IFormatProvider provider, string format, params object[] args) {
			var entry = new LogEntry();
			entry.Title = loggerName;
			entry.Severity = severity;
			entry.Message = string.Format(provider, format, args);
			return entry;
		}
Exemplo n.º 19
0
        /// <summary>
        /// To Log exception informations
        /// Stream witer is replaced with enterprise library
        /// </summary>
        /// <param name="ex"></param>
        public static void Error(string message, Exception ex)
        {
            LogEntry logEntry = null;
            try
            {
                logEntry = new LogEntry();

                logEntry.Categories.Clear();
                logEntry.TimeStamp = DateTime.Now;
                logEntry.Severity = System.Diagnostics.TraceEventType.Error;
                logEntry.Message = message;
                logEntry.Categories.Add("General Category");
                Logger.Write(logEntry);
                System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, true);
                Logger.Write("Method: " + trace.GetFrame(trace.FrameCount - 1).GetMethod().Name);
                Logger.Write("Line: " + trace.GetFrame(trace.FrameCount - 1).GetFileLineNumber());
                Logger.Write("Column: " + trace.GetFrame(trace.FrameCount - 1).GetFileColumnNumber());
            }
            catch
            {
                throw;
            }
            finally
            {
                logEntry = null;
            }
        }
        public void ShouldCacheTheMessagesBasedOnCacheInterval()
        {
            var listener = new CachedEmailTraceListener(
                string.Empty,
                string.Empty,
                string.Empty,
                string.Empty,
                string.Empty,
                2500,
                null,
                EmailAuthenticationMode.WindowsCredentials,
                string.Empty,
                string.Empty,
                false,
                1.0); // 1 hour cache time

            var logEntry = new LogEntry { Message = "ABC Error", Severity = TraceEventType.Error};
            try
            {
                listener.TraceData(null, string.Empty, TraceEventType.Error, 1, logEntry);
                // If no exception
                Assert.Fail();
            }
            catch (ArgumentException ex)
            {
                Assert.AreEqual("The parameter 'address' cannot be an empty string.\r\nParameter name: address", ex.Message);
            }
            catch
            {
                Assert.Fail();
            }

            //Second call should not hit the base TraceData call..
            listener.TraceData(null, string.Empty, TraceEventType.Error, 1, logEntry);
        }
Exemplo n.º 21
0
        public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
        {
            Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry logEntry = data as Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry;
            if (logEntry != null)
            {
                using (ApplicationDataContext context = new ApplicationDataContext())
                {
                    Data.Applications.LogEntry dbLogEntry = new Data.Applications.LogEntry();

                    dbLogEntry.LogEntryId    = Guid.NewGuid();
                    dbLogEntry.LogTypeId     = (int)logEntry.Severity;
                    dbLogEntry.ApplicationId = BrokerContext.Current.ApplicationId;
                    dbLogEntry.UserToken     = BrokerContext.Current.UserToken;
                    dbLogEntry.UserId        = BrokerContext.Current.UserName;
                    dbLogEntry.ActivityID    = BrokerContext.Current.ActivityId;

                    dbLogEntry.MethodName = Strings.ObjectToString(logEntry.ExtendedProperties[Constants.Logging.MethodName]);
                    dbLogEntry.Text       = logEntry.Message;

                    dbLogEntry.DataObjectType = Strings.ObjectToString(logEntry.ExtendedProperties[Constants.Logging.DataObjectType]);
                    dbLogEntry.DataObjectXml  = Strings.ObjectToString(logEntry.ExtendedProperties[Constants.Logging.DataObjectXml]);
                    dbLogEntry.LogDate        = logEntry.TimeStamp;


                    context.LogEntries.InsertOnSubmit(dbLogEntry);
                    context.SubmitChanges();
                }
            }
        }
Exemplo n.º 22
0
		/// <summary>
		/// Merges each key/value pair from the context items dictionary with the ExtendedProperties
		/// dictionary of the <see cref="LogEntry"/>.
		/// </summary>
		/// <param name="log"><see cref="LogEntry"/> object that is being logged.</param>
		public void ProcessContextItems(LogEntry log)
		{
			Hashtable contextItems = null;

			// avoid retrieval if necessary permissions are not granted to the executing assembly
			if (SecurityManager.IsGranted(new SecurityPermission(SecurityPermissionFlag.Infrastructure)))
			{
				try
				{
					contextItems = GetContextItems();
				}
				catch (SecurityException)
				{
					// ignore the security exception - no item could have been set if we get the exception here.
				}
			}

			if (contextItems == null || contextItems.Count == 0)
			{
				return;
			}

			foreach (DictionaryEntry entry in contextItems)
			{
				string itemValue = GetContextItemValue(entry.Value);
				log.ExtendedProperties.Add(entry.Key.ToString(), itemValue);
			}
		}
        /// <summary>
        /// Processes the request.
        /// </summary>
        /// <param name="requestMessage">The request message.</param>
        /// <returns></returns>
        public override void ProcessRequest(RequestMessage requestMessage)
        {
            try
            {
#if DEBUG
                // Log that the shipment cannot be updated
                Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry logEntry = new Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry(
                    string.Concat(""),
                    "Request Management",
                    0,
                    0,
                    TraceEventType.Information,
                    null,
                    null);

                // Write to the log
                Logger.Write(logEntry);
#endif
                AddCommonFieldsToSchema();
                textFieldParser.RecordFound += new TextFieldParser.RecordFoundHandler(textFieldParser_RecordFound);
                base.ProcessRequest(requestMessage);
                //save the commander object and return the success of this process
            }
            catch (Exception ex)
            {
                // Store the exception
                LastError = ex;

                // Failed
                Status = SubscriberStatusEnum.Failed;
            }
        }
Exemplo n.º 24
0
 /// <summary>
 /// Logs the exception - Critical Level.
 /// </summary>
 /// <param name="exception">The exception.</param>
 public void LogException(Exception exception)
 {
     LogEntry logEntry = new LogEntry();
     logEntry.Message = string.Format(logTemplate, exception.Message, exception.StackTrace);
     logEntry.Severity = TraceEventType.Critical;
     Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(logEntry);
 }
Exemplo n.º 25
0
 public static void WriteException(TraceEventType Severity, String ErrorMessage, String MethodName)
 {
     LogEntry entry = new LogEntry();
     entry.Severity = Severity;
     entry.Message = ErrorMessage;
     Logger.Write(entry);
 }
        public void RedirectsToCommonLogging()
        {
            CapturingLoggerFactoryAdapter testLoggerFactoryAdapter = new CapturingLoggerFactoryAdapter();
            LogManager.Adapter = testLoggerFactoryAdapter;

            // force entlib logging init
            Logger.Write("init");

            // ensure external configuration didn't change
            Assert.AreEqual("Test Capturing Listener", TestCommonLoggingEntlibTraceListener.Instance.Name);
            LogEntry logEntry = new LogEntry();
            logEntry.Categories.Add("mycategory");
            logEntry.Message = "testmessage";
            ILogFormatter formatter = TestCommonLoggingEntlibTraceListener.Instance.Formatter;
            string s = formatter.Format(logEntry);
            Assert.AreEqual("Category: mycategory, Message: testmessage", s);

            using (TestCommonLoggingEntlibTraceListener.Instance.Capture())
            {
                // note that output depends on the formatter configured for the entlib listener!
                Logger.Write("message1");
                Assert.AreEqual("Category: General, Message: message1", testLoggerFactoryAdapter.LastEvent.RenderedMessage);
                Assert.AreEqual(LogLevel.Info, testLoggerFactoryAdapter.LastEvent.Level);

                Logger.Write("message2", "custom category", -1, -1, TraceEventType.Warning);
                Assert.AreEqual("Category: custom category, Message: message2", testLoggerFactoryAdapter.LastEvent.RenderedMessage);
                Assert.AreEqual("Test Capturing Listener/All Events", testLoggerFactoryAdapter.LastEvent.Source.Name);
                Assert.AreEqual(LogLevel.Warn, testLoggerFactoryAdapter.LastEvent.Level);
            }
        }
Exemplo n.º 27
0
 static void LogToDatabase()
 {
     // Check if logging is enabled before creating log entries.
     if (defaultWriter.IsLoggingEnabled())
     {
         // Create a Dictionary of extended properties
         Dictionary<string, object> exProperties = new Dictionary<string, object>();
         exProperties.Add("Extra Information", "Some Special Value");
         // Create a LogEntry using the constructor parameters.
         defaultWriter.Write("Log entry with category, priority, event ID, severity, title, and extended properties.", "Database",
                                                 5, 9008, TraceEventType.Warning, "Logging Block Examples", exProperties);
         Console.WriteLine("Created a log entry with a category, priority, event ID, severity, title, and   extended properties.");
         Console.WriteLine();
         // Create a LogEntry using the constructor parameters.
         LogEntry entry = new LogEntry("LogEntry with category, priority, event ID, severity, title, and extended properties.", "Database",
                                         8, 9009, TraceEventType.Error, "Logging Block Examples", exProperties);
         defaultWriter.Write(entry);
         Console.WriteLine("Created and written LogEntry with a category, priority, event ID, severity,     title, and extended properties.");
         Console.WriteLine();
         Console.WriteLine(@"Open the 'Logging.mdf' database in the Bin\Debug folder to see the results.");
     }
     else
     {
         Console.WriteLine("Logging is disabled in the configuration.");
     }
 }
Exemplo n.º 28
0
        /// <summary>
        /// Writing a information log
        /// </summary>
        /// <param name="message">information message</param>
        /// <param name="dict">Properties you want to log.
        /// Example: When input Key is Controller and Value is ExampleController in dict.
        /// Then log information will be 'Controller : ExampleController'.
        /// </param>
        public void WriteInfomation(string message, IDictionary<string, object> dict)
        {
            var logEntry = new LogEntry { ExtendedProperties = dict, Message = message, Severity = TraceEventType.Information };
            logEntry.Categories.Add("Information");

            Logger.Writer.Write(logEntry);
            Logger.Writer.Dispose();
        }
Exemplo n.º 29
0
 public static void Log(string category, TraceEventType type, string message)
 {
     LogEntry entry = new LogEntry();
     entry.Categories.Add(category);
     entry.Message = message;
     entry.Severity = type;
     Logger.Write(entry);
 }
Exemplo n.º 30
0
 public static void Verbose(string message)
 {
     if (Logger.IsLoggingEnabled())
     {
         LogEntry entry = new LogEntry() { Message = message, Severity = System.Diagnostics.TraceEventType.Verbose };
         Logger.Write(entry);
     }
 }
Exemplo n.º 31
0
 /// <summary>
 /// Log error mostly service with error details
 /// </summary>
 /// <param name="title">Title of the error</param>
 /// <param name="message">Detail of the error</param>
 public static void LogError(string title, string message)
 {
     LogEntry logEntry = new LogEntry();
     logEntry.Title = title;
     logEntry.Message = message;
     logEntry.Severity = System.Diagnostics.TraceEventType.Error;
     Logger.Write(logEntry);
 }
Exemplo n.º 32
0
 public static void Log(LogCategories category, LogEventID id, TraceEventType type, string message)
 {
     LogEntry entry = new LogEntry();
     entry.EventId = (int)id;
     entry.Categories.Add(category.ToString());
     entry.Message = message;
     entry.Severity = type;
     Logger.Write(entry);
 }
        /// <summary>
        /// Writes a trace entry using enterpise library logging block.
        /// </summary>
        /// <param name="traceEntry">The <see cref="TraceEntry"/> that is to be written.</param>
        protected virtual void WriteEntry(TraceEntry traceEntry)
        {
            var entlibTraceEntry = new EntLib.LogEntry();

            entlibTraceEntry.Message = traceEntry.Method + " " + traceEntry.Duration;
            entlibTraceEntry.Title   = traceEntry.Operation;
            entlibTraceEntry.Categories.Add("Trace");
            EntLib.Logger.Write(entlibTraceEntry);
        }
Exemplo n.º 34
0
 private LogEntry NewLogEntry(object message, TraceEventType severity = TraceEventType.Verbose)
 {
     LogEntry entry = new LogEntry();
     entry.Message = message == null? String.Empty : message.ToString();
     entry.EventId = 100;
     entry.Categories = new string[] { _logName };
     entry.Severity = severity;
     return entry;
 }
Exemplo n.º 35
0
		public void Write(string message)
		{
			LogEntry ent = new LogEntry();
			ent.TimeStamp = ent.TimeStamp.ToLocalTime();
			ent.Categories.Add(CONS_ERROR_CATEGORY);  // To use another category use traceSources.Add("OtherCat", Listener);
			ent.Message = message;
			ent.Severity = System.Diagnostics.TraceEventType.Error;
			m_logWriter.Write(ent);
		}
Exemplo n.º 36
0
        static void LogProviderLogProviderException(object sender, PluginExceptionEventArgs args)
        {
            var logEntry =
                new Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry
            {
                Severity = TraceEventType.Error,
                Message  = args.Exception.ToString()
            };

            Logger.Write(logEntry);
        }
        public override ent.LogEntry Create(TraceEventType logLevel, string message)
        {
            var log = new ent.LogEntry()
            {
                Message  = message,
                Title    = this.Source,
                Severity = logLevel
            };

            return(log);
        }
Exemplo n.º 38
0
 /// <summary>
 /// 向指定的日志种类(日志种类指的是配置文件如:App.config里面配置的具体Logger种类)
 /// 写入一个新的带有错误异常信息的LogEntry.
 /// </summary>
 /// <param name="message">错误异常信息</param>
 /// <param name="ex">错误异常对象</param>
 public void Error(string message, System.Exception ex)
 {
     elib.LogEntry le = new elib.LogEntry();
     le.Message    = message;
     le.Priority   = 2;
     le.Categories = new string[] { Category };
     le.Severity   = System.Diagnostics.TraceEventType.Error;
     le.ExtendedProperties.Add("Exception", ex.Message);
     le.ExtendedProperties.Add("ExceptionType", ex.GetType().Name);
     le.ExtendedProperties.Add("CallStack", ex.StackTrace);
     elib.Logger.Write(le);
 }
        /// <summary>
        /// Writes a log entry using enterpise library logging block.
        /// </summary>
        /// <param name="logEntry">The <see cref="LogEntry"/> that is to be written.</param>
        protected virtual void WriteEntry(LogEntry logEntry)
        {
            var entliblogEntry = new EntLib.LogEntry();

            entliblogEntry.Message           = logEntry.Message;
            entliblogEntry.Priority          = logEntry.Priority;
            entliblogEntry.Severity          = (System.Diagnostics.TraceEventType)Enum.Parse(typeof(System.Diagnostics.TraceEventType), Enum.GetName(typeof(TraceEventType), logEntry.Severity));
            entliblogEntry.TimeStamp         = logEntry.Timestamp;
            entliblogEntry.ManagedThreadName = logEntry.ThreadName;
            entliblogEntry.Title             = logEntry.Title;
            entliblogEntry.Categories.Add(logEntry.Category);
            EntLib.Logger.Write(entliblogEntry);
        }
Exemplo n.º 40
0
 public bool ShouldLog(string category, TraceEventType severity)
 {
     try
     {
         ELAB.LogEntry logEntry = new ELAB.LogEntry();
         logEntry.Categories.Add(category);
         logEntry.Severity = severity;
         return(ELAB.Logger.ShouldLog(logEntry));
     }
     catch (Exception e)
     {
         DumpException(e);
         return(false);
     }
 }
Exemplo n.º 41
0
        public QuartzLogging.Logger GetLogger(string name)
        {
            return((level, func, exception, parameters) =>
            {
                if (exception != null)
                {
                    return ExceptionPolicy.HandleException(exception, "quartzPolicy");
                }

                var logEntiry = new EntLibLogging.LogEntry();

                switch (level)
                {
                case QuartzLogging.LogLevel.Trace:
                    logEntiry.Severity = System.Diagnostics.TraceEventType.Information;
                    break;

                case QuartzLogging.LogLevel.Debug:
                    logEntiry.Severity = System.Diagnostics.TraceEventType.Verbose;
                    break;

                case QuartzLogging.LogLevel.Info:
                    logEntiry.Severity = System.Diagnostics.TraceEventType.Information;
                    break;

                case QuartzLogging.LogLevel.Warn:
                    logEntiry.Severity = System.Diagnostics.TraceEventType.Warning;
                    break;

                case QuartzLogging.LogLevel.Error:
                    logEntiry.Severity = System.Diagnostics.TraceEventType.Error;
                    break;

                case QuartzLogging.LogLevel.Fatal:
                    logEntiry.Severity = System.Diagnostics.TraceEventType.Error;
                    break;
                }

                if (func != null)
                {
                    logEntiry.Title = name;
                    logEntiry.Message = string.Format(func(), parameters);
                    EntLibLogging.Logger.Write(logEntiry);
                }

                return true;
            });
        }
Exemplo n.º 42
0
 public static void LogMessage(String message, System.Diagnostics.TraceEventType severity)
 {
     try
     {
         Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry logEntry = new Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry();
         logEntry.AppDomainName = "";
         logEntry.Severity      = severity;
         logEntry.Message       = message;
         Microsoft.Practices.EnterpriseLibrary.Logging.Logger.Write(logEntry);
     }
     catch (Exception ex)
     {
         //Logging not configured properly and message could not be written
         throw ex;
     }
 }
Exemplo n.º 43
0
        private void Log(string message, LoggingCategory category, TraceEventType severity,
                         params object[] parameters)
        {
            var logEntry = new EntLib.LogEntry();

            logEntry.Categories.Add(category.ToString());
            logEntry.Severity = severity;
            if (EntLib.Logger.ShouldLog(logEntry))
            {
                if (parameters.Length > 0)
                {
                    logEntry.Message = string.Format(message, parameters);
                }
                else
                {
                    logEntry.Message = message;
                }
            }
            EntLib.Logger.Write(logEntry);
        }
Exemplo n.º 44
0
        /// <summary>
        /// Logs a new log entry with a specific category, priority, event Id, and severity title. If the LogCategory is "Event", it logs into Event.log else it logs into Error.log.
        /// </summary>
        /// <param name="logEntry">The log entry.</param>
        public static void DoLog(LogEntry logEntry)
        {
            if (defaultWriter.IsLoggingEnabled())
            {
                Dictionary <string, object> exproperties = new Dictionary <string, object>();
                if (!string.IsNullOrEmpty(logEntry.MethodName) || !string.IsNullOrEmpty(logEntry.ClassName))
                {
                    exproperties.Add(logEntry.MethodName, logEntry.ClassName);
                }

                var logEntity = new Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry();
                logEntity.Categories         = new string[] { logEntry.LogCategory.ToString() };
                logEntity.Message            = logEntry.MessageDetails;
                logEntity.Priority           = (int)logEntry.LogPriority;
                logEntity.Severity           = logEntry.LogEventType;
                logEntity.TimeStamp          = System.DateTime.Now;
                logEntity.ExtendedProperties = exproperties;
                defaultWriter.Write(logEntity);
            }
        }
        /// <summary>
        /// Writes a message to the log.
        /// </summary>
        /// <param name="logMessage">The message to be written to the log.</param>
        public void Write(IDaLogMessage logMessage)
        {
            if (logMessage == null)
            {
                throw new ArgumentNullException();
            }

            var mselLogEntry = new MselLogging.LogEntry()
            {
                Priority = logMessage.Priority,
                Title    = logMessage.Title,
                Message  = logMessage.Text
            };

            if (logMessage.Categories != null)
            {
                mselLogEntry.Categories = logMessage.Categories;
            }

            MselLogging.Logger.Write(mselLogEntry);
        }
Exemplo n.º 46
0
        public void WriteLog(string message, string category, TraceEventType level)
        {
            if (level == TraceEventType.Error)
            {
                category = Category.GeneralError;
            }

            try
            {
                ELAB.LogEntry logEntry = new ELAB.LogEntry();
                logEntry.Categories.Add(category);
                logEntry.Message  = message;
                logEntry.Priority = 1;
                logEntry.Severity = level;
                ELAB.Logger.Write(logEntry);
            }
            catch (Exception e)
            {
                DumpException(e);
            }
        }
Exemplo n.º 47
0
        /// <summary>
        /// Processes the request.
        /// </summary>
        /// <param name="requestMessage">The request message.</param>
        public override void ProcessRequest(RequestMessage requestMessage)
        {
            try
            {
                // Get the opco shipment from the request processor
                if (!RequestProcessor.RequestDictionary.ContainsKey("OpCoShipment") ||
                    RequestProcessor.RequestDictionary["OpCoShipment"] == null)
                {
                    // Failed to retrieve the opco shipment from the processor
                    throw new Exception("Attempting to map an Op Co Shipment but it was not found in the Request Processor.  Make sure that the shipment parser has been subscribed before the shipment mapper.");
                }

                // Get the cached opco shipment from the processor
                opCoShipment = (OpCoShipment)RequestProcessor.RequestDictionary["OpCoShipment"];

                // Get the audit entry from the processor if we have one (optional)
                if (RequestProcessor.RequestDictionary.ContainsKey("AuditEntry") &&
                    RequestProcessor.RequestDictionary["AuditEntry"] != null)
                {
                    // Get the cached audit entry from the processor
                    auditEntry = (MessageAuditEntry)RequestProcessor.RequestDictionary["AuditEntry"];
                }

                // *****************************************************************
                // ** SEE IF WE HAVE AN EXISTING OPCO SHIPMENT
                // *****************************************************************

                // See if we already have the shipment in the db
                existingOpCoShipment = OpCoShipmentController.GetShipment(
                    opCoShipment.OpCoCode,
                    opCoShipment.ShipmentNumber,
                    opCoShipment.DespatchNumber);

                // Did we find an existing opco shipment
                if (null != existingOpCoShipment)
                {
                    // We've found the shipment, make sure that our sequence number is later
                    if (existingOpCoShipment.OpCoSequenceNumber >= opCoShipment.OpCoSequenceNumber)
                    {
                        // Consume the message as it's old
                        Status = SubscriberStatusEnum.Processed;

                        // Log that the shipment cannot be updated
                        Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry logEntry = new Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry(
                            string.Format("Unable to update existing opco shipment {0} - {1} for for opco {2}.  The request sequence number is {3} but sequence {4} has already been processed.",
                                          opCoShipment.ShipmentNumber,
                                          opCoShipment.DespatchNumber,
                                          opCoShipment.OpCoCode,
                                          opCoShipment.OpCoSequenceNumber,
                                          existingOpCoShipment.OpCoSequenceNumber),
                            "Request Management",
                            0,
                            0,
                            TraceEventType.Information,
                            "Request Management",
                            null);

                        // Write to the log
                        Logger.Write(logEntry);

                        // done
                        return;
                    }
                    else
                    {
                        // See if we need to update the tdc shipment
                        if (existingOpCoShipment.Status == Shipment.StatusEnum.Mapped)
                        {
                            // *****************************************************************
                            // ** SEE IF WE HAVE AN EXISTING TDC SHIPMENT
                            // *****************************************************************

                            // Get the existing tdc shipment
                            existingTDCShipment = TDCShipmentController.GetShipment(
                                opCoShipment.OpCoCode,
                                opCoShipment.ShipmentNumber,
                                opCoShipment.DespatchNumber);

                            // Did we find an existing tdc shipment?
                            if (null != existingTDCShipment)
                            {
                                // See if the tdc shipment can be updated
                                if (existingTDCShipment.Status != Shipment.StatusEnum.Mapped)
                                {
                                    // Consume the message, we can't make the update
                                    Status = SubscriberStatusEnum.Consumed;

                                    // Log that the shipment cannot be updated
                                    Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry logEntry = new Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry(
                                        string.Format("Unable to update existing tdc shipment {0} - {1} for for opco {2}.  The status of the existing tdc shipment is {3} disallowing this update.",
                                                      existingTDCShipment.ShipmentNumber,
                                                      existingTDCShipment.DespatchNumber,
                                                      existingTDCShipment.OpCoCode,
                                                      existingTDCShipment.Status),
                                        "Request Management",
                                        0,
                                        0,
                                        TraceEventType.Information,
                                        "Request Management",
                                        null);

                                    // Write to the log
                                    Logger.Write(logEntry);

                                    // done
                                    return;
                                }
                            }
                            else
                            {
                                // We should have found the tdc shipment
                                Status = SubscriberStatusEnum.Failed;

                                // Log that the tdc shipment cannot be updated
                                Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry logEntry = new Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry(
                                    string.Concat("Unable to update tdc shipment ", opCoShipment.ShipmentNumber, "-", opCoShipment.DespatchNumber, " for opco ", opCoShipment.OpCoCode, ".  The tdc shipment was not found."),
                                    "Request Management",
                                    0,
                                    0,
                                    TraceEventType.Error,
                                    "Request Management",
                                    null);

                                // Write to the log
                                Logger.Write(logEntry);

                                // done
                                return;
                            }
                        }
                    }
                }

                // *****************************************************************
                // ** SAVE OR UPDATE THE OPCO SHIPMENT
                // *****************************************************************

                // See if we have an existing opco shipment
                if (null != existingOpCoShipment)
                {
                    // Update existing opco shipment
                    opCoShipment = (OpCoShipment)existingOpCoShipment.UpdateFromShipment(opCoShipment);
                }

                // Specify that the shipment was updated by this subscriber
                opCoShipment.UpdatedBy = this.GetType().FullName;

                // See if the shipment has been cancelled
                if (0 == opCoShipment.TotalLineQuantity)
                {
                    // Cancel the shipment
                    opCoShipment.Status = Shipment.StatusEnum.Cancelled;
                }
                else if (opCoShipment.OpCoHeld)
                {
                    // Hold the shipment
                    opCoShipment.Status = Shipment.StatusEnum.Held;
                }

                // See if we have an audit entry (not required)
                if (null != auditEntry)
                {
                    // Store the audit entry id
                    opCoShipment.AuditId = auditEntry.Id;
                }

                // Save the opco shipment to the db
                if (-1 != OpCoShipmentController.SaveShipment(opCoShipment))
                {
                    // Cache the opco shipment for other subscribers
                    RequestProcessor.RequestDictionary["OpCoShipment"] = opCoShipment;

                    // *****************************************************************
                    // ** MAP AND SAVE THE TDC SHIPMENT
                    // *****************************************************************

                    // We only create the TDC Shipment if the OpCo Shipment has not been cancelled
                    // If it has been cancelled and we have an existing TDC Shipment we still update it
                    if (opCoShipment.Status != Shipment.StatusEnum.Cancelled || null != existingTDCShipment)
                    {
                        try
                        {
                            // Map the opco shipment to a new tdc shipment
                            tdcShipment = opCoShipment.MapToTDC(existingTDCShipment, this.GetType().FullName, true);

                            // Store the tdc shipment for other subscribers
                            RequestProcessor.RequestDictionary["TDCShipment"] = tdcShipment;
                        }
                        catch (Exception ex)
                        {
                            // Log that the shipment cannot be updated
                            Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry logEntry = new Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry(
                                string.Format("The opco shipment {0} - {1} for opco {2} has a status of NOTMAPPED.  The error was {3}", opCoShipment.ShipmentNumber, opCoShipment.DespatchNumber, opCoShipment.OpCoCode, ex.Message),
                                "Request Management",
                                0,
                                0,
                                TraceEventType.Error,
                                "Request Management",
                                null);

                            // Write to the log
                            Logger.Write(logEntry);
                        }
                    }

                    // Processed
                    Status = SubscriberStatusEnum.Processed;
                }
                else
                {
                    // We failed to save the op co shipment
                }
            }
            catch (Exception ex)
            {
                // Store the exception
                LastError = ex;

                // Failed
                Status = SubscriberStatusEnum.Failed;
            }
            finally
            {
                // Cleanup
                existingOpCoShipment = null;
                existingTDCShipment  = null;
            }
        }
Exemplo n.º 48
0
 void Logger_MessageLogged(Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry entry)
 {
     this.InvokeIfRequired(() => {
         _entries.Add(entry);
     });
 }
        void textFieldParser_RecordFound(ref int currentLineNumber, TextFieldCollection textFields, string lineText)
        {
            string type;
            string subType;

            if (!string.IsNullOrEmpty(lineText))
            {
                GetRowTypeAndSubType(lineText, out type, out subType);

                if (type != HeaderOrFooter && !(subType == "F" || subType == "L"))
                {
                    //check the type and subtype so we know what schema to set the parser to and which handlers to setup
                    RequestSubscriber subscriber = null;
                    switch (type)
                    {
                    case Stock_Code:
                        subscriber = new CommanderProductMaintenanceParsing(this.RequestProcessor);
                        subscriber.ProcessRequest(this.RequestProcessor.RequestMessage);
                        break;

                    case Stock_Receipt:
                        subscriber = new CommanderGoodsInParsing(this.RequestProcessor);
                        subscriber.ProcessRequest(this.RequestProcessor.RequestMessage);
                        break;

                    case Customer_Order:
                        subscriber = new CommanderSalesOrderParsing(this.RequestProcessor);
                        subscriber.ProcessRequest(this.RequestProcessor.RequestMessage);
                        break;

                    case Stock_Summary:
                        subscriber = new CommanderStockParsing(this.RequestProcessor);
                        subscriber.ProcessRequest(this.RequestProcessor.RequestMessage);
                        break;

                    default:
                        // Log that a unrecognised commander message has been found
                        Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry logEntry = new Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry(
                            string.Concat(""),
                            "Request Management",
                            0,
                            0,
                            TraceEventType.Information,
                            null,
                            null);

                        // Write to the log
                        Logger.Write(logEntry);

                        //         Status=SubscriberStatusEnum.Consumed;
                        break;
                    }
                    //textFieldParser.RecordRead -= new TextFieldParser.RecordReadHandler(textFieldParser_RecordRead);
                    if (subscriber != null && subscriber.Status == SubscriberStatusEnum.Failed)
                    {
                        this.LastError = subscriber.LastError;
                        this.Status    = subscriber.Status;
                    }
                }
            }
        }