//it also works with mappings
        private void AddLastUpdateUser(SystemToDbViewModel systemToDbViewModel, JiraRequest jiraRequest, Staging staging, List <SyncSystemFieldMapping> syncSystemFieldMappings)
        {
            if (staging == null)
            {
                return;
            }
            if (jiraRequest.User == null)
            {
                return;
            }
            if (jiraRequest.Issue?.Fields?.Assignee != null &&
                jiraRequest.User.Name == jiraRequest.Issue.Fields.Assignee.Name)
            {
                return;
            }
            SyncSystemFieldMapping lastUpdateUserFieldMapping = syncSystemFieldMappings
                                                                .FirstOrDefault(x => x.EpmFieldName == ProjectServerConstants.LastUpdateUser);

            if (lastUpdateUserFieldMapping != null)
            {
                var stagingFieldMappingValue = new StagingFieldMappingValue
                {
                    Staging = staging,
                    SyncSystemFieldMappingId = lastUpdateUserFieldMapping.SyncSystemFieldMappingId,
                    Value = jiraRequest.User.Key
                };
                systemToDbViewModel.StagingFieldMappingValuesToInsert.Add(stagingFieldMappingValue);
            }
        }
        //on jira request we want to get Sprints to our DB -> we got
        //customfield in webhook for it, so we just need to parse it
        //into our values, and as we don't have rows for them in our tables
        //we store them in field mapping tables
        private void AddSprints(SystemToDbViewModel systemToDbViewModel, JiraRequest jiraRequest, JiraAccessService jiraAccessService,
                                Master master, Staging staging, MasterHistory masterHistory, List <SyncSystemFieldMapping> syncSystemFieldMappings)
        {
            //we receiving fild from jira and getting its value
            CustomField customFieldSprint = customFields.FirstOrDefault(x => x.Name == JiraConstants.SprintFieldName);

            logger.Info($"WebHookReceiver AddSprints issue.Key: {jiraRequest.Issue.Key}");
            if (customFieldSprint != null && jiraRequest.Issue.GetField(customFieldSprint.Id) != null)
            {
                string[] sprintsStrings = JsonConvert.DeserializeObject <string[]>(jiraRequest.Issue.GetField(customFieldSprint.Id).ToString());

                logger.Info($"WebHookReceiver AddSprints jiraRequest.Issue.Key: {jiraRequest.Issue.Key}; " +
                            $"customFieldSprint.Name: {customFieldSprint.Name}; " +
                            $"customFieldSprint.Id: {customFieldSprint.Id}; " +
                            $"sprints.Length: {sprintsStrings.Length}");

                List <MasterFieldMappingValue>        masterFieldMappingValues        = new List <MasterFieldMappingValue>();
                List <MasterHistoryFieldMappingValue> masterHistoryFieldMappingValues = new List <MasterHistoryFieldMappingValue>();
                List <StagingFieldMappingValue>       stagingFieldMappingValues       = new List <StagingFieldMappingValue>();

                JiraSprint jiraSprint = jiraAccessService.ParseSprintField(sprintsStrings);
                commonBusinessService.SetSprintField(jiraSprint, syncSystemFieldMappings, master, masterHistory, staging,
                                                     masterFieldMappingValues, masterHistoryFieldMappingValues, stagingFieldMappingValues);

                systemToDbViewModel.MasterFieldMappingValuesToInsert.AddRange(masterFieldMappingValues);
                systemToDbViewModel.MasterHistoryFieldMappingValuesToInsert.AddRange(masterHistoryFieldMappingValues);
                systemToDbViewModel.StagingFieldMappingValuesToInsert.AddRange(stagingFieldMappingValues);
            }
        }
        private void FillWorkLog(SystemToDbViewModel systemToDbViewModel, JiraRequest jiraRequest, int systemId)
        {
            MasterWorklog masterWorklog = masterWorklogBusinessService
                                          .GetWorkLogById(systemId, jiraRequest.Worklog.Id);

            if (masterWorklog == null)
            {
                masterWorklog = new MasterWorklog
                {
                    RecordDateCreated = DateTime.Now,
                };
                systemToDbViewModel.MasterWorklogsToInsert.Add(masterWorklog);
            }

            masterWorklog.RecordDateUpdated  = DateTime.Now;
            masterWorklog.RecordState        = RecordStateConst.New;
            masterWorklog.WebHookEvent       = jiraRequest.WebhookEvent;
            masterWorklog.SystemId           = systemId;
            masterWorklog.WorkLogId          = jiraRequest.Worklog.Id;
            masterWorklog.IssueId            = jiraRequest.Worklog.IssueId;
            masterWorklog.TimeSpentSeconds   = jiraRequest.WebhookEvent == "worklog_deleted" ? 0 : jiraRequest.Worklog.TimeSpentSeconds;
            masterWorklog.DateStarted        = DateTime.Parse(jiraRequest.Worklog.Started);
            masterWorklog.DateCreated        = DateTime.Parse(jiraRequest.Worklog.Created);
            masterWorklog.DateUpdated        = DateTime.Parse(jiraRequest.Worklog.Updated);
            masterWorklog.Comment            = jiraRequest.Worklog.Comment;
            masterWorklog.AuthorName         = jiraRequest.Worklog.Author.Name.ToLower();
            masterWorklog.AuthorEmailAddress = jiraRequest.Worklog.Author.EmailAddress.ToLower();
            masterWorklog.AuthorKey          = jiraRequest.Worklog.Author.Name.ToLower();
        }
        private async Task GetDataFromTfs(SystemToDbViewModel syncAllViewModel, List <WorkItem> workItems,
                                          int systemId, List <SyncSystemFieldMapping> syncSystemFieldMappings,
                                          WorkItemTrackingHttpClient witClient)
        {
            List <int> childItemIds = new List <int>();

            foreach (WorkItem workItem in workItems)
            {
                FillSyncAllRecord(syncAllViewModel, workItem, systemId, syncSystemFieldMappings);

                if (workItem.Relations != null)
                {
                    foreach (var relationE in workItem.Relations)
                    {
                        if (relationE.Rel == "System.LinkTypes.Hierarchy-Forward")
                        {
                            int childItemId = int.Parse(relationE.Url.Substring(relationE.Url.LastIndexOf("/", StringComparison.Ordinal) + 1));
                            childItemIds.Add(childItemId);
                        }
                    }
                }
            }
            if (childItemIds.Count == 0)
            {
                return;
            }
            List <WorkItem> childItems =
                await witClient.GetWorkItemsAsync(childItemIds, expand : WorkItemExpand.Relations);

            if (childItems.Count == 0)
            {
                return;
            }
            await GetDataFromTfs(syncAllViewModel, childItems, systemId, syncSystemFieldMappings, witClient);
        }
        private Master FillMasterVersionAsync(SystemToDbViewModel systemToDbViewModel, JiraRequest jiraRequest, int systemId)
        {
            logger.Info("WebHookReceiver Version Master");
            Master master = masterBusinessService.GetIssueById(systemId, jiraRequest.Version.Id, "version");

            if (master == null)
            {
                master = new Master
                {
                    RecordDateCreated = DateTime.Now
                };
                systemToDbViewModel.MastersToInsert.Add(master);
            }
            master.RecordDateUpdated = DateTime.Now;
            master.SystemId          = systemId;

            master.IssueId               = jiraRequest.Version.Id;
            master.IssueKey              = jiraRequest.Version.Id;
            master.IssueName             = GetVersionName(jiraRequest);
            master.ProjectId             = jiraRequest.Version.ProjectId.ToString();
            master.ParentVersionReleased = jiraRequest.Version.Released;
            master.IssueTypeName         = "version";
            master.IssueTypeId           = "version";
            master.DateFinish            = jiraRequest.Version.UserReleaseDate;
            master.DateRelease           = jiraRequest.Version.UserReleaseDate;
            //await unitOfWork.SaveChangesAsync();
            return(master);
        }
        private Staging FillStagingVersionAsync(SystemToDbViewModel systemToDbViewModel, JiraRequest jiraRequest,
                                                int systemId, List <SyncSystemFieldMapping> syncSystemFieldMappings)
        {
            if (!CheckChangeLog(jiraRequest, syncSystemFieldMappings))
            {
                return(null);
            }

            logger.Info("WebHookReceiver Version Master");
            var staging = new Staging
            {
                RecordDateCreated     = DateTime.Now,
                RecordDateUpdated     = DateTime.Now,
                RecordState           = RecordStateConst.New,
                WebHookEvent          = jiraRequest.WebhookEvent,
                SystemId              = systemId,
                IssueId               = jiraRequest.Version.Id,
                IssueKey              = jiraRequest.Version.Id,
                IssueName             = GetVersionName(jiraRequest),
                ProjectId             = jiraRequest.Version.ProjectId.ToString(),
                ParentVersionReleased = jiraRequest.Version.Released,
                IssueTypeName         = "version",
                IssueTypeId           = "version",
                DateFinish            = jiraRequest.Version.UserReleaseDate,
                DateRelease           = jiraRequest.Version.UserReleaseDate
            };

            //await unitOfWork.SaveChangesAsync();
            systemToDbViewModel.StagingsToInsert.Add(staging);
            return(staging);
        }
        private MasterHistory FillMasterHistoryVersionAsync(SystemToDbViewModel systemToDbViewModel, JiraRequest jiraRequest, int systemId)
        {
            logger.Info("WebHookReceiver Version MasterHistory");
            var masterHistory = new MasterHistory
            {
                RecordDateCreated = DateTime.Now
            };

            systemToDbViewModel.MasterHistoriesToInsert.Add(masterHistory);

            masterHistory.RecordDateUpdated = DateTime.Now;
            masterHistory.SystemId          = systemId;

            masterHistory.IssueId               = jiraRequest.Version.Id;
            masterHistory.IssueName             = GetVersionName(jiraRequest);
            masterHistory.IssueKey              = jiraRequest.Version.Name.Trim();
            masterHistory.ProjectId             = jiraRequest.Version.ProjectId.ToString();
            masterHistory.ParentVersionReleased = jiraRequest.Version.Released;
            masterHistory.IssueTypeName         = "version";
            masterHistory.IssueTypeId           = "version";
            masterHistory.DateFinish            = jiraRequest.Version.UserReleaseDate;
            masterHistory.DateRelease           = jiraRequest.Version.UserReleaseDate;
            //await unitOfWork.SaveChangesAsync();
            return(masterHistory);
        }
        //function that directly updates our Staging table in DB
        private Staging FillStagingIssueAsync(SystemToDbViewModel systemToDbViewModel, JiraRequest jiraRequest, string jiraEpicLink,
                                              SyncSystemDTO syncSystem, List <SyncSystemFieldMapping> syncSystemFieldMappings)
        {
            if (!CheckChangeLog(jiraRequest, syncSystemFieldMappings))
            {
                return(null);
            }

            logger.Info("WebHookReceiver Staging");
            if (jiraRequest.WebhookEvent == "jira:issue_deleted")
            {
                return(null);
            }

            var staging = new Staging
            {
                RecordDateCreated = DateTime.Now,
                SystemId          = syncSystem.SystemId,
                RecordDateUpdated = DateTime.Now,
                RecordState       = RecordStateConst.New,
                WebHookEvent      = jiraRequest.WebhookEvent,
                ProjectId         = jiraRequest.Issue.Fields.Project.Id,
                ProjectKey        = jiraRequest.Issue.Fields.Project.Key,
                ProjectName       = jiraRequest.Issue.Fields.Project.Name,
                IssueId           = jiraRequest.Issue.Id,
                IssueKey          = jiraRequest.Issue.Key,
                IssueTypeId       = jiraRequest.Issue.Fields.IssueType.Id,
                IssueTypeName     = jiraRequest.Issue.Fields.IssueType.Name,
                IsSubTask         = jiraRequest.Issue.Fields.IssueType.Subtask,
                IssueName         = GetIssueName(jiraRequest),
                ParentEpicKey     = jiraEpicLink,
                //ParentIssueKey = jiraEpicLink,
                OriginalEstimate = jiraRequest.Issue.Fields.TimeOriginalEstimate,
                IssueActualWork  = jiraRequest.Issue.Fields.TimeSpent,
                IssueStatus      = jiraRequest.Issue.Fields.Status.Name,
                DateStart        = jiraRequest.Issue.Fields.Created
            };

            GetChangedFields(jiraRequest.ChangeLog?.Items, staging);
            if (jiraRequest.Issue.Fields.FixVersions != null && jiraRequest.Issue.Fields.FixVersions.Count != 0)
            {
                staging.ParentVersionId       = jiraRequest.Issue.Fields.FixVersions[0].Id;
                staging.ParentVersionName     = jiraRequest.Issue.Fields.FixVersions[0].Name;
                staging.ParentVersionReleased = jiraRequest.Issue.Fields.FixVersions[0].Released;
                staging.DateRelease           = jiraRequest.Issue.Fields.FixVersions[0].ReleaseDate;
            }

            if (jiraRequest.Issue.Fields.Assignee != null)
            {
                staging.Assignee = jiraRequest.Issue.Fields.Assignee.Name.ToLower();
            }
            if (jiraRequest.Issue.Fields.Parent != null)
            {
                staging.ParentIssueId  = jiraRequest.Issue.Fields.Parent.Id;
                staging.ParentIssueKey = jiraRequest.Issue.Fields.Parent.Key;
            }
            systemToDbViewModel.StagingsToInsert.Add(staging);
            return(staging);
        }
        //function that directly updates our Master table in DB
        private Master FillMasterIssueAsync(SystemToDbViewModel systemToDbViewModel, JiraRequest jiraRequest, string jiraEpicLink, SyncSystemDTO syncSystem)
        {
            logger.Info("WebHookReceiver Issue Master");
            Master master = masterBusinessService.GetIssueById(syncSystem.SystemId, jiraRequest.Issue.Id,
                                                               jiraRequest.Issue.Fields.IssueType.Id);

            if (jiraRequest.WebhookEvent == "jira:issue_deleted" && master != null)
            {
                systemToDbViewModel.MastersToDelete.Add(master);
                return(null);
            }
            if (master == null)
            {
                master = new Master
                {
                    RecordDateCreated = DateTime.Now
                };
                systemToDbViewModel.MastersToInsert.Add(master);
            }
            master.RecordDateUpdated = DateTime.Now;
            master.SystemId          = syncSystem.SystemId;
            master.ProjectId         = jiraRequest.Issue.Fields.Project.Id;
            master.ProjectKey        = jiraRequest.Issue.Fields.Project.Key;
            master.ProjectName       = jiraRequest.Issue.Fields.Project.Name;

            master.IssueId       = jiraRequest.Issue.Id;
            master.IssueKey      = jiraRequest.Issue.Key;
            master.IssueTypeId   = jiraRequest.Issue.Fields.IssueType.Id;
            master.IssueTypeName = jiraRequest.Issue.Fields.IssueType.Name;
            master.IsSubTask     = jiraRequest.Issue.Fields.IssueType.Subtask;
            master.IssueName     = GetIssueName(jiraRequest);
            master.ParentEpicKey = jiraEpicLink;
            //master.ParentIssueKey = jiraEpicLink;

            master.OriginalEstimate = jiraRequest.Issue.Fields.TimeOriginalEstimate;
            master.IssueActualWork  = jiraRequest.Issue.Fields.TimeSpent;
            master.DateStart        = jiraRequest.Issue.Fields.Created;

            if (jiraRequest.Issue.Fields.FixVersions != null && jiraRequest.Issue.Fields.FixVersions.Count != 0)
            {
                master.ParentVersionId       = jiraRequest.Issue.Fields.FixVersions[0].Id;
                master.ParentVersionName     = jiraRequest.Issue.Fields.FixVersions[0].Name;
                master.ParentVersionReleased = jiraRequest.Issue.Fields.FixVersions[0].Released;
                master.DateRelease           = jiraRequest.Issue.Fields.FixVersions[0].ReleaseDate;
            }

            if (jiraRequest.Issue.Fields.Assignee != null)
            {
                master.Assignee = jiraRequest.Issue.Fields.Assignee.Name.ToLower();
            }
            master.IssueStatus = jiraRequest.Issue.Fields.Status.Name;
            if (jiraRequest.Issue.Fields.Parent != null)
            {
                master.ParentIssueId  = jiraRequest.Issue.Fields.Parent.Id;
                master.ParentIssueKey = jiraRequest.Issue.Fields.Parent.Key;
            }
            return(master);
        }
        public async Task <ProxyResponse> Execute(int systemId, int itemId, string projectId)
        {
            SystemToDbViewModel syncAllViewModel = new SystemToDbViewModel();

            SyncSystemDTO syncSystem = await syncSystemBusinessService.GetSyncSystemAsync(systemId);

            List <SyncSystemFieldMapping> syncSystemFieldMappings = syncSystemFieldMappingBusinessService.GetSyncSystemFieldMappings(syncSystem.SystemId);

            VssConnection connection = new VssConnection(new Uri(syncSystem.SystemUrl + "/DefaultCollection"),
                                                         new VssBasicCredential(String.Empty, syncSystem.SystemPassword));
            // Create instance of WorkItemTrackingHttpClient using VssConnection
            WorkItemTrackingHttpClient witClient = connection.GetClient <WorkItemTrackingHttpClient>();

            List <WorkItem> epics = new List <WorkItem>();

            if (itemId == 0)
            {
                Wiql wiQuery = new Wiql()
                {
                    Query =
                        "Select [System.Id] "
                        + "from WorkItems"
                        + " Where [System.WorkItemType] = 'Epic'"
                        + $" And [System.TeamProject] = '{projectId}'"
                };
                var items = await witClient.QueryByWiqlAsync(wiQuery);

                List <int>      epicsIds    = items.WorkItems.Select(x => x.Id).ToList();
                List <WorkItem> masterItems = await witClient.GetWorkItemsAsync(epicsIds, expand : WorkItemExpand.Relations);

                epics.AddRange(masterItems);
            }
            else
            {
                WorkItem masterItem = await witClient.GetWorkItemAsync(itemId, expand : WorkItemExpand.Relations);

                epics.Add(masterItem);
            }



            await GetDataFromTfs(syncAllViewModel, epics, systemId, syncSystemFieldMappings, witClient);

            await commonBusinessService.AddNewData(syncAllViewModel);

            commonBusinessService.DeleteOldData(syncAllViewModel, syncSystem.SystemId);

            return(new ProxyResponse
            {
                Result = "ok",
                Data = "TFS Execute OK"
            });
        }
        //function that directly updates our MasterHistory table in DB
        private MasterHistory FillMasterHistoryIssueAsync(SystemToDbViewModel systemToDbViewModel, JiraRequest jiraRequest, string jiraEpicLink, SyncSystemDTO syncSystem)
        {
            logger.Info("WebHookReceiver Issue MasterHistory");
            if (jiraRequest.WebhookEvent == "jira:issue_deleted")
            {
                return(null);
            }
            var masterHistory = new MasterHistory
            {
                RecordDateCreated = DateTime.Now,
                RecordDateUpdated = DateTime.Now,
                SystemId          = syncSystem.SystemId,
                ProjectId         = jiraRequest.Issue.Fields.Project.Id,
                ProjectKey        = jiraRequest.Issue.Fields.Project.Key,
                ProjectName       = jiraRequest.Issue.Fields.Project.Name,
                IssueId           = jiraRequest.Issue.Id,
                IssueKey          = jiraRequest.Issue.Key,
                IssueTypeId       = jiraRequest.Issue.Fields.IssueType.Id,
                IssueTypeName     = jiraRequest.Issue.Fields.IssueType.Name,
                IsSubTask         = jiraRequest.Issue.Fields.IssueType.Subtask,
                IssueName         = GetIssueName(jiraRequest),
                ParentEpicKey     = jiraEpicLink,
                //ParentIssueKey = jiraEpicLink,
                IssueStatus = jiraRequest.Issue.Fields.Status.Name,
                DateStart   = jiraRequest.Issue.Fields.Created
            };

            if (jiraRequest.Issue.Fields.FixVersions != null && jiraRequest.Issue.Fields.FixVersions.Count != 0)
            {
                masterHistory.ParentVersionId       = jiraRequest.Issue.Fields.FixVersions[0].Id;
                masterHistory.ParentVersionName     = jiraRequest.Issue.Fields.FixVersions[0].Name;
                masterHistory.ParentVersionReleased = jiraRequest.Issue.Fields.FixVersions[0].Released;
                masterHistory.DateRelease           = jiraRequest.Issue.Fields.FixVersions[0].ReleaseDate;
            }

            if (jiraRequest.Issue.Fields.Assignee != null)
            {
                masterHistory.Assignee = jiraRequest.Issue.Fields.Assignee.Name.ToLower();
            }
            if (jiraRequest.Issue.Fields.Parent != null)
            {
                masterHistory.ParentIssueId  = jiraRequest.Issue.Fields.Parent.Id;
                masterHistory.ParentIssueKey = jiraRequest.Issue.Fields.Parent.Key;
            }
            systemToDbViewModel.MasterHistoriesToInsert.Add(masterHistory);
            return(masterHistory);
        }
        void FillSyncAllRecord(SystemToDbViewModel syncAllViewModel, WorkItem workItem, int systemId, List <SyncSystemFieldMapping> syncSystemFieldMappings)
        {
            Staging staging = FillSyncAllStagingTable(syncAllViewModel, workItem, systemId);
            Master  master  = FillSyncAllMasterTable(syncAllViewModel, workItem, systemId);

            SyncSystemFieldMapping fieldMappingRecordStateGeneral = syncSystemFieldMappings
                                                                    .FirstOrDefault(x => x.SystemId == systemId &&
                                                                                    x.EpmFieldName == ProjectServerConstants.RecordStateGeneral);

            FillFieldMappingValueTables(syncAllViewModel, staging, master, fieldMappingRecordStateGeneral, RecordStateConst.New);

            SyncSystemFieldMapping fieldMappingRecordStateActual = syncSystemFieldMappings
                                                                   .FirstOrDefault(x => x.SystemId == systemId &&
                                                                                   x.EpmFieldName == ProjectServerConstants.RecordStateActual);

            FillFieldMappingValueTables(syncAllViewModel, staging, master, fieldMappingRecordStateActual, RecordStateConst.Done);
        }
        void FillFieldMappingValueTables(SystemToDbViewModel syncAllViewModel, Staging staging, Master master, SyncSystemFieldMapping fieldMapping, string customFieldValue)
        {
            StagingFieldMappingValue stagingValue = new StagingFieldMappingValue
            {
                Staging = staging,
                SyncSystemFieldMappingId = fieldMapping.SyncSystemFieldMappingId,
                Value = customFieldValue
            };

            syncAllViewModel.StagingFieldMappingValuesToInsert.Add(stagingValue);

            MasterFieldMappingValue masterValue = new MasterFieldMappingValue
            {
                Master = master,
                SyncSystemFieldMappingId = fieldMapping.SyncSystemFieldMappingId,
                Value = customFieldValue
            };

            syncAllViewModel.MasterFieldMappingValuesToInsert.Add(masterValue);
        }
