Esempio n. 1
0
        public void Build()
        {
            CodeEditor.DebugFlag       = true;
            this.resourceFactoryEditor = new CodeEditor();
            this.resourceFactoryEditor.Load(Path.Combine(this.OutputDir, "Generated", "ResourceFactory.cs"));
            this.resourceFactoryProfileBlock = this.resourceFactoryEditor.Blocks.Find("Profile");
            this.resourceFactoryProfileBlock.Clear();

            if (Directory.Exists(this.OutputDir) == false)
            {
                Directory.CreateDirectory(this.OutputDir);
            }

            if (this.CleanFlag)
            {
                this.fc = new FileCleaner();
                this.fc.Add(Path.Combine(this.OutputDir, "Generated"));
            }

            this.BuildReferences();
            this.BuildLocalCodeSystems();
            this.BuildCodeSystems();
            this.BuildValueSets();
            this.BuildFragments();
            this.SaveAll();

            this.fc?.Dispose();
        }
Esempio n. 2
0
        private void Extract(string inputFilePath, string outputFolderPath, CancellationToken token)
        {
            using (var fc = new FileCleaner())
            {
                var idsFilePath = Path.GetTempFileName();
                fc.AddFile(idsFilePath);

                if (token.IsCancellationRequested)
                {
                    return;
                }
                if (ExtractShell(_ExtractShellCLI, inputFilePath, idsFilePath, token))
                {
                    //如果抽壳成功,则从原始模型中把外壳提取出来另存
                    if (token.IsCancellationRequested)
                    {
                        return;
                    }
                    using (var doc = SvfDocument.LoadFrom(inputFilePath))
                    {
                        if (token.IsCancellationRequested)
                        {
                            return;
                        }
                        doc.Extract(idsFilePath, outputFolderPath, token);
                    }
                }
            }
        }
        protected bool MoveWaybill(string archFileName, string fileName, DataRow drCurrent, BaseDocumentReader documentReader)
        {
            using (var cleaner = new FileCleaner()) {
                var supplierId = Convert.ToUInt32(drCurrent[WaybillSourcesTable.colFirmCode]);
                try {
                    var addresses  = With.Connection(c => documentReader.ParseAddressIds(c, supplierId, archFileName, fileName));
                    var formatFile = documentReader.FormatOutputFile(fileName, drCurrent);

                    cleaner.Watch(fileName);
                    cleaner.Watch(formatFile);

                    foreach (var addressId in addresses)
                    {
                        var log = DocumentReceiveLog.LogNoCommit(supplierId,
                                                                 (uint)addressId,
                                                                 formatFile,
                                                                 _currentDocumentType.DocType,
                                                                 "Получен с нашего FTP");

                        _logger.InfoFormat("WaybillLanSourceHandler: обработка файла {0}", fileName);
                        documentReader.ImportDocument(log, fileName);
                        new WaybillService().Process(new[] { log }.ToList());
                    }
                }
                catch (Exception e) {
                    var message = "Не удалось отформатировать документ.\nОшибка: " + e;
                    _logger.ErrorFormat("WaybillLanSourceHandler: {0}, archfilename {1}, fileName {2}, error {3}", message, archFileName, fileName, e);
                    DocumentReceiveLog.Log(supplierId, null, fileName, _currentDocumentType.DocType, message);
                    return(false);
                }
            }

            return(true);
        }
Esempio n. 4
0
        public void DbSetup()
        {
            restore    = false;
            disposable = new CompositeDisposable();
            cleaner    = new FileCleaner();
            disposable.Add(cleaner);

            fixtureHelper = new FixtureHelper();
            disposable.Add(fixtureHelper);

            session = IntegrationSetup.Factory.OpenSession();
            disposable.Add(session);
            stateless = IntegrationSetup.Factory.OpenStatelessSession();
            disposable.Add(stateless);

            config   = IntegrationSetup.clientConfig;
            user     = session.Query <User>().FirstOrDefault();
            address  = session.Query <Address>().OrderBy(x => x.Name).FirstOrDefault();
            settings = session.Query <Settings>().FirstOrDefault();
            using (var transaction = session.BeginTransaction())
            {
                settings.WaybillDir = settings.MapPath("Waybills");
                settings.RejectDir  = settings.MapPath("Rejects");
                settings.ReportDir  = settings.MapPath("Reports");
                session.Save(settings);
                transaction.Commit();
            }
            session.Transaction.Begin();
        }
