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
19
Source : RedisAttributeTests.cs
with MIT License
from daulet
with MIT License
from daulet
[Fact]
public async Task Redis_GetStringValue_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/string/{key}");
// replacedert
var actualValue = await response.Content.ReadreplacedtringAsync();
replacedert.Equal(value, actualValue);
}
19
Source : RedisAttributeTests.cs
with MIT License
from daulet
with MIT License
from daulet
[Fact]
public async Task Redis_SetStringValue_ValueSetInRedis()
{
// Arrange
var key = Path.GetRandomFileName();
var value = Path.GetRandomFileName();
// Act
var response =
await httpClient.PostAsync($"http://localhost:7075/test/string/{key}", new StringContent(value));
// replacedert
var database = await _database.Value;
var actualValue = await database.StringGetAsync(key);
replacedert.Equal(value, actualValue);
}
19
Source : RedisAttributeTests.cs
with MIT License
from daulet
with MIT License
from daulet
[Fact]
public async Task Redis_GetPocoValue_ValueReadFromRedis()
{
// Arrange
var key = Path.GetRandomFileName();
var expectedObject = new CustomObject()
{
IntegerProperty = new Random().Next(),
StringProperty = Path.GetRandomFileName(),
};
var database = await _database.Value;
await database.StringSetAsync(key, JsonConvert.SerializeObject(expectedObject));
// Act
var response = await httpClient.GetAsync($"http://localhost:7075/test/poco/{key}");
var content = await response.Content.ReadreplacedtringAsync();
// replacedert
var actualObject = JsonConvert.DeserializeObject<CustomObject>(content);
replacedert.Equal(expectedObject.IntegerProperty, actualObject.IntegerProperty);
replacedert.Equal(expectedObject.StringProperty, actualObject.StringProperty);
}
19
Source : RedisAttributeTests.cs
with MIT License
from daulet
with MIT License
from daulet
[Fact]
public async Task Redis_InvalidPocoStored_NullFetched()
{
// Arrange
var key = Path.GetRandomFileName();
var database = await _database.Value;
await database.StringSetAsync(key, Path.GetRandomFileName());
// Act
var response = await httpClient.GetAsync($"http://localhost:7075/test/poco/{key}");
var content = await response.Content.ReadreplacedtringAsync();
// replacedert
var actualObject = JsonConvert.DeserializeObject<CustomObject>(content);
replacedert.Null(actualObject);
}
19
Source : RedisAttributeTests.cs
with MIT License
from daulet
with MIT License
from daulet
[Fact]
public async Task Redis_SetPocoValue_ValueReadFromRedis()
{
// Arrange
var key = Path.GetRandomFileName();
var expectedObject = new CustomObject()
{
IntegerProperty = new Random().Next(),
StringProperty = Path.GetRandomFileName(),
};
// Act
var response = await httpClient.PostAsync($"http://localhost:7075/test/poco/{key}",
new StringContent(JsonConvert.SerializeObject(expectedObject)));
var content = await response.Content.ReadreplacedtringAsync();
// replacedert
var database = await _database.Value;
var actualValue = await database.StringGetAsync(key);
var actualObject = JsonConvert.DeserializeObject<CustomObject>(content);
replacedert.Equal(expectedObject.IntegerProperty, actualObject.IntegerProperty);
replacedert.Equal(expectedObject.StringProperty, actualObject.StringProperty);
}
19
Source : HashedHashedContentStore.cs
with GNU General Public License v3.0
from deccer
with GNU General Public License v3.0
from deccer
public async Task<ContentHash> WriteAsync(Stream stream, CancellationToken cancellationToken = new CancellationToken(), IEnumerable<IContentEncoding> encodings = null)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
// Create a new, empty temporary file
// We will write the source content into this file, whilst computing the content's hash
// Once we have the hash, we can move this temp file into the correct location
var tempFile = Path.GetRandomFileName();
// Create a SHA-1 hash builder
using var hashBuilder = IncrementalHash.CreateHash(HashAlgorithmName.SHA1);
// Open the temp file for write
await using (var fileStream = new FileStream(tempFile,
FileMode.Open, FileAccess.Write, FileShare.None,
BufferSize, FileOptions.SequentialScan | FileOptions.Asynchronous))
{
// Allocate a buffer, used to process data in chunks
// We use parallel read/write for increased throughput which requires two buffers
var buffers = new[] { new byte[BufferSize], new byte[BufferSize] };
var bufferIndex = 0;
var writeTask = (Task)null;
// Loop until the source stream is exhausted
while (true)
{
// Swap buffers
bufferIndex ^= 1;
// Start read a chunk of data into the buffer asynchronously
var readTask = stream.ReadAsync(buffers[bufferIndex], 0, BufferSize, cancellationToken);
if (writeTask != null)
{
await Task.WhenAll(readTask, writeTask);
}
var readCount = readTask.Result;
// If the stream has ended, break
if (readCount == 0)
{
break;
}
// Integrate the source data chunk into the hash
hashBuilder.AppendData(buffers[bufferIndex], 0, readCount);
// Write the source data chunk to the output file
writeTask = fileStream.WriteAsync(buffers[bufferIndex], 0, readCount, cancellationToken);
}
}
// Retrieve the computed hash
var hash = ContentHash.FromBytes(hashBuilder.GetHashAndReset());
// Determine the location for the content file
GetPaths(hash, null, out string subPath, out string contentPath);
// We might need to lock some file system operations
_fileSystemLock.EnterUpgradeableReadLock();
try
{
// Test whether a file already exists for this hash
if (File.Exists(contentPath))
{
// This content already exists in the store
// Delete the temporary file
// NOTE a write lock is not needed here
File.Delete(tempFile);
}
else
{
// We're about to start changing the file system, so take a write lock
_fileSystemLock.EnterWriteLock();
try
{
// Ensure the sub-path exists
if (!Directory.Exists(subPath))
{
Directory.CreateDirectory(subPath);
}
// Move the temporary file into its correct location
File.Move(tempFile, contentPath);
// Set the read-only flag on the file
File.SetAttributes(contentPath, FileAttributes.ReadOnly);
}
finally
{
_fileSystemLock.ExitWriteLock();
}
}
}
finally
{
_fileSystemLock.ExitUpgradeableReadLock();
}
// Write any encoded forms of the content too
if (encodings != null)
{
foreach (var encoding in encodings)
{
var encodedContentPath = contentPath + "." + encoding.Name;
if (File.Exists(encodedContentPath))
{
continue;
}
// Create a new temporary file for the encoded content
tempFile = Path.GetRandomFileName();
await using (var inputStream = new FileStream(contentPath, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, FileOptions.SequentialScan | FileOptions.Asynchronous))
{
await using (var outputStream = new FileStream(tempFile, FileMode.Open, FileAccess.Write, FileShare.None, BufferSize, FileOptions.SequentialScan | FileOptions.Asynchronous))
{
await using (var encodedOutputStream = encoding.Encode(outputStream))
{
await inputStream.CopyToAsync(encodedOutputStream, BufferSize, cancellationToken);
}
}
}
// Move the temporary file into its correct location
File.Move(tempFile, encodedContentPath);
// Set the read-only flag on the file
File.SetAttributes(encodedContentPath, FileAttributes.ReadOnly);
}
}
// The caller receives the hash, regardless of whether the
// file previously existed in the store
return hash;
}
19
Source : FileSystem.cs
with GNU General Public License v3.0
from Decimation
with GNU General Public License v3.0
from Decimation
public static string CreateRandomName() => Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
19
Source : DirectoryHelper.cs
with GNU General Public License v3.0
from DeepHydro
with GNU General Public License v3.0
from DeepHydro
public static string GetUniqueString()
{
//Guid g = Guid.NewGuid();
//string GuidString = Convert.ToBase64String(g.ToByteArray());
//GuidString = GuidString.Replace("=", "");
//GuidString = GuidString.Replace("+", "");
// return GuidString;
var str = Path.GetRandomFileName();
str = str.Replace(".", "x");
return str;
}
19
Source : UploadingFiles.cs
with Apache License 2.0
from DevExpress
with Apache License 2.0
from DevExpress
private void uploadControl_FilesUploadSavingTemporaryFilesComplete(object sender, FilesUploadCompleteEventArgs e) {
var uploadedFiles = ((MVCxUploadControl)sender).UploadedFiles;
if(uploadedFiles != null && uploadedFiles.Length > 0) {
for(int i = 0; i < uploadedFiles.Length; i++) {
UploadedFile file = uploadedFiles[i];
if(file.IsValid && file.FileName != "") {
string fileName = string.Format("{0}{1}", HostingEnvironment.MapPath("~/Upload/Processing/"),
Path.GetRandomFileName() + ".tmp");
file.SaveAs(fileName, true);
// DoFileProcessing(fileName);
}
}
}
}
19
Source : UploadControlTempFileName.aspx.cs
with Apache License 2.0
from DevExpress
with Apache License 2.0
from DevExpress
protected void uploadControl_FilesUploadComplete(object sender, DevExpress.Web.FilesUploadCompleteEventArgs e) {
if(uploadControl.UploadedFiles != null && uploadControl.UploadedFiles.Length > 0) {
for(int i = 0; i < uploadControl.UploadedFiles.Length; i++) {
UploadedFile file = uploadControl.UploadedFiles[i];
if(file.IsValid) {
string fileName = string.Format("{0}{1}", MapPath("~/UploadingFiles/Processing/"),
Path.GetRandomFileName() + ".tmp");
file.SaveAs(fileName, true);
// DoFileProcessing(fileName);
}
}
}
}
19
Source : AddCommand.cs
with MIT License
from devlooped
with MIT License
from devlooped
public override async Task<int> ExecuteAsync()
{
var http = HttpClientFactory.Create();
var result = 0;
if (Files.Count == 0)
return 0;
var length = Files.Select(x => x.Path).Max(x => x.Length) + 1;
void Write(string s) => Console.Write(s + new string(' ', length - s.Length));
var processed = new Dictionary<(string, Uri), object?>();
// TODO: allow configuration to provide HTTP headers, i.e. auth?
foreach (var file in Files)
{
var section = Configuration.GetSection("file", file.Path);
if (section.GetBoolean("skip") == true)
continue;
if (File.Exists(file.Path) && File.GetAttributes(file.Path).HasFlag(FileAttributes.ReadOnly))
{
Write(file.Path);
Console.WriteLine("? Readonly, skipping");
continue;
}
var uri = file.Uri;
if (uri == null)
{
var url = section.GetString("url");
if (url != null)
{
uri = new Uri(url);
}
else
{
Write(file.Path);
Console.WriteLine("x Unconfigured");
continue;
}
}
if (processed.ContainsKey((file.Path, uri)))
continue;
var etag = file.ETag ?? section.GetString("etag");
var weak = section.GetBoolean("weak");
var sha = section.GetString("sha");
var originalUri = uri;
try
{
processed.Add((file.Path, uri), null);
var request = new HttpRequestMessage(DryRun ? HttpMethod.Head : HttpMethod.Get, uri);
// Propagate previous values, used in GitHubRawHandler to optimize SHA retrieval
if (etag != null)
request.Headers.TryAddWithoutValidation("X-ETag", etag);
if (sha != null)
request.Headers.TryAddWithoutValidation("X-Sha", sha);
if (etag != null && File.Exists(file.Path))
{
// Try HEAD and skip file if same etag
var headReq = new HttpRequestMessage(HttpMethod.Head, uri);
// Propagate previous values, used in GitHubRawHandler to optimize SHA retrieval
if (etag != null)
headReq.Headers.TryAddWithoutValidation("X-ETag", etag);
if (sha != null)
headReq.Headers.TryAddWithoutValidation("X-Sha", sha);
var headResp = await http.SendAsync(headReq);
if (headResp.IsSuccessStatusCode &&
headResp.Headers.ETag?.Tag?.Trim('"') == etag)
{
// To keep "noise" from unchanged files to a minimum, when
// doing a dry run we only list actual changes.
if (!DryRun)
{
// No need to download
Write(file.Path);
ColorConsole.Write("=".DarkGray());
Console.WriteLine($" <- {originalUri}");
// For backs compat, set the sha if found and not already present.
if (sha == null &&
headResp.Headers.TryGetValues("X-Sha", out var headShas) &&
headShas.FirstOrDefault() is string headSha &&
!string.IsNullOrEmpty(headSha))
section.SetString("sha", headSha);
}
continue;
}
// NOTE: this code alone didn't work consistently:
// For some reason, GH would still give us the full response,
// even with a different etag from the previous request.
request.Headers.IfNoneMatch.Add(new EnreplacedyTagHeaderValue("\"" + etag + "\"", weak.GetValueOrDefault()));
}
Write(file.Path);
var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
if (response.Headers.TryGetValues("X-Sha", out var values) &&
values.FirstOrDefault() is string newSha &&
!string.IsNullOrEmpty(newSha))
file.NewSha = newSha;
else
file.NewSha = null;
if (response.StatusCode == HttpStatusCode.NotModified)
{
// No need to download
ColorConsole.Write("=".DarkGray());
Console.WriteLine($" <- {originalUri}");
// For backs compat, set the sha if found and not already present.
if (section.GetString("sha") == null &&
file.NewSha != null)
section.SetString("sha", file.NewSha);
continue;
}
if (!response.IsSuccessStatusCode)
{
if (uri.Host.Equals("github.com") && !GitHub.TryIsInstalled(out var output))
{
ColorConsole.WriteLine("=> ", "the GitHub CLI is required for this URL".Red());
ColorConsole.WriteLine(output.Yellow());
ColorConsole.WriteLine("See https://cli.github.com/manual/installation".Yellow());
System.Diagnostics.Process.Start(new ProcessStartInfo("https://cli.github.com/manual/installation") { UseShellExecute = true });
return -1;
}
// The URL might be a directory or repo branch top-level path. If so, we can use the GitHub cli to fetch all files.
if (uri.Host.Equals("github.com") &&
(response.StatusCode == HttpStatusCode.NotFound ||
// BadRequest from our conversion to raw URLs in GitHubRawHandler
response.StatusCode == HttpStatusCode.BadRequest))
{
var gh = GitHub.TryGetFiles(file, out var repoFiles);
switch (gh)
{
case GitHubResult.Success:
var targetDir = file.IsDefaultPath ? null : file.Path;
// Store the URL for later updates
if (!Configuration.GetAll("file", targetDir, "url").Any(entry => uri.ToString().Equals(entry.RawValue, StringComparison.OrdinalIgnoreCase)))
Configuration.AddString("file", targetDir, "url", uri.ToString());
// Run again with the fetched files.
var command = Clone();
command.Files.AddRange(repoFiles);
Console.WriteLine();
// Track all files as already processed to skip duplicate processing from
// existing expanded list.
foreach (var repoFile in repoFiles)
processed.Add((repoFile.Path, repoFile.Uri!), null);
result = await command.ExecuteAsync();
foreach (var change in command.Changes)
Changes.Add(change);
continue;
case GitHubResult.Failure:
return -1;
case GitHubResult.Skip:
break;
default:
break;
}
}
ColorConsole.WriteLine($"x <- {originalUri}".Yellow());
if (response.StatusCode != HttpStatusCode.NotFound ||
!OnRemoteUrlMissing(file))
{
// Only show as error if we haven't deleted the file as part of a
// sync operation, or if the error is not 404.
ColorConsole.WriteLine(new string(' ', length + 5), $"{(int)response.StatusCode}: {response.ReasonPhrase}".Red());
}
continue;
}
if (!DryRun)
{
etag = response.Headers.ETag?.Tag?.Trim('"');
var path = file.Path.IndexOf(Path.AltDirectorySeparatorChar) != -1
? file.Path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar)
: file.Path;
// Ensure target directory exists.
if (Path.GetDirectoryName(path)?.Length > 0)
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
var tempPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
try
{
using var stream = File.Open(tempPath, FileMode.Create);
await response.Content.CopyToAsync(stream);
}
catch (Exception) // Delete temp file on error
{
File.Delete(tempPath);
throw;
}
#if NETCOREAPP2_1
if (File.Exists(path))
File.Delete(path);
File.Move(tempPath, path);
#else
File.Move(tempPath, path, overwrite: true);
#endif
section.SetString("url", originalUri.ToString());
if (file.NewSha != null)
section.SetString("sha", file.NewSha);
else
section.Unset("sha");
if (etag == null)
section.Unset("etag");
else
section.SetString("etag", etag);
if (response.Headers.ETag?.IsWeak == true)
section.SetBoolean("weak", true);
else
section.Unset("weak");
}
Changes.Add(file);
ColorConsole.Write("✓".Green());
Console.WriteLine($" <- {originalUri}");
}
catch (Exception e)
{
ColorConsole.WriteLine($"x <- {originalUri}".Yellow());
Console.Write(new string(' ', length + 5));
ColorConsole.WriteLine(e.Message.Red());
result = 1;
}
}
return result;
}
19
Source : DataSetGenWindow.Presenter.cs
with MIT License
from DevZest
with MIT License
from DevZest
private async Task<int> RunAsync(IProgress<string> progress, CancellationToken ct)
{
var project = _dbSessionProvider.Value.Project;
var dbSessionProvider = _dbSessionProvider.Value.TypeSymbol;
var input = dbSessionProvider.GetDbInitInput(_codeContext.Compilation);
var showLog = _showDbLog.Value;
var tableNames = new string[DataSet.Count];
for (int i = 0; i < DataSet.Count; i++)
tableNames[i] = _.DbTableProperty[i].Name;
var outputDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
Directory.CreateDirectory(outputDir);
var runner = DbInitProjectRunner.CreateDataSetGen(project, dbSessionProvider, input, _showDbLog.Value, tableNames, outputDir, _dte);
var result = await runner.RunAsync(progress, ct);
if (result != ExitCodes.Succeeded)
{
DeleteDirectoryIfExists(outputDir);
return result;
}
for (int i = 0; i < DataSet.Count; i++)
{
var dbTable = _.DbTableProperty[i].Name;
_.ReferencedTypes[i] = File.ReadAllText(Path.Combine(outputDir, dbTable + ".types"));
_.DataSetMethodBody[i] = File.ReadAllText(Path.Combine(outputDir, dbTable + ".statements"));
}
DeleteDirectoryIfExists(outputDir);
var doreplacedent = await DbInitMapper.GenerateDataSetsAsync(_codeContext, DataSet, ct);
var workspace = project.Solution.Workspace;
workspace.TryApplyChanges(doreplacedent.Project.Solution);
return ExitCodes.Succeeded;
}
19
Source : FileServiceTests.cs
with MIT License
from DistechControls
with MIT License
from DistechControls
private BlobInfo GetFakeBlobInfo(string containerName, string deviceName, DateTimeOffset lastModified)
{
return new FakeBlobInfo($"/{containerName}/{deviceName}/RestApi/{System.IO.Path.GetRandomFileName()}", lastModified);
}
19
Source : SyntaxTreeHelper.cs
with Apache License 2.0
from donet5
with Apache License 2.0
from donet5
public static Type GetModelTypeByClreplaced(string clreplacedString, string typeName)
{
//Write("Parsing the code into the SyntaxTree");
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(clreplacedString);
string replacedemblyName = Path.GetRandomFileName();
var refPaths = new[] {
//typeof(AccessViolationException).replacedembly.Location,
typeof(System.Object).GetTypeInfo().replacedembly.Location,
typeof(Console).GetTypeInfo().replacedembly.Location,
Path.Combine(Path.GetDirectoryName(typeof(System.Runtime.GCSettings).GetTypeInfo().replacedembly.Location), "System.Runtime.dll"),
typeof(SqlSugar.SqlSugarClient).replacedembly.Location
};
MetadataReference[] references = refPaths.Select(r => MetadataReference.CreateFromFile(r)).ToArray();
//Write("Adding the following references");
//foreach (var r in refPaths)
// Write(r);
//Write("Compiling ...");
CSharpCompilation compilation = CSharpCompilation.Create(
replacedemblyName,
syntaxTrees: new[] { syntaxTree },
references: references,
options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
using (var ms = new MemoryStream())
{
EmitResult result = compilation.Emit(ms);
if (!result.Success)
{
//Write("Compilation failed!");
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error);
string message = "";
foreach (Diagnostic diagnostic in failures)
{
message += diagnostic.GetMessage();
}
throw new Exception("解析实体类出错,请检查命名" + message +" \r\n "+clreplacedString);
}
else
{
//Write("Compilation successful! Now instantiating and executing the code ...");
ms.Seek(0, SeekOrigin.Begin);
replacedembly replacedembly = replacedemblyLoadContext.Default.LoadFromStream(ms);
var type = replacedembly.GetType("RoslynCompileSampleDemo." + typeName);
//Console.WriteLine(type.Name);
return type;
}
}
}
19
Source : MainWindow.xaml.cs
with MIT License
from dotnet-campus
with MIT License
from dotnet-campus
private void ContainerGrid_OnDrop(object sender, DragEventArgs e)
{
try
{
var fileNames = e.Data.GetData(DataFormats.FileDrop, true) as string[];
if (fileNames == null || !fileNames.Any()) return;
var svgs = fileNames.Where(x => Path.GetExtension(x) == ".svg").ToArray();
if (!svgs.Any()) return;
var sb = new StringBuilder();
foreach (var svg in svgs)
{
var svgFileName = Path.GetFileNameWithoutExtension(svg);
Drawing drawing = _fileSvgReader.GetDrawingGroup(svg);
//去掉冗余的层次
while (drawing is DrawingGroup drawingGroup && (drawingGroup.Children.Count == 1))
{
var dr = drawingGroup.Children[0];
if (dr != null)
{
if (drawingGroup.Transform != null)
{
if (dr is DrawingGroup @group)
{
@group.Transform = drawingGroup.Transform;
}
else if (dr is GeometryDrawing geometryDrawing)
{
geometryDrawing.Geometry.Transform = drawingGroup.Transform;
}
}
drawing = dr;
}
else
{
break;
}
}
var drawingImage = new DrawingImage(drawing);
if (drawing is GeometryDrawing geometryDrawing1)
{
if (geometryDrawing1.Geometry is PathGeometry geo)
{
var pathGeometry = new PathGeometry();
foreach (var figure in geo.Figures)
{
pathGeometry.Figures.Add(figure);
}
var combineGeometry = Geometry.Combine(Geometry.Empty, pathGeometry,
GeometryCombineMode.Union, geometryDrawing1.Geometry.Transform);
geometryDrawing1.Geometry = combineGeometry;
drawing = geometryDrawing1;
}
}
var xaml = GetXaml(drawingImage);
var bounds = drawing.Bounds;
var image = new Image
{
Source = drawingImage,
Width = bounds.Width,
Height = bounds.Height,
ToolTip = $"{drawing.Bounds.Width},{drawing.Bounds.Height}",
SnapsToDevicePixels = true,
UseLayoutRounding = true,
Stretch = Stretch.None,
};
IconsContainer.Children.Add(image);
HintText.Text = string.Empty;
sb.Append(xaml);
sb.Append(Environment.NewLine);
sb.Append(Environment.NewLine);
sb.Replace("<DrawingImage xmlns", $"<DrawingImage x:Key=\"{svgFileName}\" xmlns");
}
//替换掉不需要的字符串
sb.Replace(" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"", string.Empty);
sb.Replace(" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"", string.Empty);
sb.Replace(" xmlns:svg=\"http://sharpvectors.codeplex.com/runtime/\"", string.Empty);
sb.Replace(" Pen=\"{x:Null}\"", string.Empty);
var result = sb.ToString();
result = Regex.Replace(result, " svg:SvgLink.Key=\".*\"", string.Empty);
result = Regex.Replace(result, " svg:SvgObject.Id=\".*\"", string.Empty);
result = Regex.Replace(result, "<PathGeometry FillRule=\"EvenOdd\" Figures=\"([^T]*?)\" />",
"<StreamGeometry>$1</StreamGeometry>");
var tempXamlFile = Path.Combine(Path.GetTempPath(), $"{Path.GetRandomFileName()}.xaml");
WriteToFile(result, tempXamlFile);
TryOpenXamlFile(tempXamlFile);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
19
Source : DirectoryUtility.cs
with MIT License
from dotnet-toolbelt
with MIT License
from dotnet-toolbelt
public static string GetTempDirectory()
{
return Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
}
19
Source : RealmHelper.cs
with MIT License
from DotNetRu
with MIT License
from DotNetRu
internal static async Task<Realm> GetRealm(this User user, Uri realmUrl)
{
var tempRealmFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
var syncConfiguration = new FullSyncConfiguration(realmUrl, user, tempRealmFile);
return await Realm.GetInstanceAsync(syncConfiguration);
}
19
Source : TempFileManager.cs
with GNU General Public License v3.0
from dtube
with GNU General Public License v3.0
from dtube
public static string GetNewTempFilePath()
{
return Path.Combine(GetTempDirectory(), Path.GetRandomFileName());
}
19
Source : LinkController.cs
with MIT License
from ecampidoglio
with MIT License
from ecampidoglio
[HttpPost]
public IActionResult Create(string url)
{
return Create(UniqueId(), url);
string UniqueId()
=> Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
}
19
Source : Files.cs
with GNU General Public License v3.0
from EEVblog
with GNU General Public License v3.0
from EEVblog
public static string UniqueFilename()
{
string output = "";
while (File.Exists(output = Path.GetRandomFileName())) ;
return output;
}
19
Source : FilesaveController.cs
with GNU General Public License v3.0
from efonsecab
with GNU General Public License v3.0
from efonsecab
[HttpPost("[action]")]
[Authorize(Roles = Common.Global.Constants.Roles.User)]
[DisableRequestSizeLimit]
//[RequestSizeLimit(1073741824)] //1GB
[RequestFormLimits(ValueLengthLimit = int.MaxValue, MultipartBodyLengthLimit = int.MaxValue)]
public async Task<ActionResult<IList<UploadResult>>> PostFile(
[FromForm] IEnumerable<IFormFile> files, CancellationToken cancellationToken)
{
//TODO: Disabling request limits it is not recommended. We'll use it as a temporary measure, but needs to be changed
var userAzueAdB2cObjectId = this.CurrentUserProvider.GetObjectId();
var maxAllowedFiles = 3;
long maxFileSize = Common.Global.Constants.UploadLimits.MaxBytesAllowed;
var filesProcessed = 0;
var resourcePath = new Uri($"{Request.Scheme}://{Request.Host}/");
List<UploadResult> uploadResults = new();
foreach (var file in files)
{
var uploadResult = new UploadResult();
string trustedFileNameForFileStorage;
var untrustedFileName = file.FileName;
uploadResult.FileName = untrustedFileName;
var trustedFileNameForDisplay =
WebUtility.HtmlEncode(untrustedFileName);
if (filesProcessed < maxAllowedFiles)
{
if (file.Length == 0)
{
logger.LogInformation("{FileName} length is 0 (Err: 1)",
trustedFileNameForDisplay);
uploadResult.ErrorCode = 1;
}
else if (file.Length > maxFileSize)
{
logger.LogInformation("{FileName} of {Length} bytes is " +
"larger than the limit of {Limit} bytes (Err: 2)",
trustedFileNameForDisplay, file.Length, maxFileSize);
uploadResult.ErrorCode = 2;
}
else
{
try
{
var fileExtension = Path.GetExtension(file.FileName);
trustedFileNameForFileStorage = $"{Path.GetRandomFileName()}{fileExtension}";
string fileRelativePath = $"User/{userAzueAdB2cObjectId}/{trustedFileNameForFileStorage}";
var blobUploadResult = await this.AzureBlobStorageService.UploadFileAsync(
this.DataStorageConfiguration.UntrustedUploadsContainerName, fileRelativePath,
file.OpenReadStream(), true, cancellationToken);
logger.LogInformation("{FileName} saved at {Path}",
trustedFileNameForDisplay, fileRelativePath);
uploadResult.Uploaded = true;
uploadResult.StoredFileName = trustedFileNameForFileStorage;
}
catch (IOException ex)
{
logger.LogError("{FileName} error on upload (Err: 3): {Message}",
trustedFileNameForDisplay, ex.Message);
uploadResult.ErrorCode = 3;
throw;
}
}
filesProcessed++;
}
else
{
logger.LogInformation("{FileName} not uploaded because the " +
"request exceeded the allowed {Count} of files (Err: 4)",
trustedFileNameForDisplay, maxAllowedFiles);
uploadResult.ErrorCode = 4;
}
uploadResults.Add(uploadResult);
}
return new CreatedResult(resourcePath, uploadResults);
}
19
Source : Utilities.cs
with BSD 3-Clause "New" or "Revised" License
from eksperience
with BSD 3-Clause "New" or "Revised" License
from eksperience
public static string GenerateExportPath(string majorVersion)
{
string fileName = Path.GetRandomFileName();
RegistryKey outlookSecurity = Registry.CurrentUser.OpenSubKey(string.Format(@"SOFTWARE\Microsoft\Office\{0}\Outlook\Security", majorVersion));
if (outlookSecurity != null)
{
object value = outlookSecurity.GetValue("OutlookSecureTempFolder");
if (value != null)
{
return value.ToString() + fileName;
}
}
return string.Format(@"{0}\Temp\{1}", Environment.GetEnvironmentVariable("LOCALAPPDATA"), fileName);
}
19
Source : ImageDataObject.cs
with MIT License
from Elem8100
with MIT License
from Elem8100
private void PrepareImageFile()
{
string fileName = this.FileName;
string tempDir = new DirectoryInfo(Environment.GetEnvironmentVariable("TEMP")).FullName;
bool willSaveImage = false;
if (string.IsNullOrEmpty(fileName))
{
fileName = Path.Combine(tempDir, Path.GetRandomFileName());
willSaveImage = true;
}
else
{
if (string.IsNullOrEmpty(Path.GetDirectoryName(fileName)))//没有文件夹 保存文件
{
fileName = Path.Combine(tempDir, fileName);
if (File.Exists(fileName))
{
string fileNameNoExt = Path.GetFileNameWithoutExtension(fileName);
string ext = Path.GetExtension(fileName);
for (int i = 1; ; i++)
{
fileName = Path.Combine(tempDir, string.Format("{0}({1}){2}", fileNameNoExt, i, ext));
if (!File.Exists(fileName))
{
break;
}
}
}
willSaveImage = true;
}
}
if (willSaveImage)
{
Image.Save(fileName, Image.RawFormat);
this.FileName = fileName;
}
}
19
Source : WzPatcher.cs
with MIT License
from Elem8100
with MIT License
from Elem8100
private string CreateRandomDir(string folder)
{
string randomDir = null;
do
{
randomDir = Path.Combine(folder, Path.GetRandomFileName());
}
while (Directory.Exists(randomDir));
Directory.CreateDirectory(randomDir);
return randomDir;
}
19
Source : Functions.cs
with GNU General Public License v3.0
from ElevenPaths
with GNU General Public License v3.0
from ElevenPaths
public static string GetNotExistsPath(string strPath)
{
if (Path.GetFileName(strPath) == string.Empty)
strPath = Path.GetDirectoryName(strPath) + "\\tempfile";
if (!File.Exists(strPath) && IsValidFilename(strPath))
return strPath;
string strDirectory, strFilename;
var strExt = Path.GetExtension(strPath);
try
{
strDirectory = Path.GetDirectoryName(strPath);
strFilename = Path.GetFileName(strPath);
}
catch (PathTooLongException)
{
strDirectory = strPath.Remove(strPath.LastIndexOf('\\'));
var strRandomPath = Path.GetRandomFileName();
strFilename = strRandomPath + strExt;
strPath = strDirectory + "\\" + strFilename;
}
for (var i = 1; File.Exists(strPath); i++)
{
strPath = strDirectory + "\\" + Path.GetFileNameWithoutExtension(strFilename) + " (" + i + ")" + strExt;
}
return strPath;
}
19
Source : ElementLocation_Tests.cs
with MIT License
from enricosada
with MIT License
from enricosada
[Fact]
public void TestLargeElementLocationUsedLargeColumn()
{
string file = null;
try
{
file = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
File.WriteAllText(file, ObjectModelHelpers.CleanupFileContents("<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>\r\n<ItemGroup>") + new string(' ', 70000) + @"<x/></ItemGroup></Project>");
ProjectRootElement projectXml = ProjectRootElement.Open(file);
}
catch (InvalidProjectFileException ex)
{
replacedert.Equal(70012, ex.ColumnNumber);
replacedert.Equal(2, ex.LineNumber);
}
finally
{
File.Delete(file);
}
}
19
Source : ElementLocation_Tests.cs
with MIT License
from enricosada
with MIT License
from enricosada
[Fact]
public void TestLargeElementLocationUsedLargeLine()
{
string file = null;
try
{
string longstring = String.Empty;
for (int i = 0; i < 7000; i++)
{
longstring += "\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n";
}
file = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
File.WriteAllText(file, ObjectModelHelpers.CleanupFileContents("<Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'>\r\n<ItemGroup>") + longstring + @" <x/></ItemGroup></Project>");
ProjectRootElement projectXml = ProjectRootElement.Open(file);
}
catch (InvalidProjectFileException ex)
{
replacedert.Equal(70002, ex.LineNumber);
replacedert.Equal(2, ex.ColumnNumber);
}
finally
{
File.Delete(file);
}
}
19
Source : ResolveCodeAnalysisRuleSet_Tests.cs
with MIT License
from enricosada
with MIT License
from enricosada
[Fact]
[Trait("Category", "netcore-osx-failing")]
[Trait("Category", "netcore-linux-failing")]
public void GetResolvedRuleSetPath_SimpleNameAndProjectDirectory_NonExistent()
{
MockEngine mockEngine = new MockEngine();
ResolveCodereplacedysisRuleSet task = new ResolveCodereplacedysisRuleSet();
task.BuildEngine = mockEngine;
string projectDirectory = Path.GetTempPath();
string codereplacedysisRuleSet = Path.GetRandomFileName() + ".ruleset";
task.CodereplacedysisRuleSet = codereplacedysisRuleSet;
task.MSBuildProjectDirectory = projectDirectory;
task.CodereplacedysisRuleSetDirectories = null;
bool result = task.Execute();
string resolvedRuleSet = task.ResolvedCodereplacedysisRuleSet;
replacedert.Equal(expected: true, actual: result);
replacedert.Equal(expected: null, actual: resolvedRuleSet);
mockEngine.replacedertLogContains("MSB3884");
}
19
Source : ResolveCodeAnalysisRuleSet_Tests.cs
with MIT License
from enricosada
with MIT License
from enricosada
[Fact]
[Trait("Category", "netcore-osx-failing")]
[Trait("Category", "netcore-linux-failing")]
public void GetResolvedRuleSetPath_SimpleNameAndDirectories_NonExistent()
{
MockEngine mockEngine = new MockEngine();
ResolveCodereplacedysisRuleSet task = new ResolveCodereplacedysisRuleSet();
task.BuildEngine = mockEngine;
string directory = Path.GetTempPath();
task.CodereplacedysisRuleSet = Path.GetRandomFileName() + ".ruleset";
task.MSBuildProjectDirectory = null;
task.CodereplacedysisRuleSetDirectories = new[] { directory };
bool result = task.Execute();
string resolvedRuleSet = task.ResolvedCodereplacedysisRuleSet;
replacedert.Equal(expected: true, actual: result);
replacedert.Equal(expected: null, actual: resolvedRuleSet);
mockEngine.replacedertLogContains("MSB3884");
}
19
Source : ResolveCodeAnalysisRuleSet_Tests.cs
with MIT License
from enricosada
with MIT License
from enricosada
[Fact]
[Trait("Category", "netcore-osx-failing")]
[Trait("Category", "netcore-linux-failing")]
public void GetResolvedRuleSetPath_RelativePath_WithProject_NonExistent()
{
MockEngine mockEngine = new MockEngine();
ResolveCodereplacedysisRuleSet task = new ResolveCodereplacedysisRuleSet();
task.BuildEngine = mockEngine;
string subdirectoryName = Path.GetRandomFileName();
string projectDirectory = Path.GetTempPath();
task.CodereplacedysisRuleSet = Path.Combine(subdirectoryName, "Codereplacedysis.ruleset");
task.MSBuildProjectDirectory = projectDirectory;
task.CodereplacedysisRuleSetDirectories = null;
bool result = task.Execute();
string resolvedRuleSet = task.ResolvedCodereplacedysisRuleSet;
replacedert.Equal(expected: true, actual: result);
replacedert.Equal(expected: null, actual: resolvedRuleSet);
mockEngine.replacedertLogContains("MSB3884");
}
19
Source : ResolveCodeAnalysisRuleSet_Tests.cs
with MIT License
from enricosada
with MIT License
from enricosada
[Fact]
[Trait("Category", "netcore-osx-failing")]
[Trait("Category", "netcore-linux-failing")]
public void GetResolvedRuleSetPath_RelativePath_WithProject_Existent()
{
MockEngine mockEngine = new MockEngine();
ResolveCodereplacedysisRuleSet task = new ResolveCodereplacedysisRuleSet();
task.BuildEngine = mockEngine;
string subdirectoryName = Path.GetRandomFileName();
string codereplacedysisRuleSet = Path.Combine(subdirectoryName, "Codereplacedysis.ruleset");
string projectDirectory = Path.GetTempPath();
task.CodereplacedysisRuleSet = codereplacedysisRuleSet;
task.MSBuildProjectDirectory = projectDirectory;
task.CodereplacedysisRuleSetDirectories = null;
string ruleSetFullPath = Path.Combine(projectDirectory, codereplacedysisRuleSet);
using (new TemporaryDirectory(Path.GetDirectoryName(ruleSetFullPath)))
using (new TemporaryFile(ruleSetFullPath, "foo"))
{
bool result = task.Execute();
string resolvedRuleSet = task.ResolvedCodereplacedysisRuleSet;
replacedert.Equal(expected: true, actual: result);
replacedert.Equal(expected: codereplacedysisRuleSet, actual: resolvedRuleSet);
mockEngine.replacedertLogDoesntContain("MSB3884");
}
}
19
Source : ResolveCodeAnalysisRuleSet_Tests.cs
with MIT License
from enricosada
with MIT License
from enricosada
[Fact]
[Trait("Category", "netcore-osx-failing")]
[Trait("Category", "netcore-linux-failing")]
public void GetResolvedRuleSetPath_RelativePath_NoProject()
{
MockEngine mockEngine = new MockEngine();
ResolveCodereplacedysisRuleSet task = new ResolveCodereplacedysisRuleSet();
task.BuildEngine = mockEngine;
string subdirectoryName = Path.GetRandomFileName();
task.CodereplacedysisRuleSet = Path.Combine(subdirectoryName, "Codereplacedysis.ruleset");
task.MSBuildProjectDirectory = null;
task.CodereplacedysisRuleSetDirectories = null;
bool result = task.Execute();
string resolvedRuleSet = task.ResolvedCodereplacedysisRuleSet;
replacedert.Equal(expected: true, actual: result);
replacedert.Equal(expected: null, actual: resolvedRuleSet);
mockEngine.replacedertLogContains("MSB3884");
}
19
Source : BMFontImporter.cs
with BSD 3-Clause "New" or "Revised" License
from exomia
with BSD 3-Clause "New" or "Revised" License
from exomia
public override async Task<FontFile?> ImportAsync(Stream stream,
ImporterContext context,
CancellationToken cancellationToken)
{
return await Task.Run(
() =>
{
FontDescription? description = Json.Deserialize<FontDescription>(stream);
if (description == null)
{
context.AddMessage("Importing item failed! Expected type {0}!", typeof(FontDescription));
return null;
}
FontStyle fs = FontStyle.Regular;
if (description.IsBold)
{
fs |= FontStyle.Bold;
}
if (description.IsItalic)
{
fs |= FontStyle.Italic;
}
using (Font fnt = new Font(description.Name, description.Size, fs))
{
if (string.Compare(
fnt.Name, description.Name,
StringComparison.InvariantCultureIgnoreCase) != 0)
{
context.AddMessage(
"Can't import the font '{0:OrangeRed}'! " +
"The font doesn't exists on the current system!", description);
return null;
}
}
string tempFileNameLocation =
Path.Combine(TEMP_FILE_DIR, $"{description.Size}_{Path.GetRandomFileName()}.fnt");
string configLocation =
Path.Combine("tools", $"config{Thread.CurrentThread.ManagedThreadId}.bmfc");
int textureWidth =
Math2.RoundUpToPowerOfTwo(
(int)Math.Sqrt(GetCharCount(description.Chars) * description.Size));
while (textureWidth <= Resource.MaximumTexture2DSize)
{
if (cancellationToken.IsCancellationRequested)
{
return null;
}
File.WriteAllText(
configLocation,
CreateConfig(description, textureWidth, textureWidth));
using (Process p = Process.Start(
new ProcessStartInfo(
_bmFontExeLocation,
$"-c {configLocation} -o {tempFileNameLocation}")
{
UseShellExecute = false, CreateNoWindow = false
}))
{
if (!p.HasExited)
{
int i = 0;
while (!p.WaitForExit(1_000) &&
!cancellationToken.IsCancellationRequested &&
i++ < 45) { }
if (!p.HasExited)
{
try
{
p.Kill();
}
catch
{
/* IGNORE*/
}
}
}
if (p.ExitCode == 0)
{
FontFile fontFile = FontLoader.Load(tempFileNameLocation);
if (fontFile.Common!.Pages == 1)
{
if (CheckFontImageFiles(fontFile, TEMP_FILE_DIR))
{
fontFile.Pages![0].File =
Path.GetFullPath(Path.Combine(TEMP_FILE_DIR, fontFile.Pages[0].File));
return fontFile;
}
context.AddMessage("Font page file '{1}' not found!", fontFile.Pages![0].File);
return null;
}
foreach (string file in Directory.GetFiles(TEMP_FILE_DIR, $"{description.Size}*"))
{
File.Delete(file);
}
textureWidth <<= 1;
continue;
}
19
Source : Program.cs
with GNU General Public License v3.0
from F1uctus
with GNU General Public License v3.0
from F1uctus
static void ExecuteCSharp(string csCode) {
if (string.IsNullOrWhiteSpace(csCode)) {
return;
}
var refs = new List<MetadataReference>(
DefaultImports.Select(
asm => MetadataReference.CreateFromFile(asm.Location)
)
);
// Location of the .NET replacedemblies
var replacedemblyPath = Path.GetDirectoryName(typeof(object).replacedembly.Location)!;
// Adding some necessary .NET replacedemblies
// These replacedemblies couldn't be loaded correctly via
// the same construction as above.
refs.Add(MetadataReference.CreateFromFile(
Path.Join(replacedemblyPath, "mscorlib.dll")
));
refs.Add(MetadataReference.CreateFromFile(
Path.Join(replacedemblyPath, "System.dll")
));
refs.Add(MetadataReference.CreateFromFile(
Path.Join(replacedemblyPath, "System.Core.dll")
));
refs.Add(MetadataReference.CreateFromFile(
Path.Join(replacedemblyPath, "System.Runtime.dll")
));
refs.Add(MetadataReference.CreateFromFile(
typeof(Console).replacedembly.Location
));
refs.Add(MetadataReference.CreateFromFile(
Path.Join(replacedemblyPath, "System.Private.CoreLib.dll")
));
var replacedemblyName = Path.GetRandomFileName();
var syntaxTree = CSharpSyntaxTree.ParseText(csCode);
var compilation = CSharpCompilation.Create(
replacedemblyName,
new[] { syntaxTree },
refs,
new CSharpCompilationOptions(
OutputKind.DynamicallyLinkedLibrary
)
);
using var ms = new MemoryStream();
var result = compilation.Emit(ms);
if (result.Success) {
ms.Seek(0, SeekOrigin.Begin);
var replacedembly = replacedembly.Load(ms.ToArray());
var type = replacedembly.GetType("__RootModule__.__RootClreplaced__");
var main = type!.GetMethod("Main");
// Let's replacedume that compiler anyway 'd create Main method for us :)
main!.Invoke(null, new object[] { Array.Empty<string>() });
}
else {
var failures = result.Diagnostics.Where(
diagnostic => diagnostic.IsWarningAsError
|| diagnostic.Severity
== DiagnosticSeverity.Error
);
foreach (var diagnostic in failures) {
logger.Error($"{diagnostic.Id}: {diagnostic.GetMessage()}");
}
}
}
19
Source : OcrController.cs
with MIT License
from FairfieldTekLLC
with MIT License
from FairfieldTekLLC
public string CreateHocr(string language, string imagePath, string sessionName)
{
string dataFolder = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
string dataPath = TempData.Instance.CreateDirectory(sessionName, dataFolder);
string outputFile = Path.Combine(dataPath, Path.GetFileNameWithoutExtension(Path.GetRandomFileName()));
string enginePath = string.Empty;
try
{
enginePath = Path.Combine(Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location) ?? throw new InvalidOperationException(), "tessdata");
}
catch (Exception e)
{
enginePath = Path.Combine(Environment.CurrentDirectory, "tessdata");
}
using (TesseractEngine engine = new TesseractEngine(enginePath, "eng"))
{
using (var img = Pix.LoadFromFile(imagePath))
{
using (var page = engine.Process(img))
{
string hocrtext = page.GetHOCRText(0);
File.WriteAllText(outputFile + ".hocr", hocrtext);
}
}
}
return outputFile + ".hocr";
}
19
Source : TempData.cs
with MIT License
from FairfieldTekLLC
with MIT License
from FairfieldTekLLC
public string CreateTempFile(string sessionName, string extensionWithDot, string folders = null)
{
if (!_caches.ContainsKey(sessionName))
throw new Exception("Invalid Session");
string newFile = Path.Combine(_caches[sessionName],
Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + DateTime.Now.Second + DateTime.Now.Millisecond + extensionWithDot);
return newFile;
}
19
Source : ExportBase.cs
with MIT License
from FastReports
with MIT License
from FastReports
internal void ExportAndZip(Report report, Stream stream)
{
string tempFolder = Config.GetTempFolder() + Path.GetRandomFileName();
Directory.CreateDirectory(tempFolder);
try
{
Export(report, tempFolder + "/" + GetFileName(report) + GetFileExtension());
ZipArchive zip = new ZipArchive();
zip.AddDir(tempFolder);
zip.SaveToStream(stream);
}
finally
{
Directory.Delete(tempFolder, true);
}
}
19
Source : Config.cs
with MIT License
from FastReports
with MIT License
from FastReports
internal static string CreateTempFile(string dir)
{
if (String.IsNullOrEmpty(dir))
return GetTempFileName();
return Path.Combine(dir, Path.GetRandomFileName());
}
19
Source : Config.cs
with MIT License
from FastReports
with MIT License
from FastReports
private static string GetTempFileName()
{
return Path.Combine(GetTempFolder(), SystemFake.DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss-") + Path.GetRandomFileName());
}
19
Source : DynamicCompile.cs
with GNU Affero General Public License v3.0
from fbertram
with GNU Affero General Public License v3.0
from fbertram
public static replacedembly CompileSource(string sourcePath, MetadataReference[] moreReferences = null)
{
string sourceText = File.ReadAllText(sourcePath);
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(
sourceText,
path: sourcePath,
encoding: System.Text.Encoding.UTF8);
string replacedemblyName = Path.GetRandomFileName();
var replacedemblyPath = Path.GetDirectoryName(typeof(object).replacedembly.Location);
MetadataReference[] references = new MetadataReference[]
{
//--- these can't be created any other way
// https://stackoverflow.com/questions/23907305/roslyn-has-no-reference-to-system-runtime
MetadataReference.CreateFromFile(Path.Combine(replacedemblyPath, "mscorlib.dll")),
MetadataReference.CreateFromFile(Path.Combine(replacedemblyPath, "System.dll")),
MetadataReference.CreateFromFile(Path.Combine(replacedemblyPath, "System.Core.dll")),
MetadataReference.CreateFromFile(Path.Combine(replacedemblyPath, "System.Data.dll")),
MetadataReference.CreateFromFile(Path.Combine(replacedemblyPath, "System.Collections.dll")),
MetadataReference.CreateFromFile(Path.Combine(replacedemblyPath, "System.Runtime.dll")),
//--- these are referenced by a type we need
//MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().replacedembly.Location),
MetadataReference.CreateFromFile(typeof(Object).GetTypeInfo().replacedembly.Location),
MetadataReference.CreateFromFile(typeof(System.Linq.Enumerable).GetTypeInfo().replacedembly.Location),
MetadataReference.CreateFromFile(typeof(TuringTrader.Simulator.Algorithm).GetTypeInfo().replacedembly.Location),
//MetadataReference.CreateFromFile(typeof(TuringTrader.Indicators.IndicatorsBasic).GetTypeInfo().replacedembly.Location),
//--- this is what we used with CodeDOM
/*
cp.Referencedreplacedemblies.Add(replacedembly.GetExecutingreplacedembly().Location);
cp.Referencedreplacedemblies.Add("System.dll");
cp.Referencedreplacedemblies.Add("System.Runtime.dll");
cp.Referencedreplacedemblies.Add("System.Collections.dll");
cp.Referencedreplacedemblies.Add("System.Core.dll");
cp.Referencedreplacedemblies.Add("System.Data.dll");
cp.Referencedreplacedemblies.Add("OxyPlot.dll");
cp.Referencedreplacedemblies.Add("OxyPlot.Wpf.dll");
*/
};
if (moreReferences != null)
foreach (var r in moreReferences)
references = references.Append(r).ToArray();
CSharpCompilation compilation = CSharpCompilation.Create(
replacedemblyName,
syntaxTrees: new[] { syntaxTree },
references: references,
options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
using (var dll = new MemoryStream())
using (var pdb = new MemoryStream())
{
EmitResult result = compilation.Emit(dll, pdb);
if (!result.Success)
{
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error);
foreach (Diagnostic diagnostic in failures)
{
// find error location and line number
int errorChar = diagnostic.Location.SourceSpan.Start;
string errorSource = sourceText.Substring(0, errorChar);
int lineNumber = errorSource.Split('\n').Length;
Output.WriteLine("Line {0}: {1} - {2}",
lineNumber,
diagnostic.Id,
diagnostic.GetMessage());
}
}
else
{
dll.Seek(0, SeekOrigin.Begin);
pdb.Seek(0, SeekOrigin.Begin);
replacedembly replacedembly = replacedemblyLoadContext.Default.LoadFromStream(dll, pdb);
return replacedembly;
}
}
return null;
}
19
Source : RecentFileListTests.cs
with MIT License
from fernandreu
with MIT License
from fernandreu
[SetUp]
public void SetUp()
{
do
{
this._registryKey = "Software\\" + Path.GetRandomFileName();
} while (Registry.CurrentUser.OpenSubKey(this._registryKey) != null);
this.Control = new RecentFileList();
this.Control.UseRegistryPersister(this._registryKey);
}
19
Source : SampleTests.cs
with MIT License
from fernandreu
with MIT License
from fernandreu
private static SampleFolderViewModel PopulateRandomly(string path, int numFiles, int numFolders, int nestedLevels)
{
var result = new SampleFolderViewModel
{
Name = Path.GetFileName(path)
};
for (var i = 0; i < numFiles; ++i)
{
var name = Path.GetRandomFileName();
var nestedPath = Path.Combine(path, name + ".xml");
File.WriteAllText(nestedPath, "N/A");
result.Items.Add(new FileSampleViewModel(nestedPath));
}
if (nestedLevels <= 0)
{
return result;
}
for (var i = 0; i < numFolders; ++i)
{
var name = Path.GetRandomFileName();
var nestedPath = Path.Combine(path, name);
Directory.CreateDirectory(nestedPath);
result.Items.Add(PopulateRandomly(nestedPath, numFiles, numFolders, nestedLevels - 1));
}
return result;
}
19
Source : RecentFileListTests.cs
with MIT License
from fernandreu
with MIT License
from fernandreu
[SetUp]
public void SetUp()
{
do
{
this._filePath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
} while (File.Exists(this._filePath));
this.Control = new RecentFileList();
this.Control.UseXmlPersister(this._filePath);
}
19
Source : SampleTests.cs
with MIT License
from fernandreu
with MIT License
from fernandreu
[Test]
public static void CanScanSingleFiles()
{
// Arrange
string path, name;
do
{
name = Path.GetRandomFileName();
path = Path.Combine(Path.GetTempPath(), name + ".xml");
} while (Directory.Exists(path));
File.WriteAllText(path, null);
// Act
var result = SampleUtils.LoadXmlSamples(new[] {path}, false);
// replacedert
try
{
replacedert.AreEqual(1, result.Items.Count);
replacedert.AreEqual(name, result.Items[0].Name);
}
finally
{
File.Delete(path);
}
}
19
Source : SampleTests.cs
with MIT License
from fernandreu
with MIT License
from fernandreu
[Test]
[TestCase(3, 2, 2)]
public static void CanScanFolder(int numFiles, int numFolders, int nestedLevels)
{
// Arrange: create a random folder / xml file structure
string root;
do
{
root = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
} while (Directory.Exists(root));
Directory.CreateDirectory(root);
var expected = PopulateRandomly(root, numFiles, numFolders, nestedLevels);
// Act
var result = SampleUtils.LoadXmlSamples(new[] {root}, false);
// replacedert
try
{
replacedertConsistency(expected, (SampleFolderViewModel) result.Items[0]);
}
finally
{
Directory.Delete(root, true);
}
}
19
Source : MsBuildFileSetFactory.cs
with MIT License
from filipnavara
with MIT License
from filipnavara
public async Task<FileSet> CreateAsync(CancellationToken cancellationToken)
{
var watchList = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
try
{
var projectDir = Path.GetDirectoryName(_projectFile);
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
var capture = _outputSink.StartCapture();
var arguments = new List<string>
{
"msbuild",
"/nologo",
_projectFile,
$"/p:_DotNereplacedchListFile={watchList}",
};
if (_dotNereplacedchOptions.SuppressHandlingStaticContentFiles)
{
arguments.Add("/p:DotNereplacedchContentFiles=false");
}
arguments.AddRange(_buildFlags);
var processSpec = new ProcessSpec
{
Executable = _muxerPath,
WorkingDirectory = projectDir,
Arguments = arguments,
OutputCapture = capture
};
_reporter.Verbose($"Running MSBuild target '{TargetName}' on '{_projectFile}'");
var exitCode = await _processRunner.RunAsync(processSpec, cancellationToken);
if (exitCode == 0 && File.Exists(watchList))
{
using var watchFile = File.OpenRead(watchList);
var result = await JsonSerializer.DeserializeAsync<MSBuildFileSetResult>(watchFile, cancellationToken: cancellationToken);
var fileItems = new List<FileItem>();
foreach (var project in result.Projects)
{
var value = project.Value;
var fileCount = value.Files.Count;
for (var i = 0; i < fileCount; i++)
{
fileItems.Add(new FileItem
{
FilePath = value.Files[i],
ProjectPath = project.Key,
});
}
var staticItemsCount = value.StaticFiles.Count;
for (var i = 0; i < staticItemsCount; i++)
{
var item = value.StaticFiles[i];
fileItems.Add(new FileItem
{
FilePath = item.FilePath,
ProjectPath = project.Key,
IsStaticFile = true,
StaticWebreplacedetPath = item.StaticWebreplacedetPath,
});
}
}
_reporter.Verbose($"Watching {fileItems.Count} file(s) for changes");
#if DEBUG
foreach (var file in fileItems)
{
_reporter.Verbose($" -> {file.FilePath} {(file.IsStaticFile ? file.StaticWebreplacedetPath : null)}");
}
Debug.replacedert(fileItems.All(f => Path.IsPathRooted(f.FilePath)), "All files should be rooted paths");
#endif
// TargetFrameworkVersion appears as v6.0 in msbuild. Ignore the leading v
var targetFrameworkVersion = !string.IsNullOrEmpty(result.TargetFrameworkVersion) ?
Version.Parse(result.TargetFrameworkVersion.replacedpan(1)) : // Ignore leading v
null;
var projectInfo = new ProjectInfo(
_projectFile,
result.IsNetCoreApp,
targetFrameworkVersion,
result.RunCommand,
result.RunArguments,
result.RunWorkingDirectory);
return new FileSet(projectInfo, fileItems);
}
_reporter.Error($"Error(s) finding watch items project file '{Path.GetFileName(_projectFile)}'");
_reporter.Output($"MSBuild output from target '{TargetName}':");
_reporter.Output(string.Empty);
foreach (var line in capture.Lines)
{
_reporter.Output($" {line}");
}
_reporter.Output(string.Empty);
if (!_waitOnError)
{
return null;
}
else
{
_reporter.Warn("Fix the error to continue or press Ctrl+C to exit.");
var fileSet = new FileSet(null, new[] { new FileItem { FilePath = _projectFile } });
using (var watcher = new FileSereplacedcher(fileSet, _reporter))
{
await watcher.GetChangedFileAsync(cancellationToken);
_reporter.Output($"File changed: {_projectFile}");
}
}
}
}
finally
{
if (File.Exists(watchList))
{
File.Delete(watchList);
}
}
}
19
Source : BuilderEngine.cs
with Apache License 2.0
from fission
with Apache License 2.0
from fission
public async Task<bool> Compile(string code)
{
bool issuccess = false;
#region replacedymbaly init and parent dll refrences
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code);
string replacedemblyName = Path.GetRandomFileName();
var coreDir = Directory.GetParent(typeof(Enumerable).GetTypeInfo().replacedembly.Location);
List<MetadataReference> references = new List<MetadataReference>
{
MetadataReference.CreateFromFile(coreDir.FullName + Path.DirectorySeparatorChar + "mscorlib.dll"),
MetadataReference.CreateFromFile(coreDir.FullName + Path.DirectorySeparatorChar + "netstandard.dll"),
MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().replacedembly.Location),
MetadataReference.CreateFromFile(replacedembly.GetEntryreplacedembly().Location),
MetadataReference.CreateFromFile(typeof(System.Runtime.Serialization.Json.DataContractJsonSerializer).GetTypeInfo().replacedembly.Location)
};
foreach (var referencedreplacedembly in replacedembly.GetEntryreplacedembly().GetReferencedreplacedemblies())
{
var replacedembly = replacedembly.Load(referencedreplacedembly);
references.Add(MetadataReference.CreateFromFile(replacedembly.Location));
BuilderHelper.Instance.logger.Log($"Refering replacedembaly based dls : {replacedembly.Location}");
}
#endregion
#region handler registration for runtime resolution
//now add handeler for missing dlls for parent app domain as same replacedembalies should be needed
//for parent , thus refering from https://support.microsoft.com/en-in/help/837908/how-to-load-an-replacedembly-at-runtime-that-is-located-in-a-folder-that-is
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.replacedemblyResolve += CurrentDomain_replacedemblyResolve;
#endregion
BuilderHelper.Instance.logger.Log($"dynamic handlar registered!!");
#region nuget dll refrence add
//now add those dll refrence
foreach (var dll in dllInfos)
{
BuilderHelper.Instance.logger.Log($"refering nuget based dll : {dll.path}");
references.Add(MetadataReference.CreateFromFile(dll.path));
}
#endregion
#region compilation
CSharpCompilation compilation = CSharpCompilation.Create(
replacedemblyName,
syntaxTrees: new[] { syntaxTree },
references: references,
options: new CSharpCompilationOptions(
OutputKind.DynamicallyLinkedLibrary,
optimizationLevel: OptimizationLevel.Release));
using (var ms = new MemoryStream())
{
EmitResult result = compilation.Emit(ms);
if (!result.Success)
{
BuilderHelper.Instance.logger.Log($"Compile Failed!!!!",true);
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error).ToList();
foreach (Diagnostic diagnostic in failures)
{
compile_errors.Add($"{diagnostic.Id}: {diagnostic.GetMessage()}");
BuilderHelper.Instance.logger.Log($"COMPILE ERROR :{diagnostic.Id}: {diagnostic.GetMessage()}");
}
}
else
{
BuilderHelper.Instance.logger.Log("Compile Success!!",true);
issuccess = true;
}
}
#endregion
return issuccess;
}
19
Source : FissionCompiler.cs
with Apache License 2.0
from fission
with Apache License 2.0
from fission
public static Function Compile(string code, out List<string> errors)
{
errors = new List<string>();
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code);
string replacedemblyName = Path.GetRandomFileName();
var coreDir = Directory.GetParent(typeof(Enumerable).GetTypeInfo().replacedembly.Location);
List<MetadataReference> references = new List<MetadataReference>
{
MetadataReference.CreateFromFile(coreDir.FullName + Path.DirectorySeparatorChar + "mscorlib.dll"),
MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().replacedembly.Location),
MetadataReference.CreateFromFile(replacedembly.GetEntryreplacedembly().Location),
MetadataReference.CreateFromFile(typeof(System.Runtime.Serialization.Json.DataContractJsonSerializer).GetTypeInfo().replacedembly.Location)
};
foreach (var referencedreplacedembly in replacedembly.GetEntryreplacedembly().GetReferencedreplacedemblies())
{
var replacedembly = replacedembly.Load(referencedreplacedembly);
references.Add(MetadataReference.CreateFromFile(replacedembly.Location));
}
CSharpCompilation compilation = CSharpCompilation.Create(
replacedemblyName,
syntaxTrees: new[] { syntaxTree },
references: references,
options: new CSharpCompilationOptions(
OutputKind.DynamicallyLinkedLibrary,
optimizationLevel: OptimizationLevel.Release));
using (var ms = new MemoryStream())
{
EmitResult result = compilation.Emit(ms);
if (!result.Success)
{
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error).ToList();
foreach (Diagnostic diagnostic in failures)
{
errors.Add($"{diagnostic.Id}: {diagnostic.GetMessage()}");
}
}
else
{
ms.Seek(0, SeekOrigin.Begin);
replacedembly replacedembly = replacedemblyLoadContext.Default.LoadFromStream(ms);
var type = replacedembly.GetType("FissionFunction");
var info = type.GetMember("Execute").First() as MethodInfo;
return new Function(replacedembly, type, info);
}
}
return null;
}
19
Source : FissionCompiler.cs
with Apache License 2.0
from fission
with Apache License 2.0
from fission
public static Function Compile(string code, out List<string> errors)
{
errors = new List<string>();
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code);
string replacedemblyName = Path.GetRandomFileName();
var coreDir = Directory.GetParent(typeof(Enumerable).GetTypeInfo().replacedembly.Location);
List<MetadataReference> references = new List<MetadataReference>
{
MetadataReference.CreateFromFile(coreDir.FullName + Path.DirectorySeparatorChar + "mscorlib.dll"),
MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().replacedembly.Location),
MetadataReference.CreateFromFile(replacedembly.GetEntryreplacedembly().Location),
MetadataReference.CreateFromFile(typeof(System.Runtime.Serialization.Json.DataContractJsonSerializer).GetTypeInfo().replacedembly.Location)
};
foreach (var referencedreplacedembly in replacedembly.GetEntryreplacedembly().GetReferencedreplacedemblies())
{
var replacedembly = replacedembly.Load(referencedreplacedembly);
references.Add(MetadataReference.CreateFromFile(replacedembly.Location));
}
CSharpCompilation compilation = CSharpCompilation.Create(
replacedemblyName,
syntaxTrees: new[] { syntaxTree },
references: references,
options: new CSharpCompilationOptions(
OutputKind.DynamicallyLinkedLibrary,
optimizationLevel: OptimizationLevel.Release));
using (var ms = new MemoryStream())
{
EmitResult result = compilation.Emit(ms);
if (!result.Success)
{
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error).ToList();
foreach (Diagnostic diagnostic in failures)
{
errors.Add($"{diagnostic.Id}: {diagnostic.GetMessage()}");
}
}
else
{
ms.Seek(0, SeekOrigin.Begin);
replacedembly replacedembly = replacedemblyLoadContext.Default.LoadFromStream(ms);
//support for Namespace , as well as backward compatibility for existing functions
var type = replacedembly.GetTypes().FirstOrDefault(x => x.Name.EndsWith("FissionFunction"));
var info = type.GetMember("Execute").First() as MethodInfo;
return new Function(replacedembly, type, info);
}
}
return null;
}
19
Source : FissionCompiler.cs
with Apache License 2.0
from fission
with Apache License 2.0
from fission
public Function Compilev2(string code, out List<string> errors, out List<string> oinfo)
{
errors = new List<string>();
oinfo = new List<string>();
#region syntext tree and default refrence build
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code);
string replacedemblyName = Path.GetRandomFileName();
var coreDir = Directory.GetParent(typeof(Enumerable).GetTypeInfo().replacedembly.Location);
Console.WriteLine("Adding core refrences !!");
List<MetadataReference> references = new List<MetadataReference>
{
MetadataReference.CreateFromFile(coreDir.FullName + Path.DirectorySeparatorChar + "mscorlib.dll"),
MetadataReference.CreateFromFile(coreDir.FullName + Path.DirectorySeparatorChar + "netstandard.dll"),
MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().replacedembly.Location),
MetadataReference.CreateFromFile(replacedembly.GetEntryreplacedembly().Location),
MetadataReference.CreateFromFile(typeof(System.Runtime.Serialization.Json.DataContractJsonSerializer).GetTypeInfo().replacedembly.Location)
};
Console.WriteLine("Adding parent replacedembaly based refrences !!");
foreach (var referencedreplacedembly in replacedembly.GetEntryreplacedembly().GetReferencedreplacedemblies())
{
var replacedembly = replacedembly.Load(referencedreplacedembly);
references.Add(MetadataReference.CreateFromFile(replacedembly.Location));
}
#endregion
#region load function specs based dlls
Console.WriteLine($"going to get function specification...");
//load all available dlls from deployment folder in dllinfo object
functionSpecification = EnvironmentHelper.Instance.GetFunctionSpecs(packagepath);
Console.WriteLine($"going to get package dlls...");
//iterate and all all libraries mentioned
foreach (var library in functionSpecification.libraries)
{
string dllCompletePath = Path.Combine(packagepath, library.path).GetrelevantPathAsPerOS();
references.Add(MetadataReference.CreateFromFile(dllCompletePath));
Console.WriteLine($"refered folder based dll : {dllCompletePath} from package {library.nugetPackage}");
}
Console.WriteLine($"refered all available dlls!!");
oinfo.Add("refered all available dlls!!");
#endregion
#region dynamic resolve handeler registration
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.replacedemblyResolve += CurrentDomain_replacedemblyResolve;
#endregion
#region function compile
Console.WriteLine($"Trying to Compile");
CSharpCompilation compilation = CSharpCompilation.Create(
replacedemblyName,
syntaxTrees: new[] { syntaxTree },
references: references,
options: new CSharpCompilationOptions(
OutputKind.DynamicallyLinkedLibrary,
optimizationLevel: OptimizationLevel.Release));
using (var ms = new MemoryStream())
{
EmitResult result = compilation.Emit(ms);
if (!result.Success)
{
Console.WriteLine($"Compile Failed , see pod logs for more details");
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error).ToList();
foreach (Diagnostic diagnostic in failures)
{
errors.Add($"{diagnostic.Id}: {diagnostic.GetMessage()}");
Console.WriteLine($"COMPILE ERROR :{diagnostic.Id}: {diagnostic.GetMessage()}", "ERROR");
}
}
else
{
oinfo.Add("COMPILE SUCCESS!!");
Console.WriteLine($"COMPILE SUCCESS!!");
ms.Seek(0, SeekOrigin.Begin);
replacedembly replacedembly = replacedemblyLoadContext.Default.LoadFromStream(ms);
//var type = replacedembly.GetType("FissionFunction");
//support for Namespace , as well as backward compatibility for existing functions
var type = replacedembly.GetTypes().FirstOrDefault(x => x.Name.EndsWith("FissionFunction"));
//replacedembly.GetTypes().Where(x=>x.Name.ToLower().EndsWith("FissionFunction".ToLower())).FirstOrDefault();
var info = type.GetMember("Execute").First() as MethodInfo;
return new Function(replacedembly, type, info);
}
}
return null;
#endregion
}
See More Examples