private int Accomplice(int a, int b, int c, DoIt d) { Console.WriteLine("Accomplice"); DoIt d2 = this.DoItWrong; return(d(a, b, c, d2)); }
public async Task Check(string host) { var client = new AsyncHttpClient(GetBaseUri(host), true); var result = await client.DoRequestAsync(HttpMethod.Get, "/", null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false); if (result.StatusCode != HttpStatusCode.OK) { throw new CheckerException(result.StatusCode.ToExitCode(), "get / failed"); } await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false); var query = "?query=" + WebUtility.UrlEncode(RndText.RandomWord(RndUtil.GetInt(2, 10))); result = await client.DoRequestAsync(HttpMethod.Get, ApiNotesSearch + query, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false); if (result.StatusCode != HttpStatusCode.OK) { throw new CheckerException(result.StatusCode.ToExitCode(), $"get {ApiNotesSearch} failed"); } var notes = DoIt.TryOrDefault(() => JsonSerializer.Deserialize <List <Note> >(result.BodyAsString)); if (notes == default) { throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiNotesSearch} response"); } await Console.Error.WriteLineAsync($"found '{notes.Count}' notes by query '{query}'").ConfigureAwait(false); }
public static int Main() { Repro r = new Repro(); DoIt d = r.DoItRight; return(r.Accomplice(1, 2, 3, d)); }
public static int TestEntryPoint() { Repro r = new Repro(); DoIt d = r.DoItRight; return(r.Accomplice(1, 2, 3, d)); }
static void Main(string[] args) { if (args.Length < 2) { Console.WriteLine("usage: urlstrong.exe <url map> <output>"); Environment.Exit(1); return; } if (!File.Exists(args[0])) { Console.WriteLine("Can't find url map: " + args[0]); Environment.Exit(1); return; } var outDir = Path.GetDirectoryName(args[1]); if (!String.IsNullOrEmpty(outDir) && !Directory.Exists(outDir)) { Console.WriteLine("Can't find output dir: " + outDir); Environment.Exit(1); return; } using(var reader = new StreamReader(args[0])) using(var writer = new StreamWriter(args[1])) { var doIt = new DoIt(); doIt.Now(reader, writer); } }
public async Task ShouldFailWithNoId() { var cmd = new DoIt(Auto.Create <string>()); var result = await Service.Handle(cmd, default); result.Success.Should().BeFalse(); (result as ErrorResult <TestState, TestId>) !.Exception.Should().BeOfType <Exceptions.InvalidIdException>(); }
public static int test_0_tests() { // Check that creation of delegates do not runs the class cctor DoIt doit = new DoIt(B.method); // // Beginn Aenderung Test // // if (A.b_cctor_run) // return 1; // // Ende Aenderung Test // Tests test = new Tests(); SimpleDelegate d = new SimpleDelegate(F); SimpleDelegate d1 = new SimpleDelegate(test.VF); NotSimpleDelegate d2 = new NotSimpleDelegate(G); NotSimpleDelegate d3 = new NotSimpleDelegate(test.H); d(); d1(); // we run G() and H() before and after using them as delegates // to be sure we don't corrupt them. G(2); test.H(3); Console.WriteLine(d2(2)); Console.WriteLine(d3(3)); G(2); test.H(3); if (d.Method.Name != "F") { return(1); } if (d3.Method == null) { return(1); } object [] args = { 3 }; Console.WriteLine(d3.DynamicInvoke(args)); AnotherDelegate d4 = new AnotherDelegate(puts); if (d4.Method == null) { return(1); } Console.WriteLine(d4.Method); Console.WriteLine(d4.Method.Name); Console.WriteLine(d4.Method.DeclaringType); return(0); }
protected override void OnAppearing() { base.OnAppearing(); // - - - - - - DoIt.OnMainThread(() => { BackboneViewModel.Current.DecBusy(); }); }
private void foreachChildrenUp(List <Tchild> Parents, DoIt doIt) { this.Element?.ForEach(localchild => { if ((localchild != null) && (localchild.Me != null)) { doIt(localchild, Parents); } List <Tchild> parents = new List <Tchild>(Parents); parents.Add(localchild); localchild?.foreachChildrenUp(parents, doIt); }); }
private void foreachChildrenDown(List <Tchild> Parents, DoIt doIt) { Element?.ForEach(localchild => { List <Tchild> parents = new List <Tchild>(Parents); parents.Add(localchild); localchild.foreachChildrenDown(parents, doIt); if (localchild.Me != null) { doIt(localchild, Parents); } }); }
public async Task Get(string host, string id, string flag, int vuln) { var parts = id.Split(':'); if (parts.Length != 3) { throw new Exception($"Invalid flag id '{id}'"); } var login = parts[0]; var pass = parts[1]; var cookie = Encoding.UTF8.GetString(Convert.FromBase64String(parts[2])); var client = new AsyncHttpClient(GetBaseUri(host), true); var result = await client.DoRequestAsync(HttpMethod.Get, ApiScoreboard, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false); if (result.StatusCode != HttpStatusCode.OK) { throw new CheckerException(result.StatusCode.ToExitCode(), $"get {ApiScoreboard} failed"); } var solutions = DoIt.TryOrDefault(() => JsonSerializer.Deserialize <List <Solution> >(result.BodyAsString)); if (solutions == default || solutions.Count == 0 || solutions.All(sln => sln.Login != login)) { throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiScoreboard} response"); } await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false); client = new AsyncHttpClient(GetBaseUri(host), true); client.Cookies.SetCookies(GetBaseUri(host), cookie); result = await client.DoRequestAsync(HttpMethod.Get, ApiAuth, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false); if (result.StatusCode != HttpStatusCode.OK) { throw new CheckerException(result.StatusCode.ToExitCode(), $"get {ApiAuth} failed"); } var user = DoIt.TryOrDefault(() => JsonSerializer.Deserialize <User>(result.BodyAsString)); if (user == default || user.Login != login || user.Bio != flag) { throw new CheckerException(ExitCode.CORRUPT, "flag not found"); } }
public void CanBuildSimpleMsiPackage() { var folder = TestData.Get(@"TestData\SimpleMsiPackage\MsiPackage"); using (var fs = new DisposableFileSystem()) { var baseFolder = fs.GetFolder(); var intermediateFolder = Path.Combine(baseFolder, "obj"); var pdbPath = Path.Combine(baseFolder, @"bin\testpackage.wixpdb"); var engine = new FakeBuildEngine(); var task = new DoIt { BuildEngine = engine, SourceFiles = new[] { new TaskItem(Path.Combine(folder, "Package.wxs")), new TaskItem(Path.Combine(folder, "PackageComponents.wxs")), }, LocalizationFiles = new[] { new TaskItem(Path.Combine(folder, "Package.en-us.wxl")), }, BindInputPaths = new[] { new TaskItem(Path.Combine(folder, "data")), }, IntermediateDirectory = new TaskItem(intermediateFolder), OutputFile = new TaskItem(Path.Combine(baseFolder, @"bin\test.msi")), PdbType = "Full", PdbFile = new TaskItem(pdbPath), }; var result = task.Execute(); Assert.True(result, $"MSBuild task failed unexpectedly. Output:\r\n{engine.Output}"); Assert.True(File.Exists(Path.Combine(baseFolder, @"bin\test.msi"))); Assert.True(File.Exists(pdbPath)); Assert.True(File.Exists(Path.Combine(baseFolder, @"bin\cab1.cab"))); var intermediate = Intermediate.Load(pdbPath); var section = intermediate.Sections.Single(); var fileTuple = section.Tuples.OfType <FileTuple>().Single(); Assert.Equal(Path.Combine(folder, @"data\test.txt"), fileTuple[FileTupleFields.Source].AsPath().Path); Assert.Equal(@"test.txt", fileTuple[FileTupleFields.Source].PreviousValue.AsPath().Path); } }
static string GenerateCodeString(string inputFileName, string inputFileContent) { try { var doIt = new DoIt(); using (var reader = new StringReader(inputFileContent)) using (var writer = new StringWriter()) { doIt.Now(reader, writer); return writer.ToString(); } } catch (Exception err) { return "/*" + err + "*/"; } }
public List <Tchild> Where(Func <Tchild, List <Tchild>, bool> Delegate) { List <Tchild> Res = new List <Tchild>(); DoIt doIt = new DoIt(new Action <Tchild, List <Tchild> >((me, plist) => { if (Delegate(me, plist)) { Res.Add(me); } })); if (Delegate((Tchild)this, new List <Tchild>())) { Res.Add((Tchild)this); } RunForeachChildren(doIt); return(Res); }
public override bool Execute() { var outputFiles = new List<ITaskItem>(); foreach (var item in InputFiles) { if (item.ItemSpec.Length == 0) continue; var input = item.ItemSpec; if (!File.Exists(input)) { Log.LogError("Couldn't find url file: {0}", item.ItemSpec); return false; } string outputDir; if (OutputDir != null && OutputDir.ItemSpec.Length > 0) { if (!Directory.Exists(OutputDir.ItemSpec)) { Log.LogError("Output directory doesn't exist: {0}", OutputDir.ItemSpec); return false; } outputDir = OutputDir.ItemSpec; } else { outputDir = Path.GetDirectoryName(input); } var output = Path.Combine(outputDir, Path.GetFileNameWithoutExtension(input) + ".generated.cs"); using (var reader = new StreamReader(input)) using (var writer = new StreamWriter(output)) { var doIt = new DoIt(); doIt.Now(reader, writer); outputFiles.Add(new TaskItem(output)); } } OutputFiles = outputFiles.ToArray<ITaskItem>(); return true; }
public void ReportsInnerExceptionForUnexpectedExceptions() { var folder = TestData.Get(@"TestData\SimpleMsiPackage\MsiPackage"); using (var fs = new DisposableFileSystem()) { var baseFolder = fs.GetFolder(); var intermediateFolder = Path.Combine(baseFolder, "obj"); var pdbPath = Path.Combine(baseFolder, @"bin\testpackage.wixpdb"); var engine = new FakeBuildEngine(); var task = new DoIt { BuildEngine = engine, SourceFiles = new[] { new TaskItem(Path.Combine(folder, "Package.wxs")), new TaskItem(Path.Combine(folder, "PackageComponents.wxs")), }, LocalizationFiles = new[] { new TaskItem(Path.Combine(folder, "Package.en-us.wxl")), }, BindInputPaths = new[] { new TaskItem(Path.Combine(folder, "data")), }, IntermediateDirectory = new TaskItem(intermediateFolder), OutputFile = new TaskItem(Path.Combine(baseFolder, @"bin\test.msi")), PdbType = "Full", PdbFile = new TaskItem(pdbPath), }; var result = task.Execute(); Assert.False(result, $"MSBuild task succeeded unexpectedly. Output:\r\n{engine.Output}"); Assert.Contains( "System.PlatformNotSupportedException: Could not find platform specific 'wixnative.exe' ---> System.IO.FileNotFoundException: Could not find internal piece of WiX Toolset from", engine.Output); } }
public static int test_0_tests () { // Check that creation of delegates do not runs the class cctor DoIt doit = new DoIt (B.method); if (A.b_cctor_run) return 1; Tests test = new Tests (); SimpleDelegate d = new SimpleDelegate (F); SimpleDelegate d1 = new SimpleDelegate (test.VF); NotSimpleDelegate d2 = new NotSimpleDelegate (G); NotSimpleDelegate d3 = new NotSimpleDelegate (test.H); d (); d1 (); // we run G() and H() before and after using them as delegates // to be sure we don't corrupt them. G (2); test.H (3); Console.WriteLine (d2 (2)); Console.WriteLine (d3 (3)); G (2); test.H (3); if (d.Method.Name != "F") return 1; if (d3.Method == null) return 1; object [] args = {3}; Console.WriteLine (d3.DynamicInvoke (args)); AnotherDelegate d4 = new AnotherDelegate (puts); if (d4.Method == null) return 1; Console.WriteLine (d4.Method); Console.WriteLine (d4.Method.Name); Console.WriteLine (d4.Method.DeclaringType); return 0; }
public void RunForeachChildren(DoIt doIt, EnumerationType EnumerationType = EnumerationType.FromDowntoUp) { if (EnumerationType == EnumerationType.FromDowntoUp) { foreachChildrenDown(new List <Tchild>() { (Tchild)this }, doIt); doIt((Tchild)this, new List <Tchild>()); } else if (EnumerationType == EnumerationType.FromUptoDown) { doIt((Tchild)this, new List <Tchild>()); foreachChildrenUp(new List <Tchild>() { (Tchild)this }, doIt); } else { throw new ArgumentException(); } }
public async Task <string> Put(string host, string id, string flag, int vuln) { var client = new AsyncHttpClient(GetBaseUri(host), true); var login = RndText.RandomWord(RndUtil.GetInt(MinRandomFieldLength, MaxRandomFieldLength)).RandomLeet().RandomUpperCase(); var name = RndText.RandomWord(RndUtil.GetInt(MinRandomFieldLength, MaxRandomFieldLength)).RandomLeet().RandomUpperCase(); var pass = RndText.RandomWord(RndUtil.GetInt(MinRandomFieldLength, MaxRandomFieldLength)).RandomLeet().RandomUpperCase(); await Console.Error.WriteLineAsync($"login '{login}', name '{name}', pass '{pass}'").ConfigureAwait(false); var signUpQuery = $"?login={WebUtility.UrlEncode(login)}&name={WebUtility.UrlEncode(name)}&password={WebUtility.UrlEncode(pass)}"; var result = await client.DoRequestAsync(HttpMethod.Post, ApiAuthSignUp + signUpQuery, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false); if (result.StatusCode != HttpStatusCode.OK) { throw new CheckerException(result.StatusCode.ToExitCode(), $"get {ApiAuthSignUp} failed"); } await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false); var items = Enumerable.Range(0, RndUtil.GetInt(1, 3)).Select(i => new Note { Title = RndText.RandomText(RndUtil.GetInt(MinRandomTitleLength, MaxRandomTitleLength)).RandomUmlauts(), Text = RndText.RandomText(RndUtil.GetInt(MinRandomTextLength, MaxRandomTextLength)).RandomUmlauts() }).ToArray(); var itemWithFlag = RndUtil.Choice(items); if (RndUtil.GetInt(0, 2) == 0) { itemWithFlag.Text = flag; } else { itemWithFlag.Title = flag; } itemWithFlag.IsPrivate = true; foreach (var item in items) { await Console.Error.WriteLineAsync($"title '{item.Title}', text '{item.Text}', isPrivate '{item.IsPrivate}'").ConfigureAwait(false); var q = $"?title={WebUtility.UrlEncode(item.Title)}&text={WebUtility.UrlEncode(item.Text)}" + (item.IsPrivate ? "&isPrivate=on" : null); result = await client.DoRequestAsync(HttpMethod.Post, ApiNotesAdd + q, null, NetworkOpTimeout).ConfigureAwait(false); if (result.StatusCode != HttpStatusCode.OK) { throw new CheckerException(result.StatusCode.ToExitCode(), $"post {ApiNotesAdd} failed"); } await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false); } var query = GetRandomQuery(itemWithFlag); if (query.Trim('\"', ' ').Length <= 4) //NOTE: too low entropy { query = flag; } await Console.Error.WriteLineAsync($"random query '{query}'").ConfigureAwait(false); var cookie = client.Cookies.GetCookieHeader(GetBaseUri(host)); await Console.Error.WriteLineAsync($"cookie '{cookie}'").ConfigureAwait(false); var bytes = DoIt.TryOrDefault(() => Encoding.UTF8.GetBytes(cookie)); if (bytes == null || bytes.Length > 1024) { throw new CheckerException(result.StatusCode.ToExitCode(), "too large or invalid cookies"); } return($"{login}:{pass}:{Convert.ToBase64String(bytes)}:{WebUtility.UrlEncode(query)}"); }
public RelayCommand(DoIt action, CanWeDoIt canWeDoIt) { this.action = action; this.canWeDoIt = canWeDoIt; }
private int DoItWrong(int a, int b, int c, DoIt d) { Console.WriteLine("Failed"); return -1; }
private int DoItRight(int a, int b, int c, DoIt d) { Console.WriteLine("Pass"); return(100); }
private int DoItWrong(int a, int b, int c, DoIt d) { Console.WriteLine("Failed"); return(-1); }
private void button2_Click(object sender, EventArgs e) { if (button2.Cursor == Cursors.No) { DialogResult result = MessageBox.Show("Maalesef uygulamamızı kullanmanız için verilen süre doldu. Tekrar hizmet almak için tekliflerimiz görmek ister misiniz?", "Yetkisiz Erişim", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (result == DialogResult.Yes) { Process.Start("https://hilecenter.com/faceitte-calisan-csgo-hilesi-satin-al"); } return; } if (dllName == null) { MessageBox.Show("Lütfen bir hile seçin.", "Hatalı İşlem", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } try { Directory.CreateDirectory(Application.LocalUserAppDataPath + "\\File"); if (dllName == "memphis") { File.WriteAllBytes(Application.LocalUserAppDataPath + "\\File\\" + dllName + ".dll", Properties.Resources.memphis); } else if (dllName == "osiris") { File.WriteAllBytes(Application.LocalUserAppDataPath + "\\File\\" + dllName + ".dll", Properties.Resources.osiris); } else if (dllName == "padisah") { File.WriteAllBytes(Application.LocalUserAppDataPath + "\\File\\" + dllName + ".dll", Properties.Resources.padisah); } else if (dllName == "fatih") { File.WriteAllBytes(Application.LocalUserAppDataPath + "\\File\\" + dllName + ".dll", Properties.Resources.fatih); } else if (dllName == "osmanli") { File.WriteAllBytes(Application.LocalUserAppDataPath + "\\File\\" + dllName + ".dll", Properties.Resources.osmanli); } DoIt doIt = new DoIt(); if (doIt.Inject(Application.LocalUserAppDataPath + "\\File\\" + dllName + ".dll", Program.gameProcessName)) { MessageBox.Show("Hile başlatıldı..."); } else { try { Process.Start("steam://rungameid/730"); } catch (Exception ex) { MessageBox.Show("Hile başlatılamadı. Oyunun açık olduğundan emin olun."); } } timer1.Start(); } catch (Exception) { MessageBox.Show("Hile zaten çalışıyor."); } }
private int DoItRight(int a, int b, int c, DoIt d) { Console.WriteLine("Pass"); return 100; }
private int Accomplice(int a, int b, int c, DoIt d) { Console.WriteLine("Accomplice"); DoIt d2 = this.DoItWrong; return d(a, b, c, d2); }
static object Do (DoIt d) { return d (); }
public async Task Get(string host, string id, string flag, int vuln) { var parts = id.Split(':', 4); if (parts.Length != 4) { throw new Exception($"Invalid flag id '{id}'"); } var login = parts[0]; var pass = parts[1]; var cookie = Encoding.UTF8.GetString(Convert.FromBase64String(parts[2])); var encodedQuery = parts[3]; var client = new AsyncHttpClient(GetBaseUri(host), true); if (RndUtil.GetInt(0, 2) == 0) { await Console.Error.WriteLineAsync($"login by cookie '{cookie}'").ConfigureAwait(false); client.Cookies.SetCookies(GetBaseUri(host), cookie); } else { await Console.Error.WriteLineAsync($"login with login '{login}' and pass '{pass}'").ConfigureAwait(false); var loginQuery = $"?login={WebUtility.UrlEncode(login)}&password={WebUtility.UrlEncode(pass)}"; var signInResult = await client.DoRequestAsync(HttpMethod.Post, ApiAuthSignIn + loginQuery).ConfigureAwait(false); if (signInResult.StatusCode != HttpStatusCode.OK) { throw new CheckerException(signInResult.StatusCode.ToExitCode(), $"get {ApiAuthSignIn} failed"); } await Console.Error.WriteLineAsync($"cookie '{client.Cookies.GetCookieHeader(GetBaseUri(host))}'").ConfigureAwait(false); await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false); } var query = RndUtil.Choice("?query=&myOnly=on", "?query=" + encodedQuery); var result = await client.DoRequestAsync(HttpMethod.Get, ApiNotesSearch + query, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false); if (result.StatusCode != HttpStatusCode.OK) { throw new CheckerException(result.StatusCode.ToExitCode(), $"get {ApiNotesSearch} failed"); } var notes = DoIt.TryOrDefault(() => JsonSerializer.Deserialize <List <Note> >(result.BodyAsString)); if (notes == default) { throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiNotesSearch} response"); } await Console.Error.WriteLineAsync($"found '{notes.Count}' notes by query '{query}'").ConfigureAwait(false); var note = notes.FirstOrDefault(note => note.Author.Contains(flag) || note.Title.Contains(flag) || note.Text.Contains(flag)); if (note == null) { throw new CheckerException(ExitCode.CORRUPT, "flag not found"); } //NOTE: Also check phrase query if (!query.StartsWith("?query=%22") || !query.EndsWith("%22")) { return; } var words = WebUtility.UrlDecode(encodedQuery).Trim('"', ' ').Split().Where(word => !string.IsNullOrWhiteSpace(word)).Distinct().ToArray(); if (words.Length < 2) { return; } query = string.Join(' ', words.Reverse()); if (note.Author.Contains(query, StringComparison.InvariantCultureIgnoreCase) || note.Title.Contains(query, StringComparison.InvariantCultureIgnoreCase) || note.Text.Contains(query, StringComparison.InvariantCultureIgnoreCase)) { return; } query = "?query=" + WebUtility.UrlEncode('"' + query + '"'); await Console.Error.WriteLineAsync($"check phrase query reversed '{query}'").ConfigureAwait(false); result = await client.DoRequestAsync(HttpMethod.Get, ApiNotesSearch + query, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false); if (result.StatusCode != HttpStatusCode.OK) { throw new CheckerException(result.StatusCode.ToExitCode(), $"get {ApiNotesSearch} failed"); } notes = DoIt.TryOrDefault(() => JsonSerializer.Deserialize <List <Note> >(result.BodyAsString)); if (notes == default) { throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiNotesSearch} response"); } await Console.Error.WriteLineAsync($"found '{notes.Count}' notes by query '{query}'").ConfigureAwait(false); if (notes.Any(note => note.Author.Contains(flag) || note.Title.Contains(flag) || note.Text.Contains(flag))) { throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiNotesSearch} response: phrase query"); } }
public async Task <string> Put(string host, string id, string flag, int vuln) { var client = new AsyncHttpClient(GetBaseUri(host), true); var result = await client.DoRequestAsync(HttpMethod.Get, ApiGenerate, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false); if (result.StatusCode != HttpStatusCode.OK) { throw new CheckerException(result.StatusCode.ToExitCode(), $"get {ApiGenerate} failed"); } var rubik = DoIt.TryOrDefault(() => JsonSerializer.Deserialize <GeneratedRubik>(result.BodyAsString)); if (rubik == default) { throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiGenerate} response"); } await Console.Error.WriteLineAsync($"rubik '{rubik.Rubik}', signed '{rubik.Value}'").ConfigureAwait(false); string solution; try { solution = DoIt.TryOrDefault(() => SolveHelper.ConvertOutputSolution(RubikSolver.FindSolution(SolveHelper.ConvertInputCube(rubik.Rubik), 32, 10000))); } catch (RubikSolveException e) { await Console.Error.WriteLineAsync(e.Message).ConfigureAwait(false); throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiGenerate} response: unsolvable puzzle"); } await Console.Error.WriteLineAsync($"solution '{solution}'").ConfigureAwait(false); await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false); var login = RndText.RandomWord(RndUtil.GetInt(MinRandomFieldLength, MaxRandomFieldLength)).RandomLeet().RandomUpperCase(); var pass = RndText.RandomWord(RndUtil.GetInt(MinRandomFieldLength, MaxRandomFieldLength)).RandomLeet().RandomUpperCase(); await Console.Error.WriteLineAsync($"name '{login}', pass '{pass}', bio '{flag}'").ConfigureAwait(false); var query = $"?login={WebUtility.UrlEncode(login)}&pass={WebUtility.UrlEncode(pass)}&bio={WebUtility.UrlEncode(flag)}&puzzle={WebUtility.UrlEncode(rubik.Value)}&solution={WebUtility.UrlEncode(solution)}"; result = await client.DoRequestAsync(HttpMethod.Post, ApiSolve + query, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false); if (result.StatusCode != HttpStatusCode.OK) { throw new CheckerException(result.StatusCode.ToExitCode(), $"post {ApiSolve} failed"); } var sln = DoIt.TryOrDefault(() => JsonSerializer.Deserialize <Solution>(result.BodyAsString)); if (sln == default || sln.Login != login || sln.MovesCount != solution.Length) { throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiSolve} response"); } await Console.Error.WriteLineAsync($"solution '{solution}'").ConfigureAwait(false); var cookie = client.Cookies.GetCookieHeader(GetBaseUri(host)); await Console.Error.WriteLineAsync($"cookie '{cookie}'").ConfigureAwait(false); if (string.IsNullOrEmpty(cookie) || cookie.Length > 512) { throw new CheckerException(result.StatusCode.ToExitCode(), $"invalid {ApiSolve} response: cookies"); } return($"{login}:{pass}:{Convert.ToBase64String(Encoding.UTF8.GetBytes(cookie))}"); }
public async Task Check(string host) { var client = new AsyncHttpClient(GetBaseUri(host), true); var result = await client.DoRequestAsync(HttpMethod.Get, "/", null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false); if (result.StatusCode != HttpStatusCode.OK) { throw new CheckerException(result.StatusCode.ToExitCode(), "get / failed"); } await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false); result = await client.DoRequestAsync(HttpMethod.Get, ApiGenerate, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false); if (result.StatusCode != HttpStatusCode.OK) { throw new CheckerException(result.StatusCode.ToExitCode(), $"get {ApiGenerate} failed"); } var rubik = DoIt.TryOrDefault(() => JsonSerializer.Deserialize <GeneratedRubik>(result.BodyAsString)); if (rubik == default) { throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiGenerate} response"); } await Console.Error.WriteLineAsync($"rubik '{rubik.Rubik}', signed '{rubik.Value}'").ConfigureAwait(false); await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false); var login = RndText.RandomWord(RndUtil.GetInt(MinRandomFieldLength, MaxRandomFieldLength)).RandomLeet().RandomUpperCase(); var pass = RndText.RandomWord(RndUtil.GetInt(MinRandomFieldLength, MaxRandomFieldLength)).RandomLeet().RandomUpperCase(); var flag = RndText.RandomWord(RndUtil.GetInt(MinRandomFieldLength, MaxRandomFieldLength)).RandomLeet().RandomUpperCase(); await Console.Error.WriteLineAsync($"name '{login}', pass '{pass}', bio '{flag}'").ConfigureAwait(false); var solution = RndRubik.RandomSolution(MinRandomSolutionLength, MaxRandomSolutionLength); var query = $"?login={WebUtility.UrlEncode(login)}&pass={WebUtility.UrlEncode(pass)}&bio={WebUtility.UrlEncode(flag)}&puzzle={WebUtility.UrlEncode(rubik.Value)}&solution={WebUtility.UrlEncode(solution)}"; result = await client.DoRequestAsync(HttpMethod.Post, ApiSolve + query, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false); if (result.StatusCode != (HttpStatusCode)418) { throw new CheckerException(result.StatusCode == HttpStatusCode.OK ? ExitCode.MUMBLE : result.StatusCode.ToExitCode(), $"invalid {ApiSolve} response"); } await RndUtil.RndDelay(MaxDelay).ConfigureAwait(false); result = await client.DoRequestAsync(HttpMethod.Get, ApiAuth, null, NetworkOpTimeout, MaxHttpBodySize).ConfigureAwait(false); if (result.StatusCode != HttpStatusCode.OK) { throw new CheckerException(result.StatusCode.ToExitCode(), $"get {ApiAuth} failed"); } var user = DoIt.TryOrDefault(() => JsonSerializer.Deserialize <User>(result.BodyAsString)); if (user == default || user.Login != login || user.Bio != flag) { throw new CheckerException(ExitCode.MUMBLE, $"invalid {ApiAuth} response"); } }
static void Main(string[] args) { // -------- Most of the examples work with these lists -------- List <int> numbers = new List <int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; List <string> words = new List <string> { "one", "two", "three", "four", "five" }; Console.WriteLine("Our starting numbers list:"); foreach (int item in numbers) { Console.Write("{0}, ", item); } Console.WriteLine(); Console.WriteLine("Our starting words list:"); foreach (string item in words) { Console.Write("{0}, ", item); } Console.WriteLine(); // -------- Delegate examples -------- // -------- Doing the same thing with a "raw" delegate, an anonymous methd, and a lambda expression -------- Console.WriteLine("\nThe following three examples do essentially the same task using " + "C# 1.x's raw delegates, C# 2.0's anonymous methods, and C# 3.0's lambda expressions (Ch 16):"); // Example 1a. Invoke the delegate the C# 1.x (1.0 and 1.1) way: with a "raw" delegate. Console.WriteLine("\n1a. Using a plain old raw delegate:"); DoIt doSomethingOld = new DoIt(PrintThis); // Pass callback method name to delegate instantiation. if (doSomethingOld != null) { doSomethingOld("\tThe C# 1.x way: Hello, I'm your standard old delegate!"); // Invoke the delegate. } // Example 1b. Invoke the delegate the simpler C# 2.0 way: with an anonymous method. Console.WriteLine("\n1b. Using a newer anonymous method: "); // This example creates the delegate, then invokes it. DoIt doSomethingNewer = delegate(string msg) { Console.WriteLine(msg); }; if (doSomethingNewer != null) { doSomethingNewer("\tThe C# 2.0 way: Hello, I'm a cool anonymous method."); // Invoke the delegate. } // Example 1c. Invoke the delegate the really simple 3.0 way: with a lambda expression. Console.WriteLine("\n1c. Using a lambda expression: "); DoIt doSomethingReallyNew = new DoIt(msg => Console.WriteLine(msg)); if (doSomethingReallyNew != null) { // Invoke the delegate. doSomethingReallyNew("\tThe new C# 3.0 way: Pay no attention to the old-fashioned dudes. I'm a hot new lambda expression."); } // Doing the do-to-each problem using raw delegates, anonymous methods, and lambdas. // See Chapter 16 for the do-to-each problem. Console.WriteLine("\n2. A few do-to-each examples (not discussed in the Delegates and Events chapter):"); Console.Write("\t2a. First, find numbers > 5 in a list with a raw delegate: "); int firstNumberGreaterThanFive = numbers.Find(NumberGT5); Console.WriteLine(firstNumberGreaterThanFive.ToString()); Console.Write("\t2b. Next, find numbers > 7 in a list with an anonymous method: "); int firstNumberGreaterThanSeven = numbers.Find(delegate(int num) { return(num > 7); }); Console.WriteLine(firstNumberGreaterThanSeven); Console.WriteLine("\t2c. Last, find numbers > 5 and < 8 in a list with a lambda expression: "); List <int> allNumbersGT5AndLT8 = numbers.FindAll(num => num > 5 && num < 8); foreach (int n in allNumbersGT5AndLT8) { Console.WriteLine("\t{0}", n.ToString()); } Console.WriteLine(); // -------- Anonymous methods vs. lambda expressions -------- Console.WriteLine("\n3a. Do an action on numbers list using an anonymous method:"); numbers.ForEach(delegate(int num) { Console.WriteLine("Number before {0} is {1}", num, num - 1); }); Console.WriteLine("\n3b. Do an action on numbers list using a lambda expression:"); // You can also make a compact loop with this kind of code. numbers.ForEach(i => Console.WriteLine("I'm {0}; my square is {1}", i, i * i)); // Use an anonymous method to supply an on-the-fly delegate instance to a work-horse method that // takes a delegate-type parameter. The delegate is called HandleTwo - see delegate definitions. // Instead of creating the delegate, then invoking it, this example simply creates it in the // process of passing a delegate instance to a method. Console.WriteLine("\n4. Another Anonymous Method Example: "); int result = Multiply(2, 3, delegate(int n, int m) { return(n * m); }); Console.WriteLine("\tProduct of {0} * {1} is {2}", 2, 3, result); // Now do the same as above, but with a lambda expression. // Note: This is an example of a lambda that takes multiple parameters. // That's because it's based on a delegate that takes two parameters, the HandleTwo delegate // (technically, the lambda gets resolved to a delegate similar to HandleTwo). Console.WriteLine("\n5. Previous example but with a lambda expression: "); int result3 = Multiply(2, 3, (n, m) => n * m); Console.WriteLine("\tProduct of {0} * {1} is {2}", 2, 3, result3); Console.WriteLine("\n6. Try invoking a null delegate: Oops!"); try { int result4 = Multiply(2, 3, null); } catch (ArgumentNullException e) { Console.WriteLine(e.Message); } Console.WriteLine("\nPress Enter to terminate..."); Console.Read(); }
public static int test_0_tests() { DoIt doit = new DoIt (B.method); if (A.b_cctor_run) return 1; Tests test = new Tests (); SimpleDelegate d = new SimpleDelegate (F); SimpleDelegate d1 = new SimpleDelegate (test.VF); NotSimpleDelegate d2 = new NotSimpleDelegate (G); NotSimpleDelegate d3 = new NotSimpleDelegate (test.H); d (); d1 (); G (2); test.H (3); Console.WriteLine (d2 (2)); Console.WriteLine (d3 (3)); G (2); test.H (3); if (d.Method.Name != "F") return 1; if (d3.Method == null) return 1; object [] args = {3}; Console.WriteLine (d3.DynamicInvoke (args)); AnotherDelegate d4 = new AnotherDelegate (puts); if (d4.Method == null) return 1; Console.WriteLine (d4.Method); Console.WriteLine (d4.Method.Name); Console.WriteLine (d4.Method.DeclaringType); return 0; }
static void Main(string[] args) { // -------- Most of the examples work with these lists -------- List<int> numbers = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; List<string> words = new List<string> { "one", "two", "three", "four", "five" }; Console.WriteLine("Our starting numbers list:"); foreach (int item in numbers) { Console.Write("{0}, ", item); } Console.WriteLine(); Console.WriteLine("Our starting words list:"); foreach (string item in words) { Console.Write("{0}, ", item); } Console.WriteLine(); // -------- Delegate examples -------- // -------- Doing the same thing with a "raw" delegate, an anonymous methd, and a lambda expression -------- Console.WriteLine("\nThe following three examples do essentially the same task using " + "C# 1.x's raw delegates, C# 2.0's anonymous methods, and C# 3.0's lambda expressions (Ch 16):"); // Example 1a. Invoke the delegate the C# 1.x (1.0 and 1.1) way: with a "raw" delegate. Console.WriteLine("\n1a. Using a plain old raw delegate:"); DoIt doSomethingOld = new DoIt(PrintThis); // Pass callback method name to delegate instantiation. if (doSomethingOld != null) { doSomethingOld("\tThe C# 1.x way: Hello, I'm your standard old delegate!"); // Invoke the delegate. } // Example 1b. Invoke the delegate the simpler C# 2.0 way: with an anonymous method. Console.WriteLine("\n1b. Using a newer anonymous method: "); // This example creates the delegate, then invokes it. DoIt doSomethingNewer = delegate(string msg) { Console.WriteLine(msg); }; if (doSomethingNewer != null) { doSomethingNewer("\tThe C# 2.0 way: Hello, I'm a cool anonymous method."); // Invoke the delegate. } // Example 1c. Invoke the delegate the really simple 3.0 way: with a lambda expression. Console.WriteLine("\n1c. Using a lambda expression: "); DoIt doSomethingReallyNew = new DoIt(msg => Console.WriteLine(msg)); if (doSomethingReallyNew != null) { // Invoke the delegate. doSomethingReallyNew("\tThe new C# 3.0 way: Pay no attention to the old-fashioned dudes. I'm a hot new lambda expression."); } // Doing the do-to-each problem using raw delegates, anonymous methods, and lambdas. // See Chapter 16 for the do-to-each problem. Console.WriteLine("\n2. A few do-to-each examples (not discussed in the Delegates and Events chapter):"); Console.Write("\t2a. First, find numbers > 5 in a list with a raw delegate: "); int firstNumberGreaterThanFive = numbers.Find(NumberGT5); Console.WriteLine(firstNumberGreaterThanFive.ToString()); Console.Write("\t2b. Next, find numbers > 7 in a list with an anonymous method: "); int firstNumberGreaterThanSeven = numbers.Find(delegate(int num) { return num > 7; }); Console.WriteLine(firstNumberGreaterThanSeven); Console.WriteLine("\t2c. Last, find numbers > 5 and < 8 in a list with a lambda expression: "); List<int> allNumbersGT5AndLT8 = numbers.FindAll(num => num > 5 && num < 8); foreach (int n in allNumbersGT5AndLT8) { Console.WriteLine("\t{0}", n.ToString()); } Console.WriteLine(); // -------- Anonymous methods vs. lambda expressions -------- Console.WriteLine("\n3a. Do an action on numbers list using an anonymous method:"); numbers.ForEach(delegate(int num) { Console.WriteLine("Number before {0} is {1}", num, num - 1); }); Console.WriteLine("\n3b. Do an action on numbers list using a lambda expression:"); // You can also make a compact loop with this kind of code. numbers.ForEach(i => Console.WriteLine("I'm {0}; my square is {1}", i, i * i)); // Use an anonymous method to supply an on-the-fly delegate instance to a work-horse method that // takes a delegate-type parameter. The delegate is called HandleTwo - see delegate definitions. // Instead of creating the delegate, then invoking it, this example simply creates it in the // process of passing a delegate instance to a method. Console.WriteLine("\n4. Another Anonymous Method Example: "); int result = Multiply(2, 3, delegate(int n, int m) { return n * m; }); Console.WriteLine("\tProduct of {0} * {1} is {2}", 2, 3, result); // Now do the same as above, but with a lambda expression. // Note: This is an example of a lambda that takes multiple parameters. // That's because it's based on a delegate that takes two parameters, the HandleTwo delegate // (technically, the lambda gets resolved to a delegate similar to HandleTwo). Console.WriteLine("\n5. Previous example but with a lambda expression: "); int result3 = Multiply(2, 3, (n, m) => n * m); Console.WriteLine("\tProduct of {0} * {1} is {2}", 2, 3, result3); Console.WriteLine("\n6. Try invoking a null delegate: Oops!"); try { int result4 = Multiply(2, 3, null); } catch (ArgumentNullException e) { Console.WriteLine(e.Message); } Console.WriteLine("\nPress Enter to terminate..."); Console.Read(); }