System.IO.Path.GetRandomFileName()

Here are the examples of the csharp api System.IO.Path.GetRandomFileName() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

567 Examples 7

19 Source : OutputTasks.cs
with GNU General Public License v3.0
from BloodHoundAD

internal static async Task CollapseLoopZipFiles()
        {
            var options = Options.Instance;
            if (options.NoOutput || options.NoZip)
                return;

            var finalName = Helpers.GetLoopFileName();

            Console.WriteLine($"Compressing zip files to {finalName}");

            var buffer = new byte[4096];

            if (File.Exists(finalName))
            {
                Console.WriteLine("Zip File already exists, randomizing filename");
                finalName = Helpers.ResolveFileName(Path.GetRandomFileName(), "zip", true);
                Console.WriteLine($"New filename is {finalName}");
            }

            using (var zipStream = new ZipOutputStream(File.Create(finalName)))
            {
                //Set level to 0, since we're just storing the other zips
                zipStream.SetLevel(0);

                if (options.EncryptZip)
                {
                    var preplacedword = ZipPreplacedwords.Value;
                    zipStream.Preplacedword = preplacedword;
                    Console.WriteLine($"Preplacedword for zip file is {preplacedword}. Unzip files manually to upload to interface");
                }
                else
                {
                    Console.WriteLine("Unzip the zip file and upload the other zips to the interface");
                }

                foreach (var file in ZipFileNames)
                {
                    var entry = new ZipEntry(Path.GetFileName(file)) { DateTime = DateTime.Now };
                    zipStream.PutNextEntry(entry);

                    using (var fileStream = File.OpenRead(file))
                    {
                        int source;
                        do
                        {
                            source = await fileStream.ReadAsync(buffer, 0, buffer.Length);
                            zipStream.Write(buffer, 0, source);
                        } while (source > 0);
                    }

                    File.Delete(file);
                }

                zipStream.Finish();
            }
        }

19 Source : OutputTasks.cs
with GNU General Public License v3.0
from BloodHoundAD

internal static async Task CompleteOutput()
        {
            PrintStatus();
            Console.WriteLine($"Enumeration finished in {_runTimer.Elapsed}");

            if (Options.Instance.DumpComputerStatus)
            {
                CompleteComputerStatusOutput();
                await _computerStatusTask;
            }

            var domainName = Helpers.NormalizeDomainName(Options.Instance.Domain);
            var forestName = Helpers.GetForestName(domainName).ToUpper();
            var dcSids = BaseProducer.GetDomainControllers();
            var domainSid = new SecurityIdentifier(dcSids.First().Key).AccountDomainSid.Value.ToUpper();
            var enterpriseDomainControllers = new Group(null)
            {
                ObjectIdentifier = $"{forestName}-S-1-5-9",
                Domain = forestName,
                Members = BaseProducer.GetDomainControllers().Keys.Select(sid => new GenericMember
                {
                    MemberId = sid,
                    MemberType = LdapTypeEnum.Computer
                }).ToArray()
            };

            enterpriseDomainControllers.Properties.Add("name", $"ENTERPRISE DOMAIN CONTROLLERS@{forestName}");
            enterpriseDomainControllers.Properties.Add("domain", forestName);

            _groupOutput.Value.WriteObject(enterpriseDomainControllers);

            var members = new[]
            {
                new GenericMember
                {
                    MemberType = LdapTypeEnum.Group,
                    MemberId = $"{domainSid}-515"
                },
                new GenericMember
                {
                    MemberType = LdapTypeEnum.Group,
                    MemberId = $"{domainSid}-513"
                }
            };

            var everyone = new Group(null)
            {
                ObjectIdentifier = $"{domainName}-S-1-1-0",
                Domain = domainName,
                Members = members
            };

            everyone.Properties.Add("name", $"EVERYONE@{domainName}");
            everyone.Properties.Add("domain", domainName);

            _groupOutput.Value.WriteObject(everyone);

            var authUsers = new Group(null)
            {
                ObjectIdentifier = $"{domainName}-S-1-5-11",
                Domain = domainName,
                Members = members
            };

            authUsers.Properties.Add("name", $"AUTHENTICATED USERS@{domainName}");
            authUsers.Properties.Add("domain", domainName);

            _groupOutput.Value.WriteObject(authUsers);

            //Write objects for common principals
            foreach (var seen in SeenCommonPrincipals)
            {
                var domain = seen.Key;
                var sid = seen.Value;

                CommonPrincipal.GetCommonSid(sid, out var principal);

                sid = Helpers.ConvertCommonSid(sid, domain);
                switch (principal.Type)
                {
                    case LdapTypeEnum.User:
                        var u = new User(null)
                        {
                            ObjectIdentifier = sid
                        };
                        u.Properties.Add("name", $"{principal.Name}@{domain}".ToUpper());
                        u.Properties.Add("domain", domain);
                        _userOutput.Value.WriteObject(u);
                        break;
                    case LdapTypeEnum.Computer:
                        var c = new Computer(null)
                        {
                            ObjectIdentifier = sid
                        };

                        c.Properties.Add("name", $"{principal.Name}@{domain}".ToUpper());
                        c.Properties.Add("domain", domain);
                        _computerOutput.Value.WriteObject(c);
                        break;
                    case LdapTypeEnum.Group:
                        var g = new Group(null)
                        {
                            ObjectIdentifier = sid
                        };
                        g.Properties.Add("name", $"{principal.Name}@{domain}".ToUpper());
                        g.Properties.Add("domain", domain);
                        _groupOutput.Value.WriteObject(g);
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }
            }

            _runTimer.Stop();
            _statusTimer.Stop();
            if (_userOutput.IsValueCreated)
                _userOutput.Value.CloseWriter();
            if (_computerOutput.IsValueCreated)
                _computerOutput.Value.CloseWriter();
            if (_groupOutput.IsValueCreated)
                _groupOutput.Value.CloseWriter();
            if (_domainOutput.IsValueCreated)
                _domainOutput.Value.CloseWriter();
            if (_gpoOutput.IsValueCreated)
                _gpoOutput.Value.CloseWriter();
            if (_ouOutput.IsValueCreated)
                _ouOutput.Value.CloseWriter();

            _userOutput = new Lazy<JsonFileWriter>(() => new JsonFileWriter("users"), false);
            _groupOutput = new Lazy<JsonFileWriter>(() => new JsonFileWriter("groups"), false);
            _computerOutput = new Lazy<JsonFileWriter>(() => new JsonFileWriter("computers"), false);
            _domainOutput = new Lazy<JsonFileWriter>(() => new JsonFileWriter("domains"), false);
            _gpoOutput = new Lazy<JsonFileWriter>(() => new JsonFileWriter("gpos"), false);
            _ouOutput = new Lazy<JsonFileWriter>(() => new JsonFileWriter("ous"), false);

            string finalName;
            var options = Options.Instance;

            if (options.NoZip || options.NoOutput)
                return;

            if (options.ZipFilename != null)
                finalName = Helpers.ResolveFileName(Options.Instance.ZipFilename, "zip", true);
            else
            {
                finalName = Helpers.ResolveFileName("BloodHound", "zip", true);
            }

            Console.WriteLine($"Compressing data to {finalName}");

            var buffer = new byte[4096];

            if (File.Exists(finalName))
            {
                Console.WriteLine("Zip File already exists, randomizing filename");
                finalName = Helpers.ResolveFileName(Path.GetRandomFileName(), "zip", true);
                Console.WriteLine($"New filename is {finalName}");
            }

            using (var zipStream = new ZipOutputStream(File.Create(finalName)))
            {
                //Set level to 9, maximum compressions
                zipStream.SetLevel(9);

                if (options.EncryptZip)
                {
                    if (!options.Loop)
                    {
                        var preplacedword = ZipPreplacedwords.Value;
                        zipStream.Preplacedword = preplacedword;

                        Console.WriteLine($"Preplacedword for Zip file is {preplacedword}. Unzip files manually to upload to interface");
                    }
                }
                else
                {
                    Console.WriteLine("You can upload this file directly to the UI");
                }

                foreach (var file in UsedFileNames)
                {
                    var entry = new ZipEntry(Path.GetFileName(file)) { DateTime = DateTime.Now };
                    zipStream.PutNextEntry(entry);

                    using (var fileStream = File.OpenRead(file))
                    {
                        int source;
                        do
                        {
                            source = await fileStream.ReadAsync(buffer, 0, buffer.Length);
                            zipStream.Write(buffer, 0, source);
                        } while (source > 0);
                    }

                    File.Delete(file);
                }

                zipStream.Finish();
            }

            if (options.Loop)
                ZipFileNames.Add(finalName);

            UsedFileNames.Clear();
        }

19 Source : Helpers.cs
with GNU General Public License v3.0
from BloodHoundAD

internal static string GetLoopFileName()
        {
            var options = Options.Instance;
            var finalFilename = options.ZipFilename == null ? "BloodHoundLoopResults.zip" : $"{options.ZipFilename}.zip";

            if (options.RandomizeFilenames)
            {
                finalFilename = $"{Path.GetRandomFileName()}.zip";
            }

            finalFilename = $"{ProcStartTime}_{finalFilename}";

            if (options.OutputPrefix != null)
            {
                finalFilename = $"{options.OutputPrefix}_{finalFilename}";
            }

            var finalPath = Path.Combine(options.OutputDirectory, finalFilename);

            return finalPath;
        }

19 Source : Helpers.cs
with GNU General Public License v3.0
from BloodHoundAD

internal static string ResolveFileName(string filename, string extension, bool addTimestamp)
        {
            var finalFilename = filename;
            if (!filename.EndsWith(extension))
                finalFilename = $"{filename}.{extension}";

            if ((extension == "json" || extension == "zip") && Options.Instance.RandomizeFilenames)
            {
                finalFilename = $"{Path.GetRandomFileName()}";
            }

            if (addTimestamp)
            {
                finalFilename = $"{_currentLoopTime}_{finalFilename}";
            }

            if (Options.Instance.OutputPrefix != null)
            {
                finalFilename = $"{Options.Instance.OutputPrefix}_{finalFilename}";
            }

            var finalPath = Path.Combine(Options.Instance.OutputDirectory, finalFilename);

            return finalPath;
        }

19 Source : ScriptBuilder.cs
with MIT License
from BoltBait