Esempio n. 5
0
        public ResourcesMaker(FileCleaner fc,
                              String resourceDir,
                              String pageDir,
                              String cacheDir)
        {
            const String fcn = "ResourcesMaker";

            Self = this;

            this.fc          = fc;
            this.resourceDir = resourceDir;
            this.pageDir     = pageDir;

            if (Directory.Exists(this.resourceDir) == false)
            {
                Directory.CreateDirectory(this.resourceDir);
            }

            if (Directory.Exists(this.pageDir) == false)
            {
                Directory.CreateDirectory(this.pageDir);
            }

            if (FhirStructureDefinitions.Self == null)
            {
                this.ConversionInfo(this.GetType().Name, fcn, $"Init'g 'FhirStructureDefinitions'");
                FhirStructureDefinitions.Create(cacheDir);
            }
        }
        private void ResetButton(object sender, MouseButtonEventArgs e)
        {
            FileCleaner.Clear();
            this.Hide();
            MainWindow mainWindow = new MainWindow();

            mainWindow.Show();
        }
 public FocusMapMaker(FileCleaner fc,
                      ResourceMap map,
                      String graphicsDir,
                      String contentDir) : base(map)
 {
     this.fc          = fc;
     this.map         = map;
     this.graphicsDir = graphicsDir;
     this.contentDir  = contentDir;
 }
        private void ImportData()
        {
            var helper = new FixtureHelper();

            using (var cleaner = new FileCleaner()) {
                var sampleData = helper.Run <SampleData>();
                cleaner.Watch(sampleData.Files.Select(x => x.LocalFileName).Where(x => x != null));
                helper.Run(new LoadSampleData(sampleData.Files));
            }
        }
 public FragmentMapMaker(FileCleaner fc,
                         ResourceMap map,
                         String graphicsDir,
                         String pageTemplateDir)
 {
     this.fc              = fc;
     this.map             = map;
     this.graphicsDir     = graphicsDir;
     this.pageTemplateDir = pageTemplateDir;
 }
Esempio n. 10
0
        public void TestCreate()
        {
            //using (var create = MyCSVWriter._initCSV("DDT-create.csv", "name", "verb", "batchmode", "input_file", "target_file", "expected", "append", "verbose"))
            var folder   = Column(0);
            var verb     = Column(1); // "create", unused
            var isbatch  = Boolean.Parse(Column(2));
            var input    = Column(3);
            var target   = Column(4); // unused
            var expected = Column(5);
            var output   = Column(6);
            var append   = Boolean.Parse(Column(7));
            var verbose  = Boolean.Parse(Column(8));

            using (var cleaner = FileCleaner.New())
            {
                // this is the sloppiest code ever
                if (append)
                {
                    // copy to out-append.json for the test to avoid overwriting generated artifacts
                    var out_append      = "out-append.json";
                    var full_out_append = Path.Combine(folder, out_append);
                    File.Copy(Path.Combine(folder, output), full_out_append, true);
                    output = out_append;
                    cleaner.Add(full_out_append);
                }
                else
                {
                    cleaner.Add(Path.Combine(folder, output));
                }
                if (!String.IsNullOrWhiteSpace(target))
                {
                    cleaner.Add(target);
                }

                string cmdline;
                if (isbatch)
                {
                    cmdline = $"create -b -i \"{input}\" -o \"{output}\"";
                }
                else
                {
                    cmdline = $"create -i \"{input}\" -t \"target.txt\" -o \"{output}\"";
                }
                if (append)
                {
                    cmdline += " -a";
                }

                var proc = FVTestUtil.RunProcess(cmdline, folder);
                Assert.AreEqual(0, proc.ExitCode);
                var exp_text = LoadOutput(Path.Combine(folder, expected));
                var got_text = LoadOutput(Path.Combine(folder, output));
                DictCompare(exp_text, got_text);
            }
        }
