Here are the examples of the csharp api System.IO.Path.IsPathRooted(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
978 Examples
19
View Source File : UiHelper.Textures.cs
License : GNU Affero General Public License v3.0
Project Creator : 0ceal0t
License : GNU Affero General Public License v3.0
Project Creator : 0ceal0t
public unsafe static AtkUldreplacedet* Createreplacedets(List<string> paths) {
var ret = Createreplacedets((uint)paths.Count);
for (int i = 0; i < paths.Count; i++) {
var hd = JobBars.Config.Use4K ? (byte)2 : (byte)1;
var tex = (AtkTexture*)(new IntPtr(ret) + 0x20 * i + 0x8);
var path = paths[i];
// get mapping to some file in necessary (icon.tex -> C:/mods/icon.tex)
// could also be icon.tex -> icon.tex
var resolvedPath = GetResolvedPath(JobBars.Config.Use4K ? path.Replace(".tex", "_hr1.tex") : path);
PluginLog.Log($"Resolved {path} -> {resolvedPath}");
if (Path.IsPathRooted(resolvedPath)) {
TextureLoadPath(tex, resolvedPath, 1); // don't want to re-apply _hr1
Marshal.WriteByte(new IntPtr(tex->Resource) + 0x1a, hd);
}
else {
TextureLoadPath(tex, path, hd);
}
}
return ret;
}
19
View Source File : FileSystemHelper.cs
License : zlib License
Project Creator : 0x0ade
License : zlib License
Project Creator : 0x0ade
public static string ChangePath(string path, char separator) {
// Can't trust File.Exists if MONO_IOMAP_ALL is set.
if (!MONO_IOMAP_ALL) {
string pathMaybe = path;
// Check if target exists in the first place.
if (Directory.Exists(path) || File.Exists(path))
return pathMaybe;
// Try a simpler fix first: Maybe the casing is already correct...
pathMaybe = path.Replace('/', separator).Replace('\\', separator);
if (Directory.Exists(pathMaybe) || File.Exists(pathMaybe))
return pathMaybe;
// Fall back to the slow rebuild.
}
// Check if the path has been rebuilt before.
Dictionary<string, string> cachedPaths;
if (!_CachedChanges.TryGetValue(separator, out cachedPaths))
_CachedChanges[separator] = cachedPaths = new Dictionary<string, string>();
string cachedPath;
if (cachedPaths.TryGetValue(path, out cachedPath))
return cachedPath;
// Split and rebuild path.
string[] pathSplit = path.Split(DirectorySeparatorChars);
StringBuilder builder = new StringBuilder();
bool unixRooted = false;
if (Path.IsPathRooted(path)) {
// The first element in a rooted path will always be correct.
// On Windows, this will be the drive letter.
// On Unix and Unix-like systems, this will be empty.
if (unixRooted = (builder.Length == 0))
// Path is rooted, but the path separator is the root.
builder.Append(separator);
else
builder.Append(pathSplit[0]);
}
for (int i = 1; i < pathSplit.Length; i++) {
string next;
if (i < pathSplit.Length - 1)
next = GetDirectory(builder.ToString(), pathSplit[i]);
else
next = GetTarget(builder.ToString(), pathSplit[i]);
next = next ?? pathSplit[i];
if (i != 1 || !unixRooted)
builder.Append(separator);
builder.Append(next);
}
return cachedPaths[path] = builder.ToString();
}
19
View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 0xthirteen
License : GNU General Public License v3.0
Project Creator : 0xthirteen
static void WriteToFileSMB(string host, string droploc, string fname, string paylocation)
{
try
{
byte[] filen = null;
var writeuncpath = String.Format(@"\\{0}\C${1}\{2}", host, droploc, fname);
//this is meant to be updated to compile file into replacedembly
if (Path.IsPathRooted(paylocation))
{
filen = File.ReadAllBytes(paylocation);
}
Console.WriteLine("[+] Writing data to : {0}", host);
File.WriteAllBytes(writeuncpath, filen);
}
catch (Exception ex)
{
Console.WriteLine("[X] Error : {0}", ex.Message);
return;
}
}
19
View Source File : ProjectItem.cs
License : MIT License
Project Creator : 3F
License : MIT License
Project Creator : 3F
private void SetFullPath(string slnDir)
{
if(path == null) {
return;
}
if(Path.IsPathRooted(path)) {
fullPath = path;
}
else {
fullPath = (slnDir != null) ? Path.Combine(slnDir, path) : path;
}
fullPath = Path.GetFullPath(fullPath); // D:\a\b\c\..\..\MvsSlnTest.csproj -> D:\a\MvsSlnTest.csproj
}
19
View Source File : IOUtil.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static string ResolvePath(String rootPath, String relativePath)
{
ArgUtil.NotNullOrEmpty(rootPath, nameof(rootPath));
ArgUtil.NotNullOrEmpty(relativePath, nameof(relativePath));
if (!Path.IsPathRooted(rootPath))
{
throw new ArgumentException($"{rootPath} should be a rooted path.");
}
if (relativePath.IndexOfAny(Path.GetInvalidPathChars()) > -1)
{
throw new InvalidOperationException($"{relativePath} contains invalid path characters.");
}
else if (Path.GetFileName(relativePath).IndexOfAny(Path.GetInvalidFileNameChars()) > -1)
{
throw new InvalidOperationException($"{relativePath} contains invalid folder name characters.");
}
else if (Path.IsPathRooted(relativePath))
{
throw new InvalidOperationException($"{relativePath} can not be a rooted path.");
}
else
{
rootPath = rootPath.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
relativePath = relativePath.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
// Root the path
relativePath = String.Concat(rootPath, Path.AltDirectorySeparatorChar, relativePath);
// Collapse ".." directories with their parent, and skip "." directories.
String[] split = relativePath.Split(new[] { Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
var segments = new Stack<String>(split.Length);
Int32 skip = 0;
for (Int32 i = split.Length - 1; i >= 0; i--)
{
String segment = split[i];
if (String.Equals(segment, ".", StringComparison.Ordinal))
{
continue;
}
else if (String.Equals(segment, "..", StringComparison.Ordinal))
{
skip++;
}
else if (skip > 0)
{
skip--;
}
else
{
segments.Push(segment);
}
}
if (skip > 0)
{
throw new InvalidOperationException($"The file path {relativePath} is invalid");
}
#if OS_WINDOWS
if (segments.Count > 1)
{
return String.Join(Path.DirectorySeparatorChar, segments);
}
else
{
return segments.Pop() + Path.DirectorySeparatorChar;
}
#else
return Path.DirectorySeparatorChar + String.Join(Path.DirectorySeparatorChar, segments);
#endif
}
}
19
View Source File : ActionCommandManager.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public void ProcessCommand(IExecutionContext context, string line, ActionCommand command, ContainerInfo container)
{
var file = command.Data;
// File is required
if (string.IsNullOrEmpty(file))
{
context.Warning("File path must be specified.");
return;
}
// Translate file path back from container path
if (container != null)
{
file = container.TranslateToHostPath(file);
}
// Root the path
if (!Path.IsPathRooted(file))
{
var githubContext = context.ExpressionValues["github"] as GitHubContext;
ArgUtil.NotNull(githubContext, nameof(githubContext));
var workspace = githubContext["workspace"].ToString();
ArgUtil.NotNullOrEmpty(workspace, "workspace");
file = Path.Combine(workspace, file);
}
// Load the config
var config = IOUtil.LoadObject<IssueMatchersConfig>(file);
// Add
if (config?.Matchers?.Count > 0)
{
config.Validate();
context.AddMatchers(config);
}
}
19
View Source File : ActionCommandManager.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public void ProcessCommand(IExecutionContext context, string line, ActionCommand command, ContainerInfo container)
{
command.Properties.TryGetValue(RemoveMatcherCommandProperties.Owner, out string owner);
var file = command.Data;
// Owner and file are mutually exclusive
if (!string.IsNullOrEmpty(owner) && !string.IsNullOrEmpty(file))
{
context.Warning("Either specify an owner name or a file path in ##[remove-matcher] command. Both values cannot be set.");
return;
}
// Owner or file is required
if (string.IsNullOrEmpty(owner) && string.IsNullOrEmpty(file))
{
context.Warning("Either an owner name or a file path must be specified in ##[remove-matcher] command.");
return;
}
// Remove by owner
if (!string.IsNullOrEmpty(owner))
{
context.RemoveMatchers(new[] { owner });
}
// Remove by file
else
{
// Translate file path back from container path
if (container != null)
{
file = container.TranslateToHostPath(file);
}
// Root the path
if (!Path.IsPathRooted(file))
{
var githubContext = context.ExpressionValues["github"] as GitHubContext;
ArgUtil.NotNull(githubContext, nameof(githubContext));
var workspace = githubContext["workspace"].ToString();
ArgUtil.NotNullOrEmpty(workspace, "workspace");
file = Path.Combine(workspace, file);
}
// Load the config
var config = IOUtil.LoadObject<IssueMatchersConfig>(file);
if (config?.Matchers?.Count > 0)
{
// Remove
context.RemoveMatchers(config.Matchers.Select(x => x.Owner));
}
}
}
19
View Source File : GenerateNuSpecFileTask.cs
License : MIT License
Project Creator : adamecr
License : MIT License
Project Creator : adamecr
public override bool Execute()
{
if (DebugTasks)
{
//Wait for debugger
Log.LogMessage(
MessageImportance.High,
$"Debugging task {GetType().Name}, set the breakpoint and attach debugger to process with PID = {System.Diagnostics.Process.GetCurrentProcess().Id}");
while (!System.Diagnostics.Debugger.IsAttached)
{
Thread.Sleep(1000);
}
}
var replacedle = !string.IsNullOrEmpty(replacedle) ? replacedle : PackageId;
var sb = new System.Text.StringBuilder(); //TODO refactor to LINQ XML
sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
sb.AppendLine($"<package xmlns=\"http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd\">");
sb.AppendLine($" <metadata>");
sb.AppendLine($" <id>{PackageId}</id>");
sb.AppendLine($" <version>{PackageVersionFull}</version>");
sb.AppendLine($" <authors>{Authors}</authors>");
sb.AppendLine($" <replacedle>{replacedle}</replacedle>");
sb.AppendLine($" <owners>{Authors}</owners>");
sb.AppendLine($" <requireLicenseAcceptance>{PackageRequireLicenseAcceptance}</requireLicenseAcceptance>");
// ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
if (!string.IsNullOrEmpty(PackageLicense))
{
sb.AppendLine($" <license type=\"expression\">{PackageLicense}</license>");
}
else
{
sb.AppendLine($" <licenseUrl>{PackageLicenseUrl}</licenseUrl>");
}
sb.AppendLine($" <projectUrl>{PackageProjectUrl}</projectUrl>");
sb.AppendLine($" <iconUrl>{PackageIconUrl}</iconUrl>");
sb.AppendLine($" <description>{Description}</description>");
sb.AppendLine($" <releaseNotes>{PackageReleaseNotes}</releaseNotes>");
sb.AppendLine($" <copyright>{Copyright}</copyright>");
sb.AppendLine($" <tags>{PackageTags}</tags>");
sb.AppendLine(
$" <repository url=\"{RepositoryUrl}\" type=\"git\" branch=\"{GitBranch}\" commit=\"{GitCommit}\" />");
sb.AppendLine($" <dependencies>");
sb.AppendLine($" <group targetFramework=\"{TargetFramework}\">");
if (PackageReferences != null)
{
foreach (var r in PackageReferences)
{
var item = r.ItemSpec;
if (item != "NETStandard.Library")
sb.AppendLine(
$" <dependency id=\"{r.ItemSpec}\" version=\"{r.GetMetadata("Version")}\" exclude=\"Build,replacedyzers\" />");
}
}
var resolvedProjectReferences =
new List<string>(); //project references that has been resolved as NuGet packages
if (ProjectReferences != null)
{
foreach (var src in ProjectReferences)
{
var refPackageDependencyFile = Path.Combine(src.GetMetadata("RelativeDir"), IntermediateOutputPath,
Configuration, "package_dependency.txt");
if (!File.Exists(refPackageDependencyFile)) continue;
var refPackageDependency = File.ReadAllText(refPackageDependencyFile);
resolvedProjectReferences.Add(refPackageDependency);
sb.AppendLine(refPackageDependency);
}
}
sb.AppendLine($" </group>");
sb.AppendLine($" </dependencies>");
sb.AppendLine($" </metadata>");
sb.AppendLine($" <files>");
var dllFile = Path.Combine(ProjectDirectory, OutputPath, $"{replacedemblyName}.dll");
sb.AppendLine([email protected]" <file src=""{dllFile}"" target=""lib\{TargetFramework}\{replacedemblyName}.dll"" />");
var pdbFile = Path.Combine(ProjectDirectory, OutputPath, $"{replacedemblyName}.pdb");
if (File.Exists(pdbFile))
{
sb.AppendLine([email protected]" <file src=""{pdbFile}"" target=""lib\{TargetFramework}\{replacedemblyName}.pdb"" />");
}
var xmlDocFile = Path.Combine(ProjectDirectory, OutputPath, $"{replacedemblyName}.xml");
if (File.Exists(xmlDocFile))
{
sb.AppendLine(
[email protected]" <file src=""{xmlDocFile}"" target=""lib\{TargetFramework}\{replacedemblyName}.xml"" />");
}
if (SourceFiles != null && Configuration.ToLower() != "release")
{
sb.AppendLine("");
foreach (var src in SourceFiles)
{
var srcFileOriginal = src.GetMetadata("OriginalItemSpec");
var srcFileRel = srcFileOriginal.Replace([email protected]"{ProjectDirectory}\", "");
if (Path.IsPathRooted(srcFileRel)) continue; //not a project file (probably source-only package) - project files have the relative path in srcFileRel, non project files have full path in srcFileRel
var targetFile = Path.Combine("src", ProjectName, srcFileRel);
sb.AppendLine([email protected]" <file src=""{src}"" target=""{targetFile}"" />");
}
}
//include project references that has NOT been resolved as NuGet packages
if (ProjectReferences != null && ReferenceCopyLocalPaths != null)
{
foreach (var rf in ReferenceCopyLocalPaths)
{
if (rf.GetMetadata("ReferenceSourceTarget") == "ProjectReference")
{
var fileName = rf.GetMetadata("FileName");
if (!resolvedProjectReferences.Exists(s => s.Contains($"id=\"{fileName}\"")))
{
sb.AppendLine(
[email protected]" <file src=""{rf.GetMetadata("FullPath")}"" target=""lib\{TargetFramework}\{rf.GetMetadata("FileName")}{rf.GetMetadata("Extension")}"" />");
}
}
}
}
sb.AppendLine($" </files>");
sb.AppendLine($"</package> ");
//Write NuSpec file to /obj directory
NuSpecFile = Path.Combine(ProjectDirectory, IntermediateOutputPath, Configuration,
PackageVersionShort + ".nuspec");
File.WriteAllText(NuSpecFile, sb.ToString());
Log.LogMessage(sb.ToString());
//Create dependency file for package in /obj directory
var dep =
[email protected]"<dependency id=""{PackageId}"" version=""{PackageVersionFull}"" exclude=""Build,replacedyzers"" />";
var dependencyFile = Path.Combine(ProjectDirectory, IntermediateOutputPath, Configuration,
"package_dependency.txt");
File.WriteAllText(dependencyFile, dep);
return true;
}
19
View Source File : PublicizeInternals.cs
License : MIT License
Project Creator : aelij
License : MIT License
Project Creator : aelij
private string GetFullFilePath(string path)
{
if (!Path.IsPathRooted(path))
{
path = Path.Combine(_sourceDir, path);
}
path = Path.GetFullPath(path);
return path;
}
19
View Source File : CoreExtensions.cs
License : MIT License
Project Creator : agc93
License : MIT License
Project Creator : agc93
internal static IConfigurationBuilder AddFile(this IConfigurationBuilder builder, string path) {
var formats = new Dictionary<string, Action<IConfigurationBuilder, string>> {
[".json"] = (builder, path) => builder.AddJsonFile(path, true),
[".yml"] = (builder, path) => builder.AddYamlFile(path, true)
};
path = Path.IsPathRooted(path) ? path : Path.GetFullPath(path);
if (Path.HasExtension(path)) {
var format = formats.TryGetValue(Path.GetExtension(path), out var confAction);
if (format) {
confAction.Invoke(builder, path);
}
} else {
var firstMatch = formats.FirstOrDefault(f => {
return File.Exists(path + f.Key);
});
if (firstMatch.Value != null) {
firstMatch.Value.Invoke(builder, path + firstMatch.Key);
}
}
return builder;
}
19
View Source File : ZipStorage.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public byte[] Extract(string fpath)
{
this.replacedert(!string.IsNullOrEmpty(fpath));
if (fpath.StartsWith("/"))
fpath = fpath.TrimStart('/');
byte[] content = null;
try
{
content = _webCache.Extract(fpath);
if (content == null)
{
//if (File.Exists(_pkgLocation))
if (Path.IsPathRooted(_pkgLocation))
{
using (FileStream fs = new FileStream(_pkgLocation, FileMode.Open, FileAccess.Read, FileShare.Read))
content = ZipStream.Extract(fs, fpath);
}
else
{
var replacedembly = System.Reflection.replacedembly.GetEntryreplacedembly();
var rs = replacedembly.GetManifestResourceStream(_pkgLocation);
content = ZipStream.Extract(rs, fpath);
}
if (content != null)
_webCache.Add(fpath, content);
}
}
catch (Exception ex) { TraceLog.WriteException(ex); throw; }
return content;
}
19
View Source File : ZipStorage.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public bool Exists(string fpath)
{
this.replacedert(!string.IsNullOrEmpty(fpath));
if (fpath.StartsWith("/"))
fpath = fpath.TrimStart('/');
bool exists = false;
try
{
exists = _webCache.Contains(fpath);
if (!exists)
{
//if (File.Exists(_pkgLocation))
if (Path.IsPathRooted(_pkgLocation))
{
using (FileStream fs = new FileStream(_pkgLocation, FileMode.Open, FileAccess.Read, FileShare.Read))
exists = ZipStream.IsExists(fs, fpath);
}
else
{
var replacedembly = System.Reflection.replacedembly.GetEntryreplacedembly();
var rs = replacedembly.GetManifestResourceStream(_pkgLocation);
exists = ZipStream.IsExists(rs, fpath);
}
}
}
catch (Exception ex) { TraceLog.WriteException(ex); throw; }
return exists;
}
19
View Source File : Toolbox.cs
License : GNU General Public License v3.0
Project Creator : akaAgar
License : GNU General Public License v3.0
Project Creator : akaAgar
internal static bool IsFilePathValid(string path, bool allowRelativePaths = false)
{
bool isValid;
try
{
string fullPath = Path.GetFullPath(path);
if (allowRelativePaths)
{
isValid = Path.IsPathRooted(path);
}
else
{
string root = Path.GetPathRoot(path);
isValid = string.IsNullOrEmpty(root.Trim(new char[] { '/' })) == false;
}
}
catch (Exception)
{
isValid = false;
}
return isValid;
}
19
View Source File : BlobInfo.cs
License : MIT License
Project Creator : akasarto
License : MIT License
Project Creator : akasarto
public static BlobInfo FromName(string blobName)
{
if (string.IsNullOrWhiteSpace(blobName) || Path.IsPathRooted(Sanitize(blobName)))
{
return null;
}
var id = Guid.Empty;
var rawId = GetRawId(blobName: blobName);
if (!Guid.TryParse(rawId, out id))
{
return null;
}
var name = blobName ?? string.Empty;
var container = GetContainer(blobName);
var cleanExtension = GetCleanExtension(blobName);
return new BlobInfo(id, container, cleanExtension);
}
19
View Source File : SystemNetSmtpEmailDispatcherService.cs
License : MIT License
Project Creator : akasarto
License : MIT License
Project Creator : akasarto
public virtual void Send(MailMessage message)
{
using (var client = _smtpClient ?? new SmtpClient())
{
switch (client.DeliveryMethod)
{
case SmtpDeliveryMethod.SpecifiedPickupDirectory:
{
if (!Path.IsPathRooted(client.PickupDirectoryLocation))
{
client.PickupDirectoryLocation = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
client.PickupDirectoryLocation.Trim('~').Trim('\\', '/').Replace("/", "\\")
);
if (!Directory.Exists(client.PickupDirectoryLocation))
{
Directory.CreateDirectory(client.PickupDirectoryLocation);
}
}
}
break;
}
client.Send(message);
}
}
19
View Source File : MainProgram.cs
License : MIT License
Project Creator : AlbertMN
License : MIT License
Project Creator : AlbertMN
public static bool IsValidPath(string path, bool allowRelativePaths = false) {
bool isValid = true;
try {
string fullPath = Path.GetFullPath(path);
if (allowRelativePaths) {
isValid = Path.IsPathRooted(path);
} else {
string root = Path.GetPathRoot(path);
isValid = string.IsNullOrEmpty(root.Trim(new char[] { '\\', '/' })) == false;
}
} catch {
isValid = false;
}
return isValid;
}
19
View Source File : AppHostVirtualDirectoryConfigurator.cs
License : MIT License
Project Creator : alethic
License : MIT License
Project Creator : alethic
public AppHostVirtualDirectoryConfigurator UsePhysicalPath(string physicalPath)
{
if (string.IsNullOrWhiteSpace(physicalPath))
throw new ArgumentException(nameof(physicalPath));
// build absolute path from current working directory
if (Path.IsPathRooted(physicalPath) == false)
physicalPath = Path.Combine(Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location), physicalPath);
element.SetAttributeValue("physicalPath", physicalPath);
return this;
}
19
View Source File : Extensions.cs
License : Apache License 2.0
Project Creator : Algoryx
License : Apache License 2.0
Project Creator : Algoryx
public static string PrettyPath( this string path )
{
var result = string.Copy( path );
// Unity replacedetDataBase and/or Resources doesn't support
// intermediate relative (..) path, e.g., replacedets/Foo/../Bar/file.txt.
if ( result.Contains( ".." ) )
result = System.IO.Path.GetFullPath( result );
result = result.Replace( '\\', '/' );
if ( System.IO.Path.IsPathRooted( result ) )
result = result.MakeRelative( Application.dataPath );
if ( result.StartsWith( "./" ) )
result = result.Remove( 0, 2 );
return result;
}
19
View Source File : LicenseManager.cs
License : Apache License 2.0
Project Creator : Algoryx
License : Apache License 2.0
Project Creator : Algoryx
public static bool GenerateEncryptedRuntime( int runtimeLicenseId,
string runtimeLicensePreplacedword,
string applicationRootDirectory,
string referenceApplicationFile,
Action<string> onSuccess = null )
{
if ( !Directory.Exists( applicationRootDirectory ) ) {
Debug.LogError( "AGXUnity.LicenseManager: Unable to generate encrypted runtime license - " +
$"application root directory \"{applicationRootDirectory}\" doesn't exist." );
return false;
}
if ( !Path.IsPathRooted( applicationRootDirectory ) ) {
Debug.LogError( "AGXUnity.LicenseManager: Unable to generate encrypted runtime license - " +
$"application root directory \"{applicationRootDirectory}\" isn't rooted." );
return false;
}
var absolutePathToReferenceFile = $"{applicationRootDirectory}/{referenceApplicationFile}".Replace( '\\', '/' );
if ( !File.Exists( absolutePathToReferenceFile ) ) {
Debug.LogError( "AGXUnity.LicenseManager: Unable to generate encrypted runtime license - " +
$"reference file \"{referenceApplicationFile}\" doesn't exist relative to \"{applicationRootDirectory}\"." );
return false;
}
try {
agxIO.Environment.instance().getFilePath( agxIO.Environment.Type.RESOURCE_PATH ).pushbackPath( applicationRootDirectory );
var encrypted = agx.Runtime.instance().encryptRuntimeActivation( runtimeLicenseId,
runtimeLicensePreplacedword,
referenceApplicationFile );
agxIO.Environment.instance().getFilePath( agxIO.Environment.Type.RESOURCE_PATH ).removeFilePath( applicationRootDirectory );
if ( !string.IsNullOrEmpty( encrypted ) ) {
// Fall-back directory is application root but we'll try to find
// the AGX Dynamics binaries and place it there if applicationRootDirectory
// is part of the resources of AGX Dynamics.
var licenseTargetDirectory = Directory.GetFiles( applicationRootDirectory,
"agxPhysics.dll",
SearchOption.AllDirectories ).Select( file => new FileInfo( file ).Directory.FullName ).FirstOrDefault() ??
applicationRootDirectory;
var encryptedFilename = $"{licenseTargetDirectory}/agx{s_runtimeActivationExtension}".Replace( '\\', '/' );
File.WriteAllText( encryptedFilename, encrypted );
onSuccess?.Invoke( encryptedFilename );
return true;
}
Debug.LogError( "AGXUnity.LicenseManager: Unable to generate encrypted runtime license - " +
$"encryption failed with status: {agx.Runtime.instance().getStatus()}" );
}
catch ( System.Exception e ) {
Debug.LogError( "AGXUnity.LicenseManager: Exception occurred during generate of encrypted runtime " +
$"for application root \"{applicationRootDirectory}\"." );
Debug.LogException( e );
}
return false;
}
19
View Source File : ExternalAGXInitializer.cs
License : Apache License 2.0
Project Creator : Algoryx
License : Apache License 2.0
Project Creator : Algoryx
private bool InitializeCheckout( string agxDir )
{
const int AGX_DEPENDENCIES = 0;
const int AGXTERRAIN_DEPENDENCIES = 1;
const int INSTALLED = 2;
Instance.AGX_DIR = agxDir;
var cmakeCache = new FileInfo( AGX_DIR + Path.DirectorySeparatorChar + "CMakeCache.txt" );
var binData = new BinDirData[]
{
new BinDirData()
{
CMakeKey = "CACHE_DEPENDENCY_DATE:STRING="
},
new BinDirData()
{
CMakeKey = "TERRAIN_DEPENDENCY_DATE:STRING="
},
new BinDirData()
{
CMakeKey = "CMAKE_INSTALL_PREFIX:PATH="
}
};
using ( var stream = cmakeCache.OpenText() ) {
var line = string.Empty;
while ( !binData.All( data => data.HasValue ) &&
( line = stream.ReadLine()?.Trim() ) != null ) {
if ( line.StartsWith( "//" ) )
continue;
binData.Any( data => data.StoreValue( line ) );
}
}
if ( !binData.All( data => data.HasValue ) ) {
foreach ( var data in binData )
if ( !data.HasValue )
Debug.LogError( $"{"ERROR".Color( Color.red )}: {data.CMakeKey}null" );
return false;
}
var dependenciesDir = new DirectoryInfo( AGX_DIR +
Path.DirectorySeparatorChar +
"dependencies" );
if ( !dependenciesDir.Exists ) {
Debug.LogError( $"{"ERROR".Color( Color.red )}: Dependencies directory {dependenciesDir.FullName} - doesn't exist." );
return false;
}
binData[ AGX_DEPENDENCIES ].Directory = dependenciesDir.GetDirectories( $"agx_dependencies_{binData[ AGX_DEPENDENCIES ].Value}*" ).FirstOrDefault();
binData[ AGXTERRAIN_DEPENDENCIES ].Directory = dependenciesDir.GetDirectories( $"agxTerrain_dependencies_{binData[ AGXTERRAIN_DEPENDENCIES ].Value}*" ).FirstOrDefault();
// Handle both absolute and relative CMAKE_INSTALL_PREFIX
var installPath = binData[ INSTALLED ].Value;
if ( Path.IsPathRooted( installPath ) )
binData[ INSTALLED ].Directory = new DirectoryInfo( installPath );
else
binData[ INSTALLED ].Directory = new DirectoryInfo( AGX_DIR +
Path.DirectorySeparatorChar +
installPath );
if ( binData.Any( data => data.Directory == null || !data.Directory.Exists ) ) {
foreach ( var data in binData )
if ( data.Directory == null || !data.Directory.Exists )
Debug.LogError( $"{"ERROR".Color( Color.red )}: Unable to find directory for key {data.CMakeKey}." );
return false;
}
AGX_BIN_PATH = ( from data in binData
select $"{data.Directory.FullName}{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}x64" ).ToArray();
AGX_PLUGIN_PATH = $"{AGX_BIN_PATH[ INSTALLED ]}{Path.DirectorySeparatorChar}plugins";
AGX_DATA_DIR = $"{binData[ INSTALLED ].Directory.FullName}{Path.DirectorySeparatorChar}data";
return true;
}
19
View Source File : WordTemplateFolderManager.cs
License : MIT License
Project Creator : alkampfergit
License : MIT License
Project Creator : alkampfergit
internal string GenerateFullFileName(string templateName)
{
if (!Path.IsPathRooted(templateName))
{
return Path.Combine(_templateFolder, templateName);
}
return templateName;
}
19
View Source File : VectorReader.cs
License : MIT License
Project Creator : altimesh
License : MIT License
Project Creator : altimesh
private static string GetPath(string filePath)
{
string path;
if (Path.IsPathRooted(filePath))
{
path = filePath;
}
else
{
path = Path.Combine(Environment.CurrentDirectory, filePath);
}
if (!File.Exists(path))
{
throw new FileNotFoundException(path);
}
return path;
}
19
View Source File : Program.cs
License : MIT License
Project Creator : amerkoleci
License : MIT License
Project Creator : amerkoleci
public static int Main(string[] args)
{
string outputPath = AppContext.BaseDirectory;
if (args.Length > 0)
{
outputPath = args[0];
}
if (!Path.IsPathRooted(outputPath))
{
outputPath = Path.Combine(AppContext.BaseDirectory, outputPath);
}
if (!Directory.Exists(outputPath))
{
Directory.CreateDirectory(outputPath);
}
string? headerFile = Path.Combine(AppContext.BaseDirectory, "vulkan", "vulkan.h");
var options = new CppParserOptions
{
ParseMacros = true,
Defines =
{
"VK_USE_PLATFORM_ANDROID_KHR",
"VK_USE_PLATFORM_IOS_MVK",
"VK_USE_PLATFORM_MACOS_MVK",
"VK_USE_PLATFORM_METAL_EXT",
"VK_USE_PLATFORM_VI_NN",
//"VK_USE_PLATFORM_WAYLAND_KHR",
//"VK_USE_PLATFORM_WIN32_KHR",
//"VK_USE_PLATFORM_SCREEN_QNX",
"VK_ENABLE_BETA_EXTENSIONS"
}
};
var compilation = CppParser.ParseFile(headerFile, options);
// Print diagnostic messages
if (compilation.HasErrors)
{
foreach (var message in compilation.Diagnostics.Messages)
{
if (message.Type == CppLogMessageType.Error)
{
var currentColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(message);
Console.ForegroundColor = currentColor;
}
}
return 0;
}
bool generateFuncFile = false;
if (generateFuncFile)
{
File.Delete("Vk.txt");
foreach (var func in compilation.Functions)
{
var signature = new System.Text.StringBuilder();
var argSignature = CsCodeGenerator.GetParameterSignature(func, true);
signature
.Append(func.ReturnType.GetDisplayName())
.Append(" ")
.Append(func.Name)
.Append("(")
.Append(argSignature)
.Append(")");
File.AppendAllText("Vk.txt", signature.ToString() + Environment.NewLine);
}
}
CsCodeGenerator.Generate(compilation, outputPath);
return 0;
}
19
View Source File : Includer.cs
License : MIT License
Project Creator : amerkoleci
License : MIT License
Project Creator : amerkoleci
private static unsafe nint shaderc_include_resolve(void* user_data, [MarshalAs(UnmanagedType.LPStr)] string requested_source, int type, [MarshalAs(UnmanagedType.LPStr)] string requesting_source, UIntPtr include_depth)
{
GCHandle gch = GCHandle.FromIntPtr((IntPtr)user_data);
#pragma warning disable CS8600
Includer includer = (Includer)gch.Target;
#pragma warning restore CS8600
#pragma warning disable CS8602
if (!includer._shadercIncludeResults.TryGetValue(requested_source, out IntPtr includeResultPtr))
#pragma warning restore CS8602
{
Native.shaderc_include_result includeResult = new();
string path = requested_source;
if (!Path.IsPathRooted(path))
{
string rootPath = includer.RootPath;
if (includer._sourceToPath.ContainsKey(requesting_source)) {
rootPath = Path.GetDirectoryName(includer._sourceToPath[requesting_source]);
}
path = Path.Combine(rootPath, path);
}
includeResult.content = File.ReadAllText(path);
includeResult.content_length = (UIntPtr)includeResult.content.Length;
includeResult.source_name = requested_source;
includeResult.source_name_length = (UIntPtr)includeResult.source_name.Length;
includeResultPtr = Marshal.AllocHGlobal(Marshal.SizeOf(includeResult));
Marshal.StructureToPtr(includeResult, includeResultPtr, false);
includer._shadercIncludeResults.Add(requested_source, includeResultPtr);
includer._ptrToName.Add(includeResultPtr, requested_source);
includer._sourceToPath.Add(requested_source, path);
}
return includeResultPtr;
}
19
View Source File : StorageExtensions.cs
License : MIT License
Project Creator : Aminator
License : MIT License
Project Creator : Aminator
public static string GetRelativePath(string relativeTo, string path)
{
relativeTo = Path.IsPathRooted(relativeTo) ? relativeTo : "C:/" + relativeTo;
path = Path.IsPathRooted(path) ? path : "C:/" + path;
Uri path1 = new Uri(relativeTo + Path.DirectorySeparatorChar);
Uri path2 = new Uri(path);
Uri relativeUri = path1.MakeRelativeUri(path2);
return Uri.UnescapeDataString(relativeUri.OriginalString.Replace('/', Path.DirectorySeparatorChar));
}
19
View Source File : Synchronization.cs
License : MIT License
Project Creator : Angelelz
License : MIT License
Project Creator : Angelelz
private static Boolean CheckKeyFile(PwDatabase sourceDb, Settings settings, PwEntry settingsEntry)
{
// If a key file is given it must exist.
if (!string.IsNullOrEmpty(settings.KeyFilePath))
{
// Default to same folder as sourceDb for the keyfile if no directory is specified
if (!Path.IsPathRooted(settings.KeyFilePath))
{
string sourceDbPath = Path.GetDirectoryName(sourceDb.IOConnectionInfo.Path);
if (sourceDbPath != null)
{
settings.KeyFilePath = Path.Combine(sourceDbPath, settings.KeyFilePath);
}
}
if (!File.Exists(settings.KeyFilePath))
{
MessageService.ShowWarning("MasterSlaveSync: Keyfile is given but could not be found for: " +
settingsEntry.Strings.ReadSafe("replacedle"), settings.KeyFilePath);
return true;
}
}
return false;
}
19
View Source File : Synchronization.cs
License : MIT License
Project Creator : Angelelz
License : MIT License
Project Creator : Angelelz
private static bool CheckTargetFilePath(Settings settings, PwEntry settingsEntry, PwDatabase sourceDb)
{
// Require targetFilePath
if (string.IsNullOrEmpty(settings.TargetFilePath))
{
MessageService.ShowWarning("MasterSlaveSync: Missing TargetFilePath for: " +
settingsEntry.Strings.ReadSafe("replacedle"));
return true;
}
// Default to same folder as sourceDb for the keyfile if no directory is specified
if (!Path.IsPathRooted(settings.TargetFilePath))
{
string sourceDbPath = Path.GetDirectoryName(sourceDb.IOConnectionInfo.Path);
if (sourceDbPath != null)
{
settings.TargetFilePath = Path.Combine(sourceDbPath, settings.TargetFilePath);
}
}
if (!File.Exists(settings.TargetFilePath))
{
MessageService.ShowWarning("MasterSlaveSync: Slave Database not found for: " +
settingsEntry.Strings.ReadSafe("replacedle"));
return true;
}
return false;
}
19
View Source File : DnaConfiguration.cs
License : MIT License
Project Creator : angelsix
License : MIT License
Project Creator : angelsix
public static string ResolveFullPath(string currentDirectory, string path, bool replaceSpecialVariables, out bool wasRelative)
{
// Initially relative
wasRelative = true;
// Replace any special variables
if (replaceSpecialVariables)
{
// Local App Data folder
path = path.Replace("%LOCALAPPDATA%", Environment.GetEnvironmentVariable("LocalAppData"));
// DnaWeb version
path = path.Replace("%VERSION%", DnaSettings.Version.ToString());
}
if (!Path.IsPathRooted(path))
// Return absolute path
return Path.GetFullPath(Path.Combine(currentDirectory ?? string.Empty, path));
// Flag this was not relative
wasRelative = false;
// Return path as it's already absolute
return path;
}
19
View Source File : AccCompiler.cs
License : GNU General Public License v3.0
Project Creator : anotak
License : GNU General Public License v3.0
Project Creator : anotak
public override bool Run()
{
ProcessStartInfo processinfo;
Process process;
TimeSpan deltatime;
int line = 0;
string sourcedir = Path.GetDirectoryName(sourcefile);
// Create parameters
string args = this.parameters;
args = args.Replace("%FI", inputfile);
args = args.Replace("%FO", outputfile);
args = args.Replace("%FS", sourcefile);
args = args.Replace("%PT", this.tempdir.FullName);
args = args.Replace("%PS", sourcedir);
// Setup process info
processinfo = new ProcessStartInfo();
processinfo.Arguments = args;
processinfo.FileName = Path.Combine(this.tempdir.FullName, info.ProgramFile);
processinfo.CreateNoWindow = false;
processinfo.ErrorDialog = false;
processinfo.UseShellExecute = true;
processinfo.WindowStyle = ProcessWindowStyle.Hidden;
processinfo.WorkingDirectory = this.workingdir;
// Output info
Logger.WriteLogLine("Running compiler...");
Logger.WriteLogLine("Program: " + processinfo.FileName);
Logger.WriteLogLine("Arguments: " + processinfo.Arguments);
try
{
// Start the compiler
process = Process.Start(processinfo);
}
catch(Exception e)
{
// Unable to start the compiler
General.ShowErrorMessage("Unable to start the compiler (" + info.Name + "). " + e.GetType().Name + ": " + e.Message, MessageBoxButtons.OK);
return false;
}
// Wait for compiler to complete
process.WaitForExit();
deltatime = TimeSpan.FromTicks(process.ExitTime.Ticks - process.StartTime.Ticks);
Logger.WriteLogLine("Compiler process has finished.");
Logger.WriteLogLine("Compile time: " + deltatime.TotalSeconds.ToString("########0.00") + " seconds");
// Now find the error file
string errfile = Path.Combine(this.workingdir, ACS_ERROR_FILE);
if(File.Exists(errfile))
{
try
{
// Regex to find error lines
Regex errlinematcher = new Regex(":[0-9]+: ", RegexOptions.Compiled | RegexOptions.CultureInvariant);
// Read all lines
string[] errlines = File.ReadAllLines(errfile);
while(line < errlines.Length)
{
// Check line
string linestr = errlines[line];
Match match = errlinematcher.Match(linestr);
if(match.Success && (match.Index > 0))
{
CompilerError err = new CompilerError();
// The match without spaces and semicolon is the line number
string linenr = match.Value.Replace(":", "").Trim();
if(!int.TryParse(linenr, out err.linenumber))
err.linenumber = CompilerError.NO_LINE_NUMBER;
else
err.linenumber--;
// Everything before the match is the filename
err.filename = linestr.Substring(0, match.Index);
if(!Path.IsPathRooted(err.filename))
{
// Add working directory to filename
err.filename = Path.Combine(processinfo.WorkingDirectory, err.filename);
}
// Everything after the match is the description
err.description = linestr.Substring(match.Index + match.Length).Trim();
// Report the error
ReportError(err);
}
// Next line
line++;
}
}
catch(Exception e)
{
// Error reading errors (ironic, isn't it)
ReportError(new CompilerError("Failed to retrieve compiler error report. " + e.GetType().Name + ": " + e.Message));
}
}
return true;
}
19
View Source File : PK3StructuredReader.cs
License : GNU General Public License v3.0
Project Creator : anotak
License : GNU General Public License v3.0
Project Creator : anotak
protected virtual string MakeRelativePath(string anypath)
{
if(Path.IsPathRooted(anypath))
{
// Make relative
string lowpath = anypath.ToLowerInvariant();
string lowlocation = location.location.ToLowerInvariant();
if((lowpath.Length > (lowlocation.Length + 1)) && lowpath.StartsWith(lowlocation))
return anypath.Substring(lowlocation.Length + 1);
else
return anypath;
}
else
{
// Path is already relative
return anypath;
}
}
19
View Source File : ScriptContext.cs
License : GNU General Public License v3.0
Project Creator : anotak
License : GNU General Public License v3.0
Project Creator : anotak
internal string CheckFilename(string filename, string error_source)
{
// references used:
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
// http://gavinmiller.io/2016/creating-a-secure-sanitization-function/
// https://github.com/madrobby/zaru/blob/master/test/test_zaru.rb
filename = filename.Trim();
filename.Replace('/', '\\');
filename.Replace("\x00", "");
string[] unsafeChars = { "?", "%", "*", ":", "|", "<", ">", "\"", "..", @".\", @"\." };
foreach (string c in unsafeChars)
{
if (filename.Contains(c))
{
throw new ScriptRuntimeException("improper filename '" + filename + "' for " + error_source + ", contains '" + c + "'");
}
}
if (Path.IsPathRooted(filename) || filename.StartsWith("\\"))
{
throw new ScriptRuntimeException("improper filename '" + filename + "' for " + error_source +", must use relative path");
}
if (filename.StartsWith("."))
{
throw new ScriptRuntimeException("improper filename '" + filename + "' for " + error_source + ", can't start with '.'");
}
return filename;
}
19
View Source File : Program.cs
License : MIT License
Project Creator : anthonyreilly
License : MIT License
Project Creator : anthonyreilly
private static bool SaveConfig(GenConfig config, string filePath = null)
{
try
{
if (string.IsNullOrEmpty(filePath))
{
filePath = defaultConfigFilename;
}
//if using the default filename, or just a filename was given, set the path to the current directory
if (System.IO.Path.IsPathRooted(filePath))
{
string executabledirectory = Path.GetDirectoryName(System.Reflection.replacedembly.GetEntryreplacedembly().Location);
filePath = Path.Combine(executabledirectory, filePath);
}
Console.WriteLine($"Saving config file to {filePath}");
string contents = JsonConvert.SerializeObject(config, Formatting.Indented);
File.WriteAllText(filePath, contents, Encoding.Unicode);
return true;
}
catch (Exception ex)
{
Console.WriteLine("Error saving config file: " + ex.Message);
return false;
}
}
19
View Source File : Program.cs
License : MIT License
Project Creator : anthonyreilly
License : MIT License
Project Creator : anthonyreilly
private static GenConfig LoadConfig(string filePath = null)
{
try
{
if (string.IsNullOrEmpty(filePath))
{
filePath = defaultConfigFilename;
}
//if using the default filename, or just a filename was given, set the path to the current directory
if (System.IO.Path.IsPathRooted(filePath))
{
string executabledirectory = Path.GetDirectoryName(System.Reflection.replacedembly.GetEntryreplacedembly().Location);
filePath = Path.Combine(executabledirectory, filePath);
}
if (!File.Exists(filePath))
{
Console.WriteLine($"No config file found at {filePath}");
return null;
}
Console.WriteLine($"Loading config file {filePath}");
string contents = File.ReadAllText(filePath);
GenConfig config = JsonConvert.DeserializeObject<GenConfig>(contents);
return config;
}
catch (Exception ex)
{
Console.WriteLine("Error loading config file: " + ex.Message);
return null;
}
}
19
View Source File : ZipEntry.cs
License : GNU General Public License v3.0
Project Creator : anydream
License : GNU General Public License v3.0
Project Creator : anydream
public static string CleanName(string name)
{
if (name == null) {
return string.Empty;
}
if (Path.IsPathRooted(name)) {
// NOTE:
// for UNC names... \\machine\share\zoom\beet.txt gives \zoom\beet.txt
name = name.Substring(Path.GetPathRoot(name).Length);
}
name = name.Replace(@"\", "/");
while ((name.Length > 0) && (name[0] == '/')) {
name = name.Remove(0, 1);
}
return name;
}
19
View Source File : MdDocumentSet.cs
License : MIT License
Project Creator : ap0llo
License : MIT License
Project Creator : ap0llo
private string NormalizeRelativePath(string value)
{
if (Path.IsPathRooted(value))
throw new ArgumentException($"Path '{value}' is not a relative path", nameof(value));
// normalize directory separators to always use '/'
value = value.Replace(Path.DirectorySeparatorChar, '/').Replace(Path.AltDirectorySeparatorChar, '/');
// convert path into absolute path to remove any navigation elements (e.g. '..')
// use the current directory as root path (any valid path will do)
var rootPath = Environment.CurrentDirectory;
if (!rootPath.EndsWith("/"))
rootPath += "/";
var rootPathUri = new Uri(rootPath);
var fullPath = Path.Combine(rootPath, value);
var fullPathUri = new Uri(fullPath);
// ensure the relative path does not refer to a location outside the root directory
if (!fullPathUri.AbsolutePath.StartsWith(rootPathUri.AbsolutePath))
throw new ArgumentException($"Relative path '{value}' leaves the root directory");
// return a (normalized) relative path
return rootPathUri.MakeRelativeUri(fullPathUri).ToString();
}
19
View Source File : FileAppender.cs
License : Apache License 2.0
Project Creator : apache
License : Apache License 2.0
Project Creator : apache
protected virtual void OpenFile(string fileName, bool append)
{
if (LogLog.IsErrorEnabled)
{
// Internal check that the fileName preplaceded in is a rooted path
bool isPathRooted = false;
using (SecurityContext.Impersonate(this))
{
isPathRooted = Path.IsPathRooted(fileName);
}
if (!isPathRooted)
{
LogLog.Error(declaringType, "INTERNAL ERROR. OpenFile(" + fileName + "): File name is not fully qualified.");
}
}
lock (this)
{
Reset();
LogLog.Debug(declaringType, "Opening file for writing [" + fileName + "] append [" + append + "]");
// Save these for later, allowing retries if file open fails
m_fileName = fileName;
m_appendToFile = append;
LockingModel.CurrentAppender = this;
LockingModel.OpenFile(fileName, append, m_encoding);
m_stream = new LockingStream(LockingModel);
if (m_stream != null)
{
m_stream.AcquireLock();
try
{
SetQWForFiles(m_stream);
}
finally
{
m_stream.ReleaseLock();
}
}
WriteHeader();
}
}
19
View Source File : IOWrapper.cs
License : MIT License
Project Creator : arasplm
License : MIT License
Project Creator : arasplm
public bool PathIsPathRooted(string path)
{
return Path.IsPathRooted(path);
}
19
View Source File : SecretStoreBuilderExtensions.cs
License : MIT License
Project Creator : arcus-azure
License : MIT License
Project Creator : arcus-azure
public static SecretStoreBuilder AddDockerSecrets(this SecretStoreBuilder builder, string directoryPath, Func<string, string> mutateSecretName = null)
{
Guard.NotNull(builder, nameof(builder), "Requires a secret store builder to add the Docker secrets to");
Guard.NotNullOrWhitespace(directoryPath, nameof(directoryPath), "Requires a non-blank directory path inside the Docker container to locate the secrets");
Guard.For(() => !Path.IsPathRooted(directoryPath),
new ArgumentException("Requires an absolute directory path inside the Docker container to located the secrets", nameof(directoryPath)));
if (!Directory.Exists(directoryPath))
{
throw new DirectoryNotFoundException($"The directory {directoryPath} which is configured as secretsDirectoryPath does not exist.");
}
return AddDockerSecrets(builder, directoryPath, name: null, mutateSecretName: mutateSecretName);
}
19
View Source File : SecretStoreBuilderExtensions.cs
License : MIT License
Project Creator : arcus-azure
License : MIT License
Project Creator : arcus-azure
public static SecretStoreBuilder AddDockerSecrets(
this SecretStoreBuilder builder,
string directoryPath,
string name,
Func<string, string> mutateSecretName)
{
Guard.NotNull(builder, nameof(builder), "Requires a secret store builder to add the Docker secrets to");
Guard.NotNullOrWhitespace(directoryPath, nameof(directoryPath), "Requires a non-blank directory path inside the Docker container to locate the secrets");
Guard.For(() => !Path.IsPathRooted(directoryPath),
new ArgumentException("Requires an absolute directory path inside the Docker container to located the secrets", nameof(directoryPath)));
if (!Directory.Exists(directoryPath))
{
throw new DirectoryNotFoundException($"The directory {directoryPath} which is configured as secretsDirectoryPath does not exist.");
}
var configuration = new KeyPerFileConfigurationSource
{
FileProvider = new PhysicalFileProvider(directoryPath),
Optional = false
};
var provider = new KeyPerFileConfigurationProvider(configuration);
provider.Load();
return builder.AddProvider(new DockerSecretsSecretProvider(directoryPath), options =>
{
options.Name = name;
options.MutateSecretName = mutateSecretName;
});
}
19
View Source File : AppEngine.cs
License : GNU General Public License v3.0
Project Creator : arduosoft
License : GNU General Public License v3.0
Project Creator : arduosoft
public static AppEngine Create(string pluginPath, ILogger logger, ReflectionManager reflectionManager, IServiceCollection services, IConfigurationRoot configuration)
{
logger.LogInformation("CREATING RAWCMS APPENGINE");
var appEngine = new AppEngine(
logger,
basedir =>
{
logger.LogInformation($"original path {pluginPath}");
var folder = pluginPath;
if (!Path.IsPathRooted(pluginPath))
{
folder = basedir + pluginPath;
logger.LogInformation($"pluigin is relative. path is made absolyte using base app");
}
logger.LogInformation($"pluigin folder final value {folder}");
return Path.GetFullPath(folder);//Directory.GetDirectories(folder).FirstOrDefault();
},
reflectionManager,
configuration
);//Hardcoded for dev
appEngine.Init();
services.AddSingleton<ILogger>(x => logger);
services.AddSingleton<AppEngine>(x => appEngine);
appEngine.LoadPlugins(services);
return appEngine;
}
19
View Source File : LibrarySyntaxReceiver.cs
License : GNU General Public License v3.0
Project Creator : asimmon
License : GNU General Public License v3.0
Project Creator : asimmon
public void OnVisitSyntaxNode(GeneratorSyntaxContext context)
{
if (context.Node is not ClreplacedDeclarationSyntax clreplacedSyntax)
{
return;
}
if (ModelExtensions.GetDeclaredSymbol(context.SemanticModel, clreplacedSyntax) is not INamedTypeSymbol clreplacedModel)
{
return;
}
var attribute = FindImageLibraryAttribute(clreplacedModel);
if (attribute == null)
{
return;
}
if (!clreplacedSyntax.Modifiers.Any(SyntaxKind.PartialKeyword))
{
this._diagnostics.Add(Diagnostic.Create(DiagnosticsDescriptors.MissingPartialModifier, context.Node.GetLocation(), clreplacedModel.GetFullName()));
return;
}
if (clreplacedSyntax.Modifiers.Any(SyntaxKind.StaticKeyword))
{
this._diagnostics.Add(Diagnostic.Create(DiagnosticsDescriptors.StaticClreplacedNotAllowed, context.Node.GetLocation()));
return;
}
if (clreplacedSyntax.Parent is ClreplacedDeclarationSyntax)
{
this._diagnostics.Add(Diagnostic.Create(DiagnosticsDescriptors.NestedClreplacedNotAllowed, context.Node.GetLocation()));
return;
}
var rawImageDirPath = attribute.ConstructorArguments[0].Value as string;
if (rawImageDirPath != null && TryValidatePath(rawImageDirPath, out var validImageDirPath))
{
if (!Path.IsPathRooted(validImageDirPath) && clreplacedSyntax.SyntaxTree.FilePath is { Length: > 0 } codeFilePath && Path.GetDirectoryName(codeFilePath) is { Length: > 0 } codeDirPath)
{
validImageDirPath = Path.Combine(codeDirPath, validImageDirPath);
}
var modifierNames = string.Join(" ", clreplacedSyntax.Modifiers.Select(x => x.ValueText));
this._targetedClreplacedes.Add(new TargetedClreplacedInfo
{
ClreplacedName = clreplacedModel.Name,
NamespaceName = clreplacedModel.GetNamespace(),
ModifierNames = modifierNames,
ImageDirectoryPath = validImageDirPath,
SyntaxNode = context.Node,
});
}
else
{
this._diagnostics.Add(Diagnostic.Create(DiagnosticsDescriptors.InvalidDirectoryPath, context.Node.GetLocation(), rawImageDirPath));
}
}
19
View Source File : SearchPathSearcher.cs
License : MIT License
Project Creator : asmichi
License : MIT License
Project Creator : asmichi
public static string? FindFile(string fileName, bool searchCurrentDirectory, IReadOnlyList<string>? searchPath)
{
if (Path.IsPathRooted(fileName))
{
return fileName;
}
string? resolvedPath;
if (searchCurrentDirectory && TryResolveRelativePath(fileName, Environment.CurrentDirectory, out resolvedPath))
{
return resolvedPath;
}
if (searchPath != null && !ContainsPathSeparator(fileName))
{
for (int i = 0; i < searchPath.Count; i++)
{
if (TryResolveRelativePath(fileName, searchPath[i], out resolvedPath))
{
return resolvedPath;
}
}
}
return null;
}
19
View Source File : SearchPathSearcher.cs
License : MIT License
Project Creator : asmichi
License : MIT License
Project Creator : asmichi
private static bool TryResolveRelativePath(string fileName, ReadOnlySpan<char> baseDir, [NotNullWhen(true)] out string? resolvedPath)
{
Debug.replacedert(!Path.IsPathRooted(fileName));
var candidate = Path.Join(baseDir, fileName.replacedpan());
if (File.Exists(candidate))
{
resolvedPath = candidate;
return true;
}
else
{
resolvedPath = null;
return false;
}
}
19
View Source File : MSBuildProjectManager.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
internal static bool TryResolveConfigurationOutputPath(ProjectInstance projectInstance, out string path)
{
var intermediateOutputPath = projectInstance.GetPropertyValue(IntermediateOutputPathPropertyName);
if (string.IsNullOrEmpty(intermediateOutputPath))
{
path = null;
return false;
}
if (!Path.IsPathRooted(intermediateOutputPath))
{
// Relative path, need to convert to absolute.
var projectDirectory = projectInstance.GetPropertyValue(MSBuildProjectDirectoryPropertyName);
if (string.IsNullOrEmpty(projectDirectory))
{
// This should never be true but we're beign extra careful.
path = null;
return false;
}
intermediateOutputPath = Path.Combine(projectDirectory, intermediateOutputPath);
}
intermediateOutputPath = intermediateOutputPath
.Replace('\\', Path.DirectorySeparatorChar)
.Replace('/', Path.DirectorySeparatorChar);
path = Path.Combine(intermediateOutputPath, RazorConfigurationFileName);
return true;
}
19
View Source File : RemoteRazorProjectFileSystem.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
protected override string NormalizeAndEnsureValidPath(string path)
{
var absolutePath = path;
if (!FilePathRootedBy(absolutePath, _root))
{
if (Path.IsPathRooted(absolutePath))
{
// Existing path is already rooted, can't translate from relative to absolute.
return absolutePath;
}
if (path[0] == '/' || path[0] == '\\')
{
path = path.Substring(1);
}
absolutePath = _root + path;
}
absolutePath = _filePathNormalizer.Normalize(absolutePath);
return absolutePath;
}
19
View Source File : CsvSource.cs
License : Apache License 2.0
Project Creator : atata-framework
License : Apache License 2.0
Project Creator : atata-framework
public static TestCaseData[] Get<T>(string filePath, Type expectedResultType = null, string expectedResultName = "ExpectedResult")
{
string completeFilePath = Path.IsPathRooted(filePath)
? filePath
: Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filePath);
using (StreamReader streamReader = new StreamReader(completeFilePath))
using (CsvReader csvReader = new CsvReader(streamReader, Thread.CurrentThread.CurrentCulture))
{
TestCaseData[] dataItems = csvReader.GetRecords<T>().
Select(x => new TestCaseData(x)).
ToArray();
if (expectedResultType != null)
{
// Reset stream reader to beginning.
streamReader.BaseStream.Position = 0;
// Read the header line.
csvReader.Read();
object[] expectedResults = GetExpectedResults(csvReader, expectedResultType, expectedResultName).ToArray();
for (int i = 0; i < dataItems.Length; i++)
{
dataItems[i].Returns(expectedResults[i]);
}
}
return dataItems;
}
}
19
View Source File : JsonConfigFile.cs
License : Apache License 2.0
Project Creator : atata-framework
License : Apache License 2.0
Project Creator : atata-framework
public static string GetFullPath(string filePath = null, string environmentAlias = null)
{
string path = GetRelativePath(filePath, environmentAlias);
return Path.IsPathRooted(path)
? path
: Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path);
}
19
View Source File : ParsedTemplate.cs
License : MIT License
Project Creator : atifaziz
License : MIT License
Project Creator : atifaziz
void Import (ITextTemplatingEngineHost host, Directive includeDirective, string relativeToDirectory)
{
string fileName;
if (includeDirective.Attributes.Count > 1 || !includeDirective.Attributes.TryGetValue ("file", out fileName)) {
LogError ("Unexpected attributes in include directive", includeDirective.StartLocation);
return;
}
//try to resolve path relative to the file that included it
if (relativeToDirectory != null && !Path.IsPathRooted (fileName)) {
string possible = Path.Combine (relativeToDirectory, fileName);
if (File.Exists (possible))
fileName = Path.GetFullPath (possible);
}
string content, resolvedName;
if (host.LoadIncludeText (fileName, out content, out resolvedName))
Parse (host, new Tokeniser (resolvedName, content), true, true);
else
LogError ("Could not resolve include file '" + fileName + "'.", includeDirective.StartLocation);
}
19
View Source File : FileUtil.cs
License : MIT License
Project Creator : atifaziz
License : MIT License
Project Creator : atifaziz
public unsafe static string AbsoluteToRelativePath (string baseDirectoryPath, string absPath)
{
if (!Path.IsPathRooted (absPath) || string.IsNullOrEmpty (baseDirectoryPath))
return absPath;
absPath = GetFullPath (absPath);
baseDirectoryPath = GetFullPath (baseDirectoryPath).TrimEnd (Path.DirectorySeparatorChar);
fixed (char* bPtr = baseDirectoryPath, aPtr = absPath) {
var bEnd = bPtr + baseDirectoryPath.Length;
var aEnd = aPtr + absPath.Length;
char* lastStartA = aEnd;
char* lastStartB = bEnd;
int indx = 0;
// search common base path
var a = aPtr;
var b = bPtr;
while (a < aEnd) {
if (*a != *b)
break;
if (IsSeparator (*a)) {
indx++;
lastStartA = a + 1;
lastStartB = b;
}
a++;
b++;
if (b >= bEnd) {
if (a >= aEnd || IsSeparator (*a)) {
indx++;
lastStartA = a + 1;
lastStartB = b;
}
break;
}
}
if (indx == 0)
return absPath;
if (lastStartA >= aEnd)
return ".";
// handle case a: some/path b: some/path/deeper...
if (a >= aEnd) {
if (IsSeparator (*b)) {
lastStartA = a + 1;
lastStartB = b;
}
}
// look how many levels to go up into the base path
int goUpCount = 0;
while (lastStartB < bEnd) {
if (IsSeparator (*lastStartB))
goUpCount++;
lastStartB++;
}
var size = goUpCount * 2 + goUpCount + aEnd - lastStartA;
var result = new char [size];
fixed (char* rPtr = result) {
// go paths up
var r = rPtr;
for (int i = 0; i < goUpCount; i++) {
*(r++) = '.';
*(r++) = '.';
*(r++) = Path.DirectorySeparatorChar;
}
// copy the remaining absulute path
while (lastStartA < aEnd)
*(r++) = *(lastStartA++);
}
return new string (result);
}
}
19
View Source File : TemplateGenerator.cs
License : MIT License
Project Creator : atifaziz
License : MIT License
Project Creator : atifaziz
protected virtual string ResolvereplacedemblyReference (string replacedemblyReference)
{
if (System.IO.Path.IsPathRooted (replacedemblyReference))
return replacedemblyReference;
foreach (string referencePath in ReferencePaths) {
var path = System.IO.Path.Combine (referencePath, replacedemblyReference);
if (System.IO.File.Exists (path))
return path;
}
var replacedemblyName = new replacedemblyName(replacedemblyReference);
if (replacedemblyName.Version != null)//Load via GAC and return full path
return replacedembly.Load (replacedemblyName).Location;
if (!replacedemblyReference.EndsWith (".dll", StringComparison.OrdinalIgnoreCase) && !replacedemblyReference.EndsWith (".exe", StringComparison.OrdinalIgnoreCase))
return replacedemblyReference + ".dll";
return replacedemblyReference;
}
See More Examples