// GET: api/Export
 public IHttpActionResult Get()
 {
     Zipper.ZipExams(_studentDbRepository.GetAllStudents());
     byte[] array = Zipper.ExportedExams();
     return(new SkeletResponse(array, Request, "Export.zip"));
 }
Exemple #2
0
    public void Tree_from_deep_focus()
    {
        var zipper = Zipper <int> .FromTree(t1);

        Assert.That(zipper.Left().Right().ToTree(), Is.EqualTo(t1));
    }
Exemple #3
0
    public void Different_paths_to_same_zipper()
    {
        var zipper = Zipper <int> .FromTree(t1);

        Assert.Equal(zipper.Right().ToTree(), zipper.Left().Up().Right().ToTree());
    }
Exemple #4
0
        public virtual string Export(int id, bool exportForPlayCourse = false)
        {
            var course = this.GetCourse(id);

            var path = this.GetCoursePath(id);

            if (course.Locked != null && course.Locked.Value)
            {
                return(path + ".zip");
            }

            path = Path.Combine(path, Guid.NewGuid().ToString());
            path = Path.Combine(path, course.Name);

            Directory.CreateDirectory(path);

            var nodes = this.GetNodes(id).ToList();

            for (var i = 0; i < nodes.Count; i++)
            {
                if (nodes[i].IsFolder == false)
                {
                    File.Copy(this.GetNodePath(nodes[i].Id) + ".html", Path.Combine(path, nodes[i].Id + ".html"));
                }
                else
                {
                    var subNodes = GetNodes(id, nodes[i].Id);
                    nodes.AddRange(subNodes);
                }
            }

            var coursePath = this.GetCoursePath(id);

            FileHelper.DirectoryCopy(Path.Combine(coursePath, "Node"), Path.Combine(path, "Node"));

            foreach (var file in this.templateFiles)
            {
                try
                {
                    File.Copy(Path.Combine(coursePath, file), Path.Combine(path, file), true);
                }
                catch (FileNotFoundException)
                {
                    continue;
                }
            }

            var helper = new ManifestManager();

            var manifest   = new Manifest();
            var sw         = new StreamWriter(Path.Combine(path, SCORM.ImsManifset));
            var parentItem = new Item();

            parentItem                      = this.AddSubItems(parentItem, null, id, helper, ref manifest);
            manifest.Organizations          = ManifestManager.AddOrganization(manifest.Organizations, helper.CreateOrganization());
            manifest.Organizations.Default  = manifest.Organizations[0].Identifier;
            manifest.Organizations[0].Items = parentItem.Items;
            manifest.Organizations[0].Title = course.Name;

            if (course.Sequencing != null)
            {
                var xml = new XmlSerializer(typeof(Sequencing));
                manifest.Organizations[0].Sequencing = (Sequencing)xml.DeserializeXElement(course.Sequencing);
            }
            var resource = new Resource
            {
                Identifier = ResourceIdForTemplateFiles,
                Files      = this.templateFiles.Select(file => new ManifestModels.ResourceModels.File(file)).ToList(),
                ScormType  = ScormType.Asset
            };

            manifest.Resources = ManifestManager.AddResource(manifest.Resources, resource);

            ManifestManager.Serialize(manifest, sw);
            sw.Close();

            Zipper.CreateZip(path + ".zip", path);

            if (exportForPlayCourse)
            {
                try
                {
                    IudicoCourseInfo ci = CourseParser.Parse(course, this);
                    this.AddCourseInfo(ci);
                }
                catch (Exception ex)
                {
                    log.Error(string.Format("Exception message: {0}\nData: {1}\nHelp Link: {2}\nInner exception: {3}\nSource: {4}\nStack trace: {5}\nTarget site: {6}", ex.Message, ex.Data, ex.HelpLink, ex.InnerException, ex.Source, ex.StackTrace, ex.TargetSite));
                }
            }

            return(path + ".zip");
        }
        public string Export(int id)
        {
            var course = GetCourse(id);

            var path = GetCoursePath(id);

            if (course.Locked != null && course.Locked.Value)
            {
                return(path + ".zip");
            }

            path = Path.Combine(path, Guid.NewGuid().ToString());
            path = Path.Combine(path, course.Name);

            Directory.CreateDirectory(path);


            var nodes = GetNodes(id).ToList();

            for (var i = 0; i < nodes.Count; i++)
            {
                if (nodes[i].IsFolder == false)
                {
                    File.Copy(GetNodePath(nodes[i].Id) + ".html", Path.Combine(path, nodes[i].Id + ".html"));
                }
                else
                {
                    var subNodes = GetNodes(id, nodes[i].Id);
                    nodes.AddRange(subNodes);
                }
            }

            var coursePath = GetCoursePath(id);

            FileHelper.DirectoryCopy(Path.Combine(coursePath, "Node"), Path.Combine(path, "Node"));

            foreach (var file in _TemplateFiles)
            {
                File.Copy(Path.Combine(coursePath, file), Path.Combine(path, file));
            }

            var helper = new ManifestManager();

            var manifest   = new Manifest();
            var sw         = new StreamWriter(Path.Combine(path, SCORM.ImsManifset));
            var parentItem = new Item();

            parentItem                      = AddSubItems(parentItem, null, id, helper, ref manifest);
            manifest.Organizations          = ManifestManager.AddOrganization(manifest.Organizations, helper.CreateOrganization());
            manifest.Organizations.Default  = manifest.Organizations[0].Identifier;
            manifest.Organizations[0].Items = parentItem.Items;
            manifest.Organizations[0].Title = course.Name;

            if (course.Sequencing != null)
            {
                var xml = new XmlSerializer(typeof(Sequencing));
                manifest.Organizations[0].Sequencing = (Sequencing)xml.DeserializeXElement(course.Sequencing);
            }
            var resource = new Resource
            {
                Identifier = _ResourceIdForTemplateFiles,
                Files      = _TemplateFiles.Select(file => new ManifestModels.ResourceModels.File(file)).ToList(),
                ScormType  = ScormType.Asset
            };

            manifest.Resources = ManifestManager.AddResource(manifest.Resources, resource);

            ManifestManager.Serialize(manifest, sw);
            sw.Close();

            Zipper.CreateZip(path + ".zip", path);

            return(path + ".zip");
        }
