Exemple #1
0
 private void LogEvent(EventLogItem eventLog, bool writeWindowsApplicationLog)
 {
     // Check to make sure the proxy is accessible
     //if (base.organizationServiceProxy == null)
     //{
     //    return;
     //}
     try
     {
         Entity logEntity = new Entity(ENTITY_EVENTLOG);
         logEntity.Attributes.Add("inf_name", "Plugin Assembly");
         logEntity.Attributes.Add("inf_type", eventLog.Type);
         logEntity.Attributes.Add("inf_user", this.PluginExecutionContext.UserId.ToString());
         logEntity.Attributes.Add("inf_host", System.Net.Dns.GetHostName());
         logEntity.Attributes.Add("inf_message", eventLog.Message);
         logEntity.Attributes.Add("inf_source", eventLog.Source);
         logEntity.Attributes.Add("inf_stacktrace", eventLog.StackTrace);
         logEntity.Attributes.Add("inf_targetsite", eventLog.TargetSite);
         logEntity.Attributes.Add("inf_innerexceptions", eventLog.InnerExceptions);
         OrganizationService.Create(logEntity);
     }
     catch (Exception handleExceptionFailure)
     {
         if (writeWindowsApplicationLog)
         {
             WriteEventLogEntry("Log failed : unable to create an event log record in MSCRM. Detailed exception:" + handleExceptionFailure.Message);
             WriteEventLogEntry(eventLog.Message + Environment.NewLine + eventLog.StackTrace);
         }
     }
 }
        public void DisplayEvent_GivenStringWithMixOfTagsAndNonTags_CreatesValidEventLogItem()
        {
            EventLog eventLog = new EventLog(new List <Card>()
            {
                new Card()
                {
                    CardID = 1, Name = "TestCard1"
                },
                new Card()
                {
                    CardID = 23, Name = "TestCard23"
                },
                new Card()
                {
                    CardID = 0, Name = "TestCard0"
                }
            });

            string serializedEvent = "Player A traded [1] for property [23] from Player B, and [0] too!";

            eventLog.DisplayEvent(serializedEvent);
            EventLogItem result = eventLog.EventList.FirstOrDefault();

            InlineCollection inlines = (result.Content as TextBlock).Inlines;

            Assert.AreEqual(7, inlines.Count);
            Assert.IsTrue(inlines.ElementAt(0).GetType() == typeof(Run));
            Assert.IsTrue(inlines.ElementAt(1).GetType() == typeof(InlineUIContainer));
            Assert.IsTrue(inlines.ElementAt(2).GetType() == typeof(Run));
            Assert.IsTrue(inlines.ElementAt(3).GetType() == typeof(InlineUIContainer));
            Assert.IsTrue(inlines.ElementAt(4).GetType() == typeof(Run));
            Assert.IsTrue(inlines.ElementAt(5).GetType() == typeof(InlineUIContainer));
            Assert.IsTrue(inlines.ElementAt(6).GetType() == typeof(Run));
        }
Exemple #3
0
        public void Log(EventCode code, EventStatus status, EntityType?entityType, int?entityId, string requestData, string responseData)
        {
            var item = new EventLogItem
            {
                EventCode   = code,
                EventStatus = status,

                UserId     = _sessionContext.IsInitialized ? (int?)_sessionContext.UserId : null,
                UserName   = _sessionContext.IsInitialized ? _sessionContext.UserName : null,
                BranchId   = _branchContext.InBranch ? (int?)_branchContext.Branch.Id : null,
                BranchName = _branchContext.InBranch ? _branchContext.Branch.Name : null,

                Uri     = _accessor.HttpContext.Request.GetDisplayUrl(),
                Address = _accessor.HttpContext.Connection.RemoteIpAddress.ToString(),

                EntityType   = entityType,
                EntityId     = entityId,
                RequestData  = requestData,
                ResponseData = responseData,

                CreateDate = DateTime.Now
            };

            _repository.Insert(item);
        }