Esempio n. 11
0
        private static void CreateNonDiacriticsFiles(string rPath)
        {
            foreach (var text in allTexts)
            {
                //string path = rPath + TextFile.FileName(text) + "_NORMALIZED" + TextFile.FileExtension(text);
                string path = rPath + text;
                FileCleaner.RemoveDiacriticsInFile(path);

                //File.Create(TextFile.FileName(rPath + text) + "_Reconstructed.txt");
            }
        }
Esempio n. 12
0
        public PreFhirGenerator(FileCleaner fc, String cacheDir)
        {
            const String fcn = "PreFhirGenerator";

            this.fc = fc;
            if (FhirStructureDefinitions.Self == null)
            {
                this.ConversionInfo(this.GetType().Name, fcn, $"Init'g 'FhirStructureDefinitions'");
                FhirStructureDefinitions.Create(Path.Combine(cacheDir, "DefinitionCache"));
            }
        }
Esempio n. 13
0
 public void Get_local_file()
 {
     using (var cleaner = new FileCleaner()) {
         var tmpFile  = cleaner.TmpFile();
         var fileInfo = new FileInfo(tmpFile);
         fileInfo.LastWriteTime = DateTime.Now.AddDays(1);
         var source = new CertificateSource {
             DecodeTableUrl = new Uri(fileInfo.FullName).ToString()
         };
         var file = handler.GetCatalogFile(source, cleaner);
         Assert.IsNotNull(file);
     }
 }
Esempio n. 14
0
 public void Delete()
 {
     using (var cleaner = new FileCleaner()) {
         foreach (var mail in SelectedItems.ToArray())
         {
             Session.Delete(mail);
             mails.Remove(mail);
             Items.Value.Remove(mail);
             cleaner.Watch(mail.Attachments.Select(a => a.LocalFilename).Where(f => f != null));
         }
     }
     Items.Refresh();
 }
Esempio n. 15
0
        private void ConvertSvfToGltf(string svfFilePath, string gltfFilePath, bool allowExtractShell, GltfOption options, CancellationToken token)
        {
            using (var fc = new FileCleaner())
            {
                #region 抽取外壳

                if (allowExtractShell)
                {
                    var idsFilePath = Path.GetTempFileName();
                    fc.AddFile(idsFilePath);

                    if (token.IsCancellationRequested)
                    {
                        return;
                    }
                    if (ExtractShell(_ExtractShellCLI, svfFilePath, idsFilePath, token))
                    {
                        //如果抽壳成功,则从原始模型中把外壳提取出来

                        var tempFolder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
                        FileSystemUtility.CreateDirectory(tempFolder);
                        fc.AddFolder(tempFolder);

                        if (token.IsCancellationRequested)
                        {
                            return;
                        }
                        using (var doc = SvfDocument.LoadFrom(svfFilePath))
                        {
                            if (token.IsCancellationRequested)
                            {
                                return;
                            }
                            if (doc.Extract(idsFilePath, tempFolder, token))
                            {
                                svfFilePath = tempFolder;   //将 Svf -> glTF 的输入源替换成已经抽壳的模型
                            }
                        }
                    }
                }

                #endregion

                if (token.IsCancellationRequested)
                {
                    return;
                }
                GltfExtension.ConvertToGltf(svfFilePath, gltfFilePath, options, token);
            }
        }
Esempio n. 16
0
        public void Setup()
        {
            tmpFiles = new FileCleaner();
            config   = FixtureSetup.Config;
            client   = TestClient.CreateNaked(session);
            session.Save(client);

            user       = session.Load <User>(client.Users[0].Id);
            controller = new MainController {
                Request     = new HttpRequestMessage(),
                Session     = session,
                CurrentUser = user,
                Config      = config,
            };
            scheduler            = new ManualScheduler();
            RequestLog.Scheduler = scheduler;
        }
