示例#1
0
 public ImportingJobDescriptor(bool isSudo, IFeatureInfo feature, AbstractFileDataSourceDefinition ds, ImportEntity importEntity)
 {
     this.IsSudo       = isSudo;
     this.Feature      = feature;
     this.DataSource   = ds;
     this.ImportEntity = importEntity;
 }
示例#2
0
        public async Task AddOrUpdateWithNotification(ImportEntity entityFromDb, ImportEntity entityFromImport)
        {
            if (entityFromDb != null)
            {
                _movieDbMapper.MapFromImportToDb(entityFromDb, entityFromImport);
                entityFromDb.UpdateAuditValuesForUpdatedEntity(_systemGuid);
                _tvSeriesContext.Update(entityFromDb);
                await _tvSeriesContext.SaveChangesAsync();

                _logger.LogInformation($"Update {entityFromDb.GetType()} with id {entityFromDb.Id}");
            }
            else
            {
                entityFromImport.UpdateAuditValuesForNewEntity(_systemGuid);
                entityFromImport.EnableImport();
                // TODO AddOrUpdateSeason
                // await _notificationService.CreateSeriesNotificationsForUsers(seasonFromImport);
                // TODO AddOrUpdateCharacter
                //await _notificationService.CreatePersonNotificationsForUsers(characterFromImport);
                await _tvSeriesContext.AddAsync(entityFromImport);

                await _tvSeriesContext.SaveChangesAsync();

                _logger.LogInformation($"Added {entityFromImport.GetType()} with id {entityFromImport.Id}");
            }
        }
        private void UpdateBrands(ImportEntity importEntity)
        {
            var brand = _productService.GetProductBySku(importEntity.BrandSku);

            if (brand == null)
            {
                brand = CreateGroupedProduct(importEntity.BrandSku, importEntity.BrandName);
                _productService.InsertProduct(brand);

                _urlRecordService.SaveSlug(brand, brand.ValidateSeName(brand.Name, brand.Name, true), 0);

                var validateName = brand.ValidateSeName(brand.Name, brand.Name, true);
                UpdateSlug(validateName, brand);

                CreateProductCategoryMapping(brand.Sku, importEntity.CategoryId);
            }
            else
            {
                //TODO:проверка на изменения данных
                brand.Name                = importEntity.BrandName;
                brand.ProductType         = ProductType.GroupedProduct;
                brand.VisibleIndividually = true;
                brand.ProductTemplateId   = 2;
                brand.Published           = false;
                brand.UpdatedOnUtc        = DateTime.UtcNow;
                _productService.UpdateProduct(brand);
            }
        }
        private void UpdateModels(ImportEntity importEntity)
        {
            //проверка сущестования модели
            var model         = _productService.GetProductBySku(importEntity.ModelSku);
            var parentProduct = _productService.GetProductBySku(importEntity.BrandSku);

            if (model == null)
            {
                model = CreateGroupedProduct(importEntity.ModelSku, importEntity.ModelName);
                model.ParentGroupedProductId = parentProduct.Id;
                _productService.InsertProduct(model);

                var validateName = model.ValidateSeName(model.Name, model.Name, true);
                UpdateSlug(validateName, model);

                CreateProductCategoryMapping(model.Sku, importEntity.CategoryId);
            }
            else
            {
                model.Name = importEntity.ModelName;
                model.ParentGroupedProductId = parentProduct.Id;
                model.UpdatedOnUtc           = DateTime.UtcNow;
                model.ProductType            = ProductType.GroupedProduct;
                model.VisibleIndividually    = true;
                model.Published         = false;
                model.ProductTemplateId = 2;
                _productService.UpdateProduct(model);
            }
        }
示例#5
0
        private static void DoImportEntity(ImportEntity importEntity)
        {
            try
            {
                Console.WriteLine(importEntity.TableName + " - download started");
                Directory.CreateDirectory(importEntity.TempFolderName);
                DownloadFile(importEntity.FileURL, importEntity.ArchiveFilePath);
                Console.WriteLine(importEntity.TableName + " - downloaded");

                if (importEntity.IsZIPed)
                {
                    ExtractFile(importEntity);
                    Console.WriteLine(importEntity.TableName + " - file was uziped");
                }

                ShrinkDB();
                ClearTable(importEntity.TableName);
                Console.WriteLine(importEntity.TableName + " - table cleared");

                ShrinkDB();
                BulkImport(importEntity);
                ClearAfterBulkInsert(importEntity);
                ShrinkDB();
            }
            catch (Exception exception)
            {
                WriteError(importEntity.FileURL + " - " + exception.Message);
            }
        }
        private async void PerformImportAsync(string id, ImportEntity jobEntity, IProgress <ImportProgress> progress)
        {
            var task = new Task(() => _importService.RunImportJob(jobEntity.ImportJob.ImportJobId, jobEntity.SourceFile));

            task.Start();

            if (progress != null)
            {
                var finished = false;
                while (!finished)
                {
                    await Task.Delay(TimeSpan.FromMilliseconds(100));

                    var res = _importService.GetImportResult(jobEntity.ImportJob.ImportJobId);
                    progress.Report(new ImportProgress
                    {
                        ImportEntity = jobEntity,
                        ImportResult = res,
                        StatusId     = id,
                        Processed    = res == null ? 0 : res.ProcessedRecordsCount + res.ErrorsCount
                    });

                    if (res != null && res.IsFinished)
                    {
                        finished = true;
                    }
                }
            }
        }
示例#7
0
        private static void BulkImport(ImportEntity importEntity)
        {
            Console.WriteLine(importEntity.TableName + " - import started");

            string logFile = importEntity.DataFilePath + ".log";

            string sqlCommand = $@"
BULK INSERT [gno].[{importEntity.TableName}]  
FROM '{importEntity.DataFilePath}'  
WITH
(
    KEEPNULLS
   ,ERRORFILE = '{logFile}'
   ,FIRSTROW = {importEntity.FirstRow}
   ,FIELDTERMINATOR = '\t'
   ,CODEPAGE = '65001'
   ,ROWTERMINATOR = '0x0a'
);
";

            using (var connection = new SqlConnection(_connectionString))
            {
                connection.Open();

                using (var command = new SqlCommand(sqlCommand, connection))
                {
                    command.CommandTimeout = int.MaxValue;
                    command.ExecuteNonQuery();
                }

                connection.Close();
            }

            Console.WriteLine(importEntity.TableName + " - was imported");
        }
示例#8
0
        // TODO: check another solution
        public Entity ProcessEntity(ImportEntity entity)
        {
            logger.InfoFormat("Import of {0} record with {1} is started", entity.GetType().Name, entity.MainFieldsMessage);
            var result = Import((TImportEntity)entity);

            logger.InfoFormat("Import of {0} record with {1} is finished", entity.GetType().Name, entity.MainFieldsMessage);
            return(result);
        }
        protected void ApplyColumns(ImportParameters importParameters, ColumnScores columnScores)
        {
            importParameters.Columns             = columnScores.Columns;
            importParameters.HeaderColumnsValues = columnScores.HeaderColumnValues;
            ImportEntity entity = importParameters.Entities.First();

            entity.ColumnValues = columnScores.EntityColumns;
        }
 private ImportEntity Map(tblProduct item)
 {
     var result = new ImportEntity {MasterDataCollective = MasterDataCollective.SaleProduct.ToString()};
     result.Fields[0] =string.IsNullOrEmpty(item.ProductCode)?"":item.ProductCode.Trim();
     result.Fields[1] = string.IsNullOrEmpty(item.Description) ? "" : item.Description.Trim(); 
     result.Fields[2] = item.ExFactoryPrice.ToString("0.00");
     return result;
 }
示例#11
0
        private static void ClearAfterBulkInsert(ImportEntity importEntity)
        {
            IEnumerable <string> logFiles = Directory.EnumerateFiles(importEntity.TempFolderName, "*.log");

            if (!logFiles.Any())
            {
                Directory.Delete(importEntity.TempFolderName, true);
            }
        }
示例#12
0
 public static bool AddProduct(ImportEntity product, string cogsAccountRef, string assetAccountRef, string incomeAccountRef)
 {
     string productcode = product.Fields[0];
     string productDescription = product.Fields[1];
     double exfactoryPrice = Convert.ToDouble(product.Fields[2]);
     IItemInventoryRet itemInventoryRet = QBFC_Core.QBAddInventory(productcode, productDescription,
                                                                   Convert.ToDouble(exfactoryPrice),cogsAccountRef, assetAccountRef, incomeAccountRef);
     return itemInventoryRet != null;
 }
示例#13
0
        public ImportJobRunViewModel(IViewModelsFactory <IPickAssetViewModel> vmFactory, ImportEntity jobEntity)
        {
            _assetVmFactory = vmFactory;

            InnerItem = jobEntity;
            OnPropertyChanged("InnerItem");

            FilePickCommand      = new DelegateCommand(RaiseFilePickInteractionRequest);
            CommonConfirmRequest = new InteractionRequest <Confirmation>();
        }
        protected virtual ImportParameters GetImportParams(EntitySchema entitySchema)
        {
            var importParameters = new ImportParameters();

            importParameters.Entities = new List <ImportEntity>();
            var entity = new ImportEntity();

            importParameters.Entities.Add(entity);
            importParameters.RootSchemaUId = entitySchema.UId;
            return(importParameters);
        }
        private ImportEntity ParseModel(string brandSku, string brandName, string modelSku, string modelName, XElement model)
        {
            var productSpecifications = _configImportCategoryEntity.ProductSpecifications.Select(i => GetProductSpecification(model, i.XName, i.RusName)).ToList();

            var productName = (string)model.Attribute("Title");
            var productSku  = (string)model.Attribute("Id");

            //проверка на удаление
            var delete    = model.Attribute("Delete").Value;
            var isDeleted = delete.Equals("true");

            //Добавляем опцию спецификации для производителя
            if (brandName != "КРЕПЕЖ")
            {
                var brandSpecification = new ProductSpecification()
                {
                    Name  = "Производитель",
                    Value = brandName
                };
                productSpecifications.Add(brandSpecification);
            }

            var storageRoot = model.Element("Storages");

            if (storageRoot == null)
            {
                throw new Exception("No storages root");
            }
            var storages = storageRoot.Elements("Storage");

            if (storages == null)
            {
                throw new Exception("No storages");
            }

            var importEntity = new ImportEntity
            {
                BrandName             = brandName,
                BrandSku              = brandSku,
                ModelSku              = modelSku,
                ModelName             = modelName,
                ProductName           = brandName + " " + productName,
                IsDeleted             = isDeleted,
                ProductSku            = productSku,
                Storages              = storages.Select(GetProductStorage).ToArray(),
                ProductSpecifications = productSpecifications.ToArray(),
                CategoryId            = _configImportCategoryEntity.CategoryId
            };

            return(importEntity);
        }
