示例#1
0
 public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
 {
     try
     {
         //Apply logging
         var objChanges = HttpContext.Current.Items[ContactInfo.CONTACT_CHANGE] as List <ActivityObjectChangeInfo>;
         if (objChanges != null)
         {
             var activityInfo = new ActivityLogInfo
             {
                 FunctionId = 0,
                 CreatedBy  = UserContext.GetCurrentUser().UserID
             };
             activityInfo.Id = ActivityLogRepository.Create(activityInfo);
             foreach (var objChange in objChanges)
             {
                 objChange.ActivityId = activityInfo.Id;
                 ActivityObjectChangeRepository.Create(objChange);
             }
         }
         HttpContext.Current.Items[ContactInfo.CONTACT_CHANGE] = null;
     }
     catch
     {
         //Dont throw exception if loging failed
     }
     base.OnActionExecuted(actionExecutedContext);
 }
示例#2
0
 public static void LogException(Exception ex)
 {
     using (ActivityLogRepository _logger = new ActivityLogRepository(new ApplicationDbContext()))
     {
         _logger.LogException(ex);
     }
 }
示例#3
0
 public DashboardController()
 {
     _activityLogRepository = new ActivityLogRepository();
     _userRepository        = new UserRepository();
     _orderRepository       = new OrderRepository();
     _productRepository     = new ProductRepository();
     _suppliersRepository   = new SupplierRepository();
 }