Esempio n. 17
0
        public void CleanupHandlesDirectoryExceptions()
        {
            IFileService fileServiceProvider = Substitute.For <IFileService>();
            MemoryStream memoryStream        = new MemoryStream();

            fileServiceProvider.CreateFileStream("").ReturnsForAnyArgs(memoryStream);
            IDirectoryInformation directoryInfo = Substitute.For <IDirectoryInformation>();
            IFileInformation      fileInfo      = Substitute.For <IFileInformation>();

            directoryInfo.EnumerateChildren().ReturnsForAnyArgs(new IFileInformation[] { fileInfo });
            fileServiceProvider.GetPathInfo("").ReturnsForAnyArgs(directoryInfo);

            using (FileCleaner cleaner = new FileCleaner("Test", fileServiceProvider))
            {
                fileServiceProvider.WhenForAnyArgs(f => f.DeleteDirectory("")).Do(a => { throw new Exception("TestException"); });
            }
        }
Esempio n. 18
0
        public void MixedFixtureSetup()
        {
            //в качестве начального значения используется время если оно совпадет то и значения будут идентичные
            //для этого тесты должны иметь общий генератор случайных чисел
            random = new Random();
            begin  = DateTime.Now;
            SystemTime.Reset();

            cleaner    = new FileCleaner();
            disposable = new CompositeDisposable();
            disposable.Add(cleaner);

            fixtureHelper = new FixtureHelper();
            disposable.Add(fixtureHelper);

            clientConfig  = Integration.IntegrationSetup.clientConfig;
            serviceConfig = Integration.IntegrationSetup.serviceConfig;

            FileHelper.InitDir(serviceConfig.RtmUpdatePath,
                               clientConfig.TmpDir,
                               Path.Combine(ConfigurationManager.AppSettings["ClientDocPath"], "АналитФАРМАЦИЯ"));

            localSession   = Integration.IntegrationSetup.Factory.OpenSession();
            localStateless = Integration.IntegrationSetup.Factory.OpenStatelessSession();

            settings = localSession.Query <Settings>().First();
            address  = localSession.Query <Address>().First();

            ViewModelFixture.StubWindowManager();

            var debugTest = Environment.GetEnvironmentVariable("DEBUG_TEST");

            if (debugTest.Match(TestContext.CurrentContext.Test.Name))
            {
                var repository = (Hierarchy)LogManager.GetRepository();
                repository.Configured = true;
                var logger = (Logger)repository.GetLogger("AnalitF.Net");
                if (logger.Level == null || logger.Level > Level.Warn)
                {
                    logger.Level = Level.Warn;
                }
                var appender = new ConsoleAppender(new PatternLayout(PatternLayout.DefaultConversionPattern));
                appender.ActivateOptions();
                logger.AddAppender(appender);
            }
        }
        public void A1_Build()
        {
            using (this.fc = new FileCleaner())
            {
                this.fc?.Add(this.graphicsDir, "*.svg");
                this.fc?.Add(this.pageDir, "*.xml");
                this.fc?.Add(this.fragmentsDir, "*.json");
                this.fc?.Add(this.resourcesDir, "*.json");

                this.C1_Build();

                this.B1_BuildFragments();
                this.B2_BuildResources();
                this.B3_PatchIntroDocs();
                this.B4_BuildGraphics();
                this.B5_BuildExamples();
                this.B6_BuildIG();
            }
        }
Esempio n. 20
0
        private static void CleanFiles()
        {
            var fc = new FileCleaner();

            var file = new UniGramFile("D:/slovniky/prim-8.0-public-all-word_frequency_non_case_sensitive/prim-8.0-public-all-word_frequency_non_case_sensitive.txt");

            Console.WriteLine(fc.CompleteProcessing(file, rmvWordsFromFreq: 0, rmvBadWordsFromFreq: 11, rmvWordsFromLength: 30));

            var file2 = new NgramFile("D:/ngramy/prim-8.0-public-all-2-gramy/prim-8.0-public-all-2-gramy.txt");

            Console.WriteLine(fc.CompleteProcessing(file2, rmvWordsFromFreq: 1, rmvBadWordsFromFreq: 11, rmvWordsFromLength: 30));

            var file3 = new NgramFile("D:/ngramy/prim-8.0-public-all-3-gramy/prim-8.0-public-all-3-gramy.txt");

            Console.WriteLine(fc.CompleteProcessing(file3, rmvWordsFromFreq: 2, rmvBadWordsFromFreq: 11, rmvWordsFromLength: 30));

            var file4 = new NgramFile("D:/ngramy/prim-8.0-public-all-4-gramy/prim-8.0-public-all-4-gramy.txt");

            Console.WriteLine(fc.CompleteProcessing(file4, rmvWordsFromFreq: 3, rmvBadWordsFromFreq: 11, rmvWordsFromLength: 30));
        }