示例#16
0
        public IImportDataProcessor GetImportDataProcessor(ImportEntity entity)
        {
            var entityType = entity.GetType();

            Console.WriteLine(entityType);

            if (entityType == typeof(PortalTest))
            {
                return(kernel.Get <RecordLockDataProcessorDecorator <PortalTest, kurdev_portal_test> >());
            }
            if (entityType == typeof(Importer.ImportType.Models.Contact))
            {
                return(kernel.Get <RecordLockDataProcessorDecorator <Importer.ImportType.Models.Contact, Contact> >());
            }
            return(null);
        }
示例#17
0
 private HostVulnerabilityEntity CreateHostVulnerability(
     int engagementId,
     int phaseId,
     HostEntity hostEntity,
     VulnerabilityEntity vulnerabilityEntity,
     ImportEntity importEntity)
 {
     return(new HostVulnerabilityEntity
     {
         EngagementId = engagementId,
         PhaseId = phaseId,
         Host = hostEntity,
         Vulnerability = vulnerabilityEntity,
         Import = importEntity
     });
 }
        private bool UpdatePublish(ImportEntity importEntity)
        {
            bool publish;

            if (_miscOneSSetting.PublishOnlyBerikolesaStorage)
            {
                publish =
                    importEntity.Storages.Any(
                        x => String.Equals(x.Name, "Berikolesa.RU", StringComparison.CurrentCultureIgnoreCase) &&
                        x.Quantity > 0);
            }
            else
            {
                publish = importEntity.Storages.Any(x => x.Price > 0 && x.Quantity > 0);
            }
            return(publish);
        }
        private void RaiseImportJobRunInteractionRequest(object item)
        {
            // initial checks
            if (item == null)
            {
                CommonNotifyRequest.Raise(new Notification {
                    Content = "Select import job to run.".Localize(), Title = "Error".Localize(null, LocalizationScope.DefaultCategory)
                });
            }
            else
            {
                var it        = ((VirtualListItem <IImportJobViewModel>)item).Data.InnerItem;
                var jobEntity = new ImportEntity {
                    ImportJob = it
                };
                var itemVM = _runVmFactory.GetViewModelInstance(
                    new KeyValuePair <string, object>("jobEntity", jobEntity)
                    );

                var confirmation = new ConditionalConfirmation(itemVM.Validate)
                {
                    Content = itemVM, Title = "Run Import Job".Localize()
                };
                CommonConfirmRequest.Raise(confirmation, async(x) =>
                {
                    if (x.Confirmed)
                    {
                        await Task.Run(() =>
                        {
                            var id = Guid.NewGuid().ToString();

                            var statusUpdate = new StatusMessage
                            {
                                ShortText       = string.Format("File '{0}' import.".Localize(), Path.GetFileName(jobEntity.SourceFile)),
                                StatusMessageId = id
                            };
                            EventSystem.Publish(statusUpdate);

                            var progress              = new Progress <ImportProgress>();
                            progress.ProgressChanged += ImportProgressChanged;
                            PerformImportAsync(id, jobEntity, progress);
                        });
                    }
                });
            }
        }
示例#20
0
        private static void ExtractFile(ImportEntity importEntity)
        {
            try
            {
                ZipFile.ExtractToDirectory(importEntity.ArchiveFilePath, importEntity.TempFolderName);
            }
            catch (IOException exception)
            {
                //Some idiots puts 2 files in 1 archive! So we should suppress exception.
            }
            catch (Exception exception)
            {
                WriteError($"{importEntity.TableName} - extract file exception: {exception.Message}");
            }

            File.Delete(importEntity.ArchiveFilePath);
        }
        private void UpdateProductSpecificationOption(ImportEntity importEntity)
        {
            var productFromBase         = _productService.GetProductBySku(importEntity.ProductSku);
            var allSpecificationOptions =
                _specificationAttributeService.GetSpecificationAttributes();
            var specificationMap = allSpecificationOptions.ToDictionary(i => i.Name, i => i);

            //если айди аттрибута из импорта нету в списке из связей в базе, то добавляем

            foreach (var productSpecificationAttribute in importEntity.ProductSpecifications)
            {
                if (!String.IsNullOrWhiteSpace(productSpecificationAttribute.Value))
                {
                    var importProductSpecification = _configImportCategoryEntity.ProductSpecifications.FirstOrDefault(
                        x => x.RusName.Equals(productSpecificationAttribute.Name));
                    var allowFilter =
                        importProductSpecification != null && importProductSpecification.FilterBy;
                    //пропишем айди в для specificationOptions из базы
                    GetIdForSpecificationOption(specificationMap, productSpecificationAttribute);

                    var productSpecifications =
                        _productService.GetProductBySku(importEntity.ProductSku).ProductSpecificationAttributes;


                    var productSpecificationAttributeOption =
                        productSpecifications.FirstOrDefault(
                            x => x.SpecificationAttributeOption.SpecificationAttributeId.Equals(productSpecificationAttribute.SpecificationId));

                    if (productSpecificationAttributeOption == null)
                    {
                        ProductSpecificationAttributeOptionMapping(productFromBase, productSpecificationAttribute, allowFilter);
                    }
                    else
                    {
                        _specificationAttributeService.DeleteProductSpecificationAttribute(
                            productSpecificationAttributeOption);

                        ProductSpecificationAttributeOptionMapping(productFromBase, productSpecificationAttribute, allowFilter);
                    }
                }
            }
        }
示例#22
0
        public async Task AddOrUpdate(ImportEntity entityFromDb, ImportEntity entityFromImport)
        {
            if (entityFromDb != null)
            {
                _movieDbMapper.MapFromImportToDb(entityFromDb, entityFromImport);
                entityFromDb.UpdateAuditValuesForUpdatedEntity(_systemGuid);
                _tvSeriesContext.Update(entityFromDb);
                await _tvSeriesContext.SaveChangesAsync();

                _logger.LogInformation($"Update {entityFromDb.GetType()} with id {entityFromDb.Id}");
            }
            else
            {
                entityFromImport.UpdateAuditValuesForNewEntity(_systemGuid);
                entityFromImport.EnableImport();
                await _tvSeriesContext.AddAsync(entityFromImport);

                await _tvSeriesContext.SaveChangesAsync();

                _logger.LogInformation($"Added {entityFromImport.GetType()} with id {entityFromImport.Id}");
            }
        }
        private void UpdateSpecificationOption(ImportEntity importEntity)
        {
            foreach (var entity in importEntity.ProductSpecifications)
            {
                var specificationAttribute = _specificationAttributeService.
                                             GetSpecificationAttributes().
                                             FirstOrDefault(x => x.Name.Equals(entity.Name));
                if (specificationAttribute != null)
                {
                    MappingAttributeSpecificationOption(entity, specificationAttribute);
                }
                else
                {
                    specificationAttribute              = new SpecificationAttribute();
                    specificationAttribute.Name         = entity.Name;
                    specificationAttribute.DisplayOrder = 0;

                    _specificationAttributeService.InsertSpecificationAttribute(specificationAttribute);
                    MappingAttributeSpecificationOption(entity, specificationAttribute);
                }
            }
        }
        private void UpdateProduct(ImportEntity importEntity)
        {
            var product       = _productService.GetProductBySku(importEntity.ProductSku);
            var parentProduct = _productService.GetProductBySku(importEntity.ModelSku);
            var publish       = UpdatePublish(importEntity);


            if (product == null)
            {
                product           = CreateSimpleProduct(importEntity.ProductSku, importEntity.ProductName);
                product.Published = publish;
                product.ParentGroupedProductId = parentProduct.Id;

                _productService.InsertProduct(product);
                //смотрим, есть ли запись в таблице адресов
                var validateName = product.ValidateSeName(product.Name, product.Name, true);
                UpdateSlug(validateName, product);
                CreateProductCategoryMapping(product.Sku, importEntity.CategoryId);
            }
            else
            {
                product.Name = importEntity.ProductName;
                product.ParentGroupedProductId = parentProduct.Id;
                product.UpdatedOnUtc           = DateTime.UtcNow;
                product.ProductType            = ProductType.SimpleProduct;
                product.VisibleIndividually    = true;
                product.Published             = publish;
                product.ProductTemplateId     = 1;
                product.ManageInventoryMethod = ManageInventoryMethod.ManageStockByAttributes;
                product.OrderMinimumQuantity  = 1;
                product.OrderMaximumQuantity  = 100;//TODO: тут нужно смотреть количество из 1с
                //product.Price = storage.Price;
                product.IsShipEnabled = true;
                _productService.UpdateProduct(product);
            }
        }