Exemple #4
0
        public async Task Service_control_is_not_killed_and_error_is_reported_via_custom_check()
        {
            CustomConfiguration = config =>
            {
                config.EnableFeature <InternalCustomChecks>();
                config.TypesToIncludeInScan(typesToScan);
            };
            EventLogItem entry = null;

            var criticalErrorTriggered = false;

            await Define <MyContext>()
            .Done(async c =>
            {
                if (!criticalErrorTriggered)
                {
                    await this.Post <object>("/api/criticalerror/trigger?message=Failed");
                    criticalErrorTriggered = true;
                    return(false);
                }

                var result = await this.TryGetSingle <EventLogItem>("/api/eventlogitems/", e => e.EventType == typeof(CustomCheckFailed).Name);
                entry      = result;
                return(result);
            })
            .Run();



            Assert.IsTrue(entry.RelatedTo.Any(item => item == "/customcheck/ServiceControl Primary Instance"), "Event log entry should be related to the Primary instance health Custom Check");
            Assert.IsTrue(entry.RelatedTo.Any(item => item.StartsWith("/endpoint/Particular.ServiceControl")), "Event log entry should be related to the ServiceControl endpoint");
        }
Exemple #5
0
        public void LogEventItem(EventLogItem item)
        {
            try
            {
                using (new PerformanceMonitor())
                {
                    var validator = new Validator <EventLogItem>();
                    if (!validator.IsValid(item, true))
                    {
                        logCore.Log(validator.AllMessages(item));
                    }
                    else if (!this.tokenValidator.IsValid(item.Token, true))
                    {
                        logCore.Log(this.tokenValidator.AllMessages(item.Token));
                    }
                    else
                    {
                        application.Validate(item.Token.ApplicationId, item.Token.ValidationKey);

                        logCore.StoreByteCount(item.Token.ApplicationId, DataCostType.Ingress, item);

                        logCore.Log(item);
                    }
                }
            }
            catch (Exception ex)
            {
                logCore.Log(ex, EventTypes.Error, (int)DatumFault.LogEventItem);
                throw;
            }
        }
Exemple #6
0
 /// <summary>
 /// Queue Event Log Item
 /// </summary>
 /// <param name="item">Event Log Item</param>
 internal void Queue(EventLogItem item)
 {
     if (null != item)
     {
         this.eventLogEntries.Enqueue(item);
     }
 }
        public void DisplayEvent_GivenStringWithOnlyTags_CreatesValidEventLogItem()
        {
            EventLog eventLog = new EventLog(new List <Card>()
            {
                new Card()
                {
                    CardID = 1, Name = "TestCard1"
                },
                new Card()
                {
                    CardID = 23, Name = "TestCard23"
                },
                new Card()
                {
                    CardID = 0, Name = "TestCard0"
                }
            });

            string serializedEvent = "[1][23][0]";

            eventLog.DisplayEvent(serializedEvent);
            EventLogItem result = eventLog.EventList.FirstOrDefault();

            InlineCollection inlines = (result.Content as TextBlock).Inlines;

            Assert.AreEqual(3, inlines.Count);
            Assert.IsTrue(inlines.ElementAt(0).GetType() == typeof(InlineUIContainer));
            Assert.IsTrue(inlines.ElementAt(1).GetType() == typeof(InlineUIContainer));
            Assert.IsTrue(inlines.ElementAt(2).GetType() == typeof(InlineUIContainer));
        }
        public async Task Should_result_in_a_custom_check_failed_event()
        {
            var allServiceControlTypes = typeof(InternalCustomChecks).Assembly.GetTypes();
            var allTypesExcludingBuiltInCustomChecks = allServiceControlTypes.Where(t => !t.GetInterfaces().Contains(typeof(ICustomCheck)));
            var customChecksUnderTest = new[] { typeof(FailingCustomCheck) };

            CustomConfiguration = config =>
            {
                config.EnableFeature <InternalCustomChecks>();
                config.TypesToIncludeInScan(allTypesExcludingBuiltInCustomChecks.Concat(customChecksUnderTest));
            };
            EventLogItem entry = null;

            await Define <MyContext>()
            .Done(async c =>
            {
                var result = await this.TryGetSingle <EventLogItem>("/api/eventlogitems/", e => e.EventType == typeof(CustomCheckFailed).Name);
                entry      = result;
                return(result);
            })
            .Run();

            Assert.AreEqual(Severity.Error, entry.Severity, "Failed custom checks should be treated as error");
            Assert.IsTrue(entry.RelatedTo.Any(item => item == "/customcheck/MyCustomCheckId"));
            Assert.IsTrue(entry.RelatedTo.Any(item => item.StartsWith("/endpoint/Particular.ServiceControl")));
        }
        public void Source()
        {
            var item = new EventLogItem();
            var data = StringHelper.ValidString();

            item.Source = data;
            Assert.AreEqual <string>(data, item.Source);
        }
        public void User()
        {
            var item = new EventLogItem();
            var data = StringHelper.ValidString();

            item.User = data;
            Assert.AreEqual <string>(data, item.User);
        }
        public void DisplayEvent_AnyString_AddsToEventLogList()
        {
            EventLog eventLog = new EventLog(new List <Card>());

            eventLog.DisplayEvent(string.Empty);
            EventLogItem result = eventLog.EventList.FirstOrDefault();

            Assert.IsNotNull(result);
        }
        public void EventId()
        {
            var random = new Random();
            var item   = new EventLogItem();
            var data   = random.Next();

            item.EventId = data;
            Assert.AreEqual <int>(data, item.EventId);
        }
        public void InstanceId()
        {
            var random = new Random();
            var item   = new EventLogItem();
            var data   = random.Next();

            item.InstanceId = data;
            Assert.AreEqual <long>(data, item.InstanceId);
        }
        public void LogEventLogItemTokenApplicationIdEmpty()
        {
            var item = new EventLogItem()
            {
                Token = new Token()
            };
            var core = new LogCore();

            core.Log(item);
        }
