Here are the examples of the csharp api System.IO.File.CreateText(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
754 Examples
19
Source : Program.cs
with MIT License
from 0xd4d
with MIT License
from 0xd4d
static DisasmJob[] GetJobs(DisasmInfo[] methods, string outputDir, FileOutputKind fileOutputKind, FilenameFormat filenameFormat, out string? baseDir) {
FilenameProvider filenameProvider;
var jobs = new List<DisasmJob>();
switch (fileOutputKind) {
case FileOutputKind.Stdout:
baseDir = null;
return new[] { new DisasmJob(() => (Console.Out, false), methods) };
case FileOutputKind.OneFile:
if (string.IsNullOrEmpty(outputDir))
throw new ApplicationException("Missing filename");
baseDir = Path.GetDirectoryName(outputDir);
return new[] { new DisasmJob(() => (File.CreateText(outputDir), true), methods) };
case FileOutputKind.OneFilePerType:
if (string.IsNullOrEmpty(outputDir))
throw new ApplicationException("Missing output dir");
baseDir = outputDir;
filenameProvider = new FilenameProvider(filenameFormat, baseDir, DASM_EXT);
var types = new Dictionary<uint, List<DisasmInfo>>();
foreach (var method in methods) {
if (!types.TryGetValue(method.TypeToken, out var typeMethods))
types.Add(method.TypeToken, typeMethods = new List<DisasmInfo>());
typeMethods.Add(method);
}
var allTypes = new List<List<DisasmInfo>>(types.Values);
allTypes.Sort((a, b) => StringComparer.Ordinal.Compare(a[0].TypeFullName, b[0].TypeFullName));
foreach (var typeMethods in allTypes) {
uint token = typeMethods[0].TypeToken;
var name = GetTypeName(typeMethods[0].TypeFullName);
var getTextWriter = CreateGetTextWriter(filenameProvider.GetFilename(token, name));
jobs.Add(new DisasmJob(getTextWriter, typeMethods.ToArray()));
}
return jobs.ToArray();
case FileOutputKind.OneFilePerMethod:
if (string.IsNullOrEmpty(outputDir))
throw new ApplicationException("Missing output dir");
baseDir = outputDir;
filenameProvider = new FilenameProvider(filenameFormat, baseDir, DASM_EXT);
foreach (var method in methods) {
uint token = method.MethodToken;
var name = method.MethodName.Replace('.', '_');
var getTextWriter = CreateGetTextWriter(filenameProvider.GetFilename(token, name));
jobs.Add(new DisasmJob(getTextWriter, new[] { method }));
}
return jobs.ToArray();
default:
throw new InvalidOperationException();
}
}
19
Source : Program.cs
with MIT License
from 0xd4d
with MIT License
from 0xd4d
static Func<(TextWriter writer, bool close)> CreateGetTextWriter(string filename) =>
() => (File.CreateText(filename), true);
19
Source : Utils.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
public static int ToJsonFile(Object obj, string filePath, bool nullValue = true)
{
int result;
try
{
using (StreamWriter file = File.CreateText(filePath))
{
JsonSerializer serializer;
if (nullValue)
{
serializer = new JsonSerializer() { Formatting = Formatting.Indented };
}
else
{
serializer = new JsonSerializer() { Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore };
}
serializer.Serialize(file, obj);
}
result = 0;
}
catch (Exception ex)
{
SaveLog(ex.Message, ex);
result = -1;
}
return result;
}
19
Source : ServerManager.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
public bool StartPrepare(string path)
{
var jsonFile = GetSettingsFileName(path);
if (!File.Exists(jsonFile))
{
using (StreamWriter file = File.CreateText(jsonFile))
{
var jsonText = JsonSerializer.Serialize(ServerSettings, new JsonSerializerOptions() { WriteIndented = true });
file.WriteLine(jsonText);
}
Console.WriteLine("Created Settings.json, server was been stopped");
Console.WriteLine($"RU: Настройте сервер, заполните {jsonFile}");
Console.WriteLine("Enter some key");
Console.ReadKey();
return false;
}
else
{
try
{
using (var fs = new StreamReader(jsonFile, Encoding.UTF8))
{
var jsonString = fs.ReadToEnd();
ServerSettings = JsonSerializer.Deserialize<ServerSettings>(jsonString);
}
ServerSettings.WorkingDirectory = path;
var results = new List<ValidationResult>();
var context = new ValidationContext(ServerSettings);
if (!Validator.TryValidateObject(ServerSettings, context, results, true))
{
foreach (var error in results)
{
Console.WriteLine(error.ErrorMessage);
Loger.Log(error.ErrorMessage);
}
Console.ReadKey();
return false;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine($"RU: Проверьте настройки сервера {jsonFile}");
Console.WriteLine("EN: Check Settings.json");
Console.ReadKey();
return false;
}
}
MainHelper.OffAllLog = false;
Loger.PathLog = path;
Loger.IsServer = true;
var rep = Repository.Get;
rep.SaveFileName = GetWorldFileName(path);
rep.Load();
CheckDiscrordUser();
FileHashChecker = new FileHashChecker(ServerSettings);
return true;
}
19
Source : ExportExampleHelper.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private static void ExportExampleToSolution(ref string lastGroup, Example current)
{
string projectName = ProjectWriter.WriteProject(
current, ExportPath + @"\", TryAutomaticallyFindreplacedemblies(), false);
if (!File.Exists(ScriptPath))
{
using (var fs = File.CreateText(ScriptPath))
{
// Write the header
fs.WriteLine("REM Compile and run all exported SciChart examples for testing");
fs.WriteLine("@echo OFF");
fs.WriteLine("");
fs.Close();
}
}
if (lastGroup != null && current.Group != lastGroup)
{
using (var fs = File.AppendText(ScriptPath))
{
fs.WriteLine("@echo Finished Example Group " + lastGroup + ". Press any key to continue...");
fs.WriteLine("pause(0)");
fs.WriteLine("");
}
}
lastGroup = current.Group;
using (var fs = File.AppendText(ScriptPath))
{
fs.WriteLine("@echo Building " + projectName);
fs.WriteLine(@"IF NOT EXIST ""C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin"" @echo VisualStudio folder not exists with the following path: ""C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin"" ");
fs.WriteLine(@"call ""C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin\MSBuild.exe"" /p:Configuration=""Debug"" ""{0}/{0}.csproj"" /p:WarningLevel=0", projectName);
fs.WriteLine("if ERRORLEVEL 1 (");
fs.WriteLine(" @echo - Example {0} Failed to compile >> errorlog.txt", projectName);
fs.WriteLine(") else (");
fs.WriteLine(@" start """" ""{0}/bin/Debug/{0}.exe""", projectName);
fs.WriteLine(")");
fs.WriteLine("");
}
}
19
Source : MainViewModel.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public static void WriteLog(string entry, string fileName)
{
string strPath = fileName;
System.IO.StreamWriter sw;
if (System.IO.File.Exists(strPath))
sw = System.IO.File.AppendText(strPath);
else
sw = System.IO.File.CreateText(strPath);
if (sw != null)
{
sw.WriteLine(entry + "[" + DateTime.Now.ToLongTimeString() + "]");
sw.Close();
}
}
19
Source : Program_Setup.cs
with GNU Affero General Public License v3.0
from ACEmulator
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 : CmdLineActions.cs
with MIT License
from action-bi-toolkit
with MIT License
from action-bi-toolkit
[ArgActionMethod, ArgShortcut("export-usage"), OmitFromUsageDocs]
public void ExportUsage(
[ArgDescription("The optional path to a file to write into. Prints to console if not provided.")] string outPath
)
{
var sb = new StringBuilder();
var definitions = CmdLineArgumentsDefinitionExtensions.For<CmdLineActions>().RemoveAutoAliases();
sb.AppendLine("## Usage");
sb.AppendLine();
sb.AppendLine($" {definitions.UsageSummary}");
sb.AppendLine();
sb.AppendLine($"_{definitions.Description}_");
sb.AppendLine();
sb.AppendLine("### Actions");
sb.AppendLine();
foreach (var action in definitions.UsageActions)
{
sb.AppendLine($"#### {action.DefaultAlias}");
sb.AppendLine();
sb.AppendLine($" {action.UsageSummary}");
sb.AppendLine();
sb.AppendLine(action.Description);
sb.AppendLine();
if (action.HasArguments)
{
sb.AppendLine("| Option | Default Value | Is Switch | Description |");
sb.AppendLine("| --- | --- | --- | --- |");
foreach (var arg in action.UsageArguments.Where(a => !a.OmitFromUsage))
{
var enumValues = arg.EnumValuesAndDescriptions.Aggregate(new StringBuilder(), (sb, fullDescr) => {
var pos = fullDescr.IndexOf(" - ");
var value = fullDescr.Substring(0, pos);
var descr = fullDescr.Substring(pos);
sb.Append($" <br> `{value}` {descr}");
return sb;
});
sb.AppendLine($"| {arg.DefaultAlias}{(arg.IsRequired ? "*" : "")} | {(arg.HasDefaultValue ? $"`{arg.DefaultValue}`" : "")} | {(arg.ArgumentType == typeof(bool) ? "X" : "")} | {arg.Description}{enumValues} |");
}
sb.AppendLine();
}
if (action.HasExamples)
{
foreach (var example in action.Examples)
{
if (example.Hasreplacedle)
{
sb.AppendLine($"**{example.replacedle}**");
sb.AppendLine();
}
sb.AppendLine($" {example.Example}");
sb.AppendLine();
sb.AppendLine($"_{example.Description}_");
sb.AppendLine();
}
}
}
if (String.IsNullOrEmpty(outPath))
{
using (_appSettings.SuppressConsoleLogs())
{
Console.WriteLine(sb.ToString());
}
}
else
{
using (var writer = File.CreateText(outPath))
{
writer.Write(sb.ToString());
}
}
}
19
Source : TabularDataReader.cs
with MIT License
from action-bi-toolkit
with MIT License
from action-bi-toolkit
public void ExtractTableData(string outPath, string dateTimeFormat)
{
Directory.CreateDirectory(outPath);
foreach (var table in GetTableNames())
{
var path = Path.Combine(outPath, $"{table}.csv");
Log.Debug("Extracting table {Table} to file: {Path}", table, path);
using (var outFile = File.CreateText(path))
using (var csv = new CsvWriter(outFile, CultureInfo.CurrentCulture))
using (var cmd = _connection.CreateCommand())
{
csv.Context.TypeConverterOptionsCache.GetOptions<DateTime>().Formats = new[] { dateTimeFormat };
cmd.CommandText = $"EVALUATE '{table}'";
try
{
using (var reader = cmd.ExecuteReader())
{
// Header
for (int i = 0; i < reader.FieldCount; i++)
{
var column = colNameRegex.Match(reader.GetName(i)).Groups[2].Value ?? reader.GetName(i);
csv.WriteField(column);
}
// Data
var recordsRead = 0;
while (reader.Read())
{
csv.NextRecord();
for (int i = 0; i < reader.FieldCount; i++)
{
csv.WriteField(reader.GetValue(i));
}
recordsRead++;
}
Log.Information("Extracted {RecordCount} records from table {Table}", recordsRead, table);
}
}
catch (AdomdErrorResponseException ex)
{
Log.Debug(ex, "An error occurred reading from table {Table}", table);
}
}
}
}
19
Source : CmdLineActions.cs
with MIT License
from action-bi-toolkit
with MIT License
from action-bi-toolkit
[ArgActionMethod, ArgShortcut("export-bim"), ArgDescription("Converts the Model artifacts to a TMSL/BIM file.")]
public void ExportBim(
[ArgRequired, ArgExistingDirectory, ArgDescription("The PbixProj folder to export the BIM file from.")] string folder,
[ArgDescription("Generate model data sources. Only required for deployment to Azure replacedysis Services, but not for Power BI Premium via the XMLA endpoint.")] bool generateDataSources,
[ArgDescription("List transformations to be applied to TMSL doreplacedent.")] ExportTransforms transforms
)
{
using (var rootFolder = new FileSystem.ProjectRootFolder(folder))
{
var serializer = new Serialization.TabularModelSerializer(rootFolder, ProjectSystem.PbixProject.FromFolder(rootFolder).Settings.Model);
if (serializer.TryDeserialize(out var db)) // throws for V1 models
{
if (generateDataSources)
{
#if NETFRAMEWORK
var dataSources = TabularModel.TabularModelConversions.GenerateDataSources(db);
db["model"]["dataSources"] = dataSources;
#elif NET
throw new PlatformNotSupportedException("Generating DataSources is not supported by the pbi-tools Core version.");
#endif
}
if (transforms.HasFlag(ExportTransforms.RemovePBIDataSourceVersion))
{
db["model"]["defaultPowerBIDataSourceVersion"]?.Parent.Remove();
}
var path = Path.GetFullPath(Path.Combine(folder, "..", $"{Path.GetFileName(folder)}.bim"));
using (var writer = new JsonTextWriter(File.CreateText(path)))
{
writer.Formatting = Formatting.Indented;
db.WriteTo(writer);
}
Console.WriteLine($"BIM file written to: {path}");
}
else
{
throw new PbiToolsCliException(ExitCode.UnspecifiedError, "A BIM file could not be exported.");
}
}
}
19
Source : AppDataManager.cs
with GNU General Public License v3.0
from Adam-Wilkinson
with GNU General Public License v3.0
from Adam-Wilkinson
public void Save(string fileName, object toSave)
{
string savePath = Path.Combine(AppDataLocation, fileName);
if (!Directory.Exists(Path.GetDirectoryName(savePath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(savePath));
}
string json = JsonConvert.SerializeObject(toSave, Formatting.Indented, JsonSettings);
using var stream = File.CreateText(Path.Combine(AppDataLocation, fileName));
stream.Write(json);
}
19
Source : UpdateManager.cs
with MIT License
from admaiorastudio
with MIT License
from admaiorastudio
public async Task StartAsync()
{
// Kill any previous running processes
KillRunningProcesses();
string serverreplacedemblyPath = Path.Combine(Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location), @"Server\RealXamlServer.dll");
if (File.Exists(serverreplacedemblyPath))
{
ProcessStartInfo psiServer = new ProcessStartInfo("dotnet");
psiServer.Arguments = $"\"{serverreplacedemblyPath}\"";
psiServer.Verb = "runas";
//psiServer.CreateNoWindow = true;
//psiServer.WindowStyle = ProcessWindowStyle.Hidden;
_pServer = Process.Start(psiServer);
System.Threading.Thread.Sleep(1500);
}
if (_pServer == null)
throw new InvalidOperationException("Unable to start RealXaml server.");
if (File.Exists(_processDatFilePath))
File.Delete(_processDatFilePath);
using (var s = File.CreateText(_processDatFilePath))
{
await s.WriteAsync(_pServer.Id.ToString());
}
string ipAddress = NetworkHelper.GetLocalIPAddress();
_hubConnection = new HubConnectionBuilder()
.WithUrl($"http://localhost:5001/hub")
.Build();
await _hubConnection.StartAsync();
if (_hubConnection.State != HubConnectionState.Connected)
{
_hubConnection = null;
throw new InvalidOperationException("Unable to connect.");
}
_hubConnection.On("HelloIde", WhenHelloIde);
_hubConnection.On("ByeIde", WhenByeIde);
_hubConnection.On<string>("ClientRegistered", WhenClientRegistered);
_hubConnection.On<string, byte[]>("XamlReceived", WhenXamlReceived);
_hubConnection.On<string, string>("replacedemblyReceived", WhenreplacedemblyReceived);
_hubConnection.On<string>("PageAppeared", WhenPageAppeared);
_hubConnection.On<string>("PageDisappeared", WhenPageDisappeared);
_hubConnection.On<string>("ExceptionThrown", WhenExceptionThrown);
_hubConnection.On<string>("IdeNotified", WhenIdeNotified);
_ideId = Guid.NewGuid();
await _hubConnection.SendAsync("RegisterIde", _ideId.ToString());
}
19
Source : CrmJsonConvert.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static void SerializeFile(string path, object value)
{
using (var writer = System.IO.File.CreateText(path))
using (var jtw = new JsonTextWriter(writer))
{
var serializer = JsonSerializer.Create(SerializerSettings);
serializer.Serialize(jtw, value);
}
}
19
Source : AElfKeyStore.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
private async Task<bool> WriteKeyPairAsync(ECKeyPair keyPair, string preplacedword)
{
if (keyPair?.PrivateKey == null || keyPair.PublicKey == null)
throw new InvalidKeyPairException("Invalid keypair (null reference).", null);
// Ensure path exists
CreateKeystoreDirectory();
var address = Address.FromPublicKey(keyPair.PublicKey);
var fullPath = GetKeyFileFullPath(address.ToBase58());
await Task.Run(() =>
{
using (var writer = File.CreateText(fullPath))
{
var scryptResult = _keyStoreService.EncryptAndGenerateDefaultKeyStoreAsJson(preplacedword,
keyPair.PrivateKey,
address.ToBase58());
writer.Write(scryptResult);
writer.Flush();
}
});
return true;
}
19
Source : IdentityBuilderExtensions.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
private static IOptions<OAuthServiceAccountKey> StoreAuthFile(IServiceProvider provider, string authFilePath)
{
var authOptions = provider.GetRequiredService<IOptions<OAuthServiceAccountKey>>();
var json = JsonConvert.SerializeObject(authOptions.Value);
using (var writer = File.CreateText(authFilePath))
{
writer.Write(json);
writer.Flush();
writer.Close();
}
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", authFilePath);
return authOptions;
}
19
Source : FirestoreTestFixture.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
public static FirestoreDb CreateFirestoreDb(IServiceProvider provider)
{
var authOptions = provider.GetRequiredService<IOptions<OAuthServiceAccountKey>>();
var path = Path.GetTempFileName();
var json = JsonConvert.SerializeObject(authOptions.Value);
using var writer = File.CreateText(path);
writer.Write(json);
writer.Flush();
writer.Close();
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", path);
var client = FirestoreClient.Create();
return FirestoreDb.Create(authOptions.Value.project_id, client: client);
}
19
Source : IdentityBuilderExtensionsTest.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
[Fact]
public void AddFirebaseStores_with_project_id_Test()
{
var builder = new ConfigurationBuilder();
var configuration = builder
.AddEnvironmentVariables()
.AddJsonFile(Path.Combine(Directory.GetCurrentDirectory(), "../../../../idenreplacedyfirestore.json"))
.Build();
var authOptions = configuration.GetSection("FirestoreAuthTokenOptions").Get<OAuthServiceAccountKey>();
if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS")))
{
var path = Path.GetTempFileName();
var json = JsonConvert.SerializeObject(authOptions);
using var writer = File.CreateText(path);
writer.Write(json);
writer.Flush();
writer.Close();
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", path);
}
var services = new ServiceCollection();
services
.AddIdenreplacedy<IdenreplacedyUser, IdenreplacedyRole>()
.AddFirestoreStores(authOptions.project_id);
var provider = services.BuildServiceProvider();
replacedert.NotNull(provider.GetService<IUserStore<IdenreplacedyUser>>());
replacedert.NotNull(provider.GetService<IRoleStore<IdenreplacedyRole>>());
}
19
Source : UserStoreTest.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
private static void CreateAuthFile(IServiceProvider provider, out IOptions<OAuthServiceAccountKey> authOptions)
{
authOptions = provider.GetRequiredService<IOptions<OAuthServiceAccountKey>>();
var json = JsonConvert.SerializeObject(authOptions.Value);
var path = Path.GetTempFileName();
using var writer = File.CreateText(path);
writer.Write(json);
writer.Flush();
writer.Close();
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", path);
}
19
Source : MainWindow.xaml.cs
with MIT License
from ahopper
with MIT License
from ahopper
private void ExportFromSVG(string replacedle, string path)
{
using (var file = File.CreateText($"..\\..\\..\\Avalonia.IconPacks\\Icons\\{replacedle}.xaml"))
{
file.WriteLine("<Styles xmlns=\"https://github.com/avaloniaui\"");
file.WriteLine(" xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" >");
file.WriteLine(" <Style>");
file.WriteLine(" <Style.Resources>");
foreach (var svgpath in Directory.EnumerateFiles(path, "*.svg", SearchOption.AllDirectories))
{
try
{
XmlDoreplacedent drawingDoc = new XmlDoreplacedent();
using (XmlTextReader tr = new XmlTextReader(svgpath))
{
tr.Namespaces = false;
drawingDoc.Load(tr);
}
var name = Path.GetFileNameWithoutExtension(svgpath);
var dgChildren = drawingDoc.DoreplacedentElement.GetElementsByTagName("path");
if (dgChildren.Count == 1)
{
file.WriteLine($" <GeometryDrawing x:Key=\"{replacedle}.{name}\" Brush=\"{dgChildren[0].Attributes["fill"].Value}\" Geometry=\"{dgChildren[0].Attributes["d"].Value}\"/>");
}
else
{
file.WriteLine($" <DrawingGroup x:Key=\"{replacedle}.{name}\" >");
foreach (XmlElement dp in dgChildren)
{
file.WriteLine($" <GeometryDrawing Brush=\"{dp.Attributes["fill"].Value}\" Geometry=\"{dp.Attributes["d"].Value}\"/>");
}
file.WriteLine($" </DrawingGroup>");
}
}
catch (Exception e)
{
}
}
file.WriteLine(" </Style.Resources>");
file.WriteLine(" </Style>");
file.WriteLine("</Styles>");
}
}
19
Source : MainWindow.xaml.cs
with MIT License
from ahopper
with MIT License
from ahopper
void exportIconPack<P>(string replacedle, IDictionary<P, string> pack, bool invert = false) where P : Enum
{
//TODO use proper xml writer
using (var file = File.CreateText($"..\\..\\..\\Avalonia.IconPacks\\Icons\\{replacedle}.xaml"))
{
file.WriteLine("<Styles xmlns=\"https://github.com/avaloniaui\"");
file.WriteLine(" xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" >");
file.WriteLine(" <Style>");
file.WriteLine(" <Style.Resources>");
var icons = Enum.GetValues(typeof(P));
foreach (var icon in icons)
{
var name = icon.ToString();
var data = pack[(P)icon];
if (invert)
{
data = invertPath(data);
}
if (!String.IsNullOrEmpty(data))
{
file.WriteLine($" <GeometryDrawing x:Key=\"{replacedle}.{name}\" Brush=\"#FF000000\" Geometry=\"{data}\"/>");
}
}
file.WriteLine(" </Style.Resources>");
file.WriteLine(" </Style>");
file.WriteLine("</Styles>");
}
}
19
Source : Program.cs
with GNU Affero General Public License v3.0
from aianlinb
with GNU Affero General Public License v3.0
from aianlinb
static void Main(string[] args)
{
string path = args.Length > 0 && Path.GetFileName(args[0]) == "_.index.bin" ? args[0] : "_.index.bin";
if (!File.Exists(path))
{
Console.WriteLine("File not found: " + path);
Console.WriteLine("Click enter to exit . . .");
Console.ReadLine();
return;
}
Console.WriteLine("Loading . . .");
var ic = new IndexContainer(path);
Console.WriteLine("Found:");
Console.WriteLine(ic.Bundles.Length.ToString() + " BundleRecords");
Console.WriteLine(ic.Files.Length.ToString() + " FileRecords");
Console.WriteLine(ic.Directorys.Length.ToString() + " DirectoryRecords");
Console.WriteLine(Environment.NewLine + "Generating FileList . . .");
var sw = File.CreateText("FileList.yml");
foreach (var b in ic.Bundles)
{
sw.WriteLine(b.Name + ":");
foreach (var f in b.Files)
sw.WriteLine("- " + f.path);
}
sw.Flush();
sw.Close();
Console.WriteLine("Done!");
Console.WriteLine(Environment.NewLine + "Click enter to exit . . .");
Console.ReadLine();
}
19
Source : MainProgram.cs
with MIT License
from AlbertMN
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 : ConnectCamera.xaml.cs
with MIT License
from AlexBrochu
with MIT License
from AlexBrochu
private void OnSave(object sender, RoutedEventArgs e)
{
if (camera_name.Text == "")
{
camera_name.Background = new SolidColorBrush(Colors.Red);
}
else if(address.Text == "")
{
address.Background = new SolidColorBrush(Colors.Red);
}
else if (user.Text == "")
{
user.Background = new SolidColorBrush(Colors.Red);
}
else if (preplacedword.Preplacedword == "")
{
preplacedword.Background = new SolidColorBrush(Colors.Red);
}
else
{
CameraConnexion cc = new CameraConnexion();
cc.Address = address.Text;
cc.CameraName = camera_name.Text;
cc.Preplacedword = preplacedword.Preplacedword;
cc.User = user.Text;
// write login info in json file
if (cameras == null)
{
cameras = new List<CameraConnexion>();
}
// override camera if is already saved with same name
int index = cameras.FindIndex(element => element.CameraName.Equals(cc.CameraName));
if (index == -1)
{
cameras.Add(cc);
}
else
{
cameras[index] = cc;
}
string json = JsonConvert.SerializeObject(cameras);
if (!File.Exists(path_to_connexion_file))
{
File.CreateText(path_to_connexion_file).Close();
}
using (StreamWriter file = new StreamWriter(path_to_connexion_file, false))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, cameras);
}
LoadConnexion();
}
}
19
Source : ConnectCamera.xaml.cs
with MIT License
from AlexBrochu
with MIT License
from AlexBrochu
private void LoadConnexion()
{
listBox_saved.Items.Clear();
if (!File.Exists(path_to_connexion_file))
{
File.CreateText(path_to_connexion_file).Close();
}
using (StreamReader file = File.OpenText(path_to_connexion_file))
{
JsonSerializer serializer = new JsonSerializer();
cameras = (List<CameraConnexion>)serializer.Deserialize(file, typeof(List<CameraConnexion>));
if (cameras != null)
{
foreach (CameraConnexion cam in cameras)
{
listBox_saved.Items.Add(cam.CameraName);
}
}
}
}
19
Source : ConnectCamera.xaml.cs
with MIT License
from AlexBrochu
with MIT License
from AlexBrochu
private void delete_cam_btn_Click(object sender, RoutedEventArgs e)
{
if (selectedCam == null || cameras == null)
{
delete_cam_btn.IsEnabled = false;
return;
}
// Remove Camera login info
int index = cameras.FindIndex(element => element.CameraName.Equals(selectedCam.CameraName));
if (index >= 0)
{
cameras.RemoveAt(index);
}
string json = JsonConvert.SerializeObject(cameras);
if (!File.Exists(path_to_connexion_file))
{
File.CreateText(path_to_connexion_file).Close();
}
using (StreamWriter file = new StreamWriter(path_to_connexion_file, false))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, cameras);
}
LoadConnexion();
delete_cam_btn.IsEnabled = false;
}
19
Source : PluginInstaller.cs
with GNU General Public License v3.0
from alexdillon
with GNU General Public License v3.0
from alexdillon
private void SavePluginSettings()
{
using (StreamWriter file = File.CreateText(this.PluginSettingsFile))
{
var serializer = new JsonSerializer()
{
Formatting = Formatting.Indented,
TypeNameHandling = TypeNameHandling.Auto,
};
serializer.Converters.Add(new Newtonsoft.Json.Converters.VersionConverter());
serializer.Serialize(file, this.PluginSettings);
}
}
19
Source : SettingsManager.cs
with GNU General Public License v3.0
from alexdillon
with GNU General Public License v3.0
from alexdillon
public void SaveSettings()
{
// serialize JSON directly to a file
using (StreamWriter file = File.CreateText(this.SettingsFile))
{
JsonSerializer serializer = new JsonSerializer()
{
Formatting = Formatting.Indented,
};
serializer.Serialize(file, this);
}
}
19
Source : StanfordNLPClassifier.cs
with MIT License
from allisterb
with MIT License
from allisterb
protected FileInfo CreatePropsFile(Dictionary<string, object> properties)
{
using (TextWriter tw = File.CreateText("clreplacedifier.prop"))
{
foreach(KeyValuePair<string, object> kv in properties)
{
tw.WriteLine("{0}={1}".F(kv.Key, kv.Value));
}
}
FileInfo file = new FileInfo("clreplacedifier.prop");
return file;
}
19
Source : FileSystemResultsWriter.cs
with Apache License 2.0
from allure-framework
with Apache License 2.0
from allure-framework
protected string Write(object allureObject, string fileSuffix)
{
var filePath = Path.Combine(outputDirectory, $"{Guid.NewGuid().ToString("N")}{fileSuffix}");
using (var fileStream = File.CreateText(filePath))
{
serializer.Serialize(fileStream, allureObject);
}
return filePath;
}
19
Source : AllureBindingInvoker.cs
with Apache License 2.0
from allure-framework
with Apache License 2.0
from allure-framework
private static void StartStep(StepInfo stepInfo, string containerId)
{
var stepResult = new StepResult
{
name = $"{stepInfo.StepDefinitionType} {stepInfo.Text}"
};
allure.StartStep(containerId, PluginHelper.NewId(), stepResult);
if (stepInfo.Table != null)
{
var csvFile = $"{Guid.NewGuid().ToString()}.csv";
using (var csv = new CsvWriter(File.CreateText(csvFile),CultureInfo.InvariantCulture))
{
foreach (var item in stepInfo.Table.Header) csv.WriteField(item);
csv.NextRecord();
foreach (var row in stepInfo.Table.Rows)
{
foreach (var item in row.Values) csv.WriteField(item);
csv.NextRecord();
}
}
allure.AddAttachment("table", "text/csv", csvFile);
}
}
19
Source : frmMain.cs
with GNU General Public License v3.0
from amakvana
with GNU General Public License v3.0
from amakvana
private async Task ProcessYuzu(string yuzuLocation)
{
ToggleControls(false);
// create temp directory for downloads
string tempDir = yuzuLocation + "\\TempUpdate";
if (!Directory.Exists(tempDir))
{
Directory.CreateDirectory(tempDir);
}
// get latest yuzu version & download
using (var wc = new WebClient())
{
// fetch latest Yuzu release
string latestYuzu = "https://github.com";
string repo = "https://github.com/yuzu-emu/yuzu-mainline/releases/latest";
string repoHtml = wc.DownloadString(repo);
string version = "";
Regex r = new Regex(@"(?:\/yuzu-emu\/yuzu-mainline\/releases\/download\/[^""]+)");
foreach (Match m in r.Matches(repoHtml))
{
string url = m.Value.Trim();
if (url.Contains(".zip") && !url.Contains("debugsymbols"))
{
latestYuzu += url;
version = url.Split('/')[5].Trim().Remove(0, 11);
}
}
// download it
wc.DownloadFileCompleted += (s, e) =>
{
// unpack
SetProgressLabelStatus("Unpacking Yuzu ...");
ZipFile.ExtractToDirectory(tempDir + "\\yuzu.zip", yuzuLocation);
// update version number
using (StreamWriter sw = File.CreateText(yuzuLocation + "\\version"))
{
sw.Write(version);
}
// cleanup
DirectoryUtilities.Copy(yuzuLocation + "\\yuzu-windows-msvc", yuzuLocation, true);
Directory.Delete(yuzuLocation + "\\yuzu-windows-msvc", true);
Directory.Delete(tempDir, true);
Directory.EnumerateFiles(yuzuLocation, "*.xz").ToList().ForEach(item => File.Delete(item));
SetProgressLabelStatus("Done!");
ToggleControls(true);
pbarProgress.Value = 0;
};
wc.DownloadProgressChanged += Wc_DownloadProgressChanged;
SetProgressLabelStatus("Downloading Yuzu ...");
await wc.DownloadFileTaskAsync(new Uri(latestYuzu), tempDir + "\\yuzu.zip");
}
}
19
Source : FilesHelper.cs
with MIT License
from Amine-Smahi
with MIT License
from Amine-Smahi
public static void OpenOrCreateFile(string filePath)
{
File.CreateText(filePath);
}
19
Source : PendingChangeHandler.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
public bool CreatePatch(IEnumerable<PendingChange> changes, PendingChangeCreatePatchArgs args)
{
using (PendingCommitState state = new PendingCommitState(Context, changes))
{
if (!PreCommit_VerifySingleRoot(state)) // Verify single root 'first'
return false;
if (!PreCommit_SaveDirty(state))
return false;
if (args.AddUnversionedFiles)
{
if (!PreCommit_AddNewFiles(state))
return false;
if (!PreCommit_HandleMissingFiles(state))
return false;
}
state.FlushState();
if (!PreCommit_AddNeededParents(state))
return false;
if (!PreCommit_VerifySingleRoot(state)) // Verify single root 'again'
return false;
}
string relativeToPath = args.RelativeToPath;
string relativeToPathP = relativeToPath.EndsWith("\\") ? relativeToPath : (relativeToPath + "\\");
string fileName = args.FileName;
SvnRevisionRange revRange = new SvnRevisionRange(SvnRevision.Base, SvnRevision.Working);
SvnDiffArgs a = new SvnDiffArgs();
a.IgnoreAncestry = true;
a.NoDeleted = false;
a.Depth = SvnDepth.Empty;
using (MemoryStream stream = new MemoryStream())
{
GetService<IProgressRunner>().RunModal(PccStrings.Diffreplacedle,
delegate(object sender, ProgressWorkerArgs e)
{
foreach (PendingChange pc in changes)
{
SvnItem item = pc.SvnItem;
SvnWorkingCopy wc;
if (!string.IsNullOrEmpty(relativeToPath)
&& item.FullPath.StartsWith(relativeToPathP, StringComparison.OrdinalIgnoreCase))
a.RelativeToPath = relativeToPath;
else if ((wc = item.WorkingCopy) != null)
a.RelativeToPath = wc.FullPath;
else
a.RelativeToPath = null;
e.Client.Diff(item.FullPath, revRange, a, stream);
}
stream.Flush();
stream.Position = 0;
});
using (StreamReader sr = new StreamReader(stream))
{
string line;
// Parse to lines to resolve EOL issues
using (StreamWriter sw = File.CreateText(fileName))
{
while (null != (line = sr.ReadLine()))
sw.WriteLine(line);
}
}
}
return true;
}
19
Source : ProjectItemsEventSinkTest.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
[Test]
public void TesreplacedemAutoAdded()
{
ContextBase ctx = this.CreateContextAndLoad();
string path = Path.Combine( this.WcPath, "File.cs" );
File.CreateText( path ).Close();
ctx.DTE.Solution.Projects.Item( 1
).Projecreplacedems.AddFromFile( path );
ctx.CheckForException();
// verify that the file is correctly added.
replacedert.AreEqual( StatusKind.Added,
ctx.Client.SingleStatus(path).TextStatus );
}
19
Source : ProjectItemsEventSinkTest.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
[Test]
public void TestAutoAddIgnoredFile()
{
ContextBase ctx = this.CreateContextAndLoad();
string path = Path.Combine( this.WcPath, "File.ignored" );
File.CreateText( path ).Close();
ctx.Client.PropSet( new Property( "svn:ignore", "File.ignored" ),
this.WcPath, Recurse.Full );
int youngest;
ctx.Client.Status( out youngest, path, Revision.Unspecified,
new StatusCallback( this.IgnoredFileCallback ), false, true, false, true );
replacedert.AreEqual( StatusKind.Ignored,
this.ignoredFileStatus.TextStatus );
ctx.DTE.Solution.Projects.Item( 1
).Projecreplacedems.AddFromFile( path );
ctx.CheckForException();
// verify that the file is *NOT* added.
ctx.Client.Status( out youngest, path, Revision.Unspecified,
new StatusCallback( this.IgnoredFileCallback ), false, true, false, true );
replacedert.AreEqual( StatusKind.Ignored,
this.ignoredFileStatus.TextStatus );
}
19
Source : ProjectItemsEventSinkTest.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
[Test]
public void TesreplacedemAutoAddedTwice()
{
ContextBase ctx = this.CreateContextAndLoad();
string path = Path.Combine( this.WcPath, "File.cs" );
File.CreateText( path ).Close();
SvnItem item = ctx.StatusCache[path];
ctx.Client.Add( path, Recurse.None );
// unless the sink refreshes the item, it will be
// seen as unversioned and it will try to add it.
ctx.DTE.Solution.Projects.Item( 1
).Projecreplacedems.AddFromFile( path );
// verify that no exception was thrown
ctx.CheckForException();
// verify that the file is correctly added.
replacedert.AreEqual( StatusKind.Added,
ctx.Client.SingleStatus(path).TextStatus );
}
19
Source : ProjectItemsEventSinkTest.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
[Test]
public void TestNonVersionedMiscellaneousFileAdded()
{
ContextBase ctx = this.CreateContextAndLoad();
string dir = Path.Combine( this.WcPath, "Unversioned" );
Directory.CreateDirectory(dir);
string file = Path.Combine( dir, "unversioned.txt" );
File.CreateText( file ).Close();
ctx.DTE.ExecuteCommand( "File.OpenFile", file );
ctx.CheckForException();
replacedert.AreEqual( Status.None,
ctx.Client.SingleStatus(file) );
}
19
Source : SvnItemTest.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
[Test]
public void TestIsVersionable()
{
// normal
SvnItem item1 = this.Gereplacedem();
replacedert.IsTrue( item1.IsVersionable );
// missing
File.Delete( item1.Path );
item1.Refresh( this.Client );
replacedert.IsTrue( item1.IsVersionable );
// revert it so we can play some more with it
this.Client.Revert( new string[]{ item1.Path }, Recurse.None );
// modified
using( StreamWriter writer = new StreamWriter(item1.Path) )
writer.WriteLine( "Foo" );
item1.Refresh( this.Client );
replacedert.IsTrue( item1.IsVersionable );
// added
string addedFilePath = Path.Combine( this.WcPath, "added.txt" );
File.CreateText(addedFilePath).Close();
this.Client.Add( addedFilePath, Recurse.Full );
Status addedFileStatus = this.Client.SingleStatus( addedFilePath );
SvnItem addedItem = new SvnItem( addedFilePath, addedFileStatus );
replacedert.IsTrue( addedItem.IsVersionable );
// conflicted
string otherWc = this.GetTempFile();
Zip.ExtractZipResource( otherWc, this.GetType(), this.WC_FILE );
try
{
using( StreamWriter w2 = new StreamWriter( Path.Combine(otherWc, "Form1.cs") ) )
w2.WriteLine( "Something else" );
this.Client.Commit( new string[]{ otherWc }, Recurse.Full );
}
finally
{
Utils.PathUtils.RecursiveDelete( otherWc );
}
this.Client.Update( this.WcPath, Revision.Head, Recurse.Full );
item1.Refresh( this.Client );
replacedert.AreEqual( StatusKind.Conflicted, item1.Status.TextStatus );
replacedert.IsTrue( item1.IsVersionable );
// deleted
this.Client.Resolved( item1.Path, Recurse.None );
this.Client.Revert( new string[]{item1.Path}, Recurse.None );
this.Client.Delete( new string[]{ item1.Path }, true );
item1.Refresh( this.Client );
replacedert.AreEqual( StatusKind.Deleted, item1.Status.TextStatus );
replacedert.IsTrue( item1.IsVersionable );
// unversioned
string unversionedFile = Path.Combine( this.WcPath, "nope.txt" );
File.CreateText(unversionedFile).Close();
SvnItem unversioned = new SvnItem(unversionedFile, this.Client.SingleStatus(unversionedFile));
replacedert.AreEqual( StatusKind.Unversioned, unversioned.Status.TextStatus );
replacedert.IsTrue( unversioned.IsVersionable );
// none
string nonePath = Path.GetTempFileName();
SvnItem none = new SvnItem(nonePath, this.Client.SingleStatus(nonePath));
replacedert.AreEqual( StatusKind.None, none.Status.TextStatus );
replacedert.IsFalse( none.IsVersionable );
// subdir of wc
string newFolder = Path.Combine( this.WcPath, "NewFolder" );
Directory.CreateDirectory( newFolder );
SvnItem folder = this.Gereplacedem( newFolder );
replacedert.IsTrue( folder.IsVersionable );
// subdir of unversioned folder
string anotherFolder = Path.Combine( newFolder, "AnotherFolder" );
Directory.CreateDirectory( anotherFolder );
SvnItem folder2 = this.Gereplacedem( anotherFolder );
replacedert.IsFalse( folder2.IsVersionable );
// file in unversioned folder
string subFilePath = Path.Combine( newFolder, "NewFile.txt" );
File.CreateText( subFilePath );
SvnItem subFile = this.Gereplacedem( subFilePath );
replacedert.IsFalse( subFile.IsVersionable );
}
19
Source : ProjectItemsEventSinkTest.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
[Ignore("No idea how to programmatically add an URI")]
[Test]
public void TestAddFileUri()
{
ContextBase ctx = this.CreateContextAndLoad();
string path = Path.Combine( this.WcPath, "File.cs" );
File.CreateText( path ).Close();
string uri = "file:///" + path.Replace( "\\", "/" );
ctx.DTE.Solution.Projects.Item( 1
).Projecreplacedems.AddFromFile( uri );
ctx.CheckForException();
replacedert.AreEqual( StatusKind.Added,
ctx.Client.SingleStatus(path).TextStatus );
}
19
Source : SvnItemTest.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
[Test]
public void TestIsVersioned()
{
// normal
SvnItem item1 = this.Gereplacedem();
replacedert.IsTrue( item1.IsVersioned );
// missing
File.Delete( item1.Path );
item1.Refresh( this.Client );
replacedert.IsFalse( item1.IsVersioned );
// revert it so we can play some more with it
this.Client.Revert( new string[]{ item1.Path }, Recurse.None );
// modified
using( StreamWriter writer = new StreamWriter(item1.Path) )
writer.WriteLine( "Foo" );
item1.Refresh( this.Client );
replacedert.IsTrue( item1.IsVersioned );
// added
string addedFilePath = Path.Combine( this.WcPath, "added.txt" );
File.CreateText(addedFilePath).Close();
this.Client.Add( addedFilePath, Recurse.Full );
Status addedFileStatus = this.Client.SingleStatus( addedFilePath );
SvnItem addedItem = new SvnItem( addedFilePath, addedFileStatus );
replacedert.IsTrue( addedItem.IsVersioned );
// conflicted
string otherWc = this.GetTempFile();
Zip.ExtractZipResource( otherWc, this.GetType(), this.WC_FILE );
try
{
using( StreamWriter w2 = new StreamWriter( Path.Combine(otherWc, "Form1.cs") ) )
w2.WriteLine( "Something else" );
this.Client.Commit( new string[]{ otherWc }, Recurse.Full );
}
finally
{
Utils.PathUtils.RecursiveDelete( otherWc );
}
this.Client.Update( this.WcPath, Revision.Head, Recurse.Full );
item1.Refresh( this.Client );
replacedert.AreEqual( StatusKind.Conflicted, item1.Status.TextStatus );
replacedert.IsTrue( item1.IsVersioned );
// deleted
this.Client.Resolved( item1.Path, Recurse.None );
this.Client.Revert( new string[]{item1.Path}, Recurse.None );
this.Client.Delete( new string[]{ item1.Path }, true );
item1.Refresh( this.Client );
replacedert.AreEqual( StatusKind.Deleted, item1.Status.TextStatus );
replacedert.IsTrue( item1.IsVersioned );
// unversioned
string unversionedFile = Path.Combine( this.WcPath, "nope.txt" );
File.CreateText(unversionedFile).Close();
SvnItem unversioned = new SvnItem(unversionedFile, this.Client.SingleStatus(unversionedFile));
replacedert.AreEqual( StatusKind.Unversioned, unversioned.Status.TextStatus );
replacedert.IsFalse( unversioned.IsVersioned );
// none
string nonePath = Path.GetTempFileName();
SvnItem none = new SvnItem(nonePath, this.Client.SingleStatus(nonePath));
replacedert.AreEqual( StatusKind.None, none.Status.TextStatus );
replacedert.IsFalse( none.IsVersioned );
}
19
Source : SvnItemTest.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
[Test]
public void TestIsModified()
{
// normal
SvnItem item1 = this.Gereplacedem();
replacedert.IsFalse( item1.IsModified );
// missing
File.Delete(item1.Path);
item1.Refresh(this.Client);
replacedert.IsFalse(item1.IsModified);
this.Client.Revert(new string[]{item1.Path}, Recurse.Full);
// modified
using( StreamWriter writer = new StreamWriter(item1.Path) )
writer.WriteLine( "Foo" );
item1.Refresh( this.Client );
replacedert.IsTrue( item1.IsModified );
// added
string addedFilePath = Path.Combine( this.WcPath, "added.txt" );
File.CreateText(addedFilePath).Close();
this.Client.Add( addedFilePath, Recurse.Full );
Status addedFileStatus = this.Client.SingleStatus( addedFilePath );
SvnItem addedItem = new SvnItem( addedFilePath, addedFileStatus );
replacedert.IsTrue( addedItem.IsModified );
// conflicted
string otherWc = this.GetTempFile();
Zip.ExtractZipResource( otherWc, this.GetType(), this.WC_FILE );
try
{
using( StreamWriter w2 = new StreamWriter( Path.Combine(otherWc, "Form1.cs") ) )
w2.WriteLine( "Something else" );
this.Client.Commit( new string[]{ otherWc }, Recurse.Full );
}
finally
{
Utils.PathUtils.RecursiveDelete( otherWc );
}
this.Client.Update( this.WcPath, Revision.Head, Recurse.Full );
item1.Refresh( this.Client );
replacedert.AreEqual( StatusKind.Conflicted, item1.Status.TextStatus );
replacedert.IsTrue( item1.IsModified );
// deleted
this.Client.Resolved( item1.Path, Recurse.None );
this.Client.Revert( new string[]{item1.Path}, Recurse.None );
this.Client.Delete( new string[]{ item1.Path }, true );
item1.Refresh( this.Client );
replacedert.AreEqual( StatusKind.Deleted, item1.Status.TextStatus );
replacedert.IsTrue( item1.IsModified );
// unversioned
string unversionedFile = Path.Combine( this.WcPath, "nope.txt" );
File.CreateText(unversionedFile).Close();
SvnItem unversioned = new SvnItem(unversionedFile, this.Client.SingleStatus(unversionedFile));
replacedert.AreEqual( StatusKind.Unversioned, unversioned.Status.TextStatus );
replacedert.IsFalse( unversioned.IsModified );
// none
string nonePath = Path.GetTempFileName();
SvnItem none = new SvnItem(nonePath, this.Client.SingleStatus(nonePath));
replacedert.AreEqual( StatusKind.None, none.Status.TextStatus );
replacedert.IsFalse( none.IsModified );
}
19
Source : TestBase.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
protected string CreateTextFile( string name )
{
string path = Path.Combine( this.WcPath, name );
using ( StreamWriter writer = File.CreateText( path ) )
writer.Write( "Hello world" );
return path;
}
19
Source : FileIconMapperTest.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
[Test]
public void TestExistingFileType()
{
var statusCache = new Mock<ISvnStatusCache>();
string tempFile = Path.GetTempFileName();
string exeTempFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".exe");
using (File.CreateText(exeTempFile))
{ }
try
{
var item = new SvnItem(statusCache.Object, tempFile, NoSccStatus.Unknown, SharpSvn.SvnNodeKind.File);
replacedert.That(mapper.GetFileType(item), Is.EqualTo("TMP File"));
item = new SvnItem(statusCache.Object, exeTempFile, NoSccStatus.Unknown, SharpSvn.SvnNodeKind.File);
replacedert.That(mapper.GetFileType(item), Is.EqualTo("Application"));
item = new SvnItem(statusCache.Object, "C:\\", NoSccStatus.Unknown, SharpSvn.SvnNodeKind.Directory);
replacedert.That(mapper.GetFileType(item), Is.EqualTo("Local Disk"));
}
finally
{
File.Delete(tempFile);
File.Delete(exeTempFile);
}
}
19
Source : OptionsService.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
private void WriteOptions()
{
if (_options != null)
{
using (StreamWriter file = File.CreateText(_optionsFilePath))
{
var serializer = new JsonSerializer { Formatting = Formatting.Indented };
serializer.Serialize(file, _options);
}
}
}
19
Source : OptionsService.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
private void WriteOptions(Options? options)
{
if (options != null && _optionsFilePath != null)
{
using (var file = File.CreateText(_optionsFilePath))
{
var serializer = new JsonSerializer { Formatting = Formatting.Indented };
serializer.Serialize(file, options);
_originalOptionsSignature = GetOptionsSignature(options);
}
}
}
19
Source : OptionsService.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
private void WriteOptions()
{
if (_options != null && _optionsFilePath != null)
{
using var file = File.CreateText(_optionsFilePath);
var serializer = new JsonSerializer { Formatting = Formatting.Indented };
serializer.Serialize(file, _options);
_originalOptionsSignature = GetOptionsSignature(_options);
}
}
19
Source : OptionsService.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
private void WriteOptions(Options? options)
{
if (options != null && _optionsFilePath != null)
{
using var file = File.CreateText(_optionsFilePath);
var serializer = new JsonSerializer { Formatting = Formatting.Indented };
serializer.Serialize(file, options);
_originalOptionsSignature = GetOptionsSignature(options);
}
}
19
Source : OptionsService.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
private void WriteOptions()
{
if (string.IsNullOrEmpty(_optionsFilePath))
{
return;
}
using var file = File.CreateText(_optionsFilePath);
var originalGenre = Options.Genre;
if (originalGenre != null && originalGenre.Trim() == Properties.Resources.SPEECH)
{
// denotes default for the language.
Options.Genre = null;
}
var serializer = new JsonSerializer();
serializer.Serialize(file, Options);
Options.Genre = originalGenre;
_originalOptionsSignature = GetOptionsSignature(Options);
}
19
Source : OptionsService.cs
with MIT License
from AntonyCorbett
with MIT License
from AntonyCorbett
private void WriteOptions()
{
if (_options != null)
{
using (var file = File.CreateText(_optionsFilePath))
{
var serializer = new JsonSerializer { Formatting = Formatting.Indented };
serializer.Serialize(file, _options);
_originalOptionsSignature = GetOptionsSignature(_options);
}
}
}
19
Source : SmtpPickupDirAppender.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
protected override void SendBuffer(LoggingEvent[] events)
{
// Note: this code already owns the monitor for this
// appender. This frees us from needing to synchronize again.
try
{
string filePath = null;
StreamWriter writer = null;
// Impersonate to open the file
using(SecurityContext.Impersonate(this))
{
filePath = Path.Combine(m_pickupDir, SystemInfo.NewGuid().ToString("N") + m_fileExtension);
writer = File.CreateText(filePath);
}
if (writer == null)
{
ErrorHandler.Error("Failed to create output file for writing ["+filePath+"]", null, ErrorCode.FileOpenFailure);
}
else
{
using(writer)
{
writer.WriteLine("To: " + m_to);
writer.WriteLine("From: " + m_from);
writer.WriteLine("Subject: " + m_subject);
writer.WriteLine("Date: " + DateTime.UtcNow.ToString("r"));
writer.WriteLine("");
string t = Layout.Header;
if (t != null)
{
writer.Write(t);
}
for(int i = 0; i < events.Length; i++)
{
// Render the event and append the text to the buffer
RenderLoggingEvent(writer, events[i]);
}
t = Layout.Footer;
if (t != null)
{
writer.Write(t);
}
writer.WriteLine("");
writer.WriteLine(".");
}
}
}
catch(Exception e)
{
ErrorHandler.Error("Error occurred while sending e-mail notification.", e);
}
}
See More Examples