示例#25
0
      internal  static ICustomerRet QBAddCustomer(ImportEntity outlet)
        {
            bool boolSessionBegun = false;
            QBSessionManager sessionManager = new QBSessionManager();
            try
            {
                IMsgSetRequest requestMsgSet;
                IMsgSetResponse responseMsgSet;
                sessionManager.OpenConnection("", _appName);
                sessionManager.BeginSession(qdbpath, ENOpenMode.omDontCare);
                boolSessionBegun = true;
                requestMsgSet = GetLatestMsgSetRequest(sessionManager);
                requestMsgSet.Attributes.OnError = ENRqOnError.roeContinue;

                string errecid = "{" + Guid.NewGuid().ToString() + "}";
                sessionManager.ErrorRecoveryID.SetValue(errecid);

                sessionManager.EnableErrorRecovery = true;

                sessionManager.SaveAllMsgSetRequestInfo = true;

                #region error recovery

                if (sessionManager.IsErrorRecoveryInfo())
                {
                    IMsgSetRequest reqMsgSet = null;
                    IMsgSetResponse resMsgSet = null;
                    resMsgSet = sessionManager.GetErrorRecoveryStatus();
                    if (resMsgSet.Attributes.MessageSetStatusCode.Equals("600"))
                    {
                        MessageBox.Show(
                            "The oldMessageSetID does not match any stored IDs, and no newMessageSetID is provided.");
                    }
                    else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9001"))
                    {
                        MessageBox.Show(
                            "Invalid checksum. The newMessageSetID specified, matches the currently stored ID, but checksum fails.");
                    }
                    else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9002"))
                    {
                        MessageBox.Show("No stored response was found.");
                    }
                    else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9004"))
                    {
                        MessageBox.Show("Invalid MessageSetID, greater than 24 character was given.");
                    }
                    else if (resMsgSet.Attributes.MessageSetStatusCode.Equals("9005"))
                    {
                        MessageBox.Show("Unable to store response.");
                    }
                    else
                    {
                        IResponse res = resMsgSet.ResponseList.GetAt(0);
                        int sCode = res.StatusCode;
                        if (sCode == 0)
                        {
                            MessageBox.Show("Last request was processed and customer was added successfully!");
                        }
                        else if (sCode > 0)
                        {
                            MessageBox.Show("There was a warning but last request was processed successfully!");
                        }
                        else
                        {
                            MessageBox.Show("It seems that there was an error in processing last request");
                            reqMsgSet = sessionManager.GetSavedMsgSetRequest();
                            resMsgSet = sessionManager.DoRequests(reqMsgSet);
                            IResponse resp = resMsgSet.ResponseList.GetAt(0);
                            int statCode = resp.StatusCode;
                            if (statCode == 0)
                            {
                                string resStr = null;
                                ICustomerRet custRet = resp.Detail as ICustomerRet;
                                resStr = resStr + "Following customer has been successfully submitted to QuickBooks:\n\n\n";
                                if (custRet.ListID != null)
                                {
                                    resStr = resStr + "ListID Number = " + Convert.ToString(custRet.ListID.GetValue()) +
                                             "\n";
                                }
                                Log(QBCRUDEAction.ErrorRecovery, "SalesReceipt", (custRet == null ? "" : custRet.FullName.GetValue()), resp);
                            }
                        }
                    }

                    sessionManager.ClearErrorRecovery();
                    //MessageBox.Show("Proceeding with current transaction.");
                }

                #endregion

                string customerName = outlet.Fields[1];
                bool state = true;
                try
                {
                    if (Boolean.TryParse(outlet.Fields[2], out state)) ;
                    
                }catch(Exception)
                {
                    state = true;

                }
               
                ICustomerRet existingQB = GetCustomerByNameFilter(customerName);
                ICustomerRet customerRet = null;

                
                if (existingQB == null)
                {
                   
                    ICustomerAdd customerAdd = requestMsgSet.AppendCustomerAddRq();
                    customerAdd.Name.SetValue(customerName);
                   // customerAdd.CompanyName.SetValue(companyName);
                    customerAdd.IsActive.SetValue(state);
                    responseMsgSet = sessionManager.DoRequests(requestMsgSet);
                    IResponse response = responseMsgSet.ResponseList.GetAt(0);
                    int statusCode = response.StatusCode;
                    customerRet = response.Detail as ICustomerRet;
                    if (statusCode == 0)
                    {
                        Console.WriteLine("Success");
                    }
                    else if (statusCode == 3100)
                    {
                        MessageBox.Show("Customer with same name exists");
                    }
                    Log(QBCRUDEAction.Add, "Customer", (customerRet == null ? "" : customerRet.FullName.GetValue()), response);
                    return customerRet;
                }
                else
                {
                    ICustomerMod customerModRq = requestMsgSet.AppendCustomerModRq();
                    customerModRq.Name.SetValue(customerName);
                    customerModRq.IsActive.SetValue(state);
                  //  customerModRq.CompanyName.SetValue(companyName);
                    customerModRq.ListID.SetValue(existingQB.ListID.GetValue());
                    customerModRq.EditSequence.SetValue(existingQB.EditSequence.GetValue());
                    responseMsgSet = sessionManager.DoRequests(requestMsgSet);
                    IResponse response = responseMsgSet.ResponseList.GetAt(0);
                    int statusCode = response.StatusCode;
                    customerRet = response.Detail as ICustomerRet;
                    if (statusCode == 0)
                    {
                        Console.WriteLine("Success");
                    }
                    Log(QBCRUDEAction.Update, "Customer", (customerRet == null ? "" : customerRet.FullName.GetValue()), response);
                }

                sessionManager.ClearErrorRecovery();
                sessionManager.EndSession();
                boolSessionBegun = false;
                sessionManager.CloseConnection();
                return customerRet;
            }
            catch (Exception ex)
            {

                if (boolSessionBegun)
                {
                    sessionManager.EndSession();
                    sessionManager.CloseConnection();
                }
                string error = (ex.Message.ToString() + "\nStack Trace: \n" + ex.StackTrace + "\nExiting the application");
                Log(error);
                int attemp = 0;
                if (ex.Message.Contains("Object reference not set to an instance of an object")&& attemp<3)
                {
                    QBAddCustomer(outlet);
                    attemp++;
                }
                else
                {
                    MessageBox.Show(ex.Message);
                }
               

            }
            return null;
        }
示例#26
0
文件: Model.cs 项目: Atili0/dx_tools
 public void GetAttributes()
 {
     Attribute = new ImportEntity().GetAttributesByEntityId(EntityName, ServerConnection);
 }
        private ImportEntity Map(tblCostCentre item)
        {
            var result = new ImportEntity {MasterDataCollective = MasterDataCollective.Outlet.ToString()};
            result.Fields[0] = string.IsNullOrEmpty(item.Cost_Centre_Code)?"":item.Cost_Centre_Code.Trim();
            result.Fields[1] =string.IsNullOrEmpty(item.Name)?"":item.Name.Trim(); 
            result.Fields[2] = item.IM_Status == 1 ? true.ToString() : false.ToString();
            return result;

        }
示例#28
0
文件: V7.cs 项目: yonglehou/2sxc
        /// <summary>
        /// Add ContentTypes for ContentGroup and move all 2sxc data to EAV
        /// </summary>
        internal void Version070000()
        {
            logger.LogStep("07.00.00", "Start", false);

            var userName = "******";

            #region 1. Import new ContentTypes for ContentGroups and Templates

            logger.LogStep("07.00.00", "1. Import new ContentTypes for ContentGroups and Templates", false);
            if (DataSource.GetCache(Constants.DefaultZoneId, Constants.MetaDataAppId).GetContentType("2SexyContent-Template") == null)
            {
                var xmlToImport =
                    File.ReadAllText(HttpContext.Current.Server.MapPath("~/DesktopModules/ToSIC_SexyContent/Upgrade/07.00.00.xml"));
                //var xmlToImport = File.ReadAllText("../../../../Upgrade/07.00.00.xml");
                var xmlImport = new XmlImport("en-US", userName, true);
                var success   = xmlImport.ImportXml(Constants.DefaultZoneId, Constants.MetaDataAppId, XDocument.Parse(xmlToImport));

                if (!success)
                {
                    var messages = String.Join("\r\n- ", xmlImport.ImportLog.Select(p => p.Message).ToArray());
                    throw new Exception("The 2sxc module upgrade to 07.00.00 failed: " + messages);
                }
            }

            #endregion



            // 2. Move all existing data to the new ContentTypes - Append new IDs to old data (ensures that we can fix things that went wrong after upgrading the module)

            #region Prepare Templates
            logger.LogStep("07.00.00", "2. Move all existing data to the new ContentTypes - Append new IDs to old data (ensures that we can fix things that went wrong after upgrading the module)", false);

            var          sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString);
            var          templates     = new DataTable();
            const string sqlCommand    = @"SELECT        ToSIC_SexyContent_Templates.TemplateID, ToSIC_SexyContent_Templates.PortalID, ToSIC_SexyContent_Templates.Name, ToSIC_SexyContent_Templates.Path, 
                         ToSIC_SexyContent_Templates.AttributeSetID, ToSIC_SexyContent_Templates.DemoEntityID, ToSIC_SexyContent_Templates.Script, 
                         ToSIC_SexyContent_Templates.IsFile, ToSIC_SexyContent_Templates.Type, ToSIC_SexyContent_Templates.IsHidden, ToSIC_SexyContent_Templates.Location, 
                         ToSIC_SexyContent_Templates.UseForList, ToSIC_SexyContent_Templates.UseForItem, ToSIC_SexyContent_Templates.SysCreated, 
                         ToSIC_SexyContent_Templates.SysCreatedBy, ToSIC_SexyContent_Templates.SysModified, ToSIC_SexyContent_Templates.SysModifiedBy, 
                         ToSIC_SexyContent_Templates.SysDeleted, ToSIC_SexyContent_Templates.SysDeletedBy, ToSIC_SexyContent_Templates.AppID, 
                         ToSIC_SexyContent_Templates.PublishData, ToSIC_SexyContent_Templates.StreamsToPublish, ToSIC_SexyContent_Templates.PipelineEntityID, 
                         ToSIC_SexyContent_Templates.ViewNameInUrl, ToSIC_SexyContent_Templates.Temp_PresentationTypeID, 
                         ToSIC_SexyContent_Templates.Temp_PresentationDemoEntityID, ToSIC_SexyContent_Templates.Temp_ListContentTypeID, 
                         ToSIC_SexyContent_Templates.Temp_ListContentDemoEntityID, ToSIC_SexyContent_Templates.Temp_ListPresentationTypeID, 
                         ToSIC_SexyContent_Templates.Temp_ListPresentationDemoEntityID, ToSIC_SexyContent_Templates.Temp_NewTemplateGuid, ToSIC_EAV_Apps.ZoneID, 
                         ToSIC_EAV_Entities_1.EntityGUID AS ContentDemoEntityGuid, ToSIC_EAV_Entities_2.EntityGUID AS PresentationDemoEntityGuid, 
                         ToSIC_EAV_Entities_3.EntityGUID AS ListContentDemoEntityGuid, ToSIC_EAV_Entities_4.EntityGUID AS ListPresentationDemoEntityGuid, 
                         ToSIC_EAV_Entities.EntityGUID AS PipelineEntityGuid
