Esempio n. 1
0
 private void OpenButton_Click(object sender, EventArgs e)
 {
     OpenDialog.InitialDirectory = LastOpenPath;
     OpenDialog.FileName         = "";
     if (OpenDialog.ShowDialog() == DialogResult.OK)
     {
         LastOpenPath        = OpenDialog.FileName;
         ImportBar.Visible   = true;
         ImportLabel.Visible = true;
         List <BetterPicBox> newboxes = new List <BetterPicBox>();
         foreach (string path in OpenDialog.FileNames)
         {
             BetterPicBox pic = new BetterPicBox(null, ResizeImg(Image.FromFile(path), 128, 128, InterpolationCombo.SelectedIndex == 0 ? InterpolationMode.NearestNeighbor : InterpolationMode.HighQualityBicubic))
             {
                 Width       = 128,
                 Height      = 128,
                 SizeMode    = PictureBoxSizeMode.Zoom,
                 BorderStyle = BorderStyle.FixedSingle
             };
             Pictures.Add(pic);
             newboxes.Add(pic);
             pic.MouseClick += Pic_MouseClick;
         }
         OpenButton.Enabled = false;
         // mapify the new images in the background
         ImportProcessor.RunWorkerAsync(newboxes);
     }
 }
Esempio n. 2
0
        private static void Process(object args)
        {
            ImportProcessor ip        = new ImportProcessor();
            List <string>   arguments = new List <string>(((ActionArgs)(args)).CommandArgument.Split(';'));
            string          fileName  = Path.Combine(ImportProcessor.SharedTempPath, arguments[0]);

            arguments.RemoveAt(0);
            string controller = arguments[0];

            arguments.RemoveAt(0);
            string view = arguments[0];

            arguments.RemoveAt(0);
            string notify = arguments[0];

            arguments.RemoveAt(0);
            try
            {
                ip.Process(fileName, controller, view, notify, arguments);
            }
            finally
            {
                if (File.Exists(fileName))
                {
                    try
                    {
                        File.Delete(fileName);
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }
Esempio n. 3
0
        protected void HandleImport(IDataMap map, DefaultLogger l)
        {
            ImportProcessor p = new ImportProcessor(map, l);

            p.Process();
            txtMessage.Text = l.GetLog();

            WriteLogs(l);
        }
Esempio n. 4
0
 public RecoveryActor(ImportProcessor importProcessor,
                      BatchProcessor batchProcessor,
                      TaskProcessor taskProcessor,
                      List <TaskActor> taskActors)
 {
     _importProcessor = importProcessor;
     _batchProcessor  = batchProcessor;
     _taskProcessor   = taskProcessor;
     _taskActors      = taskActors;
 }
Esempio n. 5
0
        public IActionResult PostFile()
        {
            IFormFile       file   = Request.Form.Files[0];
            Stream          stream = file.OpenReadStream();
            DataTable       dt     = GetDataTable(stream);
            ImportProcessor import = new ImportProcessor(dt, context, 1, file.FileName);

            import.SaveToDataBase();
            return(Ok("OK"));
        }
        public void StartProcessing()
        {
            string ftpPath = Properties.Settings.Default.FtpFolderPath;
            string processedPath = Properties.Settings.Default.ProcessedFolderPath;

            var databaseAccess = new DatabaseAccess(Properties.Settings.Default.DatabaseConnectionString);
            var parseManager = GetParseManager();

            var importProcessor = new ImportProcessor(databaseAccess, parseManager, ftpPath, processedPath);
            importProcessor.ProcessImport();
        }
Esempio n. 7
0
 private void button2_Click(object sender, EventArgs e)
 {
     if (_importProcessor == null || _importProcessor.IsStopped)
     {
         StartProcess(_importProcessor = new ImportProcessor(), sender as Button);
     }
     else
     {
         StopProcess(_importProcessor, sender as Button);
     }
 }
        public void StartProcessing()
        {
            string ftpPath       = Properties.Settings.Default.FtpFolderPath;
            string processedPath = Properties.Settings.Default.ProcessedFolderPath;

            var databaseAccess = new DatabaseAccess(Properties.Settings.Default.DatabaseConnectionString);
            var parseManager   = GetParseManager();

            var importProcessor = new ImportProcessor(databaseAccess, parseManager, ftpPath, processedPath);

            importProcessor.ProcessImport();
        }
Esempio n. 9
0
 public BrokerActor(ImportProcessor importProcessor,
                    BrokerTransactionScraper brokerTransactionScraper,
                    BatchProcessor batchProcessor,
                    TaskProcessor taskProcessor,
                    IConfiguration configuration)
 {
     _importProcessor          = importProcessor;
     _brokerTransactionScraper = brokerTransactionScraper;
     _configuration            = configuration;
     _batchProcessor           = batchProcessor;
     _taskProcessor            = taskProcessor;
 }
Esempio n. 10
0
        private void ImportProcessor_DoWork(object sender, DoWorkEventArgs e)
        {
            int prog = 0;

            foreach (BetterPicBox pic in (List <BetterPicBox>)e.Argument)
            {
                pic.MainImage = Mapify(pic.HoverImage);
                prog++;
                ImportProcessor.ReportProgress(prog * 100 / OpenDialog.FileNames.Length);
            }
            PicsToAdd = (List <BetterPicBox>)e.Argument;
        }
 public BrokerTableScraper(List <Import> imports,
                           BrokerTransactionBuilder brokerTransactionBuilder,
                           BrokerTransactionProcessor brokerTransactionProcessor,
                           BrokerTransactionSimulator brokerTransactionSimulator,
                           BrokerTabNavigator brokerTabNavigator,
                           ImportProcessor importProcessor,
                           IWebDriver webDriver)
 {
     _webDriver = webDriver;
     _imports   = imports;
     _brokerTransactionBuilder   = brokerTransactionBuilder;
     _brokerTransactionProcessor = brokerTransactionProcessor;
     _brokerTransactionSimulator = brokerTransactionSimulator;
     _brokerTabNavigator         = brokerTabNavigator;
     _importProcessor            = importProcessor;
 }
Esempio n. 12
0
        public void Configure(IWizard wizard)
        {
            _wizard = wizard;
              _wizard.NextEnabled = false;
              _import = _wizard.ImportProcessor;
              _import.ActionComplete += _progress_ActionComplete;
              _import.ProgressChanged += _progress_ProgressChanged;
              btnCancel.Visible = _import is ICancelableProgressReporter;
              btnCancel.Enabled = true;
              btnCancel.Text = "Cancel";

              var thread = new Thread(o => this.MethodInvoke(_import));
              _startTime = DateTime.Now;
              thread.Start();
              _clock.Enabled = true;
              countWorker.RunWorkerAsync();
        }
Esempio n. 13
0
        public void Configure(IWizard wizard)
        {
            _wizard                  = wizard;
            _wizard.NextEnabled      = false;
            _import                  = _wizard.ImportProcessor;
            _import.ActionComplete  += _progress_ActionComplete;
            _import.ProgressChanged += _progress_ProgressChanged;
            btnCancel.Visible        = _import is ICancelableProgressReporter;
            btnCancel.Enabled        = true;
            btnCancel.Text           = "Cancel";

            var thread = new Thread(o => this.MethodInvoke(_import));

            _startTime = DateTime.Now;
            thread.Start();
            _clock.Enabled = true;
            countWorker.RunWorkerAsync();
        }
Esempio n. 14
0
        private ServiceThread GetServiceThread()
        {
            ServiceThread result = null;

            switch (ServiceName)
            {
            case "TSEmailProcessor": result = new ServiceThreadPool <EmailProcessor>("EmailProcessor"); break;

            case "TSEmailSender": result = new ServiceThreadPool <EmailSender>("EmailSender"); break;

            case "TSSlaProcessor": result = new SlaProcessor(); break;

            case "TSSlaCalculator": result = new SlaCalculator(); break;

            case "TSIndexer": result = new ServiceThreadPool <Indexer>("Indexer"); break;

            case "TSIndexRebuilder": result = new ServiceThreadPool <Indexer>("Indexer"); break;

            case "TSCrmPool": result = new CrmPool(SystemUser.CRM); break;

            case "TSReminderProcessor": result = new ReminderProcessor(); break;

            case "TSImportProcessor": result = new ImportProcessor(); break;

            case "TSWebHooksProcessor": result = new WebHooksPool(SystemUser.CRM); break;

            case "TSCustomerInsights": result = new CustomerInsightsProcessor(); break;

            case "TSReportSender": result = new ServiceThreadPool <ReportSender>("ReportSender"); break;

            case "TokTranscoder": result = new ServiceThreadPool <TokTranscoder>("TokTranscoder"); break;

            case "TSTaskProcessor": result = new ServiceThreadPool <TaskProcessor>("TaskProcessor"); break;

            default: result = null; break;
            }

            return(result);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="WizardSteps"/> class.
        /// </summary>
        /// <param name="dataTypeModel">The data type model.</param>
        /// <exception cref="ApplicationException">Unrecognized Medicare Provider Charge import type</exception>
        public WizardSteps(DataTypeModel dataTypeModel)
        {
            Context.SelectedDataType = dataTypeModel;
            Context.Steps            = this;


            // Create a group of wizard steps giving the ViewModel a function to import each line of the file
            if (dataTypeModel.Target.Guid == Constants.WingTargetGuidAsGuid)
            {
                var importer = new ImportProcessor(Context);

                AddGroupOfSteps(new StepGroup(dataTypeModel.DataTypeName)
                {
                    IsCurrent = true
                },
                                CreateSteps(importer, importer.HeaderLine, importer.LineFunction));
            }
            else
            {
                throw new ApplicationException("Unrecognized Medicare Provider Charge import type");
            }
        }
Esempio n. 16
0
        public WizardSteps(DataTypeModel dataTypeModel, int?datasetId)
        {
            Context.SelectedDataType  = dataTypeModel;
            Context.ExistingDatasetId = datasetId;
            Context.Steps             = this;


            // Create a group of wizard steps giving the ViewModel a function to import each line of the file
            if (dataTypeModel.Target.Guid == HEDISConstants.WingGuidAsGuid)
            {
                var importer = new ImportProcessor(Context);

                AddGroupOfSteps(new StepGroup(dataTypeModel.DataTypeName)
                {
                    IsCurrent = true
                },
                                CreateSteps(importer, importer.HeaderLine, importer.LineFunction));
            }
            else
            {
                throw new ApplicationException("Unrecognized NH-CAHPS Survey Results import type");
            }
        }
        internal static void Launch(IDesktopWindow parent, IEnumerable <string> paths)
        {
            try
            {
                if (_activeProcessor != null)
                {
                    parent.ShowMessageBox(SR.MessageImportAlreadyRunning, MessageBoxActions.Ok);
                    return;
                }

                if (!LocalDataStoreActivityMonitor.IsConnected)
                {
                    parent.ShowMessageBox(SR.MessageLocalDataStoreServiceMustBeRunning, MessageBoxActions.Ok);
                    return;
                }

                if (null == CollectionUtils.FirstElement(GetFiles(paths)))
                {
                    parent.ShowMessageBox(SR.MessageNothingToImport, MessageBoxActions.Ok);
                    return;
                }

                ImportFromBitmapComponent component = new ImportFromBitmapComponent();
                if (ApplicationComponentExitCode.Accepted != LaunchAsDialog(parent, component, SR.TitleImportNonDicom))
                {
                    return;
                }

                _activeProcessor = new ImportProcessor(component, paths);
                _activeProcessor.Run();
            }
            catch (Exception e)
            {
                ExceptionHandler.Report(e, parent);
            }
        }
        public ActionResult RunImport(string id, string db, string importType)
        {
            var currentDB = (!string.IsNullOrWhiteSpace(db))
                ? Configuration.Factory.GetDatabase(db)
                : Context.ContentDatabase;

            Item importItem = null;

            if (ID.IsID(id))
            {
                importItem = currentDB.GetItem(ID.Parse(id));
            }

            //check import item
            if (importItem == null)
            {
                return(GetResult("", "Import item is null"));
            }

            //check handler assembly
            TextField ha = importItem.Fields["Handler Assembly"];

            if (ha == null || string.IsNullOrWhiteSpace(ha.Value))
            {
                return(GetResult("", "Import handler assembly is not defined"));
            }

            //check handler class
            TextField hc = importItem.Fields["Handler Class"];

            if (hc == null || string.IsNullOrWhiteSpace(hc.Value))
            {
                return(GetResult("", "Import handler class is not defined"));
            }

            //check db
            if (currentDB == null)
            {
                return(GetResult("", "Database is null"));
            }

            //check conn str
            Field connStrField = importItem.Fields["Connection String Name"];

            if (connStrField == null)
            {
                return(GetResult("", "Connection String Name is not set"));
            }

            var connStr  = "";
            var connName = connStrField.Value;

            if (string.IsNullOrWhiteSpace(connName))
            {
                return(GetResult("", "Connection String Name is empty"));
            }

            foreach (ConnectionStringSettings c in ConfigurationManager.ConnectionStrings)
            {
                if (!c.Name.ToLower().Equals(connName.ToLower()))
                {
                    continue;
                }

                connStr = c.ConnectionString;
                break;
            }

            if (string.IsNullOrWhiteSpace(connStr))
            {
                return(GetResult("", "Connection string is empty"));
            }

            //try to instantiate object
            IDataMap map = null;
            ILogger  l   = new DefaultLogger();

            try
            {
                map = (IDataMap)Reflection.ReflectionUtil.CreateObject(
                    ha.Value,
                    hc.Value,
                    new object[] { currentDB, connStr, importItem, l }
                    );
            }
            catch (FileNotFoundException fnfe)
            {
                var n = fnfe.Message;
                return(GetResult("", $"the binary {ha.Value} could not be found"));
            }

            //run process
            if (map == null)
            {
                var dbName         = currentDB?.Name;
                var importItemName = importItem?.Name;
                var loggerType     = l.GetType().ToString();

                return(GetResult("", $"the data map provided could not be instantiated. Database:{dbName}, Connection String: {connStr}, Import Item: {importItemName}, Logger: {loggerType}"));
            }

            string handleName = $"{importType}Import-{DateTime.UtcNow:yyyy/MM/dd-hh:mm}";

            var importService = new ImportProcessor(map, l);

            var jobOptions = new DefaultJobOptions(
                handleName,
                importItem.DisplayName,
                Context.Site.Name,
                importService,
                "Process",
                new object[] { });

            JobManager.Start(jobOptions);

            return(GetResult(handleName, ""));
        }
Esempio n. 19
0
 public BrokerTransactionScraper(ITradeasRepository tradeasRepository,
                                 ImportProcessor importProcessor)
 {
     _tradeasRepository = tradeasRepository;
     _importProcessor   = importProcessor;
 }
Esempio n. 20
0
 public IImportPipelineBuilder UseProcessor(ImportProcessor importProcessor)
 {
     Processors.Add(importProcessor);
     return(this);
 }
Esempio n. 21
0
        protected void HandleImport(IDataMap map, ILogger l)
        {
            ImportProcessor p = new ImportProcessor(map);

            p.Process();
        }
Esempio n. 22
0
        static void Main(string[] args)
        {
            //param 0 = Assembly Name
            string assemblyName = GetArg(args, "-a");

            if (string.IsNullOrEmpty(assemblyName))
            {
                Console.WriteLine("You need to specify an assembly");
                Environment.Exit((int)ExitCode.NullAssembly);
            }

            //param 1 = Class Name
            string className = GetArg(args, "-cn");

            if (string.IsNullOrEmpty(className))
            {
                Console.WriteLine("You need to specify a class");
                Environment.Exit((int)ExitCode.NullClass);
            }

            //param 2 = database name
            string   dbName = GetArg(args, "-d");
            Database scDB   = null;

            try {
                scDB = Sitecore.Configuration.Factory.GetDatabase(dbName);
            } catch (InvalidOperationException ioe) {
                Console.WriteLine("You don't have a connection string for this database in your exe.config");
                Environment.Exit((int)ExitCode.NullDatabase);
            }
            if (scDB == null)
            {
                Console.WriteLine("You need to specify a database");
                Environment.Exit((int)ExitCode.NullDatabase);
            }

            //param 3 = connection string name
            string connStrName = GetArg(args, "-cs");
            string connStr     = string.Empty;

            try {
                connStr = ConfigurationManager.ConnectionStrings[connStrName].ConnectionString;
            } catch (InvalidOperationException ioe) {
                Console.WriteLine("You don't have a connection string for this database in your exe.config");
                Environment.Exit((int)ExitCode.NullDatabase);
            }
            if (string.IsNullOrEmpty(connStr))
            {
                Console.WriteLine("You need to specify a connection string");
                Environment.Exit((int)ExitCode.NullConnectionString);
            }

            //param 4 = import definition item id
            string idStr = GetArg(args, "-i");

            if (string.IsNullOrEmpty(idStr))
            {
                Console.WriteLine("You need to specify an import definition item ID");
                Environment.Exit((int)ExitCode.NullImportItem);
            }
            Item importDefItem = null;

            if (ID.IsID(idStr))
            {
                importDefItem = scDB.GetItem(ID.Parse(idStr));
            }
            else
            {
                Console.WriteLine("The import definition item ID you specified was not an item id");
                Environment.Exit((int)ExitCode.NullImportItem);
            }
            if (importDefItem == null)
            {
                Console.WriteLine("The import definition item ID you specified returned a null item");
                Environment.Exit((int)ExitCode.NullImportItem);
            }

            using (new SecurityDisabler()) {
                DefaultLogger l   = new DefaultLogger();
                IDataMap      map = (IDataMap)Sitecore.Reflection.ReflectionUtil.CreateObject(
                    assemblyName,
                    className,
                    new object[] { scDB, connStr, importDefItem, l }
                    );
                if (map == null)
                {
                    Console.WriteLine("The import definition map could not be instantiated");
                    Environment.Exit((int)ExitCode.NullImportInstantation);
                }
                ImportProcessor p = new ImportProcessor(map, l);
                p.Process();
                Console.WriteLine(l.GetLog());
            }
        }
 private static void OnProcessingComplete()
 {
     _activeProcessor = null;
 }
Esempio n. 24
0
        ActionResult IDataController.Execute(string controller, string view, ActionArgs args)
        {
            ActionResult result = new ActionResult();

            SelectView(controller, view);
            try
            {
                IActionHandler handler = _config.CreateActionHandler();
                if (_config.PlugIn != null)
                {
                    _config.PlugIn.PreProcessArguments(args, result, CreateViewPage());
                }
                if (args.SqlCommandType != CommandConfigurationType.None)
                {
                    using (DbConnection connection = CreateConnection())
                    {
                        ExecutePreActionCommands(args, result, connection);
                        if (handler != null)
                        {
                            handler.BeforeSqlAction(args, result);
                        }
                        if ((result.Errors.Count == 0) && !(result.Canceled))
                        {
                            DbCommand command = CreateCommand(connection, args);
                            if ((args.SelectedValues != null) && (((args.LastCommandName == "BatchEdit") && (args.CommandName == "Update")) || ((args.CommandName == "Delete") && (args.SelectedValues.Length > 1))))
                            {
                                ViewPage page = CreateViewPage();
                                PopulatePageFields(page);
                                string originalCommandText = command.CommandText;
                                foreach (string sv in args.SelectedValues)
                                {
                                    string[] key      = sv.Split(',');
                                    int      keyIndex = 0;
                                    foreach (FieldValue v in args.Values)
                                    {
                                        DataField field = page.FindField(v.Name);
                                        if (field != null)
                                        {
                                            if (!(field.IsPrimaryKey))
                                            {
                                                v.Modified = true;
                                            }
                                            else
                                            if (v.Name == field.Name)
                                            {
                                                v.OldValue = key[keyIndex];
                                                v.Modified = false;
                                                keyIndex++;
                                            }
                                        }
                                    }
                                    ConfigureCommand(command, null, args.SqlCommandType, args.Values);
                                    result.RowsAffected = (result.RowsAffected + TransactionManager.ExecuteNonQuery(command));
                                    if (handler != null)
                                    {
                                        handler.AfterSqlAction(args, result);
                                    }
                                    command.CommandText = originalCommandText;
                                    command.Parameters.Clear();
                                    if (_config.PlugIn != null)
                                    {
                                        _config.PlugIn.ProcessArguments(args, result, page);
                                    }
                                }
                            }
                            else
                            {
                                if (ConfigureCommand(command, null, args.SqlCommandType, args.Values))
                                {
                                    result.RowsAffected = TransactionManager.ExecuteNonQuery(args, result, CreateViewPage(), command);
                                    if (result.RowsAffected == 0)
                                    {
                                        result.RowNotFound = true;
                                        result.Errors.Add(Localizer.Replace("RecordChangedByAnotherUser", "The record has been changed by another user."));
                                    }
                                    else
                                    {
                                        ExecutePostActionCommands(args, result, connection);
                                    }
                                }
                                if (handler != null)
                                {
                                    handler.AfterSqlAction(args, result);
                                }
                                if (_config.PlugIn != null)
                                {
                                    _config.PlugIn.ProcessArguments(args, result, CreateViewPage());
                                }
                            }
                        }
                    }
                }
                else
                if (args.CommandName.StartsWith("Export"))
                {
                    ExecuteDataExport(args, result);
                }
                else
                if (args.CommandName.Equals("PopulateDynamicLookups"))
                {
                    PopulateDynamicLookups(args, result);
                }
                else
                if (args.CommandName.Equals("ProcessImportFile"))
                {
                    ImportProcessor.Execute(args);
                }
                else
                if (args.CommandName.Equals("Execute"))
                {
                    using (DbConnection connection = CreateConnection())
                    {
                        DbCommand command = CreateCommand(connection, args);
                        TransactionManager.ExecuteNonQuery(command);
                    }
                }
                else
                if (handler != null)
                {
                    handler.ExecuteAction(args, result);
                    ((BusinessRules)(handler)).ProcessSpecialActions(args, result);
                }
                else
                {
                    CreateBusinessRules().ProcessSpecialActions(args, result);
                }
            }
            catch (Exception ex)
            {
                if (ex.GetType() == typeof(System.Reflection.TargetInvocationException))
                {
                    ex = ex.InnerException;
                }
                HandleException(ex, args, result);
            }
            return(result);
        }
 public BrokerTransactionScraper(IBrokerTransactionRepository brokerTransactionRepository,
                                 ImportProcessor importProcessor)
 {
     _brokerTransactionRepository = brokerTransactionRepository;
     _importProcessor             = importProcessor;
 }
Esempio n. 26
0
        void IHttpHandler.ProcessRequest(HttpContext context)
        {
            string parentId   = context.Request.Params["parentId"];
            string controller = context.Request.Params["controller"];
            string view       = context.Request.Params["view"];

            if (String.IsNullOrEmpty(parentId) || (String.IsNullOrEmpty(controller) || String.IsNullOrEmpty(view)))
            {
                throw new HttpException(404, String.Empty);
            }
            string        methodName = null;
            string        data       = null;
            StringBuilder errors     = new StringBuilder();

            if (context.Request.HttpMethod == "GET")
            {
                methodName = "_initImportUpload";
            }
            else
            if ((context.Request.HttpMethod == "POST") && (context.Request.Files.Count > 0))
            {
                methodName = "_finishImportUpload";
                string tempFileName = null;
                try
                {
                    // save file to the temporary folder
                    string   fileName        = context.Request.Files[0].FileName;
                    string   extension       = Path.GetExtension(fileName).ToLower();
                    string[] validExtensions = new string[] {
                        ".csv",
                        ".xls",
                        ".xlsx"
                    };
                    if (Array.IndexOf(validExtensions, extension) == -1)
                    {
                        throw new Exception(String.Format("The format of file <b>{0}</b> is not supported.", Path.GetFileName(fileName)));
                    }
                    tempFileName = Path.Combine(ImportProcessor.SharedTempPath, (Guid.NewGuid().ToString() + extension));
                    context.Request.Files[0].SaveAs(tempFileName);
                    // return response to the client
                    ImportProcessor ip = new ImportProcessor();
                    int             numberOfRecords       = ip.CountRecords(tempFileName);
                    string          availableImportFields = ip.CreateListOfAvailableFields(controller, view);
                    string          fieldMap = ip.CreateInitialFieldMap(tempFileName, controller, view);
                    data = String.Format(@"<form>
<input id=""NumberOfRecords"" type=""hidden"" value=""{0}""/>
<input id=""AvailableImportFields"" type=""hidden"" value=""{1}""/>
<input id=""FieldMap"" type=""hidden"" value=""{2}""/><input id=""FileName"" type=""hidden"" value=""{3}""/>
</form>", numberOfRecords, HttpUtility.HtmlAttributeEncode(availableImportFields), HttpUtility.HtmlAttributeEncode(fieldMap), Path.GetFileName(tempFileName));
                }
                catch (Exception error)
                {
                    while (error != null)
                    {
                        errors.AppendLine(error.Message);
                        error = error.InnerException;
                    }
                    data = String.Format("<form><input type=\"hidden\" id=\"Errors\" value=\"{0}\"/>", HttpUtility.HtmlAttributeEncode(errors.ToString()));
                    try
                    {
                        if (File.Exists(tempFileName))
                        {
                            File.Delete(tempFileName);
                        }
                    }
                    finally
                    {
                        // release resources here
                    }
                }
            }
            else
            {
                throw new HttpException(404, String.Empty);
            }
            // format response and send it to the client
            string responseTemplate = @"<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"">
<html xmlns=""http://www.w3.org/1999/xhtml""><head></head><body onload=""if (parent && parent.window.$find)parent.window.$find('{0}').{1}(document)"">{2}</body></html>";

            context.Response.ContentType = "text/html";
            context.Response.Write(String.Format(responseTemplate, parentId, methodName, data));
        }
Esempio n. 27
0
        public static void Running(Rules_Test rule)
        {
            LoggerFactory.Instance.Logger_Info("开始测试:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "CGT.Travel.Test");
            //总共需要的数据条数
            int TicketNum = Convert.ToInt32(rule.UserNum) * Convert.ToInt32(rule.TicketNum);
            List <BasicData_Test> BasicData_TestList = new BasicData_TestRep().GetBasicData_TestList(TicketNum);

            #region  除本次数据

            string Ids = "";
            foreach (var item in BasicData_TestList)
            {
                Ids = item.Id + ",";
            }
            if (!string.IsNullOrWhiteSpace(Ids))
            {
                Ids = Ids.Substring(0, Ids.Length - 1);
                new BasicData_TestRep().DeleteBasicData_TestList(Ids);
                LoggerFactory.Instance.Logger_Info("删除数据集合:" + JsonConvert.SerializeObject(BasicData_TestList), "CGT.Travel.Test");
            }

            #endregion

            #region 设置验证总次数

            int forNum = 0;
            if (BasicData_TestList.Count < rule.TicketNum)
            {
                forNum = 1;
            }
            else if (BasicData_TestList.Count % rule.TicketNum == 0)
            {
                forNum = BasicData_TestList.Count / Convert.ToInt32(rule.UserNum);
            }
            else
            {
                forNum = (BasicData_TestList.Count / Convert.ToInt32(rule.UserNum)) + 1;
            }

            #endregion

            #region 循环请求方伟导入

            for (int r = 0; r < forNum; r++)
            {
                #region 导入接口参数组织

                BasicData_Test[] List;
                if (forNum == 1)
                {
                    List = new BasicData_Test[BasicData_TestList.Count];
                    BasicData_TestList.CopyTo(0, List, 0, BasicData_TestList.Count);
                }
                else if (r < forNum - 1)
                {
                    List = new BasicData_Test[Convert.ToInt32(rule.UserNum)];
                    BasicData_TestList.CopyTo(r * Convert.ToInt32(rule.UserNum), List, 0, Convert.ToInt32(rule.UserNum));
                }
                else
                {
                    List = new BasicData_Test[BasicData_TestList.Count % Convert.ToInt32(rule.UserNum)];
                    BasicData_TestList.CopyTo(r * Convert.ToInt32(rule.UserNum), List, 0, BasicData_TestList.Count % Convert.ToInt32(rule.UserNum));
                }

                List <BasicData_Test> datalist = List.ToList <BasicData_Test>();

                List <string> titileList = new List <string>()
                {
                    "票面价", "订单金额", "起飞日期", "出发机场三字码", "到达机场三字码", "航班号", "舱位", "乘客姓名", "票号", "出票日期", "PNR", "保理企业"
                };

                List <string> keyList = new List <string>()
                {
                    "TicketPrice", "OrderAmount", "DepartureTime", "DepartCode", "ArriveCode", "FlightNo", "Cabin", "PersonName", "TicketNum", "TicketTime", "PNR", "Enterprise"
                };

                string MerchantCode  = ""; //融宝商户号
                string PayCenterCode = ""; //分销商Code
                string PayCenterName = ""; //分销商名称
                List <ManageExcelModel> ExcelList = new List <ManageExcelModel>();
                foreach (var item in datalist)
                {
                    ManageExcelModel excel = new ManageExcelModel()
                    {
                        ArriveCode    = item.ArrCode,
                        Cabin         = item.Cabin,
                        DepartCode    = item.DepCode,
                        DepartureTime = Convert.ToDateTime(item.StratDate),
                        Enterprise    = item.EnterpriseName + "|" + item.EnterpriseId.ToString(),
                        FlightNo      = item.FlightNo,
                        OrderAmount   = Convert.ToDecimal(item.OrderPrice),
                        TicketTime    = Convert.ToDateTime(item.TicketDate),
                        TicketPrice   = Convert.ToDecimal(item.TicketPrice),
                        TicketNum     = item.TicketNo,
                        PNR           = item.PNR,
                        PersonName    = item.PersonName
                    };
                    ExcelList.Add(excel);
                    PayCenterCode = item.PayCenterCode;
                    PayCenterName = item.PayCenterName;
                    MerchantCode  = item.MerchantCode;
                }

                byte[] str = new ExeclHelper(new HostingEnvironment()
                {
                    WebRootPath = "C://"
                }).ExcelExport <ManageExcelModel>(ExcelList, titileList, keyList);

                #endregion

                //声明一个线程请求导入接口
                System.Threading.Tasks.Task task = new System.Threading.Tasks.Task(() =>
                {
                    var Result = new ImportProcessor(str, PayCenterCode, PayCenterName, MerchantCode).Execute();//调用导入接口

                    if (Result.Success)
                    {
                        LoggerFactory.Instance.Logger_Info("导入成功:" + Result.Message, "CGT.Travel.Test");
                    }
                    else
                    {
                        LoggerFactory.Instance.Logger_Info("导入失败:" + Result.Message, "CGT.Travel.Test");
                    }
                });
                task.Start();
            }

            #endregion
        }