private static replacedembly Createreplacedembly(string sourceCode, bool debug)
        {
            lineOffset = CalculateLineOffset(sourceCode);
            exceptionMsg = null;
            errors = null;

            string replacedemblyName = Path.GetRandomFileName();
            IEnumerable<SyntaxTree> syntaxTree = new[] { CSharpSyntaxTree.ParseText(sourceCode, options: debug ? parseOptions.WithPreprocessorSymbols("DEBUG") : parseOptions) };

            CSharpCompilation compilation = CSharpCompilation.Create(
                replacedemblyName, syntaxTree, references,
                compilationOptions.WithOptimizationLevel(debug ? OptimizationLevel.Debug : OptimizationLevel.Release));

            using (MemoryStream ms = new MemoryStream())
            {
                EmitResult result = compilation.Emit(ms);

                errors = result.Diagnostics.Where(ErrorFilter);

                if (!result.Success)
                {
                    return null;
                }

                replacedemblyLoadContext loadContext = new replacedemblyLoadContext(null, true);
                ms.Seek(0, SeekOrigin.Begin);
                replacedembly replacedembly = loadContext.LoadFromStream(ms);
                return replacedembly;
            }
        }

19 Source : DiskProviderFixtureBase.cs
with GNU General Public License v3.0
from bonarr

[Test]
        public void folder_should_return_correct_value_for_last_write()
        {
            var testDir = GetTempFilePath();
            var testFile = Path.Combine(testDir, Path.GetRandomFileName());

            Directory.CreateDirectory(testDir);

            Subject.FolderSetLastWriteTime(TempFolder, DateTime.UtcNow.AddMinutes(-5));

            TestLogger.Info("Path is: {0}", testFile);

            Subject.WriteAllText(testFile, "Test");

            Subject.FolderGetLastWrite(TempFolder).Should().BeOnOrAfter(DateTime.UtcNow.AddMinutes(-1));
            Subject.FolderGetLastWrite(TempFolder).Should().BeBefore(DateTime.UtcNow.AddMinutes(1));
        }

19 Source : DiskTransferServiceFixture.cs
with GNU General Public License v3.0
from bonarr

public DirectoryInfo GetFilledTempFolder()
        {
            var tempFolder = GetTempFilePath();
            Directory.CreateDirectory(tempFolder);

            File.WriteAllText(Path.Combine(tempFolder, Path.GetRandomFileName()), "RootFile");

            var subDir = Path.Combine(tempFolder, Path.GetRandomFileName());
            Directory.CreateDirectory(subDir);

            File.WriteAllText(Path.Combine(subDir, Path.GetRandomFileName()), "SubFile1");
            File.WriteAllText(Path.Combine(subDir, Path.GetRandomFileName()), "SubFile2");

            return new DirectoryInfo(tempFolder);
        }

19 Source : TestBase.cs
with GNU General Public License v3.0
from bonarr

protected string GetTempFilePath()
        {
            return Path.Combine(TempFolder, Path.GetRandomFileName());
        }

19 Source : CertificateGenerator.cs
with Apache License 2.0
from buehler

public async Task CreateServerCertificateAsync(
            string outputFolder,
            string name,
            string @namespace,
            string caPath,
            string caKeyPath)
        {
            if (!_initialized)
            {
                await PrepareExecutables();
                _initialized = true;
            }

            Directory.CreateDirectory(outputFolder);

            _servercsr = Path.Join(_tempDirectory, Path.GetRandomFileName());
            await using (var serverCsrStream = new StreamWriter(new FileStream(_servercsr, FileMode.CreateNew)))
            {
                await serverCsrStream.WriteLineAsync(
                    ServerCsr($"{name}.{@namespace}.svc", $"*.{@namespace}.svc", "*.svc"));
            }

            await _appOut.WriteLineAsync(
                $@"Generating server certificate for ""{name}"" in namespace ""{@namespace}"".");
            await ExecuteProcess(
                new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        WorkingDirectory = outputFolder,
                        FileName = ShellExecutor,
                        Arguments = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
                            ? $"/c {_cfssl} gencert -ca=file:{caPath.Replace('\\', '/')} -ca-key=file:{caKeyPath.Replace('\\', '/')} -config={_caconfig} -profile=server {_servercsr} | {_cfssljson} -bare server -"
                            : $@"-c ""{_cfssl} gencert -ca={caPath} -ca-key={caKeyPath} -config={_caconfig} -profile=server {_servercsr} | {_cfssljson} -bare server -""",
                    },
                });

            await ListDir(outputFolder);
        }

19 Source : CertificateGenerator.cs
with Apache License 2.0
from buehler

private async Task PrepareExecutables()
        {
            Directory.CreateDirectory(_tempDirectory);
            _cfssl = Path.Join(_tempDirectory, Path.GetRandomFileName());
            _cfssljson = Path.Join(_tempDirectory, Path.GetRandomFileName());
            _caconfig = Path.Join(_tempDirectory, Path.GetRandomFileName());
            _cacsr = Path.Join(_tempDirectory, Path.GetRandomFileName());

            using (var client = new HttpClient())
            await using (var cfsslStream = new FileStream(_cfssl, FileMode.CreateNew))
            await using (var cfsslJsonStream = new FileStream(_cfssljson, FileMode.CreateNew))
            await using (var caConfigStream = new StreamWriter(new FileStream(_caconfig, FileMode.CreateNew)))
            await using (var caCsrStream = new StreamWriter(new FileStream(_cacsr, FileMode.CreateNew)))
            {
                await caConfigStream.WriteLineAsync(CaConfig);
                await caCsrStream.WriteLineAsync(CaCsr);

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    await _appOut.WriteLineAsync("Download cfssl / cfssljson for windows.");
                    await using var cfsslDl = await client.GetStreamAsync(CfsslUrlWindows);
                    await using var cfsslJsonDl = await client.GetStreamAsync(CfsslJsonUrlWindows);

                    await cfsslDl.CopyToAsync(cfsslStream);
                    await cfsslJsonDl.CopyToAsync(cfsslJsonStream);
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    await _appOut.WriteLineAsync("Download cfssl / cfssljson for linux.");
                    await using var cfsslDl = await client.GetStreamAsync(CfsslUrlLinux);
                    await using var cfsslJsonDl = await client.GetStreamAsync(CfsslJsonUrlLinux);

                    await cfsslDl.CopyToAsync(cfsslStream);
                    await cfsslJsonDl.CopyToAsync(cfsslJsonStream);
                }
                else
                {
                    await _appOut.WriteLineAsync("Download cfssl / cfssljson for macos.");
                    await using var cfsslDl = await client.GetStreamAsync(CfsslUrlMacOs);
                    await using var cfsslJsonDl = await client.GetStreamAsync(CfsslJsonUrlMacOs);

                    await cfsslDl.CopyToAsync(cfsslStream);
                    await cfsslJsonDl.CopyToAsync(cfsslJsonStream);
                }
            }

            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                await _appOut.WriteLineAsync("Make unix binaries executable.");
                await ExecuteProcess(
                    new Process
                    {
                        StartInfo = new ProcessStartInfo
                        {
                            FileName = "chmod",
                            Arguments = ArgumentEscaper.EscapeAndConcatenate(
                                new[] { "+x", _cfssl, _cfssljson }),
                        },
                    });
            }
        }

19 Source : TemplateExecutor.cs
with Apache License 2.0
from buehler

public void ExecuteCSharpTemplate(string template, string? name = "Template")
        {
            _outputPath ??= Path.Join(Path.GetTempPath(), Path.GetRandomFileName());
            ExecuteDotnetProcess(
                $@"new {template} -lang ""C#"" -n {name} -o {_outputPath} ");
        }

19 Source : TemplateExecutor.cs
with Apache License 2.0
from buehler

public void ExecuteFSharpTemplate(string template, string? name = "Template")
        {
            _outputPath ??= Path.Join(Path.GetTempPath(), Path.GetRandomFileName());
            ExecuteDotnetProcess(
                $@"new {template} -lang ""F#"" -n {name} -o {_outputPath} ");
        }

19 Source : PathOfBuildingParser.cs
with MIT License
from C1rdec

private static string GetTemporaryDirectory()
        {
            var tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            Directory.CreateDirectory(tempDirectory);
            return tempDirectory;
        }

19 Source : AbstractDiskHttpData.cs
with Apache License 2.0
from cdy816

FileStream TempFile()
        {
            string newpostfix;
            string diskFilename = this.DiskFilename;
            if (diskFilename != null)
            {
                newpostfix = '_' + diskFilename;
            }
            else
            {
                newpostfix = this.Postfix;
            }
            string directory = this.BaseDirectory == null 
                ? Path.GetTempPath() 
                : Path.Combine(Path.GetTempPath(), this.BaseDirectory);
            // File.createTempFile
            string fileName = Path.Combine(directory, $"{this.Prefix}{Path.GetRandomFileName()}{newpostfix}");
            FileStream tmpFile = File.Create(fileName, 4096, // DefaultBufferSize
                this.DeleteOnExit ? FileOptions.DeleteOnClose : FileOptions.None);
            return tmpFile;
        }

19 Source : Error_Operation.cs
with GNU Affero General Public License v3.0
from ceramicskate0