FROM            ToSIC_SexyContent_Templates INNER JOIN
                         ToSIC_EAV_Apps ON ToSIC_SexyContent_Templates.AppID = ToSIC_EAV_Apps.AppID LEFT OUTER JOIN
                         ToSIC_EAV_Entities ON ToSIC_SexyContent_Templates.PipelineEntityID = ToSIC_EAV_Entities.EntityID LEFT OUTER JOIN
                         ToSIC_EAV_Entities AS ToSIC_EAV_Entities_3 ON ToSIC_SexyContent_Templates.Temp_ListContentDemoEntityID = ToSIC_EAV_Entities_3.EntityID LEFT OUTER JOIN
                         ToSIC_EAV_Entities AS ToSIC_EAV_Entities_1 ON ToSIC_SexyContent_Templates.DemoEntityID = ToSIC_EAV_Entities_1.EntityID LEFT OUTER JOIN
                         ToSIC_EAV_Entities AS ToSIC_EAV_Entities_2 ON 
                         ToSIC_SexyContent_Templates.Temp_PresentationDemoEntityID = ToSIC_EAV_Entities_2.EntityID LEFT OUTER JOIN
                         ToSIC_EAV_Entities AS ToSIC_EAV_Entities_4 ON ToSIC_SexyContent_Templates.Temp_ListPresentationDemoEntityID = ToSIC_EAV_Entities_4.EntityID
WHERE        (ToSIC_SexyContent_Templates.SysDeleted IS NULL) AND ((SELECT COUNT(*) FROM ToSIC_EAV_Entities WHERE EntityGUID = ToSIC_SexyContent_Templates.Temp_NewTemplateGuid) = 0)";

            var adapter = new SqlDataAdapter(sqlCommand, sqlConnection);
            adapter.SelectCommand.CommandTimeout = 3600;
            adapter.Fill(templates);

            var existingTemplates = templates.AsEnumerable().Select(t =>
            {
                var templateId = (int)t["TemplateID"];
                var zoneId     = (int)t["ZoneID"];
                var appId      = (int)t["AppID"];
                var cache      = ((BaseCache)DataSource.GetCache(zoneId, appId)).GetContentTypes();

                #region Helper Functions
                Func <int?, string> getContentTypeStaticName = contentTypeId =>
                {
                    if (!contentTypeId.HasValue || contentTypeId == 0)
                    {
                        return("");
                    }
                    if (cache.Any(c => c.Value.AttributeSetId == contentTypeId))
                    {
                        return(cache[contentTypeId.Value].StaticName);
                    }
                    return("");
                };

                #endregion

                // Create anonymous object to validate the types
                var tempTemplate = new
                {
                    TemplateID    = templateId,
                    Name          = (string)t["Name"],
                    Path          = (string)t["Path"],
                    NewEntityGuid = Guid.Parse((string)t["Temp_NewTemplateGuid"]),
                    //AlreadyImported = t["Temp_NewTemplateGuid"] != DBNull.Value,

                    ContentTypeId          = getContentTypeStaticName(t["AttributeSetID"] == DBNull.Value ? new int?() : (int)t["AttributeSetID"]),
                    ContentDemoEntityGuids = t["ContentDemoEntityGuid"] == DBNull.Value ? new List <Guid>() : new List <Guid> {
                        (Guid)t["ContentDemoEntityGuid"]
                    },
                    PresentationTypeId          = getContentTypeStaticName((int)t["Temp_PresentationTypeID"]),
                    PresentationDemoEntityGuids = t["PresentationDemoEntityGuid"] == DBNull.Value ? new List <Guid>() : new List <Guid> {
                        (Guid)t["PresentationDemoEntityGuid"]
                    },
                    ListContentTypeId          = getContentTypeStaticName((int)t["Temp_ListContentTypeID"]),
                    ListContentDemoEntityGuids = t["ListContentDemoEntityGuid"] == DBNull.Value ? new List <Guid>() : new List <Guid> {
                        (Guid)t["ListContentDemoEntityGuid"]
                    },
                    ListPresentationTypeId          = getContentTypeStaticName((int)t["Temp_ListPresentationTypeID"]),
                    ListPresentationDemoEntityGuids = t["ListPresentationDemoEntityGuid"] == DBNull.Value ? new List <Guid>() : new List <Guid> {
                        (Guid)t["ListPresentationDemoEntityGuid"]
                    },

                    Type                = (string)t["Type"],
                    IsHidden            = (bool)t["IsHidden"],
                    Location            = (string)t["Location"],
                    UseForList          = (bool)t["UseForList"],
                    AppId               = appId,
                    PublishData         = (bool)t["PublishData"],
                    StreamsToPublish    = (string)t["StreamsToPublish"],
                    PipelineEntityGuids = t["PipelineEntityGuid"] == DBNull.Value ? new List <Guid>() : new List <Guid> {
                        (Guid)t["PipelineEntityGuid"]
                    },
                    ViewNameInUrl = t["ViewNameInUrl"].ToString(),
                    ZoneId        = zoneId
                };

                return(tempTemplate);
            }).ToList();

            #endregion


            #region Prepare ContentGroups
            logger.LogStep("07.00.00", "2. Prepare Content Groups", false);

            var          contentGroupItemsTable  = new DataTable();
            const string sqlCommandContentGroups = @"SELECT DISTINCT        ToSIC_SexyContent_ContentGroupItems.ContentGroupItemID, ToSIC_SexyContent_ContentGroupItems.ContentGroupID, 
                         ToSIC_SexyContent_ContentGroupItems.TemplateID, ToSIC_SexyContent_ContentGroupItems.SortOrder, ToSIC_SexyContent_ContentGroupItems.Type, 
                         ToSIC_SexyContent_ContentGroupItems.SysCreated, ToSIC_SexyContent_ContentGroupItems.SysCreatedBy, ToSIC_SexyContent_ContentGroupItems.SysModified, 
                         ToSIC_SexyContent_ContentGroupItems.SysModifiedBy, ToSIC_SexyContent_ContentGroupItems.SysDeleted, 
                         ToSIC_SexyContent_ContentGroupItems.SysDeletedBy, ToSIC_SexyContent_Templates.AppID, ToSIC_EAV_Apps.ZoneID, 
                         ToSIC_EAV_Entities.EntityGUID, ToSIC_SexyContent_ContentGroupItems.EntityID, ToSIC_SexyContent_ContentGroupItems.Temp_NewContentGroupGuid, ToSIC_SexyContent_Templates.Temp_NewTemplateGuid
FROM            ToSIC_SexyContent_Templates INNER JOIN
                         ModuleSettings INNER JOIN
                         ToSIC_SexyContent_ContentGroupItems ON ModuleSettings.SettingValue = ToSIC_SexyContent_ContentGroupItems.ContentGroupID ON 
                         ToSIC_SexyContent_Templates.TemplateID = ToSIC_SexyContent_ContentGroupItems.TemplateID INNER JOIN
                         ToSIC_EAV_Apps ON ToSIC_SexyContent_Templates.AppID = ToSIC_EAV_Apps.AppID LEFT OUTER JOIN
                         ToSIC_EAV_Entities ON ToSIC_SexyContent_ContentGroupItems.EntityID = ToSIC_EAV_Entities.EntityID
