Exemplo n.º 1
0
        public JsonResult SaveBIC(List <BestInClassModel> bic)
        {
            //added by uday for PL ticket #501 added an extra line to save stage type in
            try
            {
                if (bic != null)
                {
                    string StageType_CR   = Enums.StageType.CR.ToString();
                    string StageType_SV   = Enums.StageType.SV.ToString();
                    string StageType_Size = Enums.StageType.Size.ToString();

                    // Reset existing BIC values for specific Client
                    foreach (var item in db.BestInClasses.Where(cls => cls.Stage.ClientId == Sessions.User.CID).ToList())
                    {
                        db.Entry(item).State = EntityState.Modified;
                        db.BestInClasses.Remove(item);
                        db.SaveChanges();
                    }
                    foreach (var bCls in bic)
                    {
                        BestInClass objBestInClass = new BestInClass();

                        //// Add StageId,StageType,Value to list based on StageType.
                        if (bCls.StageType != null)
                        {
                            if (bCls.StageType == StageType_CR)
                            {
                                objBestInClass.StageId   = bCls.StageID_CR;
                                objBestInClass.StageType = bCls.StageType;
                                objBestInClass.Value     = bCls.ConversionValue;
                            }
                            else if (bCls.StageType == StageType_SV)
                            {
                                objBestInClass.StageId   = bCls.StageID_SV;
                                objBestInClass.StageType = bCls.StageType;
                                objBestInClass.Value     = bCls.VelocityValue;
                            }
                            else if (bCls.StageType == StageType_Size)
                            {
                                objBestInClass.StageId   = bCls.StageID_Size;
                                objBestInClass.StageType = bCls.StageType;
                                objBestInClass.Value     = bCls.ConversionValue;
                            }
                        }
                        objBestInClass.CreatedBy       = Sessions.User.ID;
                        objBestInClass.CreatedDate     = DateTime.Now;
                        db.Entry(objBestInClass).State = EntityState.Added;
                        db.BestInClasses.Add(objBestInClass);
                        db.SaveChanges();
                    }
                    return(Json(new { msg = "Best In Class values saved successfully." }));
                }
            }
            catch (Exception e)
            {
                ErrorSignal.FromCurrentContext().Raise(e);
            }

            return(Json(new { id = 0 }));
        }