示例#4
0
        /// <summary>
        /// get List of Entries of One  Activity Type(Create/Edit)  and Save them in Hisory and ActivityLog Tables
        /// </summary>
        /// <param name="NTUser"></param>
        /// <param name="addedEntries"></param>
        /// <param name="ActivityType"></param>
        /// <returns></returns>
        private async Task SaveToLogByActivityType(int NTUser, List <DbEntityEntry> Entries, ActivityType Activity, bool isSystem = false, IDictionary <string, string> Fields = null, List <History> HistoriesList = null)
        {
            if (Entries == null || Entries.Count() <= 0)
            {
                return;
            }

            try
            {
                ActivityLog activityLog = new ActivityLog(NTUser, Activity);
                using (IActivityLogRepository db = new ActivityLogRepository())
                {
                    db.Add(activityLog);
                    await db.SaveChangesAsync();
                }

                if (HistoriesList == null)
                {
                    GetHistoryFields GetHistoryFields;
                    //if Create only get current all fields to history else get oly Updated fields in entry
                    if (Activity == ActivityType.Create)
                    {
                        GetHistoryFields = GetFields;
                    }
                    else
                    {
                        GetHistoryFields = GetUpdatedFields;
                    }
                    HistoriesList = new List <History>();
                    foreach (var item in Entries)
                    {
                        HistoriesList.AddRange(GetHistoryList(item, GetHistoryFields, activityLog.ActivityLogID, Fields));
                    }
                    // Entries.ForEach(e =>
                }
                else
                {
                    HistoriesList.ForEach(h => h.ActivityLogID = activityLog.ActivityLogID);
                }

                if (HistoriesList != null && HistoriesList.Count() > 0)
                {
                    using (PREPContext db = new PREPContext())
                    {
                        using (var transactionScope = new TransactionScope())
                        {
                            db.BulkInsert(HistoriesList);
                            db.SaveChanges();
                            transactionScope.Complete();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Errors.Write(ex.Message);
            }
        }
示例#5
0
        public void LogError_should_add_message_for_job()
        {
            using (_db.CreateTransaction())
            {
                var logger = new ActivityLogRepository();
                logger.LogError(new JobItem(), new Exception());

                using (var ctx = _db.CreateDbContext())
                {
                    var numberOfMessages = ctx.ActivityMessages.Count();
                    Assert.Equal(1, numberOfMessages);
                }
            }
        }
示例#6
0
        public void DataStored_should_add_message()
        {
            using (_db.CreateTransaction())
            {
                var logger = new ActivityLogRepository();
                logger.DataStored(new JobItem());

                using (var ctx = _db.CreateDbContext())
                {
                    var numberOfMessages = ctx.ActivityMessages.Count();
                    Assert.Equal(1, numberOfMessages);
                }
            }
        }
示例#7
0
        public void UrlDownloaded_should_add_message()
        {
            using (_db.CreateTransaction())
            {
                var logger = new ActivityLogRepository();
                logger.UrlDownloaded("URL");

                using (var ctx = _db.CreateDbContext())
                {
                    var numberOfMessages = ctx.ActivityMessages.Count();
                    Assert.Equal(1, numberOfMessages);
                }
            }
        }
        public HttpResponseMessage Get(string id)
        {
            try
            {
                ActivityLogModel    model    = new ActivityLogRepository().GetActivityLogs(id);
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, model);

                return(response);
            }
            catch (Exception ex)
            {
                _tracer.Error(Request, this.ControllerContext.ControllerDescriptor.ControllerType.FullName, ex.StackTrace);
                return(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(ex.Message)
                });
            }
        }
示例#9
0
        public void saveLog(ActivityLog data)
        {
            try
            {
                _uow.OpenConnection(_uow.GetAppSettings("MongoDBConnectionString"), _uow.GetAppSettings("TableName"));

                var repo = new ActivityLogRepository(_uow);

                _uow.BeginTransaction();

                repo.AddAsync(data).Wait();

                _uow.CommitTransaction();
            }
            catch (Exception ex)
            {
                _uow.RollbackTransaction();
                throw;
            }
        }
 public ActivityLogService(ActivityLogRepository logRepo, ILog log)
 {
     this.logRepo = logRepo;
     this.log     = log;
 }
示例#11
0
        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);

            try
            {
                var userCurent = UserContext.GetCurrentUser();
                if (userCurent != null)
                {
                    ViewBag.GroupId      = userCurent.GroupId;
                    ViewBag.GroupType    = userCurent.GroupConsultantType;
                    ViewBag.UserBranches = UserRepository.GetBranchOfUser(userCurent.UserID);
                }

                //Gói niêm yết
                ViewBag.PackagePriceListed = CatalogRepository.GetAll <PackagePriceListed>();

                // GroupType
                var wbServiceConfigTypes = new Dictionary <int, string>();
                foreach (var item in Enum.GetValues(typeof(WebServiceConfigType)))
                {
                    wbServiceConfigTypes.Add((int)item, ObjectExtensions.GetEnumDescription((WebServiceConfigType)item));
                }
                ViewBag.WebServiceConfigTypes = wbServiceConfigTypes.Select(c => new { Id = c.Key, Name = c.Value });

                // GroupType
                var groupTypes = new Dictionary <int, string>();
                foreach (var item in Enum.GetValues(typeof(GroupConsultantType)))
                {
                    groupTypes.Add((int)item, ObjectExtensions.GetEnumDescription((GroupConsultantType)item));
                }
                ViewBag.GroupTypes = groupTypes.Select(c => new { Id = c.Key, Name = c.Value });

                //Branches
                filterContext.Controller.ViewBag.BranchId = UserContext.GetDefaultBranch();

                //UserId
                filterContext.Controller.ViewBag.UserId = UserContext.GetCurrentUser().UserID;

                // Group
                StoreData.ListGroup.RemoveAll(c => c.GroupId == 0);
                filterContext.Controller.ViewBag.Groups = StoreData.ListGroup;

                // User
                StoreData.ListUser.RemoveAll(c => c.UserID == 0);
                filterContext.Controller.ViewBag.Users = StoreData.ListUser;

                // Level
                filterContext.Controller.ViewBag.Levels = StoreData.ListLevel;

                // Branch
                filterContext.Controller.ViewBag.Branches = StoreData.ListBranch;

                //Collectors
                filterContext.Controller.ViewBag.Collectors = StoreData.ListCollector;

                //StatusMap
                filterContext.Controller.ViewBag.StatusMaps = StoreData.ListStatusMap ?? new List <StatusMapInfo>();

                //StatusCare
                filterContext.Controller.ViewBag.StatusCares = StoreData.ListStatusCare ?? new List <StatusCareInfo>();

                // SourceType
                filterContext.Controller.ViewBag.SourceTypes = StoreData.ListSourceType ?? new List <SourceTypeInfo>();

                //Email
                filterContext.Controller.ViewBag.Email = StoreData.ListEmail ?? new List <EmailInfo>();

                //EducationLevel
                filterContext.Controller.ViewBag.EducationLevels = StoreData.ListEducationLevel ?? new List <EducationLevelInfo>();

                //TimeSlot
                filterContext.Controller.ViewBag.TimeSlots = StoreData.ListTimeSlot ?? new List <TimeSlotInfo>();

                //TeacherType
                filterContext.Controller.ViewBag.TeacherTypes = StoreData.ListTeacherType ?? new List <TeacherTypeInfo>();

                // Container
                filterContext.Controller.ViewBag.Containers = StoreData.ListContainer ?? new List <ContainerInfo>();

                //Import Excels
                filterContext.Controller.ViewBag.ImportExcels = StoreData.ListImportExcel ?? new List <ImportExcelInfo>();

                // WebServiceConfig
                StoreData.ListWebServiceConfig.RemoveAll(c => c.Id == 0);

                // StatusConnectType
                var statusConnectType = new Dictionary <int, string>();
                foreach (var item in Enum.GetValues(typeof(StatusConnectType)))
                {
                    statusConnectType.Add((int)item, ObjectExtensions.GetEnumDescription((StatusConnectType)item));
                }
                ViewBag.StatusConnectTypes = statusConnectType.Select(c => new { Id = c.Key, Name = c.Value });

                // Product
                //if (StoreData.ListProduct.IsNullOrEmpty())
                //{
                //    StoreData.ListProduct = ProductRepository.GetAll() ?? new List<ProductInfo>();
                //}
                filterContext.Controller.ViewBag.Products = StoreData.ListProduct ?? new List <ProductInfo>();

                // Quality
                //if (StoreData.ListQuality.IsNullOrEmpty())
                //{
                //    StoreData.ListQuality = QualityRepository.GetAll() ?? new List<QualityInfo>();
                //}
                filterContext.Controller.ViewBag.Quality = StoreData.ListQuality ?? new List <QualityInfo>();

                // FeeMoneyType
                filterContext.Controller.ViewBag.FeeMoneyType = StoreData.ListFeeMoneyType;

                // PackageFeeEdu
                filterContext.Controller.ViewBag.PackageFeeEdu = StoreData.ListPackageFeeEdu;
            }
            catch (Exception ex)
            {
            }

            try
            {
                //Apply logging
                var objChanges = HttpContext.Items[ContactInfo.CONTACT_CHANGE] as List <ActivityObjectChangeInfo>;
                if (objChanges != null)
                {
                    var activityInfo = new ActivityLogInfo
                    {
                        FunctionId = 0,
                        CreatedBy  = UserContext.GetCurrentUser().UserID
                    };
                    activityInfo.Id = ActivityLogRepository.Create(activityInfo);
                    foreach (var objChange in objChanges)
                    {
                        objChange.ActivityId = activityInfo.Id;
                        ActivityObjectChangeRepository.Create(objChange);
                    }
                }
                HttpContext.Items[ContactInfo.CONTACT_CHANGE] = null;
            }
            catch
            {
                //Dont throw exception if loging failed
            }
        }
 public ActivityLogService(ActivityLogRepository logRepo, ILog log)
 {
     this.logRepo = logRepo;
     this.log = log;
 }
