Here are the examples of the csharp api System.IO.Path.Combine(params string[]) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
16069 Examples
19
View Source File : PhiChartFileReader.cs
License : MIT License
Project Creator : 0thElement
License : MIT License
Project Creator : 0thElement
public void ReadChart()
{
CurrentChart = JsonConvert.DeserializeObject<PhiChart>(File.ReadAllText(Path.Combine(Application.dataPath, "Scripts", "testChart.json")));
PhiChartView.Instance.Refresh();
}
19
View Source File : MainActivity.cs
License : Microsoft Public License
Project Creator : 0x0ade
License : Microsoft Public License
Project Creator : 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
View Source File : MainActivity.cs
License : Microsoft Public License
Project Creator : 0x0ade
License : Microsoft Public License
Project Creator : 0x0ade
public static void SDL_Main()
{
if (string.IsNullOrEmpty(Instance.GamePath))
{
AlertDialog dialog = null;
Instance.RunOnUiThread(() =>
{
using (AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(Instance))
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("Game not found: ").AppendLine(Game);
foreach (Java.IO.File root in Instance.GetExternalFilesDirs(null))
{
stringBuilder.AppendLine();
stringBuilder.AppendLine(Path.Combine(root.AbsolutePath, Game));
}
dialogBuilder.SetMessage(stringBuilder.ToString());
dialogBuilder.SetCancelable(false);
dialog = dialogBuilder.Show();
}
});
while (dialog == null || dialog.IsShowing)
{
System.Threading.Thread.Sleep(0);
}
dialog.Dispose();
return;
}
// Replace the following with whatever was in your Program.Main method.
/*/
using (TestGame game = new TestGame())
{
game.Run();
}
/*/
replacedembly.LoadFrom(Instance.GamePath).EntryPoint.Invoke(null, new object[] { new string[] { /*args*/ } });
/**/
}
19
View Source File : Program.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
static bool VerifyFile(out string path, params string[] paths) {
path = Path.Combine(paths);
if (!File.Exists(path) && !Directory.Exists(path)) {
Console.Error.WriteLine($"Missing: {path}");
return false;
}
return true;
}
19
View Source File : MethodJitter.cs
License : MIT License
Project Creator : 0xd4d
License : MIT License
Project Creator : 0xd4d
replacedembly? Resolvereplacedembly(string? name) {
if (name is null)
return null;
if (nameToreplacedembly.TryGetValue(name, out var asm))
return asm;
nameToreplacedembly.Add(name, null);
foreach (var basePath in searchPaths) {
foreach (var ext in asmExtensions) {
var filename = Path.Combine(basePath, name + ext);
if (File.Exists(filename)) {
asm = replacedembly.LoadFile(filename);
nameToreplacedembly[name] = asm;
return asm;
}
}
}
if (!name.EndsWith(".resources", StringComparison.OrdinalIgnoreCase))
Console.WriteLine($"Failed to resolve replacedembly '{name}'");
return null;
}
19
View Source File : LocalStorageHandler.cs
License : Apache License 2.0
Project Creator : 0xFireball
License : Apache License 2.0
Project Creator : 0xFireball
private string GetUploadDirectory()
{
var uploadDirectory = Path.Combine(ServerContext.Configuration.UploadDirectory);
Directory.CreateDirectory(uploadDirectory);
return uploadDirectory;
}
19
View Source File : IrdClient.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
public async Task<Ird> DownloadAsync(SearchResulreplacedem irdInfo, string localCachePath, CancellationToken cancellationToken)
{
Ird result = null;
try
{
var localCacheFilename = Path.Combine(localCachePath, irdInfo.Filename);
// first we search local cache and try to load whatever data we can
try
{
if (File.Exists(localCacheFilename))
return IrdParser.Parse(File.ReadAllBytes(localCacheFilename));
}
catch (Exception e)
{
Log.Warn(e, "Error accessing local IRD cache: " + e.Message);
}
try
{
var resultBytes = await client.GetByteArrayAsync(GetDownloadLink(irdInfo.Filename)).ConfigureAwait(false);
result = IrdParser.Parse(resultBytes);
try
{
if (!Directory.Exists(localCachePath))
Directory.CreateDirectory(localCachePath);
File.WriteAllBytes(localCacheFilename, resultBytes);
}
catch (Exception ex)
{
Log.Warn(ex, $"Failed to write {irdInfo.Filename} to local cache: {ex.Message}");
}
}
catch (Exception e)
{
Log.Warn(e, $"Failed to download {irdInfo.Filename}: {e.Message}");
}
return result;
}
catch (Exception e)
{
Log.Error(e);
return result;
}
}
19
View Source File : Dumper.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 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
View Source File : Program.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
static async Task<int> Main(string[] args)
{
Log.Info("PS3 Disc Dumper v" + Dumper.Version);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && Console.WindowHeight < 1 && Console.WindowWidth < 1)
try
{
Log.Error("Looks like there's no console present, restarting...");
var launchArgs = Environment.GetCommandLineArgs()[0];
if (launchArgs.Contains("/var/tmp") || launchArgs.EndsWith(".dll"))
{
Log.Debug("Looks like we were launched from a single executable, looking for the parent...");
using var currentProcess = Process.GetCurrentProcess();
var pid = currentProcess.Id;
var procCmdlinePath = Path.Combine("/proc", pid.ToString(), "cmdline");
launchArgs = File.ReadAllLines(procCmdlinePath).FirstOrDefault()?.TrimEnd('\0');
}
Log.Debug($"Using cmdline '{launchArgs}'");
launchArgs = $"-e bash -c {launchArgs}";
var startInfo = new ProcessStartInfo("x-terminal-emulator", launchArgs);
using var proc = Process.Start(startInfo);
if (proc.WaitForExit(1_000))
{
if (proc.ExitCode != 0)
{
startInfo = new ProcessStartInfo("xdg-terminal", launchArgs);
using var proc2 = Process.Start(startInfo);
if (proc2.WaitForExit(1_000))
{
if (proc2.ExitCode != 0)
{
startInfo = new ProcessStartInfo("gnome-terminal", launchArgs);
using var proc3 = Process.Start(startInfo);
if (proc3.WaitForExit(1_000))
{
if (proc3.ExitCode != 0)
{
startInfo = new ProcessStartInfo("konsole", launchArgs);
using var _ = Process.Start(startInfo);
}
}
}
}
}
}
return -2;
}
catch (Exception e)
{
Log.Error(e);
return -3;
}
var lastDiscId = "";
start:
const string replacedleBase = "PS3 Disc Dumper";
var replacedle = replacedleBase;
Console.replacedle = replacedle;
var output = ".";
var inDir = "";
var showHelp = false;
var options = new OptionSet
{
{
"i|input=", "Path to the root of blu-ray disc mount", v =>
{
if (v is string ind)
inDir = ind;
}
},
{
"o|output=", "Path to the output folder. Subfolder for each disc will be created automatically", v =>
{
if (v is string outd)
output = outd;
}
},
{
"?|h|help", "Show help", v =>
{
if (v != null)
showHelp = true;
},
true
},
};
try
{
var unknownParams = options.Parse(args);
if (unknownParams.Count > 0)
{
Log.Warn("Unknown parameters: ");
foreach (var p in unknownParams)
Log.Warn("\t" + p);
showHelp = true;
}
if (showHelp)
{
ShowHelp(options);
return 0;
}
var dumper = new Dumper(ApiConfig.Cts);
dumper.DetectDisc(inDir);
await dumper.FindDiscKeyAsync(ApiConfig.IrdCachePath).ConfigureAwait(false);
if (string.IsNullOrEmpty(dumper.OutputDir))
{
Log.Info("No compatible disc was found, exiting");
return 2;
}
if (lastDiscId == dumper.ProductCode)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("You're dumping the same disc, are you sure you want to continue? (Y/N, default is N)");
Console.ResetColor();
var confirmKey = Console.ReadKey(true);
switch (confirmKey.Key)
{
case ConsoleKey.Y:
break;
default:
throw new OperationCanceledException("Aborting re-dump of the same disc");
}
}
lastDiscId = dumper.ProductCode;
replacedle += " - " + dumper.replacedle;
var monitor = new Thread(() =>
{
try
{
do
{
if (dumper.CurrentSector > 0)
Console.replacedle = $"{replacedle} - File {dumper.CurrentFileNumber} of {dumper.TotalFileCount} - {dumper.CurrentSector * 100.0 / dumper.TotalSectors:0.00}%";
Task.Delay(1000, ApiConfig.Cts.Token).GetAwaiter().GetResult();
} while (!ApiConfig.Cts.Token.IsCancellationRequested);
}
catch (TaskCanceledException)
{
}
Console.replacedle = replacedle;
});
monitor.Start();
await dumper.DumpAsync(output).ConfigureAwait(false);
ApiConfig.Cts.Cancel(false);
monitor.Join(100);
if (dumper.BrokenFiles.Count > 0)
{
Log.Fatal("Dump is not valid");
foreach (var file in dumper.BrokenFiles)
Log.Error($"{file.error}: {file.filename}");
}
else
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Dump is valid");
Console.ResetColor();
}
}
catch (OptionException)
{
ShowHelp(options);
return 1;
}
catch (Exception e)
{
Log.Error(e, e.Message);
}
Console.WriteLine("Press X or Ctrl-C to exit, any other key to start again...");
var key = Console.ReadKey(true);
switch (key.Key)
{
case ConsoleKey.X:
return 0;
default:
goto start;
}
}
19
View Source File : MainForm.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
private void selectIrdButton_Click(object sender, EventArgs e)
{
var dialog = new OpenFileDialog
{
CheckFileExists = true,
DefaultExt = ".ird",
Filter = "IRD file (*.ird)|*.ird|Redump disc key file (*.dkey)|*.dkey|All supported files|*.ird;*.dkey|All files|*",
FilterIndex = 2,
replacedle = "Select a disc key file",
SupportMultiDottedExtensions = true,
InitialDirectory = settings.IrdDir,
};
var dialogResult = dialog.ShowDialog();
if (dialogResult != DialogResult.OK || string.IsNullOrEmpty(dialog.FileName) || !File.Exists(dialog.FileName))
return;
var discKeyPath = dialog.FileName;
try
{
var discKey = File.ReadAllBytes(discKeyPath);
DiscKeyInfo keyInfo;
if (discKey.Length > 256 / 8)
{
var ird = IrdParser.Parse(discKey);
keyInfo = new DiscKeyInfo(ird.Data1, null, discKeyPath, KeyType.Ird, ird.Crc32.ToString("x8"));
}
else
keyInfo = new DiscKeyInfo(null, discKey, discKeyPath, KeyType.Redump, discKey.ToHexString());
var discKeyFilename = Path.GetFileName(discKeyPath);
var cacheFilename = Path.Combine(settings.IrdDir, discKeyFilename);
if (!File.Exists(cacheFilename))
File.Copy(discKeyPath, cacheFilename);
//todo: proper check
currentDumper.FindDiscKeyAsync(settings.IrdDir).GetAwaiter().GetResult();
if (!currentDumper.IsValidDiscKey(discKey))
{
MessageBox.Show("Selected disk key file contains incompatible file set, and cannot be used with the selected PS3 game disc.", "IRD file check", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
selectIrdButton.Visible = false;
selectIrdButton.Enabled = false;
FindMatchingIrdFinished(sender, new RunWorkerCompletedEventArgs(currentDumper, null, currentDumper?.Cts.IsCancellationRequested ?? true));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "IRD Check Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
19
View Source File : MainForm.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
private void startDumpingButton_Click(object sender, EventArgs e)
{
var outputDir = Path.Combine(settings.OutputDir, currentDumper.OutputDir);
if (Directory.Exists(outputDir))
{
var msgResult = MessageBox.Show(
$"Output folder ({currentDumper.OutputDir}) already exists.\n" +
"Are you sure you want to overwrite any existing files?",
"Output folder check",
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning
);
if (msgResult == DialogResult.No)
return;
}
settingsButton.Enabled = false;
startDumpingButton.Enabled = false;
startDumpingButton.Visible = false;
step3StatusLabel.Text = "⏳";
step3Label.Text = "Decrypting and copying files...";
discBackgroundWorker.DoWork += DumpDisc;
discBackgroundWorker.RunWorkerCompleted += DumpDiscFinished;
discBackgroundWorker.ProgressChanged += DiscDumpUpdateProgress;
discBackgroundWorker.RunWorkerAsync(currentDumper);
cancelDiscDumpButton.Enabled = true;
cancelDiscDumpButton.Visible = true;
dumpingProgressBar.Visible = true;
dumpingProgressLabel.Text = "replacedyzing file structure...";
dumpingProgressLabel.Visible = true;
TaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Normal, Handle);
}
19
View Source File : IrdProvider.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
public async Task<HashSet<DiscKeyInfo>> EnumerateAsync(string discKeyCachePath, string ProductCode, CancellationToken cancellationToken)
{
ProductCode = ProductCode?.ToUpperInvariant();
var result = new HashSet<DiscKeyInfo>();
var knownFilenames = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
Log.Trace("Searching local cache for a match...");
if (Directory.Exists(discKeyCachePath))
{
var matchingIrdFiles = Directory.GetFiles(discKeyCachePath, "*.ird", SearchOption.TopDirectoryOnly);
foreach (var irdFile in matchingIrdFiles)
{
try
{
try
{
var ird = IrdParser.Parse(File.ReadAllBytes(irdFile));
result.Add(new DiscKeyInfo(ird.Data1, null, irdFile, KeyType.Ird, ird.Crc32.ToString("x8")));
knownFilenames.Add(Path.GetFileName(irdFile));
}
catch (InvalidDataException)
{
File.Delete(irdFile);
continue;
}
catch (Exception e)
{
Log.Warn(e);
continue;
}
}
catch (Exception e)
{
Log.Warn(e, e.Message);
}
}
}
Log.Trace("Searching IRD Library for match...");
var irdInfoList = await Client.SearchAsync(ProductCode, cancellationToken).ConfigureAwait(false);
var irdList = irdInfoList?.Data?.Where(
i => !knownFilenames.Contains(i.Filename) && i.Filename.Substring(0, 9).ToUpperInvariant() == ProductCode
).ToList() ?? new List<SearchResulreplacedem>(0);
if (irdList.Count == 0)
Log.Debug("No matching IRD file was found in the Library");
else
{
Log.Info($"Found {irdList.Count} new match{(irdList.Count == 1 ? "" : "es")} in the IRD Library");
foreach (var irdInfo in irdList)
{
var ird = await Client.DownloadAsync(irdInfo, discKeyCachePath, cancellationToken).ConfigureAwait(false);
result.Add(new DiscKeyInfo(ird.Data1, null, Path.Combine(discKeyCachePath, irdInfo.Filename), KeyType.Ird, ird.Crc32.ToString("x8")));
knownFilenames.Add(irdInfo.Filename);
}
}
if (knownFilenames.Count == 0)
{
Log.Warn("No valid matching IRD file could be found");
Log.Info($"If you have matching IRD file, you can put it in '{discKeyCachePath}' and try dumping the disc again");
}
Log.Info($"Found {result.Count} IRD files");
return result;
}
19
View Source File : ModuleCollection.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
public void Load()
{
var modulesRootPath = Path.Combine(AppContext.BaseDirectory, Constants.ROOT_DIR);
if (!Directory.Exists(modulesRootPath))
return;
var moduleDirs = Directory.GetDirectories(modulesRootPath);
if (!moduleDirs.Any())
return;
_replacedemblyHelper = new replacedemblyHelper();
var optionsList = new List<ModuleOptions>();
foreach (var dir in moduleDirs)
{
var code = Path.GetFileName(dir)!.Split("_")[1];
var options = _configuration.Get<ModuleOptions>($"Mkh:Modules:{code}");
if (options.Db != null)
{
options.Code = code;
options.Dir = dir;
optionsList.Add(options);
}
}
foreach (var options in optionsList.OrderBy(m => m.Sort))
{
LoadModule(options);
}
//释放资源
_replacedemblyHelper = null;
}
19
View Source File : ModuleCollection.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
private void LoadModule(ModuleOptions options)
{
var jsonFilePath = Path.Combine(options.Dir, Constants.JSON_FILE_NAME);
if (!File.Exists(jsonFilePath))
return;
using var reader = new StreamReader(jsonFilePath, Encoding.UTF8);
var jsonStr = reader.ReadToEnd();
var moduleDescriptor = JsonSerializer.Deserialize<ModuleDescriptor>(jsonStr);
if (moduleDescriptor == null)
return;
moduleDescriptor.Options = options;
LoadLayerreplacedemblies(moduleDescriptor);
LoadServicesConfigurator(moduleDescriptor);
LoadEnums(moduleDescriptor);
LoadDbInitFilePath(options.Dir, moduleDescriptor);
Add(moduleDescriptor);
}
19
View Source File : ModuleCollection.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
private void LoadDbInitFilePath(string modulePath, ModuleDescriptor descriptor)
{
var filePath = Path.Combine(modulePath, Constants.DB_INIT_FILE_NAME);
if (!File.Exists(filePath))
return;
descriptor.DbInitFilePath = filePath;
}
19
View Source File : CodeGenerator.cs
License : MIT License
Project Creator : 188867052
License : MIT License
Project Creator : 188867052
public bool Generate(CommondConfig config)
{
var context = this.modelGenerator.GenerateCodeAsync(config).Result;
if (string.IsNullOrEmpty(context))
{
return false;
}
Console.WriteLine(context);
string fullPath = Path.Combine(config.ProjectPath, config.OutPutFile);
Console.WriteLine($"Writing file to {fullPath}...");
File.WriteAllText(fullPath, context);
Console.WriteLine("Completed.");
return true;
}
19
View Source File : FileUploadProvider.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
public async Task<IResultModel<FileDescriptor>> Upload(FileUploadModel model, CancellationToken cancellationToken = default)
{
Check.NotNull(model, nameof(model), "file upload model is null");
Check.NotNull(model.StorageRootDirectory, nameof(model.StorageRootDirectory), "the file storage root directory is null");
var result = new ResultModel<FileDescriptor>();
if (model.FormFile == null)
return result.Failed("请选择文件!");
var size = model.FormFile.Length;
//验证文件大小
if (model.MaxSize > 0 && model.MaxSize < size)
return result.Failed($"文件大小不能超过{new FileSize(model.MaxSize).ToString()}");
var name = model.FileName.IsNull() ? model.FormFile.FileName : model.FileName;
var descriptor = new FileDescriptor(name, size);
//验证扩展名
if (model.LimitExtensions != null && !model.LimitExtensions.Any(m => m.EqualsIgnoreCase(descriptor.Extension)))
return result.Failed($"文件格式无效,请上传{model.LimitExtensions.Aggregate((x, y) => x + "," + y)}格式的文件");
//按照日期来保存文件
var date = DateTime.Now;
descriptor.DirectoryName = Path.Combine(model.StorageRootDirectory, date.ToString("yyyy"), date.ToString("MM"), date.ToString("dd"));
//创建目录
if (!Directory.Exists(descriptor.DirectoryName))
{
Directory.CreateDirectory(descriptor.DirectoryName);
}
//生成文件存储名称
descriptor.StorageName = $"{Guid.NewGuid().ToString().Replace("-", "")}.{descriptor.Extension}";
//写入
await using var stream = new FileStream(descriptor.FullName, FileMode.Create);
//计算MD5
if (model.CalculateMd5)
{
descriptor.Md5 = _md5Encrypt.Encrypt(stream);
}
await model.FormFile.CopyToAsync(stream, cancellationToken);
return result.Success(descriptor);
}
19
View Source File : CodeGenerate.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public async Task<string> Setup(TaskBuild taskBuild, List<DbTableInfo> outputTables)
{
try
{
var paths = await Task.Run(() =>
{
var config = new TemplateServiceConfiguration();
config.EncodedStringFactory = new RawStringFactory();
Engine.Razor = RazorEngineService.Create(config);
string path = string.Empty;
foreach (var templatesPath in taskBuild.Templates)
{
path = $"{taskBuild.GeneratePath}\\{taskBuild.DbName}\\{templatesPath.Replace(".tpl", "").Trim()}";
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
var razorId = Guid.NewGuid().ToString("N");
var html = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "Templates", templatesPath));
Engine.Razor.Compile(html, razorId);
//开始生成操作
foreach (var table in outputTables)
{
var sw = new StringWriter();
var model = new RazorModel(taskBuild, outputTables, table);
Engine.Razor.Run(razorId, sw, null, model);
StringBuilder plus = new StringBuilder();
plus.AppendLine("//------------------------------------------------------------------------------");
plus.AppendLine("// <auto-generated>");
plus.AppendLine("// 此代码由工具生成。");
plus.AppendLine("// 运行时版本:" + Environment.Version.ToString());
plus.AppendLine("// Website: http://www.freesql.net");
plus.AppendLine("// 对此文件的更改可能会导致不正确的行为,并且如果");
plus.AppendLine("// 重新生成代码,这些更改将会丢失。");
plus.AppendLine("// </auto-generated>");
plus.AppendLine("//------------------------------------------------------------------------------");
plus.Append(sw.ToString());
plus.AppendLine();
var outPath = $"{path}\\{taskBuild.FileName.Replace("{name}", model.GetCsName(table.Name))}";
if (!string.IsNullOrEmpty(taskBuild.RemoveStr))
outPath = outPath.Replace(taskBuild.RemoveStr, "").Trim();
File.WriteAllText(outPath, plus.ToString());
}
}
return path;
});
Process.Start(paths);
return "生成成功";
}
catch (Exception ex)
{
MessageBox.Show($"生成时发生异常,请检查模版代码: {ex.Message}.");
return $"生成时发生异常,请检查模版代码: {ex.Message}.";
}
}
19
View Source File : ConfigHandler.cs
License : GNU General Public License v3.0
Project Creator : 2dust
License : GNU General Public License v3.0
Project Creator : 2dust
public static int AddCustomServer(ref Config config, string fileName)
{
string newFileName = string.Format("{0}.json", Utils.GetGUID());
//newFileName = Path.Combine(Utils.GetTempPath(), newFileName);
try
{
File.Copy(fileName, Path.Combine(Utils.GetTempPath(), newFileName));
}
catch
{
return -1;
}
VmessItem vmessItem = new VmessItem
{
address = newFileName,
configType = (int)EConfigType.Custom,
remarks = string.Format("import [email protected]{0}", DateTime.Now.ToShortDateString())
};
config.vmess.Add(vmessItem);
if (config.vmess.Count == 1)
{
config.index = 0;
Global.reloadV2ray = true;
}
ToJsonFile(config);
return 0;
}
19
View Source File : CustomMusicManager.cs
License : MIT License
Project Creator : 39M
License : MIT License
Project Creator : 39M
IEnumerator LoadAudioClipAsync(CustomMusicUIItem item, string fileName)
{
string wwwPath = Path.Combine("file:///" + Application.streamingreplacedetsPath, fileName);
using (var loader = new WWW(wwwPath))
{
yield return loader;
if (!string.IsNullOrEmpty(loader.error))
{
// Error
Debug.LogError("Load Streaming replacedets Error: " + loader.error);
yield break;
}
item.clip = NAudioPlayer.FromMp3Data(loader.bytes);
item.clip.name = fileName;
}
}
19
View Source File : PackagesConfigLocator.cs
License : MIT License
Project Creator : 3F
License : MIT License
Project Creator : 3F
private static IEnumerable<string> FindSolutionConfigs(ISlnResult sln, SlnItems items)
{
string dfile = Path.GetFullPath(Path.Combine(sln.SolutionDir, PackagesConfig.FNAME));
if(File.Exists(dfile)) yield return dfile;
if(sln.SolutionFolders != null)
foreach(RawText file in sln.SolutionFolders.SelectMany(f => f.items))
{
if(!file.trimmed.EndsWith(PackagesConfig.FNAME)) continue;
string input = Path.GetFullPath(Path.Combine(sln.SolutionDir, file));
if(File.Exists(input)) yield return input;
}
}
19
View Source File : PackagesConfigLocator.cs
License : MIT License
Project Creator : 3F
License : MIT License
Project Creator : 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
View Source File : Test.cs
License : MIT License
Project Creator : 3wz
License : MIT License
Project Creator : 3wz
IEnumerator Start()
{
string testWav = "testWav.wav";
string testMp3 = "testMp3.mp3";
WWW www = new WWW(GetFileStreamingreplacedetsPath(testWav));
yield return www;
if (string.IsNullOrEmpty(www.error))
{
string saveWavPath = Path.Combine(Application.persistentDataPath, testWav);
File.WriteAllBytes(saveWavPath, www.bytes);
button.onClick.AddListener(() =>
{
string saveMp3Path = Path.Combine(Application.persistentDataPath, testMp3);
var bitRate = string.IsNullOrEmpty(input.text) ? LAMEPreset.ABR_128 : (LAMEPreset)int.Parse(input.text);
WaveToMP3(saveWavPath, saveMp3Path, bitRate);
StartCoroutine(PlayMp3(saveMp3Path));
});
}
}
19
View Source File : NotchSimulator.cs
License : MIT License
Project Creator : 5argon
License : MIT License
Project Creator : 5argon
internal static void UpdateAllMockups()
{
//When building, the scene may open-close multiple times and brought back the mockup canvas,
//which combined with bugs mentioned at https://github.com/5argon/NotchSolution/issues/11,
//will fail the build. This `if` prevents mockup refresh while building.
if (BuildPipeline.isBuildingPlayer) return;
EnsureCanvasAndEventSetup();
//Make the editing environment contains an another copy of mockup canvas.
var prefabStage = PrefabStageUtility.GetCurrentPrefabStage();
if (prefabStage != null)
{
EnsureCanvasAndEventSetup(prefabStage: prefabStage);
}
var settings = Settings.Instance;
bool enableSimulation = settings.EnableSimulation;
var selectedDevice = SimulationDatabase.ByIndex(Settings.Instance.ActiveConfiguration.DeviceIndex);
if (enableSimulation && selectedDevice != null)
{
var name = selectedDevice.Meta.overlay;
Sprite mockupSprite = null;
if (!string.IsNullOrEmpty(name))
{
var filePath = Path.Combine(NotchSimulatorUtility.DevicesFolder, name);
mockupSprite = replacedetDatabase.LoadreplacedetAtPath<Sprite>(filePath);
if (mockupSprite == null)
{
if (System.IO.File.Exists(filePath))
{
Texture2D tex = new Texture2D(1, 1);
tex.LoadImage(System.IO.File.ReadAllBytes(filePath));
mockupSprite = Sprite.Create(tex, new Rect(0.0f, 0.0f, tex.width, tex.height), new Vector2(0.5f, 0.5f), 100.0f);
}
else Debug.LogWarning($"No mockup image named {name} in {NotchSimulatorUtility.DevicesFolder} folder!");
}
}
foreach (var mockup in AllMockupCanvases)
{
mockup.UpdateMockupSprite(
sprite: mockupSprite,
orientation: NotchSimulatorUtility.GetGameViewOrientation(),
simulate: enableSimulation,
flipped: settings.FlipOrientation,
prefabModeOverlayColor: Settings.Instance.PrefabModeOverlayColor
);
}
}
else DestroyHiddenCanvas();
}
19
View Source File : Server.cs
License : MIT License
Project Creator : 5minlab
License : MIT License
Project Creator : 5minlab
public virtual void Awake() {
// check singleton
if(s_instance == null) {
s_instance = this;
} else {
GameObject.Destroy(gameObject);
return;
}
if(dontDestroyOnLoad) {
DontDestroyOnLoad(gameObject);
}
mainThread = Thread.CurrentThread;
fileRoot = Path.Combine(Application.streamingreplacedetsPath, "Sagiri");
// Start server
// 이전에 사용한 서버에 문제가 생겨서 포트번호를 다시 쓸수 없을지 모른다
// 그러면 다음 포트번호로 접속을 시도해보자
var success = false;
for(int i = 0; i < maxRetryCount; i++) {
var portNum = portCandidate + i;
try {
listener = new HttpListener();
listener.Prefixes.Add("http://*:" + portNum + "/");
listener.Start();
listener.BeginGetContext(ListenerCallback, null);
Debug.Log("Starting Sagiri Server on " + Host + ":" + portNum);
success = true;
Port = portNum;
StartCoroutine(HandleRequests());
break;
} catch (SocketException e) {
Debug.LogException(e, this);
Debug.LogFormat(this, "Cannot use Port {0}, use next port", portNum);
}
}
if(!success) {
Debug.Log("Cannot execute Sagiri server");
}
}
19
View Source File : KissMangaDownload.cs
License : GNU General Public License v3.0
Project Creator : 9vult
License : GNU General Public License v3.0
Project Creator : 9vult
public void StartDownloading()
{
File.Create(Path.Combine(chapter.GetChapterRoot().Parent.FullName, "dl" + chapter.GetID())).Close();
string mName = chapter.GetChapterRoot().Parent.Name;
string cUrl = "https://kissmanga.org/chapter/" + mName + "/" + chapter.GetID();
string[] pageUrls = KissMangaHelper.GetPageUrls(cUrl);
foreach (string url in pageUrls)
{
string imgFile = Path.Combine(chapter.GetChapterRoot().FullName, KissMangaHelper.GetPageFileName(url));
DownloadAsync(new Uri(url), imgFile);
}
}
19
View Source File : KissMangaDownload.cs
License : GNU General Public License v3.0
Project Creator : 9vult
License : GNU General Public License v3.0
Project Creator : 9vult
public bool CheckStartNext()
{
if (clients.Count == 0)
{
DownloadCompleted.Invoke(this);
File.Delete(Path.Combine(chapter.GetChapterRoot().Parent.FullName, "dl" + chapter.GetID()));
return true;
}
return false;
}
19
View Source File : MangaDexDownload.cs
License : GNU General Public License v3.0
Project Creator : 9vult
License : GNU General Public License v3.0
Project Creator : 9vult
public void StartDownloading()
{
File.Create(Path.Combine(chapter.GetChapterRoot().Parent.FullName, "dl" + chapter.GetID())).Close();
string jsonUrl = MangaDexHelper.MANGADEX_URL + "/api/chapter/" + chapter.GetID();
string jsonString;
using (var wc = new WebClient())
{
jsonString = wc.DownloadString(jsonUrl);
}
JObject jobj = JObject.Parse(jsonString);
string server = (string)jobj["server"];
string hash = (string)jobj["hash"];
// string[] page_array = /* ((string) */ jobj["page_array"]. /* ).Split(',') */;
List<string> page_array = new List<string>();
IJEnumerable<JToken> jtokens = jobj["page_array"].Values();
foreach(JToken t in jtokens)
{
page_array.Add((string)t);
}
foreach (string file in page_array)
{
if (server == "/data/")
server = MangaDexHelper.MANGADEX_URL + "/data/";
string imgUrl = server + hash + "/" + file;
FileInfo imgFile = new FileInfo(
Path.Combine(
chapter.GetChapterRoot().FullName,
ConvertToNumericFileName(file)
));
if (File.Exists(imgFile.FullName))
if (imgFile.Length <= 0)
File.Delete(imgFile.FullName);
DownloadAsync(new Uri(imgUrl), imgFile.FullName);
}
}
19
View Source File : NhentaiDownload.cs
License : GNU General Public License v3.0
Project Creator : 9vult
License : GNU General Public License v3.0
Project Creator : 9vult
public void StartDownloading()
{
File.Create(Path.Combine(chapter.GetChapterRoot().Parent.FullName, "dl" + chapter.GetID())).Close();
List<HtmlDoreplacedent> docs = new List<HtmlDoreplacedent>();
int pageCount = NhentaiHelper.GetPageCount("https://nhentai.net/g/" + chapter.GetID());
string hUrl = "https://nhentai.net/g/" + chapter.GetID() + "/";
string baseUrl = NhentaiHelper.GetImageUrl(hUrl + "1");
string hash = NhentaiHelper.GetHash(baseUrl);
for (int page = 1; page <= pageCount; page++)
{
string imgUrl = NhentaiHelper.ImgBase() + hash + "/" + page + "." + NhentaiHelper.GetExt(baseUrl);
string imgFile = Path.Combine(chapter.GetChapterRoot().FullName, page + "." + NhentaiHelper.GetExt(baseUrl));
DownloadAsync(new Uri(imgUrl), imgFile);
}
}
19
View Source File : SettingsHelper.cs
License : GNU General Public License v3.0
Project Creator : 9vult
License : GNU General Public License v3.0
Project Creator : 9vult
public static void Create()
{
File.WriteAllLines(Path.Combine(
FileHelper.APP_ROOT.FullName, "mikureader.txt"),
new string[] {
"False // Use Double-Page Reader",
"True // Check for updates on startup"
}
);
}
19
View Source File : FrmBrowser.cs
License : GNU General Public License v3.0
Project Creator : 9vult
License : GNU General Public License v3.0
Project Creator : 9vult
private void BtnAdd_Click(object sender, EventArgs e)
{
string url = gfxBrowser.Url.ToString();
string name = string.Empty;
string num = string.Empty;
switch (cmboSource.SelectedItem.ToString().ToLower())
{
case "mangadex":
name = url.Split('/')[5];
num = url.Split('/')[4];
url = MangaDexHelper.MANGADEX_URL + "/api/manga/" + num;
Manga m = new MangaDex(FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, num)), url);
FrmEdit editor = new FrmEdit(m, false);
DialogResult result = editor.ShowDialog();
if (result == DialogResult.OK)
{
// cleanup
foreach (Chapter ch in m.GetChapters())
{
try
{
string s = ch.GetChapterRoot().ToString();
Directory.Delete(ch.GetChapterRoot().ToString());
} catch (Exception) { }
}
WFClient.dbm.GetMangaDB().Add(m);
String[] dls = m.GetDLChapters();
if (dls == null || dls[0].Equals("-1"))
{
foreach (Chapter c in m.GetSetPrunedChapters(false))
{
WFClient.dlm.AddToQueue(new MangaDexDownload(c));
}
} else
{ // Only download selected chapters
foreach (Chapter c in m.GetSetPrunedChapters(false))
{
if (dls.Contains(c.GetNum()))
{
WFClient.dlm.AddToQueue(new MangaDexDownload(c));
}
}
}
// Start downloading the first one
WFClient.dlm.DownloadNext();
} else
{
}
break;
case "kissmanga":
// MessageBox.Show("Sorry, can't do this yet! ;(\n\n(ignore the download started box)");
// break;
// TODO
string kName = KissMangaHelper.GetName(url);
string kHash = KissMangaHelper.GetHash(url);
// Manga km = new Manga(FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, num)), url);
Manga km = new KissManga(FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, kHash)), url);
FrmEdit editor1 = new FrmEdit(km, false);
DialogResult result1 = editor1.ShowDialog();
if (result1 == DialogResult.OK)
{
// cleanup
foreach (Chapter ch in km.GetChapters())
{
try
{
string s = ch.GetChapterRoot().ToString();
Directory.Delete(ch.GetChapterRoot().ToString());
}
catch (Exception) { }
}
WFClient.dbm.GetMangaDB().Add(km);
String[] dls = km.GetDLChapters();
if (dls == null || dls[0].Equals("-1"))
{
foreach (Chapter c in km.GetSetPrunedChapters(false))
{
WFClient.dlm.AddToQueue(new KissMangaDownload(c));
}
}
else
{ // Only download selected chapters
foreach (Chapter c in km.GetSetPrunedChapters(false))
{
if (dls.Contains(c.GetNum()))
{
WFClient.dlm.AddToQueue(new KissMangaDownload(c));
}
}
}
// Start downloading the first one
WFClient.dlm.DownloadNext();
}
else
{
}
break;
case "nhentai":
num = url.Split('/')[4];
name = gfxBrowser.Doreplacedentreplacedle.Substring(0, gfxBrowser.Doreplacedentreplacedle.IndexOf("nhentai:") - 3);
JObject hJson = new JObject(
new JProperty("hentai",
new JObject(
new JProperty("replacedle", name),
new JProperty("num", num),
new JProperty("url", url))));
DirectoryInfo hDir = FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, "h" + num));
Hentai h = new Nhentai(hDir, hJson.ToString());
FrmEdit edit = new FrmEdit(h, false);
DialogResult rezult = edit.ShowDialog();
if (rezult == DialogResult.OK)
{
WFClient.dbm.GetMangaDB().Add(h);
Chapter ch = h.GetChapters()[0];
WFClient.dlm.AddToQueue(new NhentaiDownload(ch));
// Start downloading the first one
WFClient.dlm.DownloadNext();
}
break;
}
MessageBox.Show("Download started! You may close the browser at any time, but please keep MikuReader open until the download has completed.");
}
19
View Source File : FrmLauncher.cs
License : GNU General Public License v3.0
Project Creator : 9vult
License : GNU General Public License v3.0
Project Creator : 9vult
private void FrmLauncher_Load(object sender, EventArgs e)
{
WFClient.logger.Log("Starting");
// Set embedded fonts
label1.Font = bigFont;
label2.Font = smallFont;
if (Properties.Settings.Default["approot"].ToString() == String.Empty)
{
Properties.Settings.Default["approot"] = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MikuReader2");
Properties.Settings.Default.Save();
}
FileHelper.APP_ROOT = FileHelper.CreateDI(Properties.Settings.Default["approot"].ToString());
Directory.CreateDirectory(FileHelper.APP_ROOT.FullName);
WFClient.logger.Log("Loading from " + FileHelper.APP_ROOT);
if (File.Exists(Path.Combine(FileHelper.APP_ROOT.FullName, "mikureader.txt")))
{
SettingsHelper.Initialize();
}
else
{
SettingsHelper.Create();
SettingsHelper.Initialize();
}
WFClient.dlm.ProgressUpdated += new ProgressUpdatedEventHandler(ProgressUpdatedCallback);
RepopulateItems();
if (SettingsHelper.CheckForUpdates)
Updater.Start();
}
19
View Source File : BrowsePage.cs
License : GNU General Public License v3.0
Project Creator : 9vult
License : GNU General Public License v3.0
Project Creator : 9vult
private void BtnAdd_Clicked(object sender, EventArgs e)
{
string url = txtUrl.Text;
string name = string.Empty;
string num = string.Empty;
if (url == "" || url == null)
{
PopUp("Error", "Please enter a URL");
return;
}
if (url.StartsWith("https://mangadex.org/replacedle/"))
{
// TODO: Name
name = url.Split('/')[5];
num = url.Split('/')[4];
url = "https://mangadex.org/api/manga/" + num;
Manga m = new Manga(FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, num)), url);
MClient.dbm.GetMangaDB().Add(m);
foreach (Chapter c in m.GetChapters())
{
MClient.dlm.AddToQueue(new MangaDexDownload(c));
}
// Start downloading the first one
MClient.dlm.DownloadNext();
}
else if (url.StartsWith("https://nhentai.net/g/"))
{
num = url.Split('/')[4];
name = txtName.Text != "" ? txtName.Text : "Hentai " + new Random().Next();
JObject hJson = new JObject(
new JProperty("hentai",
new JObject(
new JProperty("replacedle", name),
new JProperty("num", num),
new JProperty("url", url))));
DirectoryInfo hDir = FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, "h" + num));
Hentai h = new Hentai(hDir, hJson.ToString());
MClient.dbm.GetMangaDB().Add(h);
Chapter ch = h.GetChapters()[0];
MClient.dlm.AddToQueue(new NhentaiDownload(ch));
// Start downloading the first one
MClient.dlm.DownloadNext();
} else
{
PopUp("Error", "Invalid URL!");
return;
}
PopUp("Info", "Download started!\nPlease do not close MikuReader until the download is complete.");
}
19
View Source File : ListPage.cs
License : GNU General Public License v3.0
Project Creator : 9vult
License : GNU General Public License v3.0
Project Creator : 9vult
private void temp()
{
var url = "https://mangadex.org/api/manga/" + "32043";
Manga m = new Manga(FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, "32043")), url);
MClient.dbm.GetMangaDB().Add(m);
foreach (Chapter c in m.GetChapters())
{
MClient.dlm.AddToQueue(new MangaDexDownload(c));
}
MClient.dlm.DownloadNext();
RepopulateItems();
}
19
View Source File : RecordService.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
public string GetRecordFilename(string streamName)
{
return Path.Combine(_configuration.RecordPath, _configuration.FilenameFormat.Replace("{streamName}", streamName));
}
19
View Source File : FileUtils.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public static string GetInternalDataStoreFolder(bool fullPath = false, bool editorOnly = true)
{
var settingsFolderPath = "";
if (fullPath)
settingsFolderPath = Path.Combine(Application.dataPath, Path.Combine("UMA", "InternalDataStore"));
else
settingsFolderPath = Path.Combine("replacedets", Path.Combine("UMA", "InternalDataStore"));
if (editorOnly)
{
settingsFolderPath = Path.Combine(settingsFolderPath, "InEditor");
}
else
{
settingsFolderPath = Path.Combine(settingsFolderPath, Path.Combine("InGame", "Resources"));
}
if (!Directory.Exists(settingsFolderPath))
Directory.CreateDirectory(settingsFolderPath);
if (fullPath)
settingsFolderPath = Path.GetFullPath(settingsFolderPath);
return settingsFolderPath;
}
19
View Source File : compiler.cs
License : MIT License
Project Creator : aaaddress1
License : MIT License
Project Creator : aaaddress1
public static bool generateExe(string asmPath, string exeOutPath)
{
Process p = new Process();
p.StartInfo.RedirectStandardError = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = Path.Combine(Properties.Settings.Default.gwPath, "g++.exe");
p.StartInfo.WorkingDirectory = Properties.Settings.Default.gwPath;
p.StartInfo.Arguments = string.Format("{0} -masm=intel {2} -o {1}", asmPath, exeOutPath, Properties.Settings.Default.linkArg);
p.Start();
string errr = p.StandardError.ReadToEnd();
string oupt = p.StandardOutput.ReadToEnd();
p.WaitForExit();
if (File.Exists(exeOutPath)) return true;
Program.mainUi.Invoke((MethodInvoker)delegate ()
{
if (logText == null) return;
logMsg("============= Error =============", Color.Red);
logMsg(errr + oupt, Color.Red);
});
return false;
}
19
View Source File : config.cs
License : MIT License
Project Creator : aaaddress1
License : MIT License
Project Creator : aaaddress1
private void button1_Click(object sender, EventArgs e)
{
var gwPathInput = this.gwPathTB.Text;
if (!new DirectoryInfo(gwPathInput).Exists)
{
MessageBox.Show(string.Format("MinGW path \"{0}\" not found!", gwPathInput));
return;
}
if (!new FileInfo(Path.Combine(gwPathInput, "gcc.exe")).Exists)
{
MessageBox.Show(string.Format("MinGW compiler \"{0}\" not found!", Path.Combine(gwPathInput, "gcc.exe")));
return;
}
if (!new FileInfo(Path.Combine(gwPathInput, "ld.exe")).Exists)
{
MessageBox.Show(string.Format("MinGW linker \"{0}\" not found!", Path.Combine(gwPathInput, "ld.exe")));
return;
}
int p = 0;
if (!int.TryParse(this.obfusPcntTB.Text, out p))
{
MessageBox.Show(string.Format("Obfuscate % \"{0}\" not found!", this.obfusPcntTB.Text));
return;
}
Properties.Settings.Default.gwPath = this.gwPathTB.Text;
Properties.Settings.Default.linkArg = this.lkArgTB.Text;
Properties.Settings.Default.clArg = this.clArgTB.Text;
Properties.Settings.Default.obfusPcnt = p;
Properties.Settings.Default.cnfseCode = this.cnfOrgJunk.Checked;
Properties.Settings.Default.insrtJunk = this.insrtJunkCB.Checked;
Properties.Settings.Default.clnAftCompile = this.clnComplieCB.Checked;
Properties.Settings.Default.Save();
MessageBox.Show("save config successfully!");
this.Close();
}
19
View Source File : TestCustomizerDD.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public void ListLoadableFiles(ScrollRect ItemList)
{
var thisSubFolder = Avatar.loadPath.TrimStart('\\', '/').TrimEnd('\\', '/').Trim();//trim this at the start and the end of slashes. And then we may need to switch any slashes in the middle depending on the platform- for explode on them or something
//we can find things in resources/thisSubFolder and in persistentDataPath/thisSubFolder
//Clear the item list
ItemList.content.GetComponent<VerticalLayoutGroup>().enabled = false;//dont seem to be able to clear the content with this on...
foreach (Transform child in ItemList.content.transform)
{
Destroy(child.gameObject);
}
ItemList.content.GetComponent<VerticalLayoutGroup>().enabled = true;
//- I need to basically get rid of the other oprions in CharacterAvatars enumerator since they are effectively useless apart from in the editor
var persistentPath = Path.Combine(Application.persistentDataPath, thisSubFolder);
if (Directory.Exists(persistentPath))
{
string[] persistentDataFiles = Directory.GetFiles(persistentPath, "*.txt");
foreach (string path in persistentDataFiles)
{
GameObject thisLoadableItem = Instantiate(loadableItemPrefab) as GameObject;
thisLoadableItem.transform.SetParent(ItemList.content.transform, false);
thisLoadableItem.GetComponent<CSLoadableItem>().customizerScript = this;
thisLoadableItem.GetComponent<CSLoadableItem>().filepath = path;
thisLoadableItem.GetComponent<CSLoadableItem>().filename = Path.GetFileNameWithoutExtension(path);
thisLoadableItem.GetComponentInChildren<Text>().text = Path.GetFileNameWithoutExtension(path);
}
}
foreach (KeyValuePair<string, string> kp in (UMAContext.Instance.dynamicCharacterSystem as DynamicCharacterSystem).CharacterRecipes)
{
GameObject thisLoadableItem = Instantiate(loadableItemPrefab) as GameObject;
thisLoadableItem.transform.SetParent(ItemList.content.transform, false);
thisLoadableItem.GetComponent<CSLoadableItem>().customizerScript = this;
thisLoadableItem.GetComponent<CSLoadableItem>().filename = Path.GetFileNameWithoutExtension(kp.Key);
thisLoadableItem.GetComponentInChildren<Text>().text = Path.GetFileNameWithoutExtension(kp.Key);
}
}
19
View Source File : compiler.cs
License : MIT License
Project Creator : aaaddress1
License : MIT License
Project Creator : aaaddress1
public static bool geneateAsmSource(string srcPath, string outAsmPath)
{
Process p = new Process();
p.StartInfo.RedirectStandardError = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = Path.Combine(Properties.Settings.Default.gwPath, "g++.exe");
p.StartInfo.WorkingDirectory = Properties.Settings.Default.gwPath;
p.StartInfo.Arguments = string.Format("-S {0} -masm=intel {2} -o {1}", srcPath, outAsmPath, Properties.Settings.Default.clArg);
p.Start();
string errr = p.StandardError.ReadToEnd();
string oupt = p.StandardOutput.ReadToEnd();
p.WaitForExit();
if (File.Exists(outAsmPath)) return true;
Program.mainUi.Invoke((MethodInvoker)delegate ()
{
if (logText == null) return;
logMsg("============= Error =============", Color.Red);
logMsg(errr + oupt, Color.Red);
});
return false;
}
19
View Source File : HistoryViewer.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : 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
View Source File : RepositorySaveData.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
private string GetFileNameBase(string login)
{
return Path.Combine(MainRepository.SaveFolderDataPlayers, Repository.NormalizeLogin(login) + ".dat");
}
19
View Source File : FileChecker.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public static void FileSynchronization(string modsDir, ModelModsFiles serverFiles)
{
restoreFolderTree(modsDir, serverFiles.FoldersTree);
foreach (var serverFile in serverFiles.Files)
{
var fullName = Path.Combine(modsDir, serverFile.FileName);
// Имя присутствует в списке, файл необходимо будет удалить ( или заменить)
if (File.Exists(fullName))
{
File.Delete(fullName);
}
if (serverFile.Hash == null)
{
continue;
}
// Create the file, or overwrite if the file must exist.
using (FileStream fs = File.Create(fullName))
{
Loger.Log("Restore: " + fullName);
if (serverFile.Hash.Length > 0)
{
fs.Write(serverFile.Hash, 0, serverFile.Hash.Length);
}
}
}
}
19
View Source File : FileChecker.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
private static void restoreFolderTree(string modsDir, FoldersTree foldersTree)
{
if (foldersTree.SubDirs == null)
{
return;
}
foreach (var folder in foldersTree.SubDirs)
{
var dirName = Path.Combine(modsDir, folder.directoryName);
if (!Directory.Exists(dirName))
{
Loger.Log($"Create directory: {dirName}");
Directory.CreateDirectory(dirName);
}
// check and create subdirs
restoreFolderTree(dirName, folder);
}
}
19
View Source File : FileChecker.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public static byte[] CreateListFolder(string directory)
{
var dirs = Directory.GetDirectories(directory).OrderBy(x => x);
var sb = new StringBuilder();
foreach (var dir in dirs)
{
// только для дебага, а то папка Online city каждый раз обновляется
var di = new DirectoryInfo(dir);
#if DEBUG
if (di.Name.Equals("OnlineCity"))
continue;
#endif
sb.AppendLine(di.Name);
}
var txt = sb.ToString();
var diRoot = new DirectoryInfo(directory);
File.WriteAllText(Path.Combine(Loger.PathLog, diRoot.Name + ".txt"), txt);
return Encoding.ASCII.GetBytes(txt);
}
19
View Source File : App.xaml.cs
License : Microsoft Public License
Project Creator : AArnott
License : Microsoft Public License
Project Creator : 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
View Source File : SimpleAnimationNodeEditor.cs
License : MIT License
Project Creator : aarthificial
License : MIT License
Project Creator : 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
View Source File : ImageSaver.cs
License : MIT License
Project Creator : Abdulrhman5
License : MIT License
Project Creator : Abdulrhman5
public async Task<CommandResult<SavedImageViewModel>> SaveImage(IFormFile image)
{
if (image is null)
{
return new CommandResult<SavedImageViewModel>(
new ErrorMessage
{
ErrorCode = "IMAGE.NULL",
Message = "Please send a valid data",
StatusCode = System.Net.HttpStatusCode.BadRequest
});
}
if (!ImageMimeType.Any(m => m.EqualsIC(image.ContentType))
|| !ImageExtension.Any(e => e.EqualsIC(Path.GetExtension(image.FileName))))
{
return new CommandResult<SavedImageViewModel>(new ErrorMessage
{
ErrorCode = "IMAGE.NOT.IMAGE",
Message = "Please send image",
StatusCode = System.Net.HttpStatusCode.BadRequest
});
}
if (image.Length == 0)
{
return new CommandResult<SavedImageViewModel>(
new ErrorMessage
{
ErrorCode = "IMAGE.TOO.SMALL",
Message = "Please send a valid image",
StatusCode = System.Net.HttpStatusCode.BadRequest
});
}
if (image.Length > 4 * 1024 * 1024)
{
return new CommandResult<SavedImageViewModel>(
new ErrorMessage
{
ErrorCode = "IMAGE.TOO.LARGE",
Message = "Please send a smaller image",
StatusCode = System.Net.HttpStatusCode.BadRequest
});
}
var name = Guid.NewGuid();
var withExtension = name + Path.GetExtension(image.FileName);
var path = Path.Combine(contentRoot, "replacedets", "Images", "Profile");
Directory.CreateDirectory(path);
var full = Path.Combine(path, withExtension);
try
{
using (Stream s = new FileStream(full, FileMode.OpenOrCreate))
{
await image.CopyToAsync(s);
}
return new CommandResult<SavedImageViewModel>(new SavedImageViewModel
{
Name = name,
Path = full,
});
}
catch (Exception e)
{
_logger.LogError(e, "An error occurred while trying to save an image to the desk");
return new CommandResult<SavedImageViewModel>(new ErrorMessage
{
ErrorCode = "IMAGE.ERROR",
Message = "An error occurred while trying to save the image",
StatusCode = System.Net.HttpStatusCode.InternalServerError
});
}
}
19
View Source File : SimMachine.cs
License : MIT License
Project Creator : abdullin
License : MIT License
Project Creator : abdullin
public string GetServiceFolder(string service, string name) {
var sim = Runtime.GetSimulationFolder();
var folder = Path.Combine(Name, $"{service}_{name}");
var localPath = Path.Combine(sim, folder);
if (!Directory.Exists(localPath)) {
Debug(LogType.RuntimeInfo, $"Allocating folder {folder}");
Directory.CreateDirectory(localPath);
} else {
Debug(LogType.RuntimeInfo, $"Reusing folder {folder}");
}
return localPath;
}
19
View Source File : SimMachine.cs
License : MIT License
Project Creator : abdullin
License : MIT License
Project Creator : abdullin
public void WipeStorage() {
var sim = Runtime.GetSimulationFolder();
var machinePath = Path.Combine(sim, Name);
if (Directory.Exists(machinePath)) {
Debug(LogType.Fault, $"ERASE STORAGE for machine {Name}");
Directory.Delete(machinePath, true);
}
}
See More Examples