Exemple #1
0
        public async Task OnAsync(Event <LogEventData> evt)
        {
            try
            {
                //If the event level is defined and it is not in the list do not log it
                if ((LogEventLevelList?.Count ?? 0) > 0 && !LogEventLevelList.Contains(evt.Data.Level))
                {
                    return;
                }

                if (TraceMessage)
                {
                    _log.Information("Start Processing {Message}", evt.Data.RenderedMessage);
                }

                using (var client = new HttpClient(_httpClientHandler, disposeHandler: false))
                {
                    client.BaseAddress = new Uri(TeamsBaseUrl);

                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var js = new JsonSerializerSettings
                    {
                        NullValueHandling = NullValueHandling.Ignore
                    };

                    O365ConnectorCard body = BuildBody(evt);
                    var bodyJson           = JsonConvert.SerializeObject(body, js);
                    var response           = await client.PostAsync("", new StringContent(bodyJson, Encoding.UTF8, "application/json"));

                    if (!response.IsSuccessStatusCode)
                    {
                        _log.Error("Could not send Teams message, server replied {StatusCode} {StatusMessage}: {Message}. Request Body: {RequestBody}", Convert.ToInt32(response.StatusCode), response.StatusCode, await response.Content.ReadAsStringAsync(), bodyJson);
                    }
                    else
                    {
                        if (TraceMessage)
                        {
                            var responseResult = await response.Content.ReadAsStringAsync();

                            _log.Information("Server replied {StatusCode} {StatusMessage}: {Message}", Convert.ToInt32(response.StatusCode), response.StatusCode, responseResult);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex, "An error occured while constructing the request");
            }
        }
Exemple #2
0
        private void SendEventToUdp(Event <LogEventData> evt)
        {
            if (evt == null)
            {
                return;
            }

            if ((LogEventLevelList?.Count ?? 0) > 0 && !LogEventLevelList.Contains(evt.Data.Level))
            {
                return;
            }

            var encoding = Encoding.UTF8;

            IPAddress remoteAddress;

            if (!IPAddress.TryParse(RemoteAddress, out remoteAddress))
            {
                return;
            }

            if (RemotePort < IPEndPoint.MinPort || RemotePort > IPEndPoint.MaxPort)
            {
                return;
            }

            int localPort = LocalPort <= IPEndPoint.MinPort || LocalPort > IPEndPoint.MaxPort ? 0 : LocalPort;

            RemoteEndPoint = new IPEndPoint(remoteAddress, RemotePort);

            using (
                UdpClient client = localPort == 0
                    ? new UdpClient(RemoteEndPoint.AddressFamily)
                    : new UdpClient(localPort, RemoteEndPoint.AddressFamily))
            {
                var renderedMessage   = evt.Data.RenderedMessage;
                var propValuesInTitle = BuildPropertyValuesString(evt);
                var logLevel          = evt.Data.Level.ToString();

                StringBuilder sb = new StringBuilder();
                sb.AppendLine($"[{logLevel}]{(propValuesInTitle.HasValue() ? " " + propValuesInTitle + " | " : " ")} {evt.Data.LocalTimestamp} | {renderedMessage}");

                Byte[] buffer = encoding.GetBytes(sb.ToString().ToCharArray());
                client.Send(buffer, buffer.Length, RemoteEndPoint);
                client.Close();
            }
        }
        public async Task OnAsync(Event <LogEventData> evt)
        {
            //If the event level is defined and it is not in the list do not log it
            if ((LogEventLevelList?.Count ?? 0) > 0 && !LogEventLevelList.Contains(evt.Data.Level))
            {
                return;
            }

            try
            {
                await CreateIssueAsync(evt);
            }
            catch (AggregateException aex)
            {
                var fex = aex.Flatten();
                throw new SeqAppException($"Error while creating item in Azure DevOps. The step is: {_step}.", fex);
            }
            catch (Exception ex)
            {
                throw new SeqAppException($"Error while creating item in Azure DevOps. The step is: {_step}.", ex);
            }
        }
Exemple #4
0
        private async Task <bool> CreateIssue(Event <LogEventData> evt)
        {
            if (evt == null)
            {
                return(false);
            }

            if ((LogEventLevelList?.Count ?? 0) > 0 && !LogEventLevelList.Contains(evt.Data.Level))
            {
                return(false);
            }

            if (!(GitLabProjectName ?? "").HasValue() || !(GitLabPrivateToken ?? "").HasValue())
            {
                return(false);
            }

            object projectNamePropValue = null;

            evt?.Data?.Properties?.TryGetValue(GitLabProjectName, out projectNamePropValue);
            var projectName = projectNamePropValue?.ToString() ?? GitLabProjectName;

            if (!(projectName ?? "").HasValue())
            {
                return(false);
            }


            var apiBaseUrl = GitLabRestApiUrl.NormalizeHostOrFQDN();
            var client     = new JsonRestClient(apiBaseUrl);

            client.DoNotAuthorize = true;

            // Add private token data to request header
            Dictionary <string, string> headers = new Dictionary <string, string>
            {
                ["PRIVATE-TOKEN"] = GitLabPrivateToken
            };

            _step = $"Will get project id for {projectName}";



            var searchResult = await client.GetAsync <List <IdDto> >($"projects/search/{projectName}", headers)
                               .ConfigureAwait(false);

            var projectId = searchResult.FirstOrDefault();

            if (projectId == null)
            {
                Log.Error($"Project not found {projectName}");
                return(false);
            }

            var renderedMessage = (evt?.Data?.RenderedMessage ?? "");
            var summary         = renderedMessage.CleanCRLF().TruncateWithEllipsis(255);

            _step = $"DONE get project id for {projectName}";



            var seqUrl            = SeqUrl.NormalizeHostOrFQDN();
            var eventUrl          = $"{seqUrl}#/events?filter=@Id%20%3D%20'{evt.Id}'";
            var propValuesInTitle = BuildPropertyValuesString(evt, TitlePropertiesList);
            var labels            = BuildPropertyValuesString(evt, LabelPropertiesList, ",", (AddLogLevelAsLabel ? new string[1] {
                evt.Data.Level.ToString()
            } : null));
            StringBuilder sb      = new StringBuilder();



            // Attach the rendered message
            if (renderedMessage.HasValue())
            {
                sb.AppendLine($"**Message** [View Event]({eventUrl})");
                sb.AppendLine("```");
                sb.AppendLine(renderedMessage);
                sb.AppendLine("```");
                sb.AppendLine("");
            }

            // If event has exception attach that Exception
            if (AttachException && (evt?.Data?.Exception ?? "").HasValue())
            {
                sb.AppendLine("**Exception**");
                sb.AppendLine("```");
                sb.AppendLine(evt?.Data?.Exception);
                sb.AppendLine("```");
                sb.AppendLine("");
            }


            // Attach structured properties
            if (AttachProperties && (evt?.Data?.Properties?.Count ?? 0) > 0)
            {
                sb.AppendLine("**Properties**");

                var allProps         = evt.Data.Properties;
                var additionPropList = AdditionalPropertiesList;
                sb.AppendLine("```");
                foreach (var kvp in allProps)
                {
                    if (additionPropList?.Count > 0 && !additionPropList.Contains(kvp.Key))
                    {
                        continue;
                    }

                    sb.AppendLine($"* {kvp.Key} : {(kvp.Value != null ? JsonConvert.SerializeObject(kvp.Value) : "")}");;
                }
                sb.AppendLine("```");
                sb.AppendLine("");
            }


            // Create the issue
            var gitLabIssue = new NewIssuePayload
            {
                id          = projectId.id,
                title       = $"{(propValuesInTitle.HasValue() ? propValuesInTitle + " : " : "")}{summary}",
                description = sb.ToString(),
                labels      = labels
            };

            _step = $"Will create issue for {projectId.id} -> {projectName}";

            // Post the message
            var createIssueResult = await client.PostAsync <NewIssueResponsePayload, NewIssuePayload>($"projects/{projectId.id}/issues", gitLabIssue, headers)
                                    .ConfigureAwait(false);

            if (createIssueResult == null || !createIssueResult.id.HasValue)
            {
                var e     = new ApplicationException($"Can not create issue for project {projectId.id} -> {projectName}");
                var error = (createIssueResult?.error ?? "");
                Log.Error(e, "GitLab create issue failure : {error}", error);
                return(false);
            }

            _step = $"DONE create issue {projectId.id} -> {projectName}";
            return(true);
        }
Exemple #5
0
        private async Task <bool> PostMessage(Event <LogEventData> evt)
        {
            if (evt == null)
            {
                return(false);
            }

            if ((LogEventLevelList?.Count ?? 0) > 0 && !LogEventLevelList.Contains(evt.Data.Level))
            {
                return(false);
            }

            if (!(Channel ?? "").HasValue())
            {
                return(false);
            }

            var apiBaseUrl = RocketApiUrl.NormalizeHostOrFQDN();
            var client     = new JsonRestClient(apiBaseUrl);

            client.DoNotAuthorize = true;

            // Get the auth ticket
            _step = "Will authenticate: " + client.GetUriForResource("login");
            var authTicket =
                await
                client.PostAsync <RocketAuthTicket, RocketAuthPayload>("login", new RocketAuthPayload { username = Username, password = Password })
                .ConfigureAwait(false);

            if (authTicket?.data == null || authTicket.status != "success")
            {
                var e = new ApplicationException("Can not authenticate Rocket.Chat with the specified username/passwod");
                Log.Error(e, "Rocket.Chat authentication failure");
                return(false);
            }

            _step = "Done authenticate";

            var renderedMessage = (evt?.Data?.RenderedMessage ?? "");
            var summary         = renderedMessage.CleanCRLF().TruncateWithEllipsis(255);


            var channel  = Channel.StartsWith("#") ? Channel.Trim() : $"#{Channel.Trim()}";
            var seqUrl   = SeqUrl.NormalizeHostOrFQDN();
            var eventUrl = $"{seqUrl}#/events?filter=@Id%20%3D%20'{evt.Id}'";


            var propValuesInTitle = BuildPropertyValuesString(evt);

            // Create the rocket message
            var rocketMessage = new RocketChatMessage
            {
                channel = channel,
                text    = $"[ View Event ]({eventUrl}) {(propValuesInTitle.HasValue() ? propValuesInTitle + " : " : "")}{summary}"
            };

            // Attach the rendered message
            if (renderedMessage.HasValue())
            {
                var attachment = new RocketChatMessageAttachment
                {
                    color = RocketChatMessageAttachment.ColorByLevel(evt.Data.Level),
                    title = "Message",
                    //title_link = eventUrl,
                    collapsed = true,
                };

                var field = new RocketChatMessageAttachmentField
                {
                    @short = false,
                    value  = renderedMessage,
                };

                attachment.fields = attachment.fields ?? new List <RocketChatMessageAttachmentField>();
                attachment.fields.Add(field);

                rocketMessage.attachments = rocketMessage.attachments ?? new List <RocketChatMessageAttachment>();
                rocketMessage.attachments.Add(attachment);
            }

            // If event has exception attach that Exception
            if (AttachException && (evt?.Data?.Exception ?? "").HasValue())
            {
                var attachment = new RocketChatMessageAttachment
                {
                    color = RocketChatMessageAttachment.ColorByLevel(LogEventLevel.Fatal),
                    title = "Exception",
                    //title_link = eventUrl,
                    collapsed = true,
                };

                var field = new RocketChatMessageAttachmentField
                {
                    @short = false,
                    value  = evt.Data.Exception,
                };

                attachment.fields = attachment.fields ?? new List <RocketChatMessageAttachmentField>();
                attachment.fields.Add(field);

                rocketMessage.attachments = rocketMessage.attachments ?? new List <RocketChatMessageAttachment>();
                rocketMessage.attachments.Add(attachment);
            }


            // Attach structured properties
            if (AttachProperties && (evt?.Data?.Properties?.Count ?? 0) > 0)
            {
                var attachment = new RocketChatMessageAttachment
                {
                    title = "Additional Data",
                    //title_link = eventUrl,
                    collapsed = true
                };

                var allProps         = evt.Data.Properties;
                var additionPropList = AdditionalPropertiesList;

                foreach (var kvp in allProps)
                {
                    if (additionPropList?.Count > 0 && !additionPropList.Contains(kvp.Key))
                    {
                        continue;
                    }

                    var field = new RocketChatMessageAttachmentField
                    {
                        @short = false,
                        title  = kvp.Key,
                        value  = kvp.Value != null?JsonConvert.SerializeObject(kvp.Value) : ""
                    };
                    attachment.fields = attachment.fields ?? new List <RocketChatMessageAttachmentField>();
                    attachment.fields.Add(field);
                }

                rocketMessage.attachments = rocketMessage.attachments ?? new List <RocketChatMessageAttachment>();
                rocketMessage.attachments.Add(attachment);
            }

            // Add auth token data to request header
            Dictionary <string, string> authHeaders = new Dictionary <string, string>
            {
                ["X-User-Id"]    = authTicket.data.userId,
                ["X-Auth-Token"] = authTicket.data.authToken,
            };

            _step = "Will post message";

            // Post the message
            var postMessageResult = await client.PostAsync <RocketChatPostMessageResult, RocketChatMessage>("chat.postMessage", rocketMessage, authHeaders).ConfigureAwait(false);

            if (postMessageResult == null || !postMessageResult.success)
            {
                var e     = new ApplicationException("Can not post message to Rocket.Chat");
                var error = (postMessageResult?.error ?? "");
                Log.Error(e, "Rocket.Chat post message failure : {error}", error);
                return(false);
            }

            _step = "Done post message";
            return(true);
        }
Exemple #6
0
        private async Task <bool> CreateIssue(Event <LogEventData> evt)
        {
            if (evt == null)
            {
                return(false);
            }

            if ((LogEventLevelList?.Count ?? 0) > 0 && !LogEventLevelList.Contains(evt.Data.Level))
            {
                return(false);
            }

            if (!(GitHubRepoName ?? "").HasValue() ||
                !(GitHubRepoOwnerName ?? "").HasValue() ||
                !(GitHubUsername ?? "").HasValue()
                )
            {
                return(false);
            }

            Uri entUri = null;

            if ((GitHubEntUrl ?? "").HasValue() && !Uri.TryCreate(GitHubEntUrl, UriKind.RelativeOrAbsolute, out entUri))
            {
                return(false);
            }


            var phv = new ProductHeaderValue("SeqApp.GitHub");

            if (entUri != null)
            {
                _step = $"Will probe GitHub enterprise {entUri}";
                var probe  = new EnterpriseProbe(phv);
                var result = await probe.Probe(entUri);

                _step = $"DONE probe GitHub enterprise {entUri}";
                if (result != EnterpriseProbeResult.Ok)
                {
                    Log.Error("Probe enterprise GitHub failed with result {result}", result);
                    return(false);
                }
            }


            object repoNamePropValue = null;

            evt?.Data?.Properties?.TryGetValue(GitHubRepoName, out repoNamePropValue);
            var repoName = repoNamePropValue?.ToString() ?? GitHubRepoName;

            if (!(repoName ?? "").HasValue())
            {
                return(false);
            }

            object repoOwnerNamePropValue = null;

            evt?.Data?.Properties?.TryGetValue(GitHubRepoOwnerName, out repoOwnerNamePropValue);
            var repoOwnerName = repoOwnerNamePropValue?.ToString() ?? GitHubRepoOwnerName;

            if (!(repoOwnerName ?? "").HasValue())
            {
                return(false);
            }

            var creds = (GitHubPassword ?? "").HasValue()
                ? new Credentials(GitHubUsername, GitHubPassword)
                : new Credentials(GitHubUsername);

            var client = entUri == null ? new GitHubClient(phv) : new GitHubClient(phv, entUri);

            client.Credentials = creds;

            var renderedMessage   = (evt?.Data?.RenderedMessage ?? "");
            var summary           = renderedMessage.CleanCRLF().TruncateWithEllipsis(255);
            var seqUrl            = SeqUrl.NormalizeHostOrFQDN();
            var eventUrl          = $"{seqUrl}#/events?filter=@Id%20%3D%20'{evt.Id}'";
            var propValuesInTitle = BuildPropertyValuesString(evt, TitlePropertiesList);

            StringBuilder sb = new StringBuilder();

            // Attach the rendered message
            if (renderedMessage.HasValue())
            {
                sb.AppendLine($"**Message** [View Event]({eventUrl})");
                sb.AppendLine("```");
                sb.AppendLine(renderedMessage);
                sb.AppendLine("```");
                sb.AppendLine("");
            }

            // If event has exception attach that Exception
            if (AttachException && (evt?.Data?.Exception ?? "").HasValue())
            {
                sb.AppendLine("**Exception**");
                sb.AppendLine("```");
                sb.AppendLine(evt?.Data?.Exception);
                sb.AppendLine("```");
                sb.AppendLine("");
            }


            // Attach structured properties
            if (AttachProperties && (evt?.Data?.Properties?.Count ?? 0) > 0)
            {
                sb.AppendLine("**Properties**");

                var allProps         = evt.Data.Properties;
                var additionPropList = AdditionalPropertiesList;
                sb.AppendLine("```");
                foreach (var kvp in allProps)
                {
                    if (additionPropList?.Count > 0 && !additionPropList.Contains(kvp.Key))
                    {
                        continue;
                    }

                    sb.AppendLine($"* {kvp.Key} : {(kvp.Value != null ? JsonConvert.SerializeObject(kvp.Value) : "")}");;
                }
                sb.AppendLine("```");
                sb.AppendLine("");
            }


            // Create the issue
            var title = $"{(propValuesInTitle.HasValue() ? propValuesInTitle + " : " : "")}{summary}";

            var newIssue = new NewIssue(title)
            {
                Body = sb.ToString(),
            };
            var labels = GetPropertyValuesAsList(evt, LabelPropertiesList, ",", (AddLogLevelAsLabel ? new string[1] {
                evt.Data.Level.ToString()
            } : null));

            if (labels?.Count > 0)
            {
                labels.ForEach(lb => newIssue.Labels.Add(lb));
            }

            _step = $"Will create issue for {GitHubRepoOwnerName}/{GitHubRepoName}";

            var createdIssue = await client.Issue.Create(GitHubRepoOwnerName, GitHubRepoName, newIssue).ConfigureAwait(false);

            _step = $"DONE create issue for {GitHubRepoOwnerName}/{GitHubRepoName}";
            return(true);
        }
Exemple #7
0
        public void On(Event <LogEventData> evt)
        {
            try
            {
                //If the event level is defined and it is not in the list do not log it
                if ((LogEventLevelList?.Count ?? 0) > 0 && !LogEventLevelList.Contains(evt.Data.Level))
                {
                    return;
                }

                if (TraceMessage)
                {
                    Log
                    .ForContext("Uri", new Uri(TeamsBaseUrl))
                    .Information("Start Processing {Message}", evt.Data.RenderedMessage);
                }

                O365ConnectorCard body = BuildBody(evt);

                var httpClientHandler = new HttpClientHandler();

                if (!string.IsNullOrEmpty(WebProxy))
                {
                    ICredentials credentials = null;
                    if (!string.IsNullOrEmpty(WebProxyUserName))
                    {
                        credentials = new NetworkCredential(WebProxyUserName, WebProxyPassword);
                    }
                    httpClientHandler.Proxy    = new WebProxy(WebProxy, false, null, credentials);
                    httpClientHandler.UseProxy = true;
                }
                else
                {
                    httpClientHandler.UseProxy = false;
                }

                using (var client = new HttpClient(httpClientHandler))
                {
                    client.BaseAddress = new Uri(TeamsBaseUrl);

                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var js = new JsonSerializerSettings();
                    js.NullValueHandling = NullValueHandling.Ignore;

                    var bodyJson = JsonConvert.SerializeObject(body, js);
                    var response = client.PostAsync(
                        "",
                        new StringContent(bodyJson, Encoding.UTF8, "application/json")
                        ).Result;

                    if (!response.IsSuccessStatusCode)
                    {
                        Log
                        .ForContext("Uri", response.RequestMessage.RequestUri)
                        .Error("Could not send Teams message, server replied {StatusCode} {StatusMessage}: {Message}. Request Body: {RequestBody}", Convert.ToInt32(response.StatusCode), response.StatusCode, response.Content.ReadAsStringAsync().Result, bodyJson);
                    }
                    else
                    {
                        if (TraceMessage)
                        {
                            string reponseResult = response.Content.ReadAsStringAsync().Result;
                            Log
                            .ForContext("Uri", response.RequestMessage.RequestUri)
                            .Information("Server replied {StatusCode} {StatusMessage}: {Message}", Convert.ToInt32(response.StatusCode), response.StatusCode, reponseResult);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log
                .ForContext("Uri", new Uri(TeamsBaseUrl))
                .Error(ex, "An error occured while constructing request.");
            }
        }
        public async Task <bool> CreateIssue(Event <LogEventData> evt)
        {
            if (evt == null) //Not sure when or if this could happen?
            {
                return(false);
            }

            //If the event level is defined and it is not in the list do not log it
            if ((LogEventLevelList?.Count ?? 0) > 0 && !LogEventLevelList.Contains(evt.Data.Level))
            {
                return(false);
            }

            _step = "Beginning process";
            LogIfDebug(_step);
            var description = evt.Data.Exception ?? evt.Data.RenderedMessage;
            //var messageId = ComputeId(description);

            var connection = new VssConnection(new Uri(AzureDevOpsUrl), new VssBasicCredential(string.Empty, PersonalAccessToken));

            var workitemClient = await connection.GetClientAsync <WorkItemTrackingHttpClient>();

            WorkItemQueryResult workItemQueryResult = null;

            // Try to match an existing work item
            if (!string.IsNullOrEmpty(SeqEventField))
            {
                _step = "Querying existing work item";
                LogIfDebug(_step);
                Wiql wiql = new Wiql()
                {
                    Query = "Select [State], [Title] " +
                            "From WorkItems " +
                            "Where [" + SeqEventField + "] = '" + evt.Id + "' " +
                            "And [System.TeamProject] = '" + Project + "' " +
                            //"And [System.State] <> 'Closed' " +
                            "Order By [State] Asc, [Changed Date] Desc"
                };

                //execute the query to get the list of work items in teh results
                workItemQueryResult = await workitemClient.QueryByWiqlAsync(wiql);

                if (workItemQueryResult.WorkItems.Count() != 0)
                {
                    Log.Information("Duplicate DevOps item creation prevented for event id {id}", evt.Id);
                    return(false);
                }
            }

            _step = "Adding fields";
            LogIfDebug(_step);
            var document = new JsonPatchDocument();

            _step = "Adding title";
            string title = $"SEQ Event - {evt.Data.RenderedMessage}".TruncateWithEllipsis(255); //DevOps has max 255 character length for title

            if (!string.IsNullOrEmpty(Title))                                                   //User has defined their own title parsing
            {
                title = GetSeqMappedPropertyString(Title, evt).TruncateWithEllipsis(255);
            }
            document.Add(
                new JsonPatchOperation()
            {
                Path      = "/fields/System.Title",
                Operation = Operation.Add,
                Value     = title
            });

            document.Add(
                new JsonPatchOperation()
            {
                Path      = "/fields/System.AssignedTo",
                Operation = Operation.Add,
                Value     = AssignedTo ?? string.Empty
            });

            if (!ParentWorkItemLinkUrl.IsNullOrEmpty())
            {
                document.Add(
                    new JsonPatchOperation()
                {
                    Operation = Operation.Add,
                    Path      = "/relations/-",
                    Value     = new
                    {
                        rel        = "System.LinkTypes.Hierarchy-Reverse",
                        url        = ParentWorkItemLinkUrl,
                        attributes = new
                        {
                            comment = "Seq Event Auto-Parent Link"
                        }
                    }
                }
                    );
            }

            if (!string.IsNullOrEmpty(SeqEventField))
            {
                _step = "Adding Seq ID mapping";
                LogIfDebug(_step);
                document.Add(new JsonPatchOperation()
                {
                    Path      = "/fields/" + SeqEventField,
                    Operation = Operation.Add,
                    Value     = evt.Id
                });
            }

            if (!string.IsNullOrEmpty(Tags))
            {
                _step = "Adding tags";
                LogIfDebug(_step);
                document.Add(new JsonPatchOperation()
                {
                    Path      = "/fields/Tags",
                    Operation = Operation.Add,
                    Value     = Tags //DevOps takes a comma seperated list without any alterations
                });
            }

            _step = "Setting description";
            LogIfDebug(_step);

            document.Add(
                new JsonPatchOperation()
            {
                Path      = $"/fields/{DescriptionDevOpsMappingField}",
                Operation = Operation.Add,
                Value     = RenderDescription(evt)
            });

            if (!string.IsNullOrEmpty(SeqToDevOpsMapping))
            {
                _step = "Setting Seq to DevOps property mappings";
                LogIfDebug(_step);
                var keyValuePairs = SeqToDevOpsMapping.ParseKeyValueArray();
                foreach (var value in keyValuePairs)
                {
                    if (evt.Data.Properties.ContainsKey(value.Key))
                    {
                        LogIfDebug("Setting Seq to DevOps Property: " + value.Value + " Value: " + value.Key);
                        document.Add(
                            new JsonPatchOperation()
                        {
                            Path      = $"/fields/{value.Value}",
                            Operation = Operation.Add,
                            Value     = evt.Data.Properties[value.Key]
                        });
                    }
                }
            }

            if (!string.IsNullOrEmpty(DevOpsMappings))
            {
                _step = "Setting DevOps static property mappings";
                LogIfDebug(_step);
                var keyValuePairs = DevOpsMappings.ParseKeyValueArray();
                foreach (var value in keyValuePairs)
                {
                    LogIfDebug("Setting DevOps Static Property: " + value.Key + " Value: " + value.Value);
                    document.Add(
                        new JsonPatchOperation()
                    {
                        Path      = $"/fields/{value.Key}",
                        Operation = Operation.Add,
                        Value     = value.Value
                    });
                }
            }

            if (!string.IsNullOrEmpty(AreaPath))
            {
                _step = "Setting Area Path";
                LogIfDebug(_step);
                document.Add(
                    new JsonPatchOperation()
                {
                    Path      = $"/fields/System.AreaPath",
                    Operation = Operation.Add,
                    Value     = AreaPath
                });
            }

            if (!string.IsNullOrEmpty(Iteration))
            {
                _step = "Setting Iteration";
                LogIfDebug(_step);
                document.Add(
                    new JsonPatchOperation()
                {
                    Path      = $"/fields/System.IterationPath",
                    Operation = Operation.Add,
                    Value     = Iteration
                });
            }

            _step = "Adding work item";
            LogIfDebug(_step);
            var workitem = await workitemClient.CreateWorkItemAsync(document, Project, DevOpsIssueType, false, true);

            _step = "Finished process";
            LogIfDebug(_step);
            return(true);
        }
Exemple #9
0
        public async Task <bool> CreateIssue(Event <LogEventData> evt)
        {
            if (evt == null)
            {
                return(false);
            }

            if ((LogEventLevelList?.Count ?? 0) > 0 && !LogEventLevelList.Contains(evt.Data.Level))
            {
                return(false);
            }

            var description = evt.Data.Exception ?? evt.Data.RenderedMessage;
            var messageId   = ComputeId(description);
            var summary     = evt.Data.RenderedMessage.CleanCRLF().TruncateWithEllipsis(255);

            var client = new JsonRestClient(JiraApiUrl)
            {
                Username = Username,
                Password = Password
            };


            // Try to match
            if (SeqEventField.HasValue)
            {
                var searchUrl = GiveMeTheSearchDuplicateIssueUrl(messageId);

                var searchResult = await client.GetAsync <JiraIssueSearchResult>(searchUrl).ConfigureAwait(false);

                if ((searchResult?.total ?? 0) > 0)
                {
                    return(false);
                }
            }

            var fields = new Dictionary <string, object>
            {
                { "project", new { key = ProjectKey.Trim() } },
                { "issuetype", new { name = JiraIssueType.Trim() } },
                { "summary", summary },
                { "description", RenderDescription(evt) },
            };

            // Process components
            var components = ComponentsAsArray;

            if ((components?.Count ?? 0) > 0)
            {
                fields.Add("components", components);
            }

            // Process labels
            var labels = Labels.IsNullOrEmpty()
                ? null
                : Labels.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            if ((labels?.Length ?? 0) > 0)
            {
                fields.Add("labels", labels.TrimAll());
            }

            if (SeqEventField.HasValue)
            {
                fields.Add($"customfield_{SeqEventField}", messageId);
            }
            var payload = new { fields };

            //var payloadJson = JsonConvert.SerializeObject(payload);

            // Create the issue
            _step = "Will create issue";
            var result = await client.PostAsync <JiraCreateIssueResponse, object>("issue", payload)
                         .ConfigureAwait(false);

            if ((result?.Errors?.Count ?? 0) > 0)
            {
                var e = new ApplicationException("Jira errors are  " + JsonConvert.SerializeObject(result.Errors));
                Log.Error(e, "Can not crate issue on Jira");
                return(false);
            }
            _step = "Issue created";

            // Add details as comment
            if (!FullDetailsInDescription)
            {
                _step = "Will add details as comment";
                var commentBody = $"{{noformat}}{evt.Data.RenderedMessage}{{noformat}}";
                if (commentBody.HasValue())
                {
                    await CommentAsync(result, commentBody).ConfigureAwait(false);
                }
                _step = "Added details as comment";
            }

            // Properties as comment
            if (PropertiesAsComment)
            {
                _step = "Will add properties as comment";
                var commentBody = RenderProperties(evt, "Structured Event Properties");
                if (commentBody.HasValue())
                {
                    await CommentAsync(result, commentBody).ConfigureAwait(false);
                }
                _step = "Added properties as comment";
            }


            return(true);
        }