public void Setup()
        {
            _fileSystem = new MemoryFileSystem().WithDrives("c:", "d:");

            _emptyDrive = _fileSystem.DriveDescribing("d:");
            _nonExistingDrive = _fileSystem.DriveDescribing("e:");
            _nonExistingDirectory = _fileSystem.DirectoryDescribing(@"c:\nonExistingDirectory");

            var populate = new FileSystemBuilder(_fileSystem);
            _emptyDirectory = populate.WithDir(@"c:\emptyDirectory");
            _nonEmptyDirectory = populate.WithDir(@"c:\crowdedDirectory");
            populate.WithDir(@"c:\crowdedDirectory\first");
            populate.WithDir(@"c:\crowdedDirectory\first\first");
            populate.WithDir(@"c:\crowdedDirectory\second");
        }
示例#2
0
        protected AggregateFileSystem GetCommonAggregateFileSystem(out MemoryFileSystem fs1, out MemoryFileSystem fs2, out MemoryFileSystem fs3)
        {
            // ----------------------------------------------
            // This creates the following AggregateFileSystem
            // ----------------------------------------------
            // /a                 -> fs2
            //     /a             -> fs1
            //        a1.txt      -> fs1
            //     /b             -> fs1
            //        b.i         -> fs1
            //     /C             -> fs2
            //     /d             -> fs2
            //     a1.txt         -> fs2
            //     A.txt          -> fs2
            //     b.txt          -> fs2
            //     c.txt1         -> fs2
            //     d.i            -> fs2
            //     f.i1           -> fs2
            //     E              -> fs2
            // /b                 -> fs1
            //    b.i             -> fs1
            // /C                 -> fs2
            // /d                 -> fs3
            // A.txt              -> fs3
            // b.txt              -> fs2
            // c.txt1             -> fs3
            // d.i                -> fs3
            // f.i1               -> fs3
            // E                  -> fs2

            fs1 = new MemoryFileSystem()
            {
                Name = "mem0"
            };
            CreateFolderStructure(fs1);
            fs2      = fs1.Clone();
            fs2.Name = "mem1";
            fs3      = fs2.Clone();
            fs3.Name = "mem2";

            // Delete part of fs2 so that it will fallback to fs1
            fs2.DeleteDirectory("/a/a", true);
            fs2.DeleteDirectory("/a/b", true);
            fs2.DeleteDirectory("/b", true);

            // Delete on fs3 to fallback to fs2 and fs1
            fs3.DeleteDirectory("/a", true);
            fs3.DeleteDirectory("/C", true);
            fs3.DeleteFile("/b.txt");
            fs3.DeleteFile("/E");

            var aggfs = new AggregateFileSystem(fs1);

            aggfs.AddFileSystem(fs2);
            aggfs.AddFileSystem(fs3);

            return(aggfs);
        }
示例#3
0
        public async Task ReadToEndSuccess(TestResultSet[] testDataSet)
        {
            // Setup: Create a results Available callback for result set
            //
            ResultSetSummary resultSummaryFromAvailableCallback = null;

            Task AvailableCallback(ResultSet r)
            {
                Debug.WriteLine($"available result notification sent, result summary was: {r.Summary}");
                resultSummaryFromAvailableCallback = r.Summary;
                return(Task.CompletedTask);
            }

            // Setup: Create a results updated callback for result set
            //
            List <ResultSetSummary> resultSummariesFromUpdatedCallback = new List <ResultSetSummary>();

            Task UpdatedCallback(ResultSet r)
            {
                Debug.WriteLine($"updated result notification sent, result summary was: {r.Summary}");
                resultSummariesFromUpdatedCallback.Add(r.Summary);
                return(Task.CompletedTask);
            }

            // Setup: Create a  results complete callback for result set
            //
            ResultSetSummary resultSummaryFromCompleteCallback = null;

            Task CompleteCallback(ResultSet r)
            {
                Debug.WriteLine($"Completed result notification sent, result summary was: {r.Summary}");
                resultSummaryFromCompleteCallback = r.Summary;
                return(Task.CompletedTask);
            }

            // If:
            // ... I create a new resultset with a valid db data reader that has data
            // ... and I read it to the end
            DbDataReader mockReader        = GetReader(testDataSet, false, Constants.StandardQuery);
            var          fileStreamFactory = MemoryFileSystem.GetFileStreamFactory(testDataSet[0].Rows.Count / Common.StandardRows + 1);
            ResultSet    resultSet         = new ResultSet(Common.Ordinal, Common.Ordinal, fileStreamFactory);

            resultSet.ResultAvailable  += AvailableCallback;
            resultSet.ResultUpdated    += UpdatedCallback;
            resultSet.ResultCompletion += CompleteCallback;
            await resultSet.ReadResultToEnd(mockReader, CancellationToken.None);

            Thread.Yield();
            resultSet.ResultAvailable  -= AvailableCallback;
            resultSet.ResultUpdated    -= UpdatedCallback;
            resultSet.ResultCompletion -= CompleteCallback;

            // Then:
            // ... The columns should be set
            // ... There should be rows to read back
            Assert.NotNull(resultSet.Columns);
            Assert.Equal(Common.StandardColumns, resultSet.Columns.Length);
            Assert.Equal(testDataSet[0].Rows.Count, resultSet.RowCount);

            // ... The summary should have the same info
            Assert.NotNull(resultSet.Summary.ColumnInfo);
            Assert.Equal(Common.StandardColumns, resultSet.Summary.ColumnInfo.Length);
            Assert.Equal(testDataSet[0].Rows.Count, resultSet.Summary.RowCount);

            // and:
            //
            VerifyReadResultToEnd(resultSet, resultSummaryFromAvailableCallback, resultSummaryFromCompleteCallback, resultSummariesFromUpdatedCallback);
        }