Exemplo n.º 2
0
        public static void SaveIntegrationInstanceLogDetails(int _entityId, int?IntegrationInstanceLogId, Enums.MessageOperation MsgOprtn, string functionName, Enums.MessageLabel MsgLabel, string logMsg)
        {
            string logDescription = string.Empty, preMessage = string.Empty;

            try
            {
                if (MsgOprtn.Equals(Enums.MessageOperation.None))
                {
                    preMessage = (MsgLabel.Equals(Enums.MessageLabel.None) ? string.Empty : MsgLabel.ToString() + " : ") + "---";   // if message operation "None" than Message prefix should be "---" ex: .
                }
                else
                {
                    preMessage = (MsgLabel.Equals(Enums.MessageLabel.None) ? string.Empty : (MsgOprtn.Equals(Enums.MessageOperation.Start)) ? string.Empty : (MsgLabel.ToString() + " : ")) + MsgOprtn.ToString() + " :";
                }

                logDescription = preMessage + " " + functionName + " : " + logMsg;
                using (MRPEntities db = new MRPEntities())
                {
                    IntegrationInstanceLogDetail objLogDetails = new IntegrationInstanceLogDetail();
                    objLogDetails.EntityId = _entityId;
                    objLogDetails.IntegrationInstanceLogId = IntegrationInstanceLogId;
                    objLogDetails.LogTime         = System.DateTime.Now;
                    objLogDetails.LogDescription  = logDescription;
                    db.Entry(objLogDetails).State = System.Data.EntityState.Added;
                    db.SaveChanges();
                }
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Dharmraj
        /// Function to update next sync date
        /// </summary>
        /// <param name="integrationInstanceId"></param>
        private void UpdateNextSyncDate(int integrationInstanceId)
        {
            var objSyncFrequency = db.SyncFrequencies.FirstOrDefault(varS => varS.IntegrationInstanceId == integrationInstanceId);

            if (objSyncFrequency != null)
            {
                if (objSyncFrequency.Frequency == FrequencyType.Hourly.ToString())
                {
                    objSyncFrequency.NextSyncDate = objSyncFrequency.NextSyncDate.Value.AddHours(1);
                }
                else if (objSyncFrequency.Frequency == FrequencyType.Daily.ToString())
                {
                    objSyncFrequency.NextSyncDate = objSyncFrequency.NextSyncDate.Value.AddDays(1);
                }
                else if (objSyncFrequency.Frequency == FrequencyType.Weekly.ToString())
                {
                    objSyncFrequency.NextSyncDate = objSyncFrequency.NextSyncDate.Value.AddDays(7);
                }
                else if (objSyncFrequency.Frequency == FrequencyType.Monthly.ToString())
                {
                    objSyncFrequency.NextSyncDate = objSyncFrequency.NextSyncDate.Value.AddMonths(1);
                }

                db.Entry(objSyncFrequency).State = EntityState.Modified;
                db.SaveChanges();
            }
        }
Exemplo n.º 4
0
        //function to apply depedancy order for custom fields.
        //public static void setCustomFieldHierarchy(int parentId, List<CustomAttribute> lstCustomField, ref List<CustomAttribute> finalList)
        //{
        //    foreach (var item in lstCustomField.Where(cf => cf.ParentID == parentId).ToList())
        //    {
        //        finalList.Add(item);
        //        if (lstCustomField.Where(cf => cf.ParentID == int.Parse(item.CustomFieldId)).Any())
        //        {
        //            setCustomFieldHierarchy(int.Parse(item.CustomFieldId), lstCustomField, ref finalList);
        //        }
        //    }
        //}
        public int UpdateColumnView(User_CoulmnView columnview, bool Isgrid, int UserId, string xmlElements)
        {
            int result = 0;

            columnview.ModifyBy   = UserId;
            columnview.ModifyDate = DateTime.Now;
            columnview.IsDefault  = true;
            if (Isgrid)
            {
                columnview.GridAttribute = xmlElements;
            }
            else
            {
                columnview.BudgetAttribute = xmlElements;
            }
            objDbMrpEntities.Entry(columnview).State = EntityState.Modified;
            objDbMrpEntities.SaveChanges();
            result = columnview.ViewId;

            return(result);
        }
Exemplo n.º 5
0
        public void ExecuteStoreProcedure(MRPEntities context, string storeProcName, params object[] parameters)
        {
            string command = "EXEC " + storeProcName;

            foreach (var parameter in parameters)
            {
                command += " @" + parameter + ",";
            }
            command = command.TrimEnd(',');
            context.Database.ExecuteSqlCommand(command, parameters);
            context.SaveChanges();
        }
Exemplo n.º 6
0
 /// <summary>
 /// To update log in IntegrationInstanceSection
 /// Added by Dharmraj on 18-8-2014, PL#684
 /// </summary>
 /// <param name="IntegrationInstanceSectionId"></param>
 /// <param name="Status"></param>
 /// <param name="SyncEnd"></param>
 /// <param name="Description"></param>
 public static void UpdateIntegrationInstanceSection(int IntegrationInstanceSectionId, StatusResult Status, string Description)
 {
     using (MRPEntities db = new MRPEntities())
     {
         IntegrationInstanceSection objIntegrationInstanceSection = db.IntegrationInstanceSections.FirstOrDefault(i => i.IntegrationInstanceSectionId == IntegrationInstanceSectionId);
         objIntegrationInstanceSection.Status          = Status.ToString();
         objIntegrationInstanceSection.Description     = Description;
         objIntegrationInstanceSection.SyncEnd         = DateTime.Now;
         db.Entry(objIntegrationInstanceSection).State = EntityState.Modified;
         db.SaveChanges();
     }
 }
Exemplo n.º 7
0
        /// <summary>
        /// Get Integration Instance Log Id
        /// </summary>
        /// <param name="_userId">User Id.</param>
        /// <param name="_integrationInstanceId"> Integration Instance Id.</param>
        /// <returns>return Integration Instance Log Id.</returns>
        public static int GetIntegrationInstanceLogId(int _userId, int _integrationInstanceId)
        {
            IntegrationInstanceLog instanceLogStart = new IntegrationInstanceLog();

            instanceLogStart.IntegrationInstanceId = Convert.ToInt32(_integrationInstanceId);
            instanceLogStart.SyncStart             = DateTime.Now;
            instanceLogStart.CreatedBy             = _userId;
            instanceLogStart.CreatedDate           = DateTime.Now;
            db.Entry(instanceLogStart).State       = EntityState.Added;
            int result = db.SaveChanges();

            return(instanceLogStart.IntegrationInstanceLogId);
        }
Exemplo n.º 8
0
        public void DeleteTransactionLineItemMapping(int clientId, int mappingId)
        {
            Contract.Requires <ArgumentOutOfRangeException>(clientId > 0, "A clientId less than or equal to zero is invalid, and likely indicates the clientId was not set properly");
            Contract.Requires <ArgumentOutOfRangeException>(mappingId > 0, "A mappingId less than or equal to zero is invalid, and likely indicates the mappingId was not set properly");


            IQueryable <Models.TransactionLineItemMapping> sqlQuery = from tlim in _database.TransactionLineItemMappings
                                                                      join transaction in _database.Transactions on tlim.TransactionId equals transaction.TransactionId
                                                                      where tlim.TransactionLineItemMappingId == mappingId && transaction.ClientID == clientId
                                                                      select tlim;

            Models.TransactionLineItemMapping modelTLIM = sqlQuery.SingleOrDefault();

            if (modelTLIM != null)
            {
                _database.Entry(modelTLIM).State = EntityState.Deleted;
                _database.SaveChanges();
            }
        }
Exemplo n.º 9
0
        public int UpdateAlertRule(AlertRuleDetail objRule, int UserId)
        {
            int result = 0;

            try
            {
                Alert_Rules objalertRule = objDbMrpEntities.Alert_Rules.Where(a => a.RuleId == objRule.RuleId && a.UserId == UserId).FirstOrDefault();
                if (objalertRule != null)
                {
                    objalertRule.EntityId             = Int32.Parse(objRule.EntityID);
                    objalertRule.EntityType           = objRule.EntityType;
                    objalertRule.Indicator            = objRule.Indicator;
                    objalertRule.IndicatorComparision = objRule.IndicatorComparision;;
                    objalertRule.IndicatorGoal        = Int32.Parse(objRule.IndicatorGoal);
                    objalertRule.CompletionGoal       = Int32.Parse(objRule.CompletionGoal);
                    objalertRule.Frequency            = objRule.Frequency;
                    if (objRule.Frequency == Convert.ToString(SyncFrequencys.Weekly))
                    {
                        objalertRule.DayOfWeek = Convert.ToByte(objRule.DayOfWeek);
                    }
                    if (objRule.Frequency == Convert.ToString(SyncFrequencys.Monthly))
                    {
                        if (objRule.DateOfMonth != null)
                        {
                            objalertRule.DateOfMonth = Convert.ToByte(objRule.DateOfMonth);
                        }
                        else
                        {
                            objalertRule.DateOfMonth = 10;
                        }
                    }

                    objalertRule.ModifiedDate       = DateTime.Now;
                    objalertRule.ModifiedBy         = UserId;
                    objalertRule.RuleSummary        = objRule.RuleSummary;
                    objalertRule.LastProcessingDate = DateTime.Now;
                    objalertRule.IsDisabled         = false;

                    objDbMrpEntities.Entry(objalertRule).State = EntityState.Modified;
                    result = objDbMrpEntities.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
            }
            return(result);
        }
Exemplo n.º 10
0
 /// <summary>
 /// To insert log in IntegrationInstanceSection
 /// Added by Dharmraj on 18-8-2014, PL#684
 /// </summary>
 /// <param name="IntegartionInstanceLogId">IntegartionInstanceLogId</param>
 /// <param name="IntegartionInstanceId">Integration Instance Id</param>
 /// <param name="SectionName">Name of section (Entity) for which sync starts</param>
 /// <param name="SyncStart">sync start timestamp</param>
 /// <param name="CreateBy">logged in user id</param>
 /// <returns>IntegrationInstanceSectionId</returns>
 public static int CreateIntegrationInstanceSection(int IntegartionInstanceLogId, int IntegartionInstanceId, string SectionName, DateTime SyncStart, int CreateBy)
 {
     using (MRPEntities db = new MRPEntities())
     {
         IntegrationInstanceSection objIntegrationInstanceSection = new IntegrationInstanceSection();
         objIntegrationInstanceSection.IntegrationInstanceLogId = IntegartionInstanceLogId;
         objIntegrationInstanceSection.IntegrationInstanceId    = IntegartionInstanceId;
         objIntegrationInstanceSection.SectionName     = SectionName;
         objIntegrationInstanceSection.SyncStart       = SyncStart;
         objIntegrationInstanceSection.CreatedDate     = DateTime.Now;
         objIntegrationInstanceSection.CreateBy        = CreateBy;
         db.Entry(objIntegrationInstanceSection).State = EntityState.Added;
         int resulValue = db.SaveChanges();
         if (resulValue > 0)
         {
             return(objIntegrationInstanceSection.IntegrationInstanceSectionId);
         }
         else
         {
             return(0);
         }
     }
 }
Exemplo n.º 11
0
        public bool SyncData(out List <SyncError> lstSyncError)
        {
            lstSyncError = new List <SyncError>();
            string currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            Common.SaveIntegrationInstanceLogDetails(_id, _integrationInstanceLogId, Enums.MessageOperation.Start, currentMethodName, Enums.MessageLabel.Success, "SyncData method start.");
            _integrationInstanceSectionId = Common.CreateIntegrationInstanceSection(_integrationInstanceLogId, _integrationInstanceId, Enums.IntegrationInstanceSectionName.PushTacticData.ToString(), DateTime.Now, _userId);
            _isResultError = false;
            /// Set client Id based on integration instance.
            var IntegrationInstanceslist = db.IntegrationInstances.FirstOrDefault(instance => instance.IntegrationInstanceId == _integrationInstanceId);

            _clientId          = IntegrationInstanceslist.ClientId;
            _integrationTypeId = IntegrationInstanceslist.IntegrationTypeId;

            StringBuilder sbMessage = new StringBuilder();

            //int logRecordSize = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["LogRecordSize"]);
            //int pushRecordBatchSize = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["IntegrationPushRecordBatchSize"]);
            try
            {
                int       TitleLengthLimit = 255; // Keep fix.
                string    tactic           = Enums.EntityType.Tactic.ToString();
                DataTable dtFieldMappings  = new DataTable();
                DataSet   dsFieldMappings  = new DataSet();
                Common.SaveIntegrationInstanceLogDetails(_id, _integrationInstanceLogId, Enums.MessageOperation.Start, currentMethodName, Enums.MessageLabel.Success, "Check DataType Mapping Start.");
                #region "Validate Mappings configured or not"
                List <IntegrationInstanceDataTypeMapping> dataTypeMapping = db.IntegrationInstanceDataTypeMappings.Where(mapping => mapping.IntegrationInstanceId.Equals(_integrationInstanceId)).ToList();
                if (!dataTypeMapping.Any()) // check if there is no field mapping configure then log error to IntegrationInstanceLogDetails table.
                {
                    Enums.EntityType _entityTypeSection = (Enums.EntityType)Enum.Parse(typeof(Enums.EntityType), Convert.ToString(_entityType), true);
                    _ErrorMessage = "You have not configure any single field with Marketo field.";
                    _lstSyncError.Add(Common.PrepareSyncErrorList(0, _entityTypeSection, Enums.IntegrationInstanceSectionName.PushTacticData.ToString(), _ErrorMessage, Enums.SyncStatus.Error, DateTime.Now));
                    Common.SaveIntegrationInstanceLogDetails(_id, _integrationInstanceLogId, Enums.MessageOperation.None, currentMethodName, Enums.MessageLabel.Error, "You have not configure any single field with Marketo field.");
                    _isResultError = true;    // return true value that means error exist and do not proceed for the further mapping list.
                }
                #endregion
                Common.SaveIntegrationInstanceLogDetails(_id, _integrationInstanceLogId, Enums.MessageOperation.End, currentMethodName, Enums.MessageLabel.Success, "Check DataType Mapping End.");

                if (!_isResultError)
                {
                    Common.SaveIntegrationInstanceLogDetails(_id, _integrationInstanceLogId, Enums.MessageOperation.Start, currentMethodName, Enums.MessageLabel.Success, "callling GetFieldMappings to get mapping fields.");
                    dsFieldMappings = objSp.GetFieldMappings(tactic, _clientId, Convert.ToInt32(_integrationTypeId), Convert.ToInt32(_integrationInstanceId));
                    dtFieldMappings = dsFieldMappings.Tables[0];

                    ApiIntegration integrationMarketoClient = new ApiIntegration(Convert.ToInt32(_integrationInstanceId), _id, _entityType, _userId, 0, _applicationId);
                    Common.SaveIntegrationInstanceLogDetails(_id, _integrationInstanceLogId, Enums.MessageOperation.None, currentMethodName, Enums.MessageLabel.Success, "convert filled map datatable to list .");
                    List <Integration.fieldMapping> lstFiledMap = dtFieldMappings.AsEnumerable().Select(m => new Integration.fieldMapping
                    {
                        sourceFieldName      = m.Field <string>("sourceFieldName"),
                        destinationFieldName = m.Field <string>("destinationFieldName"),
                        marketoFieldType     = m.Field <string>("marketoFieldType")
                    }).ToList();

                    Common.SaveIntegrationInstanceLogDetails(_id, _integrationInstanceLogId, Enums.MessageOperation.Start, currentMethodName, Enums.MessageLabel.Success, "creating a parameter list to call the StoreProcedure from API.");
                    List <SpParameters> lstparams = new List <SpParameters>();
                    SpParameters        objSPParams;

                    objSPParams = new SpParameters();
                    objSPParams.parameterValue = _entityType.ToString();
                    objSPParams.name           = "entityType";
                    lstparams.Add(objSPParams);

                    objSPParams = new SpParameters();
                    objSPParams.parameterValue = _id;
                    objSPParams.name           = "id";
                    lstparams.Add(objSPParams);

                    objSPParams = new SpParameters();
                    objSPParams.parameterValue = _clientId.ToString();
                    objSPParams.name           = "clientId";
                    lstparams.Add(objSPParams);

                    objSPParams = new SpParameters();
                    objSPParams.parameterValue = TitleLengthLimit;
                    objSPParams.name           = "SFDCTitleLengthLimit";
                    lstparams.Add(objSPParams);

                    objSPParams = new SpParameters();
                    objSPParams.parameterValue = _integrationInstanceLogId;
                    objSPParams.name           = "integrationInstanceLogId";
                    lstparams.Add(objSPParams);
                    Common.SaveIntegrationInstanceLogDetails(_id, _integrationInstanceLogId, Enums.MessageOperation.End, currentMethodName, Enums.MessageLabel.Success, "parameter list created to call the StoreProcedure from API.");
                    Common.SaveIntegrationInstanceLogDetails(_id, _integrationInstanceLogId, Enums.MessageOperation.Start, currentMethodName, Enums.MessageLabel.Success, "Call Api to push Marketo Data and return error log.");
                    List <Integration.LogDetails> logDetailsList = new List <LogDetails>();
                    try
                    {
                        logDetailsList = integrationMarketoClient.MarketoData_Push("spGetMarketoData", lstFiledMap, _clientId, lstparams);
                    }
                    catch (Exception)
                    {
                        // This catch remains blank to continue log execution process getting from Integration WEB API.
                    }
                    Common.SaveIntegrationInstanceLogDetails(_id, _integrationInstanceLogId, Enums.MessageOperation.None, currentMethodName, Enums.MessageLabel.Success, "Marketo Log detail list get successfully.");

                    IntegrationInstancePlanEntityLog instanceEntity = new IntegrationInstancePlanEntityLog();

                    IntegrationInstanceLogDetail instanceLogDetail = new IntegrationInstanceLogDetail();

                    Dictionary <int, string>   TacticMarketoProgMappingIds = new Dictionary <int, string>();
                    Dictionary <int, DateTime> TacticMarketoLastSyncDates  = new Dictionary <int, DateTime>();

                    List <Plan_Campaign_Program_Tactic> tblTactics = new List <Plan_Campaign_Program_Tactic>();
                    List <int> lstSourceIds = new List <int>();
                    Common.SaveIntegrationInstanceLogDetails(_id, _integrationInstanceLogId, Enums.MessageOperation.Start, currentMethodName, Enums.MessageLabel.Success, "Marketo Log detail insert into database start.");
                    if (logDetailsList.Count > 0 && logDetailsList != null)
                    {
                        lstSourceIds = logDetailsList.Where(log => log.SourceId.HasValue).Select(log => log.SourceId.Value).ToList();
                        tblTactics   = db.Plan_Campaign_Program_Tactic.Where(tac => lstSourceIds.Contains(tac.PlanTacticId)).ToList();

                        #region "Declare Enums & local variables"
                        bool   isExist = false;
                        string strEventAPICall, strEventAuthentication, strErrorConnection, strGetProgramData, strInvalidConnection, strNoRecord, strFetchUserInfo, strParameter, strSystemError;
                        string strInsertProgram, strUpdateProgram, strRequiredTagNotExist, strDataMapping, strFieldMapping;
                        //strEventAPICall = strEventAuthentication = strErrorConnection = strGetProgramData = strInvalidConnection = strNoRecord = strFetchUserInfo = strParameter = strSystemError = string.Empty;


                        strEventAuthentication = Enums.MarketoAPIEventNames.Authentication.ToString();

                        //Common message (Single time)
                        strErrorConnection   = Enums.MarketoAPIEventNames.ErrorInSettingDestinationConnectin.ToString();
                        strGetProgramData    = Enums.MarketoAPIEventNames.GetProgramData.ToString();
                        strInvalidConnection = Enums.MarketoAPIEventNames.InvalidConnection.ToString();
                        strNoRecord          = Enums.MarketoAPIEventNames.NoRecord.ToString();
                        strFetchUserInfo     = Enums.MarketoAPIEventNames.FetchUserInfo.ToString();
                        strParameter         = Enums.MarketoAPIEventNames.Parameter.ToString();
                        strSystemError       = Enums.MarketoAPIEventNames.SystemError.ToString();
                        strEventAPICall      = Enums.MarketoAPIEventNames.APIcall.ToString();
                        strFieldMapping      = Enums.MarketoAPIEventNames.FieldMapping.ToString();

                        //for Each Entity Log
                        strInsertProgram       = Enums.MarketoAPIEventNames.InsertProgram.ToString();
                        strUpdateProgram       = Enums.MarketoAPIEventNames.UpdateProgram.ToString();
                        strRequiredTagNotExist = Enums.MarketoAPIEventNames.RequiredTagNotExist.ToString();
                        strDataMapping         = Enums.MarketoAPIEventNames.DataMapping.ToString();

                        int    entId = 0;
                        string tacticTitle, exMessage;
                        #endregion

                        #region "Authentication Log"
                        //foreach (var logdetail in logDetailsList.Where(log => log.EventName.Equals(strEventAuthentication)))
                        //{
                        //    LogEndErrorDescription = "Authentication Failed :" + integrationSalesforceClient._ErrorMessage;
                        //    Common.SaveIntegrationInstanceLogDetails(_id, integrationinstanceLogId, Enums.MessageOperation.None, currentMethodName, Enums.MessageLabel.Error, LogEndErrorDescription);

                        //    _isResultError = true;
                        //    _isA = true;
                        //    _lstAllSyncError.Add(Common.PrepareSyncErrorList(0, Enums.EntityType.Tactic, string.Empty, "Authentication Failed :" + integrationSalesforceClient._ErrorMessage, Enums.SyncStatus.Error, DateTime.Now));
                        //}
                        #endregion

                        #region "Check log for integration instance section"
                        isExist = logDetailsList.Where(log => (log.EventName.Equals(strErrorConnection) || log.EventName.Equals(strGetProgramData) || log.EventName.Equals(strInvalidConnection) || log.EventName.Equals(strNoRecord) || log.EventName.Equals(strFetchUserInfo) || log.EventName.Equals(strParameter) || log.EventName.Equals(strSystemError) || log.EventName.Equals(strFieldMapping)) && log.Status.ToUpper().Equals("FAILURE")).Any();
                        if (isExist)
                        {
                            _isResultError = true;
                            _ErrorMessage  = "Error in getting data from source, to push to marketo";
                        }
                        #endregion

                        Common.SaveIntegrationInstanceLogDetails(_id, _integrationInstanceLogId, Enums.MessageOperation.Start, currentMethodName, Enums.MessageLabel.Success, "Insert Log detail into IntegrationInstanceLogDetails start.");
                        #region "Original Log for Push Marketo"
                        //Insert Failure error log to IntegrationInstanceLogDetails table
                        foreach (var logdetail in logDetailsList.Where(log => (log.EventName.Equals(strErrorConnection) || log.EventName.Equals(strGetProgramData) || log.EventName.Equals(strInvalidConnection) || log.EventName.Equals(strNoRecord) || log.EventName.Equals(strFetchUserInfo) || log.EventName.Equals(strParameter) || log.EventName.Equals(strSystemError) || log.EventName.Equals(strFieldMapping)) && log.Status.ToUpper().Equals("FAILURE")))
                        {
                            //if (logdetail.Status.ToUpper().Equals("FAILURE"))
                            //{

                            instanceLogDetail          = new IntegrationInstanceLogDetail();
                            entId                      = Convert.ToInt32(logdetail.SourceId);
                            instanceLogDetail.EntityId = entId;
                            instanceLogDetail.IntegrationInstanceLogId = _integrationInstanceLogId;
                            instanceLogDetail.LogTime         = logdetail.EndTimeStamp;
                            instanceLogDetail.LogDescription  = logdetail.Description;
                            db.Entry(instanceLogDetail).State = EntityState.Added;
                            //}
                        }
                        #endregion
                        Common.SaveIntegrationInstanceLogDetails(_id, _integrationInstanceLogId, Enums.MessageOperation.End, currentMethodName, Enums.MessageLabel.Success, "Insert Log detail into IntegrationInstanceLogDetails end.");
                        #region "Entity Logs for each tactic"
                        Common.SaveIntegrationInstanceLogDetails(_id, _integrationInstanceLogId, Enums.MessageOperation.Start, currentMethodName, Enums.MessageLabel.Success, "Insert Log detail into IntegrationInstancePlanEntityLog start.");
                        List <Integration.LogDetails> logDetailsList1 = logDetailsList.Where(log => (log.EventName.Equals(strInsertProgram) || log.EventName.Equals(strUpdateProgram)) || (log.EventName.Equals(strEventAPICall) && log.Status.ToUpper().Equals("FAILURE")) || (log.EventName.Equals(strDataMapping) && log.Status.ToUpper().Equals("FAILURE")) || (log.EventName.Equals(strRequiredTagNotExist) && log.Status.ToUpper().Equals("FAILURE"))).ToList();
                        int pushRecordBatchSize = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["IntegrationPushRecordBatchSize"]);
                        int pushCntr            = 0;
                        try
                        {
                            foreach (var logdetail in logDetailsList1)
                            {
                                db.Configuration.AutoDetectChangesEnabled = false;
                                //Insert  log into IntegrationInstancePlanEntityLog table
                                entId          = Convert.ToInt32(logdetail.SourceId);
                                instanceEntity = new IntegrationInstancePlanEntityLog();
                                instanceEntity.IntegrationInstanceId = _integrationInstanceId;
                                instanceEntity.EntityId      = entId;
                                instanceEntity.EntityType    = Enums.EntityType.Tactic.ToString();
                                instanceEntity.SyncTimeStamp = logdetail.EndTimeStamp;
                                instanceEntity.Operation     = logdetail.Mode.ToString();
                                if (logdetail.Status.ToUpper().Equals("FAILURE"))
                                {
                                    instanceEntity.Status = Enums.SyncStatus.Error.ToString();
                                }
                                else
                                {
                                    instanceEntity.Status = logdetail.Status.ToString();
                                }
                                instanceEntity.ErrorDescription             = logdetail.Description;
                                instanceEntity.CreatedBy                    = _userId;
                                instanceEntity.CreatedDate                  = DateTime.Now;
                                instanceEntity.IntegrationInstanceSectionId = _integrationInstanceSectionId;
                                db.Entry(instanceEntity).State              = EntityState.Added;

                                if (!_lstSyncError.Any(lserr => lserr.EntityId.Equals(entId)))
                                {
                                    if (logdetail.Status.ToUpper().Equals("FAILURE"))
                                    {
                                        //Add Failure Log for Summary Email.
                                        _isResultError = true;
                                        tacticTitle    = tblTactics.Where(tac => tac.PlanTacticId == entId).Select(tac => tac.Title).FirstOrDefault();
                                        exMessage      = "System error occurred while create/update tactic \"" + tacticTitle + "\": " + logdetail.Description;
                                        _lstSyncError.Add(Common.PrepareSyncErrorList(entId, Enums.EntityType.Tactic, Enums.IntegrationInstanceSectionName.PushTacticData.ToString(), exMessage, Enums.SyncStatus.Error, DateTime.Now));
                                    }
                                    else
                                    {
                                        //Add Success Log for Summary Email.
                                        exMessage = logdetail.Mode.ToString();
                                        _lstSyncError.Add(Common.PrepareSyncErrorList(entId, Enums.EntityType.Tactic, Enums.IntegrationInstanceSectionName.PushTacticData.ToString(), exMessage, Enums.SyncStatus.Success, DateTime.Now));
                                    }
                                }
                                if (((pushCntr + 1) % pushRecordBatchSize) == 0)
                                {
                                    db.SaveChanges();
                                }
                                pushCntr++;
                            }
                        }
                        finally
                        {
                            db.Configuration.AutoDetectChangesEnabled = true;
                        }
                        #endregion
                        Common.SaveIntegrationInstanceLogDetails(_id, _integrationInstanceLogId, Enums.MessageOperation.End, currentMethodName, Enums.MessageLabel.Success, "Insert Log detail into IntegrationInstancePlanEntityLog end.");
                        Common.SaveIntegrationInstanceLogDetails(_id, _integrationInstanceLogId, Enums.MessageOperation.Start, currentMethodName, Enums.MessageLabel.Success, "Update Tactic's Marketo ProgramId Mappig list start.");
                        #region "Update Tactic's Marketo ProgramId Mappig list"
                        string     strCreateMode    = Operation.Create.ToString();
                        List <int> lstCreatedTacIds = new List <int>();

                        TacticMarketoProgMappingIds = logDetailsList.Where(log => (log.EventName.Equals(strInsertProgram) || log.EventName.Equals(strUpdateProgram)) && log.SourceId.HasValue && log.EntityId.HasValue).ToDictionary(log => log.SourceId.Value, log => log.EntityId.Value.ToString());
                        var marketoURL = logDetailsList.Where(log => (log.EventName.Equals(strInsertProgram) || log.EventName.Equals(strUpdateProgram)) && log.SourceId.HasValue && log.EntityId.HasValue).ToDictionary(log => log.SourceId.Value, log => log.Url);
                        TacticMarketoLastSyncDates = logDetailsList.Where(log => (log.EventName.Equals(strInsertProgram) || log.EventName.Equals(strUpdateProgram)) && log.SourceId.HasValue && log.EntityId.HasValue).ToDictionary(log => log.SourceId.Value, log => log.EndTimeStamp);
                        if (TacticMarketoProgMappingIds != null && TacticMarketoProgMappingIds.Count > 0)
                        {
                            string AttrMarketoUrl = Enums.EntityIntegrationAttribute.MarketoUrl.ToString();
                            string EntityType     = Enums.EntityType.Tactic.ToString();
                            List <EntityIntegration_Attribute> ListEntityIntegrationAttr = new List <EntityIntegration_Attribute>();
                            EntityIntegration_Attribute        objEntityIntegrationAttr  = new EntityIntegration_Attribute();
                            if (marketoURL.Count > 0)
                            {
                                ListEntityIntegrationAttr = db.EntityIntegration_Attribute.Where(attr => attr.IntegrationinstanceId == _integrationInstanceId &&
                                                                                                 attr.AttrType == AttrMarketoUrl && attr.EntityType == EntityType).ToList();
                            }
                            string   strMarketoProgId, strMarketoURL;
                            DateTime strMarketoLastSync;
                            lstCreatedTacIds = TacticMarketoProgMappingIds.Select(tac => tac.Key).ToList();
                            List <Plan_Campaign_Program_Tactic> lstCreatedTacs = tblTactics.Where(tac => lstCreatedTacIds.Contains(tac.PlanTacticId)).ToList();
                            pushCntr = 0;
                            try
                            {
                                foreach (Plan_Campaign_Program_Tactic tac in lstCreatedTacs)
                                {
                                    db.Configuration.AutoDetectChangesEnabled = false;
                                    strMarketoProgId   = strMarketoURL = string.Empty;
                                    strMarketoProgId   = TacticMarketoProgMappingIds.Where(prg => prg.Key == tac.PlanTacticId).Select(prg => prg.Value).FirstOrDefault();
                                    strMarketoLastSync = TacticMarketoLastSyncDates.Where(prg => prg.Key == tac.PlanTacticId).Select(prg => prg.Value).FirstOrDefault();
                                    if (strMarketoProgId != null)
                                    {
                                        tac.IntegrationInstanceMarketoID = strMarketoProgId;
                                        tac.LastSyncDate    = strMarketoLastSync; // Modified By Rahul shah // To add last sync date
                                        db.Entry(tac).State = EntityState.Modified;
                                    }
                                    else
                                    {
                                        _isResultError = true;
                                        _ErrorMessage  = "Error updating Marketo Program id for Tactic - " + tac.Title;
                                    }
                                    // Add By Nishant Sheth
                                    // Description :: #2134 Add Marketo Pushed Program url.
                                    strMarketoURL = marketoURL.Where(prg => prg.Key == tac.PlanTacticId).Select(prg => prg.Value).FirstOrDefault();
                                    if (!string.IsNullOrEmpty(strMarketoURL))
                                    {
                                        objEntityIntegrationAttr = ListEntityIntegrationAttr.Where(attr => attr.EntityId == tac.PlanTacticId).FirstOrDefault();
                                        if (objEntityIntegrationAttr == null)
                                        {
                                            objEntityIntegrationAttr                       = new EntityIntegration_Attribute();
                                            objEntityIntegrationAttr.EntityId              = tac.PlanTacticId;
                                            objEntityIntegrationAttr.EntityType            = Enums.EntityType.Tactic.ToString();
                                            objEntityIntegrationAttr.AttrType              = Enums.EntityIntegrationAttribute.MarketoUrl.ToString();
                                            objEntityIntegrationAttr.AttrValue             = strMarketoURL;
                                            objEntityIntegrationAttr.IntegrationinstanceId = _integrationInstanceId;
                                            objEntityIntegrationAttr.CreatedDate           = DateTime.Now;
                                            db.Entry(objEntityIntegrationAttr).State       = EntityState.Added;
                                        }
                                        else
                                        {
                                            objEntityIntegrationAttr.AttrValue       = strMarketoURL;
                                            db.Entry(objEntityIntegrationAttr).State = EntityState.Modified;
                                        }
                                    }
                                    if (((pushCntr + 1) % pushRecordBatchSize) == 0)
                                    {
                                        db.SaveChanges();
                                    }
                                    pushCntr++;
                                    // End By Nishant Sheth
                                }
                            }
                            finally
                            {
                                db.Configuration.AutoDetectChangesEnabled = true;
                            }
                        }
                        #endregion

                        db.SaveChanges();
                        #region "Create Tactic-Linked Tactic Mapping"
                        Dictionary <int, int> lstTacLinkIdMappings = new Dictionary <int, int>();
                        lstTacLinkIdMappings = tblTactics.Where(tac => lstSourceIds.Contains(tac.PlanTacticId) && tac.LinkedTacticId.HasValue).ToDictionary(tac => tac.PlanTacticId, tac => tac.LinkedTacticId.Value);
                        #endregion

                        UpdateLinkedTacticComment(lstSourceIds, tblTactics, lstCreatedTacIds, lstTacLinkIdMappings);
                    }
                }
                Common.SaveIntegrationInstanceLogDetails(_id, _integrationInstanceLogId, Enums.MessageOperation.End, currentMethodName, Enums.MessageLabel.Success, "SyncData method end.");
            }
            catch (Exception e)
            {
                string exMessage = Common.GetInnermostException(e);
                _isResultError = true;
                _ErrorMessage  = exMessage;
                Common.SaveIntegrationInstanceLogDetails(_id, _integrationInstanceLogId, Enums.MessageOperation.None, currentMethodName, Enums.MessageLabel.Error, "Error occurred while syncing Tactic :- " + exMessage);
            }

            if (_isResultError)
            {
                Common.UpdateIntegrationInstanceSection(_integrationInstanceSectionId, StatusResult.Error, _ErrorMessage);
            }
            else
            {
                Common.UpdateIntegrationInstanceSection(_integrationInstanceSectionId, StatusResult.Success, string.Empty);
            }


            lstSyncError.AddRange(_lstSyncError);
            return(_isResultError);
        }
Exemplo n.º 12
0
        [AuthorizeUser(Enums.ApplicationActivity.BoostImprovementTacticCreateEdit)]    // Added by Sohel Pathan on 19/06/2014 for PL ticket #537 to implement user permission Logic
        public ActionResult saveImprovementTacticData(int improvementId, string improvementDetails, bool status, double cost, string desc, string title, bool deployToIntegrationStatus, int UserId = 0)
        {
            string successMessage = string.Empty;
            string ErrorMessage   = string.Empty;

            string[] value = improvementDetails.Split(',');
            PlanExchangeRate = Sessions.PlanExchangeRate;
            try
            {
                /* if id !=0 then its update into db other wise add new record in db*/
                if (improvementId != 0)
                {
                    ImprovementTacticType objIt = GetImprovementTacticTypeRecordbyId(improvementId);                                                                                                                                                                                         //// Modified by :- Sohel Pathan on 20/05/2014 for PL #457 to delete a boost tactic.
                    var existTactic             = db.ImprovementTacticTypes.Where(_imprvTac => _imprvTac.ClientId == Sessions.User.CID && _imprvTac.Title.ToLower() == title.ToLower() && _imprvTac.ImprovementTacticTypeId != improvementId && _imprvTac.IsDeleted.Equals(false)).ToList(); //// Modified by :- Sohel Pathan on 20/05/2014 for PL #457 to delete a boost tactic.
                    if (existTactic.Count == 0)
                    {
                        /*edit new improvementTactic record*/
                        objIt.ImprovementTacticTypeId = improvementId;
                        objIt.Title                   = title;
                        objIt.Description             = desc;
                        objIt.Cost                    = objCurrency.SetValueByExchangeRate(cost, PlanExchangeRate); //Modified by Rahul Shah for PL #2501 to apply multi currency on boost screen
                        objIt.IsDeployed              = status;
                        objIt.IsDeployedToIntegration = deployToIntegrationStatus;
                        db.Entry(objIt).State         = EntityState.Modified;
                        int result = db.SaveChanges();
                        while (db.ImprovementTacticType_Metric.Where(itm => itm.ImprovementTacticTypeId == improvementId).Count() != 0)
                        {
                            /*remove old data based on improvementTacticId*/
                            ImprovementTacticType_Metric Itm = db.ImprovementTacticType_Metric.Where(itm => itm.ImprovementTacticTypeId == improvementId).FirstOrDefault();
                            db.Entry(Itm).State = EntityState.Deleted;
                            result = db.SaveChanges();
                        }
                        successMessage = string.Format(Common.objCached.EditImprovementTacticSaveSucess);
                    }
                    else
                    {
                        ErrorMessage = string.Format(Common.objCached.DuplicateImprovementTacticExits);
                        return(Json(new { errormsg = ErrorMessage }, JsonRequestBehavior.AllowGet));
                    }
                }
                else
                {
                    /*Add new improvementTactic record*/
                    ImprovementTacticType objIt = new ImprovementTacticType();
                    var existTactic             = db.ImprovementTacticTypes.Where(_imprvTac => _imprvTac.ClientId == Sessions.User.CID && _imprvTac.Title.ToLower() == title.ToLower() && _imprvTac.IsDeleted.Equals(false)).ToList(); //// Modified by :- Sohel Pathan on 20/05/2014 for PL #457 to delete a boost tactic.
                    if (existTactic.Count == 0)
                    {
                        objIt.Title       = title;
                        objIt.Description = desc;
                        objIt.Cost        = objCurrency.SetValueByExchangeRate(cost, PlanExchangeRate); //Modified by Rahul Shah for PL #2501 to apply multi currency on boost screen
                        objIt.IsDeployed  = status;
                        objIt.ClientId    = Sessions.User.CID;
                        objIt.CreatedBy   = Sessions.User.ID;
                        objIt.IsDeleted   = false;
                        objIt.CreatedDate = System.DateTime.Now;
                        int intRandomColorNumber = rnd.Next(Common.ColorcodeList.Count);
                        objIt.ColorCode = Convert.ToString(Common.ColorcodeList[intRandomColorNumber]);
                        objIt.IsDeployedToIntegration = deployToIntegrationStatus;
                        //  db.ImprovementTacticTypes.Attach(objIt);
                        db.Entry(objIt).State = EntityState.Added;
                        db.ImprovementTacticTypes.Add(objIt);
                        int result = db.SaveChanges();

                        improvementId  = objIt.ImprovementTacticTypeId;
                        successMessage = string.Format(Common.objCached.NewImprovementTacticSaveSucess);
                    }
                    else
                    {
                        ErrorMessage = string.Format(Common.objCached.DuplicateImprovementTacticExits);
                        return(Json(new { errormsg = ErrorMessage }, JsonRequestBehavior.AllowGet));
                    }
                }
                //Modified by Mitesh Vaishnav on 03/06/2014 for Customized Target stage - Boost Improvement Tactic
                /*add into improvementType_metric table based on improvementId*/
                improvementDetails = improvementDetails.Replace(@"\", "");
                var stageValueList = JsonConvert.DeserializeObject <List <StageDetails> >(improvementDetails);
                ImprovementTacticType_Metric objItm = null;
                int         MetricId = 0;
                double      Weight   = 0.0;
                MRPEntities dbAdd    = null;
                foreach (var item in stageValueList)
                {
                    objItm   = new ImprovementTacticType_Metric();
                    Weight   = 0.0;
                    MetricId = 0;
                    int.TryParse(item.StageId, out MetricId);
                    objItm.StageId = MetricId;
                    double.TryParse(item.Value, out Weight);
                    objItm.Weight = Weight;
                    objItm.ImprovementTacticTypeId = improvementId;
                    objItm.CreatedDate             = System.DateTime.Now;
                    objItm.CreatedBy = Sessions.User.ID;
                    objItm.StageType = item.StageType;
                    dbAdd            = new MRPEntities();
                    dbAdd.ImprovementTacticType_Metric.Attach(objItm);
                    dbAdd.Entry(objItm).State = EntityState.Added;
                    dbAdd.SaveChanges();
                    dbAdd.Dispose();
                }
                TempData["SuccessMessage"] = successMessage;
            }
            catch (Exception e)
            {
                ErrorSignal.FromCurrentContext().Raise(e);
                TempData["SuccessMessage"] = string.Empty;
                TempData["ErrorMessage"]   = e.InnerException.Message;
                return(Json(new { errormsg = e.InnerException.Message }, JsonRequestBehavior.AllowGet));
            }
            return(Json(new { redirect = Url.Action("Index") }));
        }