Here are the examples of the csharp api System.IO.File.AppendAllText(string, string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
623 Examples
19
View Source File : Form1.cs
License : Apache License 2.0
Project Creator : 1694439208
License : Apache License 2.0
Project Creator : 1694439208
private void button5_Click(object sender, EventArgs e)
{
byte[] jmp_inst =
{
233,0,0,0,0,//JMP Address
};
int Method = NativeAPI.GetMethodPTR(typeof(WeChetHook), "Callback");
textBox3.Text = (3212659 + int.Parse(label1.Text)).ToString();
List<byte> byteSource = new List<byte>();
byteSource.AddRange(new byte[] { 199, 134, 236, 2, 0, 0 });//mov dword [esi+0x000002EC],
byteSource.AddRange(BitConverter.GetBytes(int.Parse(textBox3.Text) + 5));//0x00000000 把hook的后五个字节地址压进寄存器
byteSource.AddRange(jmp_inst);//让他跳到跳板函数
//这部分根据实际情况填写
byteSource.Add(185);//补充替换的汇编指令
byteSource.AddRange(BitConverter.GetBytes(int.Parse(label1.Text) + 19255272));//补充替换的汇编指令地址
//开始hook
Inline_Hook.InlineHook(int.Parse(textBox3.Text),5, byteSource.ToArray(), getInt(Method),11+10,"接收消息",(obj) =>{
StringBuilder sb = new StringBuilder();
sb.Append("接收消息:");
int a = 0x68;
//System.Windows.Forms.MessageBox.Show("esp:"+a.ToString());
try
{
if (obj.ESP == 0)
return;
int MsgPtr = NativeAPI.ReadMemoryValue(obj.ESP);
if (MsgPtr == 0)
return;
MsgPtr = NativeAPI.ReadMemoryValue(MsgPtr);
if (MsgPtr == 0)
return;
MsgPtr = NativeAPI.ReadMemoryValue(MsgPtr + 0x68);
if (MsgPtr == 0)
return;
int len = NativeAPI.lstrlenW(MsgPtr);
if (len == 0)
return;
sb.Append(NativeAPI.ReadMemoryStrValue(MsgPtr, len*2+2));
sb.Append("\r\n");
listBox1.Items.Add(sb.ToString());
}
catch (Exception es)
{
File.AppendAllText("error.txt", es.Message);
}
});
}
19
View Source File : Logger.cs
License : GNU General Public License v3.0
Project Creator : 9vult
License : GNU General Public License v3.0
Project Creator : 9vult
public static void Log(string message)
{
File.AppendAllText(logFile, "[Log] " + GetTime() + " " + message + "\n");
}
19
View Source File : Logger.cs
License : GNU General Public License v3.0
Project Creator : 9vult
License : GNU General Public License v3.0
Project Creator : 9vult
public static void Error(string message)
{
File.AppendAllText(logFile, "[Error] " + GetTime() + " " + message + "\n");
}
19
View Source File : Logger.cs
License : GNU General Public License v3.0
Project Creator : 9vult
License : GNU General Public License v3.0
Project Creator : 9vult
public static void Warn(string message)
{
File.AppendAllText(logFile, "[Warn] " + GetTime() + " " + message + "\n");
}
19
View Source File : Log.cs
License : MIT License
Project Creator : acandylevey
License : MIT License
Project Creator : acandylevey
internal static void LogMessage(string msg)
{
if (!Active)
return;
try
{
File.AppendAllText(MessageLogLocation, msg + Environment.NewLine);
}
catch (IOException)
{
Console.WriteLine("Could Not Log To File");
//Supress Exception
}
}
19
View Source File : RecordCast.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public void Flush()
{
File.AppendAllText(Filename, Buffer.ToString());
Buffer.Clear();
}
19
View Source File : Program_DbUpdates.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : 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
View Source File : CustomTextReporter.cs
License : Microsoft Public License
Project Creator : achimismaili
License : Microsoft Public License
Project Creator : achimismaili
public void Process(Story story)
{
// use this report only for tic tac toe stories
if (story.Metadata == null || !story.Metadata.Type.Name.Contains("TicTacToe"))
return;
var scenario = story.Scenarios.First();
var scenarioReport = new StringBuilder();
scenarioReport.AppendLine(string.Format(" SCENARIO: {0} ", scenario.replacedle));
if (scenario.Result != Result.Preplaceded && scenario.Steps.Any(s => s.Exception != null))
{
scenarioReport.Append(string.Format(" {0} : ", scenario.Result));
scenarioReport.AppendLine(scenario.Steps.First(s => s.Result == scenario.Result).Exception.Message);
}
scenarioReport.AppendLine();
foreach (var step in scenario.Steps)
scenarioReport.AppendLine(string.Format(" [{1}] {0}", step.replacedle, step.Result));
scenarioReport.AppendLine("--------------------------------------------------------------------------------");
scenarioReport.AppendLine();
File.AppendAllText(Path, scenarioReport.ToString());
}
19
View Source File : Logging.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat
public static void LogMessage(string message)
{
string toLog = message + Environment.NewLine;
CreateLogFileIfNotExists(OutputFilename);
File.AppendAllText(OutputFilename, GetTimestamp() + toLog);
LogTextbox(toLog);
}
19
View Source File : Logging.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat
public static void LogException(Exception ex, string message)
{
string toLog = (ex == null) ? Environment.NewLine + "Application encountered an error" : ex.ToString();
if (!string.IsNullOrWhiteSpace(message))
toLog += ": " + message;
else
toLog += "!";
toLog += Environment.NewLine + Environment.NewLine;
CreateLogFileIfNotExists(OutputFilename);
File.AppendAllText(OutputFilename, GetTimestamp() + toLog);
LogTextbox(toLog);
}
19
View Source File : Serialization.Save.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat
public static void Append(GNFS gnfs, Relation relation)
{
if (relation != null && relation.IsSmooth && !relation.IsPersisted)
{
string filename = Path.Combine(gnfs.SaveLocations.SaveDirectory, $"{nameof(RelationContainer.SmoothRelations)}.json");
string json = JsonConvert.SerializeObject(relation, Formatting.Indented);
if (FileExists(gnfs))
{
json = json.Insert(0, ",");
}
File.AppendAllText(filename, json);
gnfs.CurrentRelationsProgress.SmoothRelationsCounter += 1;
relation.IsPersisted = true;
}
}
19
View Source File : Serialization.Save.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat
public static void Append(GNFS gnfs, Relation roughRelation)
{
if (roughRelation != null && !roughRelation.IsSmooth && !roughRelation.IsPersisted)
{
string filename = Path.Combine(gnfs.SaveLocations.SaveDirectory, $"{nameof(RelationContainer.RoughRelations)}.json");
string json = JsonConvert.SerializeObject(roughRelation, Formatting.Indented);
if (FileExists(gnfs))
{
json += ",";
}
File.AppendAllText(filename, json);
roughRelation.IsPersisted = true;
}
}
19
View Source File : Serialization.Save.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat
public static void AppendList(GNFS gnfs, List<Relation> roughRelations)
{
if (roughRelations != null && roughRelations.Any())
{
string filename = Path.Combine(gnfs.SaveLocations.SaveDirectory, $"{nameof(RelationContainer.RoughRelations)}.json");
string json = JsonConvert.SerializeObject(roughRelations, Formatting.Indented);
json = json.Replace("[", "").Replace("]", ",");
File.AppendAllText(filename, json);
roughRelations.ForEach(rel => rel.IsPersisted = true);
}
}
19
View Source File : Log.cs
License : GNU General Public License v3.0
Project Creator : Aeroblast
License : GNU General Public License v3.0
Project Creator : Aeroblast
public static void Append(string path)
{
File.AppendAllText(path, "\r\n\r\n" + t);
}
19
View Source File : FileIOControl.cs
License : MIT License
Project Creator : akihiro0105
License : MIT License
Project Creator : akihiro0105
public static IEnumerator WriteAppendTextFile(string name, string data, Action action = null)
{
#if WINDOWS_UWP
var task = Task.Run(() =>File.AppendAllText(name, data));
yield return new WaitWhile(() => task.IsCompleted == false);
#else
var thread = new Thread(() => File.AppendAllText(name, data));
thread.Start();
yield return new WaitWhile(() => thread.IsAlive == true);
#endif
yield return null;
if (action != null) action.Invoke();
}
19
View Source File : CmdOutput.cs
License : MIT License
Project Creator : AkiniKites
License : MIT License
Project Creator : AkiniKites
public static void WriteLine(string text)
{
text ??= "";
File.AppendAllText(CommandOutputFile, text);
}
19
View Source File : Errors.cs
License : MIT License
Project Creator : AkiniKites
License : MIT License
Project Creator : AkiniKites
public static void WriteError(object exception)
{
try
{
File.AppendAllText("error.log", $"{exception}\r\n\r\n");
}
catch { }
}
19
View Source File : Errors.cs
License : MIT License
Project Creator : AkiniKites
License : MIT License
Project Creator : AkiniKites
public static void WriteError(Exception exception)
{
try
{
File.AppendAllText("error.log", $"{exception}\r\n\r\n");
}
catch { }
}
19
View Source File : SimpleFileLoggerActor.cs
License : Apache License 2.0
Project Creator : akkadotnet
License : Apache License 2.0
Project Creator : akkadotnet
private void Log(LogLevel level, string str)
{
var fullPath = Path.GetFullPath(LogPath);
Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
File.AppendAllText(fullPath, $"{str}\r\n");
}
19
View Source File : FileLogger.cs
License : MIT License
Project Creator : akpaevj
License : MIT License
Project Creator : akpaevj
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception,
Func<TState, Exception, string> formatter)
{
var levelName = Enum.GetName(typeof(LogLevel), logLevel);
var message = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} | {levelName} | {_categoryName}[{eventId.Id}]\n\t{ formatter(state, exception)}";
lock (Locker)
{
File.AppendAllText(_path, message + Environment.NewLine);
}
}
19
View Source File : MainProgram.cs
License : MIT License
Project Creator : AlbertMN
License : MIT License
Project Creator : AlbertMN
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs args) {
Exception e = (Exception)args.ExceptionObject;
string errorLogLoc = Path.Combine(dataFolderLocation, "error_log.txt");
string subKey = @"SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion";
RegistryKey thekey = Registry.LocalMachine;
RegistryKey skey = thekey.OpenSubKey(subKey);
string windowsVersionName = skey.GetValue("ProductName").ToString();
string rawWindowsVersion = Environment.OSVersion.ToString();
int totalExecutions = 0;
foreach (int action in Properties.Settings.Default.TotalActionsExecuted) {
totalExecutions += action;
}
if (File.Exists(errorLogLoc))
try {
File.Delete(errorLogLoc);
} catch {
DoDebug("Failed to delete error log");
}
if (!File.Exists(errorLogLoc)) {
try {
using (var tw = new StreamWriter(errorLogLoc, true)) {
tw.WriteLine("OS;");
tw.WriteLine("- " + windowsVersionName);
tw.WriteLine("- " + rawWindowsVersion);
tw.WriteLine();
tw.WriteLine("ACC info;");
tw.WriteLine("- Version; " + softwareVersion + ", " + releaseDate);
tw.WriteLine("- UID; " + Properties.Settings.Default.UID);
tw.WriteLine("- Running from; " + currentLocationFull);
tw.WriteLine("- Start with Windows; " + (ACCStartsWithWindows() ? "[Yes]" : "[No]"));
tw.WriteLine("- Check for updates; " + (Properties.Settings.Default.CheckForUpdates ? "[Yes]" : "[No]"));
tw.WriteLine("- In beta program; " + (Properties.Settings.Default.BetaProgram ? "[Yes]" : "[No]"));
tw.WriteLine("- Has completed setup guide; " + (Properties.Settings.Default.HasCompletedTutorial ? "[Yes]" : "[No]"));
tw.WriteLine("- Check path; " + CheckPath());
tw.WriteLine("- Check extension; " + Properties.Settings.Default.ActionFileExtension);
tw.WriteLine("- Actions executed; " + totalExecutions);
tw.WriteLine("- replacedistant type; " + "[Google replacedistant: " + Properties.Settings.Default.replacedistantType[0] + "] [Alexa: " + Properties.Settings.Default.replacedistantType[1] + "] [Unknown: " + Properties.Settings.Default.replacedistantType[1] + "]");
tw.WriteLine();
tw.WriteLine(e);
tw.Close();
}
} catch {
//Caught exception when trying to log exception... *sigh*
}
}
File.AppendAllText(errorLogLoc, DateTime.Now.ToString() + ": " + e + Environment.NewLine);
if (debug) {
Console.WriteLine(e);
}
MessageBox.Show("A critical error occurred. The developer has been notified and will resolve this issue ASAP! Try and start ACC again, and avoid whatever just made it crash (for now) :)", "ACC | Error");
}
19
View Source File : FileProvider.cs
License : MIT License
Project Creator : alfa-laboratory
License : MIT License
Project Creator : alfa-laboratory
public bool AppendAllText(string filename, string path, string content)
{
try
{
var fullPath = Path.Combine(path, filename);
System.IO.File.AppendAllText(fullPath, content);
if (!Exist(fullPath)) return false;
Log.Logger().LogInformation($"The file \"{filename}\" in the \"{path}\" directory has been created");
return true;
}
catch (FileNotFoundException e)
{
Log.Logger().LogWarning($"The file \"{filename}\" in the \"{path}\" directory was not created due to \"{e.Message}\"");
return false;
}
}
19
View Source File : SYS_MASTER.cs
License : GNU General Public License v3.0
Project Creator : Alpaca-Studio
License : GNU General Public License v3.0
Project Creator : Alpaca-Studio
public static void SaveLog(){
//logData.Clear();
string path = Application.persistentDataPath + "/" + Application.productName + "/Logs/SysLog.txt";
foreach(string message in logData){
File.AppendAllText(path, string.Format("{0}{1}", message.ToString(), System.Environment.NewLine));
}
lastPath = path;
Debug.Log("SysLog.txt saved to default location: " + (Application.persistentDataPath + "/" + Application.productName + "/Logs/SysLog.txt"));
}
19
View Source File : SYS_MASTER.cs
License : GNU General Public License v3.0
Project Creator : Alpaca-Studio
License : GNU General Public License v3.0
Project Creator : Alpaca-Studio
public static void SaveLog(string path){
//logData.Clear();
foreach(string message in logData){
File.AppendAllText(path, string.Format("{0}{1}", message.ToString(), System.Environment.NewLine));
}
lastPath = path;
Debug.Log("SysLog.txt saved to location: " + path);
}
19
View Source File : SYS_MASTER.cs
License : GNU General Public License v3.0
Project Creator : Alpaca-Studio
License : GNU General Public License v3.0
Project Creator : Alpaca-Studio
public static void SaveLog(string path, bool openDir){
//logData.Clear();
foreach(string message in logData){
File.AppendAllText(path, string.Format("{0}{1}", message.ToString(), System.Environment.NewLine));
}
if(openDir){System.Diagnostics.Process.Start(path);}
lastPath = path;
Debug.Log("SysLog.txt saved to location: " + path);
Debug.Log("Opening Directory: " + path);
}
19
View Source File : SYS_MASTER.cs
License : GNU General Public License v3.0
Project Creator : Alpaca-Studio
License : GNU General Public License v3.0
Project Creator : Alpaca-Studio
public static void SaveDataToFile(string path, string[] data){
if(!File.Exists(path)){
File.Create(path).Dispose();
foreach(string d in data){
File.AppendAllText(path, string.Format("{0}{1}", d.ToString(), System.Environment.NewLine));
}
} else {
File.Create(path).Dispose();
foreach(string d in data){
File.AppendAllText(path, string.Format("{0}{1}", d.ToString(), System.Environment.NewLine));
}
}
}
19
View Source File : SYS_MASTER.cs
License : GNU General Public License v3.0
Project Creator : Alpaca-Studio
License : GNU General Public License v3.0
Project Creator : Alpaca-Studio
public static void SaveDataToFile(string path, string[] data, bool clearOldFiles){
if(!File.Exists(path)){
File.Create(path).Dispose();
foreach(string d in data){
File.AppendAllText(path, string.Format("{0}{1}", d.ToString(), System.Environment.NewLine));
}
} else {
if(clearOldFiles){
File.Create(path).Dispose();
foreach(string d in data){
File.AppendAllText(path, string.Format("{0}{1}", d.ToString(), System.Environment.NewLine));
}
} else {
foreach(string d in data){
File.AppendAllText(path, string.Format("{0}{1}", d.ToString(), System.Environment.NewLine));
}
}
}
}
19
View Source File : SYS_MASTER.cs
License : GNU General Public License v3.0
Project Creator : Alpaca-Studio
License : GNU General Public License v3.0
Project Creator : Alpaca-Studio
public static void SaveFile(string path, string[] data, bool clearOldFiles){
if(!File.Exists(path)){
File.Create(path).Dispose();
foreach(string d in data){
File.AppendAllText(path, string.Format("{0}{1}", d.ToString(), System.Environment.NewLine));
}
} else {
if(clearOldFiles){
File.Create(path).Dispose();
foreach(string d in data){
File.AppendAllText(path, string.Format("{0}{1}", d.ToString(), System.Environment.NewLine));
}
} else {
foreach(string d in data){
File.AppendAllText(path, string.Format("{0}{1}", d.ToString(), System.Environment.NewLine));
}
}
}
}
19
View Source File : SYS_MASTER.cs
License : GNU General Public License v3.0
Project Creator : Alpaca-Studio
License : GNU General Public License v3.0
Project Creator : Alpaca-Studio
static void WriteDataToFile (bool openDir) {
foreach(string ab in sysInfo){
File.AppendAllText(temporaryPath, string.Format("{0} {1}", ab, System.Environment.NewLine));
i++;
}
if(i >= (sysInfo.ToArray().Length)){ i = 0; sysInfo.Clear(); }
if(openDir){System.Diagnostics.Process.Start(temporaryPath);} //Debug.Log("[Sys]: Opening File Location...");}
}
19
View Source File : SYS_MASTER.cs
License : GNU General Public License v3.0
Project Creator : Alpaca-Studio
License : GNU General Public License v3.0
Project Creator : Alpaca-Studio
public static void SaveFile(string path, string[] data){
if(!File.Exists(path)){
File.Create(path).Dispose();
foreach(string d in data){
File.AppendAllText(path, string.Format("{0}{1}", d.ToString(), System.Environment.NewLine));
}
} else {
File.Create(path).Dispose();
foreach(string d in data){
File.AppendAllText(path, string.Format("{0}{1}", d.ToString(), System.Environment.NewLine));
}
}
}
19
View Source File : ModLogger.cs
License : MIT License
Project Creator : amazingalek
License : MIT License
Project Creator : amazingalek
private static void LogInternal(string message) =>
File.AppendAllText(_logFileName, $"{DateTime.Now}: {message}{Environment.NewLine}");
19
View Source File : Logging.cs
License : MIT License
Project Creator : AmazingDM
License : MIT License
Project Creator : AmazingDM
private static void Write(string text, LogLevel logLevel)
{
lock (FileLock)
{
File.AppendAllText(LogFile, [email protected]"[{DateTime.Now}][{logLevel.ToString()}] {text}{Global.EOF}");
}
}
19
View Source File : NFController.cs
License : MIT License
Project Creator : AmazingDM
License : MIT License
Project Creator : AmazingDM
private void saveProcessProxyIPLog(string log)
{
try
{
string ProcessProxyIPLog_logPath = Path.Combine(Global.NetchDir, "logging\\ProcessProxyIP.log");
if (File.Exists(ProcessProxyIPLog_logPath))
File.Delete(ProcessProxyIPLog_logPath);
File.AppendAllText(ProcessProxyIPLog_logPath, log);
}
catch (Exception exception)
{
Logging.Warning("写入 代理IP 日志错误:\n" + exception.Message);
}
}
19
View Source File : Guard.cs
License : MIT License
Project Creator : AmazingDM
License : MIT License
Project Creator : AmazingDM
private void SaveBufferTimerEvent(object sender, EventArgs e)
{
try
{
if (_logPath != null && _logBuffer != null)
{
File.AppendAllText(_logPath, _logBuffer.ToString());
_logBuffer.Clear();
}
}
catch (Exception exception)
{
Logging.Warning($"写入 {Name} 日志错误:\n" + exception.Message);
}
}
19
View Source File : Program.cs
License : MIT License
Project Creator : amerkoleci
License : MIT License
Project Creator : amerkoleci
public static int Main(string[] args)
{
string outputPath = AppContext.BaseDirectory;
if (args.Length > 0)
{
outputPath = args[0];
}
if (!Path.IsPathRooted(outputPath))
{
outputPath = Path.Combine(AppContext.BaseDirectory, outputPath);
}
if (!Directory.Exists(outputPath))
{
Directory.CreateDirectory(outputPath);
}
string? headerFile = Path.Combine(AppContext.BaseDirectory, "vulkan", "vulkan.h");
var options = new CppParserOptions
{
ParseMacros = true,
Defines =
{
"VK_USE_PLATFORM_ANDROID_KHR",
"VK_USE_PLATFORM_IOS_MVK",
"VK_USE_PLATFORM_MACOS_MVK",
"VK_USE_PLATFORM_METAL_EXT",
"VK_USE_PLATFORM_VI_NN",
//"VK_USE_PLATFORM_WAYLAND_KHR",
//"VK_USE_PLATFORM_WIN32_KHR",
//"VK_USE_PLATFORM_SCREEN_QNX",
"VK_ENABLE_BETA_EXTENSIONS"
}
};
var compilation = CppParser.ParseFile(headerFile, options);
// Print diagnostic messages
if (compilation.HasErrors)
{
foreach (var message in compilation.Diagnostics.Messages)
{
if (message.Type == CppLogMessageType.Error)
{
var currentColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(message);
Console.ForegroundColor = currentColor;
}
}
return 0;
}
bool generateFuncFile = false;
if (generateFuncFile)
{
File.Delete("Vk.txt");
foreach (var func in compilation.Functions)
{
var signature = new System.Text.StringBuilder();
var argSignature = CsCodeGenerator.GetParameterSignature(func, true);
signature
.Append(func.ReturnType.GetDisplayName())
.Append(" ")
.Append(func.Name)
.Append("(")
.Append(argSignature)
.Append(")");
File.AppendAllText("Vk.txt", signature.ToString() + Environment.NewLine);
}
}
CsCodeGenerator.Generate(compilation, outputPath);
return 0;
}
19
View Source File : DesignerContextMenuAddIn.cs
License : GNU General Public License v3.0
Project Creator : anderson-joyle
License : GNU General Public License v3.0
Project Creator : anderson-joyle
public override void OnClick(AddinDesignerEventArgs e)
{
try
{
StringBuilder result;
INamedElement namedElement = e.SelectedElement as INamedElement;
if (namedElement is Tables.ITable)
{
result = this.GenerateFromTable(namedElement as Tables.ITable, true);
}
else if (namedElement is Tables.ITableExtension)
{
result = this.GenerateFromTableExtension(namedElement as Tables.ITableExtension, true);
}
else if (namedElement is Tables.IRelation)
{
result = this.GenerateFromTableRelations(e.SelectedElements.OfType<Tables.IRelation>());
var selectedRelations = e.SelectedElements.OfType<Tables.IRelation>();
if (selectedRelations.Any())
{
result = this.GenerateFromTableRelations(selectedRelations);
}
}
else if (namedElement is DataEnreplacedies.IDataEnreplacedyView)
{
result = this.GenerateFromDataEnreplacedy(namedElement as DataEnreplacedies.IDataEnreplacedyView, true);
}
else
{
throw new NotImplementedException($"Element {e.SelectedElement.ToString()} is not supported.");
}
if (result != null)
{
string message = string.Empty;
int counter = 0;
message += $"Counting for " + tableName;
message += "\n\n";
using (SqlConnection conn = new SqlConnection(BusinessDatabaseConnectionString))
{
var query = result.ToString();
query = query.Replace("\n", " ");
query = query.Replace("\r", " ");
query = query.Replace(" GO ", "");
conn.Open();
using (SqlCommand command = new SqlCommand(query, conn))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
if (reader.FieldCount == 1)
{
string counterLocStr = reader["COUNTER"].ToString();
counter += int.Parse(counterLocStr);
}
else
{
string dataAreaId = reader["DATAAREAID"].ToString();
string counterLocStr = reader["COUNTER"].ToString();
message += $"{dataAreaId.ToUpper()}: {int.Parse(counterLocStr)}";
counter += int.Parse(counterLocStr);
}
}
}
}
conn.Close();
}
message += "\n\n";
message += $"Total: {counter}";
message += "\n\n";
message += "================== USED QUERY ===================\n";
message += result.ToString();
message += "===============================================";
message += "\n\n";
message += "Do you want to open this query in MSSQL Management Studio?";
if (CoreUtility.PromptYesNo(message, "Counting records"))
{
// Save the SQL file and open it in SQL management studio.
string temporaryFileName = Path.GetTempFileName();
// Rename and move
var sqlFileName = temporaryFileName.Replace(".tmp", ".sql");
File.Move(temporaryFileName, sqlFileName);
// Store the script in the file
File.AppendAllText(sqlFileName, result.ToString());
//var dte = CoreUtility.ServiceProvider.GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
//dte.ExecuteCommand("File.OpenFile", sqlFileName);
Process sqlManagementStudio = new Process();
sqlManagementStudio.StartInfo.FileName = sqlFileName;
sqlManagementStudio.StartInfo.UseShellExecute = true;
sqlManagementStudio.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
sqlManagementStudio.Start();
}
}
}
catch (Exception ex)
{
CoreUtility.HandleExceptionWithErrorMessage(ex);
}
}
19
View Source File : Program.cs
License : MIT License
Project Creator : ANF-Studios
License : MIT License
Project Creator : ANF-Studios
public static void Main(string[] args)
{
Console.replacedle = AppDomain.CurrentDomain.FriendlyName;
string currentVersion = GetInstalledWinPathVersion();
if (currentVersion is null)
Environment.Exit(-1);
if (currentVersion == "0.2.0") // Backwards compatibility support.
executableDirectory = $"{Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)}\\WinPath\\temp\\download\\WinPath.exe";
if (int.Parse(currentVersion[2].ToString()) > 2)
{
if (args.Length < 1) // To prevent crashing if args is 0 in the next if-statement.
return;
if (args[0] != launchingFromWinPath)
return;
}
try
{
if (Environment.Is64BitOperatingSystem)
{
Directory.CreateDirectory(
//Environment.GetFolderPath(
// Environment.SpecialFolder.ProgramFiles
//)
"C:\\Program Files" + "\\WinPath"
);
File.Move(
executableDirectory,
//Environment.GetFolderPath(
// Environment.SpecialFolder.ProgramFiles
//)
"C:\\Program Files" + "\\WinPath\\WinPath.exe",
true
);
}
else
{
Directory.CreateDirectory(
//Environment.GetFolderPath(
// Environment.SpecialFolder.ProgramFilesX86
//)
"C:\\Program Files (x86)" + "\\WinPath"
);
File.Move(
executableDirectory,
//Environment.GetFolderPath(
// Environment.SpecialFolder.ProgramFilesX86
//)
"C:\\Program Files (x86)" + "\\WinPath\\WinPath.exe",
true
);
}
Console.WriteLine("WinPath is installed successfully!");
Environment.ExitCode = 0;
}
catch (Exception exception)
{
Console.WriteLine("Could not install WinPath: " + exception.Message);
//Console.ReadKey();
Directory.CreateDirectory(logDirectory.Replace("log.txt", string.Empty));
File.AppendAllText(
logDirectory,
DateTime.Today.ToLongDateString()
+ "\n"
+ errorMessage
+ exception.Message
+ "\n"
+ "Please report this to the developer."
+ "\n"
);
Console.WriteLine("Exception logged at " + logDirectory);
Environment.ExitCode = 1;
}
Environment.Exit(Environment.ExitCode);
}
19
View Source File : LogLock.cs
License : Apache License 2.0
Project Creator : anjoy8
License : Apache License 2.0
Project Creator : anjoy8
public static void OutSql2Log(string filename, string[] dataParas)
{
try
{
//设置读写锁为写入模式独占资源,其他写入请求需要等待本次写入结束之后才能继续写入
//注意:长时间持有读线程锁或写线程锁会使其他线程发生饥饿 (starve)。 为了得到最好的性能,需要考虑重新构造应用程序以将写访问的持续时间减少到最小。
// 从性能方面考虑,请求进入写入模式应该紧跟文件操作之前,在此处进入写入模式仅是为了降低代码复杂度
// 因进入与退出写入模式应在同一个try finally语句块内,所以在请求进入写入模式之前不能触发异常,否则释放次数大于请求次数将会触发异常
LogWriteLock.EnterWriteLock();
var path = contentRoot + @"\Log";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string logFilePath = path + [email protected]"\{filename}.log";
var now = DateTime.Now;
var logContent = (
"--------------------------------\r\n" +
DateTime.Now + "|\r\n" +
String.Join("\r\n", dataParas) + "\r\n"
);
File.AppendAllText(logFilePath, logContent);
WritedCount++;
}
catch (Exception e)
{
Console.Write(e.Message);
FailedCount++;
}
finally
{
//退出写入模式,释放资源占用
//注意:一次请求对应一次释放
// 若释放次数大于请求次数将会触发异常[写入锁定未经保持即被释放]
// 若请求处理完成后未释放将会触发异常[此模式不下允许以递归方式获取写入锁定]
LogWriteLock.ExitWriteLock();
}
}
19
View Source File : Logger.cs
License : GNU General Public License v3.0
Project Creator : anotak
License : GNU General Public License v3.0
Project Creator : anotak
public static void LoggerThread()
{
bool bNeedToLog = false;
string line = "";
// Remove the previous log file and start logging
if (File.Exists(logfile)) File.Delete(logfile);
while (true)
{
lock (toLog)
{
if (toLog.Count > 0)
{
bNeedToLog = true;
line = toLog.Dequeue();
}
else
{
bNeedToLog = false;
}
}
if (bNeedToLog)
{
// Output to console
Console.WriteLine(line);
// Write to log file
try
{
sb.Append(line);
sb.Append(Environment.NewLine);
File.AppendAllText(logfile, sb.ToString());
}
catch (Exception)
{
}
sb.Length = 0;
}
else
{
Thread.Sleep(100);
if (!bLogging)
{
Thread.Sleep(100);
lock (toLog)
{
if (toLog.Count == 0)
{
bFinished = true;
break;
}
}
}
}
} // while true
bFinished = true;
}
19
View Source File : egsTools.cs
License : Apache License 2.0
Project Creator : AntonioDePau
License : Apache License 2.0
Project Creator : AntonioDePau
private static Hed.Entry AddFile(string inputFolder, string filename, FileStream hedStream, FileStream pkgStream, bool shouldCompressData = false, bool shouldEncryptData = false)
{
var completeFilePath = Path.Combine(inputFolder, ORIGINAL_FILES_FOLDER_NAME, filename);
var offset = pkgStream.Position;
#region Data
using var newFileStream = File.OpenRead(completeFilePath);
var header = new EgsHdreplacedet.Header()
{
// CompressedLenght => -2: no compression and encryption, -1: no compression
CompressedLength = !shouldCompressData ? !shouldEncryptData ? -2 : -1 : 0,
DecompressedLength = (int)newFileStream.Length,
RemasteredreplacedetCount = 0,
CreationDate = -1
};
var decompressedData = newFileStream.ReadAllBytes();
var compressedData = decompressedData.ToArray();
if (shouldCompressData)
{
compressedData = Helpers.CompressData(decompressedData);
header.CompressedLength = compressedData.Length;
}
SDreplacedet sdreplacedet = new SDreplacedet(filename, decompressedData);
if(sdreplacedet != null && !sdreplacedet.Invalid) header.RemasteredreplacedetCount = sdreplacedet.TextureCount;
// Encrypt and write current file data in the PKG stream
// The seed used for encryption is the original data header
var seed = new MemoryStream();
BinaryMapping.WriteObject<EgsHdreplacedet.Header>(seed, header);
var encryptionSeed = seed.ReadAllBytes();
var encryptedData = header.CompressedLength > -2 ? EgsEncryption.Encrypt(compressedData, encryptionSeed) : compressedData;
// Write original file header
BinaryMapping.WriteObject<EgsHdreplacedet.Header>(pkgStream, header);
if (header.RemasteredreplacedetCount > 0)
{
// Create an "replacedet" to preplaced to ReplaceRemasteredreplacedets
EgsHdreplacedet replacedet = new EgsHdreplacedet(header, decompressedData, encryptedData, encryptionSeed);
ReplaceRemasteredreplacedets(inputFolder, filename, replacedet, pkgStream, encryptionSeed, encryptedData, sdreplacedet);
}
else
{
// Make sure to write the original file after remastered replacedets headers
pkgStream.Write(encryptedData);
}
#endregion
// Write a new entry in the HED stream
var hedHeader = new Hed.Entry()
{
MD5 = Helpers.ToBytes(Helpers.CreateMD5(filename)),
ActualLength = (int)newFileStream.Length,
DataLength = (int)(pkgStream.Position - offset),
Offset = offset
};
if (!Names.TryGetValue(Helpers.ToString(hedHeader.MD5), out var existingfilename)){
File.AppendAllText("resources/custom_filenames.txt", filename + "\n");
}
BinaryMapping.WriteObject<Hed.Entry>(hedStream, hedHeader);
return hedHeader;
}
19
View Source File : egsTools.cs
License : Apache License 2.0
Project Creator : AntonioDePau
License : Apache License 2.0
Project Creator : AntonioDePau
private static List<EgsHdreplacedet.RemasteredEntry> ReplaceRemasteredreplacedets(string inputFolder, string originalFile, EgsHdreplacedet replacedet, FileStream pkgStream, byte[] seed, byte[] originalreplacedetData, SDreplacedet sdreplacedet)
{
var newRemasteredHeaders = new List<EgsHdreplacedet.RemasteredEntry>();
var oldRemasteredHeaders = new List<EgsHdreplacedet.RemasteredEntry>();
var relativePath = Helpers.GetRelativePath(originalFile, Path.Combine(inputFolder, ORIGINAL_FILES_FOLDER_NAME));
var remasteredreplacedetsFolder = Path.Combine(inputFolder, REMASTERED_FILES_FOLDER_NAME, relativePath);
var allRemasteredreplacedetsData = new MemoryStream();
foreach (var remasteredreplacedetHeader in replacedet.RemasteredreplacedetHeaders.Values){
oldRemasteredHeaders.Add(remasteredreplacedetHeader);
}
//At the moment this only applies on fresh PKGs (or ones that haven't been patched with this modded MDLX before, otherwise we'd neet to replacedyse ALL MDLX files)
if(sdreplacedet != null && !sdreplacedet.Invalid){
File.AppendAllText("custom_hd_replacedets.txt", "HD replacedets for: " + originalFile + "\n");
while(oldRemasteredHeaders.Count > sdreplacedet.TextureCount){
File.AppendAllText("custom_hd_replacedets.txt", "Removing: -" + (oldRemasteredHeaders.Count-1) + ".dds\n");
oldRemasteredHeaders.RemoveAt(oldRemasteredHeaders.Count-1);
}
while(oldRemasteredHeaders.Count < sdreplacedet.TextureCount){
var newRemasteredreplacedetHeader = new EgsHdreplacedet.RemasteredEntry()
{
CompressedLength = 0,
DecompressedLength = 0,
Name = "-" + oldRemasteredHeaders.Count + ".dds",
Offset = 0,
OriginalreplacedetOffset = 0
};
File.AppendAllText("custom_hd_replacedets.txt", "Adding: -" + oldRemasteredHeaders.Count + ".dds\n");
oldRemasteredHeaders.Add(newRemasteredreplacedetHeader);
}
File.AppendAllText("custom_hd_replacedets.txt", "\n");
}
// 0x30 is the size of this header
var totalRemasteredreplacedetHeadersSize = oldRemasteredHeaders.Count() * 0x30;
// This offset is relative to the original replacedet data
var offset = totalRemasteredreplacedetHeadersSize + 0x10 + replacedet.OriginalreplacedetHeader.DecompressedLength;
for(int i=0;i<oldRemasteredHeaders.Count;i++)
{
var remasteredreplacedetHeader = oldRemasteredHeaders[i];
var filename = remasteredreplacedetHeader.Name;
var replacedetFilePath = Path.Combine(remasteredreplacedetsFolder, filename);
// Use base remastered replacedet data
var replacedetData = replacedet.RemasteredreplacedetsDecompressedData.ContainsKey(filename) ? replacedet.RemasteredreplacedetsDecompressedData[filename] : new byte[]{};
var decompressedLength = remasteredreplacedetHeader.DecompressedLength;
var originalreplacedetOffset = remasteredreplacedetHeader.OriginalreplacedetOffset;
if (File.Exists(replacedetFilePath))
{
Console.WriteLine($"Replacing remastered file: {relativePath}/{filename}");
replacedetData = File.ReadAllBytes(replacedetFilePath);
decompressedLength = replacedetData.Length;
replacedetData = remasteredreplacedetHeader.CompressedLength > -1 ? Helpers.CompressData(replacedetData) : replacedetData;
replacedetData = remasteredreplacedetHeader.CompressedLength > -2 ? EgsEncryption.Encrypt(replacedetData, seed) : replacedetData;
if(sdreplacedet != null && !sdreplacedet.Invalid) originalreplacedetOffset = sdreplacedet.Offsets[i];
}
else
{
Console.WriteLine($"Keeping remastered file: {relativePath}/{filename}");
// The original file have been replaced, we need to encrypt all remastered replacedet with the new key
if (!seed.SequenceEqual(replacedet.Seed))
{
replacedetData = remasteredreplacedetHeader.CompressedLength > -1 ? Helpers.CompressData(replacedetData) : replacedetData;
replacedetData = remasteredreplacedetHeader.CompressedLength > -2 ? EgsEncryption.Encrypt(replacedetData, seed) : replacedetData;
if(sdreplacedet != null && !sdreplacedet.Invalid && sdreplacedet.TextureCount >= i) originalreplacedetOffset = sdreplacedet.Offsets[i];
}else{
replacedetData = replacedet.RemasteredreplacedetsCompressedData.ContainsKey(filename) ? replacedet.RemasteredreplacedetsCompressedData[filename] : new byte[]{};
}
}
var compressedLength = remasteredreplacedetHeader.CompressedLength > -1 ? replacedetData.Length : remasteredreplacedetHeader.CompressedLength;
var newRemasteredreplacedetHeader = new EgsHdreplacedet.RemasteredEntry()
{
CompressedLength = compressedLength,
DecompressedLength = decompressedLength,
Name = filename,
Offset = offset,
OriginalreplacedetOffset = originalreplacedetOffset
};
newRemasteredHeaders.Add(newRemasteredreplacedetHeader);
// Write replacedet header in the PKG stream
BinaryMapping.WriteObject<EgsHdreplacedet.RemasteredEntry>(pkgStream, newRemasteredreplacedetHeader);
// Don't write into the PKG stream yet as we need to write
// all HD replacedets header juste after original file's data
allRemasteredreplacedetsData.Write(replacedetData);
// Make sure to align remastered replacedet data on 16 bytes
if (replacedetData.Length % 0x10 != 0)
{
allRemasteredreplacedetsData.Write(Enumerable.Repeat((byte)0xCD, 16 - (replacedetData.Length % 0x10)).ToArray());
}
offset += decompressedLength;
}
pkgStream.Write(originalreplacedetData);
pkgStream.Write(allRemasteredreplacedetsData.ReadAllBytes());
return newRemasteredHeaders;
}
19
View Source File : KHPCPatchManager.cs
License : Apache License 2.0
Project Creator : AntonioDePau
License : Apache License 2.0
Project Creator : AntonioDePau
[STAThread]
static void Main(string[] args){
if (Environment.OSVersion.Version.Major >= 6)
SetProcessDPIAware();
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(Executingreplacedembly.Location);
version = "v" + fvi.ProductVersion;
if(!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "/resources")){
UpdateResources();
}
if(!File.Exists(AppDomain.CurrentDomain.BaseDirectory + "/resources/custom_filenames.txt")){
File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "/resources/custom_filenames.txt", "");
}
Console.WriteLine($"KHPCPatchManager {version}");
string hedFile = null, pkgFile = null, pkgFolder = null;
List<string> originFolder = new List<string>();
List<string> patchFolders = new List<string>();
bool help = false;
try{
for(int i=0;i<args.Length;i++){
if(Path.GetExtension(args[i]) == ".hed"){
hedFile = args[i];
}else if(Path.GetExtension(args[i]) == ".pkg"){
pkgFile = args[i];
}else if(Directory.Exists(args[i])){
pkgFolder = args[i];
patchFolders.Add(args[i]);
}else if(Path.GetExtension(args[i]) == ".kh1pcpatch"){
patchType.Add("KH1");
originFolder.Add(args[i]);
}else if(Path.GetExtension(args[i]) == ".kh2pcpatch"){
patchType.Add("KH2");
originFolder.Add(args[i]);
}else if(Path.GetExtension(args[i]) == ".compcpatch"){
patchType.Add("COM");
originFolder.Add(args[i]);
}else if(Path.GetExtension(args[i]) == ".bbspcpatch"){
patchType.Add("BBS");
originFolder.Add(args[i]);
}else if(Path.GetExtension(args[i]) == ".dddpcpatch"){
patchType.Add("DDD");
originFolder.Add(args[i]);
}else{
if(args[i] == "help" || args[i] == "-help" || args[i] == "--help" || args[i] == "-h" || args[i] == "--h" || args[i] == "?") help = true;
}
}
if(hedFile != null){
Console.WriteLine("Extracting pkg...");
OpenKh.Egs.EgsTools.Extract(hedFile, hedFile + "_out");
Console.WriteLine("Done!");
}else if(pkgFile != null && pkgFolder != null){
Console.WriteLine("Patching pkg...");
OpenKh.Egs.EgsTools.Patch(pkgFile, pkgFolder, pkgFolder + "_out");
Console.WriteLine("Done!");
}else if(pkgFile == null && pkgFolder != null){
Console.WriteLine("Creating patch...");
using(var zip = new ZipFile()){
for(int i=0;i<patchFolders.Count;i++){
Console.WriteLine("Adding: {0}", patchFolders[i]);
zip.AddDirectory(patchFolders[i], "");
if (Directory.Exists(patchFolders[i] + @"\kh1_first") || Directory.Exists(patchFolders[i] + @"\kh1_second") || Directory.Exists(patchFolders[i] + @"\kh1_third") || Directory.Exists(patchFolders[i] + @"\kh1_fourth") || Directory.Exists(patchFolders[i] + @"\kh1_fifth")){
zip.Save("MyPatch.kh1pcpatch");
}else if (Directory.Exists(patchFolders[i] + @"\kh2_first") || Directory.Exists(patchFolders[i] + @"\kh2_second") || Directory.Exists(patchFolders[i] + @"\kh2_third") || Directory.Exists(patchFolders[i] + @"\kh2_fourth") || Directory.Exists(patchFolders[i] + @"\kh2_fifth") || Directory.Exists(patchFolders[i] + @"\kh2_sixth")){
zip.Save("MyPatch.kh2pcpatch");
}else if (Directory.Exists(patchFolders[i] + @"\Recom")){
zip.Save("MyPatch.compcpatch");
}else if (Directory.Exists(patchFolders[i] + @"\bbs_first") || Directory.Exists(patchFolders[i] + @"\bbs_second") || Directory.Exists(patchFolders[i] + @"\bbs_third") || Directory.Exists(patchFolders[i] + @"\bbs_fourth")){
zip.Save("MyPatch.bbspcpatch");
}else if (Directory.Exists(patchFolders[i] + @"\kh3d_first") || Directory.Exists(patchFolders[i] + @"\kh3d_second") || Directory.Exists(patchFolders[i] + @"\kh3d_third") || Directory.Exists(patchFolders[i] + @"\kh3d_fourth")){
zip.Save("MyPatch.dddpcpatch");
}
}
}
Console.WriteLine("Done!");
}else if(originFolder.Count > 0){
if(patchType.Distinct().ToList().Count == 1){
ApplyPatch(originFolder, patchType[0]);
}else{
Console.WriteLine(multiplePatchTypesSelected);
}
}else if(help){
Console.WriteLine("\nHow to use KHPCPatchManager in CLI:");
Console.WriteLine("- Feed a .hed file to unpack the replacedociated .pkg file:\n khpcpatchmanager <hed_file>\n");
Console.WriteLine("- Feed a .pkg file and its unpacked folder to patch it:\n khpcpatchmanager <pkg_file> <unpacked_pkg_folder>\n");
Console.WriteLine("- Feed a folder(s) (extracted .pkg format) to create a kh1pcpatch, kh2pcpatch, bbspcpatch, compcpatch or a dddpcpatch:\n khpcpatchmanager <unpacked_pkg_folder>\n");
Console.WriteLine("- Feed a kh1pcpatch, kh2pcpatch, bbspcpatch, compcpatch or a dddpcpatch to patch your .pkgs:\n khpcpatchmanager <.[kh1/com/kh2/bbs/ddd]pcpatch file>\n");
}else{
InitUI();
}
}catch(Exception e){
Console.WriteLine($"Error: {e}");
}
if(!GUI_Displayed) Console.ReadLine();
}
19
View Source File : MusicExampleBuilder.cs
License : MIT License
Project Creator : aornelas
License : MIT License
Project Creator : aornelas
private bool CreateOrModifyPackage()
{
DirectoryInfo rootDI = Directory.GetParent(Application.dataPath);
string fullyQualifiedProjectRoot = rootDI.FullName;
string packageFile = Path.Combine(fullyQualifiedProjectRoot, PlayerSettings.applicationIdentifier + ".package");
if (!File.Exists(packageFile))
{
string compFile = Path.Combine(Path.Combine(fullyQualifiedProjectRoot, "Temp/StagingArea"), "replacedets");
var pkg_builder = new UnityEditor.Lumin.Packaging.PackageBuilder();
pkg_builder.UseComponent(compFile);
pkg_builder.WriteToFile(packageFile, true);
}
string contents = File.ReadAllText(packageFile);
bool hasDATAS = contents.Contains("DATAS");
bool hasProvider = contents.Contains("example_music_provider");
if (hasDATAS && !hasProvider)
{
UnityEngine.Debug.LogErrorFormat("Error: MusicExampleBuilder.CreateOrModifyPackage failed. Reason: Package file at {0} already contained a DATAS entry but not the reference to example_music_provider.\n" +
"Delete the .package file or manually add example_music_provider.", packageFile);
return false;
}
else if (!hasDATAS)
{
File.AppendAllText(packageFile, "\nDATAS = \\\n\texample_music_provider \\");
}
return true;
}
19
View Source File : RenderStreamingLegacyRPAutomator.cs
License : Apache License 2.0
Project Creator : araobp
License : Apache License 2.0
Project Creator : araobp
static void OnPackageListRequestSuccess(Request<PackageCollection> req) {
UnityEditor.EditorApplication.LockReloadreplacedemblies();
ImportLegacyRPSample();
UnityEditor.EditorApplication.UnlockReloadreplacedemblies();
m_sampleImported = true;
//update json
RenderStreamingSettings settings = LoadSettings();
if (null!=settings) {
PackageInfo renderStreamingPackageInfo = req.FindPackage("com.unity.renderstreaming");
if (null != renderStreamingPackageInfo) {
settings.Version = renderStreamingPackageInfo.version;
SaveSettings(settings);
}
}
//Change the C# file to trigger recompilation next time "Import in project" is pushed again
File.AppendAllText(m_codePath, System.Environment.NewLine + "//Automatically Modified to trigger recompilation");
UnityEditor.replacedetDatabase.Importreplacedet(m_codePath);
}
19
View Source File : Program.cs
License : MIT License
Project Creator : Arefu
License : MIT License
Project Creator : Arefu
[STAThread]
private static void Main()
{
Console.replacedle = "Vortex";
if (File.Exists("YGO_DATA.dat"))
File.Delete("YGO_DATA.dat");
if (File.Exists("YGO_DATA.toc"))
File.Delete("YGO_DATA.toc");
var YgoFolder = "";
using (var Fbd = new FolderBrowserDialog())
{
Fbd.ShowNewFolderButton = false;
Fbd.Description = "Select the YGO_DATA folder.";
Fbd.SelectedPath = Application.StartupPath;
if (Fbd.ShowDialog() != DialogResult.OK)
Environment.Exit(1);
else
YgoFolder = Fbd.SelectedPath;
}
if (!YgoFolder.Contains("YGO_DATA"))
throw new Exception("YGO_DATA Folder Not Found!");
Files = Utilities.ParseTocFile();
FilesToPack = Directory.GetFiles($"{YgoFolder}", "*.*", SearchOption.AllDirectories);
File.AppendAllText("YGO_DATA.toc", "UT\n");
using (var Writer = new BinaryWriter(File.Open("YGO_DATA.dat", FileMode.Append, FileAccess.Write)))
{
foreach (var Item in Files)
{
var CurrentFileName = FilesToPack?.First(File => File.Contains(Item));
Utilities.Log($"Packing File: {CurrentFileName}.", Utilities.Event.Information);
var CurrentFileNameLength = Utilities.DecToHex(CurrentFileName
.Split(new[] {"YGO_DATA"}, StringSplitOptions.None).Last().TrimStart('\\').Length);
var CurrentFileSize = Utilities.DecToHex(new FileInfo($"{CurrentFileName}").Length);
while (CurrentFileSize.Length != 12)
CurrentFileSize = CurrentFileSize.Insert(0, " ");
while (CurrentFileNameLength.Length != 2)
CurrentFileNameLength = CurrentFileNameLength.Insert(0, " ");
var Reader = new BinaryReader(File.Open(CurrentFileName, FileMode.Open, FileAccess.Read));
var NewSize = new FileInfo(CurrentFileName).Length;
while (NewSize % 4 != 0)
NewSize = NewSize + 1;
var BufferSize = NewSize - new FileInfo(CurrentFileName).Length;
Writer.Write(Reader.ReadBytes((int) new FileInfo(CurrentFileName).Length));
if (BufferSize > 0)
while (BufferSize != 0)
{
Writer.Write(new byte[] {00});
BufferSize = BufferSize - 1;
}
File.AppendAllText("YGO_DATA.toc",
$"{CurrentFileSize} {CurrentFileNameLength} {CurrentFileName.Split(new[] {"YGO_DATA\\"}, StringSplitOptions.None).Last()}\n");
}
}
Utilities.Log("Finished Packing Files.", Utilities.Event.Information);
}
19
View Source File : MicrosoftAuthentication.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
[Theory, Trait("FunctionalTests", "Security")]
[InlineData(HostType.HttpListener)]
public async Task Security_MicrosoftAuthenticationWithProvider(HostType hostType)
{
using (ApplicationDeployer deployer = new ApplicationDeployer("katanatesting.com"))
{
//Edit the hosts file at c:\Windows\System32\drivers\etc\hosts and append this at the end before running the test
//#My entries
//127.0.0.1 katanatesting.com
var hostsFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), @"drivers\etc\hosts");
if (!File.ReadAllText(hostsFilePath).Contains("127.0.0.1 katanatesting.com"))
{
File.AppendAllText(hostsFilePath, "127.0.0.1 katanatesting.com");
}
string applicationUrl = deployer.Deploy(hostType, MicrosoftAuthenticationWithProviderConfiguration);
//Fix application Url hostname
applicationUrl = new UriBuilder(applicationUrl) { Host = "katanatesting.com" }.Uri.AbsoluteUri;
var handler = new HttpClientHandler() { AllowAutoRedirect = false };
var httpClient = new HttpClient(handler);
// Unauthenticated request - verify Redirect url
var response = await httpClient.GetAsync(applicationUrl);
replacedert.Equal<string>("https://login.microsoftonline.com/common/oauth2/v2.0/authorize", response.Headers.Location.AbsoluteUri.Replace(response.Headers.Location.Query, string.Empty));
var queryItems = response.Headers.Location.ParseQueryString();
replacedert.Equal<string>("code", queryItems["response_type"]);
replacedert.Equal<string>("000000004C0F442C", queryItems["client_id"]);
replacedert.Equal<string>(applicationUrl + "signin-microsoft", queryItems["redirect_uri"]);
replacedert.Equal<string>("https://graph.microsoft.com/user.read", queryItems["scope"]);
replacedert.Equal<string>("ValidStateData", queryItems["state"]);
replacedert.Equal<string>("custom", queryItems["custom_redirect_uri"]);
//This is just to generate a correlation cookie. Previous step would generate this cookie, but we have reset the handler now.
httpClient = new HttpClient(handler = new HttpClientHandler());
response = await httpClient.GetAsync(applicationUrl);
var correlationCookie = handler.CookieContainer.GetCookies(new Uri(applicationUrl))[".AspNet.Correlation.Microsoft"];
replacedert.NotNull(correlationCookie);
//Invalid state, but valid code
response = await httpClient.GetAsync(GetMicrosoftSignInMockData(applicationUrl, state: "InvalidStateData"));
replacedert.Equal<HttpStatusCode>(HttpStatusCode.InternalServerError, response.StatusCode);
replacedert.Null(handler.CookieContainer.GetCookies(new Uri(applicationUrl))[".AspNet.Application"]);
replacedert.NotNull(handler.CookieContainer.GetCookies(new Uri(applicationUrl))[".AspNet.Correlation.Microsoft"]);
//Valid state, but missing code
handler.CookieContainer.Add(correlationCookie);
response = await httpClient.GetAsync(GetMicrosoftSignInMockData(applicationUrl, code: null));
replacedert.Equal<HttpStatusCode>(HttpStatusCode.InternalServerError, response.StatusCode);
replacedert.Equal<string>("SignIn_Failed", await response.Content.ReadreplacedtringAsync());
replacedert.Null(handler.CookieContainer.GetCookies(new Uri(applicationUrl))[".AspNet.Correlation.Microsoft"]);
//Valid code & Valid state
handler.CookieContainer.Add(correlationCookie);
response = await httpClient.GetAsync(GetMicrosoftSignInMockData(applicationUrl));
replacedert.Equal<string>("Microsoft", await response.Content.ReadreplacedtringAsync());
var cookies = handler.CookieContainer.GetCookies(new Uri(applicationUrl));
replacedert.NotNull(cookies[".AspNet.Application"]);
replacedert.Null(handler.CookieContainer.GetCookies(new Uri(applicationUrl))[".AspNet.Correlation.Microsoft"]);
//Retry with valid credentials for a few times
for (int retry = 0; retry < 4; retry++)
{
response = await httpClient.GetAsync(applicationUrl);
replacedert.Equal<string>("Microsoft", await response.Content.ReadreplacedtringAsync());
}
//Valid state, but invalid code
httpClient = new HttpClient(handler = new HttpClientHandler());
response = await httpClient.GetAsync(applicationUrl);
response = await httpClient.GetAsync(GetMicrosoftSignInMockData(applicationUrl, code: "InvalidCode"));
replacedert.Equal<HttpStatusCode>(HttpStatusCode.InternalServerError, response.StatusCode);
replacedert.Equal<string>("SignIn_Failed", await response.Content.ReadreplacedtringAsync());
//Valid state, trigger CertValidator
httpClient = new HttpClient(handler = new HttpClientHandler());
response = await httpClient.GetAsync(applicationUrl);
response = await httpClient.GetAsync(GetMicrosoftSignInMockData(applicationUrl, code: "InvalidCert"));
replacedert.Equal<HttpStatusCode>(HttpStatusCode.InternalServerError, response.StatusCode);
replacedert.Equal<string>("SignIn_Failed", await response.Content.ReadreplacedtringAsync());
}
}
19
View Source File : Utils.cs
License : MIT License
Project Creator : Assistant
License : MIT License
Project Creator : Assistant
public static void Log(string message, string severity = "LOG")
{
string path = Path.GetDirectoryName(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath);
string logFile = $"{path}{Path.DirectorySeparatorChar}log.log";
File.AppendAllText(logFile, $"[{DateTime.UtcNow:yyyy-mm-dd HH:mm:ss.ffffff}][{severity.ToUpper()}] {message}\n");
}
19
View Source File : Installer.cs
License : MIT License
Project Creator : Astropilot
License : MIT License
Project Creator : Astropilot
public bool Install()
{
if (IsInstalled)
{
return DoError("Already installed");
}
string gameManagedPath = Path.Combine(GamePath, "valheim_Data", "Managed");
string toolerManagedPath = Path.Combine(_launcherPath, "Managed");
string gameManagedBackupPath = Path.Combine(_launcherPath, "Backups");
if (!Directory.Exists(gameManagedPath))
{
return DoError("Game managed folder cannot be found!");
}
if (!Directory.Exists(toolerManagedPath))
{
return DoError("Managed folder cannot be found!");
}
if (Directory.Exists(gameManagedBackupPath))
{
try
{
Directory.Delete(gameManagedBackupPath, true);
}
catch (Exception exc)
{
return DoError(exc.Message);
}
}
try
{
Directory.CreateDirectory(gameManagedBackupPath);
CopyDir.CopyAll(new DirectoryInfo(gameManagedPath), new DirectoryInfo(gameManagedBackupPath));
CopyDir.CopyAll(new DirectoryInfo(toolerManagedPath), new DirectoryInfo(gameManagedPath));
}
catch (Exception exc)
{
return DoError(exc.Message);
}
DirectoryInfo gameManagedDir = new DirectoryInfo(gameManagedPath);
IEnumerable<FileInfo> gameManagedFiles = gameManagedDir.GetFiles("*.*", SearchOption.AllDirectories);
var postInstallGameManagedFiles = new Dictionary<string, string>();
File.Delete("post_install.chk");
foreach (FileInfo file in gameManagedFiles)
{
postInstallGameManagedFiles.Add(FileUtils.GetRelativePath(file.FullName, gameManagedPath), file.ComputeHash());
}
var gameManagedHashesJson = JsonConvert.SerializeObject(postInstallGameManagedFiles);
File.AppendAllText("post_install.chk", gameManagedHashesJson);
InstalledVersion = replacedembly.GetEntryreplacedembly().GetName().Version;
_isInstalled = true;
return true;
}
19
View Source File : NativeTestsRunnerPluginService.cs
License : Apache License 2.0
Project Creator : AutomateThePlanet
License : Apache License 2.0
Project Creator : AutomateThePlanet
public string BuildNativeRunnerArguments(string libraryName, string libraryPath, List<TestCase> testCasesToBeExecuted, string testResultsFilePath, string outputFilesDir, string nativeArguments)
{
// 1. copy all js files to temp folder
// 2. edit conf.js and add results logger
// 3. edit js files and set to focus all present here in the testCases names
var allJsFiles = Directory.GetFiles(new FileInfo(libraryPath).Directory.FullName, "*.js", SearchOption.AllDirectories);
// Ignore all files in node_modules folder
var specFiles = allJsFiles.Where(x => !x.Contains("node_modules"));
var tempFolderPath = Path.GetTempPath();
var newTempFolder = Path.Combine(tempFolderPath, Guid.NewGuid().ToString());
// Write the path of the file that we will later delete.
File.AppendAllText(_deleteItemsFilePath, newTempFolder + Environment.NewLine);
Directory.CreateDirectory(newTempFolder);
// Copy all spec files to a temporary folder so that we can update them.
foreach (var currentFile in specFiles)
{
var fileInfo = new FileInfo(currentFile);
string newFilePath = Path.Combine(newTempFolder, fileInfo.Name);
File.Copy(currentFile, newFilePath);
}
// Gather the paths to all copied spec files.
var copiedSpecFiles = Directory.GetFiles(newTempFolder, "*.js", SearchOption.AllDirectories);
// locate the conf.js file
var confFile = copiedSpecFiles.FirstOrDefault(x => x.Contains(libraryName));
// If the mentioned conf file doesn't exist we throw an exception since we cannot proceed.
if (confFile == null)
{
throw new ArgumentException("The specified configuration file doesn't exist.");
}
// Read the content of the copied conf file and add the NUnit Jasmine reporter with specified results file path.
string confFileContent = File.ReadAllText(confFile);
// if for some reason a temp file exists we delete it, because the jasmine NUnit report cannot create a file but creates a folder.
if (File.Exists(testResultsFilePath))
{
File.Delete(testResultsFilePath);
}
testResultsFilePath = testResultsFilePath.Replace("\\", "//");
confFileContent = confFileContent.Replace("framework: 'jasmine',", JasminNUnitReporter.Replace("#", testResultsFilePath));
File.WriteAllText(confFile, confFileContent);
// To execute only the mentioned test cases we edit all spec files and set the 'f' infront of all it functions so that they are filtered.
foreach (var newSpecFile in copiedSpecFiles)
{
string newSpecFileContent = File.ReadAllText(newSpecFile);
var regex = new Regex(ItNamePattern);
string focusedContent = ReplaceItNamesWithFocused(newSpecFileContent, regex, "itBegin", "f", testCasesToBeExecuted.Select(x => x.FullName).ToList());
File.WriteAllText(newSpecFile, focusedContent);
}
// Copy jasmin_reporters node_modules folder to temp folder, otherwise the run cannot happen.
string jasminReportersPluginsFolder = Path.Combine(GetRunningreplacedemblyPath(), "Plugins\\node_modules_jasmin_reporters");
string jasminReportersModuleFolder = Path.Combine(newTempFolder, "node_modules");
Copy(jasminReportersPluginsFolder, jasminReportersModuleFolder);
var arguments = $" /c {Path.Combine(GetRunningreplacedemblyPath(), "Plugins\\node_modules\\.bin\\protractor")} {confFile} {nativeArguments}";
return arguments;
}
19
View Source File : LogHelper.cs
License : MIT License
Project Creator : awesomedotnetcore
License : MIT License
Project Creator : awesomedotnetcore
public static void WriteLog_LocalTxt(string log)
{
Task.Run(() =>
{
string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "A_log.txt");
string logContent = $"{DateTime.Now.ToCstTime().ToString("yyyy-MM-dd HH:mm:ss")}:{log}\r\n";
File.AppendAllText(filePath, logContent);
});
}
See More Examples