示例#4
0
        protected override async Task <bool> ProcessInternal()
        {
            if (this.Plugin == "csharp-simplifier")
            {
                var fs = new MemoryFileSystem();

                // setup filesystem
                var files = await ListInputs();

                foreach (var file in files)
                {
                    fs.WriteAllText(file, await ReadFile(file));
                }

                // simplify
                new AutoRest.Simplify.CSharpSimplifier().Run(fs).ConfigureAwait(false).GetAwaiter().GetResult();
                await WriteFiles(fs);

                return(true);
            }
            else
            {
                var files = await ListInputs();

                if (files.Length != 1)
                {
                    throw new Exception($"Generator received incorrect number of inputs: {files.Length} : {string.Join(",", files)}");
                }
                var modelAsJson = (await ReadFile(files[0])).EnsureYamlIsJson();
                var codeModelT  = new ModelSerializer <CodeModel>().Load(modelAsJson);

                // build settings
                var altNamespace = (await GetValue <string[]>("input-file") ?? new[] { "" }).FirstOrDefault()?.Split('/').Last().Split('\\').Last().Split('.').First();

                new Settings
                {
                    Namespace  = await GetValue("namespace"),
                    ClientName = GetXmsCodeGenSetting <string>(codeModelT, "name") ?? await GetValue("override-client-name"),
                    PayloadFlatteningThreshold = GetXmsCodeGenSetting <int?>(codeModelT, "ft") ?? await GetValue <int?>("payload-flattening-threshold") ?? 0,
                    AddCredentials             = await GetValue <bool?>("add-credentials") ?? false,
                    Host = this
                };
                var header = await GetValue("license-header");

                if (header != null)
                {
                    Settings.Instance.Header = header;
                }
                Settings.Instance.CustomSettings.Add("InternalConstructors", GetXmsCodeGenSetting <bool?>(codeModelT, "internalConstructors") ?? await GetValue <bool?>("use-internal-constructors") ?? false);
                Settings.Instance.CustomSettings.Add("SyncMethods", GetXmsCodeGenSetting <string>(codeModelT, "syncMethods") ?? await GetValue("sync-methods") ?? "essential");
                Settings.Instance.CustomSettings.Add("UseDateTimeOffset", GetXmsCodeGenSetting <bool?>(codeModelT, "useDateTimeOffset") ?? await GetValue <bool?>("use-datetimeoffset") ?? false);
                Settings.Instance.CustomSettings["ClientSideValidation"] = await GetValue <bool?>("client-side-validation") ?? false;

                int defaultMaximumCommentColumns = Settings.DefaultMaximumCommentColumns;
                Settings.Instance.MaximumCommentColumns = await GetValue <int?>("max-comment-columns") ?? defaultMaximumCommentColumns;

                Settings.Instance.OutputFileName = await GetValue <string>("output-file");

                Settings.Instance.Header = $"<auto-generated>\n{Settings.Instance.Header}\n</auto-generated>";

                // process
                var plugin = ExtensionsLoader.GetPlugin(
                    this.Plugin,
                    await GetValue <bool?>("azure-arm") ?? false,
                    await GetValue <bool?>("fluent") ?? false);
                Settings.PopulateSettings(plugin.Settings, Settings.Instance.CustomSettings);

                using (plugin.Activate())
                {
                    Settings.Instance.Namespace = Settings.Instance.Namespace ?? CodeNamer.Instance.GetNamespaceName(altNamespace);
                    var codeModel = plugin.Serializer.Load(modelAsJson);
                    codeModel = plugin.Transformer.TransformCodeModel(codeModel);
                    if (await GetValue <bool?>("sample-generation") ?? false)
                    {
                        plugin.CodeGenerator.GenerateSamples(codeModel).GetAwaiter().GetResult();
                    }
                    else
                    {
                        plugin.CodeGenerator.Generate(codeModel).GetAwaiter().GetResult();
                    }
                }

                // write out files
                await WriteFiles(Settings.Instance.FileSystemOutput);

                return(true);
            }
        }
示例#5
0
 public FileSystemEntryRedirect()
 {
     _fs = new MemoryFileSystem();
 }
示例#6
0
 public TestMemoryFileSystemCompact()
 {
     fs = new MemoryFileSystem();
 }
示例#7
0
 public MemoryFileSystemTest()
 {
     FileSystem = new MemoryFileSystem();
 }
 public void QueryExecuteNoSettings()
 {
     // If:
     // ... I create a query that has a null settings
     // Then:
     // ... It should throw an exception
     Assert.Throws <ArgumentNullException>(() =>
                                           new Query("Some query", Common.CreateTestConnectionInfo(null, false), null, MemoryFileSystem.GetFileStreamFactory()));
 }
