Here are the examples of the csharp api System.IO.File.Copy(string, string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
831 Examples
19
View Source File : Program.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 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
View Source File : Program.cs
License : MIT License
Project Creator : 0x727
License : MIT License
Project Creator : 0x727
public static void Copy(string inputfile, string randomname, string min)
{
string appdataFile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string sourceFile = [email protected]"{inputfile}";
//获取拓展名
string extension = Path.GetExtension(sourceFile);
string destinationFile = appdataFile + [email protected]"\Microsoft\Windows\Themes\{randomname}" + extension;
if (File.Exists(destinationFile))
{
Console.WriteLine($"\n[x] File name exists: {destinationFile}");
return;
}
else
{
File.Copy(sourceFile, destinationFile);
//File.Move(sourceFile, destinationFile);
Console.WriteLine($"\n[*] Copy File location: \n{destinationFile}");
CreateTask(randomname, destinationFile, min);
}
}
19
View Source File : Utils.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
public static void CopyDir(string fromDir, string toDir)
{
if (!Directory.Exists(fromDir))
return;
if (!Directory.Exists(toDir))
{
Directory.CreateDirectory(toDir);
}
string[] files = Directory.GetFiles(fromDir);
foreach (string formFileName in files)
{
string fileName = Path.GetFileName(formFileName);
string toFileName = Path.Combine(toDir, fileName);
File.Copy(formFileName, toFileName);
}
string[] fromDirs = Directory.GetDirectories(fromDir);
foreach (string fromDirName in fromDirs)
{
string dirName = Path.GetFileName(fromDirName);
string toDirName = Path.Combine(toDir, dirName);
CopyDir(fromDirName, toDirName);
}
}
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 : AssetBundleUtil.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public static void BuildreplacedetBundle(replacedetBundleSetting replacedetBundleSetting)
{
Dictionary<string, replacedetBundleData> replacedetBundleDataDict = new Dictionary<string, replacedetBundleData>();
Dictionary<string, replacedetBundleRuleType> replacedetBundleRuleTypeDict = new Dictionary<string, replacedetBundleRuleType>();
string path = PathUtil.GetPath(PathType.DataPath, replacedetBundleSetting.outputPath, GetPlatformForreplacedetBundle(EditorUserBuildSettings.activeBuildTarget));
foreach (DirectoryInfo item in DirectoryUtil.GetDirectorys(new DirectoryInfo(path), new List<DirectoryInfo>()))
{
item.Delete();
}
foreach (FileInfo item in FileUtil.GetFiles(new DirectoryInfo(path), new List<FileInfo>()))
{
item.Delete();
}
List<replacedetBundleBuild> replacedetBundleBuildList = new List<replacedetBundleBuild>();
foreach (replacedetBundleRule item in replacedetBundleSetting.replacedetBundleRuleList)
{
if (item.replacedetBundleRuleType == replacedetBundleRuleType.File)
{
FileInfo[] fileInfos = FileUtil.GetFiles(new DirectoryInfo(item.path), new List<FileInfo>());
if (fileInfos.Length == 0) continue;
List<FileInfo> fileInfoList = (from fileInfo in fileInfos where !string.IsNullOrEmpty(Path.GetExtension(fileInfo.Name)) && Path.GetExtension(fileInfo.Name) != ".meta" select fileInfo).ToList();
foreach (FileInfo fileInfo in fileInfoList)
{
replacedetBundleRuleTypeDict.Add(fileInfo.FullName.Substring(fileInfo.FullName.IndexOf("replacedets")).Replace("\\", "/"), replacedetBundleRuleType.File);
}
}
if (item.replacedetBundleRuleType == replacedetBundleRuleType.Directory)
{
DirectoryInfo[] directoryInfos = DirectoryUtil.GetDirectorys(new DirectoryInfo(item.path), new List<DirectoryInfo>());
if (directoryInfos.Length == 0) continue;
foreach (DirectoryInfo directoryInfo in directoryInfos)
{
FileInfo[] fileInfos = directoryInfo.GetFiles();
if (fileInfos.Length == 0) continue;
List<FileInfo> fileInfoList = (from fileInfo in fileInfos where !string.IsNullOrEmpty(Path.GetExtension(fileInfo.Name)) && Path.GetExtension(fileInfo.Name) != ".meta" select fileInfo).ToList();
foreach (FileInfo fileInfo in fileInfoList)
{
replacedetBundleRuleTypeDict.Add(fileInfo.FullName.Substring(fileInfo.FullName.IndexOf("replacedets")).Replace("\\", "/"), replacedetBundleRuleType.Directory);
}
}
}
}
foreach (replacedetBundleData item in replacedetBundleSetting.replacedetBundleDataList)
{
replacedetBundleBuildList.Add(new replacedetBundleBuild()
{
replacedetBundleName = item.replacedetBundleName,
replacedetNames = item.replacedetNames,
});
}
replacedetBundleManifest replacedetBundleManifest = BuildPipeline.BuildreplacedetBundles(path, replacedetBundleBuildList.ToArray(), BuildreplacedetBundleOptions.None, EditorUserBuildSettings.activeBuildTarget);
foreach (replacedetBundleData item in replacedetBundleSetting.replacedetBundleDataList)
{
item.replacedetBundleHash = replacedetBundleManifest.GetreplacedetBundleHash(item.replacedetBundleName).ToString();
BuildPipeline.GetCRCForreplacedetBundle($"{path}/{item.replacedetBundleName}", out item.replacedetBundleCRC);
item.fileSize = FileUtil.GetFileSize($"{path}/{item.replacedetBundleName}");
replacedetBundleDataDict.Add(Path.GetFileNameWithoutExtension(item.replacedetBundleName), item);
}
replacedetBundleConfig replacedetBundleConfig = new replacedetBundleConfig(replacedetBundleSetting.buildId, replacedetBundleDataDict, replacedetBundleRuleTypeDict);
FileUtil.Savereplacedet(path, "replacedetBundleConfig.json", JsonUtil.ToJson(replacedetBundleConfig));
if (replacedetBundleSetting.isCopyStreamingreplacedets)
{
string copyPath = PathUtil.GetPath(PathType.StreamingreplacedetsPath, "Res", GetPlatformForreplacedetBundle(EditorUserBuildSettings.activeBuildTarget));
foreach (DirectoryInfo item in DirectoryUtil.GetDirectorys(new DirectoryInfo(copyPath), new List<DirectoryInfo>()))
{
item.Delete();
}
foreach (FileInfo item in FileUtil.GetFiles(new DirectoryInfo(copyPath), new List<FileInfo>()))
{
item.Delete();
}
foreach (FileInfo item in FileUtil.GetFiles(new DirectoryInfo(path), new List<FileInfo>()))
{
if (Path.GetExtension(item.Name) == ".meta") continue;
File.Copy(item.FullName, $"{PathUtil.GetPath(PathType.StreamingreplacedetsPath, "Res", GetPlatformForreplacedetBundle(EditorUserBuildSettings.activeBuildTarget))}/{item.Name}");
}
}
replacedetDatabase.Refresh();
}
19
View Source File : AndroidVideoEditorUtil.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
[MenuItem("Oculus/Video/Enable Native Android Video Player")]
public static void EnableNativeVideoPlayer()
{
// rename NativeJavaPlayer.java.DISABLED to NativeJavaPlayer.java
if (File.Exists(disabledPlayerFileName))
{
File.Move(disabledPlayerFileName, videoPlayerFileName);
File.Move(disabledPlayerFileName + ".meta", videoPlayerFileName + ".meta");
}
replacedetDatabase.Importreplacedet(videoPlayerFileName);
replacedetDatabase.Deletereplacedet(disabledPlayerFileName);
// Enable audio plugins
PluginImporter audio360 = (PluginImporter)replacedetImporter.GetAtPath(audio360PluginPath);
PluginImporter audio360exo29 = (PluginImporter)replacedetImporter.GetAtPath(audio360Exo29PluginPath);
if (audio360 != null && audio360exo29 != null)
{
audio360.SetCompatibleWithPlatform(BuildTarget.Android, true);
audio360exo29.SetCompatibleWithPlatform(BuildTarget.Android, true);
audio360.SaveAndReimport();
audio360exo29.SaveAndReimport();
}
// Enable gradle build with exoplayer
EditorUserBuildSettings.androidBuildSystem = AndroidBuildSystem.Gradle;
// create android plugins directory if it doesn't exist
if (!Directory.Exists(androidPluginsFolder))
{
Directory.CreateDirectory(androidPluginsFolder);
}
if (!File.Exists(gradleTemplatePath))
{
if (File.Exists(gradleTemplatePath + ".DISABLED"))
{
File.Move(disabledGradleTemplatePath, gradleTemplatePath);
File.Move(disabledGradleTemplatePath + ".meta", gradleTemplatePath+".meta");
}
else
{
File.Copy(internalGradleTemplatePath, gradleTemplatePath);
}
replacedetDatabase.Importreplacedet(gradleTemplatePath);
}
// parse the gradle file to check the current version:
string currentFile = File.ReadAllText(gradleTemplatePath);
List<string> lines = new List<string>(currentFile.Split('\n'));
var gradleVersion = new System.Text.RegularExpressions.Regex("com.android.tools.build:gradle:([0-9]+\\.[0-9]+\\.[0-9]+)").Match(currentFile).Groups[1].Value;
if (gradleVersion == "2.3.0")
{
// add google() to buildscript/repositories
int buildscriptRepositories = GoToSection("buildscript.repositories", lines);
if (FindInScope("google\\(\\)", buildscriptRepositories + 1, lines) == -1)
{
lines.Insert(GetScopeEnd(buildscriptRepositories + 1, lines), "\t\tgoogle()");
}
// add google() and jcenter() to allprojects/repositories
int allprojectsRepositories = GoToSection("allprojects.repositories", lines);
if (FindInScope("google\\(\\)", allprojectsRepositories + 1, lines) == -1)
{
lines.Insert(GetScopeEnd(allprojectsRepositories + 1, lines), "\t\tgoogle()");
}
if (FindInScope("jcenter\\(\\)", allprojectsRepositories + 1, lines) == -1)
{
lines.Insert(GetScopeEnd(allprojectsRepositories + 1, lines), "\t\tjcenter()");
}
}
// add "compile 'com.google.android.exoplayer:exoplayer:2.9.5'" to dependencies
int dependencies = GoToSection("dependencies", lines);
if (FindInScope("com\\.google\\.android\\.exoplayer:exoplayer", dependencies + 1, lines) == -1)
{
lines.Insert(GetScopeEnd(dependencies + 1, lines), "\tcompile 'com.google.android.exoplayer:exoplayer:2.9.5'");
}
int android = GoToSection("android", lines);
// add compileOptions to add Java 1.8 compatibility
if (FindInScope("compileOptions", android + 1, lines) == -1)
{
int compileOptionsIndex = GetScopeEnd(android + 1, lines);
lines.Insert(compileOptionsIndex, "\t}");
lines.Insert(compileOptionsIndex, "\t\ttargetCompatibility JavaVersion.VERSION_1_8");
lines.Insert(compileOptionsIndex, "\t\tsourceCompatibility JavaVersion.VERSION_1_8");
lines.Insert(compileOptionsIndex, "\tcompileOptions {");
}
// add sourceSets if Version < 2018.2
#if !UNITY_2018_2_OR_NEWER
if (FindInScope("sourceSets\\.main\\.java\\.srcDir", android + 1, lines) == -1)
{
lines.Insert(GetScopeEnd(android + 1, lines), "\tsourceSets.main.java.srcDir \"" + gradleSourceSetPath + "\"");
}
#endif
File.WriteAllText(gradleTemplatePath, string.Join("\n", lines.ToArray()));
}
19
View Source File : Program.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public static void Main(string[] args)
{
var consolereplacedle = $"ACEmulator - v{ServerBuildInfo.FullVersion}";
Console.replacedle = consolereplacedle;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit);
// Typically, you wouldn't force the current culture on an entire application unless you know sure your application is used in a specific region (which ACE is not)
// We do this because almost all of the client/user input/output code does not take culture into account, and replacedumes en-US formatting.
// Without this, many commands that require special characters like , and . will break
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
// Init our text encoding options. This will allow us to use more than standard ANSI text, which the client also supports.
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
// Look for the log4net.config first in the current environment directory, then in the Executingreplacedembly location
var exeLocation = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
var containerConfigDirectory = "/ace/Config";
var log4netConfig = Path.Combine(exeLocation, "log4net.config");
var log4netConfigExample = Path.Combine(exeLocation, "log4net.config.example");
var log4netConfigContainer = Path.Combine(containerConfigDirectory, "log4net.config");
if (IsRunningInContainer && File.Exists(log4netConfigContainer))
File.Copy(log4netConfigContainer, log4netConfig, true);
var log4netFileInfo = new FileInfo("log4net.config");
if (!log4netFileInfo.Exists)
log4netFileInfo = new FileInfo(log4netConfig);
if (!log4netFileInfo.Exists)
{
var exampleFile = new FileInfo(log4netConfigExample);
if (!exampleFile.Exists)
{
Console.WriteLine("log4net Configuration file is missing. Please copy the file log4net.config.example to log4net.config and edit it to match your needs before running ACE.");
throw new Exception("missing log4net configuration file");
}
else
{
if (!IsRunningInContainer)
{
Console.WriteLine("log4net Configuration file is missing, cloning from example file.");
File.Copy(log4netConfigExample, log4netConfig);
}
else
{
if (!File.Exists(log4netConfigContainer))
{
Console.WriteLine("log4net Configuration file is missing, ACEmulator is running in a container, cloning from docker file.");
var log4netConfigDocker = Path.Combine(exeLocation, "log4net.config.docker");
File.Copy(log4netConfigDocker, log4netConfig);
File.Copy(log4netConfigDocker, log4netConfigContainer);
}
else
{
File.Copy(log4netConfigContainer, log4netConfig);
}
}
}
}
var logRepository = LogManager.GetRepository(replacedembly.GetEntryreplacedembly());
XmlConfigurator.ConfigureAndWatch(logRepository, log4netFileInfo);
if (Environment.ProcessorCount < 2)
log.Warn("Only one vCPU was detected. ACE may run with limited performance. You should increase your vCPU count for anything more than a single player server.");
// Do system specific initializations here
try
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// On many windows systems, the default resolution for Thread.Sleep is 15.6ms. This allows us to command a tighter resolution
MM_BeginPeriod(1);
}
}
catch (Exception ex)
{
log.Error(ex.ToString());
}
log.Info("Starting ACEmulator...");
if (IsRunningInContainer)
log.Info("ACEmulator is running in a container...");
var configFile = Path.Combine(exeLocation, "Config.js");
var configConfigContainer = Path.Combine(containerConfigDirectory, "Config.js");
if (IsRunningInContainer && File.Exists(configConfigContainer))
File.Copy(configConfigContainer, configFile, true);
if (!File.Exists(configFile))
{
if (!IsRunningInContainer)
DoOutOfBoxSetup(configFile);
else
{
if (!File.Exists(configConfigContainer))
{
DoOutOfBoxSetup(configFile);
File.Copy(configFile, configConfigContainer);
}
else
File.Copy(configConfigContainer, configFile);
}
}
log.Info("Initializing ConfigManager...");
ConfigManager.Initialize();
if (ConfigManager.Config.Server.WorldName != "ACEmulator")
{
consolereplacedle = $"{ConfigManager.Config.Server.WorldName} | {consolereplacedle}";
Console.replacedle = consolereplacedle;
}
if (ConfigManager.Config.Offline.PurgeDeletedCharacters)
{
log.Info($"Purging deleted characters, and their possessions, older than {ConfigManager.Config.Offline.PurgeDeletedCharactersDays} days ({DateTime.Now.AddDays(-ConfigManager.Config.Offline.PurgeDeletedCharactersDays)})...");
ShardDatabaseOfflineTools.PurgeCharactersInParallel(ConfigManager.Config.Offline.PurgeDeletedCharactersDays, out var charactersPurged, out var playerBiotasPurged, out var possessionsPurged);
log.Info($"Purged {charactersPurged:N0} characters, {playerBiotasPurged:N0} player biotas and {possessionsPurged:N0} possessions.");
}
if (ConfigManager.Config.Offline.PurgeOrphanedBiotas)
{
log.Info($"Purging orphaned biotas...");
ShardDatabaseOfflineTools.PurgeOrphanedBiotasInParallel(out var numberOfBiotasPurged);
log.Info($"Purged {numberOfBiotasPurged:N0} biotas.");
}
if (ConfigManager.Config.Offline.PruneDeletedCharactersFromFriendLists)
{
log.Info($"Pruning invalid friends from all friend lists...");
ShardDatabaseOfflineTools.PruneDeletedCharactersFromFriendLists(out var numberOfFriendsPruned);
log.Info($"Pruned {numberOfFriendsPruned:N0} invalid friends found on friend lists.");
}
if (ConfigManager.Config.Offline.PruneDeletedObjectsFromShortcutBars)
{
log.Info($"Pruning invalid shortcuts from all shortcut bars...");
ShardDatabaseOfflineTools.PruneDeletedObjectsFromShortcutBars(out var numberOfShortcutsPruned);
log.Info($"Pruned {numberOfShortcutsPruned:N0} deleted objects found on shortcut bars.");
}
if (ConfigManager.Config.Offline.PruneDeletedCharactersFromSquelchLists)
{
log.Info($"Pruning invalid squelches from all squelch lists...");
ShardDatabaseOfflineTools.PruneDeletedCharactersFromSquelchLists(out var numberOfSquelchesPruned);
log.Info($"Pruned {numberOfSquelchesPruned:N0} invalid squelched characters found on squelch lists.");
}
if (ConfigManager.Config.Offline.AutoUpdateWorldDatabase)
{
CheckForWorldDatabaseUpdate();
if (ConfigManager.Config.Offline.AutoApplyWorldCustomizations)
AutoApplyWorldCustomizations();
}
else
log.Info($"AutoUpdateWorldDatabase is disabled...");
if (ConfigManager.Config.Offline.AutoApplyDatabaseUpdates)
AutoApplyDatabaseUpdates();
else
log.Info($"AutoApplyDatabaseUpdates is disabled...");
// This should only be enabled manually. To enable it, simply uncomment this line
//ACE.Database.OfflineTools.Shard.BiotaGuidConsolidator.ConsolidateBiotaGuids(0xC0000000, out int numberOfBiotasConsolidated, out int numberOfErrors);
ShardDatabaseOfflineTools.CheckForBiotaPropertiesPaletteOrderColumnInShard();
// pre-load starterGear.json, abort startup if file is not found as it is required to create new characters.
if (Factories.StarterGearFactory.GetStarterGearConfiguration() == null)
{
log.Fatal("Unable to load or parse starterGear.json. ACEmulator will now abort startup.");
ServerManager.StartupAbort();
Environment.Exit(0);
}
log.Info("Initializing ServerManager...");
ServerManager.Initialize();
log.Info("Initializing DatManager...");
DatManager.Initialize(ConfigManager.Config.Server.DatFilesDirectory, true);
log.Info("Initializing DatabaseManager...");
DatabaseManager.Initialize();
if (DatabaseManager.InitializationFailure)
{
log.Fatal("DatabaseManager initialization failed. ACEmulator will now abort startup.");
ServerManager.StartupAbort();
Environment.Exit(0);
}
log.Info("Starting DatabaseManager...");
DatabaseManager.Start();
log.Info("Starting PropertyManager...");
PropertyManager.Initialize();
log.Info("Initializing GuidManager...");
GuidManager.Initialize();
if (ConfigManager.Config.Server.ServerPerformanceMonitorAutoStart)
{
log.Info("Server Performance Monitor auto starting...");
ServerPerformanceMonitor.Start();
}
if (ConfigManager.Config.Server.WorldDatabasePrecaching)
{
log.Info("Precaching Weenies...");
DatabaseManager.World.CacheAllWeenies();
log.Info("Precaching Cookbooks...");
DatabaseManager.World.CacheAllCookbooks();
log.Info("Precaching Events...");
DatabaseManager.World.GetAllEvents();
log.Info("Precaching House Portals...");
DatabaseManager.World.CacheAllHousePortals();
log.Info("Precaching Points Of Interest...");
DatabaseManager.World.CacheAllPointsOfInterest();
log.Info("Precaching Spells...");
DatabaseManager.World.CacheAllSpells();
log.Info("Precaching Treasures - Death...");
DatabaseManager.World.CacheAllTreasuresDeath();
log.Info("Precaching Treasures - Material Base...");
DatabaseManager.World.CacheAllTreasureMaterialBase();
log.Info("Precaching Treasures - Material Groups...");
DatabaseManager.World.CacheAllTreasureMaterialGroups();
log.Info("Precaching Treasures - Material Colors...");
DatabaseManager.World.CacheAllTreasureMaterialColor();
log.Info("Precaching Treasures - Wielded...");
DatabaseManager.World.CacheAllTreasureWielded();
}
else
log.Info("Precaching World Database Disabled...");
log.Info("Initializing PlayerManager...");
PlayerManager.Initialize();
log.Info("Initializing HouseManager...");
HouseManager.Initialize();
log.Info("Initializing InboundMessageManager...");
InboundMessageManager.Initialize();
log.Info("Initializing SocketManager...");
SocketManager.Initialize();
log.Info("Initializing WorldManager...");
WorldManager.Initialize();
log.Info("Initializing EventManager...");
EventManager.Initialize();
// Free up memory before the server goes online. This can free up 6 GB+ on larger servers.
log.Info("Forcing .net garbage collection...");
for (int i = 0 ; i < 10 ; i++)
GC.Collect();
// This should be last
log.Info("Initializing CommandManager...");
CommandManager.Initialize();
if (!PropertyManager.GetBool("world_closed", false).Item)
{
WorldManager.Open(null);
}
}
19
View Source File : DiagnosticLogManager.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public void UploadDiagnosticLogs(IExecutionContext executionContext,
IExecutionContext parentContext,
Pipelines.AgentJobRequestMessage message,
DateTime jobStartTimeUtc)
{
executionContext.Debug("Starting diagnostic file upload.");
// Setup folders
// \_layout\_work\_temp\[jobname-support]
executionContext.Debug("Setting up diagnostic log folders.");
string tempDirectory = HostContext.GetDirectory(WellKnownDirectory.Temp);
ArgUtil.Directory(tempDirectory, nameof(tempDirectory));
string supportRootFolder = Path.Combine(tempDirectory, message.JobName + "-support");
Directory.CreateDirectory(supportRootFolder);
// \_layout\_work\_temp\[jobname-support]\files
executionContext.Debug("Creating diagnostic log files folder.");
string supportFilesFolder = Path.Combine(supportRootFolder, "files");
Directory.CreateDirectory(supportFilesFolder);
// Create the environment file
// \_layout\_work\_temp\[jobname-support]\files\environment.txt
var configurationStore = HostContext.GetService<IConfigurationStore>();
RunnerSettings settings = configurationStore.GetSettings();
int runnerId = settings.AgentId;
string runnerName = settings.AgentName;
int poolId = settings.PoolId;
// Copy worker diagnostic log files
List<string> workerDiagnosticLogFiles = GetWorkerDiagnosticLogFiles(HostContext.GetDirectory(WellKnownDirectory.Diag), jobStartTimeUtc);
executionContext.Debug($"Copying {workerDiagnosticLogFiles.Count()} worker diagnostic logs.");
foreach (string workerLogFile in workerDiagnosticLogFiles)
{
ArgUtil.File(workerLogFile, nameof(workerLogFile));
string destination = Path.Combine(supportFilesFolder, Path.GetFileName(workerLogFile));
File.Copy(workerLogFile, destination);
}
// Copy runner diag log files
List<string> runnerDiagnosticLogFiles = GetRunnerDiagnosticLogFiles(HostContext.GetDirectory(WellKnownDirectory.Diag), jobStartTimeUtc);
executionContext.Debug($"Copying {runnerDiagnosticLogFiles.Count()} runner diagnostic logs.");
foreach (string runnerLogFile in runnerDiagnosticLogFiles)
{
ArgUtil.File(runnerLogFile, nameof(runnerLogFile));
string destination = Path.Combine(supportFilesFolder, Path.GetFileName(runnerLogFile));
File.Copy(runnerLogFile, destination);
}
executionContext.Debug("Zipping diagnostic files.");
string buildNumber = executionContext.Global.Variables.Build_Number ?? "UnknownBuildNumber";
string buildName = $"Build {buildNumber}";
string phaseName = executionContext.Global.Variables.System_PhaseDisplayName ?? "UnknownPhaseName";
// zip the files
string diagnosticsZipFileName = $"{buildName}-{phaseName}.zip";
string diagnosticsZipFilePath = Path.Combine(supportRootFolder, diagnosticsZipFileName);
ZipFile.CreateFromDirectory(supportFilesFolder, diagnosticsZipFilePath);
// upload the json metadata file
executionContext.Debug("Uploading diagnostic metadata file.");
string metadataFileName = $"diagnostics-{buildName}-{phaseName}.json";
string metadataFilePath = Path.Combine(supportFilesFolder, metadataFileName);
string phaseResult = GetTaskResultreplacedtring(executionContext.Result);
IOUtil.SaveObject(new DiagnosticLogMetadata(runnerName, runnerId, poolId, phaseName, diagnosticsZipFileName, phaseResult), metadataFilePath);
// TODO: Remove the parentContext Parameter and replace this with executioncontext. Currently a bug exists where these files do not upload correctly using that context.
parentContext.QueueAttachFile(type: CoreAttachmentType.DiagnosticLog, name: metadataFileName, filePath: metadataFilePath);
parentContext.QueueAttachFile(type: CoreAttachmentType.DiagnosticLog, name: diagnosticsZipFileName, filePath: diagnosticsZipFilePath);
executionContext.Debug("Diagnostic file upload complete.");
}
19
View Source File : HostContextL0.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Common")]
public void SecretMaskerForProxy()
{
try
{
Environment.SetEnvironmentVariable("http_proxy", "http://user:[email protected]:8888");
// Arrange.
Setup();
// replacedert.
var logFile = Path.Combine(Path.GetDirectoryName(replacedembly.GetEntryreplacedembly().Location), $"trace_{nameof(HostContextL0)}_{nameof(SecretMaskerForProxy)}.log");
var tempFile = Path.GetTempFileName();
File.Delete(tempFile);
File.Copy(logFile, tempFile);
var content = File.ReadAllText(tempFile);
replacedert.DoesNotContain("preplacedword123", content);
replacedert.Contains("http://user:***@127.0.0.1:8888", content);
}
finally
{
Environment.SetEnvironmentVariable("http_proxy", null);
// Cleanup.
Teardown();
}
}
19
View Source File : RestartApp.cs
License : MIT License
Project Creator : ADefWebserver
License : MIT License
Project Creator : ADefWebserver
[HttpGet("[action]")]
public ContentResult ShutdownSite()
{
string WebConfigOrginalFileNameAndPath = _hostEnvironment.ContentRootPath + @"\Web.config";
string WebConfigTempFileNameAndPath = _hostEnvironment.ContentRootPath + @"\Web.config.txt";
if (System.IO.File.Exists(WebConfigOrginalFileNameAndPath))
{
// Temporarily rename the web.config file
// to release the locks on any replacedemblies
System.IO.File.Copy(WebConfigOrginalFileNameAndPath, WebConfigTempFileNameAndPath);
System.IO.File.Delete(WebConfigOrginalFileNameAndPath);
// Give the site time to release locks on the replacedemblies
Task.Delay(2000).Wait(); // Wait 2 seconds with blocking
// Rename the temp web.config file back to web.config
// so the site will be active again
System.IO.File.Copy(WebConfigTempFileNameAndPath, WebConfigOrginalFileNameAndPath);
System.IO.File.Delete(WebConfigTempFileNameAndPath);
}
return new ContentResult
{
ContentType = @"text/html",
StatusCode = (int)HttpStatusCode.OK,
Content = [email protected]"<html><body><h2><a href={GetBaseUrl()}>click here to continue</a></h2></body></html>"
};
}
19
View Source File : Settings.cs
License : MIT License
Project Creator : adlez27
License : MIT License
Project Creator : adlez27
public void CopyIndex()
{
var vbIndex = Path.Combine(DestinationFolder, "index.csv");
if (Path.GetFileName(RecListFile) == "index.csv" && !File.Exists(vbIndex))
{
File.Copy(RecListFile, vbIndex);
}
}
19
View Source File : DLLCreatorWindow.cs
License : MIT License
Project Creator : adrenak
License : MIT License
Project Creator : adrenak
void SetupDirectory() {
Directory.CreateDirectory(GetOutputDirectory());
try { File.Copy(GetProjectPath() + "LICENSE", GetOutputDirectory() + "LICENSE"); } catch { }
try { File.Copy(GetProjectPath() + "LICENSE.md", GetOutputDirectory() + "LICENSE.md"); } catch { }
try { File.Copy(GetProjectPath() + "LICENSE.txt", GetOutputDirectory() + "LICENSE.txt"); } catch { }
try { File.Copy(GetProjectPath() + "README", GetOutputDirectory() + "README"); } catch { }
try { File.Copy(GetProjectPath() + "README.md", GetOutputDirectory() + "README.md"); } catch { }
try { File.Copy(GetProjectPath() + "README.txt", GetOutputDirectory() + "README.txt"); } catch { }
}
19
View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
private void GetLogFile(string arg1, string[] arg2)
{
string logPath = Path.Combine(Constants.DataPath, "ErrorLogs", "SMAPI-latest.txt");
if (!File.Exists(logPath))
{
Monitor.Log($"SMAPI log not found at {logPath}.", LogLevel.Error);
return;
}
if (arg2.Length == 0)
{
File.Copy(logPath, Environment.CurrentDirectory);
Monitor.Log($"Copied SMAPI log to game folder {Environment.CurrentDirectory}.", LogLevel.Alert);
}
else
{
string cmd = arg2[0].ToLower();
switch (cmd)
{
case "desktop":
case "dt":
File.Copy(logPath, Environment.GetFolderPath(Environment.SpecialFolder.Desktop));
Monitor.Log($"Copied SMAPI log to Desktop {Environment.GetFolderPath(Environment.SpecialFolder.Desktop)}.", LogLevel.Alert);
break;
case "copy":
case "cp":
string log = File.ReadAllText(logPath);
if (DesktopClipboard.SetText(log))
{
Monitor.Log($"Copied SMAPI log to Clipboard.", LogLevel.Alert);
}
else
{
Monitor.Log($"Coulding copy SMAPI log to Clipboard!", LogLevel.Error);
}
break;
}
}
}
19
View Source File : User.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public static void CopyProfile(string newProfile, string copyFrom)
{
System.IO.File.Copy(GetPath(copyFrom), GetPath(newProfile));
LoadProfile(newProfile);
}
19
View Source File : User.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
private static void CreateProfile(string profileName)
{
if (System.IO.File.Exists(GetPath(profileName)))
{
System.IO.File.Delete(GetPath(profileName));
}
System.IO.File.Copy(GetPath(Example), GetPath(profileName));
RefreshProfilesList();
}
19
View Source File : Form_SteamID64_Editor.cs
License : MIT License
Project Creator : Aemony
License : MIT License
Project Creator : Aemony
private void WriteSteamID()
{
steamID64 = Convert.ToUInt64(textBoxSteamID64_New.Text);
byteSteamID64 = BitConverter.GetBytes(steamID64);
steamID3 = BitConverter.ToUInt32(byteSteamID64, 0); // Relies on byteSteamID64 having been updated.
#if DEBUG
Console.WriteLine("New bytes: " + BitConverter.ToString(byteSteamID64));
Console.WriteLine("New SteamID3: " + steamID3.ToString());
Console.WriteLine("New SteamID64: " + steamID64.ToString());
#endif
// SteamID64 is stored as Little-Endian in the files, but as Intel is little-endian as well no reversal is needed
try
{
// Create a backup first
File.Copy(filePath, filePath + DateTime.Now.ToString("_yyyy-MM-dd_HH-mm-ss.bak"));
// Now overwrite the data
using (Stream stream = File.Open(filePath, FileMode.Open, FileAccess.Write))
{
stream.Position = fileOffset;
stream.Write(byteSteamID64, 0, 8);
}
textBoxSteamID3.Text = steamID3.ToString();
textBoxSteamID64.Text = steamID64.ToString();
toolStripStatusLabel1.Text = "Wrote to " + Path.GetFileName(filePath) + ": " + BitConverter.ToString(byteSteamID64);
lastStatus = toolStripStatusLabel1.Text;
buttonUpdate.Enabled = false;
}
catch (Exception ex)
{
throw ex;
}
}
19
View Source File : Form1.cs
License : GNU General Public License v3.0
Project Creator : Aemony
License : GNU General Public License v3.0
Project Creator : Aemony
private void buttonSave_Click(object sender, EventArgs e)
{
DialogResult dialogResult;
if (_byteInventoryImportedActive != null || _byteInventoryImportedCorpse != null)
{
dialogResult = MessageBox.Show("You currently have an imported inventory list active that have overwritten the original inventory list of the opened slot file. Saving will make the change permanent.\n\nAre you sure you want to continue?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
} else {
dialogResult = MessageBox.Show("Are you sure you want to save your changes to the slot file?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
}
if(dialogResult == DialogResult.Yes)
{
byte[] byteInventoryChanged = new byte[_intBlockLength];
for (int i = 0; i < 256; i++)
{
BitConverter.GetBytes(_itemInventoryActive[i].ID).CopyTo(byteInventoryChanged, i * 12);
BitConverter.GetBytes(_itemInventoryActive[i].Status).CopyTo(byteInventoryChanged, i * 12 + 4);
BitConverter.GetBytes(_itemInventoryActive[i].Amount).CopyTo(byteInventoryChanged, i * 12 + 8);
}
for (int i = 256; i < 512; i++)
{
BitConverter.GetBytes(_itemInventoryCorpse[i - 256].ID).CopyTo(byteInventoryChanged, i * 12);
BitConverter.GetBytes(_itemInventoryCorpse[i - 256].Status).CopyTo(byteInventoryChanged, i * 12 + 4);
BitConverter.GetBytes(_itemInventoryCorpse[i - 256].Amount).CopyTo(byteInventoryChanged, i * 12 + 8);
}
#if DEBUG
Console.WriteLine("Wrote:");
Console.WriteLine(BitConverter.ToString(byteInventoryChanged));
#endif
// Create a backup first
File.Copy(_filePath, _filePath + DateTime.Now.ToString("_yyyy-MM-dd_HH-mm-ss.bak"));
// Now overwrite the data
using (Stream stream = File.Open(_filePath, FileMode.Open, FileAccess.Write))
{
stream.Position = _intBlockOffset;
stream.Write(byteInventoryChanged, 0, _intBlockLength);
}
// Finally update the background stuff to reflect the new file
_byteInventory = byteInventoryChanged;
_byteInventoryImportedActive = null;
_byteInventoryImportedCorpse = null;
textBoxInventoryPath.Text = "No inventory list imported...";
MessageBox.Show("Changes were saved!", "Save complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
19
View Source File : AssetCatalog.cs
License : MIT License
Project Creator : agens-no
License : MIT License
Project Creator : agens-no
public override void Write()
{
Directory.CreateDirectory(m_Path);
var doc = new JsonDoreplacedent();
var info = WriteInfoToJson(doc);
WriteODRTagsToJson(info);
var data = doc.root.CreateArray("data");
foreach (DataSetVariant item in m_Variants)
{
var filename = Path.GetFileName(item.path);
File.Copy(item.path, Path.Combine(m_Path, filename));
var docItem = data.AddDict();
docItem.SetString("filename", filename);
WriteRequirementsToJson(docItem, item.requirement);
if (item.id != null)
docItem.SetString("universal-type-identifier", item.id);
}
doc.WriteToFile(Path.Combine(m_Path, "Contents.json"));
}
19
View Source File : AssetCatalog.cs
License : MIT License
Project Creator : agens-no
License : MIT License
Project Creator : agens-no
public override void Write()
{
Directory.CreateDirectory(m_Path);
var doc = new JsonDoreplacedent();
var info = WriteInfoToJson(doc);
WriteODRTagsToJson(info);
var images = doc.root.CreateArray("images");
foreach (ImageSetVariant item in m_Variants)
{
var filename = Path.GetFileName(item.path);
File.Copy(item.path, Path.Combine(m_Path, filename));
var docItem = images.AddDict();
docItem.SetString("filename", filename);
WriteRequirementsToJson(docItem, item.requirement);
if (item.alignment != null)
WriteAlignmentToJson(docItem, item.alignment);
if (item.resizing != null)
WriteResizingToJson(docItem, item.resizing);
}
doc.WriteToFile(Path.Combine(m_Path, "Contents.json"));
}
19
View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : ahmed605
License : GNU General Public License v3.0
Project Creator : ahmed605
private void lvFiles_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files)
{
//lvFiles.Items.Add(file);
System.IO.File.Copy(file, Path.Combine(KeyUtil.GetDir.Get(), Path.GetFileName(file)));
}
lvFiles.Refresh();
}
19
View Source File : Main.cs
License : MIT License
Project Creator : AhmedMinegames
License : MIT License
Project Creator : AhmedMinegames
private void ObfuscasteCode(string ToProtect)
{
ModuleContext ModuleCont = ModuleDefMD.CreateModuleContext();
ModuleDefMD FileModule = ModuleDefMD.Load(ToProtect, ModuleCont);
replacedemblyDef replacedembly1 = FileModule.replacedembly;
if (checkBox7.Checked)
{
foreach (var tDef in FileModule.Types)
{
if (tDef == FileModule.GlobalType) continue;
foreach (var mDef in tDef.Methods)
{
if (mDef.Name.StartsWith("get_") || mDef.Name.StartsWith("set_")) continue;
if (!mDef.HasBody || mDef.IsConstructor) continue;
mDef.Body.SimplifyBranches();
mDef.Body.SimplifyMacros(mDef.Parameters);
var blocks = GetMethod(mDef);
var ret = new List<Block>();
foreach (var group in blocks)
{
Random rnd = new Random();
ret.Insert(rnd.Next(0, ret.Count), group);
}
blocks = ret;
mDef.Body.Instructions.Clear();
var local = new Local(mDef.Module.CorLibTypes.Int32);
mDef.Body.Variables.Add(local);
var target = Instruction.Create(OpCodes.Nop);
var instr = Instruction.Create(OpCodes.Br, target);
var instructions = new List<Instruction> { Instruction.Create(OpCodes.Ldc_I4, 0) };
foreach (var instruction in instructions)
mDef.Body.Instructions.Add(instruction);
mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Stloc, local));
mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Br, instr));
mDef.Body.Instructions.Add(target);
foreach (var block in blocks.Where(block => block != blocks.Single(x => x.Number == blocks.Count - 1)))
{
mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Ldloc, local));
var instructions1 = new List<Instruction> { Instruction.Create(OpCodes.Ldc_I4, block.Number) };
foreach (var instruction in instructions1)
mDef.Body.Instructions.Add(instruction);
mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Ceq));
var instruction4 = Instruction.Create(OpCodes.Nop);
mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Brfalse, instruction4));
foreach (var instruction in block.Instructions)
mDef.Body.Instructions.Add(instruction);
var instructions2 = new List<Instruction> { Instruction.Create(OpCodes.Ldc_I4, block.Number + 1) };
foreach (var instruction in instructions2)
mDef.Body.Instructions.Add(instruction);
mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Stloc, local));
mDef.Body.Instructions.Add(instruction4);
}
mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Ldloc, local));
var instructions3 = new List<Instruction> { Instruction.Create(OpCodes.Ldc_I4, blocks.Count - 1) };
foreach (var instruction in instructions3)
mDef.Body.Instructions.Add(instruction);
mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Ceq));
mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Brfalse, instr));
mDef.Body.Instructions.Add(Instruction.Create(OpCodes.Br, blocks.Single(x => x.Number == blocks.Count - 1).Instructions[0]));
mDef.Body.Instructions.Add(instr);
foreach (var lastBlock in blocks.Single(x => x.Number == blocks.Count - 1).Instructions)
mDef.Body.Instructions.Add(lastBlock);
}
}
}
if (checkBox2.Checked)
{
for (int i = 200; i < 300; i++)
{
InterfaceImpl Interface = new InterfaceImplUser(FileModule.GlobalType);
TypeDef typedef = new TypeDefUser("", $"Form{i.ToString()}", FileModule.CorLibTypes.GetTypeRef("System", "Attribute"));
InterfaceImpl interface1 = new InterfaceImplUser(typedef);
FileModule.Types.Add(typedef);
typedef.Interfaces.Add(interface1);
typedef.Interfaces.Add(Interface);
}
}
string[] FakeObfuscastionsAttributes = { "ConfusedByAttribute", "YanoAttribute", "NetGuard", "DotfuscatorAttribute", "BabelAttribute", "ObfuscatedByGoliath", "dotNetProtector" };
if (checkBox5.Checked)
{
for (int i = 0; i < FakeObfuscastionsAttributes.Length; i++)
{
var FakeObfuscastionsAttribute = new TypeDefUser(FakeObfuscastionsAttributes[i], FileModule.CorLibTypes.Object.TypeDefOrRef);
FileModule.Types.Add(FakeObfuscastionsAttribute);
}
}
if (checkBox8.Checked)
{
foreach (TypeDef type in FileModule.Types)
{
FileModule.Name = RandomName(12);
if (type.IsGlobalModuleType || type.IsRuntimeSpecialName || type.IsSpecialName || type.IsWindowsRuntime || type.IsInterface)
{
continue;
}
else
{
for (int i = 200; i < 300; i++)
{
foreach (PropertyDef property in type.Properties)
{
if (property.IsRuntimeSpecialName) continue;
property.Name = RandomName(20) + i + RandomName(10) + i;
}
foreach (FieldDef fields in type.Fields)
{
fields.Name = RandomName(20) + i + RandomName(10) + i;
}
foreach (EventDef eventdef in type.Events)
{
eventdef.Name = RandomName(20) + i + RandomName(10) + i;
}
foreach (MethodDef method in type.Methods)
{
if (method.IsConstructor || method.IsRuntimeSpecialName || method.IsRuntime || method.IsStaticConstructor || method.IsVirtual) continue;
method.Name = RandomName(20) + i + RandomName(10) + i;
}
foreach(MethodDef method in type.Methods)
{
foreach(Parameter RenameParameters in method.Parameters)
{
RenameParameters.Name = RandomName(10);
}
}
}
}
foreach (ModuleDefMD module in FileModule.replacedembly.Modules)
{
module.Name = RandomName(13);
module.replacedembly.Name = RandomName(14);
}
}
foreach (TypeDef type in FileModule.Types)
{
foreach (MethodDef GetMethods in type.Methods)
{
for (int i = 200; i < 300; i++)
{
if (GetMethods.IsConstructor || GetMethods.IsRuntimeSpecialName || GetMethods.IsRuntime || GetMethods.IsStaticConstructor) continue;
GetMethods.Name = RandomName(15) + i;
}
}
}
}
if (checkBox6.Checked)
{
for (int i = 0; i < 200; i++)
{
var Junk = new TypeDefUser(RandomName(10) + i + RandomName(10) + i + RandomName(10) + i, FileModule.CorLibTypes.Object.TypeDefOrRef);
FileModule.Types.Add(Junk);
}
for (int i = 0; i < 200; i++)
{
var Junk = new TypeDefUser("<" + RandomName(10) + i + RandomName(10) + i + RandomName(10) + i + ">", FileModule.CorLibTypes.Object.TypeDefOrRef);
var Junk2 = new TypeDefUser(RandomName(11) + i + RandomName(11) + i + RandomName(11) + i, FileModule.CorLibTypes.Object.TypeDefOrRef);
FileModule.Types.Add(Junk);
FileModule.Types.Add(Junk2);
}
for (int i = 0; i < 200; i++)
{
var Junk = new TypeDefUser("<" + RandomName(10) + i + RandomName(10) + i + RandomName(10) + i + ">", FileModule.CorLibTypes.Object.Namespace);
var Junk2 = new TypeDefUser(RandomName(11) + i + RandomName(11) + i + RandomName(11) + i, FileModule.CorLibTypes.Object.Namespace);
FileModule.Types.Add(Junk);
FileModule.Types.Add(Junk2);
}
}
if (checkBox1.Checked)
{
foreach (TypeDef type in FileModule.Types)
{
foreach (MethodDef method in type.Methods)
{
if (method.Body == null) continue;
method.Body.SimplifyBranches();
for (int i = 0; i < method.Body.Instructions.Count; i++)
{
if (method.Body.Instructions[i].OpCode == OpCodes.Ldstr)
{
string EncodedString = method.Body.Instructions[i].Operand.ToString();
string InsertEncodedString = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(EncodedString));
method.Body.Instructions[i].OpCode = OpCodes.Nop;
method.Body.Instructions.Insert(i + 1, new Instruction(OpCodes.Call, FileModule.Import(typeof(Encoding).GetMethod("get_UTF8", new Type[] { }))));
method.Body.Instructions.Insert(i + 2, new Instruction(OpCodes.Ldstr, InsertEncodedString));
method.Body.Instructions.Insert(i + 3, new Instruction(OpCodes.Call, FileModule.Import(typeof(Convert).GetMethod("FromBase64String", new Type[] { typeof(string) }))));
method.Body.Instructions.Insert(i + 4, new Instruction(OpCodes.Callvirt, FileModule.Import(typeof(Encoding).GetMethod("GetString", new Type[] { typeof(byte[]) }))));
i += 4;
}
}
}
}
}
if (checkBox10.Checked)
{
foreach (var type in FileModule.GetTypes())
{
if (type.IsGlobalModuleType) continue;
foreach (var method in type.Methods)
{
if (!method.HasBody) continue;
{
for (var i = 0; i < method.Body.Instructions.Count; i++)
{
if (!method.Body.Instructions[i].IsLdcI4()) continue;
var numorig = new Random(Guid.NewGuid().GetHashCode()).Next();
var div = new Random(Guid.NewGuid().GetHashCode()).Next();
var num = numorig ^ div;
var nop = OpCodes.Nop.ToInstruction();
var local = new Local(method.Module.ImportAsTypeSig(typeof(int)));
method.Body.Variables.Add(local);
method.Body.Instructions.Insert(i + 1, OpCodes.Stloc.ToInstruction(local));
method.Body.Instructions.Insert(i + 2, Instruction.Create(OpCodes.Ldc_I4, method.Body.Instructions[i].GetLdcI4Value() - sizeof(float)));
method.Body.Instructions.Insert(i + 3, Instruction.Create(OpCodes.Ldc_I4, num));
method.Body.Instructions.Insert(i + 4, Instruction.Create(OpCodes.Ldc_I4, div));
method.Body.Instructions.Insert(i + 5, Instruction.Create(OpCodes.Xor));
method.Body.Instructions.Insert(i + 6, Instruction.Create(OpCodes.Ldc_I4, numorig));
method.Body.Instructions.Insert(i + 7, Instruction.Create(OpCodes.Bne_Un, nop));
method.Body.Instructions.Insert(i + 8, Instruction.Create(OpCodes.Ldc_I4, 2));
method.Body.Instructions.Insert(i + 9, OpCodes.Stloc.ToInstruction(local));
method.Body.Instructions.Insert(i + 10, Instruction.Create(OpCodes.Sizeof, method.Module.Import(typeof(float))));
method.Body.Instructions.Insert(i + 11, Instruction.Create(OpCodes.Add));
method.Body.Instructions.Insert(i + 12, nop);
i += 12;
}
method.Body.SimplifyBranches();
}
}
}
}
if (checkBox11.Checked)
{
foreach (ModuleDef module in FileModule.replacedembly.Modules)
{
TypeRef attrRef = FileModule.CorLibTypes.GetTypeRef("System.Runtime.CompilerServices", "SuppressIldasmAttribute");
var ctorRef = new MemberRefUser(module, ".ctor", MethodSig.CreateInstance(module.CorLibTypes.Void), attrRef);
var attr = new CustomAttribute(ctorRef);
module.CustomAttributes.Add(attr);
}
}
if (checkBox13.Checked)
{
// later
}
if (File.Exists(Environment.CurrentDirectory + @"\Obfuscasted.exe") == false)
{
File.Copy(ToProtect, Environment.CurrentDirectory + @"\Obfuscasted.exe");
FileModule.Write(Environment.CurrentDirectory + @"\Obfuscasted.exe");
if (checkBox12.Checked)
{
string RandomreplacedemblyName = RandomName(12);
PackAndEncrypt(Environment.CurrentDirectory + @"\Obfuscasted.exe", Environment.CurrentDirectory + @"\" + RandomreplacedemblyName + ".tmp");
File.Delete(Environment.CurrentDirectory + @"\Obfuscasted.exe");
File.Move(Environment.CurrentDirectory + @"\" + RandomreplacedemblyName + ".tmp", Environment.CurrentDirectory + @"\Obfuscasted.exe");
}
}
else
{
MessageBox.Show("Please Delete or move the file: " + Environment.CurrentDirectory + @"\Obfuscasted.exe" + " first to Obfuscaste your file", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
}
}
19
View Source File : FileSystemStore.cs
License : MIT License
Project Creator : aishang2015
License : MIT License
Project Creator : aishang2015
public Task CopyFileAsync(string srcPath, string dstPath)
{
var physicalSrcPath = GetPhysicalPath(srcPath);
if (!File.Exists(physicalSrcPath))
{
throw new FileStoreException($"The file '{srcPath}' does not exist.");
}
var physicalDstPath = GetPhysicalPath(dstPath);
if (File.Exists(physicalDstPath) || Directory.Exists(physicalDstPath))
{
throw new FileStoreException($"Cannot copy file because the destination path '{dstPath}' already exists.");
}
File.Copy(GetPhysicalPath(srcPath), GetPhysicalPath(dstPath));
return Task.CompletedTask;
}
19
View Source File : mainForm.cs
License : MIT License
Project Creator : ajohns6
License : MIT License
Project Creator : ajohns6
private bool buildBase()
{
this.outputText.Visible = true;
if (!File.Exists(Path.Combine(nxDir, "baserom.us.z64")))
{
if (File.Exists(Path.Combine(nxDir, "baserom.us.z64")))
{
File.Move(Path.Combine(nxDir, "baserom.us.z64"), Path.Combine(nxDir, "baserom.us.z64"));
}
else
{
MessageBox.Show("You are missing baserom.us.z64.\n\nPlease select your baserom.us.z64.", "ROM Missing", MessageBoxButtons.OK, MessageBoxIcon.Error);
Boolean exit = false;
var result = new OpenFileDialog();
while (!exit)
{
if (result.ShowDialog() == DialogResult.OK)
{
if (checkHash(result.FileName))
{
File.Copy(result.FileName, Path.Combine(nxDir, "baserom.us.z64"));
exit = true;
}
else
{
var answer = MessageBox.Show("ROM hash is not valid.\n\nWould you like to select another?", "Invalid ROM Hash", MessageBoxButtons.YesNo, MessageBoxIcon.Error);
if (answer == DialogResult.No) return true;
}
}
else
{
return true;
}
}
}
}
if (runProcess("cmd.exe", @"/C build.bat"))
{
this.outputText.Text += "Traditional build.bat file failed.\n\nAttempting static calls as a fallback...\n\n";
if (runProcess("cmd.exe", " /C py extract_replacedets.py && py ..\\scripts\\pak.py --source . --output ..\\romfs\\!!base.pak"))
{
MessageBox.Show("!!Base.pak failed to build.\n\nCheck for error messages in log or share them with troubleshooters.", "Base PAK Build Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
return true;
}
}
return false;
}
19
View Source File : Chrome.cs
License : MIT License
Project Creator : Akaion
License : MIT License
Project Creator : Akaion
private static StringBuilder GetDatabaseEntries()
{
// Default folder path for the database
var folderPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Google\Chrome\User Data\Default";
var databaseEntries = new StringBuilder();
// If the directory cannot be found end the function
if (!Directory.Exists(folderPath))
{
databaseEntries.AppendLine("Failed to find the default directory for Chrome");
return databaseEntries;
}
// Create a copy of the database - Chrome has the original database open and is therefore locked
if (File.Exists(folderPath + @"\Login Data Copy"))
{
File.Delete(folderPath + @"\Login Data Copy");
File.Copy(folderPath + @"\Login Data", folderPath + @"\Login Data Copy");
}
else
{
File.Copy(folderPath + @"\Login Data", folderPath + @"\Login Data Copy");
}
using (var connection = new SQLiteConnection("Data Source=" + folderPath + @"\Login Data Copy"))
{
// Query used to get the database entries
const string statement = "SELECT date_created DateCreated, origin_url OriginUrl, action_url ActionUrl, username_value UsernameValue, preplacedword_value PreplacedwordValue FROM logins";
// Open the database
connection.Open();
// Build a list of objects from the database query
var entries = connection.Query<User>(statement);
foreach (var entry in entries)
{
// Decrypt the preplacedword
var decryptedPreplacedword = Encoding.UTF8.GetString(ProtectedData.Unprotect(entry.PreplacedwordValue, null, DataProtectionScope.CurrentUser));
// Convert the value of DateCreated to datetime
var epoch = new DateTime(1601, 1, 1, 12, 0, 0).AddSeconds(entry.DateCreated / 1000000);
databaseEntries.AppendLine($"{epoch} : {entry.OriginUrl} : {entry.ActionUrl} : {entry.UsernameValue} : {decryptedPreplacedword}");
}
}
// Delete the database copy
File.Delete(folderPath + @"\Login Data Copy");
return databaseEntries;
}
19
View Source File : ContentsBrowser.cs
License : MIT License
Project Creator : alaabenfatma
License : MIT License
Project Creator : alaabenfatma
private ContextMenu contentsMenu()
{
var cm = new ContextMenu();
var import_tb = new TextBlock();
import_tb.Inlines.Add(new Run("⇓")
{
Foreground = Brushes.White,
FontSize = 14,
FontFamily = new FontFamily("Yu Gothic UI Semibold")
});
import_tb.Inlines.Add(new Run(" Import") {Foreground = Brushes.White});
var new_tb = new TextBlock();
new_tb.Inlines.Add(new Run("🗋")
{
Foreground = Brushes.White,
FontSize = 14,
FontFamily = new FontFamily("Verdana")
});
new_tb.Inlines.Add(new Run(" New") {Foreground = Brushes.White});
var openexplorer_tb = new TextBlock();
openexplorer_tb.Inlines.Add(new Run("🗀")
{
Foreground = Brushes.Yellow,
FontSize = 16,
FontFamily = new FontFamily("Yu Gothic UI Semibold")
});
openexplorer_tb.Inlines.Add(new Run(" Open in Folder in File Explorer") {Foreground = Brushes.White});
var refresh_tb = new TextBlock();
refresh_tb.Inlines.Add(new Run("↻")
{
Foreground = Brushes.Cyan,
FontSize = 14,
FontFamily = new FontFamily("Yu Gothic UI Semibold")
});
refresh_tb.Inlines.Add(new Run(" Refresh") {Foreground = Brushes.White});
var import = new MenuItem
{
Header = import_tb
};
import.Click += (s, e) => { ImportFile(); };
var newitem = new MenuItem
{
Header = new_tb
};
NewItemMenu(newitem);
var openexplorer = new MenuItem
{
Header = openexplorer_tb
};
openexplorer.Click += (s, e) => { Process.Start(Item.Path); };
var refresh = new MenuItem
{
Header = refresh_tb
};
refresh.Click += (s, e) => { Item.Load(Item.Path); };
cm.Items.Add(openexplorer);
cm.Items.Add(new Separator {Foreground = Brushes.White});
cm.Items.Add(import);
cm.Items.Add(newitem);
var paste = new MenuItem
{
Header = new TextBlock
{
Foreground = Brushes.WhiteSmoke,
Text = "Paste"
}
};
paste.Click += (s, e) =>
{
try
{
var p = Item.Path;
if (p.Substring(0, Math.Max(0, p.Length - 1)) == @"\")
File.Copy(PathToCopy, Item.Path + Path.GetFileName(PathToCopy));
else
File.Copy(PathToCopy, Item.Path + @"\" + Path.GetFileName(PathToCopy));
Item.Load(Item.Path);
}
catch
{
//Ignored
}
};
cm.Items.Add(paste);
cm.Items.Add(new Separator {Foreground = Brushes.White});
cm.Items.Add(refresh);
return cm;
}
19
View Source File : ContentsBrowser.cs
License : MIT License
Project Creator : alaabenfatma
License : MIT License
Project Creator : alaabenfatma
private void ImportFile()
{
var openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == true)
{
var p = Item.Path;
if (p.Substring(0, Math.Max(0, p.Length - 1)) == @"\")
File.Copy(openFileDialog.FileName, Item.Path + openFileDialog.SafeFileName);
else
File.Copy(openFileDialog.FileName, Item.Path + @"\" + openFileDialog.SafeFileName);
Refresh();
}
}
19
View Source File : FileLoader.cs
License : MIT License
Project Creator : allenwp
License : MIT License
Project Creator : allenwp
public static void SaveTextFile(string relativePath, string contents, bool backupExisting = false)
{
string fullPath = FullPath(relativePath);
Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
if (backupExisting && File.Exists(fullPath))
{
string backupFolder = FullPath(Path.Combine("Backup", relativePath));
Directory.CreateDirectory(backupFolder);
string backupFilePath = Path.Combine(backupFolder, DateTime.UtcNow.ToFileTimeUtc().ToString());
File.Copy(fullPath, backupFilePath);
string[] files = Directory.GetFiles(backupFolder);
Array.Sort(files);
int maxToDelete = files.Length - 10;
for (int i = 0; i < maxToDelete; i++)
{
File.Delete(Path.Combine(backupFolder, files[i]));
}
}
File.WriteAllText(fullPath, contents);
textFileCache[relativePath.ToLower()] = contents;
}
19
View Source File : RepositorySITests.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
private static void PrepareRemoteTestData(string org, string app)
{
string remoteRepoPath = TestDataHelper.GetTestDataRemoteRepository(org, app);
string configPath = Path.Combine(remoteRepoPath, "gitconfig");
string newPath = Path.Combine(remoteRepoPath, ".git\\config");
if (!File.Exists(newPath))
{
Directory.CreateDirectory(Path.Combine(remoteRepoPath, ".git"));
if (File.Exists(configPath))
{
File.Copy(configPath, newPath);
}
}
}
19
View Source File : Program.cs
License : MIT License
Project Creator : Alword
License : MIT License
Project Creator : Alword
private static void ExportFiles(IEnumerable<string> files, string outputPath)
{
Directory.CreateDirectory(outputPath);
foreach (string file in files)
{
File.Copy(file, Path.Combine(outputPath, Path.GetFileName(file)));
}
}
19
View Source File : ModPacker.cs
License : GNU General Public License v3.0
Project Creator : AM2R-Community-Developers
License : GNU General Public License v3.0
Project Creator : AM2R-Community-Developers
private void CreateModPack(string operatingSystem, string input, string output)
{
LoadProfileParameters(operatingSystem);
// Cleanup in case of previous errors
if (Directory.Exists(Path.GetTempPath() + "\\AM2RModPacker"))
{
Directory.Delete(Path.GetTempPath() + "\\AM2RModPacker", true);
}
// Create temp work folders
string tempPath = "",
tempOriginalPath = "",
tempModPath = "",
tempProfilePath = "";
// We might not have permission to access to the temp directory, so we need to catch the exception.
try
{
tempPath = Directory.CreateDirectory(Path.GetTempPath() + "\\AM2RModPacker").FullName;
tempOriginalPath = Directory.CreateDirectory(tempPath + "\\original").FullName;
tempModPath = Directory.CreateDirectory(tempPath + "\\mod").FullName;
tempProfilePath = Directory.CreateDirectory(tempPath + "\\profile").FullName;
}
catch (System.Security.SecurityException)
{
MessageBox.Show("Could not create temp directory! Please run the application with administrator rights.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
AbortPatch();
return;
}
// Extract 1.1 and modded AM2R to their own directories in temp work
ZipFile.ExtractToDirectory(originalPath, tempOriginalPath);
ZipFile.ExtractToDirectory(input, tempModPath);
if (Directory.Exists(tempModPath + "\\AM2R"))
tempModPath += "\\AM2R";
// Verify 1.1 with an MD5. If it does not match, exit cleanly and provide a warning window.
try
{
string newMD5 = CalculateMD5(tempOriginalPath + "\\data.win");
if (newMD5 != ORIGINAL_MD5)
{
// Show error box
MessageBox.Show("1.1 data.win does not meet MD5 checksum! Mod packaging aborted.\n1.1 MD5: " + ORIGINAL_MD5 + "\nYour MD5: " + newMD5, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
AbortPatch();
return;
}
}
catch (FileNotFoundException)
{
// Show error message
MessageBox.Show("data.win not found! Are you sure you selected AM2R 1.1? Mod packaging aborted.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
AbortPatch();
return;
}
// Create AM2R.exe and data.win patches
if (profile.OperatingSystem == "Windows")
{
if (!File.Exists(tempModPath + "/AM2R.exe"))
{
var result = MessageBox.Show("Modded game not found, make sure it's not placed in any subfolders.\nCreated profile will likely not be installable, are you sure you want to continue?", "WARNING", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result != DialogResult.Yes)
AbortPatch();
}
if (File.Exists(tempModPath + "profile.xml"))
{
var result = MessageBox.Show("profile.xml found. This file is used by the AM2RLauncher to determine profile stats and its inclusion may make the profile uninstallable. Are you sure you want to continue?", "WARNING", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result != DialogResult.Yes)
AbortPatch();
}
if (profile.UsesYYC)
{
CreatePatch(tempOriginalPath + "\\data.win", tempModPath + "\\AM2R.exe", tempProfilePath + "\\AM2R.xdelta");
}
else
{
CreatePatch(tempOriginalPath + "\\data.win", tempModPath + "\\data.win", tempProfilePath + "\\data.xdelta");
CreatePatch(tempOriginalPath + "\\AM2R.exe", tempModPath + "\\AM2R.exe", tempProfilePath + "\\AM2R.xdelta");
}
}
else if (profile.OperatingSystem == "Linux")
{
string runnerName = File.Exists(tempModPath + "\\" + "AM2R") ? "AM2R" : "runner";
if (!File.Exists(tempModPath + "/" + runnerName))
{
var result = MessageBox.Show("Modded Linux game not found, make sure it's not placed in any subfolders.\nCreated profile will likely not be installable, are you sure you want to continue?", "WARNING", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result != DialogResult.Yes)
AbortPatch();
}
if (File.Exists(tempModPath + "profile.xml"))
{
var result = MessageBox.Show("profile.xml found. This file is used by the AM2RLauncher to determine profile stats and its inclusion may make the profile uninstallable. Are you sure you want to continue?", "WARNING", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result != DialogResult.Yes)
AbortPatch();
}
CreatePatch(tempOriginalPath + "\\data.win", tempModPath + "\\replacedets\\game.unx", tempProfilePath + "\\game.xdelta");
CreatePatch(tempOriginalPath + "\\AM2R.exe", tempModPath + "\\" + runnerName, tempProfilePath + "\\AM2R.xdelta");
}
// Create game.droid patch and wrapper if Android is supported
if (profile.Android)
{
string tempAndroid = Directory.CreateDirectory(tempPath + "\\android").FullName;
// Extract APK
// - java -jar apktool.jar d "%~dp0AM2RWrapper_old.apk"
// Process startInfo
ProcessStartInfo procStartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
WorkingDirectory = tempAndroid,
Arguments = "/C java -jar \"" + localPath + "\\utilities\\android\\apktool.jar\" d -f -o \"" + tempAndroid + "\" \"" + apkPath + "\"",
UseShellExecute = false,
CreateNoWindow = true
};
// Run process
using (Process proc = new Process { StartInfo = procStartInfo })
{
proc.Start();
proc.WaitForExit();
}
// Create game.droid patch
CreatePatch(tempOriginalPath + "\\data.win", tempAndroid + "\\replacedets\\game.droid", tempProfilePath + "\\droid.xdelta");
// Delete excess files in APK
// Create whitelist
string[] whitelist = { "splash.png", "portrait_splash.png" };
// Get directory
DirectoryInfo androidreplacedets = new DirectoryInfo(tempAndroid + "\\replacedets");
// Delete files
foreach (FileInfo file in androidreplacedets.GetFiles())
{
if (file.Name.EndsWith(".ini") && file.Name != "modifiers.ini")
{
if (File.Exists(tempProfilePath + "\\AM2R.ini"))
{
// This shouldn't be a problem... normally...
File.Delete(tempProfilePath + "\\AM2R.ini");
}
File.Copy(file.FullName, tempProfilePath + "\\AM2R.ini");
}
if (!whitelist.Contains(file.Name))
{
File.Delete(file.FullName);
}
}
foreach (DirectoryInfo dir in androidreplacedets.GetDirectories())
{
Directory.Delete(dir.FullName, true);
}
// Create wrapper
// Process startInfo
// - java -jar apktool.jar b "%~dp0AM2RWrapper_old" -o "%~dp0AM2RWrapper.apk"
ProcessStartInfo procStartInfo2 = new ProcessStartInfo
{
FileName = "cmd.exe",
WorkingDirectory = tempAndroid,
Arguments = "/C java -jar \"" + localPath + "\\utilities\\android\\apktool.jar\" b -f \"" + tempAndroid + "\" -o \"" + tempProfilePath + "\\AM2RWrapper.apk\"",
UseShellExecute = false,
CreateNoWindow = true
};
// Run process
using (Process proc = new Process { StartInfo = procStartInfo2 })
{
proc.Start();
proc.WaitForExit();
}
string tempAndroidProfilePath = tempProfilePath + "\\android";
Directory.CreateDirectory(tempAndroidProfilePath);
File.Move(tempProfilePath + "\\AM2RWrapper.apk", tempAndroidProfilePath + "\\AM2RWrapper.apk");
if (File.Exists(tempProfilePath + "\\AM2R.ini"))
File.Move(tempProfilePath + "\\AM2R.ini", tempAndroidProfilePath + "\\AM2R.ini");
}
// Copy datafiles (exclude .ogg if custom music is not selected)
DirectoryInfo dinfo = new DirectoryInfo(tempModPath);
if (profile.OperatingSystem == "Linux")
dinfo = new DirectoryInfo(tempModPath + "\\replacedets");
Directory.CreateDirectory(tempProfilePath + "\\files_to_copy");
if (profile.UsesCustomMusic)
{
// Copy files, excluding the blacklist
CopyFilesRecursive(dinfo, DATAFILES_BLACKLIST, tempProfilePath + "\\files_to_copy");
}
else
{
// Get list of 1.1's music files
string[] musFiles = Directory.GetFiles(tempOriginalPath, "*.ogg").Select(file => Path.GetFileName(file)).ToArray();
if (profile.OperatingSystem == "Linux")
musFiles = Directory.GetFiles(tempOriginalPath, "*.ogg").Select(file => Path.GetFileName(file).ToLower()).ToArray();
// Combine musFiles with the known datafiles for a blacklist
string[] blacklist = musFiles.Concat(DATAFILES_BLACKLIST).ToArray();
// Copy files, excluding the blacklist
CopyFilesRecursive(dinfo, blacklist, tempProfilePath + "\\files_to_copy");
}
// Export profile as XML
string xmlOutput = Serializer.Serialize<ModProfileXML>(profile);
File.WriteAllText(tempProfilePath + "\\profile.xml", xmlOutput);
// Compress temp folder to .zip
if (File.Exists(output))
{
File.Delete(output);
}
ZipFile.CreateFromDirectory(tempProfilePath, output);
// Delete temp folder
Directory.Delete(tempPath, true);
}
19
View Source File : Program.cs
License : MIT License
Project Creator : AmazingDM
License : MIT License
Project Creator : AmazingDM
public static void Main(string[] args)
{
var result = false;
try
{
#region Check Arguments
if (CurrentProcess.MainModule == null)
{
Console.WriteLine("Current Process MainModule is null");
return;
}
if (args.Length != 3)
{
Console.WriteLine("The program is not user-oriented\n此程序不是面向用户的");
return;
}
// arg0 port
if (!int.TryParse(args[0], out var port))
{
Console.WriteLine("arg0 Port Parse failed");
return;
}
var updateExtracted = true;
// arg1 update File/Directory
var updatePath = Path.GetFullPath(args[1]);
if (File.Exists(updatePath))
{
updateExtracted = false;
}
else if (!Directory.Exists(updatePath))
{
Console.WriteLine("arg1 update file/directory Not found");
return;
}
// arg2 target Directory
string targetPath;
if (!File.Exists(Path.Combine(targetPath = Path.GetFullPath(args[2]), "Netch.exe")))
{
Console.Write("arg2 Netch Directory doesn't seems right");
return;
}
#region if under target Directory,then rerun in temp directory
if (UpdaterDirectory.StartsWith(targetPath))
{
// Updater 在目标目录下
// 将程序复制到临时目录,传递参数
var tempPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
var newUpdaterPath = Path.Combine(tempPath, UpdaterFriendlyName);
Directory.CreateDirectory(tempPath);
File.Copy(UpdaterFullName, newUpdaterPath);
Process.Start(new ProcessStartInfo
{
FileName = newUpdaterPath,
Arguments = $"{port} \"{updatePath}\" \"{targetPath}\"",
WorkingDirectory = tempPath,
UseShellExecute = false
});
result = true;
return;
}
#endregion
#endregion
/*Console.WriteLine("Waiting Attach");
while (!Debugger.IsAttached)
{
Thread.Sleep(1000);
}*/
#region Send Netch Exit command
Process[] _;
if ((_ = Process.GetProcessesByName("Netch")).Any())
{
Console.WriteLine("Found Netch process, Send exit command");
try
{
var udpClient = new UdpClient("127.0.0.1", port);
var sendBytes = Encoding.ASCII.GetBytes("Exit");
udpClient.Send(sendBytes, sendBytes.Length);
}
catch
{
Console.WriteLine("Send command failed");
return;
}
foreach (var proc in _)
{
try
{
proc.WaitForExit();
}
catch (Exception)
{
// ignored
}
}
}
#endregion
var counter = 0;
while (!TestFileFree(Path.Combine(targetPath, "Netch.exe")))
{
// wait 5 sec
if (counter > 25)
{
Console.WriteLine("Waiting Netch exit timeout");
return;
}
Thread.Sleep(200);
counter++;
}
#region Update
string extractPath = null;
if (!updateExtracted)
{
extractPath = Path.Combine(UpdaterDirectory, "extract");
Extract(updatePath, extractPath, true);
var netchExeFileInfo = FindFile("Netch.exe", extractPath);
if (netchExeFileInfo == null)
{
throw new Exception("Netch.exe not found in archive!");
}
updatePath = netchExeFileInfo.Directory.FullName;
}
MoveDirectory(updatePath, targetPath, true);
try
{
if (extractPath != null)
Directory.Delete(extractPath, true);
}
catch
{
// ignored
}
#endregion
#region Finished Update,Start Netch
Console.WriteLine("Start Netch");
Process.Start(new ProcessStartInfo
{
FileName = Path.Combine(targetPath, "Netch.exe"),
UseShellExecute = true,
});
#endregion
result = true;
}
catch (Exception e)
{
if (e is InvalidDataException)
Console.WriteLine("Archive file Broken");
Console.WriteLine(e.ToString());
}
finally
{
if (!result)
{
Console.WriteLine("Press any key to exit...");
Console.Read();
}
}
}
19
View Source File : NFController.cs
License : MIT License
Project Creator : AmazingDM
License : MIT License
Project Creator : AmazingDM
public static bool InstallDriver()
{
Logging.Info("安装 NF 驱动");
try
{
File.Copy(BinDriver, SystemDriver);
}
catch (Exception e)
{
Logging.Error("驱动复制失败\n" + e);
return false;
}
Global.MainForm.StatusText(i18N.Translate("Register driver"));
// 注册驱动文件
var result = NFAPI.nf_registerDriver("netfilter2");
if (result == NF_STATUS.NF_STATUS_SUCCESS)
{
Logging.Info("驱动安装成功");
}
else
{
Logging.Error($"注册驱动失败,返回值:{result}");
return false;
}
return true;
}
19
View Source File : BuildDeployTools.cs
License : MIT License
Project Creator : anderm
License : MIT License
Project Creator : anderm
public static bool BuildAppxFromSLN(string productName, string msBuildVersion, bool forceRebuildAppx, string buildConfig, string buildDirectory, bool incrementVersion, bool showDialog = true)
{
EditorUtility.DisplayProgressBar("Build AppX", "Building AppX Package...", 0);
string slnFilename = Path.Combine(buildDirectory, PlayerSettings.productName + ".sln");
if (!File.Exists(slnFilename))
{
Debug.LogError("Unable to find Solution to build from!");
EditorUtility.ClearProgressBar();
return false;
}
// Get and validate the msBuild path...
var vs = CalcMSBuildPath(msBuildVersion);
if (!File.Exists(vs))
{
Debug.LogError("MSBuild.exe is missing or invalid (path=" + vs + "). Note that the default version is " + DefaultMSBuildVersion);
EditorUtility.ClearProgressBar();
return false;
}
// Get the path to the NuGet tool
string unity = Path.GetDirectoryName(EditorApplication.applicationPath);
System.Diagnostics.Debug.replacedert(unity != null, "unity != null");
string storePath = Path.GetFullPath(Path.Combine(Path.Combine(Application.dataPath, ".."), buildDirectory));
string solutionProjectPath = Path.GetFullPath(Path.Combine(storePath, productName + @".sln"));
// Bug in Unity editor that doesn't copy project.json and project.lock.json files correctly if solutionProjectPath is not in a folder named UWP.
if (!File.Exists(storePath + "\\project.json"))
{
File.Copy(unity + @"\Data\PlaybackEngines\MetroSupport\Tools\project.json", storePath + "\\project.json");
}
string nugetPath = Path.Combine(unity, @"Data\PlaybackEngines\MetroSupport\Tools\NuGet.exe");
// Before building, need to run a nuget restore to generate a json.lock file. Failing to do
// this breaks the build in VS RTM
if (!RestoreNugetPackages(nugetPath, storePath) ||
!RestoreNugetPackages(nugetPath, storePath + "\\" + productName) ||
EditorUserBuildSettings.wsaGenerateReferenceProjects && !RestoreNugetPackages(nugetPath, storePath + "/GeneratedProjects/UWP/replacedembly-CSharp") ||
EditorUserBuildSettings.wsaGenerateReferenceProjects && !RestoreNugetPackages(nugetPath, storePath + "/GeneratedProjects/UWP/replacedembly-CSharp-firstpreplaced"))
{
Debug.LogError("Failed to restore nuget packages");
EditorUtility.ClearProgressBar();
return false;
}
EditorUtility.DisplayProgressBar("Build AppX", "Building AppX Package...", 25);
// Ensure that the generated .appx version increments by modifying
// Package.appxmanifest
if (incrementVersion)
{
IncrementPackageVersion();
}
// Now do the actual build
var pInfo = new System.Diagnostics.ProcessStartInfo
{
FileName = vs,
CreateNoWindow = false,
Arguments = string.Format("\"{0}\" /t:{2} /p:Configuration={1} /p:Platform=x86 /verbosity:m",
solutionProjectPath,
buildConfig,
forceRebuildAppx ? "Rebuild" : "Build")
};
// Uncomment out to debug by copying into command window
//Debug.Log("\"" + vs + "\"" + " " + pInfo.Arguments);
var process = new System.Diagnostics.Process { StartInfo = pInfo };
try
{
if (!process.Start())
{
Debug.LogError("Failed to start Cmd process!");
EditorUtility.ClearProgressBar();
return false;
}
process.WaitForExit();
EditorUtility.ClearProgressBar();
if (process.ExitCode == 0 &&
showDialog &&
!EditorUtility.DisplayDialog("Build AppX", "AppX Build Successful!", "OK", "Open Project Folder"))
{
System.Diagnostics.Process.Start("explorer.exe", "/select," + storePath);
}
if (process.ExitCode != 0)
{
Debug.LogError("MSBuild error (code = " + process.ExitCode + ")");
EditorUtility.DisplayDialog(PlayerSettings.productName + " build Failed!", "Failed to build appx from solution. Error code: " + process.ExitCode, "OK");
return false;
}
process.Close();
process.Dispose();
}
catch (Exception e)
{
Debug.LogError("Cmd Process EXCEPTION: " + e);
EditorUtility.ClearProgressBar();
return false;
}
return true;
}
19
View Source File : SetIconsWindow.cs
License : MIT License
Project Creator : anderm
License : MIT License
Project Creator : anderm
private void ResizeImages()
{
try
{
EditorUtility.DisplayProgressBar("Generating images", "Checking Texture Importers", 0);
// Check if we need to reimport the original textures, for enabling reading.
var reimportedAppIcon = CheckTextureImporter(_originalAppIconPath);
var reimportedSplashImage = CheckTextureImporter(_originalSplashImagePath);
if (reimportedAppIcon || reimportedSplashImage)
{
replacedetDatabase.Refresh();
}
// Create a copy of the original images
string directoryPath = Application.dataPath + "/" + _outputDirectoryName;
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
File.Copy(_originalAppIconPath, directoryPath + "/1240x1240.png");
File.Copy(_originalSplashImagePath, directoryPath + "/2480x1200.png");
// Loop through available types and scales for UWP
var types = Enum.GetValues(typeof(PlayerSettings.WSAImageType)).Cast<PlayerSettings.WSAImageType>().ToList();
var scales = Enum.GetValues(typeof(PlayerSettings.WSAImageScale)).Cast<PlayerSettings.WSAImageScale>().ToList();
float progressTotal = types.Count * scales.Count;
float progress = 0;
bool cancelled = false;
foreach (var type in types)
{
if (cancelled)
{
break;
}
foreach (var scale in scales)
{
var texture = GetUWPImageTypeTexture(type, scale);
if (texture != null)
{
string filename = null; //string.Format("{0}{1}.png", type, scale);
CloneAndResizeToFile(texture, type, scale, ref filename);
PlayerSettings.WSA.SetVisualreplacedetsImage(string.Format("replacedets/{0}/{1}", _outputDirectoryName, filename), type, scale);
progress++;
cancelled = EditorUtility.DisplayCancelableProgressBar("Generating images", string.Format("Generating resized images {0} of {1}", progress, progressTotal), progress / progressTotal);
if (cancelled)
{
break;
}
}
}
}
if (!cancelled)
{
// Set Default Icon in Player Settings (Multiple platforms, can be overridden per platform)
PlayerSettings.SetIconsForTargetGroup(BuildTargetGroup.Unknown, new[] { _originalAppIcon });
EditorUtility.DisplayDialog("Images resized!", "All images were resized and updated in the Player Settings", "Ok");
}
else
{
EditorUtility.DisplayDialog("Generation cancelled", string.Format("{0} Images of {1} were resized and updated in the Player Settings.", progress, progressTotal), "Ok");
}
EditorUtility.ClearProgressBar();
replacedetDatabase.Refresh();
}
catch (Exception)
{
EditorUtility.ClearProgressBar();
}
}
19
View Source File : ProgramConfiguration.cs
License : GNU General Public License v3.0
Project Creator : anotak
License : GNU General Public License v3.0
Project Creator : anotak
private bool Read(string cfgfilepathname, string defaultfilepathname)
{
DialogResult result;
// Check if no config for this user exists yet
if(!File.Exists(cfgfilepathname))
{
// Copy new configuration
Logger.WriteLogLine("Local user program configuration is missing!");
File.Copy(defaultfilepathname, cfgfilepathname);
Logger.WriteLogLine("New program configuration copied for local user");
}
// Load it
cfg = new Configuration(cfgfilepathname, true);
if(cfg.ErrorResult)
{
// Error in configuration
// Ask user for a new copy
result = General.ShowErrorMessage("Error in program configuration near line " + cfg.ErrorLine + ": " + cfg.ErrorDescription + "\n\nWould you like to overwrite your settings with a new configuration to restore the default settings?", MessageBoxButtons.YesNoCancel);
if(result == DialogResult.Yes)
{
// Remove old configuration and make a new copy
Logger.WriteLogLine("User requested a new copy of the program configuration");
File.Delete(cfgfilepathname);
File.Copy(defaultfilepathname, cfgfilepathname);
Logger.WriteLogLine("New program configuration copied for local user");
// Load it
cfg = new Configuration(cfgfilepathname, true);
if(cfg.ErrorResult)
{
// Error in configuration
Logger.WriteLogLine("Error in program configuration near line " + cfg.ErrorLine + ": " + cfg.ErrorDescription);
General.ShowErrorMessage("Default program configuration is corrupted. Please re-install Doom Builder.", MessageBoxButtons.OK);
return false;
}
}
else if(result == DialogResult.Cancel)
{
// User requested to cancel startup
Logger.WriteLogLine("User cancelled startup");
return false;
}
}
// Check if a version number is missing
previousversion = cfg.ReadSetting("currentversion", -1);
if(!General.NoSettings && (previousversion == -1))
{
// Remove old configuration and make a new copy
Logger.WriteLogLine("Program configuration is outdated, new configuration will be copied for local user");
File.Delete(cfgfilepathname);
File.Copy(defaultfilepathname, cfgfilepathname);
// Load it
cfg = new Configuration(cfgfilepathname, false);
if(cfg.ErrorResult)
{
// Error in configuration
Logger.WriteLogLine("Error in program configuration near line " + cfg.ErrorLine + ": " + cfg.ErrorDescription);
General.ShowErrorMessage("Default program configuration is corrupted. Please re-install Doom Builder.", MessageBoxButtons.OK);
return false;
}
}
// Success
return true;
}
19
View Source File : ScriptFileDocumentTab.cs
License : GNU General Public License v3.0
Project Creator : anotak
License : GNU General Public License v3.0
Project Creator : anotak
public override void Compile()
{
string inputfile, outputfile;
Compiler compiler;
// List of errors
List<CompilerError> errors = new List<CompilerError>();
try
{
// Initialize compiler
compiler = config.Compiler.Create();
}
catch(Exception e)
{
// Fail
errors.Add(new CompilerError("Unable to initialize compiler. " + e.GetType().Name + ": " + e.Message));
return;
}
// Copy the source file into the temporary directory
inputfile = Path.Combine(compiler.Location, Path.GetFileName(filepathname));
File.Copy(filepathname, inputfile);
// Make random output filename
outputfile = General.MakeTempFilename(compiler.Location, "tmp");
// Run compiler
compiler.Parameters = config.Parameters;
compiler.InputFile = Path.GetFileName(inputfile);
compiler.OutputFile = Path.GetFileName(outputfile);
compiler.SourceFile = filepathname;
compiler.WorkingDirectory = Path.GetDirectoryName(inputfile);
if(compiler.Run())
{
// Fetch errors
foreach(CompilerError e in compiler.Errors)
{
CompilerError newerr = e;
// If the error's filename equals our temporary file,
// replace it with the original source filename
if(string.Compare(e.filename, inputfile, true) == 0)
newerr.filename = filepathname;
errors.Add(newerr);
}
}
// Dispose compiler
compiler.Dispose();
// Feed errors to panel
panel.ShowErrors(errors);
}
19
View Source File : DirectoryReader.cs
License : GNU General Public License v3.0
Project Creator : anotak
License : GNU General Public License v3.0
Project Creator : anotak
protected override string CreateTempFile(string filename)
{
// Just copy the file
string tempfile = General.MakeTempFilename(General.Map.TempPath, "wad");
File.Copy(Path.Combine(location.location, filename), tempfile);
return tempfile;
}
19
View Source File : TimelineSettings.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
public static TimelineSettings Load(
string file)
{
var data = default(TimelineSettings);
lock (Locker)
{
try
{
autoSave = false;
// サイズ0のファイルがもしも存在したら消す
if (File.Exists(file))
{
var fi = new FileInfo(file);
if (fi.Length <= 0)
{
File.Delete(file);
}
}
if (!File.Exists(file))
{
if (File.Exists(MasterFile))
{
File.Copy(MasterFile, file);
}
else
{
data = new TimelineSettings();
return data;
}
}
using (var sr = new StreamReader(file, new UTF8Encoding(false)))
{
if (sr.BaseStream.Length > 0)
{
var xs = new XmlSerializer(typeof(TimelineSettings));
data = xs.Deserialize(sr) as TimelineSettings;
}
}
}
finally
{
if (data != null &&
!data.Styles.Any())
{
var style = TimelineStyle.SuperDefaultStyle;
style.IsDefault = true;
style.IsDefaultNotice = true;
data.Styles.Add(style);
}
autoSave = true;
}
}
return data;
}
19
View Source File : MasterFilePublisher.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
public static void Publish()
{
var dir = DirectoryHelper.FindSubDirectory("resources");
if (!Directory.Exists(dir))
{
return;
}
var masters = Directory.GetFiles(dir, "*.master*");
if (masters == null)
{
return;
}
lock (locker)
{
foreach (var master in masters)
{
var publish = master.Replace(".master", string.Empty);
if (!File.Exists(publish))
{
File.Copy(master, publish);
}
}
}
}
19
View Source File : frmAction.cs
License : GNU General Public License v3.0
Project Creator : antikmozib
License : GNU General Public License v3.0
Project Creator : antikmozib
private void bwCopyMove_DoWork(object sender, DoWorkEventArgs e)
{
frmFileReplaceSkip ReplaceForm = new frmFileReplaceSkip();
//add slash to destination path
if (Destination.Substring(Destination.Length - 1, 1) != "\\")
Destination = Destination + "\\";
general.WriteLog("Starting file copy/move. " + ActionList.Count.ToString() + " files in buffer.");//############
for (int i = 0; i < ActionList.Count; i++)
{
if (bwCopyMove.CancellationPending)
{
e.Cancel = true;
return;
}
general.WriteLog("Begin action - " + ActionList[i]);//############
currentlyWorkingPath = ActionList[i];
bwCopyMove.ReportProgress(i + 1);
//check if the real file exists or not
if (!File.Exists(ActionList[i]))
{
Errors.Add(ActionList[i] + " - File not found.");
general.WriteLog("File not found - " + ActionList[i]);//############
failed++;
continue;
}
//check if destination file already exists or not; show Skip/Replace Form accordingly
if (File.Exists(Destination + general.GetFileName(ActionList[i])))
{
general.WriteLog("File exists in destination - " + Destination + general.GetFileName(ActionList[i]));//############
if (keepDoing == false)
{
this.Invoke((MethodInvoker)delegate
{
ReplaceForm.fileName = general.GetFileName(ActionList[i]);
ReplaceForm.destiNation = Destination.Substring(0, Destination.Length - 1); //remove ugly slash
ReplaceForm.ShowDialog(this);
replaceCode = ReplaceForm.ActionType;
keepDoing = ReplaceForm.keepGoing;
});
}
if (replaceCode == 0)
{
general.WriteLog("Skip - " + ActionList[i]);//############
failed++;
continue; //skip
}
else if (replaceCode == 1) //replace
{
try
{
general.WriteLog("Deleting - " + Destination + general.GetFileName(ActionList[i]));//############
File.Delete(Destination + general.GetFileName(ActionList[i]));
}
catch (Exception ex)
{
general.WriteLog("ERROR - " + ex.Message);//############
Errors.Add(ActionList[i] + " - " + ex.Message);
failed++;
continue;
}
}
else if (replaceCode == 2) //keep both
{
general.WriteLog("Trying to keep both files."); ;//############
// Get a name for the file to be copied which doesn't conflict in the destination.
string newFileName = general.GetFileName(ActionList[i], false);
string FileExt = general.GetFileExt(ActionList[i]);
general.WriteLog("New data: " + newFileName + "; " + FileExt); ;//############
//start looping
int j = 1;
while (File.Exists(Destination + newFileName + " (" + j.ToString() + ")" + FileExt))
{
j++;
}
try
{
general.WriteLog("Keep both. Copying with new name - " + Destination + newFileName + " (" + j.ToString() + ")" + FileExt);//############
File.Copy(ActionList[i], Destination + newFileName + " (" + j.ToString() + ")" + FileExt);
successful++;
}
catch (Exception ex)
{
general.WriteLog("ERROR - " + ex.Message);//############
Errors.Add(ActionList[i] + " - " + ex.Message);
failed++;
continue;
}
}
}
else
{
try
{
general.WriteLog("Copying - " + Destination + general.GetFileName(ActionList[i]));//############
File.Copy(ActionList[i], Destination + general.GetFileName(ActionList[i]));
successful++;
}
catch (Exception ex)
{
general.WriteLog("ERROR - " + ex.Message);//############
Errors.Add(ActionList[i] + " - " + ex.Message);
failed++;
continue;
}
}
if (TypeOfWork == 2)
{
try
{
general.WriteLog("Deleting source - " + ActionList[i]);//############
File.Delete(ActionList[i]);
}
catch (Exception ex)
{
general.WriteLog("ERROR - " + ex.Message);//############
Errors.Add(ActionList[i] + " - " + ex.Message);
}
}
}
}
19
View Source File : MusicServiceExample.cs
License : MIT License
Project Creator : aornelas
License : MIT License
Project Creator : aornelas
void Start()
{
if (!CheckReferences())
{
return;
}
string[] playlist = new string[StreamingPlaylist.Length];
for (int i = 0; i < StreamingPlaylist.Length; ++i)
{
string streamingPath = Path.Combine(Path.Combine(Application.streamingreplacedetsPath, "BackgroundMusicExample"), StreamingPlaylist[i]);
string persistentPath = Path.Combine(Application.persistentDataPath, StreamingPlaylist[i]);
// The Example Music Provider will only search for songs correctly in /doreplacedents/C1 or /doreplacedents/C2 by their filename
// This allows us to package the songs with the Unity application and deploy them from Streaming replacedets.
if (!File.Exists(persistentPath))
{
File.Copy(streamingPath, persistentPath);
}
playlist[i] = "file://" + StreamingPlaylist[i];
}
MLResult result = MLMusicService.Start(MusicServiceProvider);
if (!result.IsOk)
{
Debug.LogErrorFormat("Error: MusicServiceExample failed starting MLMusicService, disabling script. Reason: {0}", result);
enabled = false;
return;
}
MLMusicService.OnPlaybackStateChange += HandlePlaybackStateChanged;
MLMusicService.OnShuffleStateChange += HandleShuffleStateChanged;
MLMusicService.OnRepeatStateChange += HandleRepeatStateChanged;
MLMusicService.OnMetadataChange += HandleMetadataChanged;
MLMusicService.OnPositionChange += HandlePositionChanged;
MLMusicService.OnError += HandleError;
MLMusicService.OnStatusChange += HandleServiceStatusChanged;
_playbackBar.OnValueChanged += Seek;
_volumeBar.OnValueChanged += SetVolume;
_playButton.OnToggle += PlayPause;
_prevButton.OnControllerTriggerDown += Previous;
_nextButton.OnControllerTriggerDown += Next;
_shuffleButton.OnToggle += ToggleShuffle;
_repeatButton.OnControllerTriggerDown += ChangeRepeatState;
// Sync the UI with the provider
_volumeBar.Value = 1.0f;
MLMusicService.RepeatState = MLMusicServiceRepeatState.Off;
MLMusicService.ShuffleState = MLMusicServiceShuffleState.Off;
MLMusicService.SetPlayList(playlist);
MLMusicService.StartPlayback();
}
19
View Source File : WebApiProjectOptions.cs
License : MIT License
Project Creator : arcus-azure
License : MIT License
Project Creator : arcus-azure
private static void AddInMemorySecretProviderFixtureFileToProject(DirectoryInfo fixtureDirectory, DirectoryInfo projectDirectory)
{
string srcInMemorySecretProviderFilePath = FindFixtureTypeInDirectory(fixtureDirectory, typeof(InMemorySecretProvider));
if (!File.Exists(srcInMemorySecretProviderFilePath))
{
throw new FileNotFoundException(
$"Cannot find {nameof(InMemorySecretProvider)}.cs for stubbing the secret during the authentication",
srcInMemorySecretProviderFilePath);
}
string destInMemorySecretProviderFilePath = Path.Combine(projectDirectory.FullName, nameof(InMemorySecretProvider) + ".cs");
File.Copy(srcInMemorySecretProviderFilePath, destInMemorySecretProviderFilePath);
}
19
View Source File : TemplateProject.cs
License : MIT License
Project Creator : arcus-azure
License : MIT License
Project Creator : arcus-azure
public void AddTypeAsFile<TFixture>(IDictionary<string, string> replacements = null, params string[] namespaces)
{
replacements = replacements ?? new Dictionary<string, string>();
namespaces = namespaces ?? new string[0];
string srcPath = FindFixtureTypeInDirectory(FixtureDirectory, typeof(TFixture));
string destPath = Path.Combine(ProjectDirectory.FullName, Path.Combine(namespaces), typeof(TFixture).Name + ".cs");
File.Copy(srcPath, destPath);
string key = typeof(TFixture).Namespace ?? throw new InvalidOperationException("Generic fixture requires a namespace");
string value = namespaces.Length == 0 ? ProjectName : $"{ProjectName}.{String.Join(".", namespaces)}";
replacements[key] = value;
string content = File.ReadAllText(destPath);
content = replacements.Aggregate(content, (txt, kv) => txt.Replace(kv.Key, kv.Value));
File.WriteAllText(destPath, content);
}
19
View Source File : Program.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus
License : GNU Affero General Public License v3.0
Project Creator : arklumpus
static async Task Main(string[] args)
{
ConsoleColor defaultBackground = Console.BackgroundColor;
ConsoleColor defaultForeground = Console.ForegroundColor;
Console.WriteLine();
Console.WriteLine("MuPDFCore test suite");
Console.WriteLine();
Console.WriteLine("Loading tests...");
replacedembly testreplacedembly = replacedembly.Getreplacedembly(typeof(MuPDFWrapperTests));
Type[] types = testreplacedembly.GetTypes();
List<(string, Func<Task>)> tests = new List<(string, Func<Task>)>();
HashSet<string> filesToDeploy = new HashSet<string>();
for (int i = 0; i < types.Length; i++)
{
bool found = false;
Attribute[] typeAttributes = Attribute.GetCustomAttributes(types[i]);
foreach (Attribute attr in typeAttributes)
{
if (attr is TestClreplacedAttribute)
{
found = true;
break;
}
}
if (found)
{
MethodInfo[] methods = types[i].GetMethods(BindingFlags.Public | BindingFlags.Instance);
foreach (MethodInfo method in methods)
{
bool foundMethod = false;
foreach (Attribute attr in method.GetCustomAttributes())
{
if (attr is TestMethodAttribute)
{
foundMethod = true;
}
if (attr is DeploymenreplacedemAttribute dia)
{
filesToDeploy.Add(dia.Path);
}
}
if (foundMethod)
{
Type type = types[i];
tests.Add((types[i].Name + "." + method.Name, async () =>
{
object obj = Activator.CreateInstance(type);
object returnValue = method.Invoke(obj, null);
if (returnValue is Task task)
{
await task;
}
}
));
}
}
}
}
int longestTestNameLength = (from el in tests select el.Item1.Length).Max();
Console.WriteLine();
Console.BackgroundColor = ConsoleColor.Blue;
Console.Write(" Found {0} tests. ", tests.Count.ToString());
Console.BackgroundColor = defaultBackground;
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("{0} files will be deployed:", filesToDeploy.Count.ToString());
foreach (string sr in filesToDeploy)
{
Console.WriteLine(" " + sr);
}
Console.WriteLine();
string deploymentPath = Path.GetTempFileName();
File.Delete(deploymentPath);
Directory.CreateDirectory(deploymentPath);
foreach (string sr in filesToDeploy)
{
File.Copy(sr, Path.Combine(deploymentPath, Path.GetFileName(sr)));
}
string originalCurrentDirectory = Directory.GetCurrentDirectory();
Directory.SetCurrentDirectory(deploymentPath);
Console.WriteLine("Deployment completed.");
Console.WriteLine();
Console.WriteLine("Running tests...");
Console.WriteLine();
List<(string, Func<Task>)> failedTests = new List<(string, Func<Task>)>();
for (int i = 0; i < tests.Count; i++)
{
Console.Write(tests[i].Item1 + new string(' ', longestTestNameLength - tests[i].Item1.Length + 1));
bool failed = false;
Stopwatch sw = Stopwatch.StartNew();
try
{
await tests[i].Item2();
sw.Stop();
}
catch (Exception ex)
{
sw.Stop();
failed = true;
failedTests.Add(tests[i]);
Console.BackgroundColor = ConsoleColor.Red;
Console.Write(" Failed ");
Console.BackgroundColor = defaultBackground;
Console.Write(" {0}ms", sw.ElapsedMilliseconds.ToString());
Console.WriteLine();
while (ex.InnerException != null)
{
Console.WriteLine(ex.Message);
ex = ex.InnerException;
}
Console.WriteLine(ex.Message);
}
if (!failed)
{
Console.BackgroundColor = ConsoleColor.Green;
Console.Write(" Succeeded ");
Console.BackgroundColor = defaultBackground;
Console.Write(" {0}ms", sw.ElapsedMilliseconds.ToString());
}
Console.WriteLine();
}
Console.WriteLine();
if (failedTests.Count < tests.Count)
{
Console.BackgroundColor = ConsoleColor.Green;
Console.Write(" {0} tests succeeded ", tests.Count - failedTests.Count);
Console.BackgroundColor = defaultBackground;
Console.WriteLine();
}
if (failedTests.Count > 0)
{
Console.BackgroundColor = ConsoleColor.Red;
Console.Write(" {0} tests failed ", failedTests.Count);
Console.BackgroundColor = defaultBackground;
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Failed tests:");
Console.ForegroundColor = ConsoleColor.Red;
for (int i= 0; i < failedTests.Count; i++)
{
Console.WriteLine(" {0}", failedTests[i].Item1);
}
Console.WriteLine();
Console.ForegroundColor = defaultForeground;
Console.WriteLine();
Console.WriteLine("The failed tests will now be repeated one by one.");
for (int i = 0; i < failedTests.Count; i++)
{
Console.WriteLine();
Console.WriteLine("Press any key to continue...");
Console.WriteLine();
Console.ReadKey();
Console.Write(failedTests[i].Item1 + new string(' ', longestTestNameLength - failedTests[i].Item1.Length + 1));
bool failed = false;
try
{
await failedTests[i].Item2();
}
catch (Exception ex)
{
failed = true;
Console.BackgroundColor = ConsoleColor.Red;
Console.Write(" Failed ");
Console.BackgroundColor = defaultBackground;
Console.WriteLine();
while (ex.InnerException != null)
{
Console.WriteLine(ex.Message);
ex = ex.InnerException;
}
Console.WriteLine(ex.Message);
}
if (!failed)
{
Console.BackgroundColor = ConsoleColor.Green;
Console.Write(" Succeeded ");
Console.BackgroundColor = defaultBackground;
}
Console.WriteLine();
}
}
Directory.SetCurrentDirectory(originalCurrentDirectory);
Directory.Delete(deploymentPath, true);
}
19
View Source File : ImageCache.cs
License : GNU General Public License v3.0
Project Creator : arklumpus
License : GNU General Public License v3.0
Project Creator : arklumpus
public static (string, bool) ImageUriResolver(string imageUri, string baseUriString)
{
if (!imageCache.TryGetValue(baseUriString + "|||" + imageUri, out string cachedImage))
{
(string imagePath, bool wasDownloaded) = VectSharp.Markdown.HTTPUtils.ResolveImageURI(imageUri, baseUriString);
if (!string.IsNullOrEmpty(imagePath) && File.Exists(imagePath))
{
string id = Guid.NewGuid().ToString();
cachedImage = Path.Combine(imageCacheFolder, id + Path.GetExtension(imagePath));
if (wasDownloaded)
{
if (!Directory.Exists(imageCacheFolder))
{
Directory.CreateDirectory(imageCacheFolder);
}
File.Move(imagePath, cachedImage);
Directory.Delete(Path.GetDirectoryName(imagePath));
}
else
{
File.Copy(imagePath, cachedImage);
}
imageCache[baseUriString + "|||" + imageUri] = cachedImage;
}
else
{
cachedImage = null;
}
}
return (cachedImage, false);
}
19
View Source File : ModHandler.cs
License : MIT License
Project Creator : AstroTechies
License : MIT License
Project Creator : AstroTechies
public void SyncModsFromDisk(bool skipIndexing = false)
{
if (!skipIndexing)
{
Mods = new List<Mod>();
string[] allMods = Directory.GetFiles(DownloadPath, "*_P.pak", SearchOption.TopDirectoryOnly);
ModLookup = new Dictionary<string, Mod>();
foreach (string modPath in allMods)
{
SyncSingleModFromDisk(modPath, out _, false);
}
}
SortVersions();
foreach (Mod mod in Mods)
{
mod.InstalledVersion = mod.AvailableVersions[0];
}
string[] installedMods = Directory.GetFiles(InstallPath, "*_P.pak", SearchOption.TopDirectoryOnly);
foreach (string modPath in installedMods)
{
var modNameOnDisk = Path.GetFileName(modPath);
var m = new Mod(ExtractMetadataFromPath(modPath), modNameOnDisk);
if (ModLookup.ContainsKey(m.CurrentModData.ModID))
{
ModLookup[m.CurrentModData.ModID].Enabled = true;
ModLookup[m.CurrentModData.ModID].NameOnDisk = modNameOnDisk;
ModLookup[m.CurrentModData.ModID].InstalledVersion = m.InstalledVersion;
ModLookup[m.CurrentModData.ModID].Priority = m.Priority;
if (!ModLookup[m.CurrentModData.ModID].AvailableVersions.Contains(m.InstalledVersion))
{
File.Copy(modPath, Path.Combine(DownloadPath, modNameOnDisk));
ModLookup[m.CurrentModData.ModID].AvailableVersions.Add(m.InstalledVersion);
ModLookup[m.CurrentModData.ModID].AllModData.Add(m.InstalledVersion, m.CurrentModData);
}
}
else
{
//if (Program.CommandLineOptions.ServerMode && m.CurrentModData.Sync == SyncMode.ClientOnly) continue;
if (m.Priority < 999)
{
File.Copy(modPath, Path.Combine(DownloadPath, modNameOnDisk), true);
m.Enabled = true;
Mods.Add(m);
ModLookup.Add(m.CurrentModData.ModID, m);
}
}
}
SortMods();
}
19
View Source File : ProfileSelector.cs
License : MIT License
Project Creator : AstroTechies
License : MIT License
Project Creator : AstroTechies
private void ForceExportProfile()
{
if (listBox1.SelectedValue == null || SelectedProfile == null)
{
this.ShowBasicButton("Please select a profile to export it as a .zip file.", "OK", null, null);
return;
}
var dialog = new SaveFileDialog();
dialog.Filter = "ZIP files (*.zip)|*.zip|All files (*.*)|*.*";
dialog.replacedle = "Export a profile";
dialog.RestoreDirectory = true;
if (dialog.ShowDialog() == DialogResult.OK)
{
string targetFolderPath = Path.Combine(Path.GetTempPath(), "AstroModLoader", "export");
Directory.CreateDirectory(targetFolderPath);
ModProfile creatingProfile = new ModProfile();
creatingProfile.ProfileData = new Dictionary<string, Mod>();
creatingProfile.Name = listBox1.SelectedValue as string;
creatingProfile.Info = "Exported by " + AMLUtils.UserAgent + " at " + DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffK");
List<KeyValuePair<string, Mod>> plannedOrdering = new List<KeyValuePair<string, Mod>>();
foreach (KeyValuePair<string, Mod> entry in SelectedProfile.ProfileData)
{
if (entry.Value.Enabled) plannedOrdering.Add(entry);
}
plannedOrdering = new List<KeyValuePair<string, Mod>>(plannedOrdering.OrderBy(o => o.Value.Priority).ToList());
for (int i = 0; i < plannedOrdering.Count; i++)
{
plannedOrdering[i].Value.Priority = i + 1;
creatingProfile.ProfileData[plannedOrdering[i].Key] = plannedOrdering[i].Value;
// Copy mod pak to the zip as well
string onePathOnDisk = OurParentForm.ModManager.GetPathOnDisk(plannedOrdering[i].Value, plannedOrdering[i].Key);
if (!string.IsNullOrEmpty(onePathOnDisk)) File.Copy(onePathOnDisk, Path.Combine(targetFolderPath, Path.GetFileName(onePathOnDisk)));
}
File.WriteAllBytes(Path.Combine(targetFolderPath, "profile1.json"), Encoding.UTF8.GetBytes(AMLUtils.SerializeObject(creatingProfile)));
ZipFile.CreateFromDirectory(targetFolderPath, dialog.FileName);
Directory.Delete(targetFolderPath, true);
RefreshBox();
statusLabel.Text = "Successfully exported profile.";
}
}
19
View Source File : BugReporter.cs
License : GNU General Public License v3.0
Project Creator : Athlon007
License : GNU General Public License v3.0
Project Creator : Athlon007
public void BugReport()
{
if (Directory.Exists(BugReportPath))
{
Directory.Delete(BugReportPath, true);
}
Directory.CreateDirectory(BugReportPath);
// Get output_log.txt
if (File.Exists($"{ExceptionManager.RootPath}/output_log.txt"))
{
File.Copy($"{ExceptionManager.RootPath}/output_log.txt", $"{BugReportPath}/output_log.txt");
}
// Now we are getting logs generated today.
string today = DateTime.Now.ToString("yyyy-MM-dd");
foreach (string log in Directory.GetFiles(ExceptionManager.LogFolder, $"*{today}*.txt"))
{
string pathToFile = log.Replace("\\", "/");
string nameOfFile = log.Split('\\')[1];
File.Copy(pathToFile, $"{BugReportPath}/{nameOfFile}");
}
// Generate a MOP report.
using (StreamWriter sw = new StreamWriter($"{BugReportPath}/MOP_REPORT.txt"))
{
sw.WriteLine(ExceptionManager.GetGameInfo());
}
// Now we are packing up everything.
string lastZipFilePath = $"{BugReportPath}/MOP Bug Report - {DateTime.Now:yyyy-MM-dd_HH-mm}.zip";
using (ZipFile zip = new ZipFile())
{
foreach (string file in Directory.GetFiles(BugReportPath, "*.txt"))
{
zip.AddFile(file, "");
}
zip.Save(lastZipFilePath);
}
// Now we are deleting all .txt files.
foreach (string file in Directory.GetFiles(BugReportPath, "*.txt"))
{
File.Delete(file);
}
// Create the tutorial.
using (StreamWriter sw = new StreamWriter($"{BugReportPath}/README.txt"))
{
sw.WriteLine("A MOP report archive has been successfully generated.\n");
sw.WriteLine("Upload .zip file to some file hosting site, such as https://www.mediafire.com/. \n\n" +
"Remember to describe how you came acorss the error!");
}
// We are asking the user if he wants to add his game save to the zip file.
if (File.Exists(SaveManager.SavePath))
{
ModPrompt.CreateYesNoPrompt("Would you like to your include save file?\n\n" +
"This may greatly improve finding and fixing the bug.", "MOP - Bug Report",
() => {
using (ZipFile zip = ZipFile.Read(lastZipFilePath))
{
// Create folder called Save in the zip and get defaultES2Save.txt and items.txt.
zip.AddDirectoryByName("Save");
if (File.Exists(SaveManager.SavePath))
{
zip.AddFile(SaveManager.SavePath, "Save");
}
if (File.Exists(SaveManager.ItemsPath))
{
zip.AddFile(SaveManager.ItemsPath, "Save");
}
zip.Save();
}
},
onPromptClose: () => { Process.Start(BugReportPath); Process.Start($"{BugReportPath}/README.txt"); });
}
}
19
View Source File : LiteDbMigrations.cs
License : GNU General Public License v3.0
Project Creator : atomex-me
License : GNU General Public License v3.0
Project Creator : atomex-me
private static void Backup(string pathToDb)
{
var dbDirectory = Path.GetDirectoryName(pathToDb);
var pathToBackups = $"{dbDirectory}/backups";
if (!Directory.Exists(pathToBackups))
Directory.CreateDirectory(pathToBackups);
var pathToBackup = $"{pathToBackups}/data_{DateTime.Now:ddMMyyyy_HHmmss_fff}";
var fullPathToDb = Path.GetFullPath(pathToDb);
var fullPathToBackup = Path.GetFullPath(pathToBackup);
File.Copy(fullPathToDb, fullPathToBackup);
}
19
View Source File : DirectoryModuleCatalogFixture.Desktop.cs
License : MIT License
Project Creator : AvaloniaCommunity
License : MIT License
Project Creator : AvaloniaCommunity
[TestMethod]
public void ShouldNotFailWhenAlreadyLoadedreplacedembliesAreAlsoFoundOnTargetDirectory()
{
CompilerHelper.CompileFile(@"Prism.Avalonia.Tests.Mocks.Modules.MockModuleA.cs",
ModulesDirectory1 + @"\MockModuleA.dll");
string filename = typeof(DirectoryModuleCatalog).replacedembly.Location;
string destinationFileName = Path.Combine(ModulesDirectory1, Path.GetFileName(filename));
File.Copy(filename, destinationFileName);
DirectoryModuleCatalog catalog = new DirectoryModuleCatalog
{
ModulePath = ModulesDirectory1
};
catalog.Load();
var modules = catalog.Modules.ToArray();
replacedert.AreEqual(1, modules.Length);
}
See More Examples