Exemple #15
0
 private async Task SendAsync(ITargetBlock <EventLogItem> nextBlock, EventLogItem item, CancellationToken stoppingToken = default)
 {
     while (!stoppingToken.IsCancellationRequested && !nextBlock.Completion.IsFaulted)
     {
         if (await nextBlock.SendAsync(item, stoppingToken))
         {
             break;
         }
     }
 }
        public void EntryType()
        {
            var random = new Random();
            var item   = new EventLogItem();

            Assert.AreEqual <EventLogEntryType>(EventLogEntryType.Unknown, item.EntryType);
            var data = EventLogEntryType.Information;

            item.EntryType = data;
            Assert.AreEqual <EventLogEntryType>(data, item.EntryType);
        }
    public void ShouldConvertAppEventSeverityFromJson()
    {
        var original     = new EventLogItem(AppEventSeverity.Values.CriticalError);
        var serialized   = JsonSerializer.Serialize(original);
        var deserialized = JsonSerializer.Deserialize <EventLogItem>(serialized);

        Assert.That(deserialized, Is.EqualTo(original));
        deserialized = JsonSerializer.Deserialize <EventLogItem>("{ \"Severity\": \"Critical Error\" }");
        Assert.That(deserialized, Is.EqualTo(original));
        deserialized = JsonSerializer.Deserialize <EventLogItem>("{ \"Severity\": 100 }");
        Assert.That(deserialized, Is.EqualTo(original));
    }
        public void TestConstructionWithDocument()
        {
            GrouperDocument document = TestHelpers.MakeDocument();
            EventLogItem    logItem  = new EventLogItem(document, message, logLevel);

            Assert.Equal(TestHelpers.DefaultDocumentId, logItem.DocumentId);
            Assert.Equal(TestHelpers.DefaultGroupName, logItem.GroupDisplayName);
            Assert.Equal(TestHelpers.DefaultGroupId, logItem.GroupId);
            Assert.Equal(TestHelpers.DefaultGroupStore, logItem.GroupStore);
            Assert.Equal(message, logItem.Message);
            Assert.Equal(logLevel, logItem.LogLevel);
        }