示例#9
0
        public void BatchCreationTest()
        {
            // If I create a new batch...
            Batch batch = new Batch(Constants.StandardQuery, Common.SubsectionDocument, Common.Ordinal, MemoryFileSystem.GetFileStreamFactory());

            // Then:
            // ... The text of the batch should be stored
            Assert.NotEmpty(batch.BatchText);

            // ... It should not have executed and no error
            Assert.False(batch.HasExecuted, "The query should not have executed.");
            Assert.False(batch.HasError);

            // ... The results should be empty
            Assert.Empty(batch.ResultSets);
            Assert.Empty(batch.ResultSummaries);

            // ... The start line of the batch should be 0
            Assert.Equal(0, batch.Selection.StartLine);

            // ... It's ordinal ID should be what I set it to
            Assert.Equal(Common.Ordinal, batch.Id);

            // ... The summary should have the same info
            Assert.Equal(Common.Ordinal, batch.Summary.Id);
            Assert.Null(batch.Summary.ResultSetSummaries);
            Assert.Equal(0, batch.Summary.Selection.StartLine);
            Assert.NotEqual(default(DateTime).ToString("o"), batch.Summary.ExecutionStart); // Should have been set at construction
            Assert.Null(batch.Summary.ExecutionEnd);
            Assert.Null(batch.Summary.ExecutionElapsed);
        }
示例#10
0
        public async Task SupportModelsNameOverride()
        {
            using (NewContext)
            {
                string modelsName = "MyModels";

                MemoryFileSystem fileSystem = CreateMockFilesystem();

                var settings = new Settings
                {
                    Modeler         = "Swagger",
                    CodeGenerator   = "CSharp",
                    FileSystem      = fileSystem,
                    OutputDirectory = "GeneratedCode",
                    Namespace       = "Test",
                    ModelsName      = modelsName
                };

                using (fileSystem = $"{GetType().Name}".GenerateCodeInto(fileSystem, settings))
                {
                    // Expected Files
                    Assert.True(fileSystem.FileExists($@"{settings.OutputDirectory}\{modelsName}\ResultObject.cs"));

                    var result = await Compile(fileSystem);

                    // filter the warnings
                    var warnings = result.Messages.Where(
                        each => each.Severity == DiagnosticSeverity.Warning &&
                        !SuppressWarnings.Contains(each.Id)).ToArray();

                    // use this to dump the files to disk for examination
                    // fileSystem.SaveFilesToTemp($"{GetType().Name}");

                    // filter the errors
                    var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray();

                    Write(warnings, fileSystem);
                    Write(errors, fileSystem);

                    // use this to write out all the messages, even hidden ones.
                    // Write(result.Messages, fileSystem);

                    // Don't proceed unless we have zero Warnings.
                    Assert.Empty(warnings);

                    // Don't proceed unless we have zero Errors.
                    Assert.Empty(errors);

                    // Should also succeed.
                    Assert.True(result.Succeeded);

                    // try to load the assembly
                    var asm = Assembly.Load(result.Output.GetBuffer());
                    Assert.NotNull(asm);

                    // verify that we have the class we expected
                    var resultObject =
                        asm.ExportedTypes.FirstOrDefault(each => each.FullName == $"Test.{modelsName}.ResultObject");
                    Assert.NotNull(resultObject);
                }
            }
        }
示例#11
0
        public async Task ServerMessageHandlerShowsInfoMessages()
        {
            // Set up the batch to track message calls
            Batch  batch             = new Batch(Constants.StandardQuery, Common.SubsectionDocument, Common.Ordinal, MemoryFileSystem.GetFileStreamFactory());
            int    errorMessageCalls = 0;
            int    infoMessageCalls  = 0;
            string actualMessage     = null;

            batch.BatchMessageSent += args =>
            {
                if (args.IsError)
                {
                    errorMessageCalls++;
                }
                else
                {
                    infoMessageCalls++;
                }
                actualMessage = args.Message;
                return(Task.CompletedTask);
            };

            // If I call the server message handler with an info message
            var infoMessage = "info message";
            await batch.HandleSqlErrorMessage(0, 0, 0, 1, string.Empty, infoMessage);

            // Then one info message call should be recorded
            Assert.Equal(0, errorMessageCalls);
            Assert.Equal(1, infoMessageCalls);

            // And the actual message should be the exact info message
            Assert.Equal(infoMessage, actualMessage);
        }
