Here are the examples of the csharp api System.IO.Path.GetTempPath() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1972 Examples
19
View Source File : CelesteNetEmojiComponent.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public void Handle(CelesteNetConnection con, DataNetEmoji netemoji) {
Logger.Log(LogLevel.VVV, "netemoji", $"Received {netemoji.ID}");
string dir = Path.Combine(Path.GetTempPath(), "CelesteNetClientEmojiCache");
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
string path = Path.Combine(dir, $"{netemoji.ID}-{netemoji.GetHashCode():X8}.png");
using (FileStream fs = File.OpenWrite(path))
using (MemoryStream ms = new(netemoji.Data))
ms.CopyTo(fs);
RunOnMainThread(() => {
Logger.Log(LogLevel.VVV, "netemoji", $"Registering {netemoji.ID}");
bool registered = false;
try {
VirtualTexture vt = VirtualContent.CreateTexture(path);
MTexture mt = new(vt);
if (vt.Texture_Safe == null) // Needed to trigger lazy loading.
throw new Exception($"Couldn't load emoji {netemoji.ID}");
Registered.Add(netemoji.ID);
RegisteredFiles.Add(path);
Emoji.Register(netemoji.ID, mt);
Emoji.Fill(CelesteNetClientFont.Font);
registered = true;
} finally {
if (!registered)
File.Delete(path);
}
});
}
19
View Source File : RawFileType.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
protected override Doreplacedent OnLoad(Stream input)
{
Doreplacedent doc = null;
string tempFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
try
{
// Write the input stream to a temporary file for LibRaw to load.
using (FileStream output = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
if (input.CanSeek)
{
output.SetLength(input.Length);
}
// 81920 is the largest multiple of 4096 that is under the large object heap limit (85,000 bytes).
byte[] buffer = new byte[81920];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, bytesRead);
}
}
doc = GetRAWImageDoreplacedent(tempFile);
}
finally
{
File.Delete(tempFile);
}
return doc;
}
19
View Source File : SyntaxTreeFixerEditor.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
protected override void Initialize(CSharpCompilation oldCompilation, CancellationToken _)
{
OptimizationLevel compilationConfiguration = oldCompilation.Options.OptimizationLevel;
if (compilationConfiguration == OptimizationLevel.Debug && !runInDebug)
return;
if (compilationConfiguration == OptimizationLevel.Release && !runInRelease)
return;
CSharpCompilation EditCompilation(CSharpCompilation compilation, CancellationToken cancellationToken)
{
int syntaxTreesLength = compilation.SyntaxTrees.Length;
string randomDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
for (int i = 0; i < syntaxTreesLength; i++)
{
SyntaxTree tree = compilation.SyntaxTrees[i];
SyntaxTree nextTree = tree;
string treePath = tree.FilePath;
SourceText source = null;
if (nextTree.Encoding == null)
{
using (MemoryStream ms = new MemoryStream())
{
using (StreamWriter writer = new StreamWriter(ms, Encoding.UTF8, 4096, leaveOpen: true))
{
nextTree.GetText(cancellationToken).Write(writer, cancellationToken);
}
ms.Position = 0;
using (StreamReader reader = new StreamReader(ms, Encoding.UTF8, false, 4096, leaveOpen: true))
{
source = SourceText.From(reader, (int)ms.Length, Encoding.UTF8);
nextTree = nextTree.WithChangedText(source);
}
}
}
if (treePath != null && oldCompilation.SyntaxTrees.FirstOrDefault(x => x.FilePath == treePath) == tree)
{
// The tree already exists as a file, and is the one the user has;
// we don't need to change anything.
if (source == null)
// No changes applied
continue;
goto Replace;
}
if (!Directory.Exists(randomDirectory))
Directory.CreateDirectory(randomDirectory);
// The tree does not exist or has been changed by an editor,
// we need to change its filepath, and write a new file.
string newPath = string.IsNullOrEmpty(treePath)
? Path.Combine(randomDirectory, Path.GetRandomFileName() + ".cs")
: Path.Combine(randomDirectory, Path.GetFileName(treePath));
nextTree = nextTree.WithFilePath(newPath);
using (FileStream fs = File.Open(newPath, FileMode.Create, FileAccess.Write))
using (StreamWriter writer = new StreamWriter(fs, nextTree.Encoding, 4096))
{
if (source == null)
source = nextTree.GetText(cancellationToken);
source.Write(writer, cancellationToken);
}
Replace:
compilation = compilation.ReplaceSyntaxTree(tree, nextTree);
}
return compilation;
}
CompilationPipeline += EditCompilation;
}
19
View Source File : FileUtils.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public static string GetTempPath()
{
// Fix gource problem with unicode file names. F.e. C:\users\Александр\AppData\ -> C:\Users\8523~1\AppData\
return GetShortPath(Path.GetTempPath());
}
19
View Source File : AllocationTests.cs
License : MIT License
Project Creator : Abc-Arbitrage
License : MIT License
Project Creator : Abc-Arbitrage
[SetUp]
public void Setup()
{
_tempDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(_tempDirectory);
_waitableAppender = new WaitableAppender(Path.Combine(_tempDirectory, "allocation-test"));
BasicConfigurator.Configure(new ZeroLogBasicConfiguration
{
Appenders = { _waitableAppender },
LogEventQueueSize = 2048 * 10,
LogEventBufferSize = 512
});
LogManager.RegisterEnum<DayOfWeek>();
LogManager.RegisterUnmanaged<UnmanagedStruct>();
}
19
View Source File : SimRuntime.cs
License : MIT License
Project Creator : abdullin
License : MIT License
Project Creator : abdullin
public string GetSimulationFolder() {
if (_folder != null) {
return _folder;
}
// HINT: create a memory disk here
var root = "/Volumes/SimDisk";
if (!Directory.Exists(root)) {
root = Path.GetTempPath();
}
var folder = Path.Combine(root, "sim", DateTime.UtcNow.ToString("yy-MM-dd-HH-mm-ss"));
_folder = folder;
return folder;
}
19
View Source File : AutomationTestBase.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public string GetTemporaryDirectory()
{
string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
Directory.CreateDirectory(tempDirectory);
return tempDirectory;
}
19
View Source File : StreamVideoSourceHandler.cs
License : MIT License
Project Creator : adamfisher
License : MIT License
Project Creator : adamfisher
public async Task<string> LoadVideoAsync(VideoSource source, CancellationToken cancellationToken = default(CancellationToken))
{
string path = null;
var streamVideoSource = source as StreamVideoSource;
if (streamVideoSource?.Stream != null)
{
using (var stream = await streamVideoSource.GetStreamAsync(cancellationToken).ConfigureAwait(false))
{
if (stream != null)
{
var tempFileName = GetFileName(stream, streamVideoSource.Format);
var tempDirectory = Path.Combine(Path.GetTempPath(), "MediaCache");
path = Path.Combine(tempDirectory, tempFileName);
if (!File.Exists(path))
{
if (!Directory.Exists(tempDirectory))
Directory.CreateDirectory(tempDirectory);
using (var tempFile = File.Create(path))
{
await stream.CopyToAsync(tempFile);
}
}
}
}
}
return path;
}
19
View Source File : TestDirectory.cs
License : Apache License 2.0
Project Creator : adamralph
License : Apache License 2.0
Project Creator : adamralph
public static string Get(string testSuiteName, string testName, object tag = null) =>
Path.Combine(
Path.GetTempPath(),
testSuiteName,
TestContext.RunId.ToString(CultureInfo.InvariantCulture),
$"{testName}{(tag == null ? "" : (tag.GetType().Name.StartsWith("ValueTuple", StringComparison.Ordinal) ? tag : $"({tag})"))}");
19
View Source File : EdgeCasesTest.cs
License : MIT License
Project Creator : adams85
License : MIT License
Project Creator : adams85
[Fact]
public async Task FailingEntryDontGetStuck()
{
var logsDirName = Guid.NewGuid().ToString("D");
var tempPath = Path.Combine(Path.GetTempPath());
var logPath = Path.Combine(tempPath, logsDirName);
if (Directory.Exists(logPath))
Directory.Delete(logPath, recursive: true);
var fileProvider = new PhysicalFileProvider(tempPath);
var options = new FileLoggerOptions
{
FileAppender = new PhysicalFileAppender(fileProvider),
BasePath = logsDirName,
Files = new[]
{
new LogFileOptions
{
Path = "default.log",
},
},
};
var optionsMonitor = new DelegatedOptionsMonitor<FileLoggerOptions>(_ => options);
var completeCts = new CancellationTokenSource();
var completionTimeoutMs = 2000;
var context = new TestFileLoggerContext(completeCts.Token, TimeSpan.FromMilliseconds(completionTimeoutMs), writeRetryDelay: TimeSpan.FromMilliseconds(250));
context.SetTimestamp(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc));
var services = new ServiceCollection();
services.AddOptions();
services.AddLogging(b => b.AddFile(context));
services.AddSingleton<IOptionsMonitor<FileLoggerOptions>>(optionsMonitor);
string filePath = Path.Combine(logPath, "default.log");
try
{
FileLoggerProvider[] providers;
using (ServiceProvider sp = services.BuildServiceProvider())
{
providers = context.GetProviders(sp).ToArray();
replacedert.Equal(1, providers.Length);
var resetTasks = new List<Task>();
foreach (FileLoggerProvider provider in providers)
provider.Reset += (s, e) => resetTasks.Add(e);
ILoggerFactory loggerFactory = sp.GetRequiredService<ILoggerFactory>();
ILogger logger = loggerFactory.CreateLogger("X");
logger.LogInformation("This should get through.");
optionsMonitor.Reload();
// ensuring that reset has been finished and the new settings are effective
await Task.WhenAll(resetTasks);
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
logger.LogInformation("This shouldn't get through.");
Task completion = context.GetCompletion(sp);
replacedert.False(completion.IsCompleted);
completeCts.Cancel();
replacedert.Equal(completion, await Task.WhenAny(completion, Task.Delay(TimeSpan.FromMilliseconds(completionTimeoutMs * 2))));
replacedert.Equal(TaskStatus.RanToCompletion, completion.Status);
}
}
IFileInfo logFile = fileProvider.GetFileInfo($"{logsDirName}/default.log");
replacedert.True(logFile.Exists && !logFile.IsDirectory);
var lines = logFile.ReadAllText(out Encoding encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
replacedert.Equal(Encoding.UTF8, encoding);
replacedert.Equal(new[]
{
$"info: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
$" This should get through.",
""
}, lines);
}
finally
{
Directory.Delete(logPath, recursive: true);
}
}
19
View Source File : LoggingTest.cs
License : MIT License
Project Creator : adams85
License : MIT License
Project Creator : adams85
private async Task LoggingToPhysicalUsingDICore(LogFileAccessMode accessMode)
{
var logsDirName = Guid.NewGuid().ToString("D");
var configData = new Dictionary<string, string>
{
[$"{nameof(FileLoggerOptions.BasePath)}"] = logsDirName,
[$"{nameof(FileLoggerOptions.FileEncodingName)}"] = "UTF-16",
[$"{nameof(FileLoggerOptions.DateFormat)}"] = "yyMMdd",
[$"{nameof(FileLoggerOptions.FileAccessMode)}"] = accessMode.ToString(),
[$"{nameof(FileLoggerOptions.Files)}:0:{nameof(LogFileOptions.Path)}"] = "logger-<date>.log",
[$"{nameof(FileLoggerOptions.Files)}:0:{nameof(LogFileOptions.MinLevel)}:Karambolo.Extensions.Logging.File"] = LogLevel.None.ToString(),
[$"{nameof(FileLoggerOptions.Files)}:0:{nameof(LogFileOptions.MinLevel)}:{LogFileOptions.DefaultCategoryName}"] = LogLevel.Information.ToString(),
[$"{nameof(FileLoggerOptions.Files)}:1:{nameof(LogFileOptions.Path)}"] = "test-<date>.log",
[$"{nameof(FileLoggerOptions.Files)}:1:{nameof(LogFileOptions.MinLevel)}:Karambolo.Extensions.Logging.File.Test"] = LogLevel.Information.ToString(),
[$"{nameof(FileLoggerOptions.Files)}:1:{nameof(LogFileOptions.MinLevel)}:{LogFileOptions.DefaultCategoryName}"] = LogLevel.None.ToString(),
};
var cb = new ConfigurationBuilder();
cb.AddInMemoryCollection(configData);
IConfigurationRoot config = cb.Build();
var tempPath = Path.Combine(Path.GetTempPath());
var logPath = Path.Combine(tempPath, logsDirName);
var fileProvider = new PhysicalFileProvider(tempPath);
var cts = new CancellationTokenSource();
var context = new TestFileLoggerContext(cts.Token, completionTimeout: Timeout.InfiniteTimeSpan);
context.SetTimestamp(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc));
var diagnosticEventReceived = false;
context.DiagnosticEvent += _ => diagnosticEventReceived = true;
var services = new ServiceCollection();
services.AddOptions();
services.AddLogging(b => b.AddFile(context, o => o.FileAppender = new PhysicalFileAppender(fileProvider)));
services.Configure<FileLoggerOptions>(config);
if (Directory.Exists(logPath))
Directory.Delete(logPath, recursive: true);
try
{
var ex = new Exception();
FileLoggerProvider[] providers;
using (ServiceProvider sp = services.BuildServiceProvider())
{
providers = context.GetProviders(sp).ToArray();
replacedert.Equal(1, providers.Length);
ILogger<LoggingTest> logger1 = sp.GetService<ILogger<LoggingTest>>();
logger1.LogInformation("This is a nice logger.");
using (logger1.BeginScope("SCOPE"))
{
logger1.LogWarning(1, "This is a smart logger.");
logger1.LogTrace("This won't make it.");
using (logger1.BeginScope("NESTED SCOPE"))
{
ILoggerFactory loggerFactory = sp.GetService<ILoggerFactory>();
ILogger logger2 = loggerFactory.CreateLogger("X");
logger2.LogError(0, ex, "Some failure!");
}
}
cts.Cancel();
// ensuring that all entries are processed
await context.GetCompletion(sp);
replacedert.True(providers.All(provider => provider.Completion.IsCompleted));
}
replacedert.False(diagnosticEventReceived);
IFileInfo logFile = fileProvider.GetFileInfo($"{logsDirName}/test-{context.GetTimestamp().ToLocalTime():yyMMdd}.log");
replacedert.True(logFile.Exists && !logFile.IsDirectory);
var lines = logFile.ReadAllText(out Encoding encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
replacedert.Equal(Encoding.Unicode, encoding);
replacedert.Equal(new[]
{
$"info: {typeof(LoggingTest)}[0] @ {context.GetTimestamp().ToLocalTime():o}",
$" This is a nice logger.",
$"warn: {typeof(LoggingTest)}[1] @ {context.GetTimestamp().ToLocalTime():o}",
$" This is a smart logger.",
""
}, lines);
logFile = fileProvider.GetFileInfo(
$"{logsDirName}/logger-{context.GetTimestamp().ToLocalTime():yyMMdd}.log");
replacedert.True(logFile.Exists && !logFile.IsDirectory);
lines = logFile.ReadAllText(out encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
replacedert.Equal(Encoding.Unicode, encoding);
replacedert.Equal(new[]
{
$"fail: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
$" Some failure!",
}
.Concat(ex.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None))
.Append(""), lines);
}
finally
{
if (Directory.Exists(logPath))
Directory.Delete(logPath, recursive: true);
}
}
19
View Source File : LoggingTest.cs
License : MIT License
Project Creator : adams85
License : MIT License
Project Creator : adams85
[Fact]
public async Task LoggingToPhysicalUsingDIAndExpectingDiagnosticEvents()
{
var logsDirName = Guid.NewGuid().ToString("D");
var tempPath = Path.Combine(Path.GetTempPath());
var logPath = Path.Combine(tempPath, logsDirName);
var fileProvider = new PhysicalFileProvider(tempPath);
var cts = new CancellationTokenSource();
var context = new TestFileLoggerContext(cts.Token, completionTimeout: Timeout.InfiniteTimeSpan);
context.SetTimestamp(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc));
var diagnosticEvents = new List<IFileLoggerDiagnosticEvent>();
context.DiagnosticEvent += diagnosticEvents.Add;
var services = new ServiceCollection();
services.AddOptions();
services.AddLogging(b => b.AddFile(context, o =>
{
o.FileAppender = new PhysicalFileAppender(fileProvider);
o.BasePath = logsDirName;
o.FileAccessMode = LogFileAccessMode.KeepOpen;
o.Files = new[]
{
new LogFileOptions
{
Path = "<invalid_filename>.log"
}
};
}));
if (Directory.Exists(logPath))
Directory.Delete(logPath, recursive: true);
try
{
FileLoggerProvider[] providers;
using (ServiceProvider sp = services.BuildServiceProvider())
{
providers = context.GetProviders(sp).ToArray();
replacedert.Equal(1, providers.Length);
ILogger<LoggingTest> logger1 = sp.GetService<ILogger<LoggingTest>>();
logger1.LogInformation("This is a nice logger.");
logger1.LogWarning(1, "This is a smart logger.");
cts.Cancel();
// ensuring that all entries are processed
await context.GetCompletion(sp);
replacedert.True(providers.All(provider => provider.Completion.IsCompleted));
}
replacedert.NotEmpty(diagnosticEvents);
replacedert.All(diagnosticEvents, e =>
{
replacedert.IsType<FileLoggerDiagnosticEvent.LogEntryWriteFailed>(e);
replacedert.IsType<FileLoggerProcessor>(e.Source);
replacedert.NotNull(e.FormattableMessage);
replacedert.NotNull(e.Exception);
});
}
finally
{
if (Directory.Exists(logPath))
Directory.Delete(logPath, recursive: true);
}
}
19
View Source File : ResourceTestBase.cs
License : MIT License
Project Creator : adrianoc
License : MIT License
Project Creator : adrianoc
protected void replacedertResourceTestWithExplicitExpectation(string resourceName, string methodSignature)
{
using (var tbc = ReadResource(resourceName, "cs", TestKind.Integration))
using (var expectedILStream = ReadResource(resourceName, "cs.il", TestKind.Integration))
{
var expectedIL = ReadToEnd(expectedILStream);
var actualreplacedemblyPath = Path.Combine(Path.GetTempPath(), "CecilifierTests/", resourceName + ".dll");
replacedertResourceTestWithExplicitExpectedIL(actualreplacedemblyPath, expectedIL, methodSignature, tbc);
Console.WriteLine();
Console.WriteLine("Expected IL: {0}", expectedIL);
Console.WriteLine("Actual replacedembly path : {0}", actualreplacedemblyPath);
}
}
19
View Source File : Startup.cs
License : MIT License
Project Creator : adrianoc
License : MIT License
Project Creator : adrianoc
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseWebSockets();
app.UseCookiePolicy();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); });
app.Use(async (context, next) =>
{
if (context.Request.Path == "/ws")
{
if (context.WebSockets.IsWebSocketRequest)
{
var webSocket = await context.WebSockets.AcceptWebSocketAsync();
CecilifyCode(webSocket);
}
else
{
context.Response.StatusCode = 400;
}
}
else
{
await next();
}
});
void CecilifyCode(WebSocket webSocket)
{
var buffer = ArrayPool<byte>.Shared.Rent(64 * 1024);
var memory = new Memory<byte>(buffer);
var received = webSocket.ReceiveAsync(memory, CancellationToken.None).Result;
while (received.MessageType != WebSocketMessageType.Close)
{
CecilifierApplication.Count++;
var toBeCecilified = JsonSerializer.Deserialize<CecilifierRequest>(memory.Span[0..received.Count]);
var bytes = Encoding.UTF8.GetBytes(toBeCecilified.Code);
using (var code = new MemoryStream(bytes, 0, bytes.Length))
{
try
{
var deployKind = toBeCecilified.WebOptions.DeployKind;
var cecilifiedResult = Core.Cecilifier.Process(code, new CecilifierOptions
{
References = GetTrustedreplacedembliesPath(),
Naming = new DefaultNameStrategy(toBeCecilified.Settings.NamingOptions, toBeCecilified.Settings.ElementKindPrefixes.ToDictionary(entry => entry.ElementKind, entry => entry.Prefix))
});
SendTextMessageToChat("One more happy user (project)", $"Total so far: {CecilifierApplication.Count}\n\n***********\n\n```{toBeCecilified.Code}```", "4437377");
if (deployKind == 'Z')
{
var responseData = ZipProject(
("Program.cs", cecilifiedResult.GeneratedCode.ReadToEnd()),
("Cecilified.csproj", ProjectContents),
NameAndContentFromResource("Cecilifier.Web.Runtime")
);
var output = new Span<byte>(buffer);
var ret = Base64.EncodeToUtf8(responseData.Span, output, out var bytesConsumed, out var bytesWritten);
if (ret == OperationStatus.Done)
{
output = output[0..bytesWritten];
}
var dataToReturn = JsonSerializedBytes(Encoding.UTF8.GetString(output), 'Z', cecilifiedResult);
webSocket.SendAsync(dataToReturn, received.MessageType, received.EndOfMessage, CancellationToken.None);
}
else
{
var dataToReturn = JsonSerializedBytes(cecilifiedResult.GeneratedCode.ReadToEnd(), 'C', cecilifiedResult);
webSocket.SendAsync(dataToReturn, received.MessageType, received.EndOfMessage, CancellationToken.None);
}
}
catch (SyntaxErrorException ex)
{
var source = ((toBeCecilified.Settings.NamingOptions & NamingOptions.IncludeSourceInErrorReports) == NamingOptions.IncludeSourceInErrorReports) ? toBeCecilified.Code : string.Empty;
SendMessageWithCodeToChat("Syntax Error", ex.Message, "15746887", source);
var dataToReturn = Encoding.UTF8.GetBytes($"{{ \"status\" : 1, \"syntaxError\": \"{HttpUtility.JavaScriptStringEncode(ex.Message)}\" }}").AsMemory();
webSocket.SendAsync(dataToReturn, received.MessageType, received.EndOfMessage, CancellationToken.None);
}
catch (Exception ex)
{
SendExceptionToChat(ex, buffer, received.Count);
var dataToReturn = Encoding.UTF8.GetBytes($"{{ \"status\" : 2, \"error\": \"{HttpUtility.JavaScriptStringEncode(ex.ToString())}\" }}").AsMemory();
webSocket.SendAsync(dataToReturn, received.MessageType, received.EndOfMessage, CancellationToken.None);
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
received = webSocket.ReceiveAsync(memory, CancellationToken.None).Result;
}
webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
Memory<byte> ZipProject(params (string fileName, string contents)[] sources)
{
/*
//TODO: For some reason this code produces an invalid stream. Need to investigate.
using var zipStream = new MemoryStream();
using var zipFile = new ZipArchive(zipStream, ZipArchiveMode.Create);
foreach (var source in sources)
{
var entry = zipFile.CreateEntry(source.fileName, CompressionLevel.Fastest);
using var entryWriter = new StreamWriter(entry.Open());
entryWriter.Write(source.contents);
}
zipStream.Position = 0;
Memory<byte> s = zipStream.GetBuffer();
Console.WriteLine($"Stream Size = {zipStream.Length}");
return s.Slice(0, (int)zipStream.Length);
*/
var tempPath = Path.GetTempPath();
var replacedetsPath = Path.Combine(tempPath, "output");
if (Directory.Exists(replacedetsPath))
Directory.Delete(replacedetsPath, true);
Directory.CreateDirectory(replacedetsPath);
foreach (var source in sources)
{
File.WriteAllText(Path.Combine(replacedetsPath, $"{source.fileName}"), source.contents);
}
var outputZipPath = Path.Combine(tempPath, "Cecilified.zip");
if (File.Exists(outputZipPath))
File.Delete(outputZipPath);
ZipFile.CreateFromDirectory(replacedetsPath, outputZipPath, CompressionLevel.Fastest, false);
return File.ReadAllBytes(outputZipPath);
}
}
IReadOnlyList<string> GetTrustedreplacedembliesPath()
{
return ((string) AppContext.GetData("TRUSTED_PLATFORM_replacedEMBLIES")).Split(Path.PathSeparator).ToList();
}
}
19
View Source File : ResourceTestBase.cs
License : MIT License
Project Creator : adrianoc
License : MIT License
Project Creator : adrianoc
protected void replacedertResourceTestBinary(string resourceBasePath, TestKind kind)
{
var expectedreplacedemblyPath = resourceBasePath.GetPathOfBinaryResource("Expected.dll", kind);
var tbc = ReadResource(resourceBasePath, "cs", kind);
var actualreplacedemblyPath = Path.Combine(Path.GetTempPath(), "CecilifierTests/", resourceBasePath + ".dll");
replacedertResourceTest(actualreplacedemblyPath, expectedreplacedemblyPath, tbc);
}
19
View Source File : ResourceTestBase.cs
License : MIT License
Project Creator : adrianoc
License : MIT License
Project Creator : adrianoc
private void replacedertResourceTest(string resourceName, IreplacedemblyDiffVisitor visitor, bool buildAsExe, Stream tbc)
{
var cecilifierTestsFolder = Path.Combine(Path.GetTempPath(), "CecilifierTests");
var cecilifiedreplacedemblyPath = Path.Combine(cecilifierTestsFolder, resourceName + ".dll");
var resourceCompiledreplacedemblyPath = CompileExpectedTestreplacedembly(cecilifiedreplacedemblyPath, buildAsExe, ReadToEnd(tbc));
Console.WriteLine();
Console.WriteLine("Compiled from res : {0}", resourceCompiledreplacedemblyPath);
Console.WriteLine("Generated from Cecilifier: {0}", cecilifiedreplacedemblyPath);
replacedertResourceTest(cecilifiedreplacedemblyPath, resourceCompiledreplacedemblyPath, tbc, visitor);
}
19
View Source File : ResourceTestBase.cs
License : MIT License
Project Creator : adrianoc
License : MIT License
Project Creator : adrianoc
private void CecilifyAndExecute(Stream tbc, string outputreplacedemblyPath)
{
cecilifiedCode = Cecilfy(tbc);
var references = Utils.GetTrustedreplacedembliesPath().Where(a => !a.Contains("mscorlib"));
var refsToCopy = new List<string>
{
typeof(ILParser).replacedembly.Location,
typeof(TypeReference).replacedembly.Location,
typeof(TypeHelpers).replacedembly.Location,
};
references = references.Concat(refsToCopy).ToList();
var actualreplacedemblyGeneratorPath = Path.Combine(Path.GetTempPath(), $"CecilifierTests/{TestContext.CurrentContext.Test.MethodName}/{cecilifiedCode.GetHashCode()}/{TestContext.CurrentContext.Test.MethodName}");
var cecilifierRunnerPath = CompilationServices.CompileExe(actualreplacedemblyGeneratorPath, cecilifiedCode, references.ToArray());
Console.WriteLine("------- Cecilified Code -------");
Console.WriteLine(cecilifiedCode);
Console.WriteLine("^^^^^^^ Cecilified Code ^^^^^^^");
Directory.CreateDirectory(Path.GetDirectoryName(outputreplacedemblyPath));
CopyFilesNextToGeneratedExecutable(cecilifierRunnerPath, refsToCopy);
Console.WriteLine("Cecil runner path: {0}", cecilifierRunnerPath);
TestFramework.Execute("dotnet", cecilifierRunnerPath + " " + outputreplacedemblyPath);
}
19
View Source File : SavePhase.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a
License : GNU General Public License v3.0
Project Creator : Aekras1a
protected override void Execute(ConfuserContext context, ProtectionParameters parameters)
{
var vr = context.Annotations.Get<Virtualizer>(context, Fish.VirtualizerKey);
var merge = context.Annotations.Get<ModuleDef>(context, Fish.MergeKey);
if(merge != null)
return;
var tmpDir = Path.GetTempPath();
var outDir = Path.Combine(tmpDir, Path.GetRandomFileName());
Directory.CreateDirectory(outDir);
var rtPath = vr.SaveRuntime(outDir);
if(context.Packer != null)
{
#if DEBUG
var protRtPath = rtPath;
#else
var protRtPath = ProtectRT(context, rtPath);
#endif
context.ExternalModules.Add(File.ReadAllBytes(protRtPath));
foreach(var rule in context.Project.Rules)
rule.RemoveWhere(item => item.Id == Parent.Id);
}
else
{
outDir = Path.GetDirectoryName(rtPath);
foreach(var file in Directory.GetFiles(outDir))
{
var path = Path.Combine(context.OutputDirectory, Path.GetFileName(file));
Directory.CreateDirectory(Path.GetDirectoryName(path));
File.Copy(file, path, true);
}
}
}
19
View Source File : SavePhase.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a
License : GNU General Public License v3.0
Project Creator : Aekras1a
private string ProtectRT(ConfuserContext context, string fileName)
{
var outDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
Directory.CreateDirectory(outDir);
var proj = new ConfuserProject();
proj.Seed = context.Project.Seed;
proj.Debug = context.Project.Debug;
//foreach (Rule rule in context.Project.Rules) {
// var r = rule.Clone();
// r.RemoveWhere(prot => prot.Id == Parent.Id);
// proj.Rules.Add(r);
//}
proj.Rules.Add(new Rule
{
new SettingItem<Protection>("anti ildasm"),
new SettingItem<Protection>("ref proxy")
{
{"mode", "mild"},
{"typeErasure", "true"}
},
new SettingItem<Protection>("rename")
{
{"mode", "repeating"}
}
});
proj.Add(new ProjectModule
{
Path = fileName
});
proj.BaseDirectory = Path.GetDirectoryName(fileName);
proj.OutputDirectory = outDir;
foreach(var path in context.Project.ProbePaths)
proj.ProbePaths.Add(path);
proj.ProbePaths.Add(context.Project.BaseDirectory);
StrongNameKey snKey = null;
foreach(var module in context.Modules)
{
snKey = context.Annotations.Get<StrongNameKey>(module, Marker.SNKey);
if(snKey != null)
break;
}
try
{
ConfuserEngine.Run(new ConfuserParameters
{
Logger = new RTLogger(context.Logger),
Marker = new RTMarker(snKey),
Project = proj
}, context.CancellationToken).Wait();
}
catch(AggregateException ex)
{
context.Logger.Error("Failed to protect Runtime.");
throw new ConfuserException(ex);
}
return Path.Combine(outDir, Path.GetFileName(fileName));
}
19
View Source File : EmbedAssembly.cs
License : Apache License 2.0
Project Creator : aequabit
License : Apache License 2.0
Project Creator : aequabit
public static void Load(string embeddedResource, string fileName)
{
if (dic == null)
dic = new Dictionary<string, replacedembly>();
byte[] ba = null;
replacedembly asm = null;
replacedembly curAsm = replacedembly.GetExecutingreplacedembly();
using (Stream stm = curAsm.GetManifestResourceStream(embeddedResource))
{
// Either the file is not existed or it is not mark as embedded resource
if (stm == null)
throw new Exception(embeddedResource + " is not found in Embedded Resources.");
// Get byte[] from the file from embedded resource
ba = new byte[(int)stm.Length];
stm.Read(ba, 0, (int)stm.Length);
try
{
asm = replacedembly.Load(ba);
// Add the replacedembly/dll into dictionary
dic.Add(asm.FullName, asm);
return;
}
catch
{
// Purposely do nothing
// Unmanaged dll or replacedembly cannot be loaded directly from byte[]
// Let the process fall through for next part
}
}
bool fileOk = false;
string tempFile = "";
using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider())
{
// Get the hash value from embedded DLL/replacedembly
string fileHash = BitConverter.ToString(sha1.ComputeHash(ba)).Replace("-", string.Empty);
// Define the temporary storage location of the DLL/replacedembly
tempFile = Path.GetTempPath() + fileName;
// Determines whether the DLL/replacedembly is existed or not
if (File.Exists(tempFile))
{
// Get the hash value of the existed file
byte[] bb = File.ReadAllBytes(tempFile);
string fileHash2 = BitConverter.ToString(sha1.ComputeHash(bb)).Replace("-", string.Empty);
// Compare the existed DLL/replacedembly with the Embedded DLL/replacedembly
if (fileHash == fileHash2)
{
// Same file
fileOk = true;
}
else
{
// Not same
fileOk = false;
}
}
else
{
// The DLL/replacedembly is not existed yet
fileOk = false;
}
}
// Create the file on disk
if (!fileOk)
{
System.IO.File.WriteAllBytes(tempFile, ba);
}
// Load it into memory
asm = replacedembly.LoadFile(tempFile);
// Add the loaded DLL/replacedembly into dictionary
dic.Add(asm.FullName, asm);
}
19
View Source File : PreferencesDialog.cs
License : GNU General Public License v2.0
Project Creator : afrantzis
License : GNU General Public License v2.0
Project Creator : afrantzis
public void LoadPreferences()
{
if (GeneralPreferencesVBox == null)
InitWidget();
string val;
//
//
val = prefs["Default.Layout.File"];
LayoutFileEntry.Text = val;
LoadCheckButtonPreference(
"Default.Layout.UseCurrent",
UseCurrentLayoutCheckButton,
false);
//
//
//
val = prefs["Default.EditMode"];
if (val != "Insert" && val != "Overwrite")
val = "Insert";
{
EditModeEnum index;
if (val == "Insert")
index = EditModeEnum.Insert;
else
index = EditModeEnum.Overwrite;
DefaultEditModeComboBox.Active = (int)index;
}
//
//
if (prefs["ByteBuffer.TempDir"] != System.IO.Path.GetTempPath())
TempDirEntry.Text = prefs["ByteBuffer.TempDir"];
else
TempDirEntry.Text = "";
}
19
View Source File : Platform.Posix.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public static UnmanagedLibrary LoadUnmanagedLibrary(string libraryName)
{
if (string.IsNullOrWhiteSpace(libraryName))
{
throw new ArgumentException("A valid library name is expected.", nameof(libraryName));
}
// Now look: This method should ExpandPaths on LibraryPaths.
// That being said, it should just enumerate
// Path, AppBase, Arch, Compiler, LibraryName, Extension
// Secondly, this method should try each /lib/x86_64-linux-gnu/libload.so.2 to load,
// Third, this method should try EmbeddedResources,
// Finally, this method fails, telling the user all libraryPaths searched.
var libraryPaths = new List<string>(Platform.LibraryPaths);
Platform.ExpandPaths(libraryPaths, "{Path}", EnumerateLibLdConf("/etc/ld.so.conf"));
var PATHs = new List<string>();
PATHs.Add(EnsureNotEndingSlash(Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location)));
PATHs.AddRange(EnumerateLibLdPATH());
Platform.ExpandPaths(libraryPaths, "{DllPath}", PATHs.ToArray());
Platform.ExpandPaths(libraryPaths, "{AppBase}", EnsureNotEndingSlash(
AppDomain.CurrentDomain.BaseDirectory));
Platform.ExpandPaths(libraryPaths, "{LibraryName}", libraryName);
// Platform.ExpandPaths(libraryPaths, "{Ext}", Platform.LibraryFileExtension);
string architecture;
string[] architecturePaths = null;
if (Platform.Architecture == ImageFileMachine.I386 && Environment.Is64BitProcess)
{
architecture = "amd64";
}
else {
architecture = Enum.GetName(typeof(ImageFileMachine), Platform.Architecture).ToLower();
}
if (architecture == "i386") architecturePaths = new string[] { "i386", "x86" };
if (architecture == "amd64") architecturePaths = new string[] { "amd64", "x64" };
if (architecturePaths == null) architecturePaths = new string[] { architecture };
Platform.ExpandPaths(libraryPaths, "{Arch}", architecturePaths);
// Expand Compiler
Platform.ExpandPaths(libraryPaths, "{Compiler}", Platform.Compiler);
// Now TRY the enumerated Directories for libFile.so.*
string traceLabel = string.Format("UnmanagedLibrary[{0}]", libraryName);
foreach (string libraryPath in libraryPaths)
{
IEnumerable<string> files;
if (libraryPath.Contains("/"))
{
string folder = null;
string filesPattern = libraryPath;
int filesPatternI;
if (-1 < (filesPatternI = filesPattern.LastIndexOf('/')))
{
folder = filesPattern.Substring(0, filesPatternI + 1);
filesPattern = filesPattern.Substring(filesPatternI + 1);
}
if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) continue;
files = Directory.EnumerateFiles(folder, filesPattern, SearchOption.TopDirectoryOnly).ToArray();
}
else
{
files = Enumerable.Repeat(libraryPath, 1);
}
foreach (string file in files)
{
// Finally, I am really loading this file
SafeLibraryHandle handle = OpenHandle(file);
if (!handle.IsNullOrInvalid())
{
// This is Platform.Posix. In mono, just dlopen'ing the library doesn't work.
// Using DllImport("__Internal", EntryPoint = "mono_dllmap_insert") to get mono on the path.
MonoDllMapInsert(libraryName, file);
Trace.TraceInformation(string.Format("{0} Loaded binary \"{1}\"",
traceLabel, file));
return new UnmanagedLibrary(libraryName, handle);
}
else
{
Exception nativeEx = GetLastLibraryError();
Trace.TraceInformation(string.Format("{0} Custom binary \"{1}\" not loaded: {2}",
traceLabel, file, nativeEx.Message));
}
}
}
// Search ManifestResources for fileName.arch.ext
// TODO: Enumerate ManifestResources for ZeroMQ{Arch}{Compiler}{LibraryName}{Ext}.so.*
string resourceName = string.Format("ZeroMQ.{0}.{1}{2}", libraryName, architecture, ".so");
string tempPath = Path.Combine(Path.GetTempPath(), resourceName);
if (ExtractManifestResource(resourceName, tempPath))
{
// TODO: need syscall_chmod_execute(path); ?
SafeLibraryHandle handle = OpenHandle(tempPath);
if (!handle.IsNullOrInvalid())
{
MonoDllMapInsert(libraryName, tempPath);
Trace.TraceInformation(string.Format("{0} Loaded binary from EmbeddedResource \"{1}\" from \"{2}\".",
traceLabel, resourceName, tempPath));
return new UnmanagedLibrary(libraryName, handle);
}
else
{
Trace.TraceWarning(string.Format("{0} Unable to run the extracted EmbeddedResource \"{1}\" from \"{2}\".",
traceLabel, resourceName, tempPath));
}
}
else
{
Trace.TraceWarning(string.Format("{0} Unable to extract the EmbeddedResource \"{1}\" to \"{2}\".",
traceLabel, resourceName, tempPath));
}
var fnf404 = new StringBuilder();
fnf404.Append(traceLabel);
fnf404.Append(" Unable to load binary \"");
fnf404.Append(libraryName);
fnf404.AppendLine("\" from folders");
foreach (string path in libraryPaths)
{
fnf404.Append("\t");
fnf404.AppendLine(path);
}
fnf404.Append(" Also unable to load binary from EmbeddedResource \"");
fnf404.Append(resourceName);
fnf404.Append("\", from temporary path \"");
fnf404.Append(tempPath);
fnf404.Append("\". See Trace output for more information.");
throw new FileNotFoundException(fnf404.ToString());
}
19
View Source File : Platform.Win32.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public static UnmanagedLibrary LoadUnmanagedLibrary(string libraryName)
{
if (string.IsNullOrWhiteSpace(libraryName))
{
throw new ArgumentException("A valid library name is expected.", nameof(libraryName));
}
// Now look: This method should ExpandPaths on LibraryPaths.
// That being said, it should just enumerate
// Path, AppBase, Arch, Compiler, LibraryName, Extension
// Secondly, this method should try each /lib/x86_64-linux-gnu/libload.so.2 to load,
// Third, this method should try EmbeddedResources,
// Finally, this method fails, telling the user all libraryPaths searched.
var libraryPaths = new List<string>(Platform.LibraryPaths);
Platform.ExpandPaths(libraryPaths, "{System32}", Environment.SystemDirectory);
var PATHs = new List<string>();
PATHs.Add(EnsureNotEndingBackSlash(Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location)));
PATHs.AddRange(EnumeratePATH());
Platform.ExpandPaths(libraryPaths, "{DllPath}", PATHs);
Platform.ExpandPaths(libraryPaths, "{AppBase}", EnsureNotEndingBackSlash(
AppDomain.CurrentDomain.BaseDirectory));
Platform.ExpandPaths(libraryPaths, "{LibraryName}", libraryName);
// Platform.ExpandPaths(libraryPaths, "{Ext}", Platform.LibraryFileExtension);
string architecture;
string[] architecturePaths = null;
if (Platform.Architecture == ImageFileMachine.I386 && Environment.Is64BitProcess)
{
architecture = "amd64";
}
else {
architecture = Enum.GetName(typeof(ImageFileMachine), Platform.Architecture).ToLower();
}
if (architecture == "i386") architecturePaths = new string[] { "i386", "x86" };
if (architecture == "amd64") architecturePaths = new string[] { "amd64", "x64" };
if (architecturePaths == null) architecturePaths = new string[] { architecture };
Platform.ExpandPaths(libraryPaths, "{Arch}", architecturePaths);
// Expand Compiler
Platform.ExpandPaths(libraryPaths, "{Compiler}", Platform.Compiler);
// Now TRY the enumerated Directories for libFile.so.*
string traceLabel = string.Format("UnmanagedLibrary[{0}]", libraryName);
foreach (string libraryPath in libraryPaths)
{
string folder = null;
string filesPattern = libraryPath;
int filesPatternI;
if (-1 < (filesPatternI = filesPattern.LastIndexOf('\\')))
{
folder = filesPattern.Substring(0, filesPatternI + 1);
filesPattern = filesPattern.Substring(filesPatternI + 1);
}
if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) continue;
string[] files = Directory.EnumerateFiles(folder, filesPattern, SearchOption.TopDirectoryOnly).ToArray();
foreach (string file in files)
{
// Finally, I am really loading this file
SafeLibraryHandle handle = OpenHandle(file);
if (!handle.IsNullOrInvalid())
{
Trace.TraceInformation(string.Format("{0} Loaded binary \"{1}\"",
traceLabel, file));
return new UnmanagedLibrary(libraryName, handle);
}
else
{
Exception nativeEx = GetLastLibraryError();
Trace.TraceInformation(string.Format("{0} Custom binary \"{1}\" not loaded: {2}",
traceLabel, file, nativeEx.Message));
}
}
}
// Search ManifestResources for fileName.arch.ext
// TODO: Enumerate ManifestResources for ZeroMQ{Arch}{Compiler}{LibraryName}{Ext}.dll
string resourceName = string.Format("ZeroMQ.{0}.{1}{2}", libraryName, architecture, ".dll");
string tempPath = Path.Combine(Path.GetTempPath(), resourceName);
if (ExtractManifestResource(resourceName, tempPath))
{
SafeLibraryHandle handle = OpenHandle(tempPath);
if (!handle.IsNullOrInvalid())
{
Trace.TraceInformation(string.Format("{0} Loaded binary from EmbeddedResource \"{1}\" from \"{2}\".",
traceLabel, resourceName, tempPath));
return new UnmanagedLibrary(libraryName, handle);
}
else
{
Trace.TraceWarning(string.Format("{0} Unable to run the extracted EmbeddedResource \"{1}\" from \"{2}\".",
traceLabel, resourceName, tempPath));
}
}
else
{
Trace.TraceWarning(string.Format("{0} Unable to extract the EmbeddedResource \"{1}\" to \"{2}\".",
traceLabel, resourceName, tempPath));
}
var fnf404 = new StringBuilder();
fnf404.Append(traceLabel);
fnf404.Append(" Unable to load binary \"");
fnf404.Append(libraryName);
fnf404.AppendLine("\" from folders");
foreach (string path in libraryPaths)
{
fnf404.Append("\t");
fnf404.AppendLine(path);
}
fnf404.Append(" Also unable to load binary from EmbeddedResource \"");
fnf404.Append(resourceName);
fnf404.Append("\", from temporary path \"");
fnf404.Append(tempPath);
fnf404.Append("\". See Trace output for more information.");
throw new FileNotFoundException(fnf404.ToString());
}
19
View Source File : KeyRotationBuilderExtensionsTest.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
[Fact]
public void PersistKeysToFileSystem_should_add_FileSystemXmlRepository()
{
var builder = new ServiceCollection()
.AddKeysRotation()
.PersistKeysToFileSystem(new DirectoryInfo(Path.GetTempPath()));
var provider = builder.Services.BuildServiceProvider();
var options = provider.GetRequiredService<IOptions<KeyRotationOptions>>();
replacedert.NotNull(options.Value.XmlRepository);
replacedert.IsType<FileSystemXmlRepository>(options.Value.XmlRepository);
}
19
View Source File : ExternalEditor.cs
License : GNU General Public License v3.0
Project Creator : ahmed605
License : GNU General Public License v3.0
Project Creator : ahmed605
public void LaunchEditor(FileSystem fs, File file)
{
if (fs is RealFileSystem)
{
// We'll edit RealFileSystems on the spot... no memory caching
// Some of the files are pretty big...
DirectoryInfo parent = new DirectoryInfo((fs as RealFileSystem).RealDirectory).Parent;
string filename = parent == null ? file.FullName : Path.Combine(parent.FullName, file.FullName);
var info = new ProcessStartInfo(filename);
info.UseShellExecute = true;
var p = Process.Start(info);
if (p != null)
{
p.WaitForExit();
}
}
else
{
// Export the file to a temporary file and load it up
string tempFileName = Path.Combine(Path.GetTempPath(), file.Name);
System.IO.File.WriteAllBytes(tempFileName, file.GetData());
var info = new ProcessStartInfo(tempFileName);
info.UseShellExecute = true;
var p = Process.Start(info);
if (p != null)
{
p.WaitForExit();
if (p.ExitCode == 0)
{
var data = System.IO.File.ReadAllBytes(tempFileName);
file.SetData(data);
}
}
}
}
19
View Source File : HyperTextViewer.cs
License : GNU General Public License v3.0
Project Creator : ahmed605
License : GNU General Public License v3.0
Project Creator : ahmed605
public Control GetView(File file)
{
var data = file.GetData();
var ms = new MemoryStream(data);
var hyperTextFile = new HyperTextFile();
try
{
hyperTextFile.Open(ms);
}
finally
{
ms.Close();
}
StringWriter sw = new StringWriter();
hyperTextFile.WriteHTML(sw);
// Create a temporary folder
string tempPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
string htmlPath = Path.Combine(tempPath, "exported.html");
Directory.CreateDirectory(tempPath);
System.IO.File.WriteAllText(htmlPath, sw.ToString());
if (hyperTextFile.EmbeddedTextureFile != null)
{
foreach (var texture in hyperTextFile.EmbeddedTextureFile)
{
string imagePath = Path.Combine(tempPath, texture.Name + ".png");
string directory = Path.GetDirectoryName(imagePath);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
Image image = texture.Decode();
image.Save(imagePath, ImageFormat.Png);
}
}
WebBrowser browser = new WebBrowser();
browser.AllowNavigation = false;
browser.AllowWebBrowserDrop = false;
//_browser.WebBrowserShortcutsEnabled = false;
//_browser.IsWebBrowserContextMenuEnabled = false;
//browser.DoreplacedentText = sw.ToString();
browser.Navigate(htmlPath);
browser.Disposed += delegate
{
Directory.Delete(tempPath, true);
if (hyperTextFile.EmbeddedTextureFile != null)
{
hyperTextFile.EmbeddedTextureFile.Dispose();
}
};
return browser;
}
19
View Source File : FilePackageStorageServiceTests.cs
License : MIT License
Project Creator : ai-traders
License : MIT License
Project Creator : ai-traders
[Fact]
public void CreatesStoreDirectoryIfItDoesNotExist()
{
string validButNotExistingPath = Path.Combine(Path.GetTempPath(), System.Guid.NewGuid().ToString("N"));
replacedert.False(Directory.Exists(validButNotExistingPath));
IPackageStorageService service = new FilePackageStorageService(validButNotExistingPath);
replacedert.False(Directory.Exists(validButNotExistingPath));
}
19
View Source File : TestServerBuilder.cs
License : MIT License
Project Creator : ai-traders
License : MIT License
Project Creator : ai-traders
private TestServerBuilder UseEmptyTempFolder()
{
Configuration.Add(DatabaseTypeKey, DatabaseType.Sqlite.ToString());
string uniqueTempFolder = Path.Combine(Path.GetTempPath(), System.Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(uniqueTempFolder);
string resolvedSqliteFile = Path.Combine(uniqueTempFolder, "LiGet.db");
string storageFolderPath = Path.Combine(uniqueTempFolder, DefaultPackagesFolderName);
Configuration.Add(ConnectionStringKey, string.Format("Data Source={0}", resolvedSqliteFile));
Configuration.Add(StorageTypeKey, StorageType.FileSystem.ToString());
Configuration.Add(FileSystemStoragePathKey, storageFolderPath);
Configuration.Add(SearchTypeKey, nameof(SearchType.Database));
Configuration.Add(CacheEnabledKey, true.ToString());
Configuration.Add(UpstreamIndexKey, "https://api.nuget.org/v3/index.json");
Configuration.Add(BaGetCompatEnabledKey, true.ToString());
string cacheDirName = Path.Combine(uniqueTempFolder, "CachedPackages");
Configuration.Add(CacheCachedDirKey, cacheDirName);
return this;
}
19
View Source File : MainWindow.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : aianlinb
License : GNU Affero General Public License v3.0
Project Creator : aianlinb
private void OnButtonOpenClick(object sender, RoutedEventArgs e)
{
var tvi = GetSelectedFile();
if (tvi == null)
return;
if (tvi is NotExistModel)
{
MessageBox.Show("This bundle wasn't loaded!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
var f = tvi.Record as FileRecord;
if (f != null) //Selected File
{
var path = Path.GetTempPath() + Path.GetFileName(f.path);
File.WriteAllBytes(path, f.Read());
try
{
Process.Start(path).Exited += OnProcessExit;
} catch (System.ComponentModel.Win32Exception)
{
Process.Start(new ProcessStartInfo("explorer.exe", "\"" + path + "\""));
}
}
}
19
View Source File : updateForm.cs
License : MIT License
Project Creator : ajohns6
License : MIT License
Project Creator : ajohns6
private void checkUpdate(object sender, EventArgs e)
{
if (!progressForm.IsConnectedToInternet())
{
this.Dispose();
return;
}
string url = "https://api.github.com/repos/ajohns6/SM64-NX-Launcher/releases";
string releaseString = "";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Accept = "application/json";
request.Method = "GET";
request.UserAgent = "Foo";
try
{
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
releaseString = reader.ReadToEnd();
}
}
catch
{
this.Dispose();
return;
}
Application.DoEvents();
var releaseList = JsonConvert.DeserializeObject<List<release>>(releaseString);
if (releaseList[0].tag_name != ("v" + version))
{
this.statusLabel.Text = "Downloading " + releaseList[0].tag_name + "...";
this.progBar.Visible = true;
string tempPath = Path.Combine(Path.GetTempPath(),
"sm64nxlauncherinstaller",
version);
string zipPath = Path.Combine(tempPath, "installer.zip");
mainForm.DeleteDirectory(tempPath);
Task.Run(() =>
{
using (var client = new WebClient())
{
if (!Directory.Exists(tempPath))
{
Directory.CreateDirectory(tempPath);
}
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloadProgress);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(downloadComplete);
Uri installerLink = new Uri(releaseList[0].replacedets[0].browser_download_url);
client.DownloadFileAsync(installerLink, zipPath);
}
});
progBar.Maximum = 100;
Application.DoEvents();
do
{
progBar.Value = progress;
} while (progress < 100);
do
{
Application.DoEvents();
} while (!complete);
this.statusLabel.Text = "Extracting installer...";
Task.Run(() =>
{
bool unzipped = false;
do
{
try
{
ZipFile.ExtractToDirectory(zipPath, tempPath);
unzipped = true;
}
catch { }
} while (!unzipped);
}).Wait();
ProcessStartInfo installStart = new ProcessStartInfo();
installStart.FileName = Path.Combine(tempPath, "setup.exe");
Process installer = new Process();
installer.StartInfo = installStart;
installer.Start();
Application.Exit();
}
this.Close();
}
19
View Source File : Injector.cs
License : MIT License
Project Creator : Akaion
License : MIT License
Project Creator : Akaion
private static string CreateTemporaryDll(byte[] dllBytes)
{
// Ensure a directory exists on disk to store the temporary DLL
var temporaryDirectoryInfo = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "Bleak", "DLL"));
// Clear the directory
foreach (var file in temporaryDirectoryInfo.EnumerateFiles())
{
try
{
file.Delete();
}
catch (Exception)
{
// The file is currently open and cannot be safely deleted
}
}
// Create a temporary DLL with a randomised name
var temporaryDllPath = Path.Combine(temporaryDirectoryInfo.FullName, Path.GetRandomFileName() + ".dll");
try
{
File.WriteAllBytes(temporaryDllPath, dllBytes);
}
catch (IOException)
{
// A DLL already exists with the specified name, is loaded in a process and cannot be safely overwritten
}
return temporaryDllPath;
}
19
View Source File : PdbFile.cs
License : MIT License
Project Creator : Akaion
License : MIT License
Project Creator : Akaion
private static async Task<string> DownloadPdb(DebugData debugData, bool isWow64)
{
// Ensure a directory exists on disk for the PDB
var directoryInfo = Directory.CreateDirectory(isWow64 ? Path.Combine(Path.GetTempPath(), "Bleak", "PDB", "WOW64") : Path.Combine(Path.GetTempPath(), "Bleak", "PDB", "x64"));
var pdbName = $"{debugData.Name}-{debugData.Guid}-{debugData.Age}.pdb";
var pdbPath = Path.Combine(directoryInfo.FullName, pdbName);
// Determine if the PDB has already been downloaded
if (directoryInfo.EnumerateFiles().Any(file => file.Name == pdbName))
{
return pdbPath;
}
// Clear the directory
foreach (var file in directoryInfo.EnumerateFiles())
{
try
{
file.Delete();
}
catch (Exception)
{
// The file is currently open and cannot be safely deleted
}
}
// Download the PDB
var pdbUri = new Uri($"http://msdl.microsoft.com/download/symbols/{debugData.Name}/{debugData.Guid}{debugData.Age}/{debugData.Name}");
void ReportDownloadProgress(object sender, ProgressChangedEventArgs eventArgs)
{
var progress = eventArgs.ProgressPercentage / 2;
Console.Write($"\rDownloading required files - [{new string('=', progress)}{new string(' ', 50 - progress)}] - {eventArgs.ProgressPercentage}%");
}
using var webClient = new WebClient();
webClient.DownloadProgressChanged += ReportDownloadProgress;
await webClient.DownloadFileTaskAsync(pdbUri, pdbPath);
return pdbPath;
}
19
View Source File : CleanupService.cs
License : MIT License
Project Creator : AlbertMN
License : MIT License
Project Creator : AlbertMN
private bool Check() {
if (EmptyCheck()) {
DirectoryInfo di = new DirectoryInfo(MainProgram.CheckPath(true));
int numFiles = 0;
try {
foreach (string file in Directory.GetFiles(MainProgram.CheckPath(true), "*." + Properties.Settings.Default.ActionFileExtension)) {
//if (cleanedFiles.Contains(file)) continue;
bool hidden = (File.GetAttributes(file) & FileAttributes.Hidden) == FileAttributes.Hidden;
if (!hidden) {
File.SetAttributes(file, FileAttributes.Hidden);
}
string tmpFolder = Path.Combine(Path.GetTempPath(), "replacedistantComputerControl");
if (!Directory.Exists(tmpFolder)) {
Directory.CreateDirectory(tmpFolder);
}
//string newFilename = Path.Combine(Path.GetDirectoryName(file), "action_" + DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString() + "_" + Guid.NewGuid() + "." + Properties.Settings.Default.ActionFileExtension);
//string newFilename = Path.Combine(tmpFolder, "action_" + DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString() + "_" + Guid.NewGuid() + "." + Properties.Settings.Default.ActionFileExtension);
//string newFilename = Path.Combine(Path.Combine(MainProgram.CheckPath(true), "used_actions"), "action_" + DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString() + "_" + Guid.NewGuid() + "." + Properties.Settings.Default.ActionFileExtension);
//File.Move(file, newFilename);
//File.Delete(newFilename);
File.Delete(file);
//cleanedFiles.Add(newFilename);
numFiles++;
}
} catch (Exception e) {
MainProgram.DoDebug("[CLEANUP] Failed to rename a file in action folder; " + e.Message + ". Successfully renamed and hid " + numFiles.ToString() + " files");
return false;
}
if (numFiles > 0) {
Thread.Sleep(1000);
}
return true;
/*if (!EmptyCheck()) {
MainProgram.DoDebug("[CLEANUP] All action folder files successfully renamed and hid (" + numFiles.ToString() + " files)");
return true;
} else {
MainProgram.DoDebug("[CLEANUP] Folder wasn't cleared");
}*/
} else {
MainProgram.DoDebug("[CLEANUP] Check done - action folder is empty");
}
return false;
}
19
View Source File : Utils.cs
License : GNU General Public License v2.0
Project Creator : albertogeniola
License : GNU General Public License v2.0
Project Creator : albertogeniola
private static string DownloadJsonFile(Uri url, string method, Dictionary<string, string> encodedpars, Dictionary<string, string> headers, ref CookieContainer cookiecontainer, string customLocalTempDir, out string computed_url)
{
string localTmp = null;
string filePath = null;
if (url == null || string.IsNullOrEmpty(url.AbsolutePath))
throw new ArgumentException("Url parameter was null or empty.");
if (method == null)
throw new ArgumentException("Method cannot be null.");
method = method.ToUpper();
if (method != "GET" && method != "POST" && method != "PUT" && method != "DELETE")
throw new ArgumentException("Invalid http method supplied: " + method);
if (!string.IsNullOrEmpty(customLocalTempDir))
{
if (!Directory.Exists(customLocalTempDir))
throw new ArgumentException("Local tmp path doesn't exist: " + customLocalTempDir);
localTmp = customLocalTempDir;
}
else
{
localTmp = Path.GetTempPath();
}
filePath = Path.Combine(localTmp, Guid.NewGuid().ToString() + ".json");
using (var handler = new HttpClientHandler() { CookieContainer = cookiecontainer })
using (var client = new HttpClient(handler) { BaseAddress = url })
{
// Setto i parametri e gli headers
handler.AllowAutoRedirect = true;
handler.UseCookies = true;
HttpRequestMessage req = new HttpRequestMessage();
req.RequestUri = url;
computed_url = url.ToString();
if (headers != null)
foreach (var h in headers) {
req.Headers.Add(h.Key, h.Value);
}
System.Threading.Tasks.Task<HttpResponseMessage> mtd = null;
switch (method)
{
case "GET":
req.Method = HttpMethod.Get;
break;
case "POST":
req.Method = HttpMethod.Post;
var data = new FormUrlEncodedContent(encodedpars);
req.Content = data;
break;
case "PUT":
req.Method = HttpMethod.Put;
data = new FormUrlEncodedContent(encodedpars);
req.Content = data;
break;
case "DELETE":
req.Method = HttpMethod.Delete;
break;
}
mtd = client.SendAsync(req);
HttpResponseMessage result = null;
try {
result = mtd.Result;
} catch(AggregateException e) {
// Any kind of exception could have happened in here.
// So, we simply wrap the exception into one of our specific clreplaced that will be catched later from the caller.
throw new DataCollectionException("Error during HTTP request to "+req.RequestUri, e.InnerException);
}
// In case there was no hard failure connected to the network, we have to check whether the result code was ok or not.
if (!result.IsSuccessStatusCode)
{
throw new BadHttpCodeException(result);
}
// Write to file.
using (var sw = new FileStream(filePath, FileMode.OpenOrCreate))
result.Content.CopyToAsync(sw).Wait();
}
return filePath;
}
19
View Source File : TempFileUtils.cs
License : GNU General Public License v3.0
Project Creator : alexdillon
License : GNU General Public License v3.0
Project Creator : alexdillon
public static string GetTempFileName(string originalFileName)
{
var extension = Path.GetExtension(originalFileName);
var tempFileName = Path.GetFileNameWithoutExtension(Path.GetTempFileName());
var tempFile = Path.Combine(Path.GetTempPath(), "GroupMeDesktopClient", tempFileName + extension);
return tempFile;
}
19
View Source File : FileAttachmentControlViewModel.cs
License : GNU General Public License v3.0
Project Creator : alexdillon
License : GNU General Public License v3.0
Project Creator : alexdillon
private async Task ClickedAction(PointerPressedEventArgs e)
{
if (e == null || e.GetCurrentPoint(null).Properties.IsLeftButtonPressed)
{
this.IsLoading = true;
var data = await this.FileAttachment.DownloadFileAsync(this.MessageContainer.Messages.First());
var extension = System.IO.Path.GetExtension(this.FileData.FileName);
var tempFileName = Path.GetFileNameWithoutExtension(Path.GetTempFileName());
var tempFile = Path.Combine(Path.GetTempPath(), "GroupMeDesktopClientAvalonia", tempFileName + extension);
File.WriteAllBytes(tempFile, data);
var psInfo = new ProcessStartInfo()
{
FileName = tempFile,
UseShellExecute = true,
};
System.Diagnostics.Process.Start(psInfo);
this.IsLoading = false;
}
}
19
View Source File : MainWindowViewModel.cs
License : GNU General Public License v3.0
Project Creator : alexdillon
License : GNU General Public License v3.0
Project Creator : alexdillon
private void ClearTempFiles()
{
var tempFolder = Path.Combine(Path.GetTempPath(), "GroupMeDesktopClientAvalonia");
if (Directory.Exists(tempFolder))
{
foreach (var file in Directory.EnumerateFiles(tempFolder))
{
try
{
File.Delete(file);
}
catch (Exception)
{
}
}
}
Directory.CreateDirectory(tempFolder);
}
19
View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
private void mnuCheckForUpdates_Click(object sender, EventArgs e)
{
System.Threading.Tasks.Task<IReadOnlyList<Octokit.Release>> releases;
Octokit.Release latest = null;
ProgressDialog progressDownload = new ProgressDialog();
Thread thread = new Thread(() =>
{
Octokit.GitHubClient client = new Octokit.GitHubClient(new Octokit.ProductHeaderValue("alexgracianoarj"));
releases = client.Repository.Release.GetAll("alexgracianoarj", "nclreplaced");
latest = releases.Result[0];
if (progressDownload.InvokeRequired)
progressDownload.BeginInvoke(new Action(() => progressDownload.Close()));
});
thread.Start();
progressDownload.Text = "Update";
progressDownload.lblPleaseWait.Text = "Checking...";
progressDownload.SetIndeterminate(true);
progressDownload.ShowDialog();
double latestVersion = Convert.ToDouble(latest.TagName.Replace("v", ""), System.Globalization.CultureInfo.InvariantCulture);
double programVersion = Convert.ToDouble(Program.CurrentVersion.ToString(2), System.Globalization.CultureInfo.InvariantCulture);
if (latestVersion > programVersion)
{
if (MessageBox.Show("There is a new version of NClreplaced.\n\nDo you want download the new version and install it now?", "NClreplaced", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.Yes)
{
thread = new Thread(() =>
{
WebClient wc = new WebClient();
wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler((sen, env) =>
{
double bytesIn = double.Parse(env.BytesReceived.ToString());
double totalBytes = double.Parse(env.TotalBytesToReceive.ToString());
double percentage = bytesIn / totalBytes * 100;
if (progressDownload.InvokeRequired)
progressDownload.BeginInvoke(new Action(() => progressDownload.SetIndeterminate(false)));
if (progressDownload.InvokeRequired)
progressDownload.BeginInvoke(new Action(() => progressDownload.lblPleaseWait.Text = "Downloaded " + Convert.ToInt32(percentage) + "% - " + (env.BytesReceived / 1024) + " KB of " + (env.TotalBytesToReceive / 1024) + " KB"));
if (progressDownload.InvokeRequired)
progressDownload.BeginInvoke(new Action(() => progressDownload.progressBar1.Value = Convert.ToInt32(percentage)));
});
wc.DownloadFileCompleted += new AsyncCompletedEventHandler((sen, env) =>
{
// Close the dialog if it hasn't been already
if (progressDownload.InvokeRequired)
progressDownload.BeginInvoke(new Action(() => progressDownload.Close()));
System.Diagnostics.Process.Start(Path.GetTempPath() + "NClreplaced_Update.exe");
Application.Exit();
});
wc.DownloadFileAsync(new Uri(latest.replacedets[0].BrowserDownloadUrl), Path.GetTempPath() + "NClreplaced_Update.exe");
});
thread.Start();
progressDownload.lblPleaseWait.Text = "Downloading...";
progressDownload.ShowDialog();
}
}
else
{
MessageBox.Show("NClreplaced is already updated.", "NClreplaced", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
19
View Source File : CheckForUpdatesWindow.cs
License : Apache License 2.0
Project Creator : Algoryx
License : Apache License 2.0
Project Creator : Algoryx
private void OnEnable()
{
m_status = Status.Preplacedive;
m_serverVersion = VersionInfo.Invalid;
m_currentVersion = PackageUpdateHandler.FindCurrentVersion();
m_sourceFilename = string.Empty;
m_downloadDirectory = Path.GetTempPath();
m_downloadProgress = 0.0f;
}
19
View Source File : WordTemplateFolderManager.cs
License : MIT License
Project Creator : alkampfergit
License : MIT License
Project Creator : alkampfergit
public string GetTable(string tableName, Boolean createTempVersion)
{
String baseFile = Path.Combine(_templateFolder, "Table" + tableName + ".docx");
if (!File.Exists(baseFile))
throw new ArgumentException($"There is no table file for table name {tableName}");
if (!createTempVersion)
return baseFile;
String tempFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".docx");
File.Copy(baseFile, tempFile);
return tempFile;
}
19
View Source File : WordTemplateFolderManager.cs
License : MIT License
Project Creator : alkampfergit
License : MIT License
Project Creator : alkampfergit
public String CopyFileInTempDirectory(String localFileName)
{
var tempFileName = Path.GetTempPath() + Guid.NewGuid() + Path.GetExtension(localFileName);
CopyFileToDestination(localFileName, tempFileName);
return tempFileName;
}
19
View Source File : Program.cs
License : MIT License
Project Creator : alkampfergit
License : MIT License
Project Creator : alkampfergit
private static void PerformTemplateExport(ConnectionManager connection)
{
var wordFolderManager = new WordTemplateFolderManager(options.TemplateFolder);
var executor = new TemplateExecutor(wordFolderManager);
//now we need to ask user parameter value
Dictionary<string, Object> parameters = new Dictionary<string, object>();
foreach (var commandLineParam in options.Parameters)
{
var splitted = commandLineParam.Split('=');
if (splitted.Length == 2)
{
Log.Debug("Found parameter {paramName} in command line with value {value}", splitted[0], splitted[1]);
parameters[splitted[0]] = splitted[1];
}
else
{
Log.Error("Command line parameter {param} is not in the form name=value", commandLineParam);
}
}
foreach (var parameterName in wordFolderManager.TemplateDefinition.ParameterSection.Parameters.Keys)
{
if (!parameters.ContainsKey(parameterName))
{
Console.Write($"Parameter {parameterName}:");
parameters[parameterName] = Console.ReadLine();
}
}
var tempFileName = Path.GetTempPath() + Guid.NewGuid().ToString();
var generatedName = executor.GenerateFile(tempFileName, connection, options.TeamProject, parameters);
System.Diagnostics.Process.Start(generatedName);
}
19
View Source File : WordManipulator.cs
License : MIT License
Project Creator : alkampfergit
License : MIT License
Project Creator : alkampfergit
public void InsertWorkItem(
WorkItem workItem,
String workItemTemplateFile,
Boolean insertPageBreak = true,
Dictionary<string, object> startingParameters = null)
{
//ok we need to open the template, give it a new name, perform subsreplacedution and finally append to the existing doreplacedent
var tempFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".docx");
File.Copy(workItemTemplateFile, tempFile, true);
startingParameters = startingParameters ?? new Dictionary<string, object>();
using (WordManipulator m = new WordManipulator(tempFile, false))
{
Dictionary<string, object> tokenList = workItem.CreateDictionaryFromWorkItem();
if (startingParameters != null)
{
foreach (var parameter in startingParameters)
{
tokenList[parameter.Key] = parameter.Value;
}
}
m.SubsreplaceduteTokens(tokenList);
}
AppendOtherWordFile(tempFile, insertPageBreak);
File.Delete(tempFile);
}
19
View Source File : WordManipulationTests.cs
License : MIT License
Project Creator : alkampfergit
License : MIT License
Project Creator : alkampfergit
private string CopyIntoTempFile(string testfileName)
{
var randomTestFileName = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".docx");
File.Copy(testfileName, randomTestFileName, true);
_generatedFileNames.Add(randomTestFileName);
return randomTestFileName;
}
19
View Source File : MainViewModel.cs
License : MIT License
Project Creator : alkampfergit
License : MIT License
Project Creator : alkampfergit
private void InnerExecuteDump()
{
foreach (var selectedTemplate in Templates.Where(t => t.IsSelected))
{
var fileName = Path.Combine(Path.GetTempPath(), selectedTemplate.TemplateName, Guid.NewGuid().ToString()) + ".txt";
if (selectedTemplate.IsScriptTemplate)
{
var executor = new TemplateExecutor(selectedTemplate.WordTemplateFolderManager);
//now we need to ask user parameter value
Dictionary<string, object> parameters = PrepareUserParameters();
executor.DumpWorkItem(fileName, ConnectionManager.Instance, SelectedTeamProject.Name, parameters);
}
else
{
var selected = SelectedQuery?.Results?.Where(q => q.Selected).ToList();
if (selected == null || selected.Count == 0)
{
return;
}
var sb = new StringBuilder();
foreach (var workItemResult in selected)
{
var workItem = workItemResult.WorkItem;
var values = workItem.CreateDictionaryFromWorkItem();
foreach (var value in values)
{
sb.AppendLine($"{value.Key.PadRight(50, ' ')}={value.Value}");
}
File.WriteAllText(fileName, sb.ToString());
}
}
System.Diagnostics.Process.Start(fileName);
}
}
19
View Source File : Settings.xaml.cs
License : MIT License
Project Creator : Alkl58
License : MIT License
Project Creator : Alkl58
private void ButtonOpenTempFolder_Click(object sender, RoutedEventArgs e)
{
// Opens the Temp Folder
if (ToggleSwitchTempFolder.IsOn == false)
{
//Creates the temp directoy if not existent
if (Directory.Exists(Path.Combine(Path.GetTempPath(), "NEAV1E")) == false) { Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "NEAV1E")); }
Process.Start(Path.Combine(Path.GetTempPath(), "NEAV1E"));
}
else
{
Process.Start(TextBoxCustomTempPath.Text);
}
}
19
View Source File : FileSystemResultsWriterTests.cs
License : Apache License 2.0
Project Creator : allure-framework
License : Apache License 2.0
Project Creator : allure-framework
[Test, Description("Should use temp path if no access to output directory")]
public void ShouldUseTempPathIfNoAccessToResultsDirectory()
{
var config = AllureConfiguration.ReadFromJObject(JObject.Parse(@"{allure:{}}"));
var expectedDir = Path.Combine(Path.GetTempPath(), AllureConstants.DEFAULT_RESULTS_FOLDER);
var moq = new Mock<FileSystemResultsWriter>(config) { CallBase = true };
moq.Setup(x => x.HasDirectoryAccess(It.IsAny<string>())).Returns(false);
replacedert.AreEqual(expectedDir, moq.Object.ToString());
}
19
View Source File : FileSystemResultsWriterTests.cs
License : Apache License 2.0
Project Creator : allure-framework
License : Apache License 2.0
Project Creator : allure-framework
[Test, Description("Cleanup test")]
public void ShouldCleanupTempResultsFolder()
{
var resultsDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
var json = $"{{\"allure\":{{\"directory\": {JsonConvert.ToString(resultsDirectory)}}}}}";
var config = AllureConfiguration.ReadFromJObject(JObject.Parse(json));
Directory.CreateDirectory(resultsDirectory);
File.WriteAllText(Path.Combine(resultsDirectory, Path.GetRandomFileName()), "");
new FileSystemResultsWriter(config).CleanUp();
replacedert.IsEmpty(Directory.GetFiles(resultsDirectory));
}
19
View Source File : InstantiationTests.cs
License : Apache License 2.0
Project Creator : allure-framework
License : Apache License 2.0
Project Creator : allure-framework
[Test]
public void ShouldThrowIfEnvVariableConfigNotFound()
{
var tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
Directory.CreateDirectory(tempDirectory);
Environment.SetEnvironmentVariable(AllureConstants.ALLURE_CONFIG_ENV_VARIABLE,
Path.Combine(tempDirectory, AllureConstants.CONFIG_FILENAME));
replacedert.Throws<FileNotFoundException>(() => { new AllureLifecycle(); });
}
19
View Source File : InstantiationTests.cs
License : Apache License 2.0
Project Creator : allure-framework
License : Apache License 2.0
Project Creator : allure-framework
[Test]
public void ShouldReadConfigFromEnvironmentVariable()
{
var configuration = @"{""allure"":{""directory"": ""env""}}";
var tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
Directory.CreateDirectory(tempDirectory);
var configFile = Path.Combine(tempDirectory, AllureConstants.CONFIG_FILENAME);
File.WriteAllText(configFile, configuration);
Environment.SetEnvironmentVariable(AllureConstants.ALLURE_CONFIG_ENV_VARIABLE, configFile);
replacedert.AreEqual("env", new AllureLifecycle().AllureConfiguration.Directory);
}
See More Examples