WHERE        (ToSIC_SexyContent_ContentGroupItems.SysDeleted IS NULL) AND (ModuleSettings.SettingName = N'ContentGroupID') AND 
                         ((SELECT COUNT(*) FROM ToSIC_EAV_Entities WHERE EntityGUID = ToSIC_SexyContent_ContentGroupItems.Temp_NewContentGroupGuid) = 0) ORDER BY SortOrder";

            var adapterContentGroups = new SqlDataAdapter(sqlCommandContentGroups, sqlConnection);
            adapterContentGroups.SelectCommand.CommandTimeout = 3600;
            adapterContentGroups.Fill(contentGroupItemsTable);

            var contentGroupItems = contentGroupItemsTable.AsEnumerable().Select(c => new
            {
                ContentGroupId      = (int)c["ContentGroupID"],
                NewContentGroupGuid = Guid.Parse((string)c["Temp_NewContentGroupGuid"]),
                EntityId            = c["EntityID"] == DBNull.Value ? new int?() : (int)c["EntityID"],
                EntityGuid          = c["EntityGUID"] == DBNull.Value ? (Guid?)null : ((Guid)c["EntityGUID"]),
                TemplateId          = c["TemplateID"] == DBNull.Value ? new int?() : (int)c["TemplateID"],
                SortOrder           = (int)c["SortOrder"],
                Type   = (string)c["Type"],
                AppId  = (int)c["AppID"],
                ZoneId = (int)c["ZoneID"],
                TemplateEntityGuids = new List <Guid>()
                {
                    Guid.Parse((string)c["Temp_NewTemplateGuid"])
                }
            });

            var existingContentGroups = contentGroupItems.GroupBy(c => c.ContentGroupId, c => c, (id, items) =>
            {
                var itemsList    = items.ToList();
                var contentGroup = new
                {
                    NewEntityGuid = itemsList.First().NewContentGroupGuid,
                    itemsList.First().AppId,
                    itemsList.First().ZoneId,
                    ContentGroupId        = id,
                    TemplateGuids         = itemsList.First().TemplateEntityGuids,
                    ContentGuids          = itemsList.Where(p => p.Type == "Content").Select(p => p.EntityGuid).ToList(),
                    PresentationGuids     = itemsList.Where(p => p.Type == "Presentation").Select(p => p.EntityGuid).ToList(),
                    ListContentGuids      = itemsList.Where(p => p.Type == "ListContent").Select(p => p.EntityGuid).ToList(),
                    ListPresentationGuids = itemsList.Where(p => p.Type == "ListPresentation").Select(p => p.EntityGuid).ToList()
                };
                return(contentGroup);
            }).ToList();

            #endregion


            // Import all entities
            logger.LogStep("07.00.00", "2. Import all entities", false);
            var apps = existingTemplates.Select(p => p.AppId).ToList();
            apps.AddRange(existingContentGroups.Select(p => p.AppId));
            apps = apps.Distinct().ToList();

            foreach (var app in apps)
            {
                logger.LogStep("07.00.00", "Starting to migrate data for app " + app + "...");

                var currentApp       = app;
                var entitiesToImport = new List <ImportEntity>();

                foreach (var t in existingTemplates.Where(t => t.AppId == currentApp))
                {
                    var entity = new ImportEntity
                    {
                        AttributeSetStaticName = "2SexyContent-Template",
                        EntityGuid             = t.NewEntityGuid,
                        IsPublished            = true,
                        AssignmentObjectTypeId = ContentTypeHelpers.AssignmentObjectTypeIDDefault
                    };
                    entity.Values = new Dictionary <string, List <IValueImportModel> >
                    {
                        { "Name", new List <IValueImportModel> {
                              new ValueImportModel <string>(entity)
                              {
                                  Value = t.Name
                              }
                          } },
                        { "Path", new List <IValueImportModel> {
                              new ValueImportModel <string>(entity)
                              {
                                  Value = t.Path
                              }
                          } },
                        { "ContentTypeStaticName", new List <IValueImportModel> {
                              new ValueImportModel <string>(entity)
                              {
                                  Value = t.ContentTypeId
                              }
                          } },
                        { "ContentDemoEntity", new List <IValueImportModel> {
                              new ValueImportModel <List <Guid> >(entity)
                              {
                                  Value = t.ContentDemoEntityGuids
                              }
                          } },
                        { "PresentationTypeStaticName", new List <IValueImportModel> {
                              new ValueImportModel <string>(entity)
                              {
                                  Value = t.PresentationTypeId
                              }
                          } },
                        { "PresentationDemoEntity", new List <IValueImportModel> {
                              new ValueImportModel <List <Guid> >(entity)
                              {
                                  Value = t.PresentationDemoEntityGuids
                              }
                          } },
                        { "ListContentTypeStaticName", new List <IValueImportModel> {
                              new ValueImportModel <string>(entity)
                              {
                                  Value = t.ListContentTypeId
                              }
                          } },
                        { "ListContentDemoEntity", new List <IValueImportModel> {
                              new ValueImportModel <List <Guid> >(entity)
                              {
                                  Value = t.ListContentDemoEntityGuids
                              }
                          } },
                        { "ListPresentationTypeStaticName", new List <IValueImportModel> {
                              new ValueImportModel <string>(entity)
                              {
                                  Value = t.ListPresentationTypeId
                              }
                          } },
                        { "ListPresentationDemoEntity", new List <IValueImportModel> {
                              new ValueImportModel <List <Guid> >(entity)
                              {
                                  Value = t.ListPresentationDemoEntityGuids
                              }
                          } },
                        { "Type", new List <IValueImportModel> {
                              new ValueImportModel <string>(entity)
                              {
                                  Value = t.Type
                              }
                          } },
                        { "IsHidden", new List <IValueImportModel> {
                              new ValueImportModel <bool?>(entity)
                              {
                                  Value = t.IsHidden
                              }
                          } },
                        { "Location", new List <IValueImportModel> {
                              new ValueImportModel <string>(entity)
                              {
                                  Value = t.Location
                              }
                          } },
                        { "UseForList", new List <IValueImportModel> {
                              new ValueImportModel <bool?>(entity)
                              {
                                  Value = t.UseForList
                              }
                          } },
                        { "PublishData", new List <IValueImportModel> {
                              new ValueImportModel <bool?>(entity)
                              {
                                  Value = t.PublishData
                              }
                          } },
                        { "StreamsToPublish", new List <IValueImportModel> {
                              new ValueImportModel <string>(entity)
                              {
                                  Value = t.StreamsToPublish
                              }
                          } },
                        { "Pipeline", new List <IValueImportModel> {
                              new ValueImportModel <List <Guid> >(entity)
                              {
                                  Value = t.PipelineEntityGuids
                              }
                          } },
                        { "ViewNameInUrl", new List <IValueImportModel> {
                              new ValueImportModel <string>(entity)
                              {
                                  Value = t.ViewNameInUrl
                              }
                          } }
                    };
                    entitiesToImport.Add(entity);
                }

                foreach (var t in existingContentGroups.Where(t => t.AppId == app))
                {
                    var entity = new ImportEntity
                    {
                        AttributeSetStaticName = "2SexyContent-ContentGroup",
                        EntityGuid             = t.NewEntityGuid,
                        IsPublished            = true,
                        AssignmentObjectTypeId = ContentTypeHelpers.AssignmentObjectTypeIDDefault
                    };
                    entity.Values = new Dictionary <string, List <IValueImportModel> >
                    {
                        { "Template", new List <IValueImportModel> {
                              new ValueImportModel <List <Guid> >(entity)
                              {
                                  Value = t.TemplateGuids
                              }
                          } },
                        { "Content", new List <IValueImportModel> {
                              new ValueImportModel <List <Guid?> >(entity)
                              {
                                  Value = t.ContentGuids
                              }
                          } },
                        { "Presentation", new List <IValueImportModel> {
                              new ValueImportModel <List <Guid?> >(entity)
                              {
                                  Value = t.PresentationGuids
                              }
                          } },
                        { "ListContent", new List <IValueImportModel> {
                              new ValueImportModel <List <Guid?> >(entity)
                              {
                                  Value = t.ListContentGuids
                              }
                          } },
                        { "ListPresentation", new List <IValueImportModel> {
                              new ValueImportModel <List <Guid?> >(entity)
                              {
                                  Value = t.ListPresentationGuids
                              }
                          } }
                    };
                    entitiesToImport.Add(entity);
                }

                var import = new Eav.Import.Import(null, app, userName);
                import.RunImport(null, entitiesToImport);

                logger.LogStep("07.00.00", "Migrated data for app " + app);
            }
            logger.LogStep("07.00.00", "Done", false);
        }
示例#29
0
        private LoadCounters ProcessImportTask( ImportEntity impEntity, ImportMode impMode,
			FileInfo dataFile, string logname, ref int rowcount, ref int skiprowcount, ref int errorcode )
        {
            using( var stream = ReadDataFile( dataFile ) )
            {
                var report = ImportFacade.ImportData( impEntity.GetFormatName(), impMode, stream, dataFile.Name );

                if( Configuration.LogDetails && ( report.HasValidationErrors || report.HasErrors ) )
                {
                    Encoding encoding = Encoding.GetEncoding( Configuration.LogEncoding );
                    using( var log = new StreamWriter( logname, false, encoding ) )
                    {
                        log.WriteLine( "found={0}", report.TotalCount );

                        if( report.HasValidationErrors )
                        {
                            log.WriteLine( "*** Parse and validation errors ***" );
                            foreach( var error in report.ValidationErrors )
                            {
                                log.WriteLine( "source record: " + error.RawRecord );
                                foreach( var detail in error.Details )
                                {
                                    detail.WriteToLog( log );
                                }
                            }
                        }

                        if( report.HasErrors )
                        {
                            foreach( var error in report.Errors )
                                LogException( error, log );
                        }
                    }
                }

                rowcount = impMode == ImportMode.BulkDelete ? report.Counters.Deleted : report.Counters.Added;
                skiprowcount = report.Counters.Skipped;
                int totalrows = rowcount + skiprowcount;
                errorcode = totalrows == report.TotalCount ? 0 : totalrows == 0 ? 2920 : 2910;

                return report.Counters;
            }
        }
示例#30
0
 public void Delete(ImportEntity entity)
 {
     this._importEntity.Delete(entity);
 }
示例#31
0
 public AlarmFile( FileInfo fileInfo, ImportEntity importEntity, AlarmFileType fileType )
 {
     FileInfo = fileInfo;
     ImportEntity = importEntity;
     FileType = fileType;
     Index = int.Parse( fileInfo.GetNameOnly() );
 }
示例#32
0
        private void SetUpMocks()
        {
            _engagementEntity = new EngagementEntity();
            _mockEngagementRepository.Setup(x => x.Get(It.IsAny <int>()))
            .Returns(_engagementEntity);

            _importEntity = new ImportEntity {
                Id = 1
            };
            _mockImportRepository.Setup(x => x.GetLatest(It.IsAny <int>()))
            .Returns(_importEntity);

            _customerEntity = new CustomerEntity();
            _mockCustomerRepository.Setup(x => x.Get(It.IsAny <int>()))
            .Returns(_customerEntity);

            _riskEntities = new List <RiskEntity>
            {
                new RiskEntity
                {
                    Impact     = 3,
                    Likelihood = 6,
                    FinalScore = 7
                }
            };
            _mockRiskRepository.Setup(x => x.GetByEngagementId(It.IsAny <int>()))
            .Returns(_riskEntities);

            _vulnerabilityEntities = new List <VulnerabilityEntity>
            {
                new VulnerabilityEntity
                {
                    CvssScore      = 1m,
                    RiskLevelBytes = Encode(ThreatLevel.High.Name)
                }
            };
            _mockVulnerabilityRepository.Setup(x => x.GetByEngagementId(It.IsAny <int>()))
            .Returns(_vulnerabilityEntities);

            _hostEntities = new List <HostEntity>
            {
                new HostEntity
                {
                    OperatingSystemBytes = Encode("Operating System"),
                    HostVulnerabilities  = new List <HostVulnerabilityEntity>
                    {
                        new HostVulnerabilityEntity
                        {
                            Vulnerability = new VulnerabilityEntity {
                                CvssScore = 10m
                            }
                        }
                    }
                }
            };
            _mockHostRepository.Setup(x => x.GetByEngagementId(It.IsAny <int>()))
            .Returns(_hostEntities);

            _governanceControlEntities = new List <GovernanceControlEntity>
            {
                new GovernanceControlEntity
                {
                    ThreatLevelId = 1,
                    CmmiStatusId  = 2
                }
            };
            _mockGovernanceControlRepository.Setup(x => x.GetByEngagementId(It.IsAny <int>()))
            .Returns(_governanceControlEntities);

            _phaseEntities = new List <PhaseEntity>
            {
                new PhaseEntity
                {
                    Name  = "Phase",
                    Risks = _riskEntities
                }
            };
            _mockPhaseRepository.Setup(x => x.GetByEngagementId(It.IsAny <int>()))
            .Returns(_phaseEntities);

            _importEntities = new List <ImportEntity>
            {
                new ImportEntity
                {
                    Id = 1
                }
            };
            _mockImportRepository.Setup(x => x.GetByEngagementId(It.IsAny <int>()))
            .Returns(_importEntities);

            _complianceEntities = new List <ComplianceEntity>
            {
                new ComplianceEntity
                {
                    Id = 1
                }
            };
            _mockComplianceRepository.Setup(x => x.GetByEngagementId(It.IsAny <int>(), It.IsAny <int>()))
            .Returns(_complianceEntities);

            _complianceSchemeEntities = new List <ComplianceSchemeEntity>
            {
                new ComplianceSchemeEntity
                {
                    Id = 1
                }
            };
            _mockComplianceSchemeRepository.Setup(x => x.GetByEngagementId(It.IsAny <int>()))
            .Returns(_complianceSchemeEntities);
        }