示例#12
0
        public void CopyFile()
        {
            //
            {
                // Create 4GB file
                using (var s = ram.Open("bigfile", FileMode.Create, FileAccess.ReadWrite, FileShare.None))
                {
                    byte[] buf = new byte[4096];
                    for (int i = 0; i < 4096; i++)
                    {
                        buf[i] = (byte)(i & 0xff);
                    }
                    for (int i = 0; i < blocks; i++)
                    {
                        s.Write(buf, 0, buf.Length);
                    }
                }

                // TODO TEst | FileOperation.Policy.CancelIfError

                // File session
                using (var session = new OperationSession())
                {
                    // Copy file
                    {
                        // Operation
                        OperationBase op = new CopyFile(session, ram, "bigfile", ram, "bigfile.copy");
                        //
                        op.Estimate();
                        //
                        Assert.IsTrue(op.CanRollback);
                        //
                        op.Run();
                        // Assert
                        using (var s = ram.Open("bigfile.copy", FileMode.Open, FileAccess.Read, FileShare.None))
                        {
                            byte[] buf = new byte[4096];
                            for (int i = 0; i < blocks; i++)
                            {
                                int x = s.Read(buf, 0, buf.Length);
                                Assert.AreEqual(buf.Length, x);
                                for (int j = 0; j < buf.Length; j++)
                                {
                                    Assert.AreEqual(buf[j], (byte)(j & 0xff));
                                }
                            }
                        }
                    }

                    // Copy to existing file
                    {
                        // Operation
                        OperationBase op = new CopyFile(session, ram, "bigfile", ram, "bigfile.copy");
                        try
                        {
                            // Estimate
                            op.Estimate();
                            //
                            Assert.Fail("Estimate should have failed");
                        } catch (FileSystemException)
                        {
                            // Catched
                        }
                    }

                    // Copy, run out of memory, rollback
                    {
                        IFileSystem dst = new MemoryFileSystem(blockSize: 1024, maxSpace: 2048);
                        // Operation
                        OperationBase op = new CopyFile(session, ram, "bigfile", dst, "bigfile.copy");
                        //
                        op.Estimate();
                        //
                        Assert.IsTrue(op.CanRollback);
                        try
                        {
                            //
                            op.Run(rollbackOnError: true);
                        } catch (FileSystemExceptionOutOfDiskSpace)
                        {
                            Assert.IsFalse(dst.Exists("bigfile.copy"));
                        }
                    }
                }
            }
        }
示例#13
0
 public void Cleanup()
 {
     ram.Dispose();
     ram = null;
 }
示例#14
0
 public FileSystemEntryRedirect(MemoryFileSystem fs)
 {
     _fs = fs ?? throw new ArgumentNullException(nameof(fs));
 }