Exemple #19
0
        /// <summary>
        /// Traces the exception in MS CRM and creates an Event Log record (inf_eventlog) in MSCRM.
        /// If this method fails, the initial error will be written in the Windows Application Log.
        /// </summary>
        /// <param name="ex"></param>
        public void LogException(Exception ex)
        {
            try
            {
                #region Trace method
                base.TracingService.Trace(ex.Message + Environment.NewLine + ex.StackTrace);
                #endregion

                #region Construct Event Log Item

                EventLogItem eventLog = new EventLogItem()
                {
                    Type       = ex.GetType().ToString(),
                    Message    = "<MESSAGE>" + ex.Message + Environment.NewLine + GetFaultDetailMessage(ex) + "</MESSAGE>",
                    Source     = ex.Source,
                    StackTrace = ex.StackTrace,
                    TargetSite = ex.TargetSite != null?ex.TargetSite.ToString() : String.Empty
                };


                StringBuilder innerExceptions = new StringBuilder();
                if (ex.InnerException != null)
                {
                    innerExceptions.Append(Environment.NewLine + "  <INNEREXCEPTIONS>");
                    AppendInnerExceptions(ex.InnerException, innerExceptions);
                    innerExceptions.Append(Environment.NewLine + "  </INNEREXCEPTIONS>");
                    eventLog.InnerExceptions = innerExceptions.ToString();
                }


                if (ex.Data != null && ex.Data.Count > 0)
                {
                    StringBuilder additionInfoMessage = new StringBuilder();
                    foreach (object key in ex.Data.Keys)
                    {
                        additionInfoMessage.Append("<" + key.ToString() + ">");
                        additionInfoMessage.Append(ex.Data[key].ToString());
                        additionInfoMessage.Append("</" + key.ToString() + ">");
                    }
                    eventLog.AdditionalInfo = additionInfoMessage.ToString();
                }

                LogEvent(eventLog, true);

                #endregion
            }
            catch (Exception handleExceptionFailure)
            {
                WriteEventLogEntry("LogException failed : unable to create an event log record in MSCRM. Detailed exception:" + handleExceptionFailure.Message);
                WriteEventLogEntry(ex.Message + Environment.NewLine + ex.StackTrace);
            }
        }
Exemple #20
0
        public void Should_result_in_a_startup_event()
        {
            var          context = new MyContext();
            EventLogItem entry   = null;

            Define(context)
            .WithEndpoint <StartingEndpoint>()
            .Done(c => TryGetSingle("/api/eventlogitems/", out entry, e => e.RelatedTo.Any(r => r.Contains(typeof(StartingEndpoint).Name)) && e.EventType == typeof(EndpointStarted).Name))
            .Run();

            Assert.AreEqual(Severity.Info, entry.Severity, "Endpoint startup should be treated as info");
            Assert.IsTrue(entry.RelatedTo.Any(item => item == "/host/" + context.HostIdentifier));
        }
Exemple #21
0
        private void WriteToLogDb(GrouperDocument document, string message, LogLevels logLevel)
        {
            EventLogItem logItem = new EventLogItem(document, message, logLevel);

            if (Environment.UserInteractive)
            {
                Console.WriteLine(logItem.ToString());
            }
            else
            {
                _logDb.StoreEventLogItemAsync(logItem).GetAwaiter().GetResult();
            }
        }
        public void Should_result_in_a_custom_check_failed_event()
        {
            var context = new MyContext();

            EventLogItem entry = null;

            Define(context)
            .WithEndpoint <EndpointWithFailingCustomCheck>()
            .Done(c => TryGetSingle("/api/eventlogitems/", out entry, e => e.EventType == typeof(CustomCheckFailed).Name))
            .Run();

            Assert.AreEqual(Severity.Error, entry.Severity, "Failed custom checks should be treated as error");
            Assert.IsTrue(entry.RelatedTo.Any(item => item == "/customcheck/EventuallyFailingCustomCheck"));
        }
        public void DisplayEvent_GivenStringWithNoTags_CreatesValidEventLogItem()
        {
            EventLog eventLog = new EventLog(new List <Card>());

            string serializedEvent = "Event with no tags";

            eventLog.DisplayEvent(serializedEvent);
            EventLogItem result = eventLog.EventList.FirstOrDefault();

            InlineCollection inlines = (result.Content as TextBlock).Inlines;

            Assert.AreEqual(1, inlines.Count);
            Assert.IsTrue(inlines.ElementAt(0).GetType() == typeof(Run));
        }
Exemple #24
0
        public void Log(EventLogItem item)
        {
            Contract.Requires <ArgumentNullException>(null != item);
            Contract.Requires <ArgumentNullException>(null != item.Token);
            Contract.Requires <ArgumentOutOfRangeException>(Guid.Empty != item.Token.ApplicationId);

            var data = item.Convert();

            this.eventLogTable.AddEntity(data);

            this.StoreByteCount(item.Token.ApplicationId, DataCostType.Stored, data);

            this.LogMetric(GeneralMetricRow.EventLog);
        }
        public void TestConstructionWithoutGroupStore()
        {
            EventLogItem logItem = new EventLogItem(
                logTime: time,
                documentId: documentId,
                groupId: groupId,
                groupDisplayName: groupName,
                groupStore: null,
                message: message,
                logLevel: logLevel
                );

            Assert.Null(logItem.GroupStore);
        }
        public void TestConstructionWithEmptyGroupDisplayName()
        {
            EventLogItem logItem = new EventLogItem(
                logTime: time,
                documentId: documentId,
                groupId: groupId,
                groupDisplayName: string.Empty,
                groupStore: store.ToString(),
                message: message,
                logLevel: logLevel
                );

            Assert.Null(logItem.GroupDisplayName);
        }