示例#33
0
 private LoadCounters ProcessDeleteTask( ImportEntity impEntity, FileInfo delFile, ref int rowcount )
 {
     using( var reader = delFile.OpenText() )
     {
         int supplierId = int.Parse(reader.ReadLine());
         var counters = ImportFacade.ClearData( impEntity.GetFormatName(), supplierId );
         rowcount = counters.Deleted;
         return counters;
     }
 }
示例#34
0
 //public string ReadAndSave(HttpPostedFileBase uploadeFile, ImportEntity model,string path)
 //{
 //    string msg = "";
 //    var fs = System.IO.File.OpenRead(path);
 //    FileInfo files = new FileInfo(fs.Name);
 //    var config = new CsvHelper.Configuration.CsvConfiguration();
 //    config.SkipEmptyRecords = true;
 //    config.WillThrowOnMissingField = false;
 //    config.DetectColumnCountChanges = false;
 //    config.Delimiter = ",";
 //    var csvPayment = new CsvReader(new StreamReader(fs), config);
 //    config.Delimiter = ",";
 //    while (csvPayment.Read())
 //    {
 //        IList<string[]> numbers = new List<string[]>();
 //        var records = csvPayment.CurrentRecord;
 //        model.Numbers = records;
 //        numbers.Add(model.Numbers);
 //        model.BatchCount = numbers.Count();
 //        model.Numbers = records;
 //        saveBulk(model);
 //    }
 //    return msg;
 //}
 public ImportEntity saveBulk(ImportEntity entity)
 {
     this._importEntity.SaveOrUpdate(entity);
     return entity;
 }
 private IEnumerable<ImportEntity> MapMasterDataList(SqlDataReader rs)
 {
    
     while (rs.Read())
     {
         var imports = new ImportEntity();
         var list = new List<string>();
         for (int i = 0; i < rs.FieldCount; i++)
         {
             string field = rs[i].ToString();
             list.Add(field);
         }
       
         imports.Fields = list.ToArray();
         imports.MasterDataCollective = masterdataEntity;
         MasterDataList.Add(imports);
        
     }
     return MasterDataList;
 }
示例#36
0
        public ActionResult SendSmS(SendSmsModel model, int?[] groups)
        {
            if (_workerContext.CurrentUserPersonalInformation.UserId != null)
            {
                var sendType = _genservice.GetAllSendType();
                var importname = _genservice.GetImportEntityPerUserID(_workerContext.CurrentUserPersonalInformation.UserId);
                BindCombo(model, importname);
                ComposeSms sms = new ComposeSms();
                if (model != null)
                {

                    List<string> numbers = model.receipientNumber.Split(',').ToList();

                    if (!string.IsNullOrEmpty(model.countryCode))
                    {
                        var num = _genservice.Numbers(numbers, model.countryCode);

                        if (num.Contains("Please Correct"))
                        {
                            model.merge.Add(new SelectListItem() { Text = "-Select-", Value = "-1", Selected = (model.mergestring == null) });
                            foreach (ImportEntity s in importname)
                                model.merge.Add(new SelectListItem() { Text = s.BatchName, Value = s.BatchName, Selected = (s.BatchName == model.mergestring) });

                            //model.Sendtype.Add(new SelectListItem() { Text = "-Select Send type-", Value = "-1", Selected = (model.Sendtype == null) });
                            foreach (SenderType s in sendType)
                                model.Sendtype.Add(new SelectListItem() { Text = s.Sendtype, Value = s.Id.ToString(), Selected = (s.Id == model.SendtypeId) });
                            TempData["line"] = string.Join(" ", num.ToArray()); ;
                            return View(model);
                        }

                        #region
                        if (model.DontSave == true)
                        {

                            var person = EngineContext.Resolve<IAuthenticationService>().GetAuthenticatedUser().UserId;
                            sms.SenderId = model.SenderId;
                            sms.message = model.message;
                            sms.UserId = _workerContext.CurrentUserPersonalInformation.UserId;
                            sms.SMSDate = DateTime.Now;
                            if (model.SendLaterDate > DateTime.Now)
                            {
                                sms.SendLaterDate = model.SendLaterDate;
                                sms.SendLaterTime = model.SendLaterTime;
                            }
                            else
                            {
                                sms.SendLaterDate = null;
                                sms.SendLaterTime = null;
                            }
                            if (model.SendtypeId >= 1)
                            {
                                sms.SendTypeId = model.SendtypeId;
                            }
                            else
                            {
                                TempData["warning"] = "Please Select send type";
                            }
                            if (groups != null)
                            {
                                var phonebook = _genservice.SendFromPhoneBook(groups);
                                foreach (string pnum in phonebook)
                                {
                                    num.Add(pnum);
                                }
                            }
                            foreach (string s_numbers in num.Distinct())
                            {
                                if (model.SendLaterDate > DateTime.Now)
                                {
                                    sms.NumberId = s_numbers;
                                    sms.MessageStatusId = (int)SystemEnums.MessageStatus.Pending;
                                    _genservice.numbers(sms);
                                }
                                sms.NumberId = s_numbers;
                                sms.MessageStatusId = (int)SystemEnums.MessageStatus.Waiting;
                                _genservice.numbers(sms);
                            }
                            //_smsService.SendSms(sms);
                            //_genservice.Savenumbers(sms.NumberId);
                            //_genservice.SaveMessagenumbers()
                            //doing the actuall sending
                            //if (sms.SendTypeId == 1)
                            //{
                            //    foreach (string x in sms.r.Split(','))
                            //    {
                            //        string pattern = @"\d{11}";

                            //        if (Regex.Match(x.Trim(), pattern).Success)
                            //        {

                            //        }
                            //        else
                            //        {
                            //            TempData["rollback"] = string.Format("{0},Is not in correct format", x);
                            //        }

                            //    }
                            //    TempData["Success"] = "Sent Succefully";
                            //}
                            if (sms.SendTypeId == 2)
                            {
                                TempData["Success"] = "Sucessfully saved as Draft";
                            }
                            if (sms.SendTypeId == 3)
                            {
                                TempData["Success"] = "Your message will be sent at the stipulated time";
                            }

                        }
                        #endregion
                        #region
                        if (model.SaveAs == true)
                        {
                            //checking if the batchName already exist for that user
                            var existingbook = _genservice.GetBatchNameForUser(model.newGroup, _workerContext.CurrentUserPersonalInformation.UserId);
                            if (!string.IsNullOrEmpty(existingbook))
                            {
                                ImportEntity import = new ImportEntity();
                                import.BatchName = model.newGroup;
                                import.BatchCount = num.Count();
                                import.countryCode = model.countryCode;
                                import.Numbers = String.Join(",", num);
                                import.UserId = _workerContext.CurrentUserPersonalInformation.UserId;
                                _genservice.saveBulk(import);
                                TempData["success"] = "Sucessfully Updated";

                                var person = EngineContext.Resolve<IAuthenticationService>().GetAuthenticatedUser().UserId;
                                sms.SenderId = model.SenderId;
                                sms.message = model.message;
                                sms.UserId = _workerContext.CurrentUserPersonalInformation.UserId;
                                sms.SMSDate = DateTime.Now;
                                if (model.SendLaterDate > DateTime.Now)
                                {
                                    sms.SendLaterDate = model.SendLaterDate;
                                    sms.SendLaterTime = model.SendLaterTime;
                                }
                                else
                                {
                                    sms.SendLaterDate = null;
                                    sms.SendLaterTime = null;
                                }
                                if (model.SendtypeId >= 1)
                                {
                                    sms.SendTypeId = model.SendtypeId;
                                }
                                else
                                {
                                    TempData["warning"] = "Please Select send type";
                                }

                                if (groups != null)
                                {
                                    var phonebook = _genservice.SendFromPhoneBook(groups);
                                    foreach (string pnum in phonebook)
                                    {
                                        num.Add(pnum);
                                    }
                                }
                                foreach (string s_numbers in num.Distinct())
                                {
                                    if (model.SendLaterDate > DateTime.Now)
                                    {
                                        sms.NumberId = s_numbers;
                                        sms.MessageStatusId = (int)SystemEnums.MessageStatus.Pending;
                                        _genservice.numbers(sms);
                                    }
                                    sms.NumberId = s_numbers;
                                    sms.MessageStatusId = (int)SystemEnums.MessageStatus.Waiting;
                                    _genservice.numbers(sms);
                                }
                                //doing the actual sending
                                //if (sms.SendTypeId == 1)
                                //{
                                //    foreach (string x in sms.receipientNumber.Split(','))
                                //    {
                                //        string pattern = @"\d{11}";

                                //        if (Regex.Match(x.Trim(), pattern).Success)
                                //        {

                                //        }
                                //        else
                                //        {
                                //            TempData["rollback"] = string.Format("{0},Is not in correct format", x);
                                //        }

                                //    }
                                //    TempData["Success"] = "Sent Succefully";
                                //}
                                if (sms.SendTypeId == 2)
                                {
                                    TempData["Success"] = "Sucessfully saved as Draft";
                                }
                                if (sms.SendTypeId == 3)
                                {
                                    TempData["Success"] = "Your message will be sent at the stipulated time";
                                }
                            }
                        }
                        #endregion
                        #region
                        if (model.MergeInto == true)
                        {
                            var oldgroupNum = _genservice.GetBatchNumbersWithUserId(_workerContext.CurrentUserPersonalInformation.UserId, model.mergestring);
                            List<string> mergeWith = oldgroupNum.Numbers.Split(',').ToList<string>();

                            List<string> lst = model.receipientNumber.Split(',').ToList();
                            var newNum = _genservice.Numbers(lst, model.countryCode);

                            if (newNum.Contains("Please Correct"))
                            {
                                model.merge.Add(new SelectListItem() { Text = "-Select-", Value = "-1", Selected = (model.mergestring == null) });
                                foreach (ImportEntity s in importname)
                                    model.merge.Add(new SelectListItem() { Text = s.BatchName, Value = s.BatchName, Selected = (s.BatchName == model.mergestring) });

                                //model.Sendtype.Add(new SelectListItem() { Text = "-Select Send type-", Value = "-1", Selected = (model.Sendtype == null) });
                                foreach (SenderType s in sendType)
                                    model.Sendtype.Add(new SelectListItem() { Text = s.Sendtype, Value = s.Id.ToString(), Selected = (s.Id == model.SendtypeId) });
                                TempData["line"] = string.Join(" ", num.ToArray()); ;
                                return View(model);
                            }
                            foreach (string merge in mergeWith)
                            {
                                newNum.Add(merge);
                            }

                            newNum.Count();
                            //ImportEntity import = new ImportEntity();
                            oldgroupNum.BatchName = model.mergestring;
                            oldgroupNum.BatchCount = newNum.Count();
                            oldgroupNum.countryCode = model.countryCode;
                            oldgroupNum.Numbers = String.Join(",", newNum);
                            oldgroupNum.UserId = _workerContext.CurrentUserPersonalInformation.UserId;
                            _genservice.saveBulk(oldgroupNum);
                            TempData["success"] = "Sucessfully Updated";
                            foreach (string addto in newNum)
                            {
                                num.Add(addto);
                            }
                            var person = EngineContext.Resolve<IAuthenticationService>().GetAuthenticatedUser().UserId;
                            sms.SenderId = model.SenderId;
                            sms.message = model.message;
                            sms.UserId = _workerContext.CurrentUserPersonalInformation.UserId;
                            sms.SMSDate = DateTime.Now;
                            if (model.SendLaterDate > DateTime.Now)
                            {
                                sms.SendLaterDate = model.SendLaterDate;
                                sms.SendLaterTime = model.SendLaterTime;
                            }
                            else
                            {
                                sms.SendLaterDate = null;
                                sms.SendLaterTime = null;
                            }
                            if (model.SendtypeId >= 1)
                            {
                                sms.SendTypeId = model.SendtypeId;
                            }
                            else
                            {
                                TempData["warning"] = "Please Select send type";
                            }
                            if (groups != null)
                            {
                                var phonebook = _genservice.SendFromPhoneBook(groups);
                                foreach (string pnum in phonebook)
                                {
                                    num.Add(pnum);
                                }
                            }
                            foreach (string s_numbers in num.Distinct())
                            {
                                if (model.SendLaterDate > DateTime.Now)
                                {
                                    sms.NumberId = s_numbers;
                                    sms.MessageStatusId = (int)SystemEnums.MessageStatus.Pending;
                                    _genservice.numbers(sms);
                                }
                                sms.NumberId = s_numbers;
                                sms.MessageStatusId = (int)SystemEnums.MessageStatus.Waiting;
                                _genservice.numbers(sms);
                            }
                            //doing the actual sending
                            //if (sms.SendTypeId == 1)
                            //{
                            //    foreach (string x in sms.receipientNumber.Split(','))
                            //    {
                            //        string pattern = @"\d{11}";

                            //        if (Regex.Match(x.Trim(), pattern).Success)
                            //        {

                            //        }
                            //        else
                            //        {
                            //            TempData["rollback"] = string.Format("{0},Is not in correct format", x);
                            //        }

                            //    }
                            //    TempData["Success"] = "Sent Succefully";
                            //}
                            if (sms.SendTypeId == 2)
                            {
                                TempData["Success"] = "Sucessfully saved as Draft";
                            }
                            if (sms.SendTypeId == 3)
                            {
                                TempData["Success"] = "Your message will be sent at the stipulated time";
                            }

                        }
                        #endregion

                    }
                }

                model.merge.Add(new SelectListItem() { Text = "-Select-", Value = "-1", Selected = (model.mergestring == null) });
                foreach (ImportEntity s in importname)
                    model.merge.Add(new SelectListItem() { Text = s.BatchName, Value = s.BatchName, Selected = (s.BatchName == model.mergestring) });

                //model.Sendtype.Add(new SelectListItem() { Text = "-Select Send type-", Value = "-1", Selected = (model.Sendtype == null) });
                foreach (SenderType s in sendType)
                    model.Sendtype.Add(new SelectListItem() { Text = s.Sendtype, Value = s.Id.ToString(), Selected = (s.Id == model.SendtypeId) });
                return RedirectToAction("SuccessPages", "Home");
            }
            else return RedirectToAction("Default", "Default");
        }