示例#15
0
        public static void Main(string[] args)
        {
            {
                #region Snippet_1
                IFileSystem filesystem = new MemoryFileSystem();
                #endregion Snippet_1
            }
            {
                #region Snippet_1b
                IFileSystem filesystem = new MemoryFileSystem(blockSize: 4096);
                #endregion Snippet_1b
            }
            {
                IFileSystem filesystem = new MemoryFileSystem();
                #region Snippet_2
                foreach (var entry in filesystem.Browse(""))
                {
                    Console.WriteLine(entry.Path);
                }
                #endregion Snippet_2
            }
            {
                IFileSystem filesystem = new MemoryFileSystem();
                filesystem.CreateFile("file.txt");
                #region Snippet_3a
                using (Stream s = filesystem.Open("file.txt", FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    Console.WriteLine(s.Length);
                }
                #endregion Snippet_3a
            }
            {
                IFileSystem filesystem = new MemoryFileSystem();
                filesystem.CreateFile("file.txt");
                #region Snippet_3b
                using (Stream s = filesystem.Open("file.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    s.WriteByte(32);
                }
                #endregion Snippet_3b
            }
            {
                IFileSystem filesystem = new MemoryFileSystem();
                #region Snippet_4
                IObserver <IEvent> observer = new Observer();
                using (IDisposable handle = filesystem.Observe("**", observer))
                {
                }
                #endregion Snippet_4
            }
            {
                IFileSystem filesystem = new MemoryFileSystem();
                #region Snippet_5
                filesystem.CreateDirectory("dir/");
                #endregion Snippet_5
            }

            {
                IFileSystem filesystem = new MemoryFileSystem();
                #region Snippet_5a
                filesystem.CreateDirectory("dir1/dir2/dir3/");
                filesystem.PrintTo(Console.Out);
                #endregion Snippet_5a
            }
            {
                IFileSystem filesystem = new MemoryFileSystem();
                #region Snippet_5b
                filesystem.CreateDirectory("/tmp/dir/");
                #endregion Snippet_5b
                filesystem.PrintTo(Console.Out);
            }
            {
                IFileSystem filesystem = new MemoryFileSystem();
                #region Snippet_5c
                filesystem.CreateDirectory("/tmp/dir/");
                #endregion Snippet_5c
                filesystem.PrintTo(Console.Out);
            }
            {
                IFileSystem filesystem = new MemoryFileSystem();
                #region Snippet_5d
                filesystem.CreateDirectory("file://");
                #endregion Snippet_5d
                filesystem.PrintTo(Console.Out);
            }

            {
                IFileSystem filesystem = new MemoryFileSystem();
                filesystem.CreateDirectory("dir/");
                #region Snippet_6
                filesystem.Delete("dir/", recurse: true);
                #endregion Snippet_6
            }
            {
                IFileSystem filesystem = new MemoryFileSystem();
                filesystem.CreateDirectory("dir/");
                #region Snippet_7
                filesystem.CreateDirectory("dir/");
                filesystem.Move("dir/", "new-name/");
                #endregion Snippet_7
                filesystem.Delete("new-name/");
            }

            {
                #region Snippet_8a
                IFileSystem filesystem = new MemoryFileSystem();
                #endregion Snippet_8a
                foreach (var entry in filesystem.Browse(""))
                {
                    Console.WriteLine(entry.Path);
                }
            }
            {
                #region Snippet_8b
                #endregion Snippet_8b
            }
            {
                #region Snippet_10a
                // Init
                object obj = new ReaderWriterLockSlim();
                IFileSystemDisposable filesystem = new FileSystem("").AddDisposable(obj);

                // ... do work ...

                // Dispose both
                filesystem.Dispose();
                #endregion Snippet_10a
            }
            {
                #region Snippet_10b
                IFileSystemDisposable filesystem = new FileSystem("")
                                                   .AddDisposeAction(f => Console.WriteLine("Disposed"));
                #endregion Snippet_10b
            }
            {
                #region Snippet_10c
                MemoryFileSystem filesystem = new MemoryFileSystem();
                filesystem.CreateDirectory("/tmp/dir/");

                // Postpone dispose
                IDisposable belateDisposeHandle = filesystem.BelateDispose();
                // Start concurrent work
                Task.Run(() =>
                {
                    // Do work
                    Thread.Sleep(1000);
                    filesystem.GetEntry("");
                    // Release belate handle. Disposes here or below, depending which thread runs last.
                    belateDisposeHandle.Dispose();
                });

                // Start dispose, but postpone it until belatehandle is disposed in another thread.
                filesystem.Dispose();
                #endregion Snippet_10c
            }

            {
                // <Snippet_20a>
                IFileSystem ms = new MemoryFileSystem(blockSize: 1024, maxSpace: 1L << 34);
                // </Snippet_20a>
            }
            {
                // <Snippet_20b>
                IFileSystem ms = new MemoryFileSystem(blockSize: 1024, maxSpace: 1L << 34);
                ms.CreateFile("file", new byte[1 << 30]);
                ms.PrintTo(Console.Out, format: PrintTree.Format.AllWithName);
                // </Snippet_20b>
            }
            {
                try
                {
                    // <Snippet_20c>
                    IFileSystem ms = new MemoryFileSystem(blockSize: 1024, maxSpace: 2048);
                    ms.CreateFile("file1", new byte[1024]);
                    ms.CreateFile("file2", new byte[1024]);

                    // throws FileSystemExceptionOutOfDiskSpace
                    ms.CreateFile("file3", new byte[1024]);
                    // </Snippet_20c>
                }
                catch (FileSystemExceptionOutOfDiskSpace) { }
            }
            {
                try
                {
                    // <Snippet_20d>
                    IBlockPool  pool = new BlockPool(blockSize: 1024, maxBlockCount: 3, maxRecycleQueue: 3);
                    IFileSystem ms1  = new MemoryFileSystem(pool);
                    IFileSystem ms2  = new MemoryFileSystem(pool);

                    // Reserve 2048 from shared pool
                    ms1.CreateFile("file1", new byte[2048]);

                    // Not enough for another 3072, throws FileSystemExceptionOutOfDiskSpace
                    ms2.CreateFile("file2", new byte[2048]);
                    // </Snippet_20d>
                }
                catch (FileSystemExceptionOutOfDiskSpace) { }
            }
            {
                try
                {
                    // <Snippet_20e>
                    IBlockPool  pool = new BlockPool(blockSize: 1024, maxBlockCount: 3, maxRecycleQueue: 3);
                    IFileSystem ms   = new MemoryFileSystem(pool);
                    Stream      s    = ms.Open("file", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                    s.Write(new byte[3072], 0, 3072);
                    ms.Delete("file");

                    Console.WriteLine(pool.BytesAvailable); // Prints 0
                    s.Dispose();
                    Console.WriteLine(pool.BytesAvailable); // Prints 3072
                    // </Snippet_20e>
                }
                catch (FileSystemExceptionOutOfDiskSpace) { }
            }
        }
示例#16
0
 public void QueryExecuteNoConnectionInfo()
 {
     // If:
     // ... I create a query that has a null connection info
     // Then:
     // ... It should throw an exception
     Assert.Throws <ArgumentNullException>(() => new Query("Some Query", null, new QueryExecutionSettings(), MemoryFileSystem.GetFileStreamFactory()));
 }
示例#17
0
 public void BatchExecuteNoSql(string query)
 {
     // If:
     // ... I create a batch that has an empty query
     // Then:
     // ... It should throw an exception
     Assert.Throws <ArgumentException>(() => new Batch(query, Common.SubsectionDocument, Common.Ordinal, MemoryFileSystem.GetFileStreamFactory()));
 }
示例#18
0
 public void BatchInvalidOrdinal()
 {
     // If:
     // ... I create a batch has has an ordinal less than 0
     // Then:
     // ... It should throw an exception
     Assert.Throws <ArgumentOutOfRangeException>(() => new Batch("stuff", Common.SubsectionDocument, -1, MemoryFileSystem.GetFileStreamFactory()));
 }
示例#19
0
        public void StatementCompletedHandlerTest()
        {
            // If:
            // ... I call the StatementCompletedHandler
            Batch batch        = new Batch(Constants.StandardQuery, Common.SubsectionDocument, Common.Ordinal, MemoryFileSystem.GetFileStreamFactory());
            int   messageCalls = 0;

            batch.BatchMessageSent += args =>
            {
                messageCalls++;
                return(Task.FromResult(0));
            };

            // Then:
            // ... The message handler for the batch should havve been called twice
            batch.StatementCompletedHandler(null, new StatementCompletedEventArgs(1));
            Assert.True(messageCalls == 1);
            batch.StatementCompletedHandler(null, new StatementCompletedEventArgs(2));
            Assert.True(messageCalls == 2);
        }
示例#20
0
        public static void Main(string[] args)
        {
            {
                // <Snippet_1>
                IFileSystem ms = new MemoryFileSystem();
                ms.CreateFile("file", new byte[1024 * 1024]);

                using (var s = new OperationSession())
                {
                    new CopyFile(s, ms, "file", ms, "file.copy")
                    .Estimate()
                    .AssertCanRollback()
                    .Run()
                    .AssertSuccessful();
                }
                // </Snippet_1>

                ms.PrintTo(Console.Out, format: PrintTree.Format.Default | PrintTree.Format.Length);
            }

            {
                IFileSystem ms = new MemoryFileSystem();
                ms.CreateFile("file", new byte[1024 * 1024]);
                // <Snippet_1b>
                var s  = new OperationSession();
                var op = new CopyFile(s, ms, "file", ms, "file.copy");
                op.Estimate();
                // </Snippet_1b>
                // <Snippet_1b1>
                Console.WriteLine(op.CanRollback);
                // </Snippet_1b1>


                // <Snippet_1b2>
                op.Estimate().AssertCanRollback();
                // </Snippet_1b2>

                // <Snippet_1c>
                op.Run();
                // </Snippet_1c>

                // <Snippet_1c1>
                if (op.CurrentState == OperationState.Completed)
                {
                    Console.WriteLine("ok");
                }
                // </Snippet_1c1>

                ms.Delete("file.copy");
                op = (CopyFile) new CopyFile(s, ms, "file", ms, "file.copy").Estimate();
                // <Snippet_1c2>
                op.Run().AssertSuccessful();
                // </Snippet_1c2>

                ms.Delete("file.copy");
                op = (CopyFile) new CopyFile(s, ms, "file", ms, "file.copy").Estimate();
                // <Snippet_1c3>
                try
                {
                    op.Run();
                }
                catch (Exception)
                {
                    // Rollback
                    op.CreateRollback()?.Run();
                }
                // </Snippet_1c3>

                // <Snippet_1c4>
                op.Run(rollbackOnError: true);
                // </Snippet_1c4>
            }

            {
                // <Snippet_2>
                IFileSystem ms = new MemoryFileSystem();
                ms.CreateDirectory("dir/dir/dir/");
                ms.CreateFile("dir/dir/dir/file", new byte[1024 * 1024]);

                using (var s = new OperationSession())
                {
                    var op = new CopyTree(s, ms, "dir", ms, "dir.copy");

                    op.Estimate().AssertCanRollback().Run().AssertSuccessful();
                }
                // </Snippet_2>
                ms.PrintTo(Console.Out);
            }
            {
                // <Snippet_3>
                IFileSystem ms = new MemoryFileSystem();
                using (var s = new OperationSession(policy: OperationPolicy.EstimateOnRun /*important*/))
                {
                    Batch batch = new Batch(s, OperationPolicy.Unset);

                    batch.Ops.Add(new CreateDirectory(s, ms, "dir/dir/dir"));
                    batch.Ops.Add(new CopyTree(s, ms, "dir", ms, "dir.copy"));
                    batch.Ops.Add(new Delete(s, ms, "dir/dir", true, policy: OperationPolicy.EstimateOnRun));
                    batch.Estimate().Run().AssertSuccessful();
                }
                // </Snippet_3>
                ms.PrintTo(Console.Out);
            }
            {
                // <Snippet_4>
                IFileSystem ms_src = new MemoryFileSystem();
                ms_src.CreateDirectory("dir/dir/dir/");
                ms_src.CreateFile("dir/dir/dir/file", new byte[1024 * 1024]);

                IFileSystem ms_dst = new MemoryFileSystem();

                using (var s = new OperationSession())
                {
                    var op = new TransferTree(s, ms_src, "dir", ms_dst, "dir.elsewhere");
                    op.Estimate().AssertCanRollback().Run().AssertSuccessful();
                }
                // </Snippet_4>
                ms_dst.PrintTo(Console.Out);
            }
            {
                // <Snippet_5>
                IFileSystem ms = new MemoryFileSystem();
                ms.CreateFile("file", new byte[1024 * 1024]);

                using (var s = new OperationSession())
                {
                    new CopyFile(s, ms, "file", ms, "file.copy")
                    .Estimate()
                    .AssertCanRollback()
                    .Run()
                    .AssertSuccessful();

                    foreach (var @event in s.Events)
                    {
                        Console.WriteLine(@event);
                    }
                }
                ms.PrintTo(Console.Out);
                // </Snippet_5>
            }
            {
                // <Snippet_6>
                IFileSystem ms = new MemoryFileSystem();
                ms.CreateFile("file", new byte[1024 * 20]);

                using (var s = new OperationSession().SetProgressInterval(1024))
                {
                    s.Subscribe(new OpEventPrinter());

                    new CopyFile(s, ms, "file", ms, "file.copy")
                    .Estimate()
                    .AssertCanRollback()
                    .Run()
                    .AssertSuccessful();
                }
                ms.PrintTo(Console.Out);
                // </Snippet_6>
            }
            {
                try
                {
                    // <Snippet_7>
                    IFileSystem ms = new MemoryFileSystem();
                    ms.CreateFile("file", new byte[1024 * 10]);
                    CancellationTokenSource cancelSrc = new CancellationTokenSource();

                    using (var s = new OperationSession(cancelSrc: cancelSrc))
                    {
                        cancelSrc.Cancel();
                        new Move(s, ms, "file", ms, "file.moved")
                        .Estimate()
                        .AssertCanRollback()
                        .Run()
                        .AssertSuccessful();
                    }
                    // </Snippet_7>
                } catch (Exception e)
                {
                }
            }
            {
                // <Snippet_8>
                // </Snippet_8>
            }
            {
                // <Snippet_9>
                // </Snippet_9>
            }
            {
                // <Snippet_10>
                // </Snippet_10>
            }
            {
                // <Snippet_11>
                // </Snippet_11>
            }
            {
                // <Snippet_12>
                // </Snippet_12>
            }
            {
                // <Snippet_13>
                // </Snippet_13>
            }
            {
                // <Snippet_14>
                // </Snippet_14>
            }
            {
                // <Snippet_15>
                // </Snippet_15>
            }
            {
                // <Snippet_16>
                // </Snippet_16>
            }
        }
示例#21
0
        public async Task Run(MemoryFileSystem fs)
        {
            string[] skipNamespace = (await Settings.Instance.Host.GetValue <string[]>("skip-simplifier-on-namespace"));

            var files = fs.GetFiles("", "*.cs", SearchOption.AllDirectories).
                        ToDictionary(each => each, each => fs.ReadAllText(each));

            var assemblies = new[] {
                typeof(IAzureClient).GetAssembly().Location,
                typeof(RestException).GetAssembly().Location,
                typeof(Uri).GetAssembly().Location,
                typeof(File).GetAssembly().Location,
                typeof(HttpStatusCode).GetAssembly().Location,
                typeof(System.Net.Http.HttpClient).GetAssembly().Location,
                typeof(object).GetAssembly().Location,
                typeof(XElement).GetAssembly().Location,
                typeof(JsonConvert).GetAssembly().Location
            };

            var projectId = ProjectId.CreateNewId();
            var solution  = new AdhocWorkspace().CurrentSolution
                            .AddProject(projectId, "MyProject", "MyProject", LanguageNames.CSharp);

            // add assemblies
            solution = assemblies.Aggregate(solution, (current, asm) => current.AddMetadataReference(projectId, MetadataReference.CreateFromFile(asm)));

            // Add existing files
            foreach (var file in files.Keys)
            {
                var documentId = DocumentId.CreateNewId(projectId);
                solution = solution.AddDocument(documentId, file, SourceText.From(files[file]));
            }

            // Simplify docs and add to
            foreach (var proj in solution.Projects)
            {
                foreach (var document in proj.Documents)
                {
                    var newRoot = await document.GetSyntaxRootAsync();

                    // get the namespaces used in the file
                    var names = new GetQualifiedNames().GetNames(newRoot).Where(each => !skipNamespace.Any(ns => ns == each)).ToArray();

                    // add the usings that we found
                    newRoot = new AddUsingsRewriter(names).Visit(newRoot);

                    // tell roslyn to simplify where it can
                    newRoot = new SimplifyNamesRewriter().Visit(newRoot);
                    var doc = document.WithSyntaxRoot(newRoot);

                    // reduce the code
                    var text = Simplifier.ReduceAsync(doc)
                               .Result.GetTextAsync()
                               .Result.ToString()
                               // get rid of any BOMs
                               .Trim('\x00EF', '\x00BB', '\x00BF', '\uFEFF', '\u200B');


                    // special cases the simplifier can't handle.
                    text = text.
                           Replace("[Newtonsoft.Json.JsonConverter(", "[JsonConverter(").
                           Replace("[System.Runtime.Serialization.EnumMember(", "[EnumMember(").
                           Replace("[Newtonsoft.Json.JsonProperty(", "[JsonProperty(").
                           Replace("[Newtonsoft.Json.JsonProperty]", "[JsonProperty]").
                           Replace("[Newtonsoft.Json.JsonObject]", "[JsonObject]").
                           Replace("[Microsoft.Rest.Serialization.JsonTransformation]", "[JsonTransformation]").
                           Replace("[Newtonsoft.Json.JsonExtensionData]", "[JsonExtensionData]");

                    // Write out the files back to their original location
                    fs.WriteAllText(document.Name, text);
                }
            }
        }
示例#22
0
 public void Initialize()
 {
     FileSystem = new MemoryFileSystem();
 }
示例#23
0
        public async Task ReadToEndForXmlJson(string forType)
        {
            // Setup:
            // ... Build a FOR XML or FOR JSON data set
            //
            DbColumn[]      columns  = { new TestDbColumn(string.Format("{0}_F52E2B61-18A1-11d1-B105-00805F49916B", forType)) };
            object[][]      rows     = Enumerable.Repeat(new object[] { "test data" }, Common.StandardRows).ToArray();
            TestResultSet[] dataSets = { new TestResultSet(columns, rows) };

            // Setup: Create a results Available callback for result set
            //
            ResultSetSummary resultSummaryFromAvailableCallback = null;

            Task AvailableCallback(ResultSet r)
            {
                Debug.WriteLine($"available result notification sent, result summary was: {r.Summary}");
                resultSummaryFromAvailableCallback = r.Summary;
                return(Task.CompletedTask);
            }

            // Setup: Create a results updated callback for result set
            //
            List <ResultSetSummary> resultSummariesFromUpdatedCallback = new List <ResultSetSummary>();

            Task UpdatedCallback(ResultSet r)
            {
                Debug.WriteLine($"updated result notification sent, result summary was: {r.Summary}");
                resultSummariesFromUpdatedCallback.Add(r.Summary);
                return(Task.CompletedTask);
            }

            // Setup: Create a  results complete callback for result set
            //
            ResultSetSummary resultSummaryFromCompleteCallback = null;

            Task CompleteCallback(ResultSet r)
            {
                Debug.WriteLine($"Completed result notification sent, result summary was: {r.Summary}");
                Assert.True(r.Summary.Complete);
                resultSummaryFromCompleteCallback = r.Summary;
                return(Task.CompletedTask);
            }

            // If:
            // ... I create a new result set with a valid db data reader that is FOR XML/JSON
            // ... and I read it to the end
            //
            DbDataReader mockReader        = GetReader(dataSets, false, Constants.StandardQuery);
            var          fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
            ResultSet    resultSet         = new ResultSet(Common.Ordinal, Common.Ordinal, fileStreamFactory);

            resultSet.ResultAvailable  += AvailableCallback;
            resultSet.ResultUpdated    += UpdatedCallback;
            resultSet.ResultCompletion += CompleteCallback;
            var   readResultTask = resultSet.ReadResultToEnd(mockReader, CancellationToken.None);
            await readResultTask;

            Debug.AutoFlush = true;
            Debug.Assert(readResultTask.IsCompletedSuccessfully, $"readResultTask did not Complete Successfully. Status: {readResultTask.Status}");
            Thread.Yield();
            resultSet.ResultAvailable  -= AvailableCallback;
            resultSet.ResultUpdated    -= UpdatedCallback;
            resultSet.ResultCompletion -= CompleteCallback;
            // Then:
            // ... There should only be one column
            // ... There should only be one row
            //
            Assert.Equal(1, resultSet.Columns.Length);
            Assert.Equal(1, resultSet.RowCount);


            // and:
            //
            VerifyReadResultToEnd(resultSet, resultSummaryFromAvailableCallback, resultSummaryFromCompleteCallback, resultSummariesFromUpdatedCallback);

            // If:
            // ... I attempt to read back the results
            // Then:
            // ... I should only get one row
            //
            var task = resultSet.GetSubset(0, 10);

            task.Wait();
            var subset = task.Result;

            Assert.Equal(1, subset.RowCount);
        }
示例#24
0
 public static void SavingDependenciesInMemoryFileSystem()
 {
     // ExStart:SavingDependenciesInMemoryFileSystem
     // The code example uses the MemoryFileSystem to intercepts the dependencies writing.
     // The path to the documents directory.
     string MyDir = RunExamples.GetDataDir();
     // Initialize Scene object
     Scene scene = new Scene();
     // Create a child node
     scene.RootNode.CreateChildNode("sphere", new Sphere()).Material = new PhongMaterial();
     // Set saving options
     ObjSaveOptions opt = new ObjSaveOptions();
     MemoryFileSystem mfs = new MemoryFileSystem();
     opt.FileSystem = mfs;
     // Save 3D scene
     scene.Save(MyDir + "SavingDependenciesInMemoryFileSystem_out.obj", opt);
     // Get the test.mtl file content
     byte[] mtl = mfs.GetFileContent(MyDir + "test.mtl");
     File.WriteAllBytes( MyDir + "Material.mtl", mtl);
     // ExEnd:SavingDependenciesInMemoryFileSystem
 }
示例#25
0
        public void CheckFunction()
        {
            var options = new CSharpConverterOptions()
            {
                GenerateAsInternal   = true,
                TypedefCodeGenKind   = CppTypedefCodeGenKind.Wrap,
                TypedefWrapWhiteList =
                {
                    "git_my_string"
                }
            };

            var csCompilation = CSharpConverter.Convert(@"
            #ifdef WIN32
            #define EXPORT_API __declspec(dllexport)
            #else
            #define EXPORT_API __attribute__((visibility(""default"")))
            #endif

            enum Toto
            {
                TOTO = 0,
                TOTO_FLAG = 1 << 0,
            };

            // This is a comment
            struct Tata
            {
                int a;

                int b;
                int c;
                char items[4];
                int item2[8];

                const char* d;
            };

            struct git_my_repo;

            typedef int git_my_yoyo;

            typedef const char* git_my_string;

            // This is a comment.
            // This is another comment
            // @param myrepo yoyo
            // @return This is a big list of things to return
            EXPORT_API bool function0(git_my_repo* myrepo, int a, float b, const char* text, const char text2[], bool arg4[], git_my_yoyo arg5, git_my_string arg6);
            ", options);

            Assert.False(csCompilation.HasErrors);

            var fs         = new MemoryFileSystem();
            var codeWriter = new CodeWriter(new CodeWriterOptions(fs));

            csCompilation.DumpTo(codeWriter);

            var text = fs.ReadAllText(options.DefaultOutputFilePath);

            Console.WriteLine(text);
        }