Esempio n. 21
0
        public void FlagFileCreationTest()
        {
            IFileService fileServiceProvider = Substitute.For <IFileService>();
            MemoryStream memoryStream        = new MemoryStream();

            fileServiceProvider.CreateFileStream("").ReturnsForAnyArgs(memoryStream);

            using (FileCleaner cleaner = new FileCleaner("Test", fileServiceProvider))
            {
                cleaner.TempFolder.Should().StartWith(Path.Combine(Path.GetTempPath(), "Test"));
                fileServiceProvider.Received(1).CreateFileStream(
                    Path.Combine(cleaner.TempFolder, TestFileCleaner.TestFlagFileName),
                    FileMode.CreateNew,
                    FileAccess.ReadWrite,
                    FileShare.None);

                memoryStream.Position = 0;
                StreamReader reader = new StreamReader(memoryStream);
                reader.ReadToEnd().Should().StartWith(XTaskStrings.FlagFileContent);
            }
        }
Esempio n. 22
0
        public void BaseUnitFixtureSetup()
        {
            cleaner = new FileCleaner();
            cleanup = new CompositeDisposable();
            cleanup.Add(cleaner);
            user        = new User();
            bus         = new MessageBus();
            scheduler   = new TestScheduler();
            Env.Current = new Env(user, bus, scheduler, null /*не нужно использовать базу для этого есть интеграционные тесты*/)
            {
                //тк в модульных тестах сессия не инициализируется все запросы будут "завершаться" моментально в той же нитке
                QueryScheduler = new CurrentThreadScheduler(),
                TplUiScheduler = new CurrentThreadScheduler(),
                Settings       = new Settings()
                {
                    Rounding = Rounding.None
                }
            };

            manager = ViewModelFixture.StubWindowManager();
            shell   = new ShellViewModel();
            cleanup.Add(shell);
        }
Esempio n. 23
0
        private static void ProcessUser(ISession session, uint userId)
        {
            log.Debug($"Обработка пользователя {userId}");
            var config = session.Query <FtpConfig>().Where(x => x.User.Id == userId).ToList();

            foreach (var priceConfig in config)
            {
                using (var cleaner = new FileCleaner())
                    using (var client = new FtpClient()) {
                        var url = new Uri(priceConfig.OrderUrl);
                        FtpExportJob.OpenFtp(url, client);
                        var dir   = url.GetComponents(UriComponents.Path, UriFormat.Unescaped);
                        var files = client.GetListing(dir);
                        foreach (var file in files)
                        {
                            var tmp        = cleaner.TmpFile();
                            var targetFile = Path.Combine(dir, file.Name);
                            using (var dst = File.OpenWrite(tmp))
                                using (var src = client.OpenRead(targetFile))
                                    src.CopyTo(dst);

                            try {
                                using (var trx = session.BeginTransaction()) {
                                    Protocols.DbfAsna.OrderImport(userId, tmp);
                                    client.DeleteFile(targetFile);
                                    trx.Commit();
                                }
                            } catch (Exception e) {
                                log.Error($"Не удалось обработать файл {file.Name} из {url}", e);
#if DEBUG
                                throw;
#endif
                            }
                        }
                    }
            }
        }
        public override void ProcessData()
        {
            using (new SessionScope()) {
                var sources = CertificateSource.Queryable.Where(s => !s.IsDisabled).ToArray();
                foreach (var source in sources)
                {
                    var ftpSource = source.GetCertificateSource() as IRemoteFtpSource;
                    if (ftpSource == null)
                    {
                        continue;
                    }

                    try {
                        using (var cleaner = new FileCleaner()) {
                            Cleanup();
                            Ping();
                            var catalogFile = GetCatalogFile(source, cleaner);
                            if (catalogFile == null)
                            {
                                continue;
                            }
                            cleaner.Watch(catalogFile.LocalFileName);
                            Ping();
                            ImportCatalogFile(catalogFile, source, ftpSource);
                            Ping();
                            doNotSmapLogger.Forget(source.Id);
                        }
                    }
                    catch (Exception e) {
                        doNotSmapLogger.Error(
                            String.Format("Не удалось загрузить перекодировочную таблица сертификатов {0}", source.DecodeTableUrl),
                            e, source.Id);
                    }
                }
            }
        }