Exemple #6
0
    public void Dead_end()
    {
        var zipper = Zipper <int> .FromTree(t1);

        Assert.Null(zipper.Left().Left());
    }
Exemple #7
0
        private void SaveWorld(WorldModel world, byte[] data)
        {
            MemoryStream inStream = new MemoryStream(data);

            Zipper.ExtractZipFile(inStream, SavesPath + world.Title);
        }
Exemple #8
0
        protected override int DoExecute(ITaskContextInternal context)
        {
            if (_sourcePackagingInfos.Count == 0)
            {
                return(0);
            }

            if (string.IsNullOrEmpty(_destinationRootDir))
            {
                _destinationRootDir = context.Properties.GetOutputDir();
            }

            FullPath df     = new FullPath(_destinationRootDir);
            ICopier  copier = new Copier(context, _logFiles);
            IZipper  zipper = new Zipper(context);
            IDirectoryFilesLister directoryFilesLister = new DirectoryFilesLister();
            StandardPackageDef    packageDef           = new StandardPackageDef();

            CopyProcessor copyProcessor = new CopyProcessor(context, copier, df);

            List <string> sourceIds = new List <string>();

            foreach (var sourceToPackage in _sourcePackagingInfos)
            {
                string sourceId;
                if (sourceToPackage.SourceType == SourceType.Directory)
                {
                    var sourceFullPath = new FullPath(sourceToPackage.SourcePath);
                    sourceId = sourceFullPath.GetHashCode().ToString();
                    DirectorySource directorySource = new DirectorySource(context, directoryFilesLister, sourceId, sourceFullPath, sourceToPackage.Recursive);
                    directorySource.SetFilter(sourceToPackage.FileFilters);
                    packageDef.AddFilesSource(directorySource);
                }
                else
                {
                    var fileFullPath = new FileFullPath(sourceToPackage.SourcePath);
                    sourceId = fileFullPath.GetHashCode().ToString();
                    SingleFileSource fileSource = new SingleFileSource(sourceId, fileFullPath);
                    packageDef.AddFilesSource(fileSource);
                }

                copyProcessor.AddTransformation(sourceId, sourceToPackage.DestinationPath);
                sourceIds.Add(sourceId);
            }

            IPackageDef copiedPackageDef = copyProcessor.Process(packageDef);

            if (ShouldPackageBeZipped)
            {
                string zipFile = _zipFileName;

                if (string.IsNullOrEmpty(zipFile))
                {
                    zipFile = _zipPrefix;
                    _addVersionAsPostFixToZipFileName = true;
                    _versionFieldCount = 3;
                }

                if (zipFile.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
                {
                    zipFile = zipFile.Substring(0, zipFile.Length - 4);
                }

                string tmp = _addVersionAsPostFixToZipFileName
                    ? $"{zipFile}_{context.Properties.GetBuildVersion().ToString(_versionFieldCount)}.zip"
                    : $"{zipFile}.zip";

                zipFile = Path.Combine(_destinationRootDir, tmp);

                DoLogInfo($"Creating zip file {zipFile}");

                ZipProcessor zipProcessor = new ZipProcessor(context, zipper, new FileFullPath(zipFile), df, _optimizeZip, sourceIds, _logFiles);
                zipProcessor.Process(copiedPackageDef);
            }

            return(0);
        }
Exemple #9
0
        private static void TargetPackage(ITaskContext context)
        {
            FullPath packagesDir = new FullPath(context.Properties.Get(BuildProps.ProductRootDir, "."));
            packagesDir = packagesDir.CombineWith(context.Properties.Get<string>(BuildProps.BuildDir));
            FullPath simplexPackageDir = packagesDir.CombineWith("Detergent");
            FileFullPath zipFileName = packagesDir.AddFileName(
                "Detergent-{0}.zip",
                context.Properties.Get<Version>(BuildProps.BuildVersion));

            StandardPackageDef packageDef = new StandardPackageDef("Detergent", context);
            VSSolution solution = context.Properties.Get<VSSolution>(BuildProps.Solution);

            VSProjectWithFileInfo projectInfo =
                (VSProjectWithFileInfo)solution.FindProjectByName("Detergent");
            LocalPath projectOutputPath = projectInfo.GetProjectOutputPath(
                context.Properties.Get<string>(BuildProps.BuildConfiguration));
            FullPath projectTargetDir = projectInfo.ProjectDirectoryPath.CombineWith(projectOutputPath);
            packageDef.AddFolderSource(
                "bin",
                projectTargetDir,
                false);

            ICopier copier = new Copier(context);
            CopyProcessor copyProcessor = new CopyProcessor(
                 context,
                 copier,
                 simplexPackageDir);
            copyProcessor
                .AddTransformation("bin", new LocalPath(string.Empty));

            IPackageDef copiedPackageDef = copyProcessor.Process(packageDef);

            Zipper zipper = new Zipper(context);
            ZipProcessor zipProcessor = new ZipProcessor(
                context,
                zipper,
                zipFileName,
                simplexPackageDir,
                null,
                "bin");
            zipProcessor.Process(copiedPackageDef);
        }
Exemple #10
0
        public void TestUnzipAll([Values(true, false)] bool fromStream)
        {
            Assert.IsTrue(File.Exists(ZipFileName), "Can't find the test file");
            string temporyDirectory = Path.Combine(Path.GetTempPath(), "TestUnzip");

            string[]     fileNames  = { "File1.txt", "File2.txt" };
            const string subDirName = "Subdir";

            try
            {
                if (Directory.Exists(temporyDirectory))
                {
                    Directory.Delete(temporyDirectory, true);
                }

                if (fromStream)
                {
                    using (Stream fs = new FileStream(ZipFileName, FileMode.Open))
                    {
                        Zipper.UnZipAll(fs, temporyDirectory);
                    }
                }
                else
                {
                    byte[] bytes = File.ReadAllBytes(ZipFileName);
                    Zipper.UnZipAll(bytes, temporyDirectory);
                }

                string[] files = Directory.GetFiles(temporyDirectory);

                Assert.IsTrue(files.Length == 2, "The unzipped direcory must have 2 files in the root");

                List <string> expectedfiles = new List <string>(fileNames);

                foreach (string file in files)
                {
                    using (StreamReader sr = new StreamReader(file))
                    {
                        string fileName = Path.GetFileName(file);
                        Assert.IsTrue(expectedfiles.Contains(fileName), "The file name is not in the expected list");
                        expectedfiles.Remove(fileName);

                        string content = sr.ReadToEnd();
                        Assert.IsTrue(content == fileName, "The file {0} doesn't content the expected text", file);
                    }
                }

                string[] directories = Directory.GetDirectories(temporyDirectory);
                Assert.IsTrue(directories.Length == 1, "The unzipped direcory must have 1 sub directory in the root");

                string subDirectory = directories[0];
                Assert.IsTrue(subDirectory == Path.Combine(temporyDirectory, subDirName), "The sub direcory has not the expected name");

                files = Directory.GetFiles(subDirectory);

                Assert.IsTrue(files.Length == 2, "The unzipped direcory must have 2 files in the sub directory");

                expectedfiles = new List <string>(fileNames);

                foreach (string file in files)
                {
                    using (StreamReader sr = new StreamReader(file))
                    {
                        string fileName = Path.GetFileName(file);
                        Assert.IsTrue(expectedfiles.Contains(fileName), "The file name is not in the expected list");
                        expectedfiles.Remove(fileName);

                        string content = sr.ReadToEnd();
                        Assert.IsTrue(content == string.Format("{0}\\{1}", subDirName, fileName), "The file {0} doesn't content the expected text", file);
                    }
                }

                Assert.IsTrue(Directory.GetDirectories(subDirectory).Length == 0, "The unzipped direcory must not have any sub-sub directory in the root");
            }
            finally
            {
                if (Directory.Exists(temporyDirectory))
                {
                    Directory.Delete(temporyDirectory, true);
                }
            }
        }
Exemple #11
0
 public FileZipperService(Zipper zip)
 {
     this.Zip = zip;
 }
Exemple #12
0
        public string GetLog(bool collect_dump)
        {
            string inventory_log = System.IO.Path.Combine(CrsEnv.GetInventoryLoc(), "logs");
            string machine_time  = Environment.MachineName + "_" + (DateTime.Now).ToString("yyyyMMddHHmmssffff");
            string log_base      = @"C:\logbk\";
            string log_upload    = @"C:\logbk\upload\";
            string log_dir       = System.IO.Path.Combine(log_base, machine_time);
            string filename_base = "log_" + machine_time;
            string info_file     = System.IO.Path.Combine(log_dir, string.Format("{0}_orahome_log_info.txt", filename_base));
            string stat_file     = System.IO.Path.Combine(log_dir, string.Format("{0}_crs_stat.txt", filename_base));

            StringBuilder sb = new StringBuilder();

            if (!Directory.Exists(log_base))
            {
                Directory.CreateDirectory(log_base);
            }
            if (!Directory.Exists(log_dir))
            {
                Directory.CreateDirectory(log_dir);
            }
            if (Directory.Exists(log_upload))
            {
                Directory.Delete(log_upload, true);
            }
            Directory.CreateDirectory(log_upload);

            var orabases = CrsEnv.GetOracleRegProperty("ORACLE_BASE", true);
            var orahome  = CrsEnv.GetOracleRegProperty("ORACLE_HOME", true);

            int    orahome_counter = 1;
            string zip_log         = string.Empty;

            using (FileStream fs = new FileStream(info_file, FileMode.Append))
                using (StreamWriter writer = new StreamWriter(fs))
                    using (Zipper zipper = new Zipper(".zip", info_file))
                    {
                        if (Directory.Exists(inventory_log))
                        {
                            sb.AppendLine("Collecting log from " + inventory_log);
                            zipper.RunZip(inventory_log, System.IO.Path.Combine(log_dir, string.Format("{0}_inventory_log", Environment.MachineName)));
                        }
                        try
                        {
                            foreach (string orabase in orabases)
                            {
                                if (Directory.Exists(orabase))
                                {
                                    sb.AppendLine("Collecting log from " + orabase);
                                    DirectoryInfo dirInfo = new DirectoryInfo(orabase);
                                    string        diag    = System.IO.Path.Combine(orabase, "diag");
                                    string        crsdata = System.IO.Path.Combine(orabase, "crsdata");
                                    string        cfgtool = System.IO.Path.Combine(orabase, "cfgtoollogs");
                                    if (Directory.Exists(diag))
                                    {
                                        zipper.RunZip(diag, System.IO.Path.Combine(log_dir, string.Format("{0}_{1}_diag", filename_base, dirInfo.Name)));
                                    }
                                    if (Directory.Exists(crsdata))
                                    {
                                        zipper.RunZip(crsdata, System.IO.Path.Combine(log_dir, string.Format("{0}_{1}_crsdata", filename_base, dirInfo.Name)));
                                    }
                                    if (Directory.Exists(cfgtool))
                                    {
                                        zipper.RunZip(cfgtool, System.IO.Path.Combine(log_dir, string.Format("{0}_{1}_cfgtoollogs", filename_base, dirInfo.Name)));
                                    }
                                    dirInfo = null;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            sb.AppendFormat("Hit ex when zipping file in {0}, {1}", orabases.ToString(), ex.Message);
                            sb.AppendLine();
                        }
                        foreach (string home in orahome)
                        {
                            if (Directory.Exists(home))
                            {
                                sb.AppendLine("Collecting log from " + home);
                                DirectoryInfo dirInfo = new DirectoryInfo(home);
                                //basename + version + seq#
                                if (dirInfo.Name.Contains("dbhome"))
                                {
                                    zip_log = System.IO.Path.Combine(log_dir, string.Format("{0}_{1}_dbhome_seq_{2}_log", filename_base, dirInfo.Parent.Name, orahome_counter));
                                }
                                else if (dirInfo.Name.Contains("grid"))
                                {
                                    zip_log = System.IO.Path.Combine(log_dir, string.Format("{0}_{1}_gihome_seq_{2}_log", filename_base, dirInfo.Name, orahome_counter));
                                }
                                else
                                {
                                    zip_log = System.IO.Path.Combine(log_dir, string.Format("{0}_{1}_orahome_seq_{2}_log", filename_base, dirInfo.Parent.Name, orahome_counter));
                                }

                                string home_log = System.IO.Path.Combine(home, "log");
                                if (Directory.Exists(home_log))
                                {
                                    zipper.RunZip(home_log, zip_log);
                                }

                                dirInfo = null;

                                writer.WriteLine(string.Format("home: {0}, zip_log: {1}", home, zip_log));
                                orahome_counter += 1;
                            }
                        }
                    }

            try
            {
                if (collect_dump)
                {
                    sb.AppendLine("Collecting Memory Dump !");
                    using (ZipArchive zip = ZipFile.Open(System.IO.Path.Combine(log_dir, string.Format("{0}_MEMORY_DMP.zip", machine_time)), ZipArchiveMode.Create))
                    {
                        zip.CreateEntryFromFile(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "MEMORY.DMP"), "MEMORY.DMP");
                    }
                }
                ZipFile.CreateFromDirectory(log_dir, System.IO.Path.Combine(log_upload, string.Format("{0}_logs.zip", machine_time)));
                sb.AppendLine("logs are collected and zipped in " + System.IO.Path.Combine(log_upload, string.Format("{0}_logs.zip", machine_time)));
                using (FileStream fs = new FileStream(stat_file, FileMode.Append))
                    using (StreamWriter writer = new StreamWriter(fs))
                    {
                        string pathVar = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine);
                        Environment.SetEnvironmentVariable("PATH", pathVar);
                        writer.WriteLine(CrsEnv.CrsStatInfo());
                        writer.WriteLine((DateTime.Now).ToString("yyyy-MM-dd HH:mm:ss.ffff"));
                    }
            }
            catch (Exception ex)
            {
                sb.AppendLine(string.Format("{0} Operation fails when collecting logs, {1}", TX_RESULT_FAIL, ex.Message));
            }
            GC.Collect();
            return(sb.ToString());
        }
Exemple #13
0
 public static void ExtractZipFile(ProjectPaths projectPaths)
 {
     Zipper.ExtractZipFile(projectPaths.PathToCourseZipFile, projectPaths.PathToTempCourseFolder);
 }
Exemple #14
0
 public void Setup()
 {
     _zipper = new Zipper();
 }
        private ZipperItem <T>[] InitialiseResults()
        {
            var actualItems = Zipper.Zip(GetASegments, GetBSegments).ToArray();

            return(actualItems);
        }
Exemple #16
0
 protected override void SetUp()
 {
     _zipper = new Zipper();
 }
Exemple #17
0
 public StorageManager()
 {
     _zipper = new Zipper();
 }
Exemple #18
0
        /// <summary>
        /// Finishes the setup of the bus, using default implementations for the options that have not explicitly been set.
        /// The only requirement, is that you must call <see cref="Transport"/> and select which transport to use - everything
        /// else can run with a default option. It should be noted though, that several of the defaults (e.g. in-mem persistence
        /// options for saga storage, subscriptions, and timeouts) are not meant for production use, and should probably be
        /// replaced by something that is actually persistent.
        /// </summary>
        public IBus Start()
        {
#if HAS_CONFIGURATION_MANAGER
            // force the silly configuration subsystem to initialize itself as a service to users, thus
            // avoiding the oft-encountered stupid Entity Framework initialization exception
            // complaining that something in Rebus' transaction context is not serializable
            System.Configuration.ConfigurationManager.GetSection("system.xml/xmlReader");
            // if you want to know more about this issue, check this out: https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/mitigation-deserialization-of-objects-across-app-domains
#endif

            VerifyRequirements();

            _injectionist.Register(c => _options);
            _injectionist.Register(c => new CancellationTokenSource());
            _injectionist.Register(c => c.Get <CancellationTokenSource>().Token);

            PossiblyRegisterDefault <IRebusLoggerFactory>(c => new ConsoleLoggerFactory(true));

            PossiblyRegisterDefault <IRebusTime>(c => new DefaultRebusTime());

            //PossiblyRegisterDefault<IAsyncTaskFactory>(c => new TimerAsyncTaskFactory(c.Get<IRebusLoggerFactory>()));
            PossiblyRegisterDefault <IAsyncTaskFactory>(c =>
            {
                var rebusLoggerFactory = c.Get <IRebusLoggerFactory>();
                return(new TplAsyncTaskFactory(rebusLoggerFactory));
            });

            PossiblyRegisterDefault <IRouter>(c =>
            {
                var rebusLoggerFactory = c.Get <IRebusLoggerFactory>();
                return(new TypeBasedRouter(rebusLoggerFactory));
            });

            PossiblyRegisterDefault <ISubscriptionStorage>(c => new DisabledSubscriptionStorage());

            PossiblyRegisterDefault <ISagaStorage>(c => new DisabledSagaStorage());

            PossiblyRegisterDefault <ITimeoutManager>(c => new DisabledTimeoutManager());

            PossiblyRegisterDefault <ISerializer>(c => new JsonSerializer());

            PossiblyRegisterDefault <IPipelineInvoker>(c =>
            {
                var pipeline = c.Get <IPipeline>();
                return(new DefaultPipelineInvokerNew(pipeline));
            });

            PossiblyRegisterDefault <IBackoffStrategy>(c =>
            {
                var backoffTimes = new[]
                {
                    // 10 s
                    Enumerable.Repeat(TimeSpan.FromMilliseconds(100), 10),

                    // on and on
                    Enumerable.Repeat(TimeSpan.FromMilliseconds(250), 1)
                };

                var options = c.Get <Options>();

                return(new DefaultBackoffStrategy(backoffTimes.SelectMany(e => e), options));
            });

            PossiblyRegisterDefault <IWorkerFactory>(c =>
            {
                var transport          = c.Get <ITransport>();
                var rebusLoggerFactory = c.Get <IRebusLoggerFactory>();
                var pipelineInvoker    = c.Get <IPipelineInvoker>();
                var options            = c.Get <Options>();
                var busLifetimeEvents  = c.Get <BusLifetimeEvents>();
                var backoffStrategy    = c.Get <IBackoffStrategy>();
                var cancellationToken  = c.Get <CancellationToken>();

                return(new ThreadPoolWorkerFactory(
                           transport: transport,
                           rebusLoggerFactory: rebusLoggerFactory,
                           pipelineInvoker: pipelineInvoker,
                           options: options,
                           busGetter: c.Get <RebusBus>,
                           busLifetimeEvents: busLifetimeEvents,
                           backoffStrategy: backoffStrategy,
                           busDisposalCancellationToken: cancellationToken
                           ));
            });

            //PossiblyRegisterDefault<IWorkerFactory>(c =>
            //{
            //    var transport = c.Get<ITransport>();
            //    var loggerFactory = c.Get<IRebusLoggerFactory>();
            //    var pipelineInvoker = c.Get<IPipelineInvoker>();
            //    var options = c.Get<Options>();
            //    var busLifetimeEvents = c.Get<BusLifetimeEvents>();
            //    var backoffStrategy = c.Get<IBackoffStrategy>();
            //    return new TplWorkerFactory(transport, loggerFactory, pipelineInvoker, options, c.Get<RebusBus>, busLifetimeEvents, backoffStrategy);
            //});

            PossiblyRegisterDefault <IErrorTracker>(c =>
            {
                var transport          = c.Get <ITransport>();
                var settings           = c.Get <SimpleRetryStrategySettings>();
                var rebusLoggerFactory = c.Get <IRebusLoggerFactory>();
                var asyncTaskFactory   = c.Get <IAsyncTaskFactory>();
                var rebusTime          = c.Get <IRebusTime>();
                return(new InMemErrorTracker(settings, rebusLoggerFactory, asyncTaskFactory, transport, rebusTime));
            });

            PossiblyRegisterDefault <IErrorHandler>(c =>
            {
                var settings           = c.Get <SimpleRetryStrategySettings>();
                var transport          = c.Get <ITransport>();
                var rebusLoggerFactory = c.Get <IRebusLoggerFactory>();
                return(new PoisonQueueErrorHandler(settings, transport, rebusLoggerFactory));
            });

            PossiblyRegisterDefault <IFailFastChecker>(c => new FailFastChecker());

            PossiblyRegisterDefault <IRetryStrategy>(c =>
            {
                var simpleRetryStrategySettings = c.Get <SimpleRetryStrategySettings>();
                var rebusLoggerFactory          = c.Get <IRebusLoggerFactory>();
                var errorTracker      = c.Get <IErrorTracker>();
                var errorHandler      = c.Get <IErrorHandler>();
                var cancellationToken = c.Get <CancellationToken>();
                return(new SimpleRetryStrategy(simpleRetryStrategySettings, rebusLoggerFactory, errorTracker, errorHandler, cancellationToken));
            });

            PossiblyRegisterDefault(c => new SimpleRetryStrategySettings());

            PossiblyRegisterDefault(c =>
            {
                var transport          = c.Get <ITransport>();
                var timeoutManager     = c.Get <ITimeoutManager>();
                var rebusLoggerFactory = c.Get <IRebusLoggerFactory>();
                var asyncTaskFactory   = c.Get <IAsyncTaskFactory>();
                return(new HandleDeferredMessagesStep(timeoutManager, transport, _options, rebusLoggerFactory, asyncTaskFactory));
            });

            PossiblyRegisterDefault(c => c.Get <IRetryStrategy>().GetRetryStep());

            PossiblyRegisterDefault <IPipeline>(c =>
            {
                var serializer         = c.Get <ISerializer>();
                var transport          = c.Get <ITransport>();
                var rebusLoggerFactory = c.Get <IRebusLoggerFactory>();
                var options            = c.Get <Options>();
                var rebusTime          = c.Get <IRebusTime>();

                return(new DefaultPipeline()
                       .OnReceive(c.Get <IRetryStrategyStep>())
                       .OnReceive(new FailFastStep(c.Get <IErrorTracker>(), c.Get <IFailFastChecker>()))
                       .OnReceive(c.Get <HandleDeferredMessagesStep>())
                       .OnReceive(new HydrateIncomingMessageStep(c.Get <IDataBus>()))
                       .OnReceive(new DeserializeIncomingMessageStep(serializer))
                       .OnReceive(new HandleRoutingSlipsStep(transport, serializer))
                       .OnReceive(new ActivateHandlersStep(c.Get <IHandlerActivator>()))
                       .OnReceive(new LoadSagaDataStep(c.Get <ISagaStorage>(), rebusLoggerFactory))
                       .OnReceive(new DispatchIncomingMessageStep(rebusLoggerFactory))

                       .OnSend(new AssignDefaultHeadersStep(transport, rebusTime, options.DefaultReturnAddressOrNull))
                       .OnSend(new FlowCorrelationIdStep())
                       .OnSend(new AutoHeadersOutgoingStep())
                       .OnSend(new SerializeOutgoingMessageStep(serializer))
                       .OnSend(new ValidateOutgoingMessageStep())
                       .OnSend(new SendOutgoingMessageStep(transport, rebusLoggerFactory)));
            });

            RegisterDecorator <IPipeline>(c => new PipelineCache(c.Get <IPipeline>()));

            PossiblyRegisterDefault(c => new BusLifetimeEvents());

            PossiblyRegisterDefault <IDataBus>(c => new DisabledDataBus());

            PossiblyRegisterDefault <ITopicNameConvention>(c => new DefaultTopicNameConvention());

            // configuration hack - keep these two bad boys around to have them available at the last moment before returning the built bus instance...
            Action startAction = null;

            PossiblyRegisterDefault(c => new RebusBus(
                                        c.Get <IWorkerFactory>(),
                                        c.Get <IRouter>(),
                                        c.Get <ITransport>(),
                                        c.Get <IPipelineInvoker>(),
                                        c.Get <ISubscriptionStorage>(),
                                        _options,
                                        c.Get <IRebusLoggerFactory>(),
                                        c.Get <BusLifetimeEvents>(),
                                        c.Get <IDataBus>(),
                                        c.Get <ITopicNameConvention>(),
                                        c.Get <IRebusTime>()
                                        ));

            // since an error during resolution does not give access to disposable instances, we need to do this
            var disposableInstancesTrackedFromInitialResolution = new ConcurrentStack <IDisposable>();

            PossiblyRegisterDefault <IBus>(c =>
            {
                try
                {
                    var bus = c.Get <RebusBus>();
                    var cancellationTokenSource = c.Get <CancellationTokenSource>();

                    c.Get <BusLifetimeEvents>().BusDisposing += () => cancellationTokenSource.Cancel();

                    bus.Disposed += () =>
                    {
                        var disposableInstances = c.TrackedInstances.OfType <IDisposable>().Reverse();

                        foreach (var disposableInstance in disposableInstances)
                        {
                            disposableInstance.Dispose();
                        }
                    };

                    var initializableInstances = c.TrackedInstances.OfType <IInitializable>();

                    foreach (var initializableInstance in initializableInstances)
                    {
                        initializableInstance.Initialize();
                    }

                    // and then we set the startAction
                    startAction = () => bus.Start(_options.NumberOfWorkers);

                    return(bus);
                }
                catch
                {
                    // stash'em here quick!
                    foreach (var disposable in c.TrackedInstances.OfType <IDisposable>())
                    {
                        disposableInstancesTrackedFromInitialResolution.Push(disposable);
                    }
                    throw;
                }
            });

            _injectionist.Decorate <IHandlerActivator>(c =>
            {
                var handlerActivator            = c.Get <IHandlerActivator>();
                var subscriptionStorage         = c.Get <ISubscriptionStorage>();
                var internalHandlersContributor = new InternalHandlersContributor(handlerActivator, subscriptionStorage);
                return(internalHandlersContributor);
            });

            _injectionist.Decorate <ISerializer>(c =>
            {
                var serializer = c.Get <ISerializer>();
                var zipper     = new Zipper();
                var unzippingSerializerDecorator = new UnzippingSerializerDecorator(serializer, zipper);
                return(unzippingSerializerDecorator);
            });

            try
            {
                var busResolutionResult = _injectionist.Get <IBus>();
                var busInstance         = busResolutionResult.Instance;

                // if there is a container adapter among the tracked instances, hand it the bus instance
                var containerAdapter = busResolutionResult.TrackedInstances
                                       .OfType <IContainerAdapter>()
                                       .FirstOrDefault();

                containerAdapter?.SetBus(busInstance);

                // and NOW we are ready to start the bus if there is a startAction
                startAction?.Invoke();

                _hasBeenStarted = true;

                return(busInstance);
            }
            catch
            {
                while (disposableInstancesTrackedFromInitialResolution.TryPop(out var disposable))
                {
                    try
                    {
                        disposable.Dispose();
                    }
                    catch { } //< disposables must never throw, but sometimes they do
                }
                throw;
            }
        }
Exemple #19
0
 private void PrepareCourse()
 {
     InitializePaths(CourseUpload.FileName);
     CourseUpload.SaveAs(projectPaths.PathToCourseZipFile);
     Zipper.ExtractZipFile(projectPaths.PathToCourseZipFile, projectPaths.PathToTempCourseFolder);
 }
Exemple #20
0
    public void Left_right_and_value()
    {
        var zipper = Zipper <int> .FromTree(t1);

        Assert.Equal(3, zipper.Left().Right().Value);
    }
        /// <summary>圧縮処理</summary>
        private void btnCompress_Click(object sender, EventArgs e)
        {
            try
            {
                // チェック処理
                this.CheckComp_DeComp();

                // 圧縮部品
                Zipper z = new Zipper();

                // 選択基準
                string[] exts = null;
                Zipper.SelectionDelegate scd = null;

                if (this.txtExt.Enabled)
                {
                    exts = this.txtExt.Text.Split(',');
                    scd  = Program.SelectionCriteriaDlgt1;
                }

                // 形式指定
                SelfExtractorFlavor?selfEx = null;

                if (this.cmbFormat.Enabled)
                {
                    selfEx = (SelfExtractorFlavor)this.cmbFormat.SelectedItem;
                }

                // ZIP内パスのルート名
                string[] temp = this.txtFile.Text.Split('\\');

                // 進捗報告処理
                z.SaveProgress = Program.MySaveProgressEventHandler;

                // ルートのディレクトリを作るか作らないか。
                string rootPathInArchive = "";

                if (!this.cbxRootDir.Checked)
                {
                    rootPathInArchive = temp[temp.Length - 1];
                }

                // 圧縮(1)デリゲートでフィルタ
                z.CreateZipFromFolder(
                    this.txtFile.Text, this.txtFolder.Text,
                    scd, exts, rootPathInArchive, // ここを空文字列にするとルートフォルダ無しになる。
                    Encoding.GetEncoding((string)this.cmbEnc.SelectedItem),
                    (EncryptionAlgorithm)this.cmbCyp.SelectedItem, this.txtPass.Text,
                    (CompressionLevel)this.cmbCmpLv.SelectedItem, selfEx);

                //// 圧縮(2):selectionCriteriaStringでフィルタ
                //string selectionCriteriaString = "";
                //if (exts != null)
                //{
                //    foreach (string ext in exts)
                //    {
                //        if (selectionCriteriaString == "")
                //        {
                //            selectionCriteriaString = "name != *." + ext;
                //        }
                //        else
                //        {
                //            selectionCriteriaString += " and name != *." + ext;
                //        }
                //    }
                //}

                //z.CreateZipFromFolder(
                //    this.txtFile.Text, this.txtFolder.Text,
                //    selectionCriteriaString,
                //    temp[temp.Length - 1],
                //    Encoding.GetEncoding((string)this.cmbEnc.SelectedItem),
                //    (EncryptionAlgorithm)this.cmbCyp.SelectedItem, this.txtPass.Text,
                //    (CompressionLevel)this.cmbCmpLv.SelectedItem, selfEx);

                //MessageBox.Show(z.StatusMSG,"サマリ",
                //    MessageBoxButtons.OK, MessageBoxIcon.Information);

                CustMsgBox custMsgBox = new CustMsgBox(ResourceMgr.GetString("Error0002"), z.StatusMSG, SystemIcons.Information);
                custMsgBox.ShowDialog();
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "エラーが発生しました。", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //For internationalization, Replaced all the Japanese language to ResourceMgr.GetString() method call
                MessageBox.Show(ex.Message, ResourceMgr.GetString("E0001"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemple #22
0
    public void Tree_from_deep_focus()
    {
        var zipper = Zipper <int> .FromTree(t1);

        Assert.Equal(t1, zipper.Left().Right().ToTree());
    }
        public static ZipActionResult Zip(this ControllerBase controller, IEnumerable <FileItem> response, string fileName = "Photos")
        {
            byte[] archive = new Zipper().Zip(response).ToArray();

            return(new ZipActionResult(archive, fileName));
        }
        public ReferencedFileSave CreateReferencedFileSaveForExistingFile(IElement containerForFile, string directoryInsideContainer, string absoluteFileName,
                                                                          PromptHandleEnum unknownTypeHandle, AssetTypeInfo ati, out string creationReport, out string errorMessage)
        {
            creationReport = "";
            errorMessage   = null;

            ReferencedFileSave referencedFileSaveToReturn = null;

            string whyItIsntValid;
            // Let's see if there is already an Entity with the same name
            string fileWithoutPath = FileManager.RemovePath(FileManager.RemoveExtension(absoluteFileName));

            bool isValid =
                NameVerifier.IsReferencedFileNameValid(fileWithoutPath, ati, referencedFileSaveToReturn, containerForFile, out whyItIsntValid);

            if (!isValid)
            {
                errorMessage = "Invalid file name:\n" + fileWithoutPath + "\n" + whyItIsntValid;
            }
            else
            {
                Zipper.UnzipAndModifyFileIfZip(ref absoluteFileName);
                string extension = FileManager.GetExtension(absoluteFileName);

                bool isValidExtensionOrIsConfirmedByUser;
                bool isUnknownType;
                CheckAndWarnAboutUnknownFileTypes(unknownTypeHandle, extension, out isValidExtensionOrIsConfirmedByUser, out isUnknownType);

                string fileToAdd = null;
                if (isValidExtensionOrIsConfirmedByUser)
                {
                    string directoryThatFileShouldBeRelativeTo = GetFullPathContentDirectory(containerForFile, directoryInsideContainer);

                    string projectDirectory = ProjectManager.ContentProject.GetAbsoluteContentFolder();

                    bool needsToCopy = !FileManager.IsRelativeTo(absoluteFileName, projectDirectory);


                    if (needsToCopy)
                    {
                        fileToAdd = directoryThatFileShouldBeRelativeTo + FileManager.RemovePath(absoluteFileName);
                        fileToAdd = FileManager.MakeRelative(fileToAdd, ProjectManager.ContentProject.GetAbsoluteContentFolder());

                        try
                        {
                            FileHelper.RecursivelyCopyContentTo(absoluteFileName,
                                                                FileManager.GetDirectory(absoluteFileName),
                                                                directoryThatFileShouldBeRelativeTo);
                        }
                        catch (System.IO.FileNotFoundException fnfe)
                        {
                            errorMessage = "Could not copy the files because of a missing file: " + fnfe.Message;
                        }
                    }
                    else
                    {
                        fileToAdd = GetNameOfFileRelativeToContentFolder(absoluteFileName, directoryThatFileShouldBeRelativeTo, projectDirectory);
                    }
                }

                if (string.IsNullOrEmpty(errorMessage))
                {
                    BuildToolAssociation bta = null;

                    if (ati != null && !string.IsNullOrEmpty(ati.CustomBuildToolName))
                    {
                        bta =
                            BuildToolAssociationManager.Self.GetBuilderToolAssociationByName(ati.CustomBuildToolName);
                    }

                    if (containerForFile != null)
                    {
                        referencedFileSaveToReturn = containerForFile.AddReferencedFile(fileToAdd, ati, bta);
                    }
                    else
                    {
                        bool useFullPathAsName = false;
                        // todo - support built files here
                        referencedFileSaveToReturn = AddReferencedFileToGlobalContent(fileToAdd, useFullPathAsName);
                    }



                    // This will be null if there was an error above in creating this file
                    if (referencedFileSaveToReturn != null)
                    {
                        if (containerForFile != null)
                        {
                            containerForFile.HasChanged = true;
                        }

                        if (fileToAdd.EndsWith(".csv"))
                        {
                            string fileToAddAbsolute = ProjectManager.MakeAbsolute(fileToAdd);
                            CsvCodeGenerator.GenerateAndSaveDataClass(referencedFileSaveToReturn, referencedFileSaveToReturn.CsvDelimiter);
                        }
                        if (isUnknownType)
                        {
                            referencedFileSaveToReturn.LoadedAtRuntime = false;
                        }

                        GlueCommands.Self.ProjectCommands.UpdateFileMembershipInProject(referencedFileSaveToReturn);

                        PluginManager.ReactToNewFile(referencedFileSaveToReturn);
                        GluxCommands.Self.SaveGlux();
                        ProjectManager.SaveProjects();
                        UnreferencedFilesManager.Self.RefreshUnreferencedFiles(false);

                        string error;
                        referencedFileSaveToReturn.RefreshSourceFileCache(false, out error);

                        if (!string.IsNullOrEmpty(error))
                        {
                            ErrorReporter.ReportError(referencedFileSaveToReturn.Name, error, false);
                        }
                    }
                }
            }

            return(referencedFileSaveToReturn);
        }
Exemple #25
0
    public void Left_right_and_value()
    {
        var zipper = Zipper <int> .FromTree(t1);

        Assert.That(zipper.Left().Right().Value, Is.EqualTo(3));
    }
Exemple #26
0
        private void RectangleReport_MouseDown(object sender, MouseButtonEventArgs e)
        {
            IndexALL indexALL = JobDB.FindIndex(((Rectangle)sender).Tag.ToString());
            if (indexALL.JobIndex != -1)
            {
                switch (indexALL.Type)
                {
                    case EnumType.HashTag:
                        {
                            var job = db.job.HashTag[indexALL.JobIndex];
                            if (job.HashTag.Count == 0)
                            {
                                MessageBOX.Show("Нету данных, попробуйте позже..");
                            }
                            else
                            {
                                Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
                                sfd.Title = "Укажите путь, куда сохранить архив";
                                sfd.FileName = "archive";
                                sfd.DefaultExt = ".zip"; 
                                sfd.Filter = "archive|*.zip";

                                //Сохраняем архив
                                if ((bool)sfd.ShowDialog() == true)
                                {
                                    MessageBOX.Show("Данные успешно сохранены");
                                    Directory.CreateDirectory("tmp");

                                    //Сохраняем теги
                                    File.WriteAllLines(@"tmp\tag.txt", job.HashTag.ToArray());

                                    //Сохраняем список групп
                                    foreach (var g in job.Group.ToArray())
                                    {
                                        File.AppendAllText(@"tmp\group.txt", ("https://vk.com/public" + g.gid.ToString().Replace("-", "") + Environment.NewLine));
                                    }

                                    //Пакуем в архив
                                    Zipper zip = new Zipper();
                                    zip.ZipFile = sfd.FileName;
                                    zip.ItemList.Add(@"tmp\" + "*.*");
                                    zip.Recurse = true;
                                    zip.Comment = "VKHashTag - feedron.ru";
                                    zip.Zip();

                                    //Удаляем темп
                                    Directory.Delete("tmp", true);
                                    zip = null;
                                }
                                sfd = null;
                            }
                            job = null;
                            break;
                        }
                }
            }

            sender = null; e = null; indexALL = null;
        }
Exemple #27
0
 public void ExportedExamsReTurnsByteArray()
 {
     Assert.NotNull(Zipper.ExportedExams());
 }