Here are the examples of the csharp api System.Console.ReadKey(bool) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
652 Examples
19
Source : HostUserInterface.cs
with GNU General Public License v3.0
from DSorlov
with GNU General Public License v3.0
from DSorlov
public override SecureString ReadLinereplacedecureString()
{
SecureString pwd = new SecureString();
if (ConsoleHandler.ConsoleLoaded)
{
while (true)
{
ConsoleKeyInfo i = Console.ReadKey(true);
if (i.Key == ConsoleKey.Enter)
{
break;
}
else if (i.Key == ConsoleKey.Backspace)
{
pwd.RemoveAt(pwd.Length - 1);
Console.Write("\b \b");
}
else
{
pwd.AppendChar(i.KeyChar);
Console.Write("*");
}
}
}
return pwd;
}
19
Source : Program.cs
with Apache License 2.0
from EdwinVW
with Apache License 2.0
from EdwinVW
static void Main(string[] args)
{
Console.OutputEncoding = System.Text.Encoding.Unicode;
var config = ConfigurationFactory.ParseString(File.ReadAllText("akkaconfig.hocon"));
using (ActorSystem system = ActorSystem.Create("cjcasystem", config))
{
Console.WriteLine("Remote actorsystem for the Central Judicial Collection Agency ready\n");
Console.ReadKey(true);
System.Console.WriteLine("Stopped. Press any key to exit.");
Console.ReadKey(true);
}
}
19
Source : Program.cs
with Apache License 2.0
from EdwinVW
with Apache License 2.0
from EdwinVW
static void Main(string[] args)
{
// start system
using (ActorSystem system = ActorSystem.Create("sales"))
{
Console.WriteLine("Sales system online. Press any key to stop");
Console.ReadKey(true);
}
}
19
Source : Program.cs
with Apache License 2.0
from EdwinVW
with Apache License 2.0
from EdwinVW
static void Main(string[] args)
{
int numberOfStores = 1;
// start system
using (ActorSystem system = ActorSystem.Create("warehouse"))
{
// create child actors
IActorRef inventoryActor = system.ActorOf<InventoryActor>("inventory");
IActorRef salesActor = system.ActorOf<SalesActor>("sales");
salesActor.Tell(new DumpSales());
IActorRef backorderActor = system.ActorOf<BackorderActor>("backorder");
Console.WriteLine("Press any key to open the stores...");
Console.ReadKey(true);
// start store simulation
for (int i = 0; i < numberOfStores; i++)
{
Props props = Props.Create<StoreActor>(new object[] { i });
system.ActorOf(props, $"store{i}");
}
Console.ReadKey(true); // keep the actorsystem alive
// dump backorders
Console.WriteLine("\nDumping backorders");
system.ActorSelection("/user/backorder").Tell(new DumpBackorders());
Console.ReadKey(true);
}
}
19
Source : Program.cs
with Apache License 2.0
from EdwinVW
with Apache License 2.0
from EdwinVW
static void Main(string[] args)
{
int numberOfStores = 1;
// start system
using (ActorSystem system = ActorSystem.Create("warehouse"))
{
// create child actors
IActorRef inventoryActor = system.ActorOf<InventoryActor>("inventory");
IActorRef salesActor = system.ActorOf<SalesActor>("sales");
IActorRef backorderActor = system.ActorOf<BackorderActor>("backorder");
Console.WriteLine("Press any key to open the stores...");
Console.ReadKey(true);
// start store simulation
for (int i = 0; i < numberOfStores; i++)
{
Props props = Props.Create<StoreActor>(new object[] { i });
system.ActorOf(props, $"store{i}");
}
Console.ReadKey(true); // keep the actorsystem alive
// dump backorders
Console.WriteLine("\nDumping sales");
salesActor.Tell(new DumpSales());
Console.ReadKey(true);
// dump backorders
Console.WriteLine("\nDumping backorders");
backorderActor.Tell(new DumpBackorders());
Console.ReadKey(true);
}
}
19
Source : Program.cs
with Apache License 2.0
from EdwinVW
with Apache License 2.0
from EdwinVW
static void Main(string[] args)
{
Console.OutputEncoding = System.Text.Encoding.Unicode;
var config = ConfigurationFactory.ParseString(File.ReadAllText("akkaconfig.hocon"));
using (ActorSystem system = ActorSystem.Create("TrafficControlSystem", config))
{
var roadInfo = new RoadInfo("A2", 10, 100, 5);
var trafficControlProps = Props.Create<TrafficControlActor>(roadInfo)
.WithRouter(new RoundRobinPool(3));
var trafficControlActor = system.ActorOf(trafficControlProps, "traffic-control");
var entryCamActor1 = system.ActorOf<EntryCamActor>("entrycam1");
var entryCamActor2 = system.ActorOf<EntryCamActor>("entrycam2");
var entryCamActor3 = system.ActorOf<EntryCamActor>("entrycam3");
var exitCamActor1 = system.ActorOf<ExitCamActor>("exitcam1");
var exitCamActor2 = system.ActorOf<ExitCamActor>("exitcam2");
var exitCamActor3 = system.ActorOf<ExitCamActor>("exitcam3");
var cjcaActor = system.ActorOf<CJCAActor>("cjcaactor");
//var cjcaActor = system.ActorOf<PersistentCJCAActor>("cjcaactor");
var simulationProps = Props.Create<SimulationActor>().WithRouter(new BroadcastPool(3));
var simulationActor = system.ActorOf(simulationProps);
Console.WriteLine("Actorsystem and actor created. Press any key to start simulation\n");
Console.ReadKey(true);
simulationActor.Tell(new StartSimulation(15));
Console.ReadKey(true);
system.Terminate();
System.Console.WriteLine("Stopped. Press any key to exit.");
Console.ReadKey(true);
}
}
19
Source : Program.cs
with Apache License 2.0
from EdwinVW
with Apache License 2.0
from EdwinVW
static void Main(string[] args)
{
using (_connection = ConnectToNats())
{
SubscribePubSub();
SubscribeRequestResponse();
SubscribeQueueGroups();
SubscribeWildcards("nats.*.wildcards");
SubscribeWildcards("nats.demo.wildcards.*");
SubscribeWildcards("nats.demo.wildcards.>");
SubscribeClear();
Console.Clear();
Console.WriteLine($"Connected to {_connection.ConnectedUrl}.");
Console.WriteLine("Consumers started");
Console.ReadKey(true);
_exit = true;
_connection.Drain(5000);
}
}
19
Source : Program.cs
with Apache License 2.0
from EdwinVW
with Apache License 2.0
from EdwinVW
static void Main(string[] args)
{
bool exit = false;
using (_connection = ConnectToNats())
{
while (!exit)
{
Console.Clear();
Console.WriteLine("NATS demo producer");
Console.WriteLine("==================");
Console.WriteLine("Select mode:");
Console.WriteLine("1) Pub / Sub");
Console.WriteLine("2) Load-balancing (queue groups)");
Console.WriteLine("3) Request / Response (explicit)");
Console.WriteLine("4) Request / Response (implicit)");
Console.WriteLine("5) Wildcards");
Console.WriteLine("6) Continuous pub/sub");
Console.WriteLine("q) Quit");
// get input
ConsoleKeyInfo input;
do
{
input = Console.ReadKey(true);
} while (!ALLOWED_OPTIONS.Contains(input.KeyChar));
switch (input.KeyChar)
{
case '1':
PubSub();
break;
case '2':
QueueGroups();
break;
case '3':
RequestResponseExplicit();
break;
case '4':
RequestResponseImplicit();
break;
case '5':
Wildcards();
break;
case '6':
ContinuousPubSub();
break;
case 'q':
case 'Q':
exit = true;
continue;
}
Console.WriteLine();
Console.WriteLine("Done. Press any key to continue...");
Console.ReadKey(true);
Clear();
}
_connection.Drain(5000);
}
}
19
Source : Program.cs
with Apache License 2.0
from EdwinVW
with Apache License 2.0
from EdwinVW
static void Main(string[] args)
{
if (args.Length != 1)
{
Console.WriteLine("Usage: consumer <clientid>");
return;
}
string clientId = args[0];
var cf = new StanConnectionFactory();
StanOptions options = StanOptions.GetDefaultOptions();
options.NatsURL = "nats://localhost:4223";
using (var c = cf.CreateConnection("test-cluster", clientId, options))
{
var opts = StanSubscriptionOptions.GetDefaultOptions();
//opts.DeliverAllAvailable();
//opts.StartAt(15);
//opts.StartAt(TimeSpan.FromSeconds(10));
//opts.StartAt(new DateTime(2019, 9, 18, 9, 0, 0));
//opts.StartWithLastReceived();
//opts.DurableName = "durable";
var s = c.Subscribe("nats.streaming.demo", opts, (obj, args) =>
{
string message = Encoding.UTF8.GetString(args.Message.Data);
Console.WriteLine($"[#{args.Message.Sequence}] {message}");
});
Console.WriteLine($"Consumer with client id '{clientId}' started. Press any key to quit...");
Console.ReadKey(true);
//s.Unsubscribe();
c.Close();
}
}
19
Source : BookStoreApp.cs
with Apache License 2.0
from EdwinVW
with Apache License 2.0
from EdwinVW
public void Start()
{
// connect to NATS
var natsConnectionFactory = new ConnectionFactory();
_natsConnection = natsConnectionFactory.CreateConnection("nats://localhost:4222");
bool exit = false;
while (!exit)
{
Console.Clear();
Console.WriteLine("Store app");
Console.WriteLine("=========");
Console.WriteLine("Choose your activity:");
Console.WriteLine("1) Create order");
Console.WriteLine("2) Order product");
Console.WriteLine("3) Remove product");
Console.WriteLine("4) Complete order");
Console.WriteLine("5) Ship order");
Console.WriteLine("6) Cancel order");
Console.WriteLine("7) Show orders overview");
Console.WriteLine("Q) Quit");
ConsoleKeyInfo input;
do
{
input = Console.ReadKey(true);
} while (!VALID_INPUT.Contains(input.KeyChar));
Console.Clear();
try
{
switch (input.KeyChar)
{
case '1':
CreateOrder();
break;
case '2':
OrderProduct();
break;
case '3':
RemoveProduct();
break;
case '4':
CompleteOrder();
break;
case '5':
ShipOrder();
break;
case '6':
CancelOrder();
break;
case '7':
ShowOrdersOverview();
break;
case 'q':
case 'Q':
exit = true;
break;
}
}
catch (Exception ex)
{
Console.WriteLine($"\nError: {ex.Message}");
Console.WriteLine("\nPress any key to return to the main menu.");
Console.ReadKey(true);
}
}
_natsConnection.Close();
}
19
Source : BookStoreApp.cs
with Apache License 2.0
from EdwinVW
with Apache License 2.0
from EdwinVW
private void CreateOrder()
{
Console.WriteLine("Create a new order");
Console.WriteLine("==================");
Console.Write("Order-number: ");
string orderNumber = Console.ReadLine();
string messageType = "CreateOrder";
string message = $"{orderNumber}";
string subject = $"store.commands.{messageType}";
var response = _natsConnection.Request(subject, Encoding.UTF8.GetBytes(message), 5000);
Console.WriteLine(Encoding.UTF8.GetString(response.Data));
Console.WriteLine("\nDone. Press any key to return to the main menu.");
Console.ReadKey(true);
}
19
Source : BookStoreApp.cs
with Apache License 2.0
from EdwinVW
with Apache License 2.0
from EdwinVW
private void OrderProduct()
{
Console.WriteLine("Order a product");
Console.WriteLine("===============");
Console.Write("Order-number: ");
string orderNumber = Console.ReadLine();
ShowProductCatalog();
Console.Write("Product-number: ");
string productNumber = Console.ReadLine();
string messageType = "OrderProduct";
string message = $"{orderNumber}|{productNumber}";
string subject = $"store.commands.{messageType}";
var response = _natsConnection.Request(subject, Encoding.UTF8.GetBytes(message), 5000);
Console.WriteLine(Encoding.UTF8.GetString(response.Data));
Console.WriteLine("\nDone. Press any key to return to the main menu.");
Console.ReadKey(true);
}
19
Source : BookStoreApp.cs
with Apache License 2.0
from EdwinVW
with Apache License 2.0
from EdwinVW
private void RemoveProduct()
{
Console.WriteLine("Remove a product");
Console.WriteLine("================");
Console.Write("Order-number: : ");
string orderNumber = Console.ReadLine();
ShowProductCatalog();
Console.Write("Product-number: ");
string productNumber = Console.ReadLine();
string messageType = "RemoveProduct";
string message = $"{orderNumber}|{productNumber}";
string subject = $"store.commands.{messageType}";
var response = _natsConnection.Request(subject, Encoding.UTF8.GetBytes(message), 5000);
Console.WriteLine(Encoding.UTF8.GetString(response.Data));
Console.WriteLine("\nDone. Press any key to return to the main menu.");
Console.ReadKey(true);
}
19
Source : BookStoreApp.cs
with Apache License 2.0
from EdwinVW
with Apache License 2.0
from EdwinVW
private void CompleteOrder()
{
Console.WriteLine("Complete an order");
Console.WriteLine("=================");
Console.Write("Order-number: ");
string orderNumber = Console.ReadLine();
Console.Write("Shipping address: ");
string shippingAddress = Console.ReadLine();
string messageType = "CompleteOrder";
string message = $"{orderNumber}|{shippingAddress}";
string subject = $"store.commands.{messageType}";
var response = _natsConnection.Request(subject, Encoding.UTF8.GetBytes(message), 5000);
Console.WriteLine(Encoding.UTF8.GetString(response.Data));
Console.WriteLine("\nDone. Press any key to return to the main menu.");
Console.ReadKey(true);
}
19
Source : BookStoreApp.cs
with Apache License 2.0
from EdwinVW
with Apache License 2.0
from EdwinVW
private void ShipOrder()
{
Console.WriteLine("Ship an order");
Console.WriteLine("=============");
Console.Write("Order-number: ");
string orderNumber = Console.ReadLine();
string messageType = "ShipOrder";
string message = $"{orderNumber}";
string subject = $"store.commands.{messageType}";
var response = _natsConnection.Request(subject, Encoding.UTF8.GetBytes(message), 5000);
Console.WriteLine(Encoding.UTF8.GetString(response.Data));
Console.WriteLine("\nDone. Press any key to return to the main menu.");
Console.ReadKey(true);
}
19
Source : BookStoreApp.cs
with Apache License 2.0
from EdwinVW
with Apache License 2.0
from EdwinVW
private void CancelOrder()
{
Console.WriteLine("Cancel an order");
Console.WriteLine("===============");
Console.Write("Order-number: ");
string orderNumber = Console.ReadLine();
string messageType = "CancelOrder";
string message = $"{orderNumber}";
string subject = $"store.commands.{messageType}";
var response = _natsConnection.Request(subject, Encoding.UTF8.GetBytes(message), 5000);
Console.WriteLine(Encoding.UTF8.GetString(response.Data));
Console.WriteLine("\nDone. Press any key to return to the main menu.");
Console.ReadKey(true);
}
19
Source : BookStoreApp.cs
with Apache License 2.0
from EdwinVW
with Apache License 2.0
from EdwinVW
private void ShowOrdersOverview()
{
Console.WriteLine("Orders Overview");
Console.WriteLine("===============");
string messageType = "OrdersOverview";
string subject = $"store.queries.{messageType}";
var response = _natsConnection.Request(subject, new byte[0], 5000);
Console.WriteLine(Encoding.UTF8.GetString(response.Data));
Console.WriteLine("\nDone. Press any key to return to the main menu.");
Console.ReadKey(true);
}
19
Source : Ide.cs
with MIT License
from egonl
with MIT License
from egonl
public static void Start(
string viewPath,
string doreplacedentPath,
object model = null,
Type baseClreplacedType = null,
Action<DoreplacedentBase> initializeDoreplacedent = null)
{
Console.WriteLine("Initializing SharpDocx IDE...");
viewPath = Path.GetFullPath(viewPath);
doreplacedentPath = Path.GetFullPath(doreplacedentPath);
ConsoleKeyInfo keyInfo;
do
{
try
{
Console.WriteLine();
Console.WriteLine($"Compiling '{viewPath}'.");
var doreplacedent = DoreplacedentFactory.Create(viewPath, model, baseClreplacedType, true);
initializeDoreplacedent?.Invoke(doreplacedent);
doreplacedent.Generate(doreplacedentPath);
Console.WriteLine($"Succesfully generated '{doreplacedentPath}'.");
try
{
// Show the generated doreplacedent.
Process.Start(doreplacedentPath);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
// Ignored.
}
}
catch (SharpDocxCompilationException e)
{
Console.WriteLine(e.SourceCode);
Console.WriteLine(e.Errors);
}
catch (Exception e)
{
Console.WriteLine(e);
}
GC.Collect();
Console.WriteLine("Press Esc to exit, any other key to retry . . .");
keyInfo = Console.ReadKey(true);
} while (keyInfo.Key != ConsoleKey.Escape);
}
19
Source : Program.cs
with GNU General Public License v3.0
from ElektroKill
with GNU General Public License v3.0
from ElektroKill
private static int Main(string[] args) {
int retValue = 1;
var replacedembly = typeof(Program).replacedembly;
var productAttr = (replacedemblyProductAttribute)replacedembly.GetCustomAttributes(typeof(replacedemblyProductAttribute), false)[0];
var verAttr = (replacedemblyInformationalVersionAttribute)replacedembly.GetCustomAttributes(typeof(replacedemblyInformationalVersionAttribute), false)[0];
string fullProductName = $"{productAttr.Product} {verAttr.InformationalVersion}";
CLIUtils.WriteLineInColor(fullProductName, ConsoleColor.White);
CLIUtils.WriteLineInColor("~ Now with 100% less reflection ~", ConsoleColor.White);
Console.WriteLine();
string origreplacedle = Console.replacedle;
Console.replacedle = $"{fullProductName} - Running...";
var parser = new CommandLineParser();
if (parser.Parse(args, out var parsedArgs)) {
if (parsedArgs.ShowHelp) {
Console.replacedle = $"{fullProductName} - Help";
CLIUtils.WriteLineInColor($"Usage: {AppDomain.CurrentDomain.FriendlyName} {{FilePath}} {{Options}}{Environment.NewLine}", ConsoleColor.Gray);
CLIUtils.WriteLineInColor("Options:", ConsoleColor.Gray);
CLIUtils.WriteLineInColor(" --help|-h Showns this screen.", ConsoleColor.Gray);
CLIUtils.WriteLineInColor(" --preserveMD|-p Preserves all metadata when writing.", ConsoleColor.Gray);
CLIUtils.WriteLineInColor(" --keepPE|-k Preserves all Win32 resources and extra PE data when writing.", ConsoleColor.Gray);
CLIUtils.WriteLineInColor(" --dataName|-d Specify CawkVM data resource name.", ConsoleColor.Gray);
retValue = 0;
}
else {
var unp = new Unpacker(new ConsoleLogger(), parsedArgs);
bool success = unp.Run();
if (success) {
Console.replacedle = $"{fullProductName} - Success";
retValue = 0;
}
else
Console.replacedle = $"{fullProductName} - Fail";
}
}
else {
Console.replacedle = $"{fullProductName} - Error";
CLIUtils.WriteLineInColor($"Argument Error: {parser.GetError()}", ConsoleColor.Red);
CLIUtils.WriteLineInColor("Use -h or --help.", ConsoleColor.Yellow);
}
Console.ResetColor();
Console.ReadKey(true);
Console.replacedle = origreplacedle;
return retValue;
}
19
Source : Program.cs
with Apache License 2.0
from Elepover
with Apache License 2.0
from Elepover
public static async Task MainAsync(string[] args)
{
try
{
Check("Initial checkpoint"); // mark initial checkpoint
Log("==> Running pre-start operations...");
// hook global errors (final failsafe)
AppDomain.CurrentDomain.UnhandledException += GlobalErrorHandler;
Log("Global error handler is armed and ready!");
// hook ctrl-c events
Console.CancelKeyPress += CtrlCHandler;
Check("Event handlers armed");
// process commandlines
await CmdLineProcess.RunCommand(Environment.CommandLine).ConfigureAwait(false);
Check("Command line arguments processed");
// everything (exits and/or errors) are handled above, please do not process.
// detect environment variables
// including:
// $pmcenter_conf
// $pmcenter_lang
try
{
var confByEnvironmentVar = Environment.GetEnvironmentVariable("pmcenter_conf");
var langByEnvironmentVar = Environment.GetEnvironmentVariable("pmcenter_lang");
if (confByEnvironmentVar != null)
{
if (File.Exists(confByEnvironmentVar))
{
Vars.ConfFile = confByEnvironmentVar;
}
else
{
Log($"==> The following file was not found: {confByEnvironmentVar}", "CORE", LogLevel.Info);
}
}
if (langByEnvironmentVar != null)
{
if (File.Exists(langByEnvironmentVar))
{
Vars.LangFile = langByEnvironmentVar;
}
else
{
Log($"==> The following file was not found: {langByEnvironmentVar}", "CORE", LogLevel.Info);
}
}
}
catch (Exception ex)
{
Log($"Failed to read environment variables: {ex}", "CORE", LogLevel.Warning);
}
Check("Environment variables processed");
Log($"==> Using configurations file: {Vars.ConfFile}");
Log($"==> Using language file: {Vars.LangFile}");
Log("==> Running start operations...");
Log("==> Initializing module - CONF"); // BY DEFAULT CONF & LANG ARE NULL! PROCEED BEFORE DOING ANYTHING. <- well anyway we have default values
await InitConf().ConfigureAwait(false);
_ = await ReadConf().ConfigureAwait(false);
Check("Configurations loaded");
await InitLang().ConfigureAwait(false);
_ = await ReadLang().ConfigureAwait(false);
Check("Custom locale loaded");
if (Vars.CurrentLang == null)
throw new InvalidOperationException("Language file is empty.");
if (Vars.RestartRequired)
{
Log("This may be the first time that you use the pmcenter bot.", "CORE");
Log("Configuration guide could be found at https://see.wtf/feEJJ", "CORE");
Log("Received restart requirement from settings system. Exiting...", "CORE", LogLevel.Error);
Log("You may need to check your settings and try again.", "CORE", LogLevel.Info);
Environment.Exit(1);
}
// check if logs are being omitted
if (Vars.CurrentConf.IgnoredLogModules.Count > 0)
{
var tmp = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("!!!!!!!!!! SOME LOG ENTRIES ARE HIDDEN ACCORDING TO CURRENT SETTINGS !!!!!!!!!!");
Console.WriteLine("To revert this, clear the \"IgnoredLogModules\" field in pmcenter.json.");
Console.WriteLine("To disable all log output, turn on \"LowPerformanceMode\".");
Console.WriteLine("This warning will appear every time pmcenter starts up with \"IgnoredLogModules\" set.");
Console.ForegroundColor = tmp;
}
Check("Warnings displayed");
Log("==> Initializing module - THREADS");
Log("Starting RateLimiter...");
Vars.RateLimiter = new Thread(() => ThrRateLimiter());
Vars.RateLimiter.Start();
Log("Waiting...");
while (!Vars.RateLimiter.IsAlive)
{
Thread.Sleep(100);
}
Check("Rate limiter online");
Log("Starting UpdateChecker...");
if (Vars.CurrentConf.EnableAutoUpdateCheck)
{
Vars.UpdateChecker = new Thread(() => ThrUpdateChecker());
Vars.UpdateChecker.Start();
Log("Waiting...");
while (!Vars.UpdateChecker.IsAlive)
{
Thread.Sleep(100);
}
}
else
{
Vars.UpdateCheckerStatus = ThreadStatus.Stopped;
Log("Skipped.");
}
Check("Update checker ready");
Log("Starting SyncConf...");
Vars.SyncConf = new Thread(() => ThrSyncConf());
Vars.SyncConf.Start();
Log("Waiting...");
while (!Vars.SyncConf.IsAlive)
{
Thread.Sleep(100);
}
Check("Configurations autosaver online");
Log("==> Initializing module - BOT");
Log("Initializing bot instance...");
if (Vars.CurrentConf.UseProxy)
{
Log("Activating SOCKS5 proxy...");
List<ProxyInfo> proxyInfoList = new List<ProxyInfo>();
foreach (var proxyInfo in Vars.CurrentConf.Socks5Proxies)
{
var newProxyInfo = new ProxyInfo(proxyInfo.ServerName,
proxyInfo.ServerPort,
proxyInfo.Username,
proxyInfo.ProxyPreplaced);
proxyInfoList.Add(newProxyInfo);
}
var proxy = new HttpToSocks5Proxy(proxyInfoList.ToArray())
{
ResolveHostnamesLocally = Vars.CurrentConf.ResolveHostnamesLocally
};
Log("SOCKS5 proxy is enabled.");
Vars.Bot = new TelegramBotClient(Vars.CurrentConf.APIKey, proxy);
}
else
{
Vars.Bot = new TelegramBotClient(Vars.CurrentConf.APIKey);
}
Check("Bot initialized");
Log("Validating API Key...");
if (Vars.CurrentConf.SkipAPIKeyVerification)
Log("API Key validation skipped", LogLevel.Warning);
else
_ = await Vars.Bot.TestApiAsync().ConfigureAwait(false);
Check("API Key test preplaceded");
Log("Hooking message processors...");
Vars.Bot.OnUpdate += BotProcess.OnUpdate;
Log("Starting receiving...");
Vars.Bot.StartReceiving(new[]
{
UpdateType.Message,
UpdateType.CallbackQuery
});
Check("Update receiving started");
Log("==> Startup complete!");
Log("==> Running post-start operations...");
try
{
// prompt startup success
if (!Vars.CurrentConf.NoStartupMessage)
{
_ = await Vars.Bot.SendTextMessageAsync(Vars.CurrentConf.OwnerUID,
Vars.CurrentLang.Message_BotStarted
.Replace("$1", $"{Math.Round(Vars.StartSW.Elapsed.TotalSeconds, 2)}s"),
ParseMode.Markdown,
false,
false).ConfigureAwait(false);
}
}
catch (Exception ex)
{
Log($"Failed to send startup message to owner.\nDid you set the \"OwnerID\" key correctly? Otherwise pmcenter could not work properly.\nYou can try to use setup wizard to update/get your OwnerID automatically, just run \"dotnet pmcenter.dll --setup\".\n\nError details: {ex}", "BOT", LogLevel.Warning);
}
Check("Startup message sent");
try
{
// check .net core runtime version
var netCoreVersion = GetNetCoreVersion();
if (!CheckNetCoreVersion(netCoreVersion) && !Vars.CurrentConf.DisableNetCore3Check)
{
_ = await Vars.Bot.SendTextMessageAsync(Vars.CurrentConf.OwnerUID,
Vars.CurrentLang.Message_NetCore31Required
.Replace("$1", netCoreVersion.ToString()),
ParseMode.Markdown,
false,
false).ConfigureAwait(false);
Vars.CurrentConf.DisableNetCore3Check = true;
_ = await SaveConf(false, true);
}
}
catch (Exception ex)
{
Log($".NET Core runtime version warning wasn't delivered to the owner: {ex.Message}, did you set the \"OwnerID\" key correctly?", "BOT", LogLevel.Warning);
}
Check(".NET Core runtime version check complete");
// check language mismatch
if (Vars.CurrentLang.TargetVersion != Vars.AppVer.ToString())
{
Log("Language version mismatch detected", "CORE", LogLevel.Warning);
if (Vars.CurrentConf.CheckLangVersionMismatch)
_ = await Vars.Bot.SendTextMessageAsync(Vars.CurrentConf.OwnerUID,
Vars.CurrentLang.Message_LangVerMismatch
.Replace("$1", Vars.CurrentLang.TargetVersion)
.Replace("$2", Vars.AppVer.ToString()),
ParseMode.Markdown,
false,
false).ConfigureAwait(false);
}
Check("Language version mismatch checked");
Check("Complete");
if (Vars.CurrentConf.replacedyzeStartupTime)
{
Log("Advanced startup time replacedysis is on, printing startup checkpoints...");
PrintCheckPoints();
_checkPoints.Clear();
}
Log("==> All finished!");
if (Vars.ServiceMode)
while (true)
Thread.Sleep(int.MaxValue);
else
while (true)
Console.ReadKey(true);
}
catch (Exception ex)
{
CheckOpenSSLComp(ex);
Log($"Unexpected error during startup: {ex}", "CORE", LogLevel.Error);
Environment.Exit(1);
}
}
19
Source : Program.cs
with MIT License
from Emotiv
with MIT License
from Emotiv
static void Main(string[] args)
{
Console.WriteLine("INJECT MARKER DEMO");
Console.WriteLine("Please wear Headset with good signal!!!");
_ctxClient = CortexClient.Instance;
_ctxClient.OnCreateRecord += RecordCreatedOK;
_ctxClient.OnStopRecord += RecordStoppedOK;
_ctxClient.OnInjectMarker += MarkerInjectedOk;
_ctxClient.OnErrorMsgReceived += MessageErrorRecieved;
_authorizer.OnAuthorized += AuthorizedOK;
_headsetFinder.OnHeadsetConnected += HeadsetConnectedOK;
_sessionCreator.OnSessionCreated += SessionCreatedOk;
_sessionCreator.OnSessionClosed += SessionClosedOK;
Console.WriteLine("Prepare to inject marker");
// Start
_authorizer.Start();
if (_readyForInjectMarkerEvent.WaitOne(50000))
{
Console.WriteLine("Press certain key except below keys to inject marker");
Console.WriteLine("Press S to stop record and quit");
Console.WriteLine("Press Esc to quit");
Console.WriteLine("Press H to show all commands");
Console.WriteLine("Ignore Tab, Enter, Spacebar and Backspace key");
int valueMaker = 1;
ConsoleKeyInfo keyInfo;
while (true)
{
keyInfo = Console.ReadKey(true);
Console.WriteLine(keyInfo.KeyChar.ToString() + " has pressed");
if (keyInfo.Key == ConsoleKey.S)
{
// Querry Sessions before quit
_ctxClient.StopRecord(_cortexToken, _sessionId);
Thread.Sleep(10000);
break;
}
if (keyInfo.Key == ConsoleKey.H)
{
Console.WriteLine("Press certain key except below keys to inject marker");
Console.WriteLine("Press S to stop record and quit");
Console.WriteLine("Press Esc to quit");
Console.WriteLine("Press H to show all commands");
Console.WriteLine("Ignore Tab, Enter, Spacebar and Backspace key");
}
else if (keyInfo.Key == ConsoleKey.Tab) continue;
else if (keyInfo.Key == ConsoleKey.Backspace) continue;
else if (keyInfo.Key == ConsoleKey.Enter) continue;
else if (keyInfo.Key == ConsoleKey.Spacebar) continue;
else if (keyInfo.Key == ConsoleKey.Escape)
{
break;
}
else
{
// Inject marker
if (_isRecording)
{
_ctxClient.InjectMarker(_cortexToken, _sessionId, keyInfo.Key.ToString(), valueMaker, Utils.GetEpochTimeNow());
Thread.Sleep(2000);
valueMaker++;
}
}
}
Thread.Sleep(10000);
}
else
{
Console.WriteLine("The preparation for injecting marker is unsuccessful. Please try again");
}
}
19
Source : Program.cs
with MIT License
from Emotiv
with MIT License
from Emotiv
static void Main(string[] args)
{
Console.WriteLine("TRAINING MENTAL COMMAND DEMO");
Console.WriteLine("Please wear Headset with good signal!!!");
_ctxClient = CortexClient.Instance;
_trainer.OnReadyForTraning += ReadyForTraining;
_trainer.OnTrainingSucceeded += TrainingSucceededOK;
_trainer.OnProfileLoaded += ProfileLoadedOK;
_trainer.OnUnProfileLoaded += ProfileUnloadedOK;
Console.WriteLine("Prepare to training");
// Start
_trainer.Start("mentalCommand");
if (_readyForTrainingEvent.WaitOne(50000))
{
Console.WriteLine("Press C to create a Profile.");
Console.WriteLine("Press L to load a Profile.");
Console.WriteLine("Press U to unload a Profile.");
Console.WriteLine("Press 0 to start Neutral training.");
Console.WriteLine("Press 1 to start Push training.");
Console.WriteLine("Press 2 to start Pull training.");
Console.WriteLine("Press A to accept training.");
Console.WriteLine("Press R to reject training.");
Console.WriteLine("Press H to show all commands.");
Console.WriteLine("Press Esc to quit");
Console.WriteLine("Ignore Tab, Enter, Spacebar and Backspace key");
ConsoleKeyInfo keyInfo;
while (true)
{
keyInfo = Console.ReadKey(true);
Console.WriteLine(keyInfo.KeyChar.ToString() + " has pressed");
if (keyInfo.Key == ConsoleKey.C)
{
if (string.IsNullOrEmpty(Program._profileName))
_profileName = Utils.GenerateUuidProfileName("McDemo");
Console.WriteLine("Create profile: " + _profileName);
_trainer.CreateProfile(_profileName);
Thread.Sleep(1000);
}
else if (keyInfo.Key == ConsoleKey.L)
{
//Load profile
Console.WriteLine("Load profile: " + _profileName);
_trainer.LoadProfile(_profileName);
Thread.Sleep(1000);
}
else if (keyInfo.Key == ConsoleKey.U)
{
//Load profile
Console.WriteLine("UnLoad profile: " + _profileName);
_trainer.UnLoadProfile(_profileName);
Thread.Sleep(1000);
}
else if (keyInfo.Key == ConsoleKey.D0)
{
if (_isProfileLoaded)
{
_currentAction = "neutral";
//Start neutral training
_trainer.DoTraining(_currentAction, "start");
Thread.Sleep(2000);
}
}
else if (keyInfo.Key == ConsoleKey.D1)
{
if (_isProfileLoaded)
{
//Start push training
_currentAction = "push";
_trainer.DoTraining(_currentAction, "start");
Thread.Sleep(2000);
}
}
else if (keyInfo.Key == ConsoleKey.D2)
{
if (_isProfileLoaded)
{
//Start pull training
_currentAction = "pull";
_trainer.DoTraining(_currentAction, "start");
Thread.Sleep(2000);
}
}
else if (keyInfo.Key == ConsoleKey.A)
{
//Accept training
if (_isSucceeded)
{
_trainer.DoTraining(_currentAction, "accept");
Thread.Sleep(1000);
_isSucceeded = false; // reset
}
}
else if (keyInfo.Key == ConsoleKey.R)
{
//Reject training
if (_isSucceeded)
{
_trainer.DoTraining(_currentAction, "reject");
Thread.Sleep(1000);
_isSucceeded = false; // reset
}
}
else if (keyInfo.Key == ConsoleKey.H)
{
Console.WriteLine("Press C to create a Profile.");
Console.WriteLine("Press L to load a Profile.");
Console.WriteLine("Press U to unload a Profile.");
Console.WriteLine("Press 0 to start Neutral training.");
Console.WriteLine("Press 1 to start Push training.");
Console.WriteLine("Press 2 to start Pull training.");
Console.WriteLine("Press A to accept training.");
Console.WriteLine("Press R to reject training.");
Console.WriteLine("Press H to show all commands");
Console.WriteLine("Press Esc to quit");
}
else if (keyInfo.Key == ConsoleKey.Tab) continue;
else if (keyInfo.Key == ConsoleKey.Backspace) continue;
else if (keyInfo.Key == ConsoleKey.Enter) continue;
else if (keyInfo.Key == ConsoleKey.Spacebar) continue;
else if (keyInfo.Key == ConsoleKey.Escape)
{
_trainer.CloseSession();
break;
}
else
{
Console.WriteLine("Unsupported key");
}
}
Thread.Sleep(10000);
}
else
{
Console.WriteLine("The preparation for training is unsuccessful. Please try again");
}
}
19
Source : Program.cs
with MIT License
from Emotiv
with MIT License
from Emotiv
static void Main(string[] args)
{
Console.WriteLine("RECORD DATA DEMO");
Console.WriteLine("Please wear Headset with good signal!!!");
_ctxClient = CortexClient.Instance;
_ctxClient.OnCreateRecord += RecordCreatedOK;
_ctxClient.OnStopRecord += RecordStoppedOK;
_ctxClient.OnErrorMsgReceived += MessageErrorRecieved;
_ctxClient.OnQueryRecords += QueryRecordsOK;
_ctxClient.OnDeleteRecords += DeleteRecordOK;
_ctxClient.OnUpdateRecord += RecordUpdatedOK;
_authorizer.OnAuthorized += AuthorizedOK;
_headsetFinder.OnHeadsetConnected += HeadsetConnectedOK;
_sessionCreator.OnSessionCreated += SessionCreatedOk;
_sessionCreator.OnSessionClosed += SessionClosedOK;
Console.WriteLine("Prepare to record Data");
// Start
_authorizer.Start();
if (_readyForRecordDataEvent.WaitOne(50000))
{
Console.WriteLine("Press certain key to inject marker");
Console.WriteLine("Press C to create record");
Console.WriteLine("Press S to stop record");
Console.WriteLine("Press Q to query record");
Console.WriteLine("Press D to delete record");
Console.WriteLine("Press U to update record");
Console.WriteLine("Press H to show all commands");
Console.WriteLine("Press Esc to quit");
Console.WriteLine("Ignore Tab, Enter, Spacebar and Backspace key");
ConsoleKeyInfo keyInfo;
while (true)
{
keyInfo = Console.ReadKey(true);
Console.WriteLine(keyInfo.KeyChar.ToString() + " has pressed");
if (keyInfo.Key == ConsoleKey.S)
{
// Stop Record
Console.WriteLine("Stop Record");
_ctxClient.StopRecord(_cortexToken, _sessionId);
}
else if (keyInfo.Key == ConsoleKey.C)
{
// Create Record
string replacedle = "RecDemo-" + _recordNo;
Console.WriteLine("Create Record" + replacedle);
_ctxClient.CreateRecord(_cortexToken, _sessionId, replacedle);
_recordNo++;
}
else if (keyInfo.Key == ConsoleKey.U)
{
// Update Record
string description = "description for RecDemo";
List<string> tags = new List<string>() { "demo1", "demo2" };
Console.WriteLine("Update Record: " + _currRecordId);
_ctxClient.UpdateRecord(_cortexToken, _currRecordId, description, tags);
}
else if (keyInfo.Key == ConsoleKey.Q)
{
// Query Record
// query param
JObject query = new JObject();
query.Add("applicationId", _sessionCreator.ApplicationId);
//order
JArray orderBy = new JArray();
JObject eleOrder = new JObject();
eleOrder.Add("startDatetime", "DESC" );
orderBy.Add(eleOrder);
// limit
int limit = 5; // number of maximum record return
int offset = 0;
_ctxClient.QueryRecord(_cortexToken, query, orderBy, offset, limit);
}
else if (keyInfo.Key == ConsoleKey.D)
{
// Delete first Record
if (_recordLists.Count > 0)
{
Record lastRecord = _recordLists[0];
string recordId = lastRecord.Uuid;
Console.WriteLine("Delete Record" + recordId);
_ctxClient.DeleteRecord(_cortexToken, new List<string>() { recordId });
}
else
{
Console.WriteLine("Please queryRecords first before call deleteRecord which delete first record in Lists");
}
}
else if (keyInfo.Key == ConsoleKey.H)
{
Console.WriteLine("Press certain key to inject marker");
Console.WriteLine("Press C to create record");
Console.WriteLine("Press S to stop record");
Console.WriteLine("Press Q to query record");
Console.WriteLine("Press D to delete record");
Console.WriteLine("Press U to update record");
Console.WriteLine("Press H to show all commands");
Console.WriteLine("Press Esc to quit");
}
else if (keyInfo.Key == ConsoleKey.Tab) continue;
else if (keyInfo.Key == ConsoleKey.Backspace) continue;
else if (keyInfo.Key == ConsoleKey.Enter) continue;
else if (keyInfo.Key == ConsoleKey.Spacebar) continue;
else if (keyInfo.Key == ConsoleKey.Escape)
{
_sessionCreator.CloseSession();
break;
}
else
{
Console.WriteLine("Unsupported key");
}
}
Thread.Sleep(10000);
}
else
{
Console.WriteLine("The preparation for injecting marker is unsuccessful. Please try again");
}
}
19
Source : Program.cs
with MIT License
from Emotiv
with MIT License
from Emotiv
static void Main(string[] args)
{
Console.WriteLine("TRAINING FACIAL EXPRESSION DEMO");
Console.WriteLine("Please wear Headset with good signal!!!");
_ctxClient = CortexClient.Instance;
_trainer.OnReadyForTraning += ReadyForTraining;
_trainer.OnTrainingSucceeded += TrainingSucceededOK;
_trainer.OnProfileLoaded += ProfileLoadedOK;
_trainer.OnUnProfileLoaded += ProfileUnloadedOK;
Console.WriteLine("Prepare to training");
// Start
_trainer.Start("facialExpression");
if (_readyForTrainingEvent.WaitOne(50000))
{
Console.WriteLine("Press C to create a Profile.");
Console.WriteLine("Press L to load a Profile.");
Console.WriteLine("Press U to unload a Profile.");
Console.WriteLine("Press 0 to start Neutral training.");
Console.WriteLine("Press 1 to start Smile training.");
Console.WriteLine("Press 2 to start Frown training.");
Console.WriteLine("Press 3 to start Clench training.");
Console.WriteLine("Press A to accept training.");
Console.WriteLine("Press R to reject training.");
Console.WriteLine("Press H to show all commands.");
Console.WriteLine("Press Esc to quit");
Console.WriteLine("Ignore Tab, Enter, Spacebar and Backspace key");
ConsoleKeyInfo keyInfo;
while (true)
{
keyInfo = Console.ReadKey(true);
Console.WriteLine(keyInfo.KeyChar.ToString() + " has pressed");
if (keyInfo.Key == ConsoleKey.C)
{
if (string.IsNullOrEmpty(Program._profileName))
Program._profileName = Utils.GenerateUuidProfileName("FeDemo");
Console.WriteLine("Create profile: " + _profileName);
_trainer.CreateProfile(_profileName);
Thread.Sleep(1000);
}
else if (keyInfo.Key == ConsoleKey.L)
{
//Load profile
Console.WriteLine("Load profile: " + _profileName);
_trainer.LoadProfile(_profileName);
Thread.Sleep(1000);
}
else if (keyInfo.Key == ConsoleKey.U)
{
//Load profile
Console.WriteLine("UnLoad profile: " + _profileName);
_trainer.UnLoadProfile(_profileName);
Thread.Sleep(1000);
}
else if (keyInfo.Key == ConsoleKey.D0)
{
if (_isProfileLoaded)
{
_currentAction = "neutral";
//Start neutral training
_trainer.DoTraining(_currentAction, "start");
Thread.Sleep(2000);
}
}
else if (keyInfo.Key == ConsoleKey.D1)
{
if (_isProfileLoaded)
{
//Start smile training
_currentAction = "smile";
_trainer.DoTraining(_currentAction, "start");
Thread.Sleep(2000);
}
}
else if (keyInfo.Key == ConsoleKey.D2)
{
if (_isProfileLoaded)
{
//Start frown training
_currentAction = "frown";
_trainer.DoTraining(_currentAction, "start");
Thread.Sleep(2000);
}
}
else if (keyInfo.Key == ConsoleKey.D3)
{
if (_isProfileLoaded)
{
//Start clench training
_currentAction = "clench";
_trainer.DoTraining(_currentAction, "start");
Thread.Sleep(2000);
}
}
else if (keyInfo.Key == ConsoleKey.A)
{
//Accept training
if (_isSucceeded)
{
_trainer.DoTraining(_currentAction, "accept");
Thread.Sleep(1000);
_isSucceeded = false; // reset
}
}
else if (keyInfo.Key == ConsoleKey.R)
{
//Reject training
if (_isSucceeded)
{
_trainer.DoTraining(_currentAction, "reject");
Thread.Sleep(1000);
_isSucceeded = false; // reset
}
}
else if (keyInfo.Key == ConsoleKey.H)
{
Console.WriteLine("Press C to create a Profile.");
Console.WriteLine("Press L to load a Profile.");
Console.WriteLine("Press U to unload a Profile.");
Console.WriteLine("Press 0 to start Neutral training.");
Console.WriteLine("Press 1 to start Smile training.");
Console.WriteLine("Press 2 to start Frown training.");
Console.WriteLine("Press 3 to start Clench training.");
Console.WriteLine("Press A to accept training.");
Console.WriteLine("Press R to reject training.");
Console.WriteLine("Press H to show all commands");
Console.WriteLine("Press Esc to quit");
}
else if (keyInfo.Key == ConsoleKey.Tab) continue;
else if (keyInfo.Key == ConsoleKey.Backspace) continue;
else if (keyInfo.Key == ConsoleKey.Enter) continue;
else if (keyInfo.Key == ConsoleKey.Spacebar) continue;
else if (keyInfo.Key == ConsoleKey.Escape)
{
_trainer.CloseSession();
break;
}
else
{
Console.WriteLine("Unsupported key");
}
}
Thread.Sleep(10000);
}
else
{
Console.WriteLine("The preparation for training is unsuccessful. Please try again");
}
}
19
Source : Program.cs
with Apache License 2.0
from Emzi0767
with Apache License 2.0
from Emzi0767
public static void Main(string[] args)
{
var proc = GameProcess.Attach();
Console.WriteLine("Attached to process");
proc.GameStarted += (o, e) => Console.WriteLine("EV: GAME_START -> map: {0}", e.Map);
proc.GameEnded += (o, e) => Console.WriteLine("EV: GAME_END");
proc.PlayerJoined += (o, e) => Console.WriteLine("EV: PLAYER_JOIN -> {0}", e.Player.Name);
proc.PlayerLeft += (o, e) => Console.WriteLine("EV: PLAYER_LEAVE -> {0}", e.Player.Name);
proc.PlayerDied += (o, e) => Console.WriteLine("EV: PLAYER_DEATH -> {0}", e.Player.Name);
proc.PlayerImpostorStatusChanged += (o, e) => Console.WriteLine("EV: PLAYER_IMPOSTOR_STATUS_CHANGE -> {0}, {1}", e.Player.Name, e.Player.IsImpostor);
proc.MeetingStarted += (o, e) => Console.WriteLine("EV: MEETING_START");
proc.MeetingEnded += (o, e) => Console.WriteLine("EV: MEETING_END -> exile: {0:0.0}s", e.ExileDuration);
proc.Start();
Console.WriteLine("Loop running");
Console.WriteLine("Press any to quit");
Console.ReadKey(true);
proc.Dispose();
Console.WriteLine("Detached");
}
19
Source : Program.cs
with MIT License
from Enichan
with MIT License
from Enichan
static void Main() {
var random = new Random();
using (var co = Coroutine.Create(CoFunction1(5, 10))) {
while (co.Resume()) {
if (co.Status != CoStatus.Waiting) {
Console.WriteLine(co.Result.ReturnValue.ToString());
}
}
}
using (var co = Coroutine.Create(CoFunction2(10, 100))) {
var i = 0;
while (co.Resume(new { x = random.Next(10), y = random.Next(10) })) {
if (co.Status != CoStatus.Waiting) {
Console.WriteLine(co.Result.ReturnValue.ToString());
}
i++;
if (i > 5000000 && !timedOut) {
timedOut = true;
Console.WriteLine("timed out");
}
}
}
var wrapped = Coroutine.Wrap(CoFunction1(5, 10));
CoResult<int> wrappedResult;
while ((wrappedResult = wrapped()) == true) {
if (wrappedResult.Status != CoStatus.Waiting) {
Console.WriteLine("Wrapped coroutine: " + wrappedResult.ReturnValue);
}
}
var sync = Coroutine.MakeSyncWithArgs<int, int, int>(CoFunction2);
Console.WriteLine("Synchronized coroutine result: " + sync(new { x = 10, y = 100 }, 8, 20));
Console.WriteLine("Press any key to run coroutine pool test");
Console.ReadKey(true);
var pool = new CoroutinePool();
var resets = new Dictionary<Coroutine, int>();
for (int i = 0; i < 5; i++) {
var co = Coroutine.Create(PoolFunc(random.Next()));
pool.Add(co);
resets[co] = 0;
}
var reset = true;
pool.OnEnd += (c) => {
if (reset) {
c.Reset();
resets[c]++;
}
};
ConsoleKey key;
do {
while (!Console.KeyAvailable) {
Console.Clear();
Console.WriteLine("Press 'q' to quit, 'r' to disable resets");
Console.WriteLine();
pool.ResumeAll();
var index = 1;
foreach (var co in pool) {
Console.SetCursorPosition(0, 1 + index);
Console.WriteLine("Coroutine " + index + ": " + co.ReturnValue);
Console.SetCursorPosition(20, 1 + index);
Console.WriteLine("Resets: " + resets[co]);
index++;
}
System.Threading.Thread.Sleep(50);
if (pool.IsEmpty) {
System.Threading.Thread.Sleep(200);
break;
}
}
if (pool.IsEmpty) {
break;
}
key = Console.ReadKey(true).Key;
if (key == ConsoleKey.R) {
reset = false;
}
} while (key != ConsoleKey.Q);
}
19
Source : Program.cs
with MIT License
from essenbee
with MIT License
from essenbee
static void Main(string[] args)
{
var ram = new byte[65536];
Array.Clear(ram, 0, ram.Length);
var romData = File.ReadAllBytes(_rom);
if (romData.Length != 16384)
{
throw new InvalidOperationException("Not a valid ROM file");
}
Array.Copy(romData, ram, 16384);
_cpu = new Z80();
IBus simpleBus = new SimpleBus(ram);
_cpu.ConnectToBus(simpleBus);
Console.Clear();
while (!(Console.KeyAvailable && (Console.ReadKey(true).Key == ConsoleKey.Escape)))
{
try
{
_cpu.Step();
Console.Write($"\rPC: {_cpu.PC.ToString("X4")}");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
Console.ReadLine();
}
}
Console.WriteLine();
Console.WriteLine();
for (var i = 0x4000; i < 0x5800; i++)
{
if (i % 16 == 0) Console.Write("{0:X4} | ", i);
{
Console.Write("{0:x2} ", ram[i]);
}
if (i % 8 == 7)
{
Console.Write(" ");
}
if (i % 16 == 15)
{
Console.WriteLine();
}
}
}
19
Source : Program.cs
with MIT License
from EtiTheSpirit
with MIT License
from EtiTheSpirit
static void Main(string[] args) {
if (args.Length != 1) {
Console.WriteLine("Drag n' drop a WEM or any audio file onto this EXE to convert it. WEM will be converted to WAV no matter what.");
Console.WriteLine("Press any key to quit...");
Console.ReadKey(true);
return;
}
FileInfo file = new FileInfo(args[0]);
if (file.Extension.ToLower() == ".wem") {
Console.WriteLine("WARNING: WEM conversion is a bit busted right now! If your file is broken, sorry! A patch will be out ASAP.");
WEMFile wem = new WEMFile(file.FullName);
WAVFile wav = wem.ConvertToWAV();
wav.SaveToFile(file.FullName + ".wav");
} else {
file = FFmpegWrapper.ConvertToWaveFile(file.FullName);
WAVFile wav = new WAVFile(file.FullName);
WEMFile wem = wav.ConvertToWEM();
wem.SaveToFile(args[0] + ".wem");
}
}
19
Source : OsuPatcher.cs
with MIT License
from exys228
with MIT License
from exys228
public static int Main(string[] args)
{
// Console.ReadKey(true);
if (args.Length < 2)
return Exit("osu!patch - osu! replacedembly patcher based on NameMapper\n" +
"by exys, 2019 - 2020\n" +
"\n" +
"Usage:\n" +
"osu!patch [clean module] [obfuscated module]");
if (!File.Exists(_cleanOsuPath = Path.GetFullPath(args[0])))
return XConsole.PrintFatal("Specified clean module path does not exist!\n");
if (!File.Exists(_obfOsuPath = Path.GetFullPath(args[1])))
return XConsole.PrintFatal("Specified obfuscated module path does not exist!\n");
try
{
_obfOsuModule = ModuleDefMD.Load(_obfOsuPath);
_cleanOsuModule = ModuleDefMD.Load(_cleanOsuPath);
_obfOsureplacedembly = replacedembly.LoadFile(_obfOsuPath);
}
catch (Exception ex) { return XConsole.PrintFatal("Unable to load one of the modules! Details:\n" + ex); }
ObfOsuHash = MD5Helper.Compute(_obfOsuPath); // ORIGINAL!!!!!!! hash, PLEASE Preplaced UNMODIFIED PEPPY-SIGNED replacedEMBLY AS _obfOsuModule!@!!32R1234 (refer to "Patch on update" patch)
XConsole.PrintInfo($"Loaded replacedemblies: {_cleanOsuModule.replacedembly.FullName} (clean); {_obfOsuModule.replacedembly.FullName} (obfuscated).");
XConsole.PrintInfo("MD5 hash of obfuscated replacedembly: " + ObfOsuHash);
try
{
LoadPlugins(); // Loading plugins
}
catch (Exception ex) { return XConsole.PrintFatal("Something really bad happened while trying to process plugins! Details:\n" + ex); }
try
{
XConsole.PrintInfo("Cleaning control flow of obfuscated replacedembly");
CleanControlFlow();
}
catch (Exception ex) { return XConsole.PrintFatal("Unable to deobfuscate control flow of obfuscated replacedembly! Details:\n" + ex); }
try
{
XConsole.PrintInfo("Fixing strings in obfuscated replacedembly.");
StringFixer.Fix(_obfOsuModule, _obfOsureplacedembly); // Fixing strings
}
catch (Exception ex) { return XConsole.PrintFatal("Unable to fix strings of obfuscated replacedembly! Details:\n" + ex); }
if (!Directory.Exists(CacheFolderLocation))
{
XConsole.PrintInfo("Creating cache folder...");
Directory.CreateDirectory(CacheFolderLocation);
}
try
{
var nameProvider = InitializeNameProvider(); // Fixing names (SimpleNameProvider/MapperNameProvider)
_obfOsuExplorer = new ModuleExplorer(_obfOsuModule, nameProvider);
}
catch (Exception ex) { return XConsole.PrintFatal("Unable to get clean names for obfuscated replacedembly! Details:\n" + ex); }
#if DEBUG
_obfOsuModule.Write(Path.Combine(Path.GetDirectoryName(_obfOsuPath), "OsuObfModule-cflow-string-nmapped.exe"), new ModuleWriterOptions(_obfOsuModule)
{
MetadataOptions = { Flags = DEFAULT_METADATA_FLAGS }
});
#endif
XConsole.PrintInfo("Done! Now patching.");
bool overallSuccess = true;
var failedDetails = new List<PatchResult>();
void ExecutePatchCli(Patch patch)
{
XConsole.PrintInfo($"{patch.Name}: ", false);
if (File.Exists(ConfigFileLocation)) // incase if config file not initialized
patch.Enabled = GetConfigEnabled(patch.Name);
PatchResult res = patch.Execute(_obfOsuExplorer);
switch (res.Result)
{
case PatchStatus.Disabled:
Console.ForegroundColor = ConsoleColor.Gray;
XConsole.WriteLine("DISABLED");
break;
case PatchStatus.Exception:
case PatchStatus.Failure:
Console.ForegroundColor = ConsoleColor.Red;
XConsole.WriteLine("FAIL");
failedDetails.Add(res);
overallSuccess = false;
break;
case PatchStatus.Success:
Console.ForegroundColor = ConsoleColor.Green;
XConsole.WriteLine("DONE");
break;
default:
Console.ForegroundColor = ConsoleColor.DarkGray;
XConsole.WriteLine("[???]");
break;
}
Console.ResetColor();
}
// Executing local patches.
foreach (var patch in LocalPatches.PatchList)
ExecutePatchCli(patch);
XConsole.PrintInfo("Done processing all local patches! Now processing patches from loaded add-ons...");
#if !CORE_PATCHES_ONLY
// Executing all patches from all loaded plugins from all loaded replacedemblies (what a hierarchy)
foreach (var plugin in _loadedPlugins)
{
XConsole.PrintInfo($"{plugin.replacedemblyName}: Processing plugin: {plugin.TypeName}.");
foreach (var patch in plugin.Type.GetPatches())
{
ExecutePatchCli(patch);
}
XConsole.PrintInfo($"{plugin.replacedemblyName}: Done processing: {plugin.TypeName}.");
}
#endif
if (!File.Exists(ConfigFileLocation))
{
XConsole.PrintInfo("Creating config file...");
var configLines = string.Empty;
foreach (var patch in Patches)
configLines += patch.Name + " = " + "Enabled\n"; // probably bad implementation of config but simplest i can imagine
File.WriteAllText(ConfigFileLocation, configLines);
XConsole.PrintInfo("Config file created!");
}
XConsole.PrintInfo("Done processing all plugins.");
if (failedDetails.Any())
{
XConsole.PrintInfo("There's some details about failed patches.");
foreach (var details in failedDetails)
{
details.PrintDetails(Console.Out);
XConsole.WriteLine();
}
}
if (!overallSuccess)
{
XConsole.PrintInfo("There are some failed patches. Do you want to continue?");
XConsole.PrintWarn("In case of self-update pressing 'N' will leave stock version of osu! without patching it!");
XConsole.Write(XConsole.PAD + "Continue? (y/n) ");
var exit = false;
while (true)
{
var key = Console.ReadKey(true).Key;
if (key == ConsoleKey.Y)
break;
if (key == ConsoleKey.N)
{
exit = true;
break;
}
}
XConsole.WriteLine();
if (exit)
return Exit(XConsole.Info("Aborted by user."));
}
string filename = Path.GetFileNameWithoutExtension(_obfOsuPath) + "-osupatch" + Path.GetExtension(_obfOsuPath);
XConsole.PrintInfo($"Saving replacedembly as {filename}");
try
{
_obfOsuModule.Write(Path.Combine(Path.GetDirectoryName(_obfOsuPath), filename), new ModuleWriterOptions(_obfOsuModule)
{
MetadataOptions = { Flags = DEFAULT_METADATA_FLAGS }
});
}
catch (Exception ex) { return Exit(XConsole.Fatal("Unable to save patched replacedembly! Details:\n" + ex)); }
_cleanOsuModule.Dispose();
_obfOsuModule.Dispose();
#if DEBUG
Console.ReadKey(true);
#endif
#if LIVE_DEBUG
Process.Start(new ProcessStartInfo
{
FileName = "cmd",
Arguments = "/c timeout /T 1 /NOBREAK & move /Y \"osu!-osupatch.exe\" \"osu!.exe\"",
WorkingDirectory = Environment.CurrentDirectory,
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
UseShellExecute = false
});
#endif
return overallSuccess ? 0 : 1;
}
19
Source : Program.cs
with MIT License
from exys228
with MIT License
from exys228
public static int Main(string[] args)
{
if (args.Length < 2)
return XConsole.WriteLine("NameMapper.CLI - map names from replacedembly with deobfuscated names to replacedembly with obfuscated names\n" +
"by exys, 2019\n" +
"\n" +
"Usage:\n" +
"NameMapper.CLI [clean module] [obfuscated module]");
if (!File.Exists(_cleanModulePath = Path.GetFullPath(args[0])))
return XConsole.PrintError("Specified clean module path does not exist");
if (!File.Exists(_obfModulePath = Path.GetFullPath(args[1])))
return XConsole.PrintError("Specified obfuscated module path does not exist");
try
{
_cleanModule = ModuleDefMD.Load(_cleanModulePath, ModuleDef.CreateModuleContext());
_obfModule = ModuleDefMD.Load(_obfModulePath, ModuleDef.CreateModuleContext());
}
catch (Exception e) { return XConsole.PrintError("An error occurred while trying to load and process modules! Details:\n" + e); }
XConsole.PrintInfo($"Loaded modules: {_cleanModule.replacedembly.FullName} (clean); {_obfModule.replacedembly.FullName} (obfuscated).");
var fancyOut = new ConcurrentQueue<string>();
// ReSharper disable once FunctionNeverReturns
ThreadPool.QueueUserWorkItem(state =>
{
while (true)
{
if (!fancyOut.IsEmpty && fancyOut.TryDequeue(out string msg))
XConsole.Write(msg);
Thread.Sleep(1);
}
});
NameMapper nameMapper = new NameMapper(_cleanModule, _obfModule, fancyOut);
nameMapper.BeginProcessing();
string filename = Path.GetFileNameWithoutExtension(_obfModulePath) + "-nmapped" + Path.GetExtension(_obfModulePath);
XConsole.PrintInfo("Finally writing module back (with \"-nmapped\" tag)!");
_obfModule.Write(
Path.Combine(
Path.GetDirectoryName(_obfModulePath) ?? throw new NameMapperCliException("Path to write module to is null unexpectedly"), filename),
new ModuleWriterOptions(_obfModule)
{
MetadataOptions = { Flags = DEFAULT_METADATA_FLAGS }
});
Console.ReadKey(true);
return 0;
}
19
Source : Program.cs
with MIT License
from exys228
with MIT License
from exys228
public static int Main(string[] args)
{
if (args.Length < 1)
return XConsole.WriteLine("StringFixer.CLI\n" +
"by exys, 2019\n" +
"\n" +
"Usage:\n" +
"StringFixer.CLI [module]");
if (!File.Exists(_modulePath = Path.GetFullPath(args[0])))
return XConsole.PrintError("Specified module path does not exist");
try
{
_module = ModuleDefMD.Load(_modulePath);
_replacedembly = replacedembly.LoadFile(_modulePath);
}
catch (Exception e) { return XConsole.PrintError("An error occurred while trying to load and process modules! Details:\n" + e); }
XConsole.PrintInfo($"Loaded module: {_module.replacedembly.FullName}.");
StringFixer.Fix(_module, _replacedembly);
string filename = Path.GetFileNameWithoutExtension(_modulePath) + "-string" + Path.GetExtension(_modulePath);
XConsole.PrintInfo("Finally writing module back (with \"-string\" tag)!");
_module.Write(
Path.Combine(
Path.GetDirectoryName(_modulePath) ?? throw new StringFixerCliException("Path to write module to is null unexpectedly"), filename),
new ModuleWriterOptions(_module)
{
MetadataOptions = { Flags = DEFAULT_METADATA_FLAGS }
});
Console.ReadKey(true);
return 0;
}
19
Source : MultiplyMatrices.cs
with Apache License 2.0
from fancunwei
with Apache License 2.0
from fancunwei
private static void OfferToPrint(int rowCount, int colCount, double[,] matrix)
{
Console.Error.Write("Computation complete. Print results (y/n)? ");
char c = Console.ReadKey(true).KeyChar;
Console.Error.WriteLine(c);
if (Char.ToUpperInvariant(c) == 'Y')
{
if (!Console.IsOutputRedirected) Console.WindowWidth = 180;
Console.WriteLine();
for (int x = 0; x < rowCount; x++)
{
Console.WriteLine("ROW {0}: ", x);
for (int y = 0; y < colCount; y++)
{
Console.Write("{0:#.##} ", matrix[x, y]);
}
Console.WriteLine();
}
}
}
19
Source : Tui.cs
with Apache License 2.0
from fcrozetta
with Apache License 2.0
from fcrozetta
public bool DrawYesNo(ColorSchema schema = ColorSchema.Regular, string txtYes = "Yes", string txtNo = "No", bool defaultAnswer = false)
{
Draw(schema);
setColorSchema(schema);
bool answer = defaultAnswer;
int CursorYes = PosLeft + MarginLeft;
int CursorNo = PosLeft + Width - (2 * MarginLeft);
int Line = (PosTop + Height - MarginTop);
ConsoleKeyInfo keypress;
do
{
Console.SetCursorPosition(CursorYes + 1, Line);
Console.Write(txtYes);
Console.SetCursorPosition(CursorNo + 1, Line);
Console.Write(txtNo);
Console.SetCursorPosition(CursorYes, Line);
Console.Write(answer ? AnswerChar : EmptyChar);
Console.SetCursorPosition(CursorNo, Line);
Console.Write(!answer ? AnswerChar : EmptyChar);
keypress = Console.ReadKey(false);
if ((keypress.Key == ConsoleKey.LeftArrow) || (keypress.Key == ConsoleKey.RightArrow))
{
answer = !answer;
}
} while (keypress.Key != ConsoleKey.Enter);
setColorSchema(ColorSchema.Regular);
return answer;
}
19
Source : Tui.cs
with Apache License 2.0
from fcrozetta
with Apache License 2.0
from fcrozetta
public string DrawList(List<String> options, ColorSchema schema = ColorSchema.Regular)
{
Draw(schema);
setColorSchema(schema);
int Line = LastBodyHeight + MarginTop;
int tmpCursor = 0;
foreach (string s in options)
{
Console.SetCursorPosition(MarginLeft + PosLeft, Line);
System.Console.Write($" {s}");
Line++;
}
Line -= options.Count;
ConsoleKeyInfo keypress;
do
{
Console.SetCursorPosition(MarginLeft + PosLeft, Line + tmpCursor);
Console.Write(AnswerChar);
keypress = Console.ReadKey(true);
if (keypress.Key == ConsoleKey.UpArrow)
{
if (tmpCursor > 0)
{
Console.SetCursorPosition(MarginLeft + PosLeft, Line + tmpCursor);
Console.Write(EmptyChar);
tmpCursor--;
}
}
if (keypress.Key == ConsoleKey.DownArrow)
{
if (tmpCursor < options.Count - 1)
{
Console.SetCursorPosition(MarginLeft + PosLeft, Line + tmpCursor);
Console.Write(EmptyChar);
tmpCursor++;
}
}
} while (keypress.Key != ConsoleKey.Enter);
setColorSchema(ColorSchema.Regular);
return options[tmpCursor];
}
19
Source : Tui.cs
with Apache License 2.0
from fcrozetta
with Apache License 2.0
from fcrozetta
public void DrawBook(ColorSchema schema = ColorSchema.Regular, string txtNext = "next", string txtPrev = "previous", string txtDone = "Done", int defaultAnswer = 1)
{
setColorSchema(schema);
int answer = defaultAnswer;
int CursorPrev = PosLeft + MarginLeft;
int CursorDone = PosLeft + Width - (2 * MarginLeft);
int CursorNext = (PosLeft + Width) / 2;
int Line = (PosTop + Height - MarginTop);
int index = 0;
string oldreplacedle = replacedle;
List<string> pages = separatePages();
int totalPages = pages.Count();
Body = pages[0];
ConsoleKeyInfo keypress;
bool keepGoing = true;
while (keepGoing)
{
replacedle = oldreplacedle + $@" [ {index + 1}/{totalPages} ]";
Draw(schema);
Console.SetCursorPosition(CursorPrev + 1, Line);
Console.Write(txtPrev);
Console.SetCursorPosition(CursorNext + 1, Line);
Console.Write(txtNext);
Console.SetCursorPosition(CursorDone + 1, Line);
Console.Write(txtDone);
Console.SetCursorPosition(CursorPrev, Line);
Console.Write(answer == 0 ? AnswerChar : EmptyChar);
Console.SetCursorPosition(CursorNext, Line);
Console.Write(answer == 1 ? AnswerChar : EmptyChar);
Console.SetCursorPosition(CursorDone, Line);
Console.Write(answer == 2 ? AnswerChar : EmptyChar);
keypress = Console.ReadKey(false);
switch (keypress.Key)
{
case ConsoleKey.LeftArrow:
answer = answer - 1 >= 0 ? answer - 1 : 2;
break;
case ConsoleKey.RightArrow:
answer = answer + 1 <= 2 ? answer + 1 : 0;
break;
case ConsoleKey.Enter:
switch (answer)
{
case 0:
index = index - 1 >= 0 ? index - 1 : pages.Count() - 1;
break;
case 1:
index = index + 1 <= pages.Count() - 1 ? index + 1 : 0;
break;
case 2:
keepGoing = false;
break;
}
break;
}
Body = pages[index];
}
setColorSchema(ColorSchema.Regular);
}
19
Source : Tui.cs
with Apache License 2.0
from fcrozetta
with Apache License 2.0
from fcrozetta
public List<CheckBoxOption> DrawCheckBox(List<CheckBoxOption> options, ColorSchema schema = ColorSchema.Regular, bool onlyChecked = true)
{
Draw(schema);
setColorSchema(schema);
int Line = LastBodyHeight + MarginTop;
int tmpCursor = 0;
List<CheckBoxOption> TmpOptions = options;
//Continue Here
foreach (CheckBoxOption o in TmpOptions)
{
char tmpSelected = o.IsSelected ? SelectedChar : EmptyChar;
Console.SetCursorPosition(MarginLeft + PosLeft, Line);
System.Console.Write($" [{tmpSelected}] {o.Name} - {o.Description}");
Line++;
}
Line -= options.Count;
ConsoleKeyInfo keypress;
do
{
Console.SetCursorPosition(MarginLeft + PosLeft, Line + tmpCursor);
Console.Write(AnswerChar);
keypress = Console.ReadKey(true);
if (keypress.Key == ConsoleKey.UpArrow)
{
if (tmpCursor > 0)
{
Console.SetCursorPosition(MarginLeft + PosLeft, Line + tmpCursor);
Console.Write(EmptyChar);
tmpCursor--;
}
}
if (keypress.Key == ConsoleKey.DownArrow)
{
if (tmpCursor < TmpOptions.Count - 1)
{
Console.SetCursorPosition(MarginLeft + PosLeft, Line + tmpCursor);
Console.Write(EmptyChar);
tmpCursor++;
}
}
if (keypress.Key == ConsoleKey.Spacebar)
{
CheckBoxOption c = TmpOptions[tmpCursor];
c.IsSelected = !c.IsSelected;
char ch = c.IsSelected ? SelectedChar : EmptyChar;
Console.SetCursorPosition(MarginLeft + 2 + PosLeft, Line + tmpCursor);
TmpOptions[tmpCursor] = c;
Console.Write(ch);
}
} while (keypress.Key != ConsoleKey.Enter);
if (onlyChecked)
{
TmpOptions = (from t in TmpOptions where t.IsSelected select t).ToList();
}
setColorSchema(ColorSchema.Regular);
return TmpOptions;
}
19
Source : PhysicalConsole.cs
with MIT License
from filipnavara
with MIT License
from filipnavara
private void ListenToConsoleKeyPress()
{
Task.Factory.StartNew(() =>
{
while (true)
{
var key = Console.ReadKey(intercept: true);
for (var i = 0; i < _keyPressedListeners.Count; i++)
{
_keyPressedListeners[i](key);
}
}
}, TaskCreationOptions.LongRunning);
}
19
Source : Program.cs
with Apache License 2.0
from FoundatioFx
with Apache License 2.0
from FoundatioFx
private static void MonitorKeyPress() {
Task.Run(() => {
while (_isRunning)
{
while (!Console.KeyAvailable) {
SystemClock.Sleep(250);
}
var key = Console.ReadKey(true).Key;
HandleKey(key);
}
});
}
19
Source : Program.cs
with GNU General Public License v3.0
from Foxlider
with GNU General Public License v3.0
from Foxlider
private static void ShowMainMenu()
{
Console.WriteLine("\n\n" +
" [ MAIN MENU ]\n" +
"1. FASTER settings backup\n" +
"2. SteamCMD Cleanup\n" +
"3. Set Install Environment Variable\n" +
"4.\n" +
"5. Migration to FASTER 1.7\n" +
"\n0. Quit\n");
ConsoleKey rk = Console.ReadKey(true).Key;
switch (rk)
{
case ConsoleKey.D0:
case ConsoleKey.NumPad0:
_exitCode = 0;
return;
case ConsoleKey.D1:
case ConsoleKey.NumPad1:
BackupSettings();
return;
case ConsoleKey.D2:
case ConsoleKey.NumPad2:
SteamCmdCleanup();
return;
case ConsoleKey.D3:
case ConsoleKey.NumPad3:
SetEnvVar();
return;
case ConsoleKey.D5:
case ConsoleKey.NumPad5:
MigrateTo17();
return;
default:
return;
}
}
19
Source : Program.cs
with GNU General Public License v3.0
from Foxlider
with GNU General Public License v3.0
from Foxlider
private static void MigrateTo17()
{
var sourcePath = Path.Combine(Environment.GetEnvironmentVariable("LocalAppData") ?? throw new InvalidOperationException(), "FoxliCorp", "FASTER_StrongName_r3kmcr0zqf35dnhwrlga5cvn2azjfziz");
var versions = Directory.GetDirectories(sourcePath).ToList();
Console.WriteLine("Select your version to update from");
foreach (var path in versions)
{
var version = path.Replace(sourcePath, "").Replace("\\", "");
if(version.StartsWith("1.7"))
continue;
Console.WriteLine($"{versions.IndexOf(path)} : v{version} ({Directory.GetLastWriteTime(path):dd:MM::yyyy}");
}
var key = Console.ReadKey(true).KeyChar;
switch (key)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
var selected = versions[int.Parse(key.ToString())];
if (selected == null || selected.Contains("1.7.")) return;
Console.WriteLine("\n\nDo you want to backup your data ? (Y/n)");
var backupKey = Console.ReadKey(true).Key;
if (backupKey != ConsoleKey.N)
{
BackupSettings();
if(_exitCode == 0)
_exitCode = -1;
else
return;
}
Console.WriteLine("Press any key to start the migration process...");
Console.ReadKey();
Console.WriteLine("Migrating...");
XmlSerializer serializer16 = new XmlSerializer(typeof(Models._16Models.Configuration));
XmlSerializer serializer17 = new XmlSerializer(typeof(Models._17Models.Configuration));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
Models._16Models.Configuration conf16;
Models._17Models.Configuration conf17 = new Models._17Models.Configuration();
using (Stream reader = new FileStream($"{selected}\\user.config", FileMode.Open))
{
// Call the Deserialize method to restore the object's state.
conf16 = (Models._16Models.Configuration) serializer16.Deserialize(reader);
}
Console.WriteLine($"\tRead config from '{selected}\\user.config'");
var servers = conf16.UserSettings.Settings.Setting.FirstOrDefault(s => s.Name == "Servers");
conf16.UserSettings.Settings.Setting.Remove(servers);
conf17.UserSettings = new Models._17Models.UserSettings { Settings = new Models._17Models.Settings { Setting = conf16.UserSettings.Settings.Setting } };
Console.WriteLine("\tConverted standard values to 1.7");
Debug.replacedert(servers != null, nameof(servers) + " != null");
var node = ((XmlNode[]) servers.Value)[0];
var ser = new XmlSerializer(typeof(ServerCollection));
MemoryStream stm = new MemoryStream();
StreamWriter stw = new StreamWriter(stm);
stw.Write(node.OuterXml);
stw.Flush();
stm.Position = 0;
ServerCollection collec = ser.Deserialize(stm) as ServerCollection;
Console.WriteLine("\tExtracted profiles");
var newProfiles = new List<FASTER.Models.ServerProfile>();
Debug.replacedert(collec != null, nameof(collec) + " != null");
foreach (var profile in collec.ServerProfile)
{
var newProfile = ConvertProfile(profile);
newProfiles.Add(newProfile);
}
conf17.UserSettings.Settings.Setting.Add(new Setting
{
Name = "Profiles",
SerializeAs = "Xml",
Value = new Value
{
ArrayOfServerProfile = new ArrayOfServerProfile
{
ServerProfile = newProfiles
}
}
});
Console.WriteLine("\tAdded new profiles to settings");
Console.WriteLine("Started serialization process...");
using (MemoryStream stream = new MemoryStream())
using (XmlTextWriter tw = new XmlTextWriter( stream, Encoding.UTF8))
{
tw.Formatting = Formatting.Indented;
tw.Indentation = 4;
serializer17.Serialize(tw, conf17, ns);
tw.BaseStream.Position = 0;
Console.WriteLine("Serialization process complete.");
using StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
string output = Path.Combine(sourcePath, "1.7.1.0");
if (!Directory.Exists(output))
Directory.CreateDirectory(output);
File.WriteAllText(Path.Combine(output, "user.config"), text);
Console.WriteLine($"Settings were written to {output}\\user.config");
}
_exitCode = 0;
break;
default :
Console.WriteLine("Invalid selection.");
break;
}
}
19
Source : Program.cs
with GNU Affero General Public License v3.0
from FrankTheBoxMonster
with GNU Affero General Public License v3.0
from FrankTheBoxMonster
public static void Pause() {
Console.WriteLine("Press any key to continue . . .");
Console.ReadKey(true);
}
19
Source : ConsoleHelpers.cs
with BSD 3-Clause Clear License
from Fs00
with BSD 3-Clause Clear License
from Fs00
public static void FlushStandardInput()
{
while (Console.KeyAvailable)
Console.ReadKey(intercept: true);
}
19
Source : Program.cs
with MIT License
from fuse-open
with MIT License
from fuse-open
public static void Main(string[] args)
{
using (new Timer("Loading solution... ")) {
solution = new Solution(SolutionFile);
}
Console.WriteLine("Loaded {0} lines of code ({1:f1} MB) in {2} files in {3} projects.",
solution.AllFiles.Sum(f => 1 + f.OriginalText.Count(c => c == '\n')),
solution.AllFiles.Sum(f => f.OriginalText.Length) / 1024.0 / 1024.0,
solution.AllFiles.Count(),
solution.Projects.Count);
//VisitorBenchmark.Run(solution.AllFiles.Select(f => f.SyntaxTree));
using (new Timer("ID String test... ")) TypeSystemTests.IDStringConsistencyCheck(solution);
using (new Timer("Resolve unresolved members... ")) TypeSystemTests.ResolvedUnresolvedMembers(solution);
//RunTestOnAllFiles("Roundtripping test", RoundtripTest.RunTest);
RunTestOnAllFiles("Resolver test", ResolverTest.RunTest);
RunTestOnAllFiles("Resolver test (no parsed file)", ResolverTest.RunTestWithoutUnresolvedFile);
RunTestOnAllFiles("Resolver test (randomized order)", RandomizedOrderResolverTest.RunTest);
new FindReferencesConsistencyCheck(solution).Run();
RunTestOnAllFiles("Pattern Matching test", PatternMatchingTest.RunTest);
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
19
Source : CSharpAmbienceTests.cs
with MIT License
from fuse-open
with MIT License
from fuse-open
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
19
Source : PreviewCommand.cs
with MIT License
from fuse-open
with MIT License
from fuse-open
public override void Run(string[] args, CancellationToken ct)
{
try
{
RunInternal(args);
}
catch (ExitWithError e)
{
if (_promtOnError)
{
Console.WriteLine("fuse: " + e.ErrorOutput);
Console.WriteLine("Press any key to exit.");
Console.ReadKey(true);
}
throw;
}
catch (Exception e)
{
if (_promtOnError)
{
Console.WriteLine("fuse: unhandled exception: " + e.Message);
Console.WriteLine(e.StackTrace);
Console.WriteLine("Press any key to exit.");
Console.ReadKey(true);
}
throw;
}
}
19
Source : Program.cs
with MIT License
from gebirgslok
with MIT License
from gebirgslok
static async Task Main()
{
BricklinkClientConfiguration.Instance.TokenValue = "<Your Token>";
BricklinkClientConfiguration.Instance.TokenSecret = "<Your Token Secret>";
BricklinkClientConfiguration.Instance.ConsumerKey = "<Your Consumer Key>";
BricklinkClientConfiguration.Instance.ConsumerSecret = "<Your Consumer Secret>";
await CatalogDemos.GereplacedemImageDemo();
CatalogDemos.GetPartImageForColorDemo();
CatalogDemos.GetBookImageDemo();
CatalogDemos.GetGearImageDemo();
CatalogDemos.GetCatalogImageDemo();
CatalogDemos.GetInstructionImageDemo();
CatalogDemos.GetOriginalBoxImageDemo();
CatalogDemos.EnsureImageUrlSchemeDemo();
await CatalogDemos.GereplacedemDemo();
await CatalogDemos.GetSupersetsDemo();
await CatalogDemos.GetSupersetsDemo2();
await CatalogDemos.GetSubsetsDemo();
await CatalogDemos.GetPriceGuideDemo();
await CatalogDemos.GetKnownColorsDemo();
await ColorDemos.GetColorListDemo();
await ColorDemos.GetColorDemo();
await CategoryDemos.GetCategoryListDemo();
await CategoryDemos.GetCategoryDemo();
await InventoryDemos.CreateInventoriesDemo();
var inventory = await InventoryDemos.CreateInventoryDemo();
await InventoryDemos.UpdatedInventoryDemo(inventory.InventoryId);
await InventoryDemos.DeleteInventoryDemo(inventory.InventoryId);
await InventoryDemos.GetInventoryListDemo();
await ItemMappingDemos.GetElementIdDemo();
await ItemMappingDemos.GereplacedemNumberDemo();
var shippingMethods = await SettingDemos.GetShippingMethodListDemo();
var id = shippingMethods.First().MethodId;
await SettingDemos.GetShippingMethodDemo(id);
await PushNotificationDemos.GetNotificationsDemo();
await MemberDemos.GetMemberRatingDemo();
await FeedbackDemos.GetFeedbackListDemo();
await FeedbackDemos.GetFeedbackDemo();
var orderId = 123456789; //replace with a valid order ID.
await FeedbackDemos.PostFeedbackDemo(orderId);
var feedbackId = 123456789; //replace with a valid feedback ID.
await FeedbackDemos.ReplyFeedbackDemo(feedbackId);
await OrderDemos.GetOrdersDemo();
await OrderDemos.GetOrderDemo();
await OrderDemos.GetOrderItemsDemo();
await OrderDemos.GetOrderMessagesDemo();
await OrderDemos.GetOrderFeedbackDemo();
await OrderDemos.UpdateOrderStatusDemo();
await OrderDemos.UpdatePaymentStatusDemo();
await OrderDemos.UpdateOrderDemo();
await CouponDemos.GetCouponsDemo();
var couponId = 123456789; //Must be a valid coupon ID.
await CouponDemos.GetCouponDemo(couponId);
await CouponDemos.DeleteCouponDemo(couponId);
await CouponDemos.CreateCouponDemo();
await CouponDemos.UpdateCouponDemo(couponId);
await PartOutValueDemos.GetPartOutValueFromPageDemo();
Console.ReadKey(true);
}
19
Source : ConsoleProfileSetup.cs
with MIT License
from Genbox
with MIT License
from Genbox
public IProfile SetupProfile(string profileName, bool persist = true)
{
IProfile? existingProfile = _profileManager.GetProfile(profileName);
if (existingProfile != null)
return existingProfile;
start:
string enteredKeyId = GetKeyId();
byte[] accessKey = GetAccessKey();
IRegionInfo region = GetRegion();
Console.WriteLine();
Console.WriteLine("Please confirm the following information:");
Console.WriteLine("Key id: " + enteredKeyId);
Console.WriteLine("Region: " + region.Code + " -- " + region.Name);
Console.WriteLine();
ConsoleKey key;
do
{
Console.WriteLine("Is it correct? Y/N");
key = Console.ReadKey(true).Key;
} while (key != ConsoleKey.Y && key != ConsoleKey.N);
if (key == ConsoleKey.N)
goto start;
IProfile profile = _profileManager.CreateProfile(profileName, enteredKeyId, accessKey, region.Code, persist);
if (persist)
{
if (!string.IsNullOrEmpty(profile.Location))
Console.WriteLine("Successfully saved the profile to " + profile.Location);
else
Console.WriteLine("Successfully saved profile");
}
//Clear the access key from memory
Array.Clear(accessKey, 0, accessKey.Length);
return profile;
}
19
Source : ConsoleHelper.cs
with MIT License
from Genbox
with MIT License
from Genbox
public static char[] ReadSecret(int expectedLength = 12)
{
List<char> preplaced = new List<char>(expectedLength);
do
{
ConsoleKeyInfo key = Console.ReadKey(true);
if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter && key.Key != ConsoleKey.Escape)
{
preplaced.Add(key.KeyChar);
Console.Write("*");
}
else
{
if (key.Key == ConsoleKey.Backspace && preplaced.Count > 0)
{
preplaced.RemoveAt(preplaced.Count - 1);
Console.Write("\b \b");
}
else if (key.Key == ConsoleKey.Enter)
{
Console.WriteLine();
break;
}
else if (key.Key == ConsoleKey.Escape)
{
while (preplaced.Count > 0)
{
preplaced.RemoveAt(preplaced.Count - 1);
Console.Write("\b \b");
}
}
}
} while (true);
return preplaced.ToArray();
}
19
Source : Program.cs
with MIT License
from Genbox
with MIT License
from Genbox
private static async Task Main(string[] args)
{
S3Provider s3Provider = UtilityHelper.SelectProvider();
Console.WriteLine();
string profileName = UtilityHelper.GetProfileName(s3Provider);
Console.WriteLine("This program will delete all buckets beginning with 'testbucket-'. Are you sure? Y/N");
ConsoleKeyInfo key = Console.ReadKey(true);
if (key.KeyChar != 'y')
return;
using ServiceProvider provider = UtilityHelper.CreateSimpleS3(s3Provider, profileName, true);
IProfile profile = UtilityHelper.GetOrSetupProfile(provider, s3Provider, profileName);
ISimpleClient client = provider.GetRequiredService<ISimpleClient>();
await foreach (S3Bucket bucket in ListAllBucketsAsync(client))
{
if (!UtilityHelper.IsTestBucket(bucket.BucketName, profile) && !UtilityHelper.IsTemporaryBucket(bucket.BucketName))
continue;
Console.Write(bucket.BucketName);
int errors = await UtilityHelper.ForceDeleteBucketAsync(s3Provider, client, bucket.BucketName);
if (errors == 0)
{
Console.Write(" [x] emptied ");
DeleteBucketResponse delBucketResp = await client.DeleteBucketAsync(bucket.BucketName).ConfigureAwait(false);
if (delBucketResp.IsSuccess)
Console.Write("[x] deleted");
else
Console.Write("[ ] deleted");
}
else
Console.Write(" [ ] emptied [ ] deleted");
Console.WriteLine();
}
}
19
Source : UtilityHelper.cs
with MIT License
from Genbox
with MIT License
from Genbox
public static S3Provider SelectProvider()
{
ConsoleKeyInfo key;
int intVal = 0;
S3Provider[] enumValues = Enum.GetValues<S3Provider>();
//Skip 'unknown' and 'all'
S3Provider[] choices = enumValues.Skip(1).Take(enumValues.Length - 2).ToArray();
do
{
Console.WriteLine("Please select which provider you want to use:");
for (int i = 0; i < choices.Length; i++)
{
Console.WriteLine($"{i + 1}. {choices[i]}");
}
key = Console.ReadKey(true);
} while (!choices.Any(x => int.TryParse(key.KeyChar.ToString(), out intVal) && intVal >= 0 && intVal <= choices.Length));
return choices[intVal - 1];
}
See More Examples