Exemple #27
0
    public void AddAction(LogType type, string action, Vector3 position)
    {
        if (!isActiveAndEnabled)
        {
            Show();
        }
        if (log.Count > maxLogSize)
        {
            EventLogItem temp = log[0];
            log.RemoveAt(0);
            Destroy(temp.gameObject);
        }
        EventLogItem eventLogItem = Instantiate(listPrefab, scrollListParent.transform).GetComponent <EventLogItem>();

        eventLogItem.Setup(position, action);
        log.Add(eventLogItem);
        SoundEnum clip;

        switch (type)
        {
        case LogType.Upgraded:
            clip = SoundEnum.BuildingUpgradeComplete;
            break;

        case LogType.Built:
            clip = SoundEnum.BuildingBuilt;
            break;

        case LogType.EnemyAttacksPlayer:
            clip = SoundEnum.BuildingUpgradeComplete;
            break;

        case LogType.EntityFinished:
            clip = SoundEnum.EntitySwordHitMetal;
            break;

        case LogType.Error:
            clip = SoundEnum.EntityArrowImpact;
            break;

        default:
            clip = SoundEnum.UI_Button_Click;
            break;
        }
        if (clip != SoundEnum.UI_Button_Click)
        {
            Sound.Instance.PlaySoundClip(clip);
        }
    }
Exemple #28
0
 public async Task StoreEventLogItemAsync(EventLogItem logItem)
 {
     await ExecuteStoredProcedureAsync("dbo.new_event_log_entry",
                                       new Dictionary <string, object>()
     {
         { "log_time", logItem.LogTime },
         { "document_id", logItem.DocumentId },
         { "group_id", logItem.GroupId },
         { "group_display_name", logItem.GroupDisplayName },
         { "group_store", logItem.GroupStore?.ToString() },
         { "level", logItem.LogLevel },
         { "message", logItem.Message },
     }
                                       );
 }
Exemple #29
0
        public void Should_add_an_event_log_item()
        {
            var context = new MyContext();

            EventLogItem entry = null;

            Define(context)
            .WithEndpoint <Receiver>(b => b.Given(bus => bus.SendLocal(new MyMessage())))
            .Done(c => TryGetSingle("/api/eventlogitems/", out entry, e => e.RelatedTo.Any(r => r.Contains(c.UniqueMessageId)) && e.EventType == typeof(MessageFailed).Name))
            .Run();

            Assert.AreEqual(Severity.Error, entry.Severity, "Failures should be treated as errors");
            Assert.IsTrue(entry.Description.Contains("exception"), "For failed messages, the description should contain the exception information");
            Assert.IsTrue(entry.RelatedTo.Any(item => item == "/message/" + context.UniqueMessageId), "Should contain the api url to retrieve additional details about the failed message");
            Assert.IsTrue(entry.RelatedTo.Any(item => item == "/endpoint/" + context.EndpointNameOfReceivingEndpoint), "Should contain the api url to retrieve additional details about the endpoint where the message failed");
        }
Exemple #30
0
        public void Should_result_in_a_custom_check_failed_event()
        {
            var context = new MyContext();

            EventLogItem entry = null;

            Scenario.Define(context)
            .WithEndpoint <ManagementEndpoint>(c => c.AppConfig(PathToAppConfig))
            .WithEndpoint <EndpointWithFailingCustomCheck>()
            .Done(c => TryGetSingle("/api/eventlogitems/", out entry, e => e.EventType == typeof(CustomCheckFailed).Name))
            .Run();

            Assert.AreEqual(Severity.Error, entry.Severity, "Failed custom checks should be treated as info");
            Assert.IsTrue(entry.RelatedTo.Any(item => item == "/customcheck/MyCustomCheckId"));
            Assert.IsTrue(entry.RelatedTo.Any(item => item.StartsWith("/endpoint/CustomChecks.EndpointWithFailingCustomCheck")));
        }