Here are the examples of the csharp api System.Runtime.CompilerServices.TaskAwaiter.GetResult() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
3955 Examples
19
View Source File : WebUserManager.cs
License : Apache License 2.0
Project Creator : 0xFireball
License : Apache License 2.0
Project Creator : 0xFireball
private RegisteredUser RegisterUser(RegistrationRequest regRequest)
{
RegisteredUser newUserRecord = null;
if (FindUserByUsernameAsync(regRequest.Username).GetAwaiter().GetResult() != null)
{
//BAD! Another conflicting user exists!
throw new SecurityException("A user with the same username already exists!");
}
var db = new DatabaseAccessService().OpenOrCreateDefault();
var registeredUsers = db.GetCollection<RegisteredUser>(DatabaseAccessService.UsersCollectionDatabaseKey);
using (var trans = db.BeginTrans())
{
// Calculate cryptographic info
var cryptoConf = PreplacedwordCryptoConfiguration.CreateDefault();
var cryptoHelper = new AuthCryptoHelper(cryptoConf);
var pwSalt = cryptoHelper.GenerateSalt();
var encryptedPreplacedword =
cryptoHelper.CalculateUserPreplacedwordHash(regRequest.Preplacedword, pwSalt);
// Create user
newUserRecord = new RegisteredUser
{
Identifier = Guid.NewGuid().ToString(),
Username = regRequest.Username,
ApiKey = StringUtils.SecureRandomString(AuthCryptoHelper.DefaultApiKeyLength),
Crypto = new ItemCrypto
{
Salt = pwSalt,
Conf = cryptoConf,
Key = encryptedPreplacedword
},
StorageQuota = ServerContext.Configuration.DefaultQuota
};
// Add the user to the database
registeredUsers.Insert(newUserRecord);
// Index database
registeredUsers.EnsureIndex(x => x.Identifier);
registeredUsers.EnsureIndex(x => x.ApiKey);
registeredUsers.EnsureIndex(x => x.Username);
trans.Commit();
}
return newUserRecord;
}
19
View Source File : Client.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 0xthirteen
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 0xthirteen
public void CreateRdpConnection(string server, string user, string domain, string preplacedword, string command, string execw, string runelevated, bool condrive, bool tover, bool nla)
{
keycode = new Dictionary<String, Code>();
KeyCodes();
runtype = runelevated;
isdrive = condrive;
cmd = command;
target = server;
execwith = execw;
takeover = tover;
networkauth = nla;
void ProcessTaskThread()
{
var form = new Form();
form.Opacity = 0;
form.Visible = false;
form.WindowState = FormWindowState.Minimized;
form.ShowInTaskbar = false;
form.FormBorderStyle = FormBorderStyle.None;
form.Width = Screen.PrimaryScreen.WorkingArea.Width;
form.Height = Screen.PrimaryScreen.WorkingArea.Height;
form.Load += (sender, args) =>
{
var rdpConnection = new AxMsRdpClient9NotSafeForScripting();
form.Controls.Add(rdpConnection);
var rdpC = rdpConnection.GetOcx() as IMsRdpClientNonScriptable5;
IMsRdpExtendedSettings rdpc2 = rdpConnection.GetOcx() as IMsRdpExtendedSettings;
rdpC.AllowPromptingForCredentials = false;
rdpC.AllowCredentialSaving = false;
rdpConnection.Server = server;
rdpConnection.Domain = domain;
rdpConnection.UserName = user;
rdpConnection.AdvancedSettings9.allowBackgroundInput = 1;
rdpConnection.AdvancedSettings9.BitmapPersistence = 0;
if(condrive == true)
{
rdpConnection.AdvancedSettings5.RedirectDrives = true;
}
if (preplacedword != string.Empty || user != string.Empty)
{
rdpConnection.UserName = user;
rdpConnection.AdvancedSettings9.ClearTextPreplacedword = preplacedword;
}
else
{
rdpc2.set_Property("RestrictedLogon", true);
rdpc2.set_Property("DisableCredentialsDelegation", true);
}
rdpConnection.AdvancedSettings9.EnableCredSspSupport = true;
if(networkauth == true)
{
rdpC.NegotiateSecurityLayer = true;
}
if (true)
{
rdpConnection.OnDisconnected += RdpConnectionOnOnDisconnected;
rdpConnection.OnLoginComplete += RdpConnectionOnOnLoginComplete;
rdpConnection.OnLogonError += RdpConnectionOnOnLogonError;
}
rdpConnection.Connect();
rdpConnection.Enabled = false;
rdpConnection.Dock = DockStyle.Fill;
Application.Run(form);
};
form.Show();
}
var rdpClientThread = new Thread(ProcessTaskThread) { IsBackground = true };
rdpClientThread.SetApartmentState(ApartmentState.STA);
rdpClientThread.Start();
while (rdpClientThread.IsAlive)
{
Task.Delay(500).GetAwaiter().GetResult();
}
}
19
View Source File : Client.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 0xthirteen
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 0xthirteen
private void RdpConnectionOnOnLogonError(object sender, IMsTscAxEvents_OnLogonErrorEvent e)
{
LogonErrorCode = e.lError;
var errorstatus = Enum.GetName(typeof(LogonErrors), (uint)LogonErrorCode);
Console.WriteLine("[-] Logon Error : {0} - {1}", LogonErrorCode, errorstatus);
Thread.Sleep(1000);
if(LogonErrorCode == -5 && takeover == true)
{
// it doesn't go to the logon event, so this has to be done here
var rdpSession = (AxMsRdpClient9NotSafeForScripting)sender;
Thread.Sleep(1000);
keydata = (IMsRdpClientNonScriptable)rdpSession.GetOcx();
Console.WriteLine("[+] Another user is logged on, asking to take over session");
SendElement("Tab");
Thread.Sleep(500);
SendElement("Enter+down");
Thread.Sleep(500);
SendElement("Enter+up");
Thread.Sleep(500);
Console.WriteLine("[+] Sleeping for 30 seconds");
Task.Delay(31000).GetAwaiter().GetResult();
Marshal.ReleaseComObject(rdpSession);
Marshal.ReleaseComObject(keydata);
}
else if (LogonErrorCode != -2)
{
Environment.Exit(0);
}
}
19
View Source File : Client.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 0xthirteen
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 0xthirteen
private void RdpConnectionOnOnLoginComplete(object sender, EventArgs e)
{
var rdpSession = (AxMsRdpClient9NotSafeForScripting)sender;
Console.WriteLine("[+] Connected to : {0}", target);
Thread.Sleep(1000);
keydata = (IMsRdpClientNonScriptable)rdpSession.GetOcx();
if (LogonErrorCode == -2)
{
Console.WriteLine("[+] User not currently logged in, creating new session");
Task.Delay(10000).GetAwaiter().GetResult();
}
string privinfo = "non-elevated";
if (runtype != string.Empty)
{
privinfo = "elevated";
}
Console.WriteLine("[+] Execution priv type : {0}", privinfo);
Thread.Sleep(1000);
SendElement("Win+R+down");
Thread.Sleep(500);
SendElement("Win+R+up");
Thread.Sleep(1000);
if (execwith == "cmd")
{
RunConsole("cmd.exe");
}
else if (execwith == "powershell" || execwith == "ps")
{
RunConsole("powershell.exe");
}
else
{
RunRun();
}
Thread.Sleep(1000);
Console.WriteLine("[+] Disconnecting from : {0}", target);
rdpSession.Disconnect();
}
19
View Source File : Program.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
static async Task<int> Main(string[] args)
{
Log.Info("PS3 Disc Dumper v" + Dumper.Version);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && Console.WindowHeight < 1 && Console.WindowWidth < 1)
try
{
Log.Error("Looks like there's no console present, restarting...");
var launchArgs = Environment.GetCommandLineArgs()[0];
if (launchArgs.Contains("/var/tmp") || launchArgs.EndsWith(".dll"))
{
Log.Debug("Looks like we were launched from a single executable, looking for the parent...");
using var currentProcess = Process.GetCurrentProcess();
var pid = currentProcess.Id;
var procCmdlinePath = Path.Combine("/proc", pid.ToString(), "cmdline");
launchArgs = File.ReadAllLines(procCmdlinePath).FirstOrDefault()?.TrimEnd('\0');
}
Log.Debug($"Using cmdline '{launchArgs}'");
launchArgs = $"-e bash -c {launchArgs}";
var startInfo = new ProcessStartInfo("x-terminal-emulator", launchArgs);
using var proc = Process.Start(startInfo);
if (proc.WaitForExit(1_000))
{
if (proc.ExitCode != 0)
{
startInfo = new ProcessStartInfo("xdg-terminal", launchArgs);
using var proc2 = Process.Start(startInfo);
if (proc2.WaitForExit(1_000))
{
if (proc2.ExitCode != 0)
{
startInfo = new ProcessStartInfo("gnome-terminal", launchArgs);
using var proc3 = Process.Start(startInfo);
if (proc3.WaitForExit(1_000))
{
if (proc3.ExitCode != 0)
{
startInfo = new ProcessStartInfo("konsole", launchArgs);
using var _ = Process.Start(startInfo);
}
}
}
}
}
}
return -2;
}
catch (Exception e)
{
Log.Error(e);
return -3;
}
var lastDiscId = "";
start:
const string replacedleBase = "PS3 Disc Dumper";
var replacedle = replacedleBase;
Console.replacedle = replacedle;
var output = ".";
var inDir = "";
var showHelp = false;
var options = new OptionSet
{
{
"i|input=", "Path to the root of blu-ray disc mount", v =>
{
if (v is string ind)
inDir = ind;
}
},
{
"o|output=", "Path to the output folder. Subfolder for each disc will be created automatically", v =>
{
if (v is string outd)
output = outd;
}
},
{
"?|h|help", "Show help", v =>
{
if (v != null)
showHelp = true;
},
true
},
};
try
{
var unknownParams = options.Parse(args);
if (unknownParams.Count > 0)
{
Log.Warn("Unknown parameters: ");
foreach (var p in unknownParams)
Log.Warn("\t" + p);
showHelp = true;
}
if (showHelp)
{
ShowHelp(options);
return 0;
}
var dumper = new Dumper(ApiConfig.Cts);
dumper.DetectDisc(inDir);
await dumper.FindDiscKeyAsync(ApiConfig.IrdCachePath).ConfigureAwait(false);
if (string.IsNullOrEmpty(dumper.OutputDir))
{
Log.Info("No compatible disc was found, exiting");
return 2;
}
if (lastDiscId == dumper.ProductCode)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("You're dumping the same disc, are you sure you want to continue? (Y/N, default is N)");
Console.ResetColor();
var confirmKey = Console.ReadKey(true);
switch (confirmKey.Key)
{
case ConsoleKey.Y:
break;
default:
throw new OperationCanceledException("Aborting re-dump of the same disc");
}
}
lastDiscId = dumper.ProductCode;
replacedle += " - " + dumper.replacedle;
var monitor = new Thread(() =>
{
try
{
do
{
if (dumper.CurrentSector > 0)
Console.replacedle = $"{replacedle} - File {dumper.CurrentFileNumber} of {dumper.TotalFileCount} - {dumper.CurrentSector * 100.0 / dumper.TotalSectors:0.00}%";
Task.Delay(1000, ApiConfig.Cts.Token).GetAwaiter().GetResult();
} while (!ApiConfig.Cts.Token.IsCancellationRequested);
}
catch (TaskCanceledException)
{
}
Console.replacedle = replacedle;
});
monitor.Start();
await dumper.DumpAsync(output).ConfigureAwait(false);
ApiConfig.Cts.Cancel(false);
monitor.Join(100);
if (dumper.BrokenFiles.Count > 0)
{
Log.Fatal("Dump is not valid");
foreach (var file in dumper.BrokenFiles)
Log.Error($"{file.error}: {file.filename}");
}
else
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Dump is valid");
Console.ResetColor();
}
}
catch (OptionException)
{
ShowHelp(options);
return 1;
}
catch (Exception e)
{
Log.Error(e, e.Message);
}
Console.WriteLine("Press X or Ctrl-C to exit, any other key to start again...");
var key = Console.ReadKey(true);
switch (key.Key)
{
case ConsoleKey.X:
return 0;
default:
goto start;
}
}
19
View Source File : MainForm.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
private void DumpDisc(object sender, DoWorkEventArgs doWorkEventArgs)
{
var backgroundWorker = (BackgroundWorker)sender;
var dumper = (Dumper)doWorkEventArgs.Argument;
try
{
var threadCts = new CancellationTokenSource();
var combinedToken = CancellationTokenSource.CreateLinkedTokenSource(threadCts.Token, dumper.Cts.Token);
var monitor = new Thread(() =>
{
try
{
do
{
if (dumper.TotalSectors > 0 && backgroundWorker.IsBusy && !backgroundWorker.CancellationPending)
try { backgroundWorker.ReportProgress((int)(dumper.CurrentSector * 10000L / dumper.TotalSectors), dumper); } catch { }
Task.Delay(1000, combinedToken.Token).GetAwaiter().GetResult();
} while (!combinedToken.Token.IsCancellationRequested);
}
catch (TaskCanceledException)
{
}
});
monitor.Start();
dumper.DumpAsync(settings.OutputDir).Wait(dumper.Cts.Token);
threadCts.Cancel();
monitor.Join(100);
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Disc dumping error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
doWorkEventArgs.Result = dumper;
}
19
View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
static void Main(string[] args)
{
try
{
RunAsync().GetAwaiter().GetResult();
}
catch (Exception ex)
{
//Console.ForegroundColor = ConsoleColor.Red;
//Console.WriteLine(ex.Message);
//Console.ResetColor();
}
//Console.WriteLine("Press any key to exit");
//Console.ReadKey();
}
19
View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r
static void Main(string[] args)
{
try
{
RunAsync().GetAwaiter().GetResult();
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
Console.ResetColor();
}
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
19
View Source File : Program.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
static void Main(string[] args)
{
if (args == null || args.Length < 1)
{
Console.WriteLine("DiscordChatBotServer.exe BotToken [PathToLog]");
return;
}
if (args.Length == 2)
{
Loger.PathLog = args[1];
}
else
{
Loger.PathLog = Environment.CurrentDirectory;
}
new Program().RunBotAsync(args[0]).GetAwaiter().GetResult();
}
19
View Source File : Program.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static int Main(string[] args)
{
// Add environment variables from .env file
LoadAndSetEnv();
using (HostContext context = new HostContext("Runner"))
{
return MainAsync(context, args).GetAwaiter().GetResult();
}
}
19
View Source File : Program.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static int Main(string[] args)
{
using (HostContext context = new HostContext("Worker"))
{
return MainAsync(context, args).GetAwaiter().GetResult();
}
}
19
View Source File : TaskExtensions.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[AsyncFixer.BlockCaller]
public static void SyncResult(this Task task)
{
// NOTE: GetResult() on TaskAwaiter uses ExceptionDispatchInfo.Throw if there
// is an exception, which preserves the original call stack and does not use
// AggregateException (unless explicitly thrown by the caller).
task.GetAwaiter().GetResult();
}
19
View Source File : TaskExtensions.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[AsyncFixer.BlockCaller]
public static T SyncResult<T>(this Task<T> task)
{
// NOTE: GetResult() on TaskAwaiter uses ExceptionDispatchInfo.Throw if there
// is an exception, which preserves the original call stack and does not use
// AggregateException (unless explicitly thrown by the caller).
return task.GetAwaiter().GetResult();
}
19
View Source File : TaskExtensions.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[AsyncFixer.BlockCaller]
public static HttpResponseMessage SyncResult(this Task<HttpResponseMessage> task)
{
// NOTE: This is effectively the same as <see cref="TaskExtensions.SyncResult(Task{T})"/>,
// but currently remains to support binary compatibility.
// NOTE: GetResult() on TaskAwaiter uses ExceptionDispatchInfo.Throw if there
// is an exception, which preserves the original call stack and does not use
// AggregateException (unless explicitly thrown by the caller).
return task.GetAwaiter().GetResult();
}
19
View Source File : SearchAutomation.cs
License : MIT License
Project Creator : ADeltaX
License : MIT License
Project Creator : ADeltaX
public static bool Execute()
{
if (IsRunning)
return false;
try
{
Console.WriteLine($"[{DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")}] Doing searches.");
IsRunning = true;
SearchRun(EdgeUpdate.Canary_Win_x86, "Canary (x86)").GetAwaiter().GetResult();
SearchRun(EdgeUpdate.Canary_Win_x64, "Canary (x64)").GetAwaiter().GetResult();
SearchRun(EdgeUpdate.Canary_Win_arm64, "Canary (ARM64)").GetAwaiter().GetResult();
SearchRun(EdgeUpdate.Dev_Win_x86, "Dev (x86)").GetAwaiter().GetResult();
SearchRun(EdgeUpdate.Dev_Win_x64, "Dev (x64)").GetAwaiter().GetResult();
SearchRun(EdgeUpdate.Dev_Win_arm64, "Dev (ARM64)").GetAwaiter().GetResult();
SearchRun(EdgeUpdate.Beta_Win_x86, "Beta (x86)").GetAwaiter().GetResult();
SearchRun(EdgeUpdate.Beta_Win_x64, "Beta (x64)").GetAwaiter().GetResult();
SearchRun(EdgeUpdate.Beta_Win_arm64, "Beta (ARM64)").GetAwaiter().GetResult();
SearchRun(EdgeUpdate.Stable_Win_x86, "Stable (x86)").GetAwaiter().GetResult();
SearchRun(EdgeUpdate.Stable_Win_x64, "Stable (x64)").GetAwaiter().GetResult();
SearchRun(EdgeUpdate.Stable_Win_arm64, "Stable (ARM64)").GetAwaiter().GetResult();
IsRunning = false;
Console.WriteLine($"[{DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")}] Finished doing searches.");
return true;
}
catch (Exception ex)
{
//RIP
Console.WriteLine($"[Error] {ex.Message}");
SharedDBcmd.TraceError($"Internal error: {ex.Message}");
IsRunning = false;
return false;
}
}
19
View Source File : RazorEngineCompiledTemplate.cs
License : MIT License
Project Creator : adoconnection
License : MIT License
Project Creator : adoconnection
public void SaveToStream(Stream stream)
{
this.SaveToStreamAsync(stream).GetAwaiter().GetResult();
}
19
View Source File : RazorEngineCompiledTemplateT.cs
License : MIT License
Project Creator : adoconnection
License : MIT License
Project Creator : adoconnection
public void SaveToFile(string fileName)
{
this.SaveToFileAsync(fileName).GetAwaiter().GetResult();
}
19
View Source File : RazorEngineCompiledTemplateT.cs
License : MIT License
Project Creator : adoconnection
License : MIT License
Project Creator : adoconnection
public string Run(Action<T> initializer)
{
return this.RunAsync(initializer).GetAwaiter().GetResult();
}
19
View Source File : RazorEngineTemplateBase.cs
License : MIT License
Project Creator : adoconnection
License : MIT License
Project Creator : adoconnection
public void WriteLiteral(string literal = null)
{
WriteLiteralAsync(literal).GetAwaiter().GetResult();
}
19
View Source File : RazorEngineTemplateBase.cs
License : MIT License
Project Creator : adoconnection
License : MIT License
Project Creator : adoconnection
public void Write(object obj = null)
{
WriteAsync(obj).GetAwaiter().GetResult();
}
19
View Source File : RazorEngineTemplateBase.cs
License : MIT License
Project Creator : adoconnection
License : MIT License
Project Creator : adoconnection
public void BeginWriteAttribute(string name, string prefix, int prefixOffset, string suffix, int suffixOffset,
int attributeValuesCount)
{
BeginWriteAttributeAsync(name, prefix, prefixOffset, suffix, suffixOffset, attributeValuesCount).GetAwaiter().GetResult();
}
19
View Source File : RazorEngineTemplateBase.cs
License : MIT License
Project Creator : adoconnection
License : MIT License
Project Creator : adoconnection
public void WriteAttributeValue(string prefix, int prefixOffset, object value, int valueOffset, int valueLength,
bool isLiteral)
{
WriteAttributeValueAsync(prefix, prefixOffset, value, valueOffset, valueLength, isLiteral).GetAwaiter().GetResult();
}
19
View Source File : RazorEngineTemplateBase.cs
License : MIT License
Project Creator : adoconnection
License : MIT License
Project Creator : adoconnection
public void EndWriteAttribute()
{
EndWriteAttributeAsync().GetAwaiter().GetResult();
}
19
View Source File : RazorEngineTemplateBase.cs
License : MIT License
Project Creator : adoconnection
License : MIT License
Project Creator : adoconnection
public void Execute()
{
ExecuteAsync().GetAwaiter().GetResult();
}
19
View Source File : RazorEngineTemplateBase.cs
License : MIT License
Project Creator : adoconnection
License : MIT License
Project Creator : adoconnection
public virtual string Result()
{
return ResultAsync().GetAwaiter().GetResult();
}
19
View Source File : RazorEngineCompiledTemplate.cs
License : MIT License
Project Creator : adoconnection
License : MIT License
Project Creator : adoconnection
public string Run(object model = null)
{
return this.RunAsync(model).GetAwaiter().GetResult();
}
19
View Source File : RazorEngineCompiledTemplateT.cs
License : MIT License
Project Creator : adoconnection
License : MIT License
Project Creator : adoconnection
public static IRazorEngineCompiledTemplate<T> LoadFromFile(string fileName)
{
return LoadFromFileAsync(fileName: fileName).GetAwaiter().GetResult();
}
19
View Source File : RazorEngineCompiledTemplateT.cs
License : MIT License
Project Creator : adoconnection
License : MIT License
Project Creator : adoconnection
public static IRazorEngineCompiledTemplate<T> LoadFromStream(Stream stream)
{
return LoadFromStreamAsync(stream).GetAwaiter().GetResult();
}
19
View Source File : RazorEngineCompiledTemplate.cs
License : MIT License
Project Creator : adoconnection
License : MIT License
Project Creator : adoconnection
public static IRazorEngineCompiledTemplate LoadFromFile(string fileName)
{
return LoadFromFileAsync(fileName: fileName).GetAwaiter().GetResult();
}
19
View Source File : RazorEngineCompiledTemplate.cs
License : MIT License
Project Creator : adoconnection
License : MIT License
Project Creator : adoconnection
public static IRazorEngineCompiledTemplate LoadFromStream(Stream stream)
{
return LoadFromStreamAsync(stream).GetAwaiter().GetResult();
}
19
View Source File : DynamicManager.cs
License : MIT License
Project Creator : Aguafrommars
License : MIT License
Project Creator : Aguafrommars
public virtual void Load()
{
foreach (var definition in _store.SchemeDefinitions)
{
if (ManagedHandlerType.Contains(definition.HandlerType))
{
base.AddAsync(definition).GetAwaiter().GetResult();
}
}
}
19
View Source File : SeedData.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
public static void SeedUsers(IServiceScope scope)
{
var context = scope.ServiceProvider.GetService<ApplicationDbContext>();
var roleMgr = scope.ServiceProvider.GetRequiredService<RoleManager<IdenreplacedyRole>>();
var roles = new string[]
{
"Is4-Writer",
"Is4-Reader"
};
foreach (var role in roles)
{
if (roleMgr.FindByNameAsync(role).GetAwaiter().GetResult() == null)
{
ExcuteAndCheckResult(() => roleMgr.CreateAsync(new IdenreplacedyRole
{
Name = role
})).GetAwaiter().GetResult();
}
}
var userMgr = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var alice = userMgr.FindByNameAsync("alice").Result;
if (alice == null)
{
alice = new ApplicationUser
{
UserName = "alice"
};
ExcuteAndCheckResult(() => userMgr.CreateAsync(alice, "Preplaced123$"))
.GetAwaiter().GetResult();
ExcuteAndCheckResult(() => userMgr.AddClaimsAsync(alice, new Claim[]{
new Claim(JwtClaimTypes.Name, "Alice Smith"),
new Claim(JwtClaimTypes.GivenName, "Alice"),
new Claim(JwtClaimTypes.FamilyName, "Smith"),
new Claim(JwtClaimTypes.Email, "[email protected]"),
new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
new Claim(JwtClaimTypes.WebSite, "http://alice.com"),
new Claim(JwtClaimTypes.Address, @"{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }", IdenreplacedyServer4.IdenreplacedyServerConstants.ClaimValueTypes.Json)
})).GetAwaiter().GetResult();
ExcuteAndCheckResult(() => userMgr.AddToRolesAsync(alice, roles))
.GetAwaiter().GetResult();
Console.WriteLine("alice created");
}
else
{
Console.WriteLine("alice already exists");
}
var bob = userMgr.FindByNameAsync("bob").GetAwaiter().GetResult();
if (bob == null)
{
bob = new ApplicationUser
{
UserName = "bob"
};
ExcuteAndCheckResult(() => userMgr.CreateAsync(bob, "Preplaced123$"))
.GetAwaiter().GetResult();
ExcuteAndCheckResult(() => userMgr.AddClaimsAsync(bob, new Claim[]{
new Claim(JwtClaimTypes.Name, "Bob Smith"),
new Claim(JwtClaimTypes.GivenName, "Bob"),
new Claim(JwtClaimTypes.FamilyName, "Smith"),
new Claim(JwtClaimTypes.Email, "[email protected]"),
new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
new Claim(JwtClaimTypes.WebSite, "http://bob.com"),
new Claim(JwtClaimTypes.Address, @"{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }", IdenreplacedyServer4.IdenreplacedyServerConstants.ClaimValueTypes.Json),
new Claim("location", "somewhere")
})).GetAwaiter().GetResult();
ExcuteAndCheckResult(() => userMgr.AddToRoleAsync(bob, "Is4-Reader"))
.GetAwaiter().GetResult();
Console.WriteLine("bob created");
}
else
{
Console.WriteLine("bob already exists");
}
context.SaveChanges();
}
19
View Source File : StringLocalizer.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
public IEnumerable<LocalizedString> GetAllStrings(bool includeParentCultures)
{
if (_resources != null)
{
return KeyValuePairs.Values;
}
GetAllResourcesAsync().GetAwaiter().GetResult();
return KeyValuePairs.Values;
}
19
View Source File : StringLocalizerFactory.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
private IEnumerable<string> GetCultureNames()
{
if (_cultureNames != null)
{
return _cultureNames;
}
lock (_provider)
{
if (_cultureNames != null)
{
return _cultureNames;
}
return GetCultureNamesAsync().GetAwaiter().GetResult();
}
}
19
View Source File : SeedData.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
public static void SeedUsers(IServiceScope scope, IConfiguration configuration)
{
var provider = scope.ServiceProvider;
var roleMgr = provider.GetRequiredService<RoleManager<IdenreplacedyRole>>();
var roles = new string[]
{
SharedConstants.WRITERPOLICY,
SharedConstants.READERPOLICY
};
foreach (var role in roles)
{
if (roleMgr.FindByNameAsync(role).GetAwaiter().GetResult() == null)
{
ExcuteAndCheckResult(() => roleMgr.CreateAsync(new IdenreplacedyRole
{
Name = role
})).GetAwaiter().GetResult();
}
}
var userMgr = provider.GetRequiredService<UserManager<ApplicationUser>>();
var userList = configuration.GetSection("InitialData:Users").Get<IEnumerable<ApplicationUser>>() ?? Array.Empty<ApplicationUser>();
int index = 0;
foreach (var user in userList)
{
var existing = userMgr.FindByNameAsync(user.UserName).GetAwaiter().GetResult();
if (existing != null)
{
Console.WriteLine($"{user.UserName} already exists");
continue;
}
var pwd = configuration.GetValue<string>($"InitialData:Users:{index}:Preplacedword");
ExcuteAndCheckResult(() => userMgr.CreateAsync(user, pwd))
.GetAwaiter().GetResult();
var claimList = configuration.GetSection($"InitialData:Users:{index}:Claims").Get<IEnumerable<Enreplacedy.UserClaim>>()
.Select(c => new Claim(c.ClaimType, c.ClaimValue, c.OriginalType, c.Issuer))
.ToList();
claimList.Add(new Claim(JwtClaimTypes.UpdatedAt, DateTime.Now.ToEpochTime().ToString(), ClaimValueTypes.Integer64));
ExcuteAndCheckResult(() => userMgr.AddClaimsAsync(user, claimList))
.GetAwaiter().GetResult();
var roleList = configuration.GetSection($"InitialData:Users:{index}:Roles").Get<IEnumerable<string>>();
ExcuteAndCheckResult(() => userMgr.AddToRolesAsync(user, roleList))
.GetAwaiter().GetResult();
Console.WriteLine($"{user.UserName} created");
index++;
}
}
19
View Source File : StringLocalizer.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
public IEnumerable<LocalizedString> GetAllStrings(bool includeParentCultures)
{
return GetAllStringsAsync(includeParentCultures).GetAwaiter().GetResult();
}
19
View Source File : AzureBlobXmlRepository.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
public IReadOnlyCollection<XElement> GetAllElements()
{
// Shunt the work onto a ThreadPool thread so that it's independent of any
// existing sync context or other potentially deadlock-causing items.
var elements = Task.Run(() => GetAllElementsAsync()).GetAwaiter().GetResult();
return new ReadOnlyCollection<XElement>(elements);
}
19
View Source File : AzureBlobXmlRepository.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
public void StoreElement(XElement element, string friendlyName)
{
if (element == null)
{
throw new ArgumentNullException(nameof(element));
}
// Shunt the work onto a ThreadPool thread so that it's independent of any
// existing sync context or other potentially deadlock-causing items.
Task.Run(() => StoreElementAsync(element)).GetAwaiter().GetResult();
}
19
View Source File : AzureKeyVaultXmlDecryptor.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
public XElement Decrypt(XElement encryptedElement)
{
return DecryptAsync(encryptedElement).GetAwaiter().GetResult();
}
19
View Source File : AzureKeyVaultXmlEncryptor.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
public EncryptedXmlInfo Encrypt(XElement plaintextElement)
{
return EncryptAsync(plaintextElement).GetAwaiter().GetResult();
}
19
View Source File : StringLocalizer.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
private string GetString(string name)
{
return GetStringAsync(name).GetAwaiter().GetResult();
}
19
View Source File : KeyRingProviderTest.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
[Fact]
public void GetCurrentKeyRing_NoExistingKeyRing_HoldsAllThreadsUntilKeyRingCreated()
{
// Arrange
var now = StringToDateTime("2015-03-01 00:00:00Z");
var expectedKeyRing = new Mock<IKeyRing>().Object;
var mockCacheableKeyRingProvider = new Mock<ICacheableKeyRingProvider>();
var keyRingProvider = CreateKeyRingProvider(mockCacheableKeyRingProvider.Object);
// This test spawns a background thread which calls GetCurrentKeyRing then waits
// for the foreground thread to call GetCurrentKeyRing. When the foreground thread
// blocks (inside the lock), the background thread will return the cached keyring
// object, and the foreground thread should consume that same object instance.
TimeSpan testTimeout = TimeSpan.FromSeconds(10);
Thread foregroundThread = Thread.CurrentThread;
ManualResetEventSlim mreBackgroundThreadHasCalledGetCurrentKeyRing = new ManualResetEventSlim();
ManualResetEventSlim mreForegroundThreadIsCallingGetCurrentKeyRing = new ManualResetEventSlim();
var backgroundGetKeyRingTask = Task.Run(() =>
{
mockCacheableKeyRingProvider
.Setup(o => o.GetCacheableKeyRing(now))
.Returns(() =>
{
mreBackgroundThreadHasCalledGetCurrentKeyRing.Set();
replacedert.True(mreForegroundThreadIsCallingGetCurrentKeyRing.Wait(testTimeout), "Test timed out.");
SpinWait.SpinUntil(() => (foregroundThread.ThreadState & ThreadState.WaitSleepJoin) != 0, testTimeout);
return new CacheableKeyRing(
expirationToken: CancellationToken.None,
expirationTime: StringToDateTime("2015-03-02 00:00:00Z"),
keyRing: expectedKeyRing);
});
return keyRingProvider.GetCurrentKeyRingCore(now);
});
replacedert.True(mreBackgroundThreadHasCalledGetCurrentKeyRing.Wait(testTimeout), "Test timed out.");
mreForegroundThreadIsCallingGetCurrentKeyRing.Set();
var foregroundRetVal = keyRingProvider.GetCurrentKeyRingCore(now);
backgroundGetKeyRingTask.Wait(testTimeout);
var backgroundRetVal = backgroundGetKeyRingTask.GetAwaiter().GetResult();
// replacedert - underlying provider only should have been called once
replacedert.Same(expectedKeyRing, foregroundRetVal);
replacedert.Same(expectedKeyRing, backgroundRetVal);
mockCacheableKeyRingProvider.Verify(o => o.GetCacheableKeyRing(It.IsAny<DateTimeOffset>()), Times.Once);
}
19
View Source File : AsyncHelper.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
public static TResult RunSync<TResult>(Func<Task<TResult>> func)
=> TaskFactory
.StartNew(func)
.Unwrap()
.GetAwaiter()
.GetResult();
19
View Source File : AsyncHelper.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
public static void RunSync(Func<Task> func)
=> TaskFactory
.StartNew(func)
.Unwrap()
.GetAwaiter()
.GetResult();
19
View Source File : Async.cs
License : MIT License
Project Creator : AkiniKites
License : MIT License
Project Creator : AkiniKites
public static void RunSync(this Func<Task> task)
{
Task.Factory.StartNew(task).Unwrap().GetAwaiter().GetResult();
}
19
View Source File : Async.cs
License : MIT License
Project Creator : AkiniKites
License : MIT License
Project Creator : AkiniKites
public static TResult RunSync<TResult>(this Func<Task<TResult>> task)
{
return Task.Factory.StartNew(task).Unwrap().GetAwaiter().GetResult();
}
19
View Source File : Program.cs
License : MIT License
Project Creator : AlexanderFroemmgen
License : MIT License
Project Creator : AlexanderFroemmgen
public static void Main(string[] args)
{
Console.WriteLine("This tool allows you to import images as AMIs and set up your AWS account accordingly.");
string accessKey;
string secretKey;
if (args.Length == 2)
{
accessKey = args[0];
secretKey = args[1];
}
else
{
Console.WriteLine(
"Please enter your AWS access key and secret key. (You can skip this step by launching with the params '<accessKey> <secretKey>'.");
Console.Write("Access key: ");
accessKey = Console.ReadLine().Trim();
Console.Write("Secret key: ");
secretKey = Console.ReadLine().Trim();
}
SelectOptions:
Console.WriteLine("---");
Console.WriteLine("You have the following options:");
Console.WriteLine("<1> Create role 'vmimport'. (This role has to exist, otherwise importing will fail.)");
Console.WriteLine("<2> Import image from S3 to AMI.");
Console.WriteLine("<3> Check status of imports.");
Console.Write("> ");
var selection = Console.ReadLine().Trim();
try
{
if (selection == "1")
{
SetupVmimportRole(accessKey, secretKey).GetAwaiter().GetResult();
}
else if (selection == "2")
{
Console.WriteLine(
"Your image needs to be in OVA file format (for example by exporting with VirtualBox) and uploaded to Amazon S3.");
Console.WriteLine("After importing has finished, you can delete the image from S3.");
Console.Write("S3 Bucket name> ");
var bucketName = Console.ReadLine().Trim();
Console.Write("S3 File name> ");
var fileName = Console.ReadLine().Trim();
ImportFromS3(accessKey, secretKey, bucketName, fileName).GetAwaiter().GetResult();
}
else if (selection == "3")
{
CheckImportStatus(accessKey, secretKey).GetAwaiter().GetResult();
}
else
{
Console.WriteLine("Invalid input.");
}
}
catch (Exception e)
{
Console.WriteLine($"{e.GetType()}: {e.Message}");
}
goto SelectOptions;
}
19
View Source File : KrakenApiClient.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
private void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
if (Subscriptions.Any())
{
foreach (var subscription in Subscriptions.Keys)
{
UnsubscribeAsync(subscription).GetAwaiter().GetResult();
}
}
socket.CloseAsync().GetAwaiter().GetResult();
}
disposedValue = true;
}
}
19
View Source File : PdfImageConverter.cs
License : MIT License
Project Creator : allantargino
License : MIT License
Project Creator : allantargino
public void GenerateImage(Stream pdfInput, ref Stream[] imageListOutput)
{
if (!pdfInput.CanSeek) throw new Exception("PdfInput Stream can not be seek!");
var rand = new Random(DateTime.Now.Second);
int value = rand.Next();
string tempPrefix = $"dou_pdf_temp_{value}";
string pdfDirectory = $@"{_tempFolder}\{tempPrefix}";
string pdfFileName = $"{tempPrefix}.pdf";
var pdfFile = ToFile(pdfInput, pdfFileName);
var images = ConvertAsync(pdfFile.FullName, _ratio).GetAwaiter().GetResult();
Console.Write($"Images generated: {images.Length}");
if (images == null)
{
Console.WriteLine("Error generating the images!");
return;
}
imageListOutput = new Stream[images.Length];
for (var i = 0; i < images.Length; i++)
{
var bytes = File.ReadAllBytes(images[i]);
MemoryStream jpgMemory = new MemoryStream(bytes);
//As the images are not in the proper order it is necessary to retrieve the page index.
var parts = images[i].Replace(".jpg", "").Split('_');
int pageIdx = int.Parse(parts[parts.Length - 1]);
imageListOutput[pageIdx - 1] = jpgMemory;
File.Delete(images[i]);
}
try
{
Directory.Delete($@"{pdfDirectory}");
}
catch (Exception ex)
{
Console.WriteLine($"Erro deleting directory {pdfDirectory} - {ex.Message}");
throw new Exception(ex.Message, ex);
}
}
19
View Source File : Program.cs
License : MIT License
Project Creator : allantargino
License : MIT License
Project Creator : allantargino
private static void Initialize(string[] args)
{
_semapreplaced = new SemapreplacedSlim(1, 1);
_config = new Config(args);
_gs = $@"{ _config.Get("GS_BIN")}";
_tempFolder = $@"{ _config.Get("TEMP_FOLDER")}";
_resolution = (int.Parse(_config.Get("IMAGE_RESOLUTION")) / 10).ToString();
if (!Directory.Exists(_tempFolder))
Directory.CreateDirectory(_tempFolder);
var connectionString = _config.Get("STORAGE_ACCOUNT");
_queueName = _config.Get("QUEUE_NAME");
_imageStorageAccount = _config.Get("IMAGE_STORAGE_ACCOUNT");
_imageStorageBlobContainer = _config.Get("IMAGE_CONTAINER_NAME");
if (string.IsNullOrWhiteSpace(connectionString)) throw new ArgumentException("connectionString is empty");
try
{
_storageAccount = CloudStorageAccount.Parse(connectionString);
}
catch (Exception ex)
{
throw new Exception($"Error parsing the storage connection string {connectionString}: {ex.Message}");
}
_queueClient = _storageAccount.CreateCloudQueueClient();
_queue = GetQueueAsync(_queueName).GetAwaiter().GetResult();
}
See More Examples