Esempio n. 14
0
 public async Task AddNewData(SystemToDbViewModel systemToDbViewModel)
 {
     Logger.Info($"SyncAll AddNewData MastersToInsert {systemToDbViewModel.MastersToInsert.Count}");
     systemToDbViewModel.MastersToInsert = UnitOfWork.MasterRepository.AddRange(systemToDbViewModel.MastersToInsert);
     Logger.Info($"SyncAll AddNewData MastersToDelete {systemToDbViewModel.MastersToDelete.Count}");
     systemToDbViewModel.MastersToDelete = UnitOfWork.MasterRepository.RemoveRange(systemToDbViewModel.MastersToDelete);
     Logger.Info($"SyncAll AddNewData MasterWorklogsToInsert {systemToDbViewModel.MasterWorklogsToInsert.Count}");
     systemToDbViewModel.MasterWorklogsToInsert = UnitOfWork.MasterWorklogRepository.AddRange(systemToDbViewModel.MasterWorklogsToInsert);
     Logger.Info($"SyncAll AddNewData StagingsToInsert {systemToDbViewModel.StagingsToInsert.Count}");
     systemToDbViewModel.StagingsToInsert = UnitOfWork.StagingRepository.AddRange(systemToDbViewModel.StagingsToInsert);
     Logger.Info($"SyncAll AddNewData MasterHistoriesToInsert {systemToDbViewModel.MasterHistoriesToInsert.Count}");
     systemToDbViewModel.MasterHistoriesToInsert = UnitOfWork.MasterHistoryRepository.AddRange(systemToDbViewModel.MasterHistoriesToInsert);
     Logger.Info($"SyncAll AddNewData MasterFieldMappingValuesToInsert {systemToDbViewModel.MasterFieldMappingValuesToInsert.Count}");
     systemToDbViewModel.MasterFieldMappingValuesToInsert = UnitOfWork.MasterFieldMappingValueRepository.AddRange(systemToDbViewModel.MasterFieldMappingValuesToInsert);
     Logger.Info($"SyncAll AddNewData StagingFieldMappingValuesToInsert {systemToDbViewModel.StagingFieldMappingValuesToInsert.Count}");
     systemToDbViewModel.StagingFieldMappingValuesToInsert = UnitOfWork.StagingFieldMappingValueRepository.AddRange(systemToDbViewModel.StagingFieldMappingValuesToInsert);
     Logger.Info($"SyncAll AddNewData MasterHistoryFieldMappingValuesToInsert {systemToDbViewModel.MasterHistoryFieldMappingValuesToInsert.Count}");
     systemToDbViewModel.MasterHistoryFieldMappingValuesToInsert = UnitOfWork.MasterHistoryFieldMappingValueRepository.AddRange(systemToDbViewModel.MasterHistoryFieldMappingValuesToInsert);
     Logger.Info("SyncAll AddNewData SaveChangesAsync");
     await UnitOfWork.SaveChangesAsync();
 }
Esempio n. 15
0
        public void DeleteOldData(SystemToDbViewModel systemToDbViewModel, int systemId)
        {
            try
            {
                Stopwatch stopwatch = new Stopwatch();
                Logger.Info($"DeleteOldData 1 stopwatch: {stopwatch.ElapsedMilliseconds}");

                List <int> newStagingIds = systemToDbViewModel.StagingsToInsert.Select(x => x.StagingId)
                                           .Distinct()
                                           .ToList();
                List <int> newMasterIds        = systemToDbViewModel.MastersToInsert.Select(x => x.MasterId).Distinct().ToList();
                List <int> newMasterWorklogIds =
                    systemToDbViewModel.MasterWorklogsToInsert.Select(x => x.MasterWorklogId).Distinct().ToList();
                List <string> issueKeys = systemToDbViewModel.MastersToInsert.Select(x => x.IssueKey).Distinct().ToList();
                List <string> issueIds  =
                    systemToDbViewModel.MasterWorklogsToInsert.Select(x => x.IssueId).Distinct().ToList();

                Logger.Info($"DeleteOldData 2 stopwatch: {stopwatch.ElapsedMilliseconds}");

                Logger.Info($"SyncAll DeleteOldData systemId: {systemId} issueKeys: {issueKeys.Count}; " +
                            $"issueIds: {issueIds.Count}; newMasterWorklogIds: {newMasterWorklogIds.Count}; " +
                            $"newStagingIds: {newStagingIds.Count}; newMasterIds: {newMasterIds.Count};");
                UnitOfWork.MasterRepository
                .RemoveRange(x => x.SystemId == systemId && issueKeys.Contains(x.IssueKey) &&
                             !newMasterIds.Contains(x.MasterId));
                UnitOfWork.StagingRepository
                .RemoveRange(x => x.SystemId == systemId && issueKeys.Contains(x.IssueKey) &&
                             !newStagingIds.Contains(x.StagingId));
                UnitOfWork.MasterWorklogRepository
                .RemoveRange(x => x.SystemId == systemId && issueIds.Contains(x.IssueId) &&
                             !newMasterWorklogIds.Contains(x.MasterWorklogId));
                Logger.Info($"DeleteOldData 4 stopwatch: {stopwatch.ElapsedMilliseconds}");
            }
            catch (Exception exception)
            {
                Logger.Warn(exception);
            }
        }
        private void SetCustomFields(SystemToDbViewModel systemToDbViewModel, SyncSystemFieldMapping fieldMapping,
                                     Master master, Staging staging, MasterHistory masterHistory, string resultValue,
                                     List <MasterFieldMappingValue> masterFieldMappingValues, bool isOnlyStaging = false)
        {
            if (fieldMapping == null)
            {
                return;
            }
            if (!isOnlyStaging)
            {
                if (master != null)
                {
                    MasterFieldMappingValue masterValue = masterFieldMappingValues
                                                          .FirstOrDefault(x => x.SyncSystemFieldMappingId == fieldMapping.SyncSystemFieldMappingId);
                    if (masterValue == null)
                    {
                        masterValue = new MasterFieldMappingValue
                        {
                            Master = master,
                            SyncSystemFieldMappingId = fieldMapping.SyncSystemFieldMappingId
                        };
                        systemToDbViewModel.MasterFieldMappingValuesToInsert.Add(masterValue);
                    }
                    if (!String.IsNullOrEmpty(resultValue))
                    {
                        masterValue.Value = resultValue.RemoveNewLinesTabs();
                    }
                }
                if (masterHistory != null)
                {
                    MasterHistoryFieldMappingValue masterHistoryValue = new MasterHistoryFieldMappingValue
                    {
                        MasterHistory            = masterHistory,
                        SyncSystemFieldMappingId = fieldMapping.SyncSystemFieldMappingId,
                        Value = resultValue
                    };
                    systemToDbViewModel.MasterHistoryFieldMappingValuesToInsert.Add(masterHistoryValue);
                }
            }
            if (staging != null)
            {
                StagingFieldMappingValue stagingValue = new StagingFieldMappingValue
                {
                    Staging = staging,
                    SyncSystemFieldMappingId = fieldMapping.SyncSystemFieldMappingId,
                    Value = resultValue
                };
                systemToDbViewModel.StagingFieldMappingValuesToInsert.Add(stagingValue);
            }
            if (!String.IsNullOrEmpty(fieldMapping.StagingFieldName))
            {
                if (staging != null)
                {
                    PropertyInfo piStaging = typeof(Staging).GetProperty(fieldMapping.StagingFieldName);
                    piStaging?.SetValue(staging, resultValue);
                }

                if (!isOnlyStaging)
                {
                    PropertyInfo piMaster = typeof(Master).GetProperty(fieldMapping.StagingFieldName);
                    piMaster?.SetValue(master, resultValue);

                    PropertyInfo piMasterHistory = typeof(MasterHistory).GetProperty(fieldMapping.StagingFieldName);
                    piMasterHistory?.SetValue(masterHistory, resultValue);
                }
            }
        }
        public async Task <ProxyResponse> AddWebhookToDataBase(string jsonWebhook, int systemId)
        {
            logger.Info("WebHookReceiver UnitOfWork");

            JiraAccessService jiraAccessService = null;
            SyncSystemDTO     syncSystem        = await syncSystemBusinessService.GetSyncSystemAsync(systemId);

            if (syncSystem != null)
            {
                jiraAccessService = new JiraAccessService(syncSystem);
            }
            if (jiraAccessService == null)
            {
                //await FillWebHookEntryAsync(unitOfWork, jsonWebhook);
                logger.Error("System not found " + systemId);
                logger.Info("WebHookReceiver END");
                return(new ProxyResponse
                {
                    Result = "ok",
                    Data = "WebHookReceiver POST"
                });
            }
            List <SyncSystemFieldMapping> syncSystemFieldMappings = syncSystemFieldMappingBusinessService.GetSyncSystemFieldMappings(syncSystem.SystemId);

            logger.Info("WebHookReceiver Get Fields Start");
            customFields = await jiraAccessService.GetCustomFields();

            if (customFields == null)
            {
                logger.Error("WebHookReceiver Custom fields for system " + systemId + " is NULL!");
                logger.Info("WebHookReceiver END");
                return(new ProxyResponse
                {
                    Result = "ok",
                    Data = "WebHookReceiver POST"
                });
            }
            jiraEpicLinkField = customFields.FirstOrDefault(x => x.Name == JiraConstants.EpicLinkFieldName);

            logger.Info("WebHookReceiver Get Fields End");
            JiraRequest jiraRequest  = null;
            string      jiraEpicLink = null;
            string      jiraEpicName = null;

            try
            {
                jiraRequest = JsonConvert.DeserializeObject <JiraRequest>(jsonWebhook);
                if (jiraRequest == null)
                {
                    //await FillWebHookEntryAsync(unitOfWork, jsonWebhook);
                    logger.Info("WebHookReceiver END");
                    return(new ProxyResponse
                    {
                        Result = "ok",
                        Data = "WebHookReceiver POST"
                    });
                }
                logger.Info($"WebHookReceiver syncSystem.SystemName: {syncSystem.SystemName}; " +
                            $"jiraRequest.WebhookEvent: {jiraRequest.WebhookEvent}");

                if (jiraRequest.Issue != null)
                {
                    jiraRequest.Issue.AllFields = GetIssueFieldsDictionary(jsonWebhook);

                    if (jiraRequest.Issue.Fields.IssueType.Name != "Epic")
                    {
                        if (jiraEpicLinkField != null)
                        {
                            jiraEpicLink = (string)jiraRequest.Issue.GetField(jiraEpicLinkField.Id);
                            Master masterEpic = masterBusinessService.GetMaster(syncSystem.SystemId, jiraEpicLink);
                            if (masterEpic != null)
                            {
                                jiraEpicName = masterEpic.IssueName;
                            }
                        }
                    }
                    else
                    {
                        jiraEpicName = jiraRequest.Issue.Fields.Summary.Trim();
                    }

                    logger.Info(syncSystem.SystemName + ": " + jiraRequest.WebhookEvent
                                + "; ProjectId: " + jiraRequest.Issue.Fields.Project.Id
                                + "; ProjectKey: " + jiraRequest.Issue.Fields.Project.Key
                                + "; IssueKey: " + jiraRequest.Issue.Key
                                + "; IssueName: " + jiraRequest.Issue.Fields.Summary.Trim()
                                + "; ChangedFields: " + GetChangedFields(jiraRequest.ChangeLog?.Items));
                }
            }
            catch (Exception exception)
            {
                HandleException(exception);
            }
            jiraEpicName = jiraEpicName.RemoveNewLinesTabs().Truncate();
            //DbContextTransaction transaction = unitOfWork.BeginTransaction();
            logger.Info("WebHookReceiver DbContextTransaction");
            try
            {
                SystemToDbViewModel systemToDbViewModel = new SystemToDbViewModel();
                Staging             staging;
                MasterHistory       masterHistory;
                Master master;
                if (jiraRequest?.Issue != null)
                {
                    if (jiraRequest.WebhookEvent == "jira:issue_deleted")
                    {
                        logger.Info("WebHookReceiver END");

                        return(new ProxyResponse
                        {
                            Result = "ok",
                            Data = "WebHookReceiver POST"
                        });
                    }
                    master        = FillMasterIssueAsync(systemToDbViewModel, jiraRequest, jiraEpicLink, syncSystem);
                    masterHistory = FillMasterHistoryIssueAsync(systemToDbViewModel, jiraRequest, jiraEpicLink, syncSystem);
                    staging       = FillStagingIssueAsync(systemToDbViewModel, jiraRequest, jiraEpicLink, syncSystem,
                                                          syncSystemFieldMappings);
                    FillCustomFields(systemToDbViewModel, jiraRequest, master, staging, masterHistory,
                                     syncSystemFieldMappings, jiraEpicName);

                    AddLastUpdateUser(systemToDbViewModel, jiraRequest, staging, syncSystemFieldMappings);
                    AddSprints(systemToDbViewModel, jiraRequest, jiraAccessService, master, staging, masterHistory,
                               syncSystemFieldMappings);
                }
                if (jiraRequest?.Worklog != null)
                {
                    FillWorkLog(systemToDbViewModel, jiraRequest, systemId);
                }
                if (jiraRequest?.Version != null)
                {
                    master        = FillMasterVersionAsync(systemToDbViewModel, jiraRequest, systemId);
                    masterHistory = FillMasterHistoryVersionAsync(systemToDbViewModel, jiraRequest, systemId);
                    staging       = FillStagingVersionAsync(systemToDbViewModel, jiraRequest, systemId, syncSystemFieldMappings);

                    if (staging != null)
                    {
                        SyncSystemFieldMapping fieldMappingRecordStateGeneral = syncSystemFieldMappings
                                                                                .FirstOrDefault(x => x.SystemId == staging.SystemId &&
                                                                                                x.EpmFieldName == ProjectServerConstants.RecordStateGeneral);
                        SetCustomFields(systemToDbViewModel, fieldMappingRecordStateGeneral, master, staging, masterHistory,
                                        RecordStateConst.New, null, true);

                        SyncSystemFieldMapping fieldMappingRecordStateActual = syncSystemFieldMappings
                                                                               .FirstOrDefault(x => x.SystemId == staging.SystemId &&
                                                                                               x.EpmFieldName == ProjectServerConstants.RecordStateActual);
                        SetCustomFields(systemToDbViewModel, fieldMappingRecordStateActual, master, staging, masterHistory,
                                        RecordStateConst.Done, null, true);
                    }
                }
                await commonBusinessService.AddNewData(systemToDbViewModel);
            }
            catch (Exception exception)
            {
                logger.Error(exception);
            }
            //catch (DbUpdateException exception)
            //{
            //    foreach (DbEntityEntry dbEntityEntry in exception.Entries)
            //    {
            //        string resultString = dbEntityEntry.CurrentValues.PropertyNames.Aggregate("",
            //            (current, propertyName) =>
            //                current +
            //                $"propertyName: {propertyName} - value: {dbEntityEntry.CurrentValues[propertyName]};");
            //        logger.Fatal(
            //            $"WebHookReceiver DbUpdateException dbEntityEntry.Entity {dbEntityEntry.Entity}; resultString: {resultString}");
            //    }
            //}
            //catch (DbEntityValidationException exception)
            //{
            //    HandleException(exception);
            //    unitOfWork.RollbackTransaction(transaction);

            //    foreach (DbEntityValidationResult validationResult in exception.EntityValidationErrors)
            //    {
            //        foreach (DbValidationError error in validationResult.ValidationErrors)
            //        {
            //            HandleException(error.PropertyName + " " + error.ErrorMessage, true);
            //        }
            //    }
            //}
            //catch (Exception exception)
            //{
            //    HandleException(exception);
            //    unitOfWork.RollbackTransaction(transaction);
            //}
            ////finally
            ////{
            ////    await FillWebHookEntryAsync(unitOfWork, jsonWebhook);
            ////}
            return(new ProxyResponse
            {
                Result = "ok",
                Data = "WebHookReceiver POST"
            });
        }
        Master FillSyncAllMasterTable(SystemToDbViewModel syncAllViewModel, WorkItem workItem, int systemId)
        {
            Master master = new Master
            {
                RecordDateCreated = DateTime.Now,
                SystemId          = systemId,
                RecordDateUpdated = DateTime.Now
            };


            if (workItem.Fields.ContainsKey("System.TeamProject"))
            {
                master.ProjectId   = (string)workItem.Fields["System.TeamProject"];
                master.ProjectKey  = (string)workItem.Fields["System.TeamProject"];
                master.ProjectName = (string)workItem.Fields["System.TeamProject"];
            }
            master.IssueId  = workItem.Id?.ToString();
            master.IssueKey = workItem.Id?.ToString();
            if (workItem.Fields.ContainsKey("System.WorkItemType"))
            {
                master.IssueTypeId   = workItem.Fields["System.WorkItemType"].ToString();
                master.IssueTypeName = workItem.Fields["System.WorkItemType"].ToString();
            }
            if (workItem.Fields.ContainsKey("System.Title"))
            {
                master.IssueName = workItem.Fields["System.Title"].ToString();
            }
            if (workItem.Fields.ContainsKey("System.IterationId"))
            {
                master.ParentVersionId = workItem.Fields["System.IterationId"].ToString();
            }
            if (workItem.Fields.ContainsKey("System.IterationLevel2"))
            {
                master.ParentVersionName = workItem.Fields["System.IterationLevel2"].ToString();
            }
            if (workItem.Fields.ContainsKey("System.AssignedTo"))
            {
                if (workItem.Fields["System.AssignedTo"] != null)
                {
                    master.Assignee = workItem.Fields["System.AssignedTo"].ToString()
                                      .Substring(workItem.Fields["System.AssignedTo"].ToString()
                                                 .IndexOf("<", StringComparison.Ordinal)).Trim('<', '>');
                }
            }
            if (workItem.Relations != null)
            {
                WorkItemRelation relationCrt = workItem.Relations
                                               .FirstOrDefault(x => x.Rel == "System.LinkTypes.Hierarchy-Reverse");
                if (relationCrt != null)
                {
                    if (workItem.Fields["System.WorkItemType"].ToString().ToLower().Equals("feature"))
                    {
                        master.ParentEpicId  = relationCrt.Url.Substring(relationCrt.Url.LastIndexOf("/", StringComparison.Ordinal) + 1);
                        master.ParentEpicKey = relationCrt.Url.Substring(relationCrt.Url.LastIndexOf("/", StringComparison.Ordinal) + 1);
                    }
                    else
                    {
                        master.ParentIssueId  = relationCrt.Url.Substring(relationCrt.Url.LastIndexOf("/", StringComparison.Ordinal) + 1);
                        master.ParentIssueKey = relationCrt.Url.Substring(relationCrt.Url.LastIndexOf("/", StringComparison.Ordinal) + 1);
                    }
                }
                else
                {
                    master.ParentIssueId  = null;
                    master.ParentIssueKey = null;
                }
            }

            syncAllViewModel.MastersToInsert.Add(master);
            return(master);
        }
        Staging FillSyncAllStagingTable(SystemToDbViewModel syncAllViewModel, WorkItem workItem, int systemId)
        {
            Staging staging = new Staging
            {
                RecordDateCreated = DateTime.Now,
                SystemId          = systemId,
                ChangedFields     = "all",
                RecordDateUpdated = DateTime.Now,
                RecordState       = RecordStateConst.New,
                WebHookEvent      = "syncAll"
            };

            if (workItem.Fields.ContainsKey("System.TeamProject"))
            {
                staging.ProjectId   = (string)workItem.Fields["System.TeamProject"];
                staging.ProjectKey  = (string)workItem.Fields["System.TeamProject"];
                staging.ProjectName = (string)workItem.Fields["System.TeamProject"];
            }
            staging.IssueId  = workItem.Id?.ToString();
            staging.IssueKey = workItem.Id?.ToString();
            if (workItem.Fields.ContainsKey("System.WorkItemType"))
            {
                staging.IssueTypeId   = workItem.Fields["System.WorkItemType"].ToString();
                staging.IssueTypeName = workItem.Fields["System.WorkItemType"].ToString();
            }
            if (workItem.Fields.ContainsKey("System.Title"))
            {
                staging.IssueName = workItem.Fields["System.Title"].ToString();
            }
            if (workItem.Fields.ContainsKey("System.IterationId"))
            {
                staging.ParentVersionId = workItem.Fields["System.IterationId"].ToString();
            }
            if (workItem.Fields.ContainsKey("System.IterationLevel2"))
            {
                staging.ParentVersionName = workItem.Fields["System.IterationLevel2"].ToString();
            }
            if (workItem.Fields.ContainsKey("System.AssignedTo"))
            {
                if (workItem.Fields["System.AssignedTo"] != null)
                {
                    staging.Assignee = workItem.Fields["System.AssignedTo"].ToString()
                                       .Substring(workItem.Fields["System.AssignedTo"].ToString()
                                                  .IndexOf("<", StringComparison.Ordinal)).Trim('<', '>');
                }
            }
            if (workItem.Relations != null)
            {
                WorkItemRelation relationCrt = workItem.Relations
                                               .FirstOrDefault(x => x.Rel == "System.LinkTypes.Hierarchy-Reverse");
                if (relationCrt != null)
                {
                    string  parentKey     = relationCrt.Url.Substring(relationCrt.Url.LastIndexOf("/", StringComparison.Ordinal) + 1);
                    Staging parentStaging = syncAllViewModel.StagingsToInsert.FirstOrDefault(x => x.IssueKey == parentKey);
                    if (parentStaging != null)
                    {
                        if (parentStaging.IssueTypeName == "Epic")
                        {
                            staging.ParentEpicId  = parentKey;
                            staging.ParentEpicKey = parentKey;
                        }
                        else
                        {
                            staging.ParentIssueId  = parentKey;
                            staging.ParentIssueKey = parentKey;
                        }
                    }
                }
                else
                {
                    staging.ParentIssueId  = null;
                    staging.ParentIssueKey = null;
                }
            }

            syncAllViewModel.StagingsToInsert.Add(staging);
            return(staging);
        }
        private void FillCustomFields(SystemToDbViewModel systemToDbViewModel, JiraRequest jiraRequest, Master master,
                                      Staging staging, MasterHistory masterHistory, List <SyncSystemFieldMapping> fieldMappings,
                                      string epicName)
        {
            List <MasterFieldMappingValue> masterFieldMappingValues =
                masterBusinessService.GetMasterFieldMappingValues(master.MasterId);

            foreach (SyncSystemFieldMapping fieldMapping in fieldMappings)
            {
                string resultValue = "";
                if (fieldMapping.EpmFieldName == ProjectServerConstants.RecordStateGeneral)
                {
                    SetCustomFields(systemToDbViewModel, fieldMapping, master, staging, masterHistory, RecordStateConst.New, null, true);
                    continue;
                }
                if (fieldMapping.EpmFieldName == ProjectServerConstants.RecordStateActual)
                {
                    SetCustomFields(systemToDbViewModel, fieldMapping, master, staging, masterHistory,
                                    RecordStateConst.Done, null, true);
                    continue;
                }
                if (String.IsNullOrEmpty(fieldMapping.SystemFieldName))
                {
                    continue;
                }
                if (fieldMapping.EpmFieldName == ProjectServerConstants.EpicName &&
                    !String.IsNullOrEmpty(epicName))
                {
                    SetCustomFields(systemToDbViewModel, fieldMapping, master, staging, masterHistory, epicName, masterFieldMappingValues);
                    continue;
                }
                CustomField customField = customFields
                                          .FirstOrDefault(x => x.Name == fieldMapping.SystemFieldName);
                if (customField != null)
                {
                    object customFieldValue = jiraRequest.Issue.GetField(customField.Id);
                    if (customFieldValue != null)
                    {
                        if (fieldMapping.IsMultiSelect && customFieldValue is JArray)
                        {
                            //logger.Info($"FillCustomFields JArray: {customFieldValue}");
                            var array = (JArray)customFieldValue;
                            resultValue = array.Aggregate(resultValue, (current, jToken) => current + (jToken + ",")).Trim(',');
                        }
                        else
                        {
                            if (fieldMapping.IsIdWithValue)
                            {
                                //logger.Info($"WebHookReceiver FillCustomFields fieldMapping.SystemFieldName: {fieldMapping.SystemFieldName} customFieldValue.ToString(): {customFieldValue}");
                                var objectProperties = JsonConvert.DeserializeObject <Dictionary <string, object> >(customFieldValue.ToString());

                                if (objectProperties.ContainsKey("value"))
                                {
                                    resultValue = objectProperties["value"].ToString();
                                }
                            }
                            else
                            {
                                resultValue = customFieldValue.ToString();
                            }
                        }
                        if (String.IsNullOrEmpty(resultValue))
                        {
                            continue;
                        }
                        SetCustomFields(systemToDbViewModel, fieldMapping, master, staging, masterHistory, resultValue, masterFieldMappingValues);
                    }
                }
            }
            //await unitOfWork.SaveChangesAsync();
        }
        public async Task <ProxyResponse> AddWebhookToDataBase(string jsonWebhook, int systemId)
        {
            Dictionary <string, object> commonDictionary    = JsonConvert.DeserializeObject <Dictionary <string, object> >(jsonWebhook);
            SystemToDbViewModel         systemToDbViewModel = new SystemToDbViewModel();

            logger.Info("WebHookReceiver UnitOfWork");
            int?id = 0;

            switch (commonDictionary[FieldEventType].ToString())
            {
            case "workitem.created":
                var webHookCreateRequest = JsonConvert.DeserializeObject <WebHookCreateRequest>(jsonWebhook);
                id = webHookCreateRequest.Resource?.Id;
                break;

            case "workitem.updated":
                var webHookUpdateRequest = JsonConvert.DeserializeObject <WebHookUpdateRequest>(jsonWebhook);
                id = webHookUpdateRequest.Resource?.WorkItemId;
                break;
            }
            SyncSystemDTO syncSystem = await syncSystemBusinessService.GetSyncSystemAsync(systemId);

            if (syncSystem == null || !id.HasValue || id == 0)
            {
                //await FillWebHookEntryAsync(unitOfWork, result);
                logger.Info("System not found " + systemId);
                logger.Info("WebHookReceiver END");
                return(new ProxyResponse
                {
                    Result = "ok",
                    Data = "WebHookReceiver POST"
                });
            }

            List <SyncSystemFieldMapping> syncSystemFieldMappings = syncSystemFieldMappingBusinessService.GetSyncSystemFieldMappings(systemId);

            //string.Empty, syncSystem.SystemPassword
            //VssConnection connection = new VssConnection(new Uri(syncSystem.SystemUrl + "/DefaultCollection"), new VssCredentials());

            VssConnection connection = new VssConnection(new Uri(syncSystem.SystemUrl + "/DefaultCollection"),
                                                         new VssBasicCredential(String.Empty, syncSystem.SystemPassword));

            // Create instance of WorkItemTrackingHttpClient using VssConnection
            WIT.WorkItemTrackingHttpClient witClient = connection.GetClient <WIT.WorkItemTrackingHttpClient>();
            WorkItem workItem = await witClient.GetWorkItemAsync(id.Value, expand : WorkItemExpand.Relations);

            //DbContextTransaction transaction = unitOfWork.BeginTransaction();
            try
            {
                #region Staging

                var staging = new Staging
                {
                    RecordDateCreated = DateTime.Now,
                    SystemId          = systemId,
                    ChangedFields     = "all",
                    RecordDateUpdated = DateTime.Now,
                    RecordState       = RecordStateConst.New,
                    WebHookEvent      = commonDictionary[FieldEventType].ToString()
                };

                if (workItem.Fields.ContainsKey("System.TeamProject"))
                {
                    staging.ProjectId   = (string)workItem.Fields["System.TeamProject"];
                    staging.ProjectKey  = (string)workItem.Fields["System.TeamProject"];
                    staging.ProjectName = (string)workItem.Fields["System.TeamProject"];
                }
                staging.IssueId  = workItem.Id?.ToString();
                staging.IssueKey = workItem.Id?.ToString();
                if (workItem.Fields.ContainsKey("System.WorkItemType"))
                {
                    staging.IssueTypeId   = workItem.Fields["System.WorkItemType"].ToString();
                    staging.IssueTypeName = workItem.Fields["System.WorkItemType"].ToString();
                }
                if (workItem.Fields.ContainsKey("System.Title"))
                {
                    staging.IssueName = workItem.Fields["System.Title"].ToString();
                }
                if (workItem.Fields.ContainsKey("System.IterationId"))
                {
                    staging.ParentVersionId = workItem.Fields["System.IterationId"].ToString();
                }
                if (workItem.Fields.ContainsKey("System.IterationLevel2"))
                {
                    staging.ParentVersionName = workItem.Fields["System.IterationLevel2"].ToString();
                }
                if (workItem.Fields.ContainsKey(FieldAssignedTo))
                {
                    if (workItem.Fields[FieldAssignedTo] != null)
                    {
                        staging.Assignee = workItem.Fields[FieldAssignedTo].ToString()
                                           .Substring(workItem.Fields[FieldAssignedTo].ToString()
                                                      .IndexOf("<", StringComparison.Ordinal)).Trim('<', '>');
                    }
                }
                if (workItem.Relations != null)
                {
                    WorkItemRelation relationCrt = workItem.Relations
                                                   .FirstOrDefault(x => x.Rel == "System.LinkTypes.Hierarchy-Reverse");
                    if (relationCrt != null)
                    {
                        if (workItem.Fields["System.WorkItemType"].ToString().ToLower().Equals("feature"))
                        {
                            staging.ParentEpicId  = relationCrt.Url.Substring(relationCrt.Url.LastIndexOf("/", StringComparison.Ordinal) + 1);
                            staging.ParentEpicKey = relationCrt.Url.Substring(relationCrt.Url.LastIndexOf("/", StringComparison.Ordinal) + 1);
                        }
                        else
                        {
                            staging.ParentIssueId  = relationCrt.Url.Substring(relationCrt.Url.LastIndexOf("/", StringComparison.Ordinal) + 1);
                            staging.ParentIssueKey = relationCrt.Url.Substring(relationCrt.Url.LastIndexOf("/", StringComparison.Ordinal) + 1);
                        }
                    }
                    else
                    {
                        staging.ParentIssueId  = null;
                        staging.ParentIssueKey = null;
                    }
                }
                systemToDbViewModel.StagingsToInsert.Add(staging);
                //FillStagingWorklog(unitOfWork, staging, workItem, systemId);

                SyncSystemFieldMapping fieldMappingRecordStateGeneral = syncSystemFieldMappings
                                                                        .FirstOrDefault(x => x.SystemId == staging.SystemId &&
                                                                                        x.EpmFieldName == ProjectServerConstants.RecordStateGeneral);

                if (fieldMappingRecordStateGeneral != null)
                {
                    var stagingFieldMappingValueGeneral = new StagingFieldMappingValue
                    {
                        Staging = staging,
                        SyncSystemFieldMappingId = fieldMappingRecordStateGeneral.SyncSystemFieldMappingId,
                        Value = RecordStateConst.New
                    };
                    systemToDbViewModel.StagingFieldMappingValuesToInsert.Add(stagingFieldMappingValueGeneral);
                }

                SyncSystemFieldMapping fieldMappingRecordStateActual = syncSystemFieldMappings
                                                                       .FirstOrDefault(x => x.SystemId == staging.SystemId &&
                                                                                       x.EpmFieldName == ProjectServerConstants.RecordStateActual);

                if (fieldMappingRecordStateActual != null)
                {
                    var stagingFieldMappingValueActual = new StagingFieldMappingValue
                    {
                        Staging = staging,
                        SyncSystemFieldMappingId = fieldMappingRecordStateActual.SyncSystemFieldMappingId,
                        Value = RecordStateConst.Done
                    };
                    systemToDbViewModel.StagingFieldMappingValuesToInsert.Add(stagingFieldMappingValueActual);
                }

                #endregion

                #region Master

                var master = masterBusinessService.GetIssueById(systemId, id.ToString(), staging.IssueTypeId);
                if (master == null)
                {
                    master = new Master
                    {
                        RecordDateCreated = DateTime.Now
                    };
                    systemToDbViewModel.MastersToInsert.Add(master);
                }

                master.RecordDateUpdated = DateTime.Now;
                master.SystemId          = systemId;

                master.IssueId   = staging.IssueId;
                master.IssueKey  = staging.IssueKey;
                master.IssueName = staging.IssueName;

                master.ProjectId   = staging.ProjectId;
                master.ProjectKey  = staging.ProjectKey;
                master.ProjectName = staging.ProjectName;

                master.IsSubTask = staging.IsSubTask;

                master.ParentVersionReleased = staging.ParentVersionReleased;
                master.IssueTypeName         = staging.IssueTypeName;
                master.IssueTypeId           = staging.IssueTypeId;
                master.DateFinish            = staging.DateFinish;
                master.DateRelease           = staging.DateRelease;

                #endregion

                #region MasterHistory

                var masterHistory = new MasterHistory
                {
                    RecordDateCreated = DateTime.Now
                };
                systemToDbViewModel.MasterHistoriesToInsert.Add(masterHistory);

                masterHistory.RecordDateUpdated = DateTime.Now;
                masterHistory.SystemId          = systemId;

                masterHistory.IssueId   = staging.IssueId;
                masterHistory.IssueKey  = staging.IssueKey;
                masterHistory.IssueName = staging.IssueName;

                masterHistory.ProjectId   = staging.ProjectId;
                masterHistory.ProjectKey  = staging.ProjectKey;
                masterHistory.ProjectName = staging.ProjectName;

                masterHistory.IsSubTask = staging.IsSubTask;

                masterHistory.ParentVersionReleased = staging.ParentVersionReleased;
                masterHistory.IssueTypeName         = staging.IssueTypeName;
                masterHistory.IssueTypeId           = staging.IssueTypeId;
                masterHistory.DateFinish            = staging.DateFinish;
                masterHistory.DateRelease           = staging.DateRelease;


                #endregion

                await commonBusinessService.AddNewData(systemToDbViewModel);

                //await unitOfWork.SaveChangesAsync();
                //unitOfWork.CommitTransaction(transaction);
            }
            //catch (DbEntityValidationException exception)
            //{
            //    logger.Fatal(exception);
            //    unitOfWork.RollbackTransaction(transaction);

            //    foreach (DbEntityValidationResult validationResult in exception.EntityValidationErrors)
            //    {
            //        foreach (DbValidationError error in validationResult.ValidationErrors)
            //        {
            //            logger.Fatal(error.PropertyName + " " + error.ErrorMessage);
            //        }
            //    }
            //}
            catch (Exception exception)
            {
                logger.Fatal(exception);
                //unitOfWork.RollbackTransaction(transaction);
            }

            logger.Info("WebHookReceiver END");
            return(new ProxyResponse
            {
                Result = "ok",
                Data = "WebHookReceiver POST"
            });
        }