Here are the examples of the csharp api System.IO.Path.GetDirectoryName(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
11615 Examples
19
Source : MainWindow.xaml.cs
with GNU General Public License v3.0
from 00000vish
with GNU General Public License v3.0
from 00000vish
private void openSteamDesktopAuthAsync()
{
if (!SteamTwoProperties.jsonSetting.SDALinkSetting.Equals(""))
{
string exepath = SteamTwoProperties.jsonSetting.SDALinkSetting;
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = exepath;
psi.WorkingDirectory = Path.GetDirectoryName(exepath);
Process.Start(psi);
}
}
19
Source : Program.cs
with MIT License
from 0ffffffffh
with MIT License
from 0ffffffffh
static void Main(string[] args)
{
Process apache=null, backend=null, sbmon=null;
List<Process> memcachedInsts = null;
appExePath = System.Reflection.replacedembly.GetExecutingreplacedembly().Location;
appWorkDir = Path.GetDirectoryName(appExePath);
CheckAdminRights();
var procList = Process.GetProcesses();
foreach (var proc in procList)
{
if (stricmp(proc.ProcessName, "httpd") == 0)
{
Log("Httpd still running");
apache = proc;
}
else if (stricmp(proc.ProcessName, "sozluk_backend") == 0)
{
Log("Backend process still running");
backend = proc;
}
else if (stricmp(proc.ProcessName, "sbmon") == 0)
{
Log("Sbmon still running");
sbmon = proc;
}
else if (stricmp(proc.ProcessName, "memcached") == 0)
{
Log("A memcached instance found");
if (memcachedInsts == null)
memcachedInsts = new List<Process>();
memcachedInsts.Add(proc);
}
}
if (apache == null)
{
Log("starting httpd");
Run(HttpdExePath,string.Empty);
}
if (backend==null)
{
if (sbmon != null)
{
Log("there is no backend but sbmon. Sbmon killing");
sbmon.Kill();
}
if (memcachedInsts!=null)
{
Log("There some memcached instances. Killing em");
foreach (var mcp in memcachedInsts)
{
mcp.Kill();
}
}
Log("Starting up backend");
Run(BackendExePath, string.Empty);
}
Console.ReadKey();
}
19
Source : Config.cs
with MIT License
from 0ffffffffh
with MIT License
from 0ffffffffh
public static Config Get()
{
string key, val;
string[] optLines;
string workDir = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
if (!File.Exists(workDir + "\\.config"))
return conf;
if (conf != null)
return conf;
conf = new Config();
optLines = File.ReadAllLines(workDir + "\\.config");
if (optLines == null)
return conf;
foreach (var item in optLines)
{
var part = item.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
if (part != null && part.Length == 2)
{
key = part[0].Trim();
val = part[1].Trim();
switch (key)
{
case "memcached_port":
conf.MemcachedPort = TryConv<int>(val, 11211);
break;
case "memcached_path":
conf.MemcachedPath = val;
break;
case "sbmon_path":
conf.SbmonPath = val;
break;
case "log_level":
conf.LogLevel = TryConv<int>(val, (int)LogType.Critical);
break;
case "dbpwd":
conf.DbPreplacedword = val;
break;
case "test_mode":
conf.TestMode = TryConv<bool>(val, true);
break;
case "html_replacedet_root":
conf.HtmlContentRoot = val;
break;
case "cacheset_salt":
conf.CacheSetSalt = val;
break;
case "records_per_page":
conf.RecordCountPerPage = TryConv<int>(val, 40);
break;
case "basliks_per_page":
conf.BaslikCountPerPage = TryConv<int>(val, 15);
break;
}
}
}
optLines = null;
return conf;
}
19
Source : CelesteNetServerModule.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
public virtual void Save(string path = "") {
path = Path.GetFullPath(path.Nullify() ?? FilePath);
Logger.Log(LogLevel.INF, "settings", $"Saving {GetType().Name} to {path}");
string? dir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
Directory.CreateDirectory(dir);
using (Stream stream = File.OpenWrite(path + ".tmp"))
using (StreamWriter writer = new(stream))
Save(writer);
if (File.Exists(path))
File.Delete(path);
File.Move(path + ".tmp", path);
}
19
Source : FileSystemUserData.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
public void SaveRaw<T>(string path, T data) where T : notnull {
lock (GlobalLock) {
string? dir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
Directory.CreateDirectory(dir);
using (Stream stream = File.OpenWrite(path + ".tmp"))
using (StreamWriter writer = new(stream))
YamlHelper.Serializer.Serialize(writer, data, typeof(T));
if (File.Exists(path))
File.Delete(path);
File.Move(path + ".tmp", path);
}
}
19
Source : FileSystemUserData.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
public override Stream WriteFile(string uid, string name) {
string path = GetUserFilePath(uid, name);
string? dir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
Directory.CreateDirectory(dir);
if (File.Exists(path))
File.Delete(path);
return File.OpenWrite(path);
}
19
Source : FileSystemUserData.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
private void InsertFileRaw(string path, Stream stream) {
lock (GlobalLock) {
string? dir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
Directory.CreateDirectory(dir);
if (File.Exists(path))
File.Delete(path);
Stream target = File.OpenWrite(path);
stream.CopyTo(target);
}
}
19
Source : Program.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
public static void Main(string[] args) {
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;
string? serverPath = typeof(CelesteNetServer).replacedembly.Location;
if (!serverPath.IsNullOrEmpty() && !(serverPath = Path.GetDirectoryName(Path.GetFullPath(serverPath))).IsNullOrEmpty())
AppDomain.CurrentDomain.replacedemblyResolve += GetreplacedemblyResolverForDirectory(serverPath);
#if INMODDIR && NETFRAMEWORK
string? celestePath = Path.GetFullPath(Path.Combine("..", "..", "..", "..", "..", ".."));
if (!File.Exists(Path.Combine(celestePath, "Celeste.exe"))) {
celestePath = null;
} else {
AppDomain.CurrentDomain.replacedemblyResolve += GetreplacedemblyResolverForDirectory(celestePath);
}
#endif
MainMain(args);
}
19
Source : Program.cs
with GNU General Public License v3.0
from 00000vish
with GNU General Public License v3.0
from 00000vish
private static void luanchSteamTwo()
{
string exepath = AppDomain.CurrentDomain.BaseDirectory + "\\Steam Two.exe";
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = exepath;
psi.WorkingDirectory = Path.GetDirectoryName(exepath);
psi.Arguments = "startup";
Process.Start(psi);
}
19
Source : MainActivity.cs
with Microsoft Public License
from 0x0ade
with Microsoft Public License
from 0x0ade
protected override void OnStart()
{
base.OnStart();
Instance = this;
ActionBar.Hide();
// Load stub Steamworks.NET
Steamworks.SteamAPI.Init();
GamePath = null;
foreach (Java.IO.File root in GetExternalFilesDirs(null))
{
string path = Path.Combine(root.AbsolutePath, Game);
if (!File.Exists(path))
continue;
GamePath = path;
break;
}
if (!string.IsNullOrEmpty(GamePath))
{
System.Environment.CurrentDirectory = Path.GetDirectoryName(GamePath);
}
System.Environment.SetEnvironmentVariable("FNADROID", "1");
// Load our copy of FNA before the game gets a chance to run its copy.
RuntimeHelpers.RunClreplacedConstructor(typeof(Game).TypeHandle);
}
19
Source : Program.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
public static void Strip(string path, ReaderParameters readerParams = null) {
if (readerParams == null) {
DefaultreplacedemblyResolver asmResolver = new DefaultreplacedemblyResolver();
asmResolver.AddSearchDirectory(Path.GetDirectoryName(path));
readerParams = new ReaderParameters() {
replacedemblyResolver = asmResolver
};
}
ModuleDefinition module = ModuleDefinition.ReadModule(path, readerParams);
int changes = 0;
if ((module.Resources?.Count ?? 0) != 0) {
changes += module.Resources.Count;
module.Resources.Clear();
}
foreach (TypeDefinition type in module.Types)
Strip(ref changes, type);
if (changes != 0) {
module.Write(path);
}
}
19
Source : Program.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
static void Main(string[] args) {
// Required for the relative extra paths to work properly.
if (!File.Exists("MonoMod.RuntimeDetour.dll"))
Environment.CurrentDirectory = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
string inputDir, outputDir;
if (args.Length != 2 ||
!Directory.Exists(inputDir = args[0]) ||
!Directory.Exists(outputDir = args[1])) {
Console.Error.WriteLine("Usage: inputdir outputdir");
return;
}
// Check that the files exist.
if (!VerifyFile(out string inputXNA, inputDir, "Terraria.XNA.exe"))
return;
if (!VerifyFile(out string inputFNA, inputDir, "Terraria.FNA.exe"))
return;
// Strip or copy.
foreach (string path in Directory.GetFiles(inputDir)) {
if (!path.EndsWith(".exe") && !path.EndsWith(".dll")) {
Console.WriteLine($"Copying: {path}");
File.Copy(path, Path.Combine(outputDir, Path.GetFileName(path)));
continue;
}
Console.WriteLine($"Stripping: {path}");
Stripper.Strip(path);
}
// Generate hooks.
string hooksXNA = Path.Combine(outputDir, "Windows.Pre.dll");
string hooksFNA = Path.Combine(outputDir, "Mono.Pre.dll");
GenHooks(inputXNA, hooksXNA);
GenHooks(inputFNA, hooksFNA);
// Merge generated .dlls and MonoMod into one .dll per environment.
string[] extrasMod = {
"TerrariaHooks.dll",
"MonoMod.exe",
"MonoMod.RuntimeDetour.dll",
"MonoMod.Utils.dll"
};
Repack(hooksXNA, extrasMod, Path.Combine(outputDir, "Windows.dll"), "TerrariaHooks.dll");
File.Delete(hooksXNA);
Repack(hooksFNA, extrasMod, Path.Combine(outputDir, "Mono.dll"), "TerrariaHooks.dll");
File.Delete(hooksFNA);
}
19
Source : Program.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
static void Repack(string input, string[] extras, string output, string name = null) {
Console.Error.WriteLine($"Repacking: {input} -> {output}");
if (name == null)
name = Path.GetFileName(output);
string outputTmp = Path.Combine(Path.GetDirectoryName(output), name);
if (File.Exists(outputTmp))
File.Delete(outputTmp);
List<string> args = new List<string>();
args.Add($"/out:{outputTmp}");
args.Add(input);
foreach (string dep in extras)
if (!string.IsNullOrWhiteSpace(dep))
args.Add(dep.Trim());
RepackOptions options = new RepackOptions(args);
ILRepack repack = new ILRepack(options);
repack.Repack();
if (output != outputTmp) {
if (File.Exists(output))
File.Delete(output);
File.Move(outputTmp, output);
}
}
19
Source : XnaToFnaUtil.cs
with zlib License
from 0x0ade
with zlib License
from 0x0ade
public void ScanPath(string path) {
if (Directory.Exists(path)) {
// Use the directory as "dependency directory" and scan in it.
if (Directories.Contains(path))
// No need to scan the dir if the dir is scanned...
return;
RestoreBackup(path);
Log($"[ScanPath] Scanning directory {path}");
Directories.Add(path);
replacedemblyResolver.AddSearchDirectory(path); // Needs to be added manually as DependencyDirs was already added
// Most probably the actual game directory - let's just copy XnaToFna.exe to there to be referenced properly.
string xtfPath = Path.Combine(path, Path.GetFileName(Thisreplacedembly.Location));
if (Path.GetDirectoryName(Thisreplacedembly.Location) != path) {
Log($"[ScanPath] Found separate game directory - copying XnaToFna.exe and FNA.dll");
File.Copy(Thisreplacedembly.Location, xtfPath, true);
string dbExt = null;
if (File.Exists(Path.ChangeExtension(Thisreplacedembly.Location, "pdb")))
dbExt = "pdb";
if (File.Exists(Path.ChangeExtension(Thisreplacedembly.Location, "mdb")))
dbExt = "mdb";
if (dbExt != null)
File.Copy(Path.ChangeExtension(Thisreplacedembly.Location, dbExt), Path.ChangeExtension(xtfPath, dbExt), true);
if (File.Exists(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll")))
File.Copy(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll"), Path.Combine(path, "FNA.dll"), true);
else if (File.Exists(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll.tmp")))
File.Copy(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll.tmp"), Path.Combine(path, "FNA.dll"), true);
}
ScanPaths(Directory.GetFiles(path));
return;
}
if (File.Exists(path + ".xex")) {
if (!ExtractedXEX.Contains(path)) {
// Remove the original file - let XnaToFna unpack and handle it later.
File.Delete(path);
} else {
// XnaToFna will handle the .xex instead.
}
return;
}
if (path.EndsWith(".xex")) {
string pathTarget = path.Substring(0, path.Length - 4);
if (string.IsNullOrEmpty(Path.GetExtension(pathTarget)))
return;
using (Stream streamXEX = File.OpenRead(path))
using (BinaryReader reader = new BinaryReader(streamXEX))
using (Stream streamRAW = File.OpenWrite(pathTarget)) {
XEXImageData data = new XEXImageData(reader);
int offset = 0;
int size = data.m_memorySize;
// Check if this file is a PE containing an embedded PE.
if (data.m_memorySize > 0x10000) { // One default segment alignment.
using (MemoryStream streamMEM = new MemoryStream(data.m_memoryData))
using (BinaryReader mem = new BinaryReader(streamMEM)) {
if (mem.ReadUInt32() != 0x00905A4D) // MZ
goto WriteRaw;
// This is horrible.
streamMEM.Seek(0x00000280, SeekOrigin.Begin);
if (mem.ReadUInt64() != 0x000061746164692E) // ".idata\0\0"
goto WriteRaw;
streamMEM.Seek(0x00000288, SeekOrigin.Begin);
mem.ReadInt32(); // Virtual size; It's somewhat incorrect?
offset = mem.ReadInt32(); // Virtual offset.
// mem.ReadInt32(); // Raw size; Still incorrect.
// Let's just write everything...
size = data.m_memorySize - offset;
}
}
WriteRaw:
streamRAW.Write(data.m_memoryData, offset, size);
}
path = pathTarget;
ExtractedXEX.Add(pathTarget);
} else if (!path.EndsWith(".dll") && !path.EndsWith(".exe"))
return;
// Check if .dll is CLR replacedembly
replacedemblyName name;
try {
name = replacedemblyName.GetreplacedemblyName(path);
} catch {
return;
}
ReaderParameters modReaderParams = Modder.GenReaderParameters(false);
// Don't ReadWrite if the module being read is XnaToFna or a relink target.
bool isReadWrite =
#if !CECIL0_9
modReaderParams.ReadWrite =
#endif
path != Thisreplacedembly.Location &&
!Mappings.Exists(mappings => name.Name == mappings.Target);
// Only read debug info if it exists
if (!File.Exists(path + ".mdb") && !File.Exists(Path.ChangeExtension(path, "pdb")))
modReaderParams.ReadSymbols = false;
Log($"[ScanPath] Checking replacedembly {name.Name} ({(isReadWrite ? "rw" : "r-")})");
ModuleDefinition mod;
try {
mod = MonoModExt.ReadModule(path, modReaderParams);
} catch (Exception e) {
Log($"[ScanPath] WARNING: Cannot load replacedembly: {e}");
return;
}
bool add = !isReadWrite || name.Name == ThisreplacedemblyName;
if ((mod.Attributes & ModuleAttributes.ILOnly) != ModuleAttributes.ILOnly) {
// Mono.Cecil can't handle mixed mode replacedemblies.
Log($"[ScanPath] WARNING: Cannot handle mixed mode replacedembly {name.Name}");
if (MixedDeps == MixedDepAction.Stub) {
ModulesToStub.Add(mod);
add = true;
} else {
if (MixedDeps == MixedDepAction.Remove) {
RemoveDeps.Add(name.Name);
}
#if !CECIL0_9
mod.Dispose();
#endif
return;
}
}
if (add && !isReadWrite) { // XNA replacement
foreach (XnaToFnaMapping mapping in Mappings)
if (name.Name == mapping.Target) {
mapping.IsActive = true;
mapping.Module = mod;
foreach (string from in mapping.Sources) {
Log($"[ScanPath] Mapping {from} -> {name.Name}");
Modder.RelinkModuleMap[from] = mod;
}
}
} else if (!add) {
foreach (XnaToFnaMapping mapping in Mappings)
if (mod.replacedemblyReferences.Any(dep => mapping.Sources.Contains(dep.Name))) {
add = true;
Log($"[ScanPath] XnaToFna-ing {name.Name}");
goto BreakMappings;
}
}
BreakMappings:
if (add) {
Modules.Add(mod);
ModulePaths[mod] = path;
} else {
#if !CECIL0_9
mod.Dispose();
#endif
}
}
19
Source : XnaToFnaUtil.cs
with zlib License
from 0x0ade
with zlib License
from 0x0ade
public void RestoreBackup(string root, string origRoot) {
Log($"[RestoreBackup] Restoring from {origRoot} to {root}");
foreach (string origPath in Directory.EnumerateFiles(origRoot, "*", SearchOption.AllDirectories)) {
Directory.CreateDirectory(Path.GetDirectoryName(root + origPath.Substring(origRoot.Length)));
File.Copy(origPath, root + origPath.Substring(origRoot.Length), true);
}
}
19
Source : TestFileSystem.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
public void AddFile(string path, string content)
{
var dir = Path.GetDirectoryName(path) ?? string.Empty;
if (!this._directories.TryGetValue(dir, out var list))
{
list = new List<string>();
this._directories.Add(dir, list);
}
list.Add(path);
if(!this._files.TryAdd(path, content))
{
throw new Exception("File already exists: " + path);
}
}
19
Source : Program.cs
with MIT License
from 0xd4d
with MIT License
from 0xd4d
static DisasmJob[] GetJobs(DisasmInfo[] methods, string outputDir, FileOutputKind fileOutputKind, FilenameFormat filenameFormat, out string? baseDir) {
FilenameProvider filenameProvider;
var jobs = new List<DisasmJob>();
switch (fileOutputKind) {
case FileOutputKind.Stdout:
baseDir = null;
return new[] { new DisasmJob(() => (Console.Out, false), methods) };
case FileOutputKind.OneFile:
if (string.IsNullOrEmpty(outputDir))
throw new ApplicationException("Missing filename");
baseDir = Path.GetDirectoryName(outputDir);
return new[] { new DisasmJob(() => (File.CreateText(outputDir), true), methods) };
case FileOutputKind.OneFilePerType:
if (string.IsNullOrEmpty(outputDir))
throw new ApplicationException("Missing output dir");
baseDir = outputDir;
filenameProvider = new FilenameProvider(filenameFormat, baseDir, DASM_EXT);
var types = new Dictionary<uint, List<DisasmInfo>>();
foreach (var method in methods) {
if (!types.TryGetValue(method.TypeToken, out var typeMethods))
types.Add(method.TypeToken, typeMethods = new List<DisasmInfo>());
typeMethods.Add(method);
}
var allTypes = new List<List<DisasmInfo>>(types.Values);
allTypes.Sort((a, b) => StringComparer.Ordinal.Compare(a[0].TypeFullName, b[0].TypeFullName));
foreach (var typeMethods in allTypes) {
uint token = typeMethods[0].TypeToken;
var name = GetTypeName(typeMethods[0].TypeFullName);
var getTextWriter = CreateGetTextWriter(filenameProvider.GetFilename(token, name));
jobs.Add(new DisasmJob(getTextWriter, typeMethods.ToArray()));
}
return jobs.ToArray();
case FileOutputKind.OneFilePerMethod:
if (string.IsNullOrEmpty(outputDir))
throw new ApplicationException("Missing output dir");
baseDir = outputDir;
filenameProvider = new FilenameProvider(filenameFormat, baseDir, DASM_EXT);
foreach (var method in methods) {
uint token = method.MethodToken;
var name = method.MethodName.Replace('.', '_');
var getTextWriter = CreateGetTextWriter(filenameProvider.GetFilename(token, name));
jobs.Add(new DisasmJob(getTextWriter, new[] { method }));
}
return jobs.ToArray();
default:
throw new InvalidOperationException();
}
}
19
Source : Dumper.cs
with MIT License
from 13xforever
with MIT License
from 13xforever
public async Task DumpAsync(string output)
{
// check and create output folder
var dumpPath = output;
while (!string.IsNullOrEmpty(dumpPath) && !Directory.Exists(dumpPath))
{
var parent = Path.GetDirectoryName(dumpPath);
if (parent == null || parent == dumpPath)
dumpPath = null;
else
dumpPath = parent;
}
if (filesystemStructure is null)
(filesystemStructure, emptyDirStructure) = GetFilesystemStructure();
var validators = GetValidationInfo();
if (!string.IsNullOrEmpty(dumpPath))
{
var root = Path.GetPathRoot(Path.GetFullPath(output));
var drive = DriveInfo.GetDrives().FirstOrDefault(d => d?.RootDirectory.FullName.StartsWith(root) ?? false);
if (drive != null)
{
var spaceAvailable = drive.AvailableFreeSpace;
TotalFileSize = filesystemStructure.Sum(f => f.Length);
var diff = TotalFileSize + 100 * 1024 - spaceAvailable;
if (diff > 0)
Log.Warn($"Target drive might require {diff.replacedtorageUnit()} of additional free space");
}
}
foreach (var dir in emptyDirStructure)
Log.Trace($"Empty dir: {dir}");
foreach (var file in filesystemStructure)
Log.Trace($"0x{file.StartSector:x8}: {file.Filename} ({file.Length})");
var outputPathBase = Path.Combine(output, OutputDir);
if (!Directory.Exists(outputPathBase))
Directory.CreateDirectory(outputPathBase);
TotalFileCount = filesystemStructure.Count;
TotalSectors = discReader.TotalClusters;
Log.Debug("Using decryption key: " + allMatchingKeys.First().DecryptedKeyId);
var decryptionKey = allMatchingKeys.First().DecryptedKey;
var sectorSize = (int)discReader.ClusterSize;
var unprotectedRegions = driveStream.GetUnprotectedRegions();
ValidationStatus = true;
foreach (var dir in emptyDirStructure)
{
try
{
if (Cts.IsCancellationRequested)
return;
var convertedName = Path.DirectorySeparatorChar == '\\' ? dir : dir.Replace('\\', Path.DirectorySeparatorChar);
var outputName = Path.Combine(outputPathBase, convertedName);
if (!Directory.Exists(outputName))
{
Log.Debug("Creating empty directory " + outputName);
Directory.CreateDirectory(outputName);
}
}
catch (Exception ex)
{
Log.Error(ex);
BrokenFiles.Add((dir, "Unexpected error: " + ex.Message));
}
}
foreach (var file in filesystemStructure)
{
try
{
if (Cts.IsCancellationRequested)
return;
Log.Info($"Reading {file.Filename} ({file.Length.replacedtorageUnit()})");
CurrentFileNumber++;
var convertedFilename = Path.DirectorySeparatorChar == '\\' ? file.Filename : file.Filename.Replace('\\', Path.DirectorySeparatorChar);
var inputFilename = Path.Combine(input, convertedFilename);
if (!File.Exists(inputFilename))
{
Log.Error($"Missing {file.Filename}");
BrokenFiles.Add((file.Filename, "missing"));
continue;
}
var outputFilename = Path.Combine(outputPathBase, convertedFilename);
var fileDir = Path.GetDirectoryName(outputFilename);
if (!Directory.Exists(fileDir))
{
Log.Debug("Creating directory " + fileDir);
Directory.CreateDirectory(fileDir);
}
var error = false;
var expectedHashes = (
from v in validators
where v.Files.ContainsKey(file.Filename)
select v.Files[file.Filename].Hashes
).ToList();
var lastHash = "";
var tries = 2;
do
{
try
{
tries--;
using var outputStream = File.Open(outputFilename, FileMode.Create, FileAccess.Write, FileShare.Read);
using var inputStream = File.Open(inputFilename, FileMode.Open, FileAccess.Read, FileShare.Read);
using var decrypter = new Decrypter(inputStream, driveStream, decryptionKey, file.StartSector, sectorSize, unprotectedRegions);
Decrypter = decrypter;
await decrypter.CopyToAsync(outputStream, 8 * 1024 * 1024, Cts.Token).ConfigureAwait(false);
outputStream.Flush();
var resultHashes = decrypter.GetHashes();
var resultMd5 = resultHashes["MD5"];
if (decrypter.WasEncrypted && decrypter.WasUnprotected)
Log.Debug("Partially decrypted " + file.Filename);
else if (decrypter.WasEncrypted)
Log.Debug("Decrypted " + file.Filename);
if (!expectedHashes.Any())
{
if (ValidationStatus == true)
ValidationStatus = null;
}
else if (!IsMatch(resultHashes, expectedHashes))
{
error = true;
var msg = "Unexpected hash: " + resultMd5;
if (resultMd5 == lastHash || decrypter.LastBlockCorrupted)
{
Log.Error(msg);
BrokenFiles.Add((file.Filename, "corrupted"));
break;
}
Log.Warn(msg + ", retrying");
}
lastHash = resultMd5;
}
catch (Exception e)
{
Log.Error(e, e.Message);
error = true;
}
} while (error && tries > 0 && !Cts.IsCancellationRequested);
}
catch (Exception ex)
{
Log.Error(ex);
BrokenFiles.Add((file.Filename, "Unexpected error: " + ex.Message));
}
}
Log.Info("Completed");
}
19
Source : Dumper.cs
with MIT License
from 13xforever
with MIT License
from 13xforever
public void DetectDisc(string inDir = "", Func<Dumper, string> outputDirFormatter = null)
{
outputDirFormatter ??= d => $"[{d.ProductCode}] {d.replacedle}";
string discSfbPath = null;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
var drives = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.CDRom && d.IsReady);
if (string.IsNullOrEmpty(inDir))
{
foreach (var drive in drives)
{
discSfbPath = Path.Combine(drive.Name, "PS3_DISC.SFB");
if (!File.Exists(discSfbPath))
continue;
input = drive.Name;
Drive = drive.Name[0];
break;
}
}
else
{
discSfbPath = Path.Combine(inDir, "PS3_DISC.SFB");
if (File.Exists(discSfbPath))
{
input = Path.GetPathRoot(discSfbPath);
Drive = discSfbPath[0];
}
}
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
if (string.IsNullOrEmpty(inDir))
inDir = "/media";
discSfbPath = IOEx.GetFilepaths(inDir, "PS3_DISC.SFB", 2).FirstOrDefault();
if (!string.IsNullOrEmpty(discSfbPath))
input = Path.GetDirectoryName(discSfbPath);
}
else
throw new NotImplementedException("Current OS is not supported");
if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(discSfbPath))
throw new DriveNotFoundException("No valid PS3 disc was detected. Disc must be detected and mounted.");
Log.Info("Selected disc: " + input);
discSfbData = File.ReadAllBytes(discSfbPath);
var replacedleId = CheckDiscSfb(discSfbData);
var paramSfoPath = Path.Combine(input, "PS3_GAME", "PARAM.SFO");
if (!File.Exists(paramSfoPath))
throw new InvalidOperationException($"Specified folder is not a valid PS3 disc root (param.sfo is missing): {input}");
using (var stream = File.Open(paramSfoPath, FileMode.Open, FileAccess.Read, FileShare.Read))
ParamSfo = ParamSfo.ReadFrom(stream);
CheckParamSfo(ParamSfo);
if (replacedleId != ProductCode)
Log.Warn($"Product codes in ps3_disc.sfb ({replacedleId}) and in param.sfo ({ProductCode}) do not match");
// todo: maybe use discutils instead to read TOC as one block
var files = IOEx.GetFilepaths(input, "*", SearchOption.AllDirectories);
DiscFilenames = new List<string>();
var totalFilesize = 0L;
var rootLength = input.Length;
foreach (var f in files)
{
try { totalFilesize += new FileInfo(f).Length; } catch { }
DiscFilenames.Add(f.Substring(rootLength));
}
TotalFileSize = totalFilesize;
TotalFileCount = DiscFilenames.Count;
OutputDir = new string(outputDirFormatter(this).ToCharArray().Where(c => !InvalidChars.Contains(c)).ToArray());
Log.Debug($"Output: {OutputDir}");
}
19
Source : TemplateEngin.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static string TranslateUrl(string url, string baseDir) {
if (string.IsNullOrEmpty(baseDir))
{
baseDir = AppContext.BaseDirectory + "/";
if (url.StartsWith(AppContext.BaseDirectory)) url = url.Substring(AppContext.BaseDirectory.Length).TrimStart('/');
}
if (string.IsNullOrEmpty(url)) return Path.GetDirectoryName(baseDir);
if (url.StartsWith("~/")) url = url.Substring(1);
if (url.StartsWith("/")) return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(baseDir), url.TrimStart('/')));
if (url.StartsWith("\\")) return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(baseDir), url.TrimStart('\\')));
if (url.IndexOf(":\\") != -1) return url;
return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(baseDir), url));
}
19
Source : SlnPackagesConfigTest.cs
with MIT License
from 3F
with MIT License
from 3F
[Fact]
public void SlnPackagesConfigTest6()
{
const string _IN_DIR = @"PackagesConfig\sln\4\";
const string _IN_PKG_LEGACY = _IN_DIR + @"packages\";
using Sln l = new(TestData.ROOT + _IN_DIR + "test.sln", SlnItems.PackagesConfigLegacy);
replacedert.Equal(3, l.Result.PackagesConfigs.Count());
replacedert.Equal(2, l.Result.Projecreplacedems.Count());
PackagesConfig pkg1 = l.Result.PackagesConfigs.First(p =>
p.File.Contains(Path.GetDirectoryName(l.Result.Projecreplacedems.ElementAt(0).fullPath))
);
PackagesConfig pkg2 = l.Result.PackagesConfigs.First(p =>
p.File.Contains(Path.GetDirectoryName(l.Result.Projecreplacedems.ElementAt(1).fullPath))
);
PackagesConfig pkg3 = l.Result.PackagesConfigs.First(p =>
p.File.Contains(_IN_PKG_LEGACY)
);
replacedert.Single(pkg1.Packages);
IPackageInfo info1 = pkg1.GetPackage("LX4Cnh");
replacedert.Equal("1.1.0", info1.Version);
replacedert.Equal("net45", info1.MetaTFM);
replacedert.Single(pkg2.Packages);
IPackageInfo info2 = pkg2.GetPackage("LX4Cnh");
replacedert.Equal("1.1.0", info2.Version);
replacedert.Equal("net40", info2.MetaTFM);
replacedert.Single(pkg3.Packages);
IPackageInfo info3 = pkg3.GetPackage("LX4Cnh");
replacedert.Equal("1.1.0", info3.Version);
replacedert.Equal("net472", info3.MetaTFM);
}
19
Source : SlnPackagesConfigTest.cs
with MIT License
from 3F
with MIT License
from 3F
[Fact]
public void SlnPackagesConfigTest7()
{
const string _IN_DIR = @"PackagesConfig\sln\4\";
const string _IN_PKG_LEGACY = _IN_DIR + @"packages\";
using Sln l = new(TestData.ROOT + _IN_DIR + "test.sln", SlnItems.PackagesConfigSolution | SlnItems.PackagesConfigLegacy);
replacedert.Equal(4, l.Result.PackagesConfigs.Count());
replacedert.Equal(2, l.Result.Projecreplacedems.Count());
PackagesConfig pkg1 = l.Result.PackagesConfigs.First(p =>
p.File.Contains(Path.GetDirectoryName(l.Result.Projecreplacedems.ElementAt(0).fullPath))
);
PackagesConfig pkg2 = l.Result.PackagesConfigs.First(p =>
p.File.Contains(Path.GetDirectoryName(l.Result.Projecreplacedems.ElementAt(1).fullPath))
);
PackagesConfig pkg3 = l.Result.PackagesConfigs.First(p =>
p.File.Contains(_IN_PKG_LEGACY)
);
replacedert.Single(pkg1.Packages);
IPackageInfo info1 = pkg1.GetPackage("LX4Cnh");
replacedert.Equal("1.1.0", info1.Version);
replacedert.Equal("net45", info1.MetaTFM);
replacedert.Single(pkg2.Packages);
IPackageInfo info2 = pkg2.GetPackage("LX4Cnh");
replacedert.Equal("1.1.0", info2.Version);
replacedert.Equal("net40", info2.MetaTFM);
replacedert.Single(pkg3.Packages);
IPackageInfo info3 = pkg3.GetPackage("LX4Cnh");
replacedert.Equal("1.1.0", info3.Version);
replacedert.Equal("net472", info3.MetaTFM);
PackagesConfig pkg4 = l.Result.PackagesConfigs.First(p =>
!p.File.Contains(_IN_PKG_LEGACY)
);
replacedert.Single(pkg4.Packages);
IPackageInfo info4 = pkg4.GetPackage("vsSolutionBuildEvent");
replacedert.Equal("1.14.1.1", info4.Version);
replacedert.Equal("vsSolutionBuildEvent", info4.MetaOutput);
}
19
Source : StringExtension.cs
with MIT License
from 3F
with MIT License
from 3F
public static string GetDirectoryFromFile(this string file)
{
if(file != null) {
file = Path.GetDirectoryName(file);
}
return file.DirectoryPathFormat();
}
19
Source : PackagesConfigLocator.cs
with MIT License
from 3F
with MIT License
from 3F
private static IEnumerable<string> FindLegacyConfigs(ISlnResult sln)
{
string dfile = Path.GetFullPath(Path.Combine(sln.SolutionDir, DIR, PackagesConfig.FNAME));
if(File.Exists(dfile)) yield return dfile;
if(sln.Projecreplacedems != null)
foreach(var prj in sln.Projecreplacedems)
{
string input = Path.Combine(Path.GetDirectoryName(prj.fullPath), PackagesConfig.FNAME);
if(File.Exists(input)) yield return input;
}
}
19
Source : AssetBundleManager.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
public replacedetBundle Loadreplacedet(string replacedetName)
{
string replacedetBundleName;
if (localreplacedetBundleConfig.replacedetBundleRuleTypeDict[replacedetName] == replacedetBundleRuleType.File)
{
replacedetBundleName = $"{MD5Util.ComputeMD5(replacedetName)}.unity3d";
}
else
{
replacedetBundleName = $"{MD5Util.ComputeMD5(Path.GetDirectoryName(replacedetName).Replace("\\", "/"))}.unity3d";
}
if (replacedetBundles.ContainsKey(replacedetBundleName))
{
return (replacedetBundle)replacedetBundles[replacedetBundleName];
}
else
{
replacedetBundle replacedetBundle = replacedetBundle.LoadFromFile($"{PathUtil.GetPath(PathType.PersistentDataPath, "Res", PathUtil.GetPlatformForreplacedetBundle())}/{replacedetBundleName}");
string[] dependencies = replacedetBundleManifest.GetAllDependencies(replacedetBundleName);
foreach (string item in dependencies)
{
replacedetBundles.Add(item, replacedetBundle.LoadFromFile($"{PathUtil.GetPath(PathType.PersistentDataPath, "Res", PathUtil.GetPlatformForreplacedetBundle())}/{item}"));
}
replacedetBundles.Add(replacedetBundleName, replacedetBundle);
return replacedetBundle;
}
}
19
Source : DownloadFile.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
public bool Downloading()
{
if (File.Exists(downloadData.path))
{
currentSize = downloadData.size;
return true;
}
long position = 0;
string tempPath = downloadData.path + ".temp";
if (File.Exists(tempPath))
{
using (FileStream fileStream = new FileStream(tempPath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
{
position = fileStream.Length;
fileStream.Seek(position, SeekOrigin.Current);
if (position == downloadData.size)
{
if (File.Exists(downloadData.path))
{
File.Delete(downloadData.path);
}
File.Move(tempPath, downloadData.path);
currentSize = position;
return true;
}
}
}
else
{
PathUtil.GetPath(PathType.PersistentDataPath, Path.GetDirectoryName(downloadData.path));
using (FileStream fileStream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
{
HttpWebRequest httpWebRequest = null;
HttpWebResponse httpWebResponse = null;
try
{
httpWebRequest = (HttpWebRequest)WebRequest.Create(downloadData.url);
httpWebRequest.ReadWriteTimeout = readWriteTimeout;
httpWebRequest.Timeout = timeout;
if (position > 0)
{
httpWebRequest.AddRange((int)position);
}
httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (Stream stream = httpWebResponse.GetResponseStream())
{
stream.ReadTimeout = timeout;
long currentSize = position;
byte[] bytes = new byte[fileReadLength];
int readSize = stream.Read(bytes, 0, fileReadLength);
while (readSize > 0)
{
fileStream.Write(bytes, 0, readSize);
currentSize += readSize;
if (currentSize == downloadData.size)
{
if (File.Exists(downloadData.path))
{
File.Delete(downloadData.path);
}
File.Move(tempPath, downloadData.path);
}
this.currentSize = currentSize;
readSize = stream.Read(bytes, 0, fileReadLength);
}
}
}
catch
{
if (File.Exists(tempPath))
{
File.Delete(tempPath);
}
if (File.Exists(downloadData.path))
{
File.Delete(downloadData.path);
}
state = DownloadState.Error;
error = "文件下载失败";
}
finally
{
if (httpWebRequest != null)
{
httpWebRequest.Abort();
httpWebRequest = null;
}
if (httpWebResponse != null)
{
httpWebResponse.Dispose();
httpWebResponse = null;
}
}
}
}
if (state == DownloadState.Error)
{
return false;
}
return true;
}
19
Source : ServiceCollectionExtension.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
public static IServiceCollection AddSwaggerGeneration(this IServiceCollection services, OpenApiContact apiContact, string swaggerreplacedle, Type callerType)
{
return services.AddSwaggerGen(options =>
{
// Resolve the temporary IApiVersionDescriptionProvider service
var provider = services.BuildServiceProvider().GetRequiredService<IApiVersionDescriptionProvider>();
// Add a swagger doreplacedent for each discovered API version
foreach (var description in provider.ApiVersionDescriptions)
{
options.SwaggerDoc(description.GroupName, new OpenApiInfo
{
replacedle = swaggerreplacedle + $" {description.ApiVersion}",
Version = description.ApiVersion.ToString(),
Contact = apiContact
});
}
// Add a custom filter for setting the default values
options.OperationFilter<SwaggerDefaultValues>();
// Tells swagger to pick up the output XML doreplacedent file
options.IncludeXmlComments(Path.Combine(Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location), $"{callerType.replacedembly.GetName().Name}.xml"));
});
}
19
Source : AuditoriumLayoutRepository.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
private static string GetExecutingreplacedemblyDirectoryFullPath()
{
var directoryName = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().CodeBase);
if (directoryName.StartsWith(@"file:\"))
{
directoryName = directoryName.Substring(6);
}
if (directoryName.StartsWith(@"file:/"))
{
directoryName = directoryName.Substring(5);
}
return directoryName;
}
19
Source : AuditoriumLayoutRepository.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
private static string GetExecutingreplacedemblyDirectoryFullPath()
{
var directoryName = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
if (directoryName != null && directoryName.StartsWith(@"file:\"))
{
directoryName = directoryName.Substring(6);
}
if (directoryName != null && directoryName.StartsWith(@"file:/"))
{
directoryName = directoryName.Substring(5);
}
return directoryName;
}
19
Source : ReservationsProvider.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
private static string GetExecutingreplacedemblyDirectoryFullPath()
{
var directoryName = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
if (directoryName != null && directoryName.StartsWith(@"file:\"))
{
directoryName = directoryName.Substring(6);
}
if (directoryName.StartsWith(@"file:/"))
{
directoryName = directoryName.Substring(5);
}
return directoryName;
}
19
Source : CreateScriptUtil.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
public static string GetSelectedPath()
{
//默认路径为replacedets
string selectedPath = PathUtil.GetPath(PathType.DataPath);
//遍历选中的资源以返回路径
foreach (Object item in Selection.GetFiltered(typeof(Object), SelectionMode.replacedets))
{
selectedPath = replacedetDatabase.GetreplacedetPath(item);
if (!string.IsNullOrEmpty(selectedPath) && File.Exists(selectedPath))
{
selectedPath = Path.GetDirectoryName(selectedPath);
break;
}
}
return selectedPath;
}
19
Source : WebContentFolderHelper.cs
with MIT License
from 52ABP
with MIT License
from 52ABP
public static string CalculateContentRootFolder()
{
var corereplacedemblyDirectoryPath = Path.GetDirectoryName(typeof(BookListCoreModule).Getreplacedembly().Location);
if (corereplacedemblyDirectoryPath == null)
{
throw new Exception("Could not find location of Cloud.BookList.Core replacedembly!");
}
var directoryInfo = new DirectoryInfo(corereplacedemblyDirectoryPath);
while (!DirectoryContains(directoryInfo.FullName, "Cloud.BookList.sln"))
{
if (directoryInfo.Parent == null)
{
throw new Exception("Could not find content root folder!");
}
directoryInfo = directoryInfo.Parent;
}
var webMvcFolder = Path.Combine(directoryInfo.FullName, "src", "Cloud.BookList.Web.Mvc");
if (Directory.Exists(webMvcFolder))
{
return webMvcFolder;
}
var webHostFolder = Path.Combine(directoryInfo.FullName, "src", "Cloud.BookList.Web.Host");
if (Directory.Exists(webHostFolder))
{
return webHostFolder;
}
throw new Exception("Could not find root folder of the web project!");
}
19
Source : WebContentFolderHelper.cs
with MIT License
from 52ABP
with MIT License
from 52ABP
public static string CalculateContentRootFolder()
{
var corereplacedemblyDirectoryPath = Path.GetDirectoryName(typeof(PhoneBookCoreModule).Getreplacedembly().Location);
if (corereplacedemblyDirectoryPath == null)
{
throw new Exception("Could not find location of SPACore.PhoneBook.Core replacedembly!");
}
var directoryInfo = new DirectoryInfo(corereplacedemblyDirectoryPath);
while (!DirectoryContains(directoryInfo.FullName, "SPACore.PhoneBook.sln"))
{
if (directoryInfo.Parent == null)
{
throw new Exception("Could not find content root folder!");
}
directoryInfo = directoryInfo.Parent;
}
var webMvcFolder = Path.Combine(directoryInfo.FullName, "src", "SPACore.PhoneBook.Web.Mvc");
if (Directory.Exists(webMvcFolder))
{
return webMvcFolder;
}
var webHostFolder = Path.Combine(directoryInfo.FullName, "src", "SPACore.PhoneBook.Web.Host");
if (Directory.Exists(webHostFolder))
{
return webHostFolder;
}
throw new Exception("Could not find root folder of the web project!");
}
19
Source : Menu_Base.cs
with MIT License
from 5minlab
with MIT License
from 5minlab
protected static bool PreExecute() {
string lastDir = "";
if (lastFilePath != "") {
lastDir = Path.GetDirectoryName(lastFilePath);
}
var fp = EditorUtility.OpenFilePanel("select config file", lastDir, "json");
if (fp == "") {
return false;
}
lastFilePath = fp;
return true;
}
19
Source : Menu_Build.cs
with MIT License
from 5minlab
with MIT License
from 5minlab
private void OnWizardCreate() {
// 빌드 저장할 위치 선택
string lastDir = "";
if (lastOutputFilePath != "") {
lastDir = Path.GetDirectoryName(lastOutputFilePath);
}
var fp = EditorUtility.SaveFilePanel("select output filepath", lastDir, "build.exe", "");
if (fp == "") {
return;
}
EntryPoint.BuildCommon(configFilePath, fp);
}
19
Source : AdaptationBaseDrawer.cs
with MIT License
from 5argon
with MIT License
from 5argon
void CreateAnimator(bool forPortrait)
{
AdaptationBase adaptation = (AdaptationBase)target;
Animator animator = adaptation.gameObject.GetComponent<Animator>();
var incompletePath = GetSaveControllerPath(adaptation.gameObject);
if (string.IsNullOrEmpty(incompletePath)) return;
var prefix = Path.GetFileNameWithoutExtension(incompletePath);
var path = $"{Path.GetDirectoryName(incompletePath)}{Path.DirectorySeparatorChar}{prefix}Adaptation.controller";
var controller = AnimatorController.CreateAnimatorControllerAtPath(path);
replacedetDatabase.Importreplacedet(path);
animator.runtimeAnimatorController = controller;
var normalStateClip = AnimatorController.AllocateAnimatorClip($"{prefix}NormalState");
var adaptedStateClip = AnimatorController.AllocateAnimatorClip($"{prefix}AdaptedState");
replacedetDatabase.AddObjectToreplacedet(normalStateClip, controller);
replacedetDatabase.AddObjectToreplacedet(adaptedStateClip, controller);
replacedetDatabase.Importreplacedet(path);
adaptation.replacedignAdaptationClips(normalStateClip, adaptedStateClip, forPortrait);
var ly = controller.layers[0].stateMachine;
var emptyState = ly.AddState("Empty State");
ly.defaultState = emptyState;
var normalGraphState = controller.AddMotion(normalStateClip, 0);
var adaptedGraphState = controller.AddMotion(adaptedStateClip, 0);
string GetSaveControllerPath(GameObject go)
{
var defaultName = go.name;
var message = $"Create a new adaptation replacedets for the game object '{defaultName}'\nThis name will be a prefix for all replacedets.";
return EditorUtility.SaveFilePanelInProject("New Animation Contoller", defaultName, "", message);
}
}
19
Source : OpenFolderDialog.cs
with MIT License
from 91Act
with MIT License
from 91Act
private DialogResult ShowLegacyDialog(IWin32Window owner)
{
using (var frm = new FolderBrowserDialog())
{
if (this.InitialFolder != null) { frm.SelectedPath = this.InitialFolder; }
if (frm.ShowDialog(owner) == DialogResult.OK)
{
this.Folder = Path.GetDirectoryName(frm.SelectedPath);
return DialogResult.OK;
}
else
{
return DialogResult.Cancel;
}
}
}
19
Source : PointCloudToMeshComponentFull.cs
with GNU Lesser General Public License v3.0
from 9and3
with GNU Lesser General Public License v3.0
from 9and3
protected override void SolveInstance(IGH_DataAccess DA) {
int Downsample = 5000;
int NormalsNeighbours = 100;
bool debug = false;
int maximumDeptOfReconstructionSurfaceTree = 8;
int targetWidthOfTheFinestLevelOctree = 0;
double ratioBetweenReconCubeAndBBCubeStd = 1.1;
bool ReconstructorUsingLinearInterpolation = false;
DA.GetData(1, ref Downsample);
DA.GetData(2, ref NormalsNeighbours);
DA.GetData(3, ref debug);
DA.GetData(4, ref maximumDeptOfReconstructionSurfaceTree);
DA.GetData(5, ref targetWidthOfTheFinestLevelOctree);
DA.GetData(6, ref ratioBetweenReconCubeAndBBCubeStd);
DA.GetData(7, ref ReconstructorUsingLinearInterpolation);
//Guid to PointCloud
//PointCloud c = new PointCloud();
PointCloudGH c = new PointCloudGH();
string debugInfo = debug ? "1" : "0";
if (DA.GetData(0, ref c)) {
if (!c.IsValid) return;
if (c.Value.Count==0) return;
Downsample = Math.Min(Downsample, c.Value.Count);
// var watch = System.Diagnostics.Stopwatch.StartNew();
// the code that you want to measure comes here
/////////////////////////////////////////////////////////////////
//Get Directory
/////////////////////////////////////////////////////////////////
string replacedemblyLocation = System.Reflection.replacedembly.GetExecutingreplacedembly().Location;
string replacedemblyPath = System.IO.Path.GetDirectoryName(replacedemblyLocation);
/////////////////////////////////////////////////////////////////
//write PointCloud to PLY
/////////////////////////////////////////////////////////////////
PlyReaderWriter.PlyWriter.SavePLY(c.Value, replacedemblyPath + @"\in.ply");
//Rhino.RhinoApp.WriteLine("PointCloudToMesh. Saved Input: " + replacedemblyPath + @"\in.ply");
//watch.Stop();
//Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());
/////////////////////////////////////////////////////////////////
//Ply to Mesh to Obj
/////////////////////////////////////////////////////////////////
//watch = System.Diagnostics.Stopwatch.StartNew();
//tring argument = replacedemblyPath + "TestVisualizer.exe " + "-1 " + "100";//--asci
string argument = " "+Downsample.ToString()+ " " + NormalsNeighbours.ToString() + " " + debugInfo + " " + maximumDeptOfReconstructionSurfaceTree.ToString() + " " + targetWidthOfTheFinestLevelOctree.ToString() + " " + ratioBetweenReconCubeAndBBCubeStd.ToString() + " " + Convert.ToInt32(ReconstructorUsingLinearInterpolation).ToString();
//--asci
// Rhino.RhinoApp.WriteLine("PointCloudToMesh. Arguments: " + argument );
// Rhino.RhinoApp.WriteLine("PointCloudToMesh. Directory: " + replacedemblyPath + @"\TestVisualizer.exe");
if (debug) {
var proc = new System.Diagnostics.Process {
StartInfo = new System.Diagnostics.ProcessStartInfo {
FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
Arguments = argument,
//UseShellExecute = false,
//RedirectStandardOutput = true,
CreateNoWindow = false,
// WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
}
};
proc.Start();
proc.WaitForExit();
} else {
var proc = new System.Diagnostics.Process {
StartInfo = new System.Diagnostics.ProcessStartInfo {
FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
Arguments = argument,
//UseShellExecute = false,
//RedirectStandardOutput = true,
CreateNoWindow = true,
WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
}
};
proc.Start();
proc.WaitForExit();
}
// watch.Stop();
//Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());
/////////////////////////////////////////////////////////////////
//Read Obj
/////////////////////////////////////////////////////////////////
///
//Outputs
// watch = System.Diagnostics.Stopwatch.StartNew();
// Initialize
var obj = new ObjParser.Obj();
// Read Wavefront OBJ file
//obj.LoadObj(@"C:\libs\windows\out.obj");
//PlyReaderWriter.PlyLoader plyLoader = new PlyReaderWriter.PlyLoader();
//Mesh mesh3D = plyLoader.load(replacedemblyPath + @"\out.ply")[0];
//Rhino.RhinoApp.WriteLine(replacedemblyPath + @"\windows\out.obj");
obj.LoadObj(replacedemblyPath + @"\out.obj");
Mesh mesh3D = new Mesh();
foreach (ObjParser.Types.Vertex v in obj.VertexList) {
mesh3D.Vertices.Add(new Point3d(v.X, v.Y, v.Z));
mesh3D.VertexColors.Add(System.Drawing.Color.FromArgb((int)(v.r * 255), (int)(v.g * 255), (int)(v.b * 255) ));
}
int num = checked(mesh3D.Vertices.Count - 1);
foreach (ObjParser.Types.Face f in obj.FaceList) {
string[] lineData = f.ToString().Split(' ');
string[] v0 = lineData[1].Split('/');
string[] v1 = lineData[2].Split('/');
string[] v2 = lineData[3].Split('/');
MeshFace mf3D = new MeshFace(Convert.ToInt32(v0[0]) - 1, Convert.ToInt32(v1[0]) - 1, Convert.ToInt32(v2[0]) - 1);
if (mf3D.IsValid())
if (!(mf3D.A > num || mf3D.B > num || mf3D.C > num || mf3D.D > num))
mesh3D.Faces.AddFace(mf3D);
}
DA.SetData(0, mesh3D);
/////////////////////////////////////////////////////////////////
//Output Iso Values
/////////////////////////////////////////////////////////////////
string[] lines = System.IO.File.ReadAllLines(replacedemblyPath + @"\out.txt");
double[] iso = new double[lines.Length];
for (int i = 0; i < lines.Length; i++) {
iso[i] = Convert.ToDouble(lines[i]);
}
//watch.Stop();
//Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds/1000.0).ToString());
DA.SetDataList(1, iso);
}
}
19
Source : PointCloudToMeshComponent.cs
with GNU Lesser General Public License v3.0
from 9and3
with GNU Lesser General Public License v3.0
from 9and3
protected override void SolveInstance(IGH_DataAccess DA) {
int Downsample = 5000;
int NormalsNeighbours = 100;
bool debug = false;
DA.GetData(1, ref Downsample);
DA.GetData(2, ref NormalsNeighbours);
DA.GetData(3, ref debug);
//Guid to PointCloud
//PointCloud c = new PointCloud();
PointCloudGH c = new PointCloudGH();
string debugInfo = debug ? "1" : "0";
if (DA.GetData(0, ref c)) {
if (!c.IsValid) return;
if (c.Value.Count == 0) return;
Downsample = Math.Min(Downsample, c.Value.Count);
// var watch = System.Diagnostics.Stopwatch.StartNew();
// the code that you want to measure comes here
/////////////////////////////////////////////////////////////////
//Get Directory
/////////////////////////////////////////////////////////////////
string replacedemblyLocation = System.Reflection.replacedembly.GetExecutingreplacedembly().Location;
string replacedemblyPath = System.IO.Path.GetDirectoryName(replacedemblyLocation);
/////////////////////////////////////////////////////////////////
//write PointCloud to PLY
/////////////////////////////////////////////////////////////////
PlyReaderWriter.PlyWriter.SavePLY(c.Value, replacedemblyPath + @"\in.ply");
//Rhino.RhinoApp.WriteLine("PointCloudToMesh. Saved Input: " + replacedemblyPath + @"\in.ply");
//watch.Stop();
//Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());
/////////////////////////////////////////////////////////////////
//Ply to Mesh to Obj
/////////////////////////////////////////////////////////////////
//watch = System.Diagnostics.Stopwatch.StartNew();
//tring argument = replacedemblyPath + "TestVisualizer.exe " + "-1 " + "100";//--asci
string argument = " "+Downsample.ToString()+ " " + NormalsNeighbours.ToString() + " " + debugInfo + " 8 0 1.1 0";//--asci
// Rhino.RhinoApp.WriteLine("PointCloudToMesh. Arguments: " + argument );
//int maximumDeptOfReconstructionSurfaceTree = atoi(argv[4]);//8
//int targetWidthOfTheFinestLevelOctree = atoi(argv[5]);//0
//float ratioBetweenReconCubeAndBBCubeStd = atof(argv[6]); // 1.1
//bool ReconstructorUsingLinearInterpolation = atoi(argv[7]) == 1;//0
// Rhino.RhinoApp.WriteLine("PointCloudToMesh. Directory: " + replacedemblyPath + @"\TestVisualizer.exe");
if (debug) {
var proc = new System.Diagnostics.Process {
StartInfo = new System.Diagnostics.ProcessStartInfo {
FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
Arguments = argument,
//UseShellExecute = false,
//RedirectStandardOutput = true,
CreateNoWindow = false,
// WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
}
};
proc.Start();
proc.WaitForExit();
} else {
var proc = new System.Diagnostics.Process {
StartInfo = new System.Diagnostics.ProcessStartInfo {
FileName = replacedemblyPath + @"\TestVisualizer.exe",//filePath+"PoissonRecon.exe",
Arguments = argument,
//UseShellExecute = false,
//RedirectStandardOutput = true,
CreateNoWindow = true,
WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
WorkingDirectory = replacedemblyPath + @"\TestVisualizer.exe"
}
};
proc.Start();
proc.WaitForExit();
}
// watch.Stop();
//Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds / 1000.0).ToString());
/////////////////////////////////////////////////////////////////
//Read Obj
/////////////////////////////////////////////////////////////////
///
//Outputs
// watch = System.Diagnostics.Stopwatch.StartNew();
// Initialize
var obj = new ObjParser.Obj();
// Read Wavefront OBJ file
//obj.LoadObj(@"C:\libs\windows\out.obj");
//PlyReaderWriter.PlyLoader plyLoader = new PlyReaderWriter.PlyLoader();
//Mesh mesh3D = plyLoader.load(replacedemblyPath + @"\out.ply")[0];
//Rhino.RhinoApp.WriteLine(replacedemblyPath + @"\windows\out.obj");
obj.LoadObj(replacedemblyPath + @"\out.obj");
Mesh mesh3D = new Mesh();
foreach (ObjParser.Types.Vertex v in obj.VertexList) {
mesh3D.Vertices.Add(new Point3d(v.X, v.Y, v.Z));
mesh3D.VertexColors.Add(System.Drawing.Color.FromArgb((int)(v.r * 255), (int)(v.g * 255), (int)(v.b * 255) ));
}
int num = checked(mesh3D.Vertices.Count - 1);
foreach (ObjParser.Types.Face f in obj.FaceList) {
string[] lineData = f.ToString().Split(' ');
string[] v0 = lineData[1].Split('/');
string[] v1 = lineData[2].Split('/');
string[] v2 = lineData[3].Split('/');
MeshFace mf3D = new MeshFace(Convert.ToInt32(v0[0]) - 1, Convert.ToInt32(v1[0]) - 1, Convert.ToInt32(v2[0]) - 1);
if (mf3D.IsValid())
if (!(mf3D.A > num || mf3D.B > num || mf3D.C > num || mf3D.D > num))
mesh3D.Faces.AddFace(mf3D);
}
DA.SetData(0, mesh3D);
/////////////////////////////////////////////////////////////////
//Output Iso Values
/////////////////////////////////////////////////////////////////
string[] lines = System.IO.File.ReadAllLines(replacedemblyPath + @"\out.txt");
double[] iso = new double[lines.Length];
for (int i = 0; i < lines.Length; i++) {
iso[i] = Convert.ToDouble(lines[i]);
}
//watch.Stop();
//Rhino.RhinoApp.WriteLine((watch.ElapsedMilliseconds/1000.0).ToString());
DA.SetDataList(1, iso);
}
}
19
Source : AssetBundleManager.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
private static string GetStreamingreplacedetsPath()
{
if (Application.isEditor)
return "file://" + System.Environment.CurrentDirectory.Replace("\\", "/"); // Use the build output folder directly.
#if !UNITY_2017_2_OR_NEWER
if (Application.isWebPlayer)
return System.IO.Path.GetDirectoryName(Application.absoluteURL).Replace("\\", "/") + "/Streamingreplacedets";
#endif
if (Application.isMobilePlatform || Application.isConsolePlatform)
return Application.streamingreplacedetsPath;
// For standalone player.
return "file://" + Application.streamingreplacedetsPath;
}
19
Source : WavUtility.cs
with GNU General Public License v3.0
from a2659802
with GNU General Public License v3.0
from a2659802
public static byte[] FromAudioClip(AudioClip audioClip, out string filepath, bool saveAsFile = true, string dirname = "recordings")
{
MemoryStream stream = new MemoryStream();
const int headerSize = 44;
// get bit depth
UInt16 bitDepth = 16; //BitDepth (audioClip);
// NB: Only supports 16 bit
//Debug.replacedertFormat (bitDepth == 16, "Only converting 16 bit is currently supported. The audio clip data is {0} bit.", bitDepth);
// total file size = 44 bytes for header format and audioClip.samples * factor due to float to Int16 / sbyte conversion
int fileSize = audioClip.samples * BlockSize_16Bit + headerSize; // BlockSize (bitDepth)
// chunk descriptor (riff)
WriteFileHeader(ref stream, fileSize);
// file header (fmt)
WriteFileFormat(ref stream, audioClip.channels, audioClip.frequency, bitDepth);
// data chunks (data)
WriteFileData(ref stream, audioClip, bitDepth);
byte[] bytes = stream.ToArray();
// Validate total bytes
Debug.replacedertFormat(bytes.Length == fileSize, "Unexpected AudioClip to wav format byte count: {0} == {1}", bytes.Length, fileSize);
// Save file to persistant storage location
if (saveAsFile)
{
filepath = string.Format("{0}/{1}/{2}.{3}", Application.persistentDataPath, dirname, DateTime.UtcNow.ToString("yyMMdd-HHmmss-fff"), "wav");
Directory.CreateDirectory(Path.GetDirectoryName(filepath));
File.WriteAllBytes(filepath, bytes);
//Debug.Log ("Auto-saved .wav file: " + filepath);
}
else
{
filepath = null;
}
stream.Dispose();
return bytes;
}
19
Source : UMAAvatarLoadSaveMenuItems.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
[MenuItem("UMA/Runtime/Save Selected Avatars generated textures to PNG")]
public static void SaveSelectedAvatarsPNG()
{
if (!Application.isPlaying)
{
EditorUtility.DisplayDialog("Notice", "This function is only available at runtime", "Got it");
return;
}
if (Selection.gameObjects.Length != 1)
{
EditorUtility.DisplayDialog("Notice", "Only one Avatar can be selected.", "OK");
return;
}
var selectedTransform = Selection.gameObjects[0].transform;
var avatar = selectedTransform.GetComponent<UMAAvatarBase>();
if (avatar == null)
{
EditorUtility.DisplayDialog("Notice", "An Avatar must be selected to use this function", "OK");
return;
}
SkinnedMeshRenderer smr = avatar.gameObject.GetComponentInChildren<SkinnedMeshRenderer>();
if (smr == null)
{
EditorUtility.DisplayDialog("Warning", "Could not find SkinnedMeshRenderer in Avatar hierarchy", "OK");
return;
}
string path = EditorUtility.SaveFilePanelInProject("Save Texture(s)", "Texture.png", "png", "Base Filename to save PNG files to.");
if (!string.IsNullOrEmpty(path))
{
string basename = System.IO.Path.GetFileNameWithoutExtension(path);
string pathname = System.IO.Path.GetDirectoryName(path);
// save the diffuse texture
for (int i = 0; i < smr.materials.Length; i++)
{
string PathBase = System.IO.Path.Combine(pathname, basename + "_material_" + i.ToString());
string DiffuseName = PathBase + "_Diffuse.PNG";
SaveTexture(smr.materials[i].GetTexture("_MainTex"), DiffuseName);
}
}
}
19
Source : UI.cs
with MIT License
from aaaddress1
with MIT License
from aaaddress1
private void refreshUi(object sender, EventArgs e)
{
/* i'm too lazy to make a editor for C/C++ :P,
* and this editor is really useful!!
* https://github.com/PavelTorgashov/FastColoredTextBox */
fastColoredTextBox.Language = FastColoredTextBoxNS.Language.CSharp;
if (srcPath == "")
srcPath = Path.Combine(Application.StartupPath, "main.cpp");
if (!File.Exists(srcPath))
File.WriteAllText(srcPath, Properties.Resources.templateSrc);
fastColoredTextBox.InsertText(File.ReadAllText(srcPath));
asmPath = Path.Combine(Path.GetDirectoryName(srcPath), Path.GetFileNameWithoutExtension(srcPath) + ".s");
obfAsmPath = Path.Combine(Path.GetDirectoryName(srcPath), Path.GetFileNameWithoutExtension(srcPath) + "_obf.s");
exePath = Path.Combine(Path.GetDirectoryName(srcPath), Path.GetFileNameWithoutExtension(srcPath) + ".exe");
this.Text = string.Format("puzzCode [{0}] by [email protected]", new FileInfo(srcPath).Name);
logBox.Clear();
logMsg(demostr, Color.Blue);
compiler.logText = this.logBox;
obfuscator.logText = this.logBox;
this.splitContainer.Panel2Collapsed = true;
if (!new DirectoryInfo(Properties.Settings.Default.gwPath).Exists)
{
MessageBox.Show("please choose your MinGW path.");
(new config()).ShowDialog();
if (!new DirectoryInfo(Properties.Settings.Default.gwPath).Exists)
{
MessageBox.Show("sorry, MinGW not found :(");
Application.Exit();
}
}
}
19
Source : SettingForm.cs
with MIT License
from aabiryukov
with MIT License
from aabiryukov
private void selectLogoFileButton_Click(object sender, EventArgs e)
{
using (var fileDialog = new OpenFileDialog())
{
if (string.IsNullOrEmpty(LogoFileTextBox.Text))
{
fileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
}
else
{
fileDialog.FileName = LogoFileTextBox.Text;
fileDialog.InitialDirectory = Path.GetDirectoryName(fileDialog.FileName);
}
fileDialog.Filter = "Images|*.jpg;*.jpeg;*.png;*.bmp";
fileDialog.replacedle = "Select Logo image file";
if (fileDialog.ShowDialog(this) == DialogResult.OK)
{
LogoFileTextBox.Text = fileDialog.FileName;
}
}
}
19
Source : HistoryViewer.cs
with MIT License
from aabiryukov
with MIT License
from aabiryukov
[System.Diagnostics.Codereplacedysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private void ExecViewHistory(Uri tfsCollectionUri, string sourceControlFolder)
{
// gource start arguments
string arguments;
string replacedle;
string avatarsDirectory = null;
if (m_settigs.PlayMode == VisualizationSettings.PlayModeOption.History)
{
replacedle = "History of " + sourceControlFolder;
var logFile = Path.Combine(FileUtils.GetTempPath(), "TfsHistoryLog.tmp.txt");
if (m_settigs.ViewAvatars)
{
avatarsDirectory = Path.Combine(FileUtils.GetTempPath(), "TfsHistoryLog.tmp.Avatars");
if (!Directory.Exists(avatarsDirectory))
{
Directory.CreateDirectory(avatarsDirectory);
}
}
bool historyFound;
bool hasLines;
using (var waitMessage = new WaitMessage("Connecting to Team Foundation Server...", OnCancelByUser))
{
var progress = waitMessage.CreateProgress("Loading history ({0}% done) ...");
hasLines =
TfsLogWriter.CreateGourceLogFile(
logFile,
avatarsDirectory,
tfsCollectionUri,
sourceControlFolder,
m_settigs,
ref m_canceled,
progress.SetValue
);
historyFound = progress.LastValue > 0;
progress.Done();
}
if (m_canceled)
return;
if (!hasLines)
{
MessageBox.Show(
historyFound
? "No items found.\nCheck your filters: 'User name' and 'File type'."
: "No items found.\nTry to change period of the history (From/To dates).",
"TFS History Visualization");
return;
}
arguments = string.Format(CultureInfo.InvariantCulture, " \"{0}\" ", logFile);
// Setting other history settings
arguments += " --seconds-per-day " + m_settigs.SecondsPerDay.ToString(CultureInfo.InvariantCulture);
if (m_settigs.TimeScale != VisualizationSettings.TimeScaleOption.None)
{
var optionValue = ConvertToString(m_settigs.TimeScale);
if (optionValue != null)
arguments += " --time-scale " + optionValue;
}
if (m_settigs.LoopPlayback)
{
arguments += " --loop";
}
arguments += " --file-idle-time 60"; // 60 is default in gource 0.40 and older. Since 0.41 default 0.
}
else
{
// PlayMode: Live
replacedle = "Live changes of " + sourceControlFolder;
arguments = " --realtime --log-format custom -";
arguments += " --file-idle-time 28800"; // 8 hours (work day)
}
var baseDirectory = Path.GetDirectoryName(System.Reflection.replacedembly.GetExecutingreplacedembly().Location) ??
"unknown";
if (baseDirectory.Contains("Test"))
{
baseDirectory += @"\..\..\..\VSExtension";
}
#if DEBUG
// baseDirectory = @"C:\Temp\aaaa\уи³пс\";
#endif
var gourcePath = Path.Combine(baseDirectory, @"Gource\Gource.exe");
var dataPath = Path.Combine(baseDirectory, @"Data");
// ******************************************************
// Configuring Gource command line
// ******************************************************
arguments +=
string.Format(CultureInfo.InvariantCulture, " --highlight-users --replacedle \"{0}\"", replacedle);
if (m_settigs.ViewLogo != CheckState.Unchecked)
{
var logoFile = m_settigs.ViewLogo == CheckState.Indeterminate
? Path.Combine(dataPath, "Logo.png")
: m_settigs.LogoFileName;
// fix gource unicode path problems
logoFile = FileUtils.GetShortPath(logoFile);
arguments += string.Format(CultureInfo.InvariantCulture, " --logo \"{0}\"", logoFile);
}
if (m_settigs.FullScreen)
{
arguments += " --fullscreen";
// By default gource not using full area of screen width ( It's a bug. Must be fixed in gource 0.41).
// Fixing fullscreen resolution to real full screen.
if (!m_settigs.SetResolution)
{
var screenBounds = Screen.PrimaryScreen.Bounds;
arguments += string.Format(CultureInfo.InvariantCulture, " --viewport {0}x{1}", screenBounds.Width,
screenBounds.Height);
}
}
if (m_settigs.SetResolution)
{
arguments += string.Format(CultureInfo.InvariantCulture, " --viewport {0}x{1}",
m_settigs.ResolutionWidth, m_settigs.ResolutionHeight);
}
if (m_settigs.ViewFilesExtentionMap)
{
arguments += " --key";
}
if (!string.IsNullOrEmpty(avatarsDirectory))
{
arguments += string.Format(CultureInfo.InvariantCulture, " --user-image-dir \"{0}\"", avatarsDirectory);
}
// Process "--hide" option
{
var hideItems = string.Empty;
if (!m_settigs.ViewDirNames)
{
hideItems = "dirnames";
}
if (!m_settigs.ViewFileNames)
{
if (hideItems.Length > 0) hideItems += ",";
hideItems += "filenames";
}
if (!m_settigs.ViewUserNames)
{
if (hideItems.Length > 0) hideItems += ",";
hideItems += "usernames";
}
if (hideItems.Length > 0)
arguments += " --hide " + hideItems;
}
arguments += " --max-files " + m_settigs.MaxFiles.ToString(CultureInfo.InvariantCulture);
if (SystemInformation.TerminalServerSession)
{
arguments += " --disable-bloom";
}
if (m_settigs.PlayMode == VisualizationSettings.PlayModeOption.History)
{
var si = new ProcessStartInfo(gourcePath, arguments)
{
WindowStyle = ProcessWindowStyle.Maximized,
// UseShellExecute = true
};
Process.Start(si);
}
else
{
var logReader = new VersionControlLogReader(tfsCollectionUri, sourceControlFolder, m_settigs.UsersFilter,
m_settigs.FilesFilter);
using (new WaitMessage("Connecting to Team Foundation Server..."))
{
logReader.Connect();
}
System.Threading.Tasks.Task.Factory.StartNew(() => RunLiveChangesMonitor(logReader, gourcePath, arguments));
}
}
19
Source : ContextIsolatedTask.cs
with Microsoft Public License
from AArnott
with Microsoft Public License
from AArnott
public sealed override bool Execute()
{
try
{
// We have to hook our own AppDomain so that the TransparentProxy works properly.
AppDomain.CurrentDomain.replacedemblyResolve += this.CurrentDomain_replacedemblyResolve;
// On .NET Framework (on Windows), we find native binaries by adding them to our PATH.
if (this.UnmanagedDllDirectory != null)
{
string pathEnvVar = Environment.GetEnvironmentVariable("PATH");
string[] searchPaths = pathEnvVar.Split(Path.PathSeparator);
if (!searchPaths.Contains(this.UnmanagedDllDirectory, StringComparer.OrdinalIgnoreCase))
{
pathEnvVar += Path.PathSeparator + this.UnmanagedDllDirectory;
Environment.SetEnvironmentVariable("PATH", pathEnvVar);
}
}
// Run under our own AppDomain so we can apply the .config file of the MSBuild Task we're hosting.
// This gives the owner the control over binding redirects to be applied.
var appDomainSetup = new AppDomainSetup();
string pathToTaskreplacedembly = this.GetType().replacedembly.Location;
appDomainSetup.ApplicationBase = Path.GetDirectoryName(pathToTaskreplacedembly);
appDomainSetup.ConfigurationFile = pathToTaskreplacedembly + ".config";
var appDomain = AppDomain.CreateDomain("ContextIsolatedTask: " + this.GetType().Name, AppDomain.CurrentDomain.Evidence, appDomainSetup);
string taskreplacedemblyFullName = this.GetType().replacedembly.GetName().FullName;
string taskFullName = this.GetType().FullName;
var isolatedTask = (ContextIsolatedTask)appDomain.CreateInstanceAndUnwrap(taskreplacedemblyFullName, taskFullName);
return this.ExecuteInnerTask(isolatedTask, this.GetType());
}
catch (OperationCanceledException)
{
this.Log.LogMessage(MessageImportance.High, "Canceled.");
return false;
}
finally
{
AppDomain.CurrentDomain.replacedemblyResolve -= this.CurrentDomain_replacedemblyResolve;
}
}
19
Source : CallIncident.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
public static void IncidentLogAppend(string record, ModelMailStartIncident mail, string data, int fromWorth = 0, int toWorth = 0)
{
Func<DateTime, string> dateTimeToStr = dt => dt == DateTime.MinValue ? "" : dt.ToString("yyyy-MM-dd hh:mm:ss", CultureInfo.InvariantCulture);
var fileName = Path.Combine(Path.GetDirectoryName(Repository.Get.SaveFileName)
, $"Incidents_{DateTime.Now.ToString("yyyy-MM")}.csv");
if (!File.Exists(fileName))
{
File.WriteAllText(fileName, $"time;record" +
$";fromLogin;toLogin;fromDay;toDay;fromWorth;toWorth;paramIncident;serverId" +
//структура data:
$";worthTarget;delayAfterMail;numberOrder;countInOrder" +
Environment.NewLine, Encoding.UTF8);
}
if (fromWorth == 0) fromWorth = (int)Repository.GetPlayerByLogin(mail.From.Login).AllCostWorldObjects();
if (toWorth == 0) toWorth = (int)Repository.GetPlayerByLogin(mail.To.Login).AllCostWorldObjects();
var param = $"{mail.IncidentType} lvl:{mail.IncidentMult} mode:{mail.IncidentArrivalMode} who:{mail.IncidentFaction}";
var contentLog = dateTimeToStr(DateTime.Now) + ";" + record
+ $";{mail.From.Login};{mail.To.Login};{mail.From.LastTick / 60000};{mail.To.LastTick / 60000};{fromWorth};{toWorth};{param};{mail.PlaceServerId}"
+ ";" + data + Environment.NewLine;
Loger.Log("IncidentLogAppend. " + contentLog);
try
{
File.AppendAllText(fileName, contentLog, Encoding.UTF8);
}
catch
{
try
{
File.AppendAllText(fileName + "add", contentLog, Encoding.UTF8);
}
catch
{
Loger.Log("IncidentLogAppend. Error write file " + fileName);
}
}
}
19
Source : App.xaml.cs
with Microsoft Public License
from AArnott
with Microsoft Public License
from AArnott
internal static UpdateManager CreateUpdateManager()
{
string channel = Thisreplacedembly.IsPrerelease ? "prerelease" : "release";
string channelOverrideFilePath = Path.Combine(Path.GetDirectoryName(replacedembly.GetEntryreplacedembly()!.Location)!, "channelname.txt");
if (File.Exists(channelOverrideFilePath))
{
channel = File.ReadAllText(channelOverrideFilePath).Trim();
}
string subchannel = RuntimeInformation.ProcessArchitecture switch
{
Architecture.Arm64 => "win-arm64",
Architecture.X64 => "win-x64",
Architecture.X86 => "win-x86",
_ => throw new NotSupportedException("Unrecognized process architecture."),
};
19
Source : SimpleAnimationNodeEditor.cs
with MIT License
from aarthificial
with MIT License
from aarthificial
[MenuItem("replacedets/Create/Reanimator/Simple Animation (From Textures)", false, 400)]
private static void CreateFromTextures()
{
var trailingNumbersRegex = new Regex(@"(\d+$)");
var sprites = new List<Sprite>();
var textures = Selection.GetFiltered<Texture2D>(SelectionMode.replacedets);
foreach (var texture in textures)
{
string path = replacedetDatabase.GetreplacedetPath(texture);
sprites.AddRange(replacedetDatabase.LoadAllreplacedetsAtPath(path).OfType<Sprite>());
}
var cels = sprites
.OrderBy(
sprite =>
{
var match = trailingNumbersRegex.Match(sprite.name);
return match.Success ? int.Parse(match.Groups[0].Captures[0].ToString()) : 0;
}
)
.Select(sprite => new SimpleCel(sprite))
.ToArray();
var replacedet = SimpleAnimationNode.Create<SimpleAnimationNode>(
cels: cels
);
string baseName = trailingNumbersRegex.Replace(textures[0].name, "");
replacedet.name = baseName + "_animation";
string replacedetPath = Path.GetDirectoryName(replacedetDatabase.GetreplacedetPath(textures[0]));
replacedetDatabase.Createreplacedet(replacedet, Path.Combine(replacedetPath ?? Application.dataPath, replacedet.name + ".replacedet"));
replacedetDatabase.Savereplacedets();
}
19
Source : ServerManager.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
public void SavePlayerStatisticsFile()
{
try
{
var msg = "Command SaveListPlayerFileStats";
Loger.Log(msg);
Func<DateTime, string> dateTimeToStr = dt => dt == DateTime.MinValue ? "" : dt.ToString("yyyy-MM-dd hh:mm:ss", CultureInfo.InvariantCulture);
var content = $"Login;LastOnlineTime;LastOnlineDay;GameDays;BaseCount;CaravanCount;MarketValue;MarketValuePawn" +
$";AttacksWonCount;AttacksInitiatorCount;ColonistsCount;ColonistsDownCount;ColonistsBleedCount;PawnMaxSkill" +
$";KillsHumanlikes;KillsMechanoids;KillsBestPawnHN;KillsBestPawnH;KillsBestPawnMN;KillsBestPawnM" +
$";Grants;EnablePVP;EMail;DiscordUserName;IntruderKeys;StartMarketValue;StartMarketValuePawn" +
$";MarketValueBy15Day;MarketValuePawnBy15Day;MarketValueByHour;MarketValuePawnByHour;TicksByHour;HourInGame" + Environment.NewLine;
foreach (var player in Repository.GetData.PlayersAll)
{
var costAll = player.CostWorldObjects();
var newLine = $"{player.Public.Login};" +
$"{dateTimeToStr(player.Public.LastOnlineTime)};" +
$"{(int)(DateTime.UtcNow - player.Public.LastOnlineTime).TotalDays};" +
$"{(int)(player.Public.LastTick / 60000)};" +
$"{costAll.BaseCount};" +
$"{costAll.CaravanCount};" +
$"{costAll.MarketValue};" +
$"{costAll.MarketValuePawn};" +
$"{player.AttacksWonCount};" +
$"{player.AttacksInitiatorCount};" +
$"{player.GameProgress?.ColonistsCount};" +
$"{player.GameProgress?.ColonistsDownCount};" +
$"{player.GameProgress?.ColonistsBleedCount};" +
$"{player.GameProgress?.PawnMaxSkill};" +
$"{player.GameProgress?.KillsHumanlikes};" +
$"{player.GameProgress?.KillsMechanoids};" +
$"{player.GameProgress?.KillsBestHumanlikesPawnName};" +
$"{player.GameProgress?.KillsBestHumanlikes};" +
$"{player.GameProgress?.KillsBestMechanoidsPawnName};" +
$"{player.GameProgress?.KillsBestMechanoids};" +
$"{player.Public.Grants.ToString()};" +
$"{(player.Public.EnablePVP ? 1 : 0)};" +
$"{player.Public.EMail};" +
$"{player.Public.DiscordUserName};" +
$"{player.IntruderKeys};" +
$"{player.StartMarketValue};" +
$"{player.StartMarketValuePawn};" +
$"{player.StatMaxDeltaGameMarketValue};" +
$"{player.StatMaxDeltaGameMarketValuePawn};" +
$"{player.StatMaxDeltaRealMarketValue};" +
$"{player.StatMaxDeltaRealMarketValuePawn};" +
$"{player.StatMaxDeltaRealTicks};" +
$"{player.TotalRealSecond / 60f / 60f};"
;
newLine = newLine.Replace(Environment.NewLine, " ")
.Replace("/r", "").Replace("/n", "");
content += newLine + Environment.NewLine;
}
var fileName = Path.Combine(Path.GetDirectoryName(Repository.Get.SaveFileName)
, $"Players_{DateTime.Now.ToString("yyyy-MM-dd_hh-mm")}.csv");
File.WriteAllText(fileName, content, Encoding.UTF8);
}
catch (Exception e)
{
Loger.Log("Command Exception " + e.ToString());
}
}
See More Examples