internal static void Log_Error(string MethodNameInCode, string Message, string StackDetails, LogSeverity LogSeverity, EventID eventID = 0)
        {
            if (Settings.Logging_Level_To_Report.ToLower() == "verbose")
            {
                Message = Message + " Stack_Info=" + StackDetails;
            }

            string msg = "DateTime=" + DateTime.Now.ToString(Settings.SWELF_Date_Time_Format) + "   SourceComputer=" + Settings.ComputerName + "   Severity=" + Severity_Levels[(int)LogSeverity] + "   Error_MethodInCode=" + MethodNameInCode + "   Error_Message=" + Message + "\n";

            try//write ALL to local error log 1st
            {
                File_Operation.CHECK_File_Size(Settings.GET_ErrorLog_Location);
                File_Operation.APPEND_AllTXT(Settings.GET_ErrorLog_Location, msg);
            }
            catch (Exception e)
            {
                try
                {
                    File_Operation.APPEND_AllTXT(Settings.SWELF_Log_File_Location + "\\" + Path.GetRandomFileName() + "_" + Settings.ErrorFile_FileName, msg);
                }
                catch (Exception ex)
                {
                    msg += "\nAdditional_ERROR: " + ex.Message.ToString() + " " + Settings.SWELF_PROC_Name + " was unable to write this error to a local file on this system at " + Settings.GET_ErrorLog_Location;
                }
            }
            if (Logging_Level_To_Report <= (int)LogSeverity)
            {
                try//write to eventlog
                {
                    WRITE_Errors_To_EventLog(MethodNameInCode, Message, LogSeverity, eventID);
                }
                catch (Exception exc)
                {
                    msg += "\nAdditional_ERROR: " + exc.Message.ToString() + " " + Settings.SWELF_PROC_Name + " was unable to write this error to the event log on this system";
                    try
                    {
                        File_Operation.APPEND_AllTXT(Settings.SWELF_Log_File_Location + "\\" + Path.GetRandomFileName() + "_" + Settings.ErrorFile_FileName, msg);
                    }
                    catch (Exception execp)
                    {
                        msg += "\nAdditional_ERROR: " + execp.Message.ToString() + " " + Settings.SWELF_PROC_Name + " was unable to write this error to a local file on this system at " + Settings.GET_ErrorLog_Location;
                    }
                }
                try// send eventlog to collector
                {
                    Log_Network_Forwarder.SEND_SINGLE_LOG(msg);
                }
                catch (Exception p)
                {
                    msg += "\nAdditional_ERROR: " + p.Message.ToString() + " " + Settings.SWELF_PROC_Name + " was unable to write error to Event Log";
                    try//write to eventlog
                    {
                        WRITE_Errors_To_EventLog(MethodNameInCode, Message, LogSeverity, eventID);
                    }
                    catch (Exception exc)
                    {
                        msg += "\nAdditional_ERROR: " + exc.Message.ToString() + " " + Settings.SWELF_PROC_Name + " was unable to write this error to the event log on this system";
                        try
                        {
                            File_Operation.APPEND_AllTXT(Settings.SWELF_Log_File_Location + "\\" + Path.GetRandomFileName() + "_" + Settings.ErrorFile_FileName, msg);
                        }
                        catch (Exception execp)
                        {
                            msg += "\nAdditional_ERROR: " + execp.Message.ToString() + " " + Settings.SWELF_PROC_Name + " was unable to write this error to a local file on this system at " + Settings.GET_ErrorLog_Location;
                        }
                    }
                }
            }
            Data_Store.ErrorsLog.Add(msg);
        }

19 Source : FilesController.cs
with MIT License
from changhuixu

[HttpPost("")]
        [DisableFormValueModelBinding]
        public async Task<IActionResult> Upload()
        {
            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                ModelState.AddModelError("File", "The request couldn't be processed (Error 1).");
                _logger.LogWarning($"The request content type [{Request.ContentType}] is invalid.");
                return BadRequest(ModelState);
            }

            var formModel = new MyFormModel();

            var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType), new FormOptions().MultipartBoundaryLengthLimit);
            var reader = new MultipartReader(boundary, HttpContext.Request.Body);
            var section = await reader.ReadNextSectionAsync();

            while (section != null)
            {
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition);

                if (hasContentDispositionHeader)
                {
                    if (contentDisposition.IsFileDisposition())
                    {
                        // Don't trust the file name sent by the client. To display the file name, HTML-encode the value.
                        var trustedFileNameForDisplay = WebUtility.HtmlEncode(contentDisposition.FileName.Value);
                        var trustedFileNameForFileStorage = Path.GetRandomFileName();

                        // todo: scan the file's contents using an anti-virus/anti-malware scanner API

                        var streamedFileContent = await FileHelpers.ProcessStreamedFile(section, contentDisposition, ModelState, _permittedExtensions, _fileSizeLimit);

                        if (!ModelState.IsValid)
                        {
                            return BadRequest(ModelState);
                        }

                        var trustedFilePath = Path.Combine(_targetFolderPath, trustedFileNameForFileStorage);
                        using (var targetStream = System.IO.File.Create(trustedFilePath))
                        {
                            await targetStream.WriteAsync(streamedFileContent);
                            formModel.TrustedFilePath = trustedFilePath;
                            formModel.TrustedFileName = trustedFileNameForDisplay;
                            _logger.LogInformation($"Uploaded file '{trustedFileNameForDisplay}' saved to '{_targetFolderPath}' as {trustedFileNameForFileStorage}");
                        }
                    }
                    else if (contentDisposition.IsFormDisposition())
                    {
                        var content = new StreamReader(section.Body).ReadToEnd();
                        if (contentDisposition.Name == "userId" && int.TryParse(content, out var useId))
                        {
                            formModel.UserId = useId;
                        }

                        if (contentDisposition.Name == "comment")
                        {
                            formModel.Comment = content;
                        }

                        if (contentDisposition.Name == "isPrimary" && bool.TryParse(content, out var isPrimary))
                        {
                            formModel.IsPrimary = isPrimary;
                        }
                    }
                }

                // Drain any remaining section body that hasn't been consumed and read the headers for the next section.
                section = await reader.ReadNextSectionAsync();
            }

            // todo: validate and persist formModel
            _logger.LogInformation(formModel.ToString());
            MyFiles.Add(formModel);

            return Created(nameof(FilesController), formModel);
        }

19 Source : ExpressionCompiler.cs
with MIT License
from chaowlert

public void AddFile(LambdaExpression node, ExpressionDefinitions? definitions = null)
        {
            definitions ??= _options?.DefaultDefinitions ?? new ExpressionDefinitions {IsStatic = true};
            definitions.TypeName ??= "Program";

            var translator = ExpressionTranslator.Create(node, definitions);
            var script = translator.ToString();
            Translators.Add(translator);

            this.AddFile(script, Path.ChangeExtension(Path.GetRandomFileName(), ".cs"));
        }

19 Source : ExpressionCompiler.cs
with MIT License
from chaowlert

public replacedembly Createreplacedembly()
        {
            var references = new HashSet<replacedembly>();
            references.UnionWith(from t in Translators
                                 from n in t.TypeNames
                                 select n.Key.replacedembly);

            if (_options?.References != null)
                references.UnionWith(_options.References);
            references.Add(typeof(object).replacedembly);

#if NETSTANDARD2_0
            references.Add(replacedembly.Load(new replacedemblyName("netstandard")));
            references.Add(replacedembly.Load(new replacedemblyName("System.Runtime")));
            references.Add(replacedembly.Load(new replacedemblyName("System.Collections")));
#endif

            var replacedemblyName = Path.GetRandomFileName();
            var symbolsName = Path.ChangeExtension(replacedemblyName, "pdb");

            var metadataReferences = references.Select(it => MetadataReference.CreateFromFile(it.Location));
            var isRelease = _options?.IsRelease ?? !Debugger.IsAttached;
            CSharpCompilation compilation = CSharpCompilation.Create(
                replacedemblyName,
                _codes,
                metadataReferences,
                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, usings: new[] { "System" })
                    .WithOptimizationLevel(isRelease ? OptimizationLevel.Release : OptimizationLevel.Debug)
                    .WithPlatform(Platform.AnyCpu)
            );

            using var replacedemblyStream = new MemoryStream();
            using var symbolsStream = new MemoryStream();
            var emitOptions = new EmitOptions(
                debugInformationFormat: DebugInformationFormat.PortablePdb,
                pdbFilePath: symbolsName);

            var embeddedTexts = _codes.Select(it => EmbeddedText.FromSource(it.FilePath, it.GetText()));

            EmitResult result = compilation.Emit(
                peStream: replacedemblyStream,
                pdbStream: symbolsStream,
                embeddedTexts: embeddedTexts,
                options: emitOptions);

            if (!result.Success)
            {
                var errors = new List<string>();

                IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                    diagnostic.IsWarningAsError ||
                    diagnostic.Severity == DiagnosticSeverity.Error);

                foreach (Diagnostic diagnostic in failures)
                    errors.Add($"{diagnostic.Id}: {diagnostic.GetMessage()}");

                throw new InvalidOperationException(string.Join("\n", errors));
            }

            replacedemblyStream.Seek(0, SeekOrigin.Begin);
            symbolsStream.Seek(0, SeekOrigin.Begin);

#if NETSTANDARD2_0
            return System.Runtime.Loader.replacedemblyLoadContext.Default.LoadFromStream(replacedemblyStream, symbolsStream);
#else
                return replacedembly.Load(replacedemblyStream.ToArray(), symbolsStream.ToArray());
#endif
        }

19 Source : SharedRazorViewCompiler.cs
with BSD 3-Clause "New" or "Revised" License
from china-live

internal replacedembly CompileAndEmit(RazorCodeDoreplacedent codeDoreplacedent, string generatedCode)
        {
            _logger.GeneratedCodeToreplacedemblyCompilationStart(codeDoreplacedent.Source.FilePath);

            var startTimestamp = _logger.IsEnabled(LogLevel.Debug) ? Stopwatch.GetTimestamp() : 0;

            var replacedemblyName = Path.GetRandomFileName();
            var compilation = CreateCompilation(generatedCode, replacedemblyName);

            var emitOptions = _csharpCompiler.EmitOptions;
            var emitPdbFile = _csharpCompiler.EmitPdb && emitOptions.DebugInformationFormat != DebugInformationFormat.Embedded;

            using (var replacedemblyStream = new MemoryStream())
            using (var pdbStream = emitPdbFile ? new MemoryStream() : null)
            {
                var result = compilation.Emit(
                    replacedemblyStream,
                    pdbStream,
                    options: emitOptions);

                if (!result.Success)
                {
                    throw CompilationFailedExceptionFactory.Create(
                        codeDoreplacedent,
                        generatedCode,
                        replacedemblyName,
                        result.Diagnostics);
                }

                replacedemblyStream.Seek(0, SeekOrigin.Begin);
                pdbStream?.Seek(0, SeekOrigin.Begin);

                var replacedembly = replacedembly.Load(replacedemblyStream.ToArray(), pdbStream?.ToArray());
                _logger.GeneratedCodeToreplacedemblyCompilationEnd(codeDoreplacedent.Source.FilePath, startTimestamp);

                return replacedembly;
            }
        }

19 Source : SimpleMessage.cs
with MIT License
from Cloet