示例#13
0
        private void DoImport(string file)
        {
            try
            {
                //Create activity log
                var activity = new ActivityLogInfo
                {
                    CreatedDate  = DateTime.Now,
                    CreatedBy    = ImportInfo.UserId,
                    FunctionId   = (int)LogFunctionType.ImportExcel,
                    FunctionType = (int)LogFunctionType.ImportExcel,
                };
                activity.Id = ActivityLogRepository.Create(activity);

                //End log
                using (var connection = new SqlConnection(ImportConfig.ConnectionString))
                {
                    connection.Open();

                    SqlTransaction transaction = null;
                    try
                    {
                        transaction = connection.BeginTransaction();
                        // Use one transaction to put all the data in the database
                        var watch = new Stopwatch();
                        watch.Start();
                        var contactIdentity          = GetIdentity("Contacts", connection, transaction);
                        var contactDuplicateIdentity = GetIdentity("ContactDuplicates", connection, transaction);
                        using (var stream = File.Open(file, FileMode.Open, FileAccess.Read))
                        {
                            using (var dr = ExcelReaderFactory.CreateOpenXmlReader(stream))
                            {
                                //Log bat dau tu
                                var rowIndex = 0;
                                while (dr.Read())
                                {
                                    if (rowIndex >= 1)
                                    {
                                        #region Read excel row
                                        var name   = dr[1] == null ? string.Empty : dr[1].ToString().Trim();
                                        var email  = dr[2] == null ? string.Empty : dr[2].ToString().Trim().ToLower();
                                        var mobile = dr[3] == null
                                            ? string.Empty
                                            : Util.CleanAlphabetAndFirstZero(dr[3].ToString().Trim());
                                        var      address = dr[4] == null ? string.Empty : dr[4].ToString().Trim();
                                        DateTime?registeredDate;
                                        if (dr[5] == null)
                                        {
                                            registeredDate = null;
                                        }
                                        else
                                        {
                                            try
                                            {
                                                registeredDate = (DateTime)dr[5];
                                            }
                                            catch
                                            {
                                                registeredDate = dr[5].ToDateTime();
                                            }
                                        }
                                        var campaindTpe   = dr[6] == null ? string.Empty : dr[6].ToString().Trim();
                                        var campaindTpeId = StaticData.GetCampaindTpeId(campaindTpe);

                                        var landingPage   = dr[7] == null ? string.Empty : dr[7].ToString().Trim();
                                        var landingPageId = StaticData.GetLandingPageId(landingPage);

                                        var channel   = dr[8] == null ? string.Empty : dr[8].ToString().Trim();
                                        var channelId = StaticData.GetChannelId(channel, ImportInfo.TypeId, ImportInfo.ChannelId);

                                        var templateAds   = dr[9] == null ? string.Empty : dr[9].ToString().Trim();
                                        var templateAdsId = StaticData.GetTemplateAdsId(templateAds);

                                        var searchKeyword   = dr[10] == null ? string.Empty : dr[10].ToString().Trim();
                                        var searchKeywordId = StaticData.GetTemplateAdsId(searchKeyword);

                                        var package   = dr[11] == null ? string.Empty : dr[11].ToString().Trim();
                                        var packageId = StaticData.GetTemplateAdsId(package);

                                        var code = dr[12] == null ? string.Empty : dr[12].ToString().Trim();

                                        var contactIdDb      = 0;
                                        var contactTmpStatus = 0;
                                        var contactInfoDb    = string.Empty;
                                        #endregion

                                        #region validate row
                                        if (string.IsNullOrEmpty(name) && string.IsNullOrEmpty(mobile) && string.IsNullOrEmpty(email))
                                        {
                                            continue;
                                        }
                                        ImportInfo.RowIndex++;
                                        ImportInfo.TotalRow++;

                                        //Contact validation
                                        var error = Validate(mobile, string.Empty, string.Empty, email);

                                        // haihm
                                        if (error == ContactError.EmailFormat)
                                        {
                                            email = null;
                                            error = ContactError.None;
                                        }
                                        if (error != ContactError.None)
                                        {
                                            ImportInfo.ErrorCount++;
                                            contactTmpStatus = (int)error;
                                        }
                                        else
                                        {
                                            //Check if contact is internal duplicate or not
                                            if (IsInternalDuplicate(mobile, string.Empty, string.Empty, email))
                                            {
                                                contactTmpStatus = (int)ContactError.InternalDuplicate;
                                                ImportInfo.InternalDuplicateCount++;
                                                Console.WriteLine("Duplicated in INTERNAL FILE with Mobile: " + mobile + "; \tEmail: " + email + "; \t\t\t\tImportId: " + ImportInfo.ImportId + "; \tImportDate:" + ImportInfo.ImportedDate + "; \tUserImportId:" + ImportInfo.UserId);
                                            }
                                            else
                                            {
                                                //If not internal duplicate, add to hashtable data
                                                //int check_db_idcts;
                                                if (!string.IsNullOrEmpty(email))
                                                {
                                                    internalPhoneAndEmails.Add(email);
                                                }
                                                if (!string.IsNullOrEmpty(mobile))
                                                {
                                                    internalPhoneAndEmails.Add(mobile);
                                                }
                                                //int check_dulicated;
                                                var check = CheckDuplicateProvider.Instance().IsDuplicate(mobile, string.Empty, string.Empty, email, string.Empty, out contactIdDb, out contactInfoDb);

                                                //check_db_idcts = ContactRepository.ContactIsDuplicate(mobile, string.Empty, string.Empty, email, string.Empty);
                                                //if (check_db_idcts != 0)
                                                //{
                                                //    check = true;
                                                //}
                                                //if (!check)
                                                //{
                                                //    check_dulicated = ContactRepository.ContactIsDuplicate(mobile, string.Empty, string.Empty, email, string.Empty);
                                                //    if (check_dulicated != 0) check = true;
                                                //}
                                                if (check)
                                                {
                                                    ImportInfo.DuplicateCount++;
                                                    contactTmpStatus = (int)ContactError.Duplicate;
                                                    Console.WriteLine("Duplicated in REDIS CACHE with Mobile: " + mobile + "; \tEmail: " + email + "; \t\t\t\tImportId: " + ImportInfo.ImportId + "; \tImportDate:" + ImportInfo.ImportedDate + "; \tUserImportId:" + ImportInfo.UserId);
                                                }
                                            }
                                        }
                                        ImportInfo.CheckCount++;
                                        #endregion

                                        switch (contactTmpStatus)
                                        {
                                        case (int)ContactError.None:
                                        {
                                            #region create contact row
//
                                            string sTypeId = "01";         //Nguon contact: MO, CC ... 01 la MO

                                            if (ImportInfo.TypeId == 3)
                                            {
                                                sTypeId = "02";
                                            }
                                            else if (ImportInfo.TypeId == 4)
                                            {
                                                sTypeId = "01";
                                            }
                                            else if (ImportInfo.TypeId == 5)
                                            {
                                                sTypeId = "03";
                                            }
                                            else if (ImportInfo.TypeId == 6)
                                            {
                                                sTypeId = "04";
                                            }

                                            else if (ImportInfo.TypeId == 8)
                                            {
                                                sTypeId = "05";
                                            }
                                            else if (ImportInfo.TypeId == 9)
                                            {
                                                sTypeId = "06";
                                            }
                                            else if (ImportInfo.TypeId == 10)
                                            {
                                                sTypeId = "07";
                                            }
                                            else if (ImportInfo.TypeId == 11)
                                            {
                                                sTypeId = "08";
                                            }
                                            else
                                            {
                                                sTypeId = "09";
                                            }


                                            var contactId = contactIdentity + rowIndex;
                                            var sCode     = DateTime.Now.ToString("yyyyMMdd") + sTypeId + contactId.ToString();

                                            var contactRow = dtContacts.NewRow();
                                            contactRow["Gender"]        = 0;
                                            contactRow["Email"]         = email;
                                            contactRow["Id"]            = contactId;
                                            contactRow["Address"]       = address;
                                            contactRow["Fullname"]      = name;
                                            contactRow["ChannelId"]     = channelId;
                                            contactRow["PackageId"]     = packageId;
                                            contactRow["CreatedDate"]   = DateTime.Now;
                                            contactRow["TypeId"]        = ImportInfo.TypeId;
                                            contactRow["LevelId"]       = ImportInfo.LevelId;
                                            contactRow["CampaindTpeId"] = campaindTpeId;
                                            contactRow["LandingPageId"] = landingPageId;
                                            contactRow["TemplateAdsId"] = templateAdsId;
                                            contactRow["BranchId"]      = ImportInfo.BranchId;
                                            contactRow["ImportId"]      = ImportInfo.ImportId;
                                            contactRow["StatusId"]      = ImportInfo.Status;    //(int)StatusType.New;
                                            // HungNV: 18/05/2020 Trường hợp kho 1-6 cần điều kiện container để phân biệt lúc thu hồi
                                            contactRow["ContainerId"]     = ImportInfo.Status;
                                            contactRow["RegisteredDate"]  = registeredDate;
                                            contactRow["UserImportId"]    = ImportInfo.UserId;
                                            contactRow["SearchKeywordId"] = searchKeywordId;
                                            contactRow["ImportedDate"]    = ImportInfo.ImportedDate;
                                            contactRow["Code"]            = code.IsStringNullOrEmpty() ? sCode : code;
                                            dtContacts.Rows.Add(contactRow);

                                            #endregion

                                            #region create phone row
                                            if (!string.IsNullOrEmpty(mobile))
                                            {
                                                var phoneRow = dtPhones.NewRow();
                                                phoneRow["ContactId"]   = contactId;
                                                phoneRow["PhoneType"]   = (int)PhoneType.HomePhone;
                                                phoneRow["PhoneNumber"] = mobile;
                                                phoneRow["IsPrimary"]   = 1;
                                                dtPhones.Rows.Add(phoneRow);
                                            }
                                            #endregion

                                            #region create contact level row
                                            var contactLelveRow = dtContactLevels.NewRow();
                                            contactLelveRow["ContactId"] = contactId;
                                            dtContactLevels.Rows.Add(contactLelveRow);
                                            #endregion

                                            #region create object changes
                                            foreach (DataColumn col in dtContacts.Columns)
                                            {
                                                if (col.ColumnName != "TypeId" &&
                                                    col.ColumnName != "LevelId" &&
                                                    col.ColumnName != "StatusId" &&
                                                    col.ColumnName != "ChannelId" &&
                                                    col.ColumnName != "BranchId")
                                                {
                                                    continue;
                                                }
                                                var objChange = dtObjectChanges.NewRow();
                                                objChange["ActivityId"] = activity.Id;
                                                objChange["ObjectType"] = (int)LogObjectType.Contact;
                                                objChange["ObjectId"]   = contactId;
                                                var      propertyType          = 0;
                                                int?     propertyValueInt      = null;
                                                string   propertyValueString   = null;
                                                DateTime?propertyValueDateTime = null;
                                                switch (col.ColumnName)
                                                {
                                                case "BranchId":
                                                    propertyType     = (int)LogPropertyType.Contacts_Branch;
                                                    propertyValueInt = ImportInfo.BranchId;
                                                    break;

                                                case "TypeId":
                                                    propertyType     = (int)LogPropertyType.Contacts_Type;
                                                    propertyValueInt = ImportInfo.TypeId;
                                                    break;

                                                case "LevelId":
                                                    propertyType     = (int)LogPropertyType.Contacts_Level;
                                                    propertyValueInt = ImportInfo.LevelId;
                                                    break;

                                                case "StatusId":
                                                    propertyType     = (int)LogPropertyType.Contacts_Status;
                                                    propertyValueInt = ImportInfo.Status;
                                                    break;

                                                case "ChannelId":
                                                    propertyType     = (int)LogPropertyType.Contacts_Channel;
                                                    propertyValueInt = channelId;
                                                    break;
                                                }
                                                objChange["PropertyType"]          = propertyType;
                                                objChange["PropertyValueInt"]      = propertyValueInt;
                                                objChange["PropertyValueString"]   = propertyValueString;
                                                objChange["PropertyValueDateTime"] = propertyValueDateTime;
                                                objChange["ChangedDate"]           = DateTime.Now;
                                                dtObjectChanges.Rows.Add(objChange);
                                            }

                                            //Them Mobile vs Email cua moi contact vao cache Redis

                                            //CachingProvider.Instance().Set(mobile, contactId.ToString());
                                            //CachingProvider.Instance().Set(email, contactId.ToString());

                                            //list_phone_email_redis.Add(Constant.NameSystem + mobile, contactId.ToString());
                                            //list_phone_email_redis.Add(Constant.NameSystem + email, contactId.ToString());
                                            #endregion

                                            //Nếu import vào kho MOL thì save log vào bảng LogContainerMOL
                                            #region create log contact kho MOL
                                            if (ImportInfo.Status == (int)StatusType.ContainerMOL)
                                            {
                                                var logContainerMOL = dtLogContainerMOL.NewRow();

                                                logContainerMOL["CreatedDate"]         = DateTime.Now;
                                                logContainerMOL["StatusContainerType"] = (int)StatusContainerTypeMOL.ImportContainer;
                                                logContainerMOL["StatusAddContact"]    = (int)StatusAddContact.ImportContact;
                                                logContainerMOL["StatusContactFirst"]  = ImportInfo.Status;
                                                logContainerMOL["StatusContactAfter"]  = null;
                                                logContainerMOL["ContactId"]           = contactId;
                                                logContainerMOL["ChannelId"]           = channelId;

                                                dtLogContainerMOL.Rows.Add(logContainerMOL);
                                            }
                                            #endregion
                                        }
                                        break;

                                        case (int)ContactError.Duplicate:
                                        {
                                            #region create contact duplicate
                                            var sourceTypes = StaticData.GetSourceTypeCheckDuplicate();
                                            if (!sourceTypes.IsNullOrEmpty() && sourceTypes.Any(c => c.SourceTypeId == ImportInfo.TypeId))
                                            {
                                                var contactDuplicateRow = dtContactDuplicate.NewRow();
                                                var contact             = ContactRepository.GetInfo(contactIdDb);
                                                //update chuyen trang thai contact neu trung chuyen sang kho trung
                                                ContactRepository.UpdateChangeStatusId(contactIdDb);
                                                int idContactDuplicate = contactDuplicateIdentity + rowIndex;

                                                contactDuplicateRow["Id"]                = idContactDuplicate;
                                                contactDuplicateRow["ContactId"]         = contactIdDb;
                                                contactDuplicateRow["SourceTypeId"]      = ImportInfo.TypeId;
                                                contactDuplicateRow["Status"]            = contact != null ? contact.StatusId: 0;
                                                contactDuplicateRow["ImportId"]          = ImportInfo.ImportId;
                                                contactDuplicateRow["DuplicateInfo"]     = contactInfoDb;
                                                contactDuplicateRow["CreatedDate"]       = DateTime.Now;
                                                contactDuplicateRow["IsNotyfiDuplicate"] = true;

                                                dtContactDuplicate.Rows.Add(contactDuplicateRow);
                                            }
                                            #endregion
                                        }
                                        break;

                                        default:
                                        {
                                            #region create contact temp errors
                                            var contactRow = dtContactTmps.NewRow();
                                            var contactId  = contactIdentity + rowIndex;
                                            contactRow["Gender"]        = 0;
                                            contactRow["Email"]         = email;
                                            contactRow["Id"]            = contactId;
                                            contactRow["Fullname"]      = name;
                                            contactRow["Mobile1"]       = mobile;
                                            contactRow["Address"]       = address;
                                            contactRow["ChannelId"]     = channelId;
                                            contactRow["PackageId"]     = packageId;
                                            contactRow["CreatedDate"]   = DateTime.Now;
                                            contactRow["TypeId"]        = ImportInfo.TypeId;
                                            contactRow["LevelId"]       = ImportInfo.LevelId;
                                            contactRow["CampaindTpeId"] = campaindTpeId;
                                            contactRow["LandingPageId"] = landingPageId;
                                            contactRow["TemplateAdsId"] = templateAdsId;
                                            contactRow["BranchId"]      = ImportInfo.BranchId;
                                            contactRow["ImportId"]      = ImportInfo.ImportId;
                                            contactRow["StatusId"]      = (int)StatusType.New;
                                            // HungNV: 18/05/2020 Trường hợp kho 1-6 cần điều kiện container để phân biệt lúc thu hồi
                                            contactRow["ContainerId"]     = ImportInfo.Status;
                                            contactRow["RegisteredDate"]  = registeredDate;
                                            contactRow["UserImportId"]    = ImportInfo.UserId;
                                            contactRow["SearchKeywordId"] = searchKeywordId;
                                            contactRow["ImportedDate"]    = ImportInfo.ImportedDate;
                                            contactRow["Code"]            = code.IsStringNullOrEmpty() ? "TPE_" + contactId : code;
                                            dtContactTmps.Rows.Add(contactRow);
                                            #endregion
                                        }
                                        break;
                                        }
                                    }
                                    rowIndex++;
                                }
                            }
                        }

                        watch.Stop();
                        Console.WriteLine("");
                        Console.WriteLine("Thoi gian read file: " + watch.ElapsedMilliseconds);
                        watch.Reset();
                        watch.Restart();

                        dtPhones = RemoveDuplicateRows(dtPhones, "PhoneNumber");
                        // Import
                        ContactBulkImport.ImportContactPhone(dtPhones, connection, transaction);
                        ContactBulkImport.ImportContact(dtContacts, connection, transaction);
                        ContactBulkImport.ImportContactLevel(dtContactLevels, connection, transaction);
                        ContactBulkImport.ImportObjectChanges(dtObjectChanges, connection, transaction);
                        ContactBulkImport.ImportContactTmp(dtContactTmps);
                        ContactBulkImport.ImportContactDuplicate(dtContactDuplicate, connection, transaction);
                        //Log table LogContainerMOL phuc vu bao cao xuat nhap kho MOL
                        ContactBulkImport.ImportLogContainerMOL(dtLogContainerMOL, connection, transaction);

                        watch.Stop();
                        Console.WriteLine("Thoi gian Import file: " + watch.ElapsedMilliseconds);

                        Console.WriteLine("Bat dau commit");
                        transaction.Commit();
                        Console.WriteLine("Commit thanh cong");
                        ImportInfo.ImportStatus = 1;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        if (transaction != null)
                        {
                            Console.WriteLine("Commit ko thanh cong. Dang rollback lai");
                            ImportInfo.ImportStatus = 2;
                            transaction.Rollback(); // This will not reset IDENT_CURRENT
                        }
                    }
                    finally
                    {
                        // Update Duplicate
                        Console.WriteLine("Bat dau vao finally.");
                        UpdateDuplicate();
                        //ImportInfo.ImportStatus = 1;
                        ImportExcelRepository.Update(ImportInfo);

                        // Load redis
                        if (ImportInfo.ImportStatus == 1)
                        {
                            Console.WriteLine("Update xong trang thai ImportExcel. Bat dau load Redis.");
                            StaticData.LoadToRedis();
                            Console.WriteLine("Load xong redis");
                        }
                    }
                }

                dtPhones        = null;
                dtContacts      = null;
                dtContactTmps   = null;
                dtContactLevels = null;
                dtObjectChanges = null;
            }
            catch (Exception ex2)
            {
                Console.WriteLine(ex2.ToString());
            }
        }
示例#14
0
 public ActivityLogController()
 {
     _activityLogRepository = new ActivityLogRepository();
 }