示例#37
0
        public ActionResult ImportBulksms(HttpPostedFileBase uploadedFile, Importmodel model)
        {
            if (_workerContext.CurrentUserPersonalInformation.UserId != null)
            {
                if (model.Radionewdescription == true)
                {
                    var existingbook = _genservice.GetBatchNameForUser(model.BatchName, _workerContext.CurrentUserPersonalInformation.UserId);

                    if (uploadedFile != null && string.IsNullOrEmpty(existingbook))
                    {
                        var fileName = Path.GetFileName(uploadedFile.FileName);
                        var File = System.Web.Hosting.HostingEnvironment.MapPath("~/uploads/files/" + fileName);
                        //var path = Path.Combine(Server.MapPath("~/uploads/files"), fileName);
                        var path = Server.MapPath("~/uploads/files/" + fileName);
                        uploadedFile.SaveAs(path);
                        var fs = System.IO.File.OpenRead(path);
                        FileInfo files = new FileInfo(fs.Name);
                        string full = Path.GetFullPath(path);
                        string file = Path.GetFileName(full);
                        var ext = Path.GetExtension(path);
                        if (ext == ".txt")
                        {
                            using (StreamReader sr = new StreamReader(File))
                            {
                                string line = sr.ReadToEnd();
                                string[] split = line.Split(',');
                                model.Numbers = ConvertStringArrayToString(split);

                                List<string> lst = new List<string>(split);
                                var num = _genservice.Numbers(lst, model.countryCode);

                                if (num.Contains("Please Correct"))
                                {

                                    TempData["line"] = string.Join(" ", num.ToArray()); ;
                                    return View(model);
                                }
                                model.BatchCount = split.Count();
                                ImportEntity import = new ImportEntity();
                                import.BatchName = model.BatchName;
                                import.BatchCount = model.BatchCount;
                                import.countryCode = model.countryCode;
                                import.Numbers = String.Join(",", num);
                                import.UserId = _workerContext.CurrentUserPersonalInformation.UserId;
                                var returnedEntity = _genservice.saveBulk(import);

                                foreach (string imNum in num.Distinct())
                                {
                                    _genservice.SaveImported(imNum, returnedEntity.Id, returnedEntity.UserId);

                                    _genservice.SavePhonebook(returnedEntity.Id, null, imNum, returnedEntity.countryCode, null, returnedEntity.UserId);
                                }

                                TempData["success"] = "Sucessfully Uploaded";
                            }
                        }
                        if (ext == ".xlsx")
                        {
                            Excel.Application xlApp = new Excel.Application();
                            Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(Path.GetFullPath(File));
                            Excel.Worksheet xlWorksheet = (Excel.Worksheet)xlWorkbook.Sheets.get_Item(1);
                            Excel.Range xlRange = xlWorksheet.UsedRange;
                            object[,] valueArray = (object[,])xlRange.get_Value(
                              Excel.XlRangeValueDataType.xlRangeValueDefault);
                            var numbers = _genservice.excelNumbers(xlWorksheet, xlRange);
                            if (numbers.Contains("Please Correct"))
                            {

                                TempData["line"] = string.Join(" ", numbers.ToArray()); ;
                                return View(model);
                            }
                            // Close the Workbook.
                            xlWorkbook.Close(false);

                            // Relase COM Object by decrementing the reference count.
                            Marshal.ReleaseComObject(xlWorkbook);

                            // Close Excel application.
                            xlApp.Quit();

                            // Release COM object.
                            Marshal.FinalReleaseComObject(xlApp);
                            model.BatchCount = numbers.Count();
                            ImportEntity import = new ImportEntity();
                            import.BatchName = model.BatchName;
                            import.BatchCount = model.BatchCount;
                            import.countryCode = model.countryCode;
                            import.Numbers = String.Join(",", numbers);
                            import.UserId = _workerContext.CurrentUserPersonalInformation.UserId;
                            var returnEntity = _genservice.saveBulk(import);

                            foreach (string imNum in numbers.Distinct())
                            {
                                _genservice.SaveImported(imNum, returnEntity.Id, returnEntity.UserId);
                                _genservice.SavePhonebook(returnEntity.Id, null, imNum, returnEntity.countryCode, null, returnEntity.UserId);
                            }

                            TempData["success"] = "Sucessfully Uploaded";
                        }
                    }
                    else
                    {
                        if (uploadedFile == null)
                        {
                            TempData["upload"] = "Please Select a file to upload";
                        }
                        if (!string.IsNullOrEmpty(existingbook))
                        {
                            TempData["upload"] = string.Format("Please select another name.A phone book with the same name '{0}' is already existing", existingbook);
                        }
                    }
                }
                else if (model.Radiomergenew == true)
                {
                    if (uploadedFile != null)
                    {
                        if (!string.IsNullOrEmpty(model.mergeString))
                        {
                            var numbers = _genservice.GetBatchNumbersWithUserId(_workerContext.CurrentUserPersonalInformation.UserId, model.mergeString);
                            List<string> mergeWith = numbers.Numbers.Split(',').ToList<string>();
                            var fileName = Path.GetFileName(uploadedFile.FileName);
                            var File = System.Web.Hosting.HostingEnvironment.MapPath("~/uploads/files/" + fileName);
                            //var path = Path.Combine(Server.MapPath("~/uploads/files"), fileName);
                            var path = Server.MapPath("~/uploads/files/" + fileName);
                            uploadedFile.SaveAs(path);
                            var fs = System.IO.File.OpenRead(path);
                            FileInfo files = new FileInfo(fs.Name);
                            string full = Path.GetFullPath(path);
                            string file = Path.GetFileName(full);
                            var ext = Path.GetExtension(path);
                            if (ext == ".txt")
                            {
                                using (StreamReader sr = new StreamReader(File))
                                {
                                    string line = sr.ReadToEnd();
                                    string[] split = line.Split(',');
                                    model.Numbers = ConvertStringArrayToString(split);
                                    List<string> lst = new List<string>(split);
                                    var num = _genservice.Numbers(lst, model.countryCode);

                                    if (num.Contains("Please Correct"))
                                    {

                                        TempData["line"] = string.Join(" ", num.ToArray());

                                        return View(model);
                                    }
                                    foreach (string merge in mergeWith)
                                    {
                                        num.Add(merge);
                                    }
                                    model.BatchCount = num.Count();
                                    //ImportEntity import = new ImportEntity();
                                    //numbers.BatchName = model.BatchName;
                                    numbers.BatchCount = model.BatchCount;
                                    //numbers.countryCode = model.countryCode;
                                    numbers.Numbers = String.Join(",", num.Distinct());
                                    //numbers.UserId = _workerContext.CurrentUserPersonalInformation.UserId;
                                    var objectvalue = _genservice.saveBulk(numbers);

                                    foreach (string imNum in num.Distinct())
                                    {
                                        _genservice.SaveImported(imNum, objectvalue.Id, objectvalue.UserId);

                                        _genservice.SavePhonebook(objectvalue.Id, null, imNum, objectvalue.countryCode, null, objectvalue.UserId);
                                    }
                                    TempData["success"] = "Sucessfully Uploaded";
                                }
                            }

                            if (ext == ".xlsx")
                            {
                                var excelNumbers = _genservice.GetBatchNumbersWithUserId(_workerContext.CurrentUserPersonalInformation.UserId, model.mergeString);
                                List<string> EmergeWith = excelNumbers.Numbers.Split(',').ToList<string>();
                                Excel.Application xlApp = new Excel.Application();
                                Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(Path.GetFullPath(File));
                                Excel.Worksheet xlWorksheet = (Excel.Worksheet)xlWorkbook.Sheets.get_Item(1);
                                Excel.Range xlRange = xlWorksheet.UsedRange;
                                object[,] valueArray = (object[,])xlRange.get_Value(
                                  Excel.XlRangeValueDataType.xlRangeValueDefault);
                                var Enumbers = _genservice.excelNumbers(xlWorksheet, xlRange);
                                if (Enumbers.Contains("Please Correct"))
                                {

                                    TempData["line"] = string.Join(" ", Enumbers.ToArray()); ;
                                    return View(model);
                                }

                                foreach (string Emerge in EmergeWith)
                                {
                                    Enumbers.Add(Emerge);
                                }

                                // Close the Workbook.
                                xlWorkbook.Close(false);

                                // Relase COM Object by decrementing the reference count.
                                Marshal.ReleaseComObject(xlWorkbook);

                                // Close Excel application.
                                xlApp.Quit();

                                // Release COM object.
                                Marshal.FinalReleaseComObject(xlApp);
                                model.BatchCount = Enumbers.Count();
                                //ImportEntity import = new ImportEntity();
                                //excelNumbers.BatchName = model.BatchName;
                                excelNumbers.BatchCount = model.BatchCount;
                                //excelNumbers.countryCode = model.countryCode;
                                excelNumbers.Numbers = String.Join(",", Enumbers.Distinct());
                                //excelNumbers.UserId = _workerContext.CurrentUserPersonalInformation.UserId;
                                var objval = _genservice.saveBulk(excelNumbers);

                                foreach (string imNum in Enumbers.Distinct())
                                {
                                    _genservice.SaveImported(imNum, objval.Id, objval.UserId);
                                    _genservice.SavePhonebook(objval.Id, null, imNum, objval.countryCode, null, objval.UserId);

                                }
                                TempData["success"] = "Sucessfully Uploaded";
                            }
                        }
                    }

                }
                var importname = _genservice.GetImportEntityPerUserID(_workerContext.CurrentUserPersonalInformation.UserId);
                model.mergeStringtype.Add(new SelectListItem() { Text = "-Select-", Value = "-1", Selected = (model.mergeString == null) });
                foreach (ImportEntity s in importname)
                    model.mergeStringtype.Add(new SelectListItem() { Text = s.BatchName, Value = s.BatchName, Selected = (s.BatchName == model.mergeString) });
                return View(model);
            }
            else return RedirectToAction("Default", "Default");
        }
 private IEnumerable<ImportEntity> MapMasterDataList(Recordset rs)
 {
     rs.MoveFirst();
     while (!(rs.EoF))
     {
         var imports = new ImportEntity();
         var list = new List<string>();
         for (int i = 0; i < rs.Fields.Count; i++)
         {
             string field = rs.Fields.Item(i).Value.ToString();
             list.Add(field);
         }
         imports.Fields = list.ToArray();
         imports.MasterDataCollective = masterdataEntity;
         MasterDataList.Add(imports);
         rs.MoveNext();
     }
     return MasterDataList;
 }
        private void CheckProductStoragesPriceAndQuantites(ImportEntity importEntity)
        {
            var product           = _productService.GetProductBySku(importEntity.ProductSku);
            var productVariantGet = _productAttributeService.GetProductVariantAttributesByProductId(product.Id);

            //связываем продукт и свойство(склад)
            if (!productVariantGet.Any())
            {
                var productVariantAttribute = new ProductVariantAttribute();
                productVariantAttribute.ProductId              = product.Id;
                productVariantAttribute.ProductAttributeId     = 1; //TODO:другой способ ввода id
                productVariantAttribute.AttributeControlTypeId = 1;
                _productAttributeService.InsertProductVariantAttribute(productVariantAttribute);
            }

            var needPreselected = true;

            foreach (var entity in importEntity.Storages)
            {
                //связываем названия свойств с маппингом продуктов и свойств
                var productVariantGetForValue =
                    _productAttributeService.GetProductVariantAttributesByProductId(product.Id).FirstOrDefault();
                var productVariantValueGet =
                    _productAttributeService.GetProductVariantAttributeValues(productVariantGetForValue.Id);
                var productVariantAttr = productVariantValueGet.FirstOrDefault(x => x.Name.Equals(entity.Name));

                var isPreselected = PreSelectedUpdate(entity, ref needPreselected);
                //цена для отображения
                if (isPreselected)
                {
                    product.Price = entity.Price;
                    _productService.UpdateProduct(product);
                }
                if (productVariantAttr == null)
                {
                    var productVariantAttributeValue  = new ProductVariantAttributeValue();
                    var productVariantAttributeForMap =
                        _productAttributeService.GetProductVariantAttributesByProductId(product.Id)
                        .FirstOrDefault();
                    productVariantAttributeValue.ProductVariantAttributeId =
                        productVariantAttributeForMap != null
                            ? productVariantAttributeForMap.Id
                            : new int();
                    productVariantAttributeValue.Name          = entity.Name;
                    productVariantAttributeValue.IsPreSelected = isPreselected;

                    _productAttributeService.InsertProductVariantAttributeValue(
                        productVariantAttributeValue);
                }
                else
                {
                    productVariantAttr.IsPreSelected = PreSelectedUpdate(entity, ref needPreselected);
                    _productAttributeService.UpdateProductVariantAttributeValue(productVariantAttr);
                }



                //связываем продукт и значения свойств
                var productVariantAttributeCombinationsGet =
                    _productAttributeService.GetAllProductVariantAttributeCombinations(product.Id);

                var productVariantAttributeValueForXml = _productService.GetProductBySku(importEntity.ProductSku)
                                                         .ProductVariantAttributes.FirstOrDefault()
                                                         .ProductVariantAttributeValues.FirstOrDefault(x => x.Name.Equals(entity.Name));
                var productVariantAttributeCombination = productVariantAttributeCombinationsGet.FirstOrDefault(
                    x => x.Sku.Equals(entity.Name));

                if (productVariantAttributeCombination == null)
                {
                    productVariantAttributeCombination = new ProductVariantAttributeCombination();
                    var productXml = "<Attributes><ProductVariantAttribute ID='" +
                                     productVariantAttributeValueForXml.ProductVariantAttributeId +
                                     "'><ProductVariantAttributeValue><Value>" +
                                     productVariantAttributeValueForXml.Id +
                                     "</Value></ProductVariantAttributeValue></ProductVariantAttribute></Attributes>";

                    productVariantAttributeCombination.ProductId       = product.Id;
                    productVariantAttributeCombination.AttributesXml   = productXml;
                    productVariantAttributeCombination.StockQuantity   = entity.Quantity;
                    productVariantAttributeCombination.OverriddenPrice = entity.Price;
                    productVariantAttributeCombination.Sku             = entity.Name;

                    _productAttributeService.InsertProductVariantAttributeCombination(
                        productVariantAttributeCombination);
                }
                else
                {
                    productVariantAttributeCombination.StockQuantity   = entity.Quantity;
                    productVariantAttributeCombination.OverriddenPrice = entity.Price;
                    _productAttributeService.UpdateProductVariantAttributeCombination(productVariantAttributeCombination);
                }
            }
        }
示例#40
0
 public static bool AddOutlet(ImportEntity outlet)
 {
     ICustomerRet customerRet = QBFC_Core.QBAddCustomer(outlet);
     return customerRet != null;
 }