Esempio n. 25
0
        public IGBuilder(String outputDir)
        {
            String SetSubDir(String subDir)
            {
                String retVal = Path.Combine(this.outputDir, subDir);

                if (Directory.Exists(retVal) == false)
                {
                    Directory.CreateDirectory(retVal);
                }
                return(retVal);
            }

            this.outputDir = outputDir;
            this.fcGuide   = new FileCleaner();
            this.fcGuide.Add(this.outputDir);
            this.fcGuide.Mark(Path.Combine(this.outputDir, "ignoreWarnings.txt"));

            this.resourceDir    = SetSubDir("resources");
            this.exampleDir     = SetSubDir("examples");
            this.pagecontentDir = SetSubDir("pagecontent");
            this.imagesDir      = SetSubDir("images");
            this.includesDir    = SetSubDir("includes");
        }
        public void ProcessMessage(ISession session, MimeMessage message, UniqueId messageId = default(UniqueId))
        {
            //используется промежуточный почтовый ящик для транзита
            //в поле To будет именно он, этот же ящик используется для транзита прайс-листов
            var emails =
                message.To.OfType <MailboxAddress>().Where(s => !string.IsNullOrEmpty(s.Address)).Select(a => a.Address).ToArray();

            if (emails.Length == 0)
            {
                NotifyAdmin("У сообщения не указано ни одного получателя.", message);
                return;
            }
            var attachments = message.Attachments.Where(m => !String.IsNullOrEmpty(GetFileName(m)) && m.IsAttachment);

            if (!attachments.Any())
            {
                NotifyAdmin($"Отсутствуют вложения в письме от адреса {message.To.Implode()}", message);
                return;
            }

            var dtSources = session.Connection.Query <SupplierSelector>(@"
SELECT distinct
	s.Id as FirmCode,
	st.EMailTo
FROM farm.sourcetypes
	join farm.Sources as st on st.SourceTypeId = sourcetypes.Id
		join usersettings.PriceItems pi on pi.SourceId = st.ID
			join usersettings.PricesCosts pc on pc.PriceItemId = pi.ID
				join UserSettings.PricesData  as PD on PD.PriceCode = pc.PriceCode
					join Customers.Suppliers as s on s.Id = PD.FirmCode
WHERE
	sourcetypes.Type = 'EMail'
	and s.Disabled = 0
	and pd.AgencyEnabled = 1"    ).ToList();

            var sources = emails
                          .SelectMany(x => dtSources.Where(y => y.EmailTo?.IndexOf(x, StringComparison.OrdinalIgnoreCase) >= 0))
                          .Distinct()
                          .ToList();

            if (sources.Count > 1)
            {
                NotifyAdmin(
                    $"Для получателей {emails.Implode()} определено более одного поставщика." +
                    $" Определенные поставщики {sources.Select(x => x.FirmCode).Implode()}.", message);
                return;
            }
            if (sources.Count == 0)
            {
                NotifyAdmin(
                    $"Не удалось идентифицировать ни одного поставщика по адресам получателя {emails.Implode()}." +
                    $" Количество записей в источниках - {dtSources.Count}", message);
                return;
            }

            var source     = sources.First();
            var supplierId = source.FirmCode;
            var supplier   = session.Load <Supplier>(supplierId);

            using (var cleaner = new FileCleaner()) {
                foreach (var mimeEntity in attachments)
                {
                    //получение текущей директории
                    var filename = Path.Combine(DownHandlerPath, GetFileName(mimeEntity));
                    var files    = new List <string> {
                        filename
                    };

                    //сохранение содержимого в текущую директорию
                    using (var fs = new FileStream(filename, FileMode.Create))
                        ((MimePart)mimeEntity).ContentObject.DecodeTo(fs);

                    try {
                        files = FileHelper.TryExtractArchive(filename, cleaner.RandomDir())?.ToList()
                                ?? files;
                    } catch (ArchiveHelper.ArchiveException e) {
                        _logger.Warn($"Не удалось распаковать файл {filename}", e);
                        NotifyAdmin($"Не удалось распаковать файл {filename}.", message, supplier);
                        continue;
                    }

                    var logs = new List <DocumentReceiveLog>();
                    foreach (var file in files)
                    {
                        //нам нужно считать файл что бы узнать кто его отправил, по хорошему нам и не нужен пока что клиент
                        var doc = new WaybillFormatDetector().Parse(session, file, new DocumentReceiveLog(supplier, new Address(new Client()), DocType.Waybill));
                        if (doc == null)
                        {
                            NotifyAdmin($"Не удалось разобрать документ {file} нет подходящего формата.", message, supplier);
                            continue;
                        }
                        if (doc.Invoice?.RecipientId == null)
                        {
                            if (doc.Parser == nameof(WaybillSstParser))
                            {
                                NotifyAdmin($"В файле {file} не заполнено поле Код получателя.", message, supplier);
                            }
                            else
                            {
                                NotifyAdmin($"Формат файла {file} не соответствует согласованному формату sst. " +
                                            $"Поле 'Код получателя' не заполнено, возможно выбранный формат {doc.Parser} не считывает поле либо оно не заполнено в файла. " +
                                            $"Проверьте настройки формата {doc.Parser} и заполнение поля 'Код получателя' в файле.", message, supplier);
                            }
                            continue;
                        }

                        var result = session.Connection.Query <uint?>(@"
select ai.AddressId
from Customers.Intersection i
	join Customers.AddressIntersection ai on ai.IntersectionId = i.Id
	join Usersettings.Pricesdata pd on pd.PriceCode = i.PriceId
		join Customers.Suppliers s on s.Id = pd.FirmCode
where ai.SupplierDeliveryId = @supplierDeliveryId
	and s.Id  = @supplierId
group by ai.AddressId", new { @supplierDeliveryId = doc.Invoice.RecipientId, @supplierId = supplierId })
                                     .FirstOrDefault();

                        if (result == null)
                        {
                            NotifyAdmin($"Не удалось обработать документ {file} для кода получателя {doc.Invoice.RecipientId} не найден адрес доставки. " +
                                        $"Проверьте заполнение поля 'Код адреса доставки' в личном кабинете поставщика {supplierId}.",
                                        message, supplier);
                            continue;
                        }

                        _logger.InfoFormat($"Файл {file} обработан для кода получателя {doc.Invoice.RecipientId} выбран адрес {result.Value}");
                        logs.Add(DocumentReceiveLog.LogNoCommit(supplierId, result.Value, file, DocType.Waybill, "Получен по Email",
                                                                (int?)messageId.Id));
                    }
                    //если логи есть, значит файл распознан и найден соответствующий адрес доставки
                    if (logs.Count > 0)
                    {
                        var service = new WaybillService();
                        service.Process(logs);
                        if (service.Exceptions.Count > 0)
                        {
                            NotifyAdmin(service.Exceptions.First().Message, message, supplier);
                        }
                    }
                }
            }
        }
Esempio n. 27
0
        private void AddPackages(SyndicationFeed feed,
                                 Uri root,
                                 string rootStoragePath,
                                 IEnumerable <IVsixPackage> packages)
        {
            // See https://msdn.microsoft.com/en-us/library/hh266717.aspx
            var items = new List <SyndicationItem>();

            var orderedPackages = packages
                                  .OrderBy(pkg => pkg.DisplayName)
                                  .ThenBy(pkg => pkg.Id)
                                  .ToArray();

            OnBackgroundProgress(new VsixFeedBuilderProgressArgs(0, orderedPackages.Length, "Starting"));

            for (var pkgIdx = 0; pkgIdx < orderedPackages.Length; pkgIdx++)
            {
                var pkg = orderedPackages[pkgIdx];

                // Possibly normalize the file name for the package,
                // visual studio does not like special characters in the file download urls so it is best to clear these out
                pkg.File = FileCleaner.NormalizePackageFileName(pkg.File);
                var pkgFileName = Path.GetFileName(pkg.File);

                OnBackgroundProgress(new VsixFeedBuilderProgressArgs(pkgIdx + 1, orderedPackages.Length, pkgFileName));

                // Schema: https://msdn.microsoft.com/en-us/library/dd393754(v=vs.100).aspx
                // Extension Schema: https://msdn.microsoft.com/en-us/library/dd393700(v=vs.100).aspx
                var item = new SyndicationItem
                {
                    Id              = pkg.Id,
                    Title           = new TextSyndicationContent(pkg.DisplayName),
                    Summary         = new TextSyndicationContent(pkg.Description),
                    PublishDate     = new DateTimeOffset(File.GetLastWriteTimeUtc(pkg.File)),
                    LastUpdatedTime = new DateTimeOffset(File.GetLastWriteTimeUtc(pkg.File))
                };

                // Create the subfolder for the package contents on the local system, ensure that the path exists
                var packageFolderPath = Path.Combine(rootStoragePath, pkg.Id);
                Directory.CreateDirectory(packageFolderPath);

                // Create a mapping between the vsix id and the file name by placing a simple file in the root
                FileCounter.SetIdToVsixFile(pkg.Id, pkgFileName, _configStorage);

                item.Authors.Add(new SyndicationPerson {
                    Name = pkg.Publisher
                });

                // If the configuration specifies that the downloads should be tracked then route the downloads
                // through the DownloadModule for tracking, if tracking is off then serve the static files directly
                // from the file-system
                item.Content = SyndicationContent.CreateUrlContent(_configGallery.TrackDownloads
                                                                   ? new Uri($"../api/download/{pkg.Id}/{pkgFileName}", UriKind.Relative)
                                                                   : root.MakeRelativeUri(new Uri(pkg.File)), "application/octet-stream");

                // Only use the first category found, the developer should put the most important category first anyways
                var category = pkg.Categories.FirstOrDefault(x => !string.IsNullOrWhiteSpace(x));
                if (category != null)
                {
                    item.Categories.Add(new SyndicationCategory(category.Trim().ToTitleCase()));
                }

                if (pkg.TrySaveIcon(packageFolderPath, out Uri iconUri))
                {
                    item.Links.Add(new SyndicationLink(root.MakeRelativeUri(iconUri), "icon", "", "", 0));
                }

                if (pkg.TrySavePreviewImage(packageFolderPath, out Uri previewUri))
                {
                    item.Links.Add(new SyndicationLink(root.MakeRelativeUri(previewUri), "previewimage", "", "", 0));
                }

                // Displays the "More Info" link if set
                if (pkg.MoreInfoUrl.IsUrl())
                {
                    item.Links.Add(new SyndicationLink(new Uri(pkg.MoreInfoUrl), "alternate", "", "", 0)); // Must be set to "alternate", rest does not need to be set
                }
                // Displays the "Release Notes" link if set
                if (pkg.ReleaseNotes.IsUrl())
                {
                    item.Links.Add(new SyndicationLink(new Uri(pkg.ReleaseNotes), "releasenotes", "", "", 0));
                }

                // Add the extensions to the item
                AddExtensions(item, pkg);

                // Now save the item
                items.Add(item);
            }
            OnBackgroundProgress(new VsixFeedBuilderProgressArgs(orderedPackages.Length, orderedPackages.Length, "All done"));

            // Save all the items into the feed object
            feed.Items = items;
        }
Esempio n. 28
0
 protected AbstractCertifcateSource()
 {
     Log     = LogManager.GetLogger(GetType());
     Cleaner = new FileCleaner();
 }
Esempio n. 29
0
 protected AbstractCertifcateSource(FileCleaner cleaner)
     : this()
 {
     Cleaner = cleaner;
 }
Esempio n. 30
0
 public void Setup()
 {
     cleaner = new FileCleaner();
 }