private void MessageHasBeenReceived()
		{

			if (MessageType != MessageType.Folder && MessageType != MessageType.File)
			{
				//Header has already been decrypted and decompressed.

				// Data
				if (Encrypted)
					_receivedBytes = _socket.DecryptBytes(_receivedBytes);

				if (Compressed)
					_receivedBytes = _socket.DecompressBytes(_receivedBytes);

				// Metadata
				if (HeaderFields[7]) {
					if (Encrypted)
						_receivedMetadataBytes = _socket.DecryptBytes(_receivedMetadataBytes);

					if (Compressed)
						_receivedMetadataBytes = _socket.DecompressBytes(_receivedMetadataBytes);
				}

			}

			//Invoke correct receiver.
			switch (MessageType)
			{

				case MessageType.Auth:
				{
						var message = Encoding.UTF8.GetString(_receivedBytes);
						var arr = message.Split('|');
						_state.ClientName = arr[0];
						_state.Guid = arr[1];
						_state.UserDomainName = arr[2];
						_state.OsVersion = arr[3];
						break;
				}
				case MessageType.BasicAuth:
				{
						var message = Encoding.UTF8.GetString(_receivedBytes);
						var arr = message.Split('|');
						_state.Guid = arr[0];
						_state.OsVersion = arr[1];
						break;
				}
				case MessageType.Object:
				{
						var type = Type.GetType(Encoding.UTF8.GetString(Header));
						var obj = _socket.ObjectSerializer.DeserializeBytesToObject(_receivedBytes, type);
						_socket.RaiseObjectReceived(_state, obj, obj.GetType());
						break;
				}
				case MessageType.Message:
						_socket.RaiseMessageReceived(_state, Encoding.UTF8.GetString(_receivedBytes));
						break;
				case MessageType.Bytes:
						_socket.RaiseBytesReceived(_state, _receivedBytes);
						break;
				case MessageType.File:
				{
						var file = Encoding.UTF8.GetString(Header);
						var output = file;

						_socket.RaiseFileReceiver(_state, _partNumber, _totalParts, output, MessageState.ReceivingData);

						if (_totalParts == _partNumber)
						{
							file = GetTempPath(file);

							if (Encrypted)
							{
								_socket.RaiseFileReceiver(_state, _partNumber, _totalParts, output, MessageState.Decrypting);
								Log("Decrypting file from path : " + file);
								var tmp = file;
								file = _socket.DecryptFile(file, _socket.TempPath + Path.GetRandomFileName()).FullName;
								File.Delete(tmp);
								Log("File has been decrypted from path: " + file);
								_socket.RaiseFileReceiver(_state, _partNumber, _totalParts, output,MessageState.DecryptingDone);
							}

							if (Compressed)
							{
								_socket.RaiseFileReceiver(_state, _partNumber, _totalParts, output,MessageState.Decompressing);
								Log("Decompressing file from path : " + file);
								var tmp = file;
								file = _socket.DecompressFile(new FileInfo(file), _socket.TempPath + Path.GetRandomFileName()).FullName;
								if (Encrypted)
									File.Delete(tmp);
								Log("File Decompressed from path : " + file);
								_socket.RaiseFileReceiver(_state, _partNumber, _totalParts, output,MessageState.DecompressingDone);
							}


							if (Encrypted || Compressed)
							{
								if (File.Exists(output))
									File.Delete(output);
								Log("Deleting file: " + output);
								File.Move(file, output);
								Log("Moving " + file + " to " + output);
								File.Delete(file); // Delete encrypted/compressed file.
								Log("Deleting temp file : " + file);
							}

							_socket.RaiseFileReceiver(_state, _partNumber, _totalParts, output, MessageState.Completed);
							Log("File has been received and saved to path : " + output);
						}
						
						break;
				}
				case MessageType.MessageWithMetadata:
				{
						var header = Encoding.UTF8.GetString(Header);
						object obj = null;
						Type objType = null;

						if (header != "ByteArray")
						{
							objType = Type.GetType(header);
							obj = _socket.ObjectSerializer.DeserializeBytesToObject(_receivedBytes, objType);
						}
						else {
							obj = _receivedBytes;
							objType = obj.GetType();
						}

						var metadata = _socket.ObjectSerializer.DeserializeJson<IDictionary<object, object>>(_receivedMetadataBytes);
						_socket.RaiseMessageWithMetaDataReceived(_state, obj, metadata, objType);
						break;
				}
				case MessageType.MessageContract:
				{
						var contractHeader = Encoding.UTF8.GetString(Header);
						var contract = GetCorrespondingMessageContract(contractHeader);
						if (contract != null)
							_socket.RaiseMessageContractReceived(_state, contract, _receivedBytes);
						else if (_debug)
							Log("MessageContract with Header '" + contractHeader + "' does not exist.");
						break;
				}
				case MessageType.Folder:
				{
						var folder = Encoding.UTF8.GetString(Header);
						var output = folder;

						_socket.RaiseFolderReceiver(_state, _partNumber, _totalParts, output, MessageState.ReceivingData);

						if (_totalParts == _partNumber)
						{
							folder = GetTempPath(folder);

							if (Encrypted)
							{
								var tmp = _socket.DecryptFile(folder, _socket.TempPath + Path.GetRandomFileName()).FullName;
								File.Delete(folder);
								folder = tmp;
							}


							_socket.ExtractToFolder(folder, output);
							File.Delete(folder); //Delete extracted folder.

							_socket.RaiseFolderReceiver(_state, _partNumber, _totalParts, output, MessageState.Completed);
						}
						break;
				}
				default:
						throw new ArgumentOutOfRangeException();
			}

			ResetReadData();

		}

19 Source : SimpleSocket.cs
with MIT License
from Cloet

protected internal FileInfo CompressFile(FileInfo file)
		{
			return FileCompressor.Compress(file, new FileInfo(TempPath + Path.GetRandomFileName() + FileCompressor.Extension));
		}

19 Source : SimpleSocket.cs
with MIT License
from Cloet

protected internal FileInfo CompressFolder(string sourceDir)
		{
			return FolderCompressor.Compress(sourceDir, TempPath + Path.GetRandomFileName() + FolderCompressor.Extension);
		}

19 Source : SimpleSocket.cs
with MIT License
from Cloet

protected internal FileInfo EncryptFile(string input)
		{
			return MessageEncryption.FileEncrypt(input, TempPath + Path.GetRandomFileName() + MessageEncryption.Extension);
		}

19 Source : MForge.cs
with MIT License
from CmlLib

public string InstallForge(string mcversion, string forgeversion)
        {
            var minecraftJar = Minecraft.GetVersionJarPath(mcversion);
            if (!File.Exists(minecraftJar))
                throw new IOException($"Install {mcversion} first");

            var installerPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            var installerStream = getInstallerStream(mcversion, forgeversion); // download installer
            var extractedFile = extractInstaller(installerStream, installerPath); // extract installer

            var profileObj = extractedFile.Item1; // version profile json
            var installerObj = extractedFile.Item2; // installer info

            // copy forge libraries to minecraft
            extractMaven(installerPath); // new installer
            extractUniversal(installerPath,
                installerObj["filePath"]?.ToString(), installerObj["path"]?.ToString()); // old installer

            // download libraries and processors
            checkLibraries(installerObj["libraries"] as JArray);

            // mapping client data
            var mapData = mapping(installerObj["data"] as JObject, "client", minecraftJar, installerPath);

            // process
            process(installerObj["processors"] as JArray, mapData);

            // version name like 1.16.2-forge-33.0.20
            var versionName = installerObj["target"]?.ToString()
                           ?? installerObj["version"]?.ToString()
                           ?? GetForgeName(mcversion, forgeversion);

            var versionPath = Minecraft.GetVersionJsonPath(versionName);

            // write version profile json
            writeProfile(profileObj, versionPath);

            return versionName;
        }

19 Source : Compiler.cs
with GNU General Public License v3.0
from cobbr

private static byte[] CompileCSharpRoslyn(CsharpFrameworkCompilationRequest request)
        {
            // Gather SyntaxTrees for compilation
            List<SourceSyntaxTree> sourceSyntaxTrees = new List<SourceSyntaxTree>();
            List<SyntaxTree> compilationTrees = new List<SyntaxTree>();

            if (request.SourceDirectories != null)
            {
                foreach (var sourceDirectory in request.SourceDirectories)
                {
                    sourceSyntaxTrees.AddRange(Directory.GetFiles(sourceDirectory, "*.cs", SearchOption.AllDirectories)
                        .Select(F => new SourceSyntaxTree { FileName = F, SyntaxTree = CSharpSyntaxTree.ParseText(File.ReadAllText(F), new CSharpParseOptions()) })
                        .ToList());
                    compilationTrees.AddRange(sourceSyntaxTrees.Select(S => S.SyntaxTree).ToList());
                }
            }
            SyntaxTree sourceTree = CSharpSyntaxTree.ParseText(request.Source, new CSharpParseOptions());
            compilationTrees.Add(sourceTree);

            List<PortableExecutableReference> references = request.References
                .Where(R => R.Framework == request.TargetDotNetVersion)
                .Where(R => R.Enabled)
                .Select(R => MetadataReference.CreateFromFile(R.File))
                .ToList();

            // Use specified OutputKind and Platform
            CSharpCompilationOptions options = new CSharpCompilationOptions(outputKind: request.OutputKind, optimizationLevel: OptimizationLevel.Release, platform: request.Platform, allowUnsafe: request.UnsafeCompile);
            // Compile to obtain SemanticModel
            CSharpCompilation compilation = CSharpCompilation.Create(
                request.replacedemblyName == null ? Path.GetRandomFileName() : request.replacedemblyName,
                compilationTrees,
                references,
                options
            );

            // Perform source code optimization, removing unused types
            if (request.Optimize)
            {
                // Find all Types used by the generated compilation
                HashSet<ITypeSymbol> usedTypes = new HashSet<ITypeSymbol>();
                GetUsedTypesRecursively(compilation, sourceTree, ref usedTypes, ref sourceSyntaxTrees);
                List<string> usedTypeNames = usedTypes.Select(T => GetFullyQualifiedTypeName(T)).ToList();

                // Filter SyntaxTrees to trees that define a used Type, otherwise the tree is not needed in this compilation
                compilationTrees = sourceSyntaxTrees.Where(SST => SyntaxTreeDefinesUsedType(compilation, SST.SyntaxTree, usedTypeNames))
                                                    .Select(SST => SST.SyntaxTree)
                                                    .ToList();

                // Removed unused Using statements from the additional entrypoint source
                List<string> usedNamespaceNames = GetUsedTypes(compilation, sourceTree)
                    .Select(T => GetFullyQualifiedContainingNamespaceName(T)).Distinct().ToList();
                List<SyntaxNode> unusedUsingDirectives = sourceTree.GetRoot().DescendantNodes().Where(N =>
                {
                    return N.Kind() == SyntaxKind.UsingDirective && !((UsingDirectiveSyntax)N).Name.ToFullString().StartsWith("System.") && !usedNamespaceNames.Contains(((UsingDirectiveSyntax)N).Name.ToFullString());
                }).ToList();
                sourceTree = sourceTree.GetRoot().RemoveNodes(unusedUsingDirectives, SyntaxRemoveOptions.KeepNoTrivia).SyntaxTree;

                // Compile again, with unused SyntaxTrees and unused using statements removed
                compilationTrees.Add(sourceTree);
                compilation = CSharpCompilation.Create(
                    request.replacedemblyName == null ? Path.GetRandomFileName() : request.replacedemblyName,
                    compilationTrees,
                    request.References.Where(R => R.Framework == request.TargetDotNetVersion).Where(R => R.Enabled).Select(R =>
                    {
                        return MetadataReference.CreateFromFile(R.File);
                    }).ToList(),
                    options
                );
            }

            // Emit compilation
            EmitResult emitResult;
            byte[] ILbytes = null;
            using (var ms = new MemoryStream())
            {
                emitResult = compilation.Emit(
                    ms,
                    manifestResources: request.EmbeddedResources.Where(ER =>
                    {
                        return request.Platform == Platform.AnyCpu || ER.Platform == Platform.AnyCpu || ER.Platform == request.Platform;
                    }).Where(ER => ER.Enabled).Select(ER =>
                    {
                        return new ResourceDescription(ER.Name, () => File.OpenRead(ER.File), true);
                    }).ToList()
                );
                if (emitResult.Success)
                {
                    ms.Flush();
                    ms.Seek(0, SeekOrigin.Begin);
                    ILbytes = ms.ToArray();
                }
                else
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (Diagnostic d in emitResult.Diagnostics)
                    {
                        sb.AppendLine(d.ToString());
                    }
                    throw new CompilerException("CompilationErrors: " + Environment.NewLine + sb);
                }
            }
            if (request.Confuse)
            {
                return Confusereplacedembly(ILbytes);
            }
            return ILbytes;
        }

19 Source : Compiler.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr

public static byte[] Compile(CompilationRequest request)
        {
            // Gather SyntaxTrees for compilation
            List<SourceSyntaxTree> sourceSyntaxTrees = Directory.GetFiles(request.SourceDirectory, "*.cs", SearchOption.AllDirectories)
                .Select(F => new SourceSyntaxTree { FileName = F, SyntaxTree = CSharpSyntaxTree.ParseText(File.ReadAllText(F), new CSharpParseOptions()) })
                .ToList();
            List<SyntaxTree> compilationTrees = sourceSyntaxTrees.Select(S => S.SyntaxTree).ToList();

            SyntaxTree sourceTree = CSharpSyntaxTree.ParseText(request.Source, new CSharpParseOptions());
            compilationTrees.Add(sourceTree);

            // Use specified OutputKind and Platform
            CSharpCompilationOptions options = new CSharpCompilationOptions(outputKind: request.OutputKind, optimizationLevel: OptimizationLevel.Release, platform: request.Platform);
            // Compile to obtain SemanticModel
            CSharpCompilation compilation = CSharpCompilation.Create(
                request.replacedemblyName == null ? Path.GetRandomFileName() : request.replacedemblyName,
                compilationTrees,
                request.References.Where(R => R.Framework == request.TargetDotNetVersion).Where(R => R.Enabled).Select(R =>
                {
                    string folder = (request.TargetDotNetVersion == DotNetVersion.Net35 ? request.ReferenceDirectory + "net35" + Path.DirectorySeparatorChar : request.ReferenceDirectory + "net40" + Path.DirectorySeparatorChar);
                    return MetadataReference.CreateFromFile(folder + R.File);
                }).ToList(),
                options
            );

            // Perform source code optimization, removing unused types
            if (request.Optimize)
            {
                // Find all Types used by the generated compilation
                List<INamedTypeSymbol> usedTypes = new List<INamedTypeSymbol>();
                GetUsedTypesRecursively(compilation, sourceTree, ref usedTypes, ref sourceSyntaxTrees);
                usedTypes = usedTypes.Distinct().ToList();
                List<string> usedTypeNames = usedTypes.Select(T => GetFullyQualifiedTypeName(T)).ToList();
                // SharpGenConsole.PrintInfoLine("usedTypes: " + String.Join(",", usedTypeNames));

                // Filter SyntaxTrees to trees that define a used Type, otherwise the tree is not needed in this compilation
                compilationTrees = sourceSyntaxTrees.Where(SST => SyntaxTreeDefinesUsedType(compilation, SST.SyntaxTree, usedTypeNames))
                                                    .Select(SST => SST.SyntaxTree)
                                                    .ToList();

                // Removed unused Using statements from the additional entrypoint source
                List<string> usedNamespaceNames = GetUsedTypes(compilation, sourceTree)
                    .Select(T => GetFullyQualifiedContainingNamespaceName(T)).Distinct().ToList();
                // SharpGenConsole.PrintInfoLine("usedNamespaces: " + String.Join(",", usedNamespaceNames));
                List<SyntaxNode> unusedUsingDirectives = sourceTree.GetRoot().DescendantNodes().Where(N =>
                {
                    return N.Kind() == SyntaxKind.UsingDirective && !usedNamespaceNames.Contains(((UsingDirectiveSyntax)N).Name.ToFullString());
                }).ToList();
                sourceTree = sourceTree.GetRoot().RemoveNodes(unusedUsingDirectives, SyntaxRemoveOptions.KeepNoTrivia).SyntaxTree;

                // Compile again, with unused SyntaxTrees and unused using statements removed
                compilationTrees.Add(sourceTree);
                compilation = CSharpCompilation.Create(
                    request.replacedemblyName == null ? Path.GetRandomFileName() : request.replacedemblyName,
                    compilationTrees,
                    request.References.Where(R => R.Framework == request.TargetDotNetVersion).Where(R => R.Enabled).Select(R =>
                    {
                        string folder = (request.TargetDotNetVersion == DotNetVersion.Net35 ? request.ReferenceDirectory + "net35" + Path.DirectorySeparatorChar : request.ReferenceDirectory + "net40" + Path.DirectorySeparatorChar);
                        return MetadataReference.CreateFromFile(folder + R.File);
                    }).ToList(),
                    options
                );
            }

            // Emit compilation
            EmitResult emitResult;
            byte[] ILbytes = null;
            using (var ms = new MemoryStream())
            {
                emitResult = compilation.Emit(
                    ms,
                    manifestResources: request.EmbeddedResources.Where(ER =>
                    {
                        return request.Platform == Platform.AnyCpu || ER.Platform == Platform.AnyCpu || ER.Platform == request.Platform;
                    }).Where(ER => ER.Enabled).Select(ER =>
                    {
                        return new ResourceDescription(ER.Name, () => File.OpenRead(request.ResourceDirectory + ER.File), true);
                    }).ToList()
                );
                if (emitResult.Success)
                {
                    ms.Flush();
                    ms.Seek(0, SeekOrigin.Begin);
                    ILbytes = ms.ToArray();
                }
                else
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (Diagnostic d in emitResult.Diagnostics)
                    {
                        sb.AppendLine(d.ToString());
                    }
                    throw new CompilerException("CompilationErrors: " + Environment.NewLine + sb);
                }
            }
            return ILbytes;
        }

19 Source : Compiler.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr

public static byte[] Compile(CompilationRequest request)
        {
            // Gather SyntaxTrees for compilation
            List<SourceSyntaxTree> sourceSyntaxTrees = Directory.GetFiles(request.SourceDirectory, "*.cs", SearchOption.AllDirectories)
                .Select(F => new SourceSyntaxTree { FileName = F, SyntaxTree = CSharpSyntaxTree.ParseText(File.ReadAllText(F), new CSharpParseOptions()) })
                .ToList();
            List<SyntaxTree> compilationTrees = sourceSyntaxTrees.Select(S => S.SyntaxTree).ToList();

            SyntaxTree sourceTree = CSharpSyntaxTree.ParseText(request.Source, new CSharpParseOptions());
            compilationTrees.Add(sourceTree);

            // Use specified OutputKind and Platform
            CSharpCompilationOptions options = new CSharpCompilationOptions(outputKind: request.OutputKind, optimizationLevel: OptimizationLevel.Release, platform: request.Platform);
            // Compile to obtain SemanticModel
            CSharpCompilation compilation = CSharpCompilation.Create(
                request.replacedemblyName == null ? Path.GetRandomFileName() : request.replacedemblyName,
                compilationTrees,
                request.References.Where(R => R.Framework == request.TargetDotNetVersion).Where(R => R.Enabled).Select(R =>
                {
                    string folder = (request.TargetDotNetVersion == DotNetVersion.Net35 ? request.ReferenceDirectory + "net35" + Path.DirectorySeparatorChar : request.ReferenceDirectory + "net40" + Path.DirectorySeparatorChar);
                    return MetadataReference.CreateFromFile(folder + R.File);
                }).ToList(),
                options
            );

            // Perform source code optimization, removing unused types
            if (request.Optimize)
            {
                // Find all Types used by the generated compilation
                List<INamedTypeSymbol> usedTypes = new List<INamedTypeSymbol>();
                GetUsedTypesRecursively(compilation, sourceTree, ref usedTypes, ref sourceSyntaxTrees);
                usedTypes = usedTypes.Distinct().ToList();
                List<string> usedTypeNames = usedTypes.Select(T => GetFullyQualifiedTypeName(T)).ToList();
                // SharpGenConsole.PrintInfoLine("usedTypes: " + String.Join(",", usedTypeNames));

                // Filter SyntaxTrees to trees that define a used Type, otherwise the tree is not needed in this compilation
                compilationTrees = sourceSyntaxTrees.Where(SST => SyntaxTreeDefinesUsedType(compilation, SST.SyntaxTree, usedTypeNames))
                                                    .Select(SST => SST.SyntaxTree)
                                                    .ToList();

                // Removed unused Using statements from the additional entrypoint source
                List<string> usedNamespaceNames = GetUsedTypes(compilation, sourceTree)
                    .Select(T => GetFullyQualifiedContainingNamespaceName(T)).Distinct().ToList();
                // SharpGenConsole.PrintInfoLine("usedNamespaces: " + String.Join(",", usedNamespaceNames));
                List<SyntaxNode> unusedUsingDirectives = sourceTree.GetRoot().DescendantNodes().Where(N =>
                {
                    return N.Kind() == SyntaxKind.UsingDirective && !usedNamespaceNames.Contains(((UsingDirectiveSyntax)N).Name.ToFullString());
                }).ToList();
                sourceTree = sourceTree.GetRoot().RemoveNodes(unusedUsingDirectives, SyntaxRemoveOptions.KeepNoTrivia).SyntaxTree;

                // Compile again, with unused SyntaxTrees and unused using statements removed
                SharpGenConsole.PrintFormattedProgressLine("Compiling optimized source: ");
                SharpGenConsole.PrintInfoLine(sourceTree.ToString());
                compilationTrees.Add(sourceTree);
                compilation = CSharpCompilation.Create(
                    request.replacedemblyName == null ? Path.GetRandomFileName() : request.replacedemblyName,
                    compilationTrees,
                    request.References.Where(R => R.Framework == request.TargetDotNetVersion).Where(R => R.Enabled).Select(R =>
                    {
                        string folder = (request.TargetDotNetVersion == DotNetVersion.Net35 ? request.ReferenceDirectory + "net35" + Path.DirectorySeparatorChar : request.ReferenceDirectory + "net40" + Path.DirectorySeparatorChar);
                        return MetadataReference.CreateFromFile(folder + R.File);
                    }).ToList(),
                    options
                );
            }

            // Emit compilation
            EmitResult emitResult;
            byte[] ILbytes = null;
            using (var ms = new MemoryStream())
            {
                emitResult = compilation.Emit(
                    ms,
                    manifestResources: request.EmbeddedResources.Where(ER =>
                    {
                        return request.Platform == Platform.AnyCpu || ER.Platform == Platform.AnyCpu || ER.Platform == request.Platform;
                    }).Where(ER => ER.Enabled).Select(ER =>
                    {
                    return new ResourceDescription(ER.Name, () => File.OpenRead(request.ResourceDirectory + ER.File), true);
                    }).ToList()
                );
                if (emitResult.Success)
                {
                    ms.Flush();
                    ms.Seek(0, SeekOrigin.Begin);
                    ILbytes = ms.ToArray();
                }
                else
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (Diagnostic d in emitResult.Diagnostics)
                    {
                        sb.AppendLine(d.ToString());
                    }
                    throw new CompilerException("CompilationErrors: " + Environment.NewLine + sb);
                }
            }
            return ILbytes;
        }

19 Source : ConanPathHelperTests.cs
with MIT License
from conan-io

[TestMethod]
        public async Task GetNearestConanfilePathWorksForDiskRootAsync()
        {
            var root = FileSystemUtils.CreateTempDirectory();
            var dir = Directory.CreateDirectory(Path.Combine(root, Path.GetRandomFileName())).FullName;

            FileSystemUtils.CreateTempFile(root, "conanfile.txt");
            replacedert.AreEqual(Path.Combine(root, "conanfile.txt"), await ConanPathHelper.GetNearestConanfilePathAsync(dir));
            replacedert.AreEqual(Path.Combine(root, "conanfile.txt"), await ConanPathHelper.GetNearestConanfilePathAsync(root));
        }

19 Source : InstrumenterHelper.cs
with MIT License
from coverlet-coverage

async public static Task<CoveragePrepareResult> Run<T>(Func<dynamic, Task> callMethod,
                                                               Func<string, string[]> includeFilter = null,
                                                               Func<string, string[]> excludeFilter = null,
                                                               Func<string, string[]> doesNotReturnAttributes = null,
                                                               string persistPrepareResultToFile = null,
                                                               bool disableRestoreModules = false,
                                                               bool skipAutoProps = false)
        {
            if (persistPrepareResultToFile is null)
            {
                throw new ArgumentNullException(nameof(persistPrepareResultToFile));
            }

            // Rename test file to avoid locks
            string location = typeof(T).replacedembly.Location;
            string fileName = Path.ChangeExtension($"testgen_{Path.GetFileNameWithoutExtension(Path.GetRandomFileName())}", ".dll");
            string logFile = Path.ChangeExtension(fileName, ".log");
            string newPath = Path.Combine(Path.GetDirectoryName(location), fileName);

            File.Copy(location, newPath);
            File.Copy(Path.ChangeExtension(location, ".pdb"), Path.ChangeExtension(newPath, ".pdb"));

            SetTestContainer(newPath, disableRestoreModules);

            static string[] defaultFilters(string _) => Array.Empty<string>();

            CoverageParameters parameters = new CoverageParameters
            {
                IncludeFilters = (includeFilter is null ? defaultFilters(fileName) : includeFilter(fileName)).Concat(
                new string[]
                {
                    $"[{Path.GetFileNameWithoutExtension(fileName)}*]{typeof(T).FullName}*"
                }).ToArray(),
                IncludeDirectories = Array.Empty<string>(),
                ExcludeFilters = (excludeFilter is null ? defaultFilters(fileName) : excludeFilter(fileName)).Concat(new string[]
                {
                    "[xunit.*]*",
                    "[coverlet.*]*"
                }).ToArray(),
                ExcludedSourceFiles = Array.Empty<string>(),
                ExcludeAttributes = Array.Empty<string>(),
                IncludeTestreplacedembly = true,
                SingleHit = false,
                MergeWith = string.Empty,
                UseSourceLink = false,
                SkipAutoProps = skipAutoProps,
                DoesNotReturnAttributes = doesNotReturnAttributes?.Invoke(fileName)
            };

            // Instrument module
            Coverage coverage = new Coverage(newPath, parameters, new Logger(logFile),
            _processWideContainer.GetService<IInstrumentationHelper>(), _processWideContainer.GetService<IFileSystem>(), _processWideContainer.GetService<ISourceRootTranslator>(), _processWideContainer.GetService<ICecilSymbolHelper>());
            CoveragePrepareResult prepareResult = coverage.PrepareModules();

            replacedert.Single(prepareResult.Results);

            // Load new replacedembly
            replacedembly asm = replacedembly.LoadFile(newPath);

            // Instance type and call method
            await callMethod(Activator.CreateInstance(asm.GetType(typeof(T).FullName)));

            // Flush tracker
            Type tracker = asm.GetTypes().Single(n => n.FullName.Contains("Coverlet.Core.Instrumentation.Tracker"));

            // For debugging purpouse
            // int[] hitsArray = (int[])tracker.GetField("HitsArray").GetValue(null);
            // string hitsFilePath = (string)tracker.GetField("HitsFilePath").GetValue(null);

            // Void UnloadModule(System.Object, System.EventArgs)
            tracker.GetTypeInfo().GetMethod("UnloadModule").Invoke(null, new object[2] { null, null });

            // Persist CoveragePrepareResult
            using (FileStream fs = new FileStream(persistPrepareResultToFile, FileMode.Open))
            {
                await CoveragePrepareResult.Serialize(prepareResult).CopyToAsync(fs);
            }

            return prepareResult;
        }

19 Source : InstrumenterTests.cs
with MIT License
from coverlet-coverage

[Theory]
        [InlineData("NotAMatch", new string[] { }, false)]
        [InlineData("ExcludeFromCoverageAttribute", new string[] { }, true)]
        [InlineData("ExcludeFromCodeCoverageAttribute", new string[] { }, true)]
        [InlineData("CustomExclude", new string[] { "CustomExclude" }, true)]
        [InlineData("CustomExcludeAttribute", new string[] { "CustomExclude" }, true)]
        [InlineData("CustomExcludeAttribute", new string[] { "CustomExcludeAttribute" }, true)]
        public void TestInstrument_replacedemblyMarkedAsExcludeFromCodeCoverage(string attributeName, string[] excludedAttributes, bool expectedExcludes)
        {
            string EmitreplacedemblyToInstrument(string outputFolder)
            {
                var attributeClreplacedSyntaxTree = CSharpSyntaxTree.ParseText("[System.AttributeUsage(System.AttributeTargets.replacedembly)]public clreplaced " + attributeName + ":System.Attribute{}");
                var instrumentableClreplacedSyntaxTree = CSharpSyntaxTree.ParseText($@"
[replacedembly:{attributeName}]
namespace coverlet.tests.projectsample.excludedbyattribute{{
public clreplaced SampleClreplaced
{{
	public int SampleMethod()
	{{
		return new System.Random().Next();
	}}
}}

}}
");
                var compilation = CSharpCompilation.Create(attributeName, new List<SyntaxTree>
                {
                    attributeClreplacedSyntaxTree,instrumentableClreplacedSyntaxTree
                }).AddReferences(
                    MetadataReference.CreateFromFile(typeof(Attribute).replacedembly.Location)).
                WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, false));

                var dllPath = Path.Combine(outputFolder, $"{attributeName}.dll");
                var pdbPath = Path.Combine(outputFolder, $"{attributeName}.pdb");

                using (var outputStream = File.Create(dllPath))
                using (var pdbStream = File.Create(pdbPath))
                {
                    var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
                    var emitOptions = new EmitOptions(pdbFilePath: pdbPath);
                    var emitResult = compilation.Emit(outputStream, pdbStream, options: isWindows ? emitOptions : emitOptions.WithDebugInformationFormat(DebugInformationFormat.PortablePdb));
                    if (!emitResult.Success)
                    {
                        var message = "Failure to dynamically create dll";
                        foreach (var diagnostic in emitResult.Diagnostics)
                        {
                            message += Environment.NewLine;
                            message += diagnostic.GetMessage();
                        }
                        throw new Xunit.Sdk.XunitException(message);
                    }
                }
                return dllPath;
            }

            string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            Directory.CreateDirectory(tempDirectory);
            disposeAction = () => Directory.Delete(tempDirectory, true);

            Mock<FileSystem> partialMockFileSystem = new Mock<FileSystem>();
            partialMockFileSystem.CallBase = true;
            partialMockFileSystem.Setup(fs => fs.NewFileStream(It.IsAny<string>(), It.IsAny<FileMode>(), It.IsAny<FileAccess>())).Returns((string path, FileMode mode, FileAccess access) =>
            {
                return new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
            });
            var loggerMock = new Mock<ILogger>();

            string excludedbyattributeDll = EmitreplacedemblyToInstrument(tempDirectory);

            InstrumentationHelper instrumentationHelper =
                    new InstrumentationHelper(new ProcessExitHandler(), new RetryHelper(), new FileSystem(), new Mock<ILogger>().Object,
                                              new SourceRootTranslator(new Mock<ILogger>().Object, new FileSystem()));
            CoverageParameters parametes = new();
            parametes.ExcludeAttributes = excludedAttributes;
            Instrumenter instrumenter = new Instrumenter(excludedbyattributeDll, "_xunit_excludedbyattribute", parametes, loggerMock.Object, instrumentationHelper, partialMockFileSystem.Object, new SourceRootTranslator(loggerMock.Object, new FileSystem()), new CecilSymbolHelper());

            InstrumenterResult result = instrumenter.Instrument();
            if (expectedExcludes)
            {
                replacedert.Empty(result.Doreplacedents);
                loggerMock.Verify(l => l.LogVerbose(It.IsAny<string>()));
            }
            else
            {
                replacedert.NotEmpty(result.Doreplacedents);
            }
        }

19 Source : RemoteExecutor.cs
with MIT License
from coverlet-coverage

private static IRemoteInvokeHandle Invoke(MethodInfo method, string[] args, bool pasteArguments = true)
        {
            Type t = method.DeclaringType;
            replacedembly a = t.GetTypeInfo().replacedembly;
            string exceptionFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            string resultFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            string metadataArgs = PasteArguments.Paste(new string[] { a.Location, t.FullName, method.Name, exceptionFile }, pasteFirstArgumentUsingArgV0Rules: false);
            string hostRunner = Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName);
            string preplacededArgs = pasteArguments ? PasteArguments.Paste(args, pasteFirstArgumentUsingArgV0Rules: false) : string.Join(" ", args);
            string testConsoleAppArgs = replacedembly.GetExecutingreplacedembly().Location + " " + metadataArgs + " " + preplacededArgs;

            ProcessStartInfo psi = new ProcessStartInfo();
            psi.FileName = hostRunner;
            psi.Arguments = testConsoleAppArgs;
            psi.UseShellExecute = false;
            return new RemoteInvokeHandle(Process.Start(psi), exceptionFile, resultFile);
        }

19 Source : System_IO_Path_Binding.cs
with MIT License
from CragonGame

static StackObject* GetRandomFileName_14(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject* __ret = ILIntepreter.Minus(__esp, 0);


            var result_of_this_method = System.IO.Path.GetRandomFileName();

            return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method);
        }

19 Source : AbstractDiskHttpData.cs
with MIT License
from cuteant

FileStream TempFile()
        {
            string newpostfix;
            string diskFilename = DiskFilename;
            if (diskFilename is object)
            {
                newpostfix = '_' + diskFilename;
            }
            else
            {
                newpostfix = Postfix;
            }
            string directory = string.IsNullOrWhiteSpace(BaseDirectory)
                ? Path.GetTempPath()
                : Path.IsPathRooted(BaseDirectory) ? BaseDirectory : Path.Combine(Path.GetTempPath(), BaseDirectory);
            // File.createTempFile
            string fileName = Path.Combine(directory, $"{Prefix}{Path.GetRandomFileName()}{newpostfix}");
            FileStream tmpFile = File.Create(fileName, 4096, // DefaultBufferSize
                DeleteOnExit ? FileOptions.DeleteOnClose : FileOptions.None);
            return tmpFile;
        }

19 Source : Context.cs
with GNU General Public License v3.0
from Cytoid

private async void InitializeApplication()
    {
        if (Application.platform == RuntimePlatform.Android)
        {
            // Get Android version
            using (var version = new AndroidJavaClreplaced("android.os.Build$VERSION")) {
                AndroidVersionCode = version.GetStatic<int>("SDK_INT");
                print("Android version code: " + AndroidVersionCode);
            }
        }
        LunarConsole.SetConsoleEnabled(true); // Enable startup debug

        InitializationState = new InitializationState();

        UserDataPath = Application.persistentDataPath;

        if (Application.platform == RuntimePlatform.Android)
        {
            var dir = GetAndroidStoragePath();
            if (dir == null)
            {
                Application.Quit();
                return;
            }

            UserDataPath = dir + "/Cytoid";
        }
        else if (Application.platform == RuntimePlatform.IPhonePlayer)
        {
            // iOS 13 fix
            iOSTemporaryInboxPath = UserDataPath
                .Replace("Doreplacedents/", "")
                .Replace("Doreplacedents", "") + "/tmp/me.tigerhix.cytoid-Inbox/";
        }
        print("User data path: " + UserDataPath);
        
#if UNITY_EDITOR
        Application.runInBackground = true;
#endif
        
        if (SceneManager.GetActiveScene().name == "Navigation") StartupLogger.Instance.Initialize();
        Debug.Log($"Package name: {Application.identifier}");

        Application.lowMemory += OnLowMemory;
        Application.targetFrameRate = 120;
        Input.gyro.enabled = true;
        DOTween.defaultEaseType = Ease.OutCubic;
        UnityEngine.Screen.sleepTimeout = SleepTimeout.NeverSleep;
        JsonConvert.DefaultSettings = () => new JsonSerializerSettings
        {
            Converters = new List<JsonConverter>
            {
                new UnityColorConverter()
            },
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
        };
        BsonMapper.Global.RegisterType
        (
            color => "#" + ColorUtility.ToHtmlStringRGB(color),
            s => s.replacedtring.ToColor()
        );
        FontManager.LoadFonts();
        
        if (Application.platform == RuntimePlatform.Android)
        {
            // Try to write to ensure we have write permissions
            try
            {
                // Create an empty folder if it doesn't already exist
                Directory.CreateDirectory(UserDataPath);
                File.Create(UserDataPath + "/.nomedia").Dispose();
                // Create and delete test file
                var file = UserDataPath + "/" + Path.GetRandomFileName();
                File.Create(file);
                File.Delete(file);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
                Dialog.PromptUnclosable("DIALOG_CRITICAL_ERROR_COULD_NOT_START_GAME_REASON_X".Get(
                    "DIALOG_CRITICAL_ERROR_REASON_WRITE_PERMISSION".Get()));
                return;
            }
        }

        try
        {
            var timer = new BenchmarkTimer("LiteDB");
            Database = CreateDatabase();
            // Database.Checkpoint();
            timer.Time();
        }
        catch (Exception e)
        {
            Debug.LogError(e);
            Dialog.Instantiate().Also(it =>
            {
                it.UseNegativeButton = false;
                it.UsePositiveButton = false;
                it.Message =
                    "DIALOG_CRITICAL_ERROR_COULD_NOT_START_GAME_REASON_X".Get(
                        "DIALOG_CRITICAL_ERROR_REASON_DATABASE".Get());
            }).Open();
            return;
        }

        // LiteDB warm-up
        Library.Initialize();
        
        // Load settings
        Player.Initialize();

        // Initialize audio
        var audioConfig = AudioSettings.GetConfiguration();
        DefaultDspBufferSize = audioConfig.dspBufferSize;

        if (Application.isEditor)
        {
            audioConfig.dspBufferSize = 2048;
        }
        else if (Application.platform == RuntimePlatform.Android && Player.Settings.AndroidDspBufferSize > 0)
        {
            audioConfig.dspBufferSize = Player.Settings.AndroidDspBufferSize;
        }
        AudioSettings.Reset(audioConfig);

        await UniTask.WaitUntil(() => AudioManager != null);
        AudioManager.Initialize();

        InitialWidth = UnityEngine.Screen.width;
        InitialHeight = UnityEngine.Screen.height;
        UpdateGraphicsQuality();

        SelectedMods = new HashSet<Mod>(Player.Settings.EnabledMods);

        PreSceneChanged.AddListener(OnPreSceneChanged);
        PostSceneChanged.AddListener(OnPostSceneChanged);

        OnLanguageChanged.AddListener(FontManager.UpdateSceneTexts);
        Localization.Instance.SelectLanguage((Language) Player.Settings.Language);
        OnLanguageChanged.Invoke();
        
        // TODO: Add standalone support?
#if UNITY_IOS || UNITY_ANDROID
        await BundleManager.Initialize();
#endif

        if (Player.ShouldOneShot(StringKey.FirstLaunch))
        {
            Player.SetTrigger(StringKey.FirstLaunch);
        }

        switch (SceneManager.GetActiveScene().name)
        {
            case "Navigation":
                if (Player.ShouldTrigger(StringKey.FirstLaunch, false))
                {
                    InitializationState.FirstLaunchPhase = FirstLaunchPhase.GlobalCalibration;

                    // Global calibration
                    SelectedGameMode = GameMode.GlobalCalibration;
                    var sceneLoader = new SceneLoader("Game");
                    await sceneLoader.Load();
                    sceneLoader.Activate();
                }
                else
                {
                    await InitializeNavigation();
                }
                break;
            case "Game":
                break;
        }

        await UniTask.DelayFrame(0);

        graphyManager = GraphyManager.Instance;
        UpdateProfilerDisplay();

        IsInitialized = true;
        OnApplicationInitialized.Invoke();
        
        LunarConsole.SetConsoleEnabled(Player.Settings.UseDeveloperConsole);
        ShouldSnapshotDatabase = true;
    }

19 Source : Storyboard.cs
with GNU General Public License v3.0
from Cytoid

private TO LoadObject<TO, TS>(JToken token) where TO : Object<TS>, new() where TS : ObjectState, new()
        {
            var states = new List<TS>();
            var obj = token.ToObject<JObject>();

            // Create initial state
            var initialState = (TS) CreateState((TS) null, obj);
            states.Add(initialState);
            // TODO: gfsd storyboard issue: template's first state should override initial state?

            // Create template states
            if (obj.TryGetValue("template", out var tmp))
            {
                var templateId = (string) tmp;
                var templateObject = Templates[templateId];

                // Template has states?
                if (templateObject["states"] != null)
                    AddStates(states, initialState, templateObject, ParseTime(obj, obj.SelectToken("time")));
            }

            // Create inline states
            AddStates(states, initialState, obj, ParseTime(obj, obj.SelectToken("time")));

            var id = (string) obj["id"] ?? Path.GetRandomFileName();
            var targetId = (string) obj.SelectToken("target_id");
            if (targetId != null && obj["id"] != null) throw new ArgumentException("Storyboard: A stage object cannot have both id and target_id");
            var parentId = (string) obj.SelectToken("parent_id");
            if (targetId != null && parentId != null) throw new ArgumentException("Storyboard: A stage object cannot have both target_id and parent_id");
            
            if (id.Contains("$note")) id = id.Replace("$note", ((int) replacements["note"]).ToString());
            if (targetId != null && targetId.Contains("$note")) targetId = targetId.Replace("$note", ((int) replacements["note"]).ToString());
            if (parentId != null && parentId.Contains("$note")) parentId = parentId.Replace("$note", ((int) replacements["note"]).ToString());

            return new TO
            {
                Id = id,
                TargetId = targetId,
                ParentId = parentId,
                States = states.OrderBy(state => state.Time).ToList() // Must sort by time
            };
        }

19 Source : CompileTimeRegistrationInfoSerializationTests.cs
with MIT License
from dadhi

[SetUp]
        public void SetupTestDirectory()
        {
            _temporaryTestDirectory = Path.GetRandomFileName();
            Directory.CreateDirectory(_temporaryTestDirectory);

            _originalDirectory = Directory.GetCurrentDirectory();
            Directory.SetCurrentDirectory(_temporaryTestDirectory);
        }

19 Source : Kernel32Tests.cs
with MIT License
from dahall

[Test]
		public void CreateHardLinkTest()
		{
			var link = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
			var fn = CreateTempFile();
			var b = CreateHardLink(link, fn);
			if (!b) TestContext.WriteLine($"CreateHardLink:{Win32Error.GetLastError()}");
			replacedert.That(b);
			replacedert.That(File.Exists(fn));
			var fnlen = new FileInfo(fn).Length;
			File.AppendAllText(link, "More text");
			replacedert.That(fnlen, Is.LessThan(new FileInfo(fn).Length));
			File.Delete(link);
			File.Delete(fn);
		}

19 Source : Kernel32Tests.cs
with MIT License
from dahall

[Test]
		public void CreateSymbolicLinkTest()
		{
			var link = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
			var fn = CreateTempFile(false);
			replacedert.That(File.Exists(fn));
			var b = CreateSymbolicLink(link, fn, SymbolicLinkType.SYMBOLIC_LINK_FLAG_FILE);
			if (!b) TestContext.WriteLine($"CreateSymbolicLink:{Win32Error.GetLastError()}");
			replacedert.That(b);
			replacedert.That(File.Exists(link));
			File.Delete(link);
			File.Delete(fn);
		}

19 Source : CSharpRunner.cs
with MIT License
from dahall

private static void CompileExe(string outputExePath, SyntaxTree syntaxTree, IEnumerable<string> references = null, string mainTypeName = null)
		{
			var mrefs = (references ?? StdRefs).Select(a => MetadataReference.CreateFromFile(a));
			var opts = new CSharpCompilationOptions(OutputKind.ConsoleApplication, allowUnsafe: true, mainTypeName: mainTypeName);
			var compilation = CSharpCompilation.Create(Path.GetRandomFileName(), new[] { syntaxTree }, mrefs, opts);
			var result = compilation.Emit(outputExePath);
			if (!result.Success)
			{
				throw new InvalidOperationException(string.Join("\n", result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error).Select(d => $"{d.Id}: {d.GetMessage()}")));
			}
		}

19 Source : CSharpRunner.cs
with MIT License
from dahall

private static replacedembly CompileLib(SyntaxTree syntaxTree, IEnumerable<string> references = null)
		{
			var mrefs = (references ?? StdRefs).Select(a => MetadataReference.CreateFromFile(a));
			var compilation = CSharpCompilation.Create(Path.GetRandomFileName(), new[] { syntaxTree }, mrefs, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

			using (var ms = new MemoryStream())
			{
				var result = compilation.Emit(ms);
				if (result.Success)
				{
					ms.Seek(0, SeekOrigin.Begin);
					return replacedembly.Load(ms.ToArray());
				}
				else
				{
					throw new InvalidOperationException(string.Join("\n", result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error).Select(d => $"{d.Id}: {d.GetMessage()}")));
				}
			}
		}

19 Source : NameSpaceApiTests.cs
with MIT License
from dahall

[Test]
		public void AddToBoundaryTest()
		{
			var bdh = CreateBoundaryDescriptor(Path.GetRandomFileName());
			replacedert.That(bdh.IsInvalid, Is.False);
			BoundaryDescriptorHandle h = bdh;
			try
			{
				var b = AddSIDToBoundaryDescriptor(ref h, SafePSID.Current);
				if (!b) TestContext.WriteLine($"ERR: AddSid={Win32Error.GetLastError()}");
				replacedert.That(b, Is.True);

				//var plsid = SafePSID.Init(KnownSIDAuthority.SECURITY_MANDATORY_LABEL_AUTHORITY, MandatoryIntegrityLevelSIDRelativeID.SECURITY_MANDATORY_MEDIUM_RID);
				//b = AddIntegrityLabelToBoundaryDescriptor(ref h, plsid);
				//if (!b) TestContext.WriteLine($"ERR: AddSid={Win32Error.GetLastError()}");
				//replacedert.That(b, Is.True);
			}
			finally
			{
				//DeleteBoundaryDescriptor(h);
				bdh.Close();
			}
		 }

19 Source : NameSpaceApiTests.cs
with MIT License
from dahall

[Test]
		public void AddToBoundaryTest2()
		{
			using (var bdh = CreateBoundaryDescriptor(Path.GetRandomFileName()))
			using (var pCurSid = SafePSID.Current)
			{
				replacedert.That(bdh.IsInvalid, Is.False);
				replacedert.That(bdh.AddSid(pCurSid), Is.True);
				//var plsid = SafePSID.Init(KnownSIDAuthority.SECURITY_MANDATORY_LABEL_AUTHORITY, MandatoryIntegrityLevelSIDRelativeID.SECURITY_MANDATORY_MEDIUM_RID);
				//replacedert.That(bdh.AddSid(plsid), Is.True);
			}
		}

19 Source : ProcessEnvTests.cs
with MIT License
from dahall

[Test]
		public void GetSetEnvironmentVariableTest()
		{
			var str = System.IO.Path.GetRandomFileName();
			replacedert.That(SetEnvironmentVariable(str, "Value"), Is.True);

			var sb = new StringBuilder(MAX_PATH);
			replacedert.That(GetEnvironmentVariable(str, sb, (uint)sb.Capacity), Is.Not.Zero);
			replacedert.That(sb.ToString(), Is.EqualTo("Value"));

			replacedert.That(SetEnvironmentVariable(str), Is.True);
		}

19 Source : WinEfsTests.cs
with MIT License
from dahall

[Test]
		public void EncryptionDisableTest()
		{
			var dir = System.IO.Path.Combine(TestCaseSources.TempDirWhack, System.IO.Path.GetRandomFileName());
			var dirInfo = System.IO.Directory.CreateDirectory(dir);
			try
			{
				replacedert.That(EncryptionDisable(dirInfo.FullName, true), ResultIs.Successful);
				replacedert.That(EncryptionDisable(dirInfo.FullName, false), ResultIs.Successful);
			}
			finally
			{
				dirInfo.Delete(true);
			}
		}

19 Source : ModifyManager.cs
with GNU General Public License v3.0
from DaneelTrevize

internal string extractSave( bool useTempDir )
        {
            if( state != SaveState.SET )
            {
                throw new InvalidOperationException( "Save File has not been set." );
            }

            if( useTempDir )
            {
                currentDecryptDir = Path.Combine( Path.GetTempPath(), Path.GetRandomFileName() );  // A random "file"/folder name under the user's temp directory
            }
            else
            {
                currentDecryptDir = Path.Combine( editsDir, Path.GetFileNameWithoutExtension( currentSaveFile ) );
            }
            if( Directory.Exists( currentDecryptDir ) )
            {
                // Dynamically generate decrypted file folders for leaving files after modification or for manual edits?

                // Nuke existing files
                Console.WriteLine( "Deleting the contents of: " + currentDecryptDir );
                DirectoryInfo decDir = new DirectoryInfo( currentDecryptDir );
                foreach( FileInfo file in decDir.GetFiles() )
                {
                    file.Delete();
                }
                foreach( DirectoryInfo dir in decDir.GetDirectories() )
                {
                    dir.Delete( true );
                }
            }
            else
            {
                Directory.CreateDirectory( currentDecryptDir );
            }

            string preplacedword = signAndGeneratePreplacedword( currentSaveFile );

            unpackSave( currentSaveFile, currentDecryptDir, preplacedword );

            state = SaveState.EXTRACTED;

            return currentSaveFile;
        }

19 Source : PackLogic.cs
with MIT License
from daryllabar

public static string GetTemporaryDirectory()
        {
            var tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            Directory.CreateDirectory(tempDirectory);
            return tempDirectory;
        }

19 Source : RedisAttributeTests.cs
with MIT License
from daulet

[Fact]
        public async Task Redis_GetMultiplexer_ValueReadFromRedis()
        {
            // Arrange
            var key = Path.GetRandomFileName();
            var value = Path.GetRandomFileName();
            var database = await _database.Value;
            await database.StringSetAsync(key, value);

            // Act
            var response = await httpClient.GetAsync($"http://localhost:7075/test/multiplexer/{key}");

            // replacedert
            var actualValue = await response.Content.ReadreplacedtringAsync();
            replacedert.Equal(value, actualValue);
        }

19 Source : RedisAttributeTests.cs
with MIT License
from daulet

[Fact]
        public async Task Redis_GetMultiplexerAsync_ValueReadFromRedis()
        {
            // Arrange
            var key = Path.GetRandomFileName();
            var value = Path.GetRandomFileName();
            var database = await _database.Value;
            await database.StringSetAsync(key, value);

            // Act
            var response = await httpClient.GetAsync($"http://localhost:7075/test/multiplexerasync/{key}");

            // replacedert
            var actualValue = await response.Content.ReadreplacedtringAsync();
            replacedert.Equal(value, actualValue);
        }

19 Source : RedisAttributeTests.cs
with MIT License
from daulet

[Fact]
        public async Task Redis_GetDatabase_ValueReadFromRedis()
        {
            // Arrange
            var key = Path.GetRandomFileName();
            var value = Path.GetRandomFileName();
            var database = await _database.Value;
            await database.StringSetAsync(key, value);

            // Act
            var response = await httpClient.GetAsync($"http://localhost:7075/test/database/{key}");

            // replacedert
            var actualValue = await response.Content.ReadreplacedtringAsync();
            replacedert.Equal(value, actualValue);
        }

19 Source : RedisAttributeTests.cs
with MIT License
from daulet

[Fact]
        public async Task Redis_GetDatabaseAsync_ValueReadFromRedis()
        {
            // Arrange
            var key = Path.GetRandomFileName();
            var value = Path.GetRandomFileName();
            var database = await _database.Value;
            await database.StringSetAsync(key, value);

            // Act
            var response = await httpClient.GetAsync($"http://localhost:7075/test/databaseasync/{key}");

            // replacedert
            var actualValue = await response.Content.ReadreplacedtringAsync();
            replacedert.Equal(value, actualValue);
        }

See More Examples