//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);
            }
        }
        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);
        }
        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"
            });
        }
        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"
            });
        }
        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);
                }
            }
        }