/// <summary> Writes a formatted message with info header </summary> public static void Info(this string tpl, params object[] args) => ConsoleUtils.Info(tpl.Args(args));
static void run(string[] args) { using (var app = new AzosApplication(args, null)) { var silent = app.CommandArgs["s", "silent"].Exists; if (!silent) { ConsoleUtils.WriteMarkupContent(typeof(ProgramBody).GetText("Welcome.txt")); ConsoleUtils.Info("Build information:"); Console.WriteLine(" Azos: " + BuildInformation.ForFramework); Console.WriteLine(" Tool: " + new BuildInformation(typeof(agm.ProgramBody).Assembly)); } if (app.CommandArgs["?", "h", "help"].Exists) { ConsoleUtils.WriteMarkupContent(typeof(ProgramBody).GetText("Help.txt")); return; } var authority = app.CommandArgs.AttrByIndex(0).Value; var connectToAuthority = authority.ToResolvedServiceNode(false).ConnectString; var scope = app.CommandArgs.AttrByIndex(1).Value; var seq = app.CommandArgs.AttrByIndex(2).Value; var bsize = app.CommandArgs.AttrByIndex(3).ValueAsInt(1); if (!silent) { ConsoleUtils.Info("Authority: " + authority); ConsoleUtils.Info("Connect to: " + connectToAuthority); ConsoleUtils.Info("Scope: " + scope); ConsoleUtils.Info("Sequence: " + seq); ConsoleUtils.Info("Block Size: " + bsize); } var w = System.Diagnostics.Stopwatch.StartNew(); var generator = new GdidGenerator(app); generator.AuthorityHosts.Register(new GdidGenerator.AuthorityHost(app, connectToAuthority)); var json = app.CommandArgs["j", "json"].Exists; var arr = app.CommandArgs["array"].Exists; if (arr) { Console.WriteLine("["); } for (var i = 0; i < bsize; i++) { var gdid = generator.GenerateOneGdid(scope, seq, bsize - i, noLWM: true); string line; if (json) { line = new { Era = gdid.Era, ID = gdid.ID, Authority = gdid.Authority, Counter = gdid.Counter } }
// private static readonly DummyUtils dummyUtils = new DummyUtils(coverageUtils); static async Task Main(string[] args) { #region Validations if (args.Length < 3) { Console.WriteLine("Not enough arguments"); return; } if (!File.Exists(args[0])) { Console.WriteLine($"Users file: {args[0]} Could not be found."); return; } if (!File.Exists(args[1])) { Console.WriteLine($"Document types: {args[1]} Could not be found."); return; } if (!File.Exists(args[2])) { Console.WriteLine($"File names: {args[1]} Could not be found."); return; } #endregion string usersFileName = args[0]; string reportTypesFileName = args[1]; string fileNamesFileName = args[2]; #region GetInput string indexName; int totalOperations; DateTime dateEnd; Console.Write("Use default values? [y/...]: "); if (Console.ReadLine() != "y") { Console.Write("Index name: "); indexName = Console.ReadLine(); totalOperations = ConsoleUtils.PromptValue("Total operations: "); Console.Write("Date to start from(yyyy/MM/dd): "); dateEnd = DateTime.ParseExact( Console.ReadLine(), "yyyy/MM/dd", CultureInfo.CurrentCulture ); } else { indexName = "cpas_downloaded_documents"; totalOperations = 7_000; dateEnd = DateTime.Now; } #endregion int operationsPerDay = totalOperations / 365; Console.WriteLine($"Operations per day: {operationsPerDay}"); List <CpasUser> users = GetUsers(usersFileName); List <CpasUser> parsedBosses = GetSubstitutionableUsers(users) .ToList(); List <ReportFile> files = GetFilenames(fileNamesFileName); List <ReportType> reportTypes = GetReportTypes(reportTypesFileName, out List <double> weights); double[] softmaxedWeights = coverageUtils .SoftmaxFn(weights.ToArray()); Console.WriteLine("Softmaxed: "); foreach (var t in softmaxedWeights) { Console.WriteLine(t); } List <CoverageInfo <ReportType> > reportTypesCoverage = reportTypes .Select((x, i) => new CoverageInfo <ReportType>(x, softmaxedWeights[i])) .ToList(); int operationsGenerated = 0; int totalReports = 0; DateTime dateStart = dateEnd.AddYears(-1); StringBuilder builder = new StringBuilder(500_000); for (int i = 0; i < 365; i++) { dateStart = dateStart.AddDays(1); if (i % 7 == 0) { Console.WriteLine($"Week: {i / 7}"); } int operations = (int)(operationsPerDay * CoverageConfig.TrafficCoefficientOfWeek[(int)dateStart.DayOfWeek] + random.Next(10)); operationsGenerated += operations; for (int j = 0; j < operations; j++) { AppendNewDocument( builder, indexName, files, coverageUtils.GetProbabilisticRandom(reportTypesCoverage), users, parsedBosses, dateStart, $"{i}_{j}", ref totalReports ); } StringContent content = new StringContent(builder.ToString()); content.Headers.ContentType = new MediaTypeHeaderValue(MediaTypeNames.Application.Json); await $"{Config.ElasticSearchAddress}/_bulk" .PostAsync(content); // Console.WriteLine($"Sending data: {builder}"); builder.Clear(); } Console.WriteLine($"Operations in total: {operationsGenerated}"); Console.WriteLine($"Total reports sent: {totalReports}"); }
public void OnDisconnected(DisconnectCause cause) { ConsoleUtils.Log("Disconnected -> " + cause.ToString()); }
private static void run(string[] args) { var config = new CommandArgsConfiguration(args); ConsoleUtils.WriteMarkupContent(typeof(ProgramBody).GetText("Welcome.txt")); if (config.Root["?", "h", "help"].Exists) { ConsoleUtils.WriteMarkupContent(typeof(ProgramBody).GetText("Help.txt")); return; } var asmFileName = config.Root.AttrByIndex(0).Value; var path = config.Root.AttrByIndex(1).Value; if (asmFileName.IsNullOrWhiteSpace()) { throw new Exception("Assembly missing"); } if (path.IsNullOrWhiteSpace()) { throw new Exception("Output path is missing"); } if (!File.Exists(asmFileName)) { throw new Exception("Assembly file does not exist"); } if (!Directory.Exists(path)) { throw new Exception("Output path does not exist"); } //20191106 DKh //var assembly = Assembly.LoadFrom(asmFileName); Assembly assembly; try { assembly = Assembly.LoadFrom(asmFileName); var allTypes = CodeGenerator.DefaultScanForAllRowTypes(assembly); //this throws on invalid loader exception as var schemas = allTypes.Select(t => Schema.GetForTypedDoc(t)).ToArray();//it touches all type/schemas because of .ToArray() ConsoleUtils.Info("Assembly contains {0} data document schemas".Args(schemas.Length)); } catch (Exception asmerror) { ConsoleUtils.Error("Could not load assembly: `{0}`".Args(asmFileName)); ConsoleUtils.Warning("Exception: "); ConsoleUtils.Warning(asmerror.ToMessageWithType()); Console.WriteLine(); ConsoleUtils.Warning(new WrappedExceptionData(asmerror).ToJson(JsonWritingOptions.PrettyPrintASCII)); throw; } using (var generator = new CodeGenerator()) { generator.RootPath = path; generator.CodeSegregation = config.Root["c", "code"].AttrByIndex(0).ValueAsEnum(CodeGenerator.GeneratedCodeSegregation.FilePerNamespace); generator.HeaderDetailLevel = config.Root["hdr", "header", "hl"].AttrByIndex(0).ValueAsInt(255); generator.Generate(assembly); } }
private async Task ExecuteCommandAsync(string outCommand, Path jsonFilename) { ConsoleUtils.RunExecutable(outCommand, $"\"{jsonFilename.FullPath}\""); await Task.CompletedTask; }
public void OnLeftRoom() { GeneralUtils.CurrentRoom = "None"; GeneralUtils.CurrentRoomName = "None"; ConsoleUtils.Log($"[Client #{ClientIndex}] Left Room."); }
public void AvcDecode(SceMpegAu *MpegAccessUnit, int FrameWidth, GuPixelFormats GuPixelFormat, PspPointer OutputBuffer) { if (MpegAccessUnit != null) { *MpegAccessUnit = GetAvcAu(StreamId.Avc); } while (MpegPsDemuxer.HasMorePackets) { if (!DecodePsPacket()) { return; } } if (VideoStream.Length <= 0) { return; } // Buffer 1MB //if (VideoStream.Length <= 1 * 1024 * 1024) return; try { //if (H264FrameDecoder.HasMorePackets) { //Console.WriteLine("VideoStream.Length: {0}", VideoStream.Length); var Frame = H264FrameDecoder.DecodeFrame(); ConsoleUtils.SaveRestoreConsoleColor(ConsoleColor.DarkGreen, () => { Console.WriteLine("DecodedFrame: {0}", FrameIndex); }); var Bitmap = FrameUtils.imageFromFrameWithoutEdges(Frame, FrameWidth, 272); var TempBuffer = new byte[PixelFormatDecoder.GetPixelsSize(GuPixelFormat, Bitmap.Width * Bitmap.Height)]; fixed(byte *TempBufferPtr = TempBuffer) { var TempBufferPtr2 = TempBufferPtr; Bitmap.LockBitsUnlock(PixelFormat.Format32bppArgb, (BitmapData) => { var InputBuffer = (OutputPixel *)BitmapData.Scan0.ToPointer(); int Count = Bitmap.Width * Bitmap.Height; for (int n = 0; n < Count; n++) { var Color = InputBuffer[n]; InputBuffer[n].R = Color.B; InputBuffer[n].G = Color.G; InputBuffer[n].B = Color.R; InputBuffer[n].A = 0xFF; } PixelFormatDecoder.Encode(GuPixelFormat, InputBuffer, TempBufferPtr2, Bitmap.Width * Bitmap.Height); PixelFormatDecoder.Encode(PspDisplay.CurrentInfo.PixelFormat, InputBuffer, (byte *)Memory.PspAddressToPointerSafe(PspDisplay.CurrentInfo.FrameAddress), 512, Bitmap.Width, Bitmap.Height); PspDisplay.CurrentInfo.PlayingVideo = true; }); PspDisplay.CurrentInfo.PlayingVideo = true; Memory.WriteBytes(OutputBuffer.Address, TempBufferPtr, TempBuffer.Length); GpuImpl.InvalidateCache(OutputBuffer.Address, TempBuffer.Length); } if (SaveBitmapFrame) { Bitmap.Save(@"c:\temp\frame" + FrameIndex + ".png"); } FrameIndex++; } //PixelFormat return; } catch (EndOfStreamException) { ConsoleUtils.SaveRestoreConsoleColor(ConsoleColor.Red, () => { Console.WriteLine("H264FrameDecoder.DecodeFrame: EndOfStreamException"); }); } }
private static void run(string[] args) { var config = new CommandArgsConfiguration(args); ConsoleUtils.WriteMarkupContent(typeof(Program).GetText("Welcome.txt")); if (config.Root["?"].Exists || config.Root["h"].Exists || config.Root["help"].Exists) { ConsoleUtils.WriteMarkupContent(typeof(Program).GetText("Help.txt")); return; } if (!config.Root.AttrByIndex(0).Exists) { ConsoleUtils.Error("Template source path is missing"); return; } var files = getFiles(config.Root); var ctypename = config.Root["c"].AttrByIndex(0).Value ?? config.Root["compiler"].AttrByIndex(0).Value; var ctype = string.IsNullOrWhiteSpace(ctypename)? typeof(NFX.Templatization.TextCSTemplateCompiler) : Type.GetType(ctypename); if (ctype == null) { throw new NFXException("Can not create compiler type: " + (ctypename ?? "<none>")); } var compiler = Activator.CreateInstance(ctype) as TemplateCompiler; var onode = config.Root["options"]; if (!onode.Exists) { onode = config.Root["o"]; } if (onode.Exists) { ConfigAttribute.Apply(compiler, onode); var asms = onode.AttrByName("ref").ValueAsString(string.Empty).Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (var asm in asms) { compiler.ReferenceAssembly(asm); } } showOptions(compiler); foreach (var f in files) { var src = new FileTemplateStringContentSource(f); ConsoleUtils.Info("Included: " + src.GetName(50)); compiler.IncludeTemplateSource(src); } compiler.Compile(); if (compiler.HasErrors) { showErrors(compiler, config.Root); return; } if (config.Root["src"].Exists) { writeToDiskCompiledSourceFiles(compiler, config.Root); } }
public async Task DoShow() { // get currently logged in user var currentUser = await _instaApi.GetCurrentUserAsync(); Console.WriteLine( $"Logged in: username - {currentUser.Value.UserName}, full name - {currentUser.Value.FullName}"); // get followers of user 'elonmusk' var followers = await _instaApi.UserProcessor.GetUserFollowersAsync("elonmusk", PaginationParameters.MaxPagesToLoad(5) .StartFromMaxId("AQAC8w90POWyM7zMjHWmO9vsZNL_TuLp6FR506_C_y3fUAjlCclrIDI2RdSGvur5UjLrq4Cq7NJN8QUhHG-vpbT6pCLB5X9crDxBOHUEuNJ4fA")); Console.WriteLine($"Count of followers [elonmusk]:{followers.Value.Count}"); Console.WriteLine($"Next id will be: '{followers.Value.NextMaxId}'"); // get self folling var following = await _instaApi.UserProcessor.GetUserFollowingAsync(currentUser.Value.UserName, PaginationParameters.MaxPagesToLoad(5)); Console.WriteLine($"Count of following [{currentUser.Value.UserName}]:{following.Value.Count}"); // get self user's media, latest 5 pages var currentUserMedia = await _instaApi.UserProcessor.GetUserMediaAsync(currentUser.Value.UserName, PaginationParameters.MaxPagesToLoad(5)); if (currentUserMedia.Succeeded) { Console.WriteLine($"Media count [{currentUser.Value.UserName}]: {currentUserMedia.Value.Count}"); foreach (var media in currentUserMedia.Value) { ConsoleUtils.PrintMedia("Self media", media, _maxDescriptionLength); } } //get user time line feed, latest 5 pages var userFeed = await _instaApi.FeedProcessor.GetUserTimelineFeedAsync(PaginationParameters.MaxPagesToLoad(5)); if (userFeed.Succeeded) { Console.WriteLine( $"Feed items (in {userFeed.Value.MediaItemsCount} pages) [{currentUser.Value.UserName}]: {userFeed.Value.Medias.Count}"); foreach (var media in userFeed.Value.Medias) { ConsoleUtils.PrintMedia("Feed media", media, _maxDescriptionLength); } //like first 10 medias from user timeline feed foreach (var media in userFeed.Value.Medias.Take(10)) { var likeResult = await _instaApi.MediaProcessor.LikeMediaAsync(media.InstaIdentifier); var resultString = likeResult.Value ? "liked" : "not liked"; Console.WriteLine($"Media {media.Code} {resultString}"); } } // get tag feed, latest 5 pages var tagFeed = await _instaApi.FeedProcessor.GetTagFeedAsync("quadcopter", PaginationParameters.MaxPagesToLoad(5)); if (tagFeed.Succeeded) { Console.WriteLine( $"Tag feed items (in {tagFeed.Value.MediaItemsCount} pages) [{currentUser.Value.UserName}]: {tagFeed.Value.Medias.Count}"); foreach (var media in tagFeed.Value.Medias) { ConsoleUtils.PrintMedia("Tag feed", media, _maxDescriptionLength); } } }
/// <inheritdoc /> public Transition() { Data.Conditions = new List <ICondition>(); Data.TargetStep = null; if (LifeCycleLoggingConfig.Instance.LogTransitions) { LifeCycle.StageChanged += (sender, args) => { Debug.LogFormat("{0}<b>Transition to</b> <i>{1}</i> is <b>{2}</b>.\n", ConsoleUtils.GetTabs(3), Data.TargetStep != null ? Data.TargetStep.Data.Name + " (Step)" : "chapter's end", LifeCycle.Stage); }; } }
static void run(string[] args) { const string FROM = "APH.Program"; using (var app = new SkyApplication(SystemApplicationType.ProcessHost, args, null)) { try { using (var procHost = new ProcessControllerService(null)) { procHost.Configure(null); procHost.Start(); try { // WARNING: Do not modify what this program reads/writes from/to standard IO streams because // AHGOV uses those particular string messages for its protocol Console.WriteLine("OK."); //<-- AHGOV protocol, AHGOV waits for this token to assess startup situation ConsoleUtils.WriteMarkupContent(typeof(ProgramBody).GetText("Welcome.txt")); Console.WriteLine("Waiting for line to terminate..."); var abortableConsole = new TerminalUtils.AbortableLineReader(); try { while (app.Active) { if (abortableConsole.Line != null) { app.Log.Write(new Message { Type = MessageType.Info, Topic = SysConsts.LOG_TOPIC_WWW, From = FROM, Text = "Main loop received CR|LF. Exiting..." }); break; //<-- AHGOV protocol, AHGOV sends a <CRLF> when it is time to shut down } Thread.Sleep(250); } } finally { abortableConsole.Abort(); } } finally { procHost.WaitForCompleteStop(); } } } catch (Exception error) { app.Log.Write(new Message { Type = MessageType.CatastrophicError, Topic = SysConsts.LOG_TOPIC_SVC, From = FROM, Text = "Exception leaked in run(): " + error.ToMessageWithType(), Exception = error }); throw error; } }//using app }
/// <summary> Writes a formatted message with error header </summary> public static void Error(this string tpl, int ln, params object[] args) => ConsoleUtils.Error(tpl.Args(args), ln);
/// <summary> Writes a formatted message with warning header </summary> public static void Warning(this string tpl, params object[] args) => ConsoleUtils.Warning(tpl.Args(args));
static void Main(string[] args) { ConsoleUtils.UserInput(); }
protected Condition() { if (LifeCycleLoggingConfig.Instance.LogConditions) { LifeCycle.StageChanged += (sender, args) => { Debug.LogFormat("{0}<b>Condition</b> <i>'{1} ({2})'</i> is <b>{3}</b>.\n", ConsoleUtils.GetTabs(2), Data.Name, GetType().Name, LifeCycle.Stage); }; } }
private static void run(IConfigSectionNode args) { var pretty = args["pp", "pretty"].Exists; var noEntropy = args["ne", "noentropy"].Exists; var scoreThreshold = args["st", "score"].AttrByIndex(0).ValueAsInt(80); if (scoreThreshold < 20) { scoreThreshold = 20; } if (scoreThreshold > 100) { scoreThreshold = 100; } var strength = args["lvl", "level"].AttrByIndex(0).ValueAsEnum <PasswordStrengthLevel>(PasswordStrengthLevel.Default); ConsoleUtils.WriteMarkupContent(typeof(Program).GetText("Welcome.txt")); if (args["?", "h", "help"].Exists) { ConsoleUtils.WriteMarkupContent(typeof(Program).GetText("Help.txt")); return; } ConsoleUtils.Info("Score Threshold: {0}%".Args(scoreThreshold)); ConsoleUtils.Info("Stength level: {0}".Args(strength)); if (!noEntropy) { var count = ExternalRandomGenerator.Instance.NextScaledRandomInteger(47, 94); ConsoleUtils.Info("Acquiring entropy from user..."); Console.WriteLine(); ConsoleUtils.WriteMarkupContent( @"<push> <f color=magenta>Please make <f color=white>{0}<f color=magenta> random keystrokes Do not hit the same key and try to space key presses in time:<pop> ".Args(count)); var pnow = Stopwatch.GetTimestamp(); Console.WriteLine(); for (var i = 0; i < count; i++) { var k = Console.ReadKey(true).KeyChar; if (k < 0x20) { continue; } var now = Stopwatch.GetTimestamp(); var elapsed = (int)(39621 * (k - 0x19) * (now - pnow)); pnow = now; ExternalRandomGenerator.Instance.FeedExternalEntropySample(elapsed); Console.Write("\r{0} {1} characters to go ...", elapsed, count - i - 1); } ConsoleUtils.Info("OK. Entropy key entered"); Console.WriteLine("-----------------------"); System.Threading.Thread.Sleep(3000); while (Console.KeyAvailable) { Console.ReadKey(true); } } SecureBuffer password = null; while (true) { Console.WriteLine("Please type-in your password and press <enter>:"); password = ConsoleUtils.ReadPasswordToSecureBuffer('*'); var score = App.SecurityManager.PasswordManager.CalculateStrenghtPercent(PasswordFamily.Text, password); var pass = score >= scoreThreshold; Console.WriteLine(); var t = "Password score: {0}% is {1} strong".Args(score, pass ? "sufficiently" : "insufficiently"); if (pass) { ConsoleUtils.Info(t); break; } ConsoleUtils.Error(t); Console.WriteLine(); } Console.WriteLine(); while (true) { Console.WriteLine("Please re-type your password and press <enter>:"); using (var p2 = ConsoleUtils.ReadPasswordToSecureBuffer('*')) if (password.Content.MemBufferEquals(p2.Content)) { break; } ConsoleUtils.Error("Passwords do not match"); } Console.WriteLine(); Console.WriteLine(); var hashed = App.SecurityManager.PasswordManager.ComputeHash( NFX.Security.PasswordFamily.Text, password, strength); password.Dispose(); var toPrint = JSONWriter.Write(hashed, pretty ? JSONWritingOptions.PrettyPrintASCII : JSONWritingOptions.CompactASCII); Console.WriteLine("Hashed Password:"); Console.WriteLine(); Console.WriteLine(toPrint); }
static void run(string[] args) { using (var app = new AzosApplication(args, null)) { var silent = app.CommandArgs["s", "silent"].Exists; if (!silent) { ConsoleUtils.WriteMarkupContent(typeof(ProgramBody).GetText("Welcome.txt")); ConsoleUtils.Info("Build information:"); Console.WriteLine(" Azos: " + BuildInformation.ForFramework); Console.WriteLine(" Tool: " + new BuildInformation(typeof(ascon.ProgramBody).Assembly)); } if (app.CommandArgs["?", "h", "help"].Exists) { ConsoleUtils.WriteMarkupContent(typeof(ProgramBody).GetText("Help.txt")); return; } var cred = app.CommandArgs["c", "cred"]; var user = cred.AttrByName("id").Value; var pwd = cred.AttrByName("pwd").Value; if (user.IsNullOrWhiteSpace()) { if (!silent) { Console.Write("User ID: "); } user = Console.ReadLine(); } else if (!silent) { ConsoleUtils.Info("User ID: " + user); } if (pwd.IsNullOrWhiteSpace()) { if (!silent) { Console.Write("Password: "******"Password: <supplied>"); } var node = app.CommandArgs.AttrByIndex(0).ValueAsString("{0}://127.0.0.1:{1}".Args(SysConsts.APTERM_BINDING, SysConsts.DEFAULT_HOST_GOV_APPTERM_PORT)); if (new Node(node).Binding.IsNullOrWhiteSpace()) { node = "{0}://{1}".Args(SysConsts.APTERM_BINDING, node); } if (new Node(node).Service.IsNullOrWhiteSpace()) { node = "{0}:{1}".Args(node, SysConsts.DEFAULT_HOST_GOV_APPTERM_PORT); } var file = app.CommandArgs["f", "file"].AttrByIndex(0).Value; if (file.IsNotNullOrWhiteSpace()) { if (!System.IO.File.Exists(file)) { throw new SkyException("File not found:" + file); } if (!silent) { ConsoleUtils.Info("Reading from file: " + file); } file = System.IO.File.ReadAllText(file); if (!silent) { ConsoleUtils.Info("Command text: " + file); } } var txt = app.CommandArgs["t", "txt"].AttrByIndex(0).Value; if (txt.IsNotNullOrWhiteSpace()) { if (!silent) { ConsoleUtils.Info("Verbatim command text: " + txt); } } var credentials = new IDPasswordCredentials(user, pwd); using (var client = new RemoteTerminal(app.Glue, node.ToResolvedServiceNode(true))) { client.Headers.Add(new AuthenticationHeader(credentials)); var hinfo = client.Connect("{0}@{1}".Args(user, System.Environment.MachineName)); if (!silent) { var c = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine("Connected. Use ';' at line end to submit statement, 'exit;' to disconnect"); Console.WriteLine("Type 'help;' for edification or '<command> /?;' for command-specific help"); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine(hinfo.WelcomeMsg); Console.ForegroundColor = c; } if (txt.IsNotNullOrWhiteSpace() || file.IsNotNullOrWhiteSpace()) { try { if (txt.IsNotNullOrWhiteSpace()) { write(client.Execute(txt)); } if (file.IsNotNullOrWhiteSpace()) { write(client.Execute(file)); } } catch (RemoteException remoteError) { TerminalUtils.ShowRemoteException(remoteError); Environment.ExitCode = -1; } } else { while (true) { if (!silent) { var c = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.White; Console.Write("{0}@{1}@{2} ".Args(hinfo.TerminalName, hinfo.AppName, hinfo.Host)); Console.ForegroundColor = ConsoleColor.Cyan; Console.Write("{0:hh:mm:ss.fff}".Args(app.TimeSource.LocalizedTime)); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine(app.TimeSource.TimeLocation.ToString()); Console.ForegroundColor = ConsoleColor.White; Console.Write("$ "); Console.ForegroundColor = c; } var command = ""; while (true) { var ln = Console.ReadLine(); command += ln; if (ln.EndsWith(";")) { break; } if (!silent) { var c = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.White; Console.Write(">"); Console.ForegroundColor = c; } } command = command.Remove(command.Length - 1, 1); if (command == "exit") { break; } string response = null; try { response = client.Execute(command); } catch (RemoteException remoteError) { TerminalUtils.ShowRemoteException(remoteError); continue; } write(response); } } var disconnectMessage = client.Disconnect(); if (!silent) { write(disconnectMessage); } } } }//run
public static void run(string[] args) { ConsoleUtils.WriteMarkupContent(typeof(ProgramBody).GetText("Welcome.txt")); ConsoleUtils.Info("Running on a `{0}` platform".Args(Azos.Platform.Abstraction.PlatformAbstractionLayer.PlatformName)); Console.WriteLine("Init app container..."); //////System.Threading.ThreadPool.SetMaxThreads(1000, 1000); using (var app = new AzosApplication(args, null)) { Console.WriteLine("...app container is up"); var cmd = app.CommandArgs.AttrByIndex(0).Value; if (app.CommandArgs["?"].Exists || app.CommandArgs["h"].Exists || app.CommandArgs["help"].Exists) { ConsoleUtils.WriteMarkupContent(typeof(ProgramBody).GetText("Help.txt")); return; } ConsoleUtils.Info("Glue servers:"); var any = false; foreach (var s in app.Glue.Servers) { Console.WriteLine(" " + s); any = true; } if (!any) { Console.WriteLine(" - No servers"); } Console.WriteLine(); if (cmd.EqualsOrdIgnoreCase("machine")) { MachineSpeed.CRC32(); } else if (cmd.EqualsOrdIgnoreCase("slim")) { SlimSpeed.SerDeserSimpleObject(); SlimSpeed.SerDeserPerson(); SlimSpeed.SerDeserPersonArray(); } else if (cmd.EqualsOrdIgnoreCase("echo")) { var node = app.CommandArgs.AttrByIndex(1).ValueAsString() ?? "sync://127.0.0.1:8000"; var count = app.CommandArgs["c"].AttrByIndex(0).ValueAsInt(1000); //count of requests var par = app.CommandArgs["p"].AttrByIndex(0).ValueAsInt(1); //max degree of parallelism // GlueSpeed.Echo(node, count, par); GlueSpeed.EchoThreaded(app.Glue, node, count, par); } else if (cmd.EqualsOrdIgnoreCase("pile")) { var threads = app.CommandArgs["t"].AttrByIndex(0).ValueAsInt(4); var count = app.CommandArgs["c"].AttrByIndex(0).ValueAsInt(20_000_000); var size = app.CommandArgs["sz"].AttrByIndex(0).ValueAsInt(32); PileSpeed.ProfileByteArray(app, threads, count, size); PileSpeed.ProfileString(app, threads, count, size); PileSpeed.ProfileSimpleObject(app, threads, count); PileSpeed.ProfilePersonObject(app, threads, count); } else if (cmd.EqualsOrdIgnoreCase("wave")) { using (var ws = new WaveServer(app)) { ws.Configure(null); ws.IgnoreClientWriteErrors = false; ws.Start(); Console.WriteLine("Web server started"); Console.WriteLine("Strike <ENTER> to terminate web server "); Console.ReadLine(); } } Console.WriteLine("Strike <ENTER> to exit app"); Console.ReadLine(); Console.WriteLine("Shutting app container..."); } Console.WriteLine("...app container is disposed"); }
static void run(string[] args) { using (var app = new AzosApplication(allowNesting: true, cmdArgs: args, rootConfig: null)) { var silent = app.CommandArgs["s", "silent"].Exists; if (!silent) { ConsoleUtils.WriteMarkupContent(typeof(ProgramBody).GetText("Welcome.txt")); ConsoleUtils.Info("Build information:"); Console.WriteLine(" Azos: " + BuildInformation.ForFramework); Console.WriteLine(" Tool: " + new BuildInformation(typeof(amm.ProgramBody).Assembly)); } if (app.CommandArgs["?", "h", "help"].Exists) { ConsoleUtils.WriteMarkupContent(typeof(ProgramBody).GetText("Help.txt")); return; } var mbPath = app.CommandArgs .AttrByIndex(0) .ValueAsString(System.Environment.GetEnvironmentVariable(BootConfLoader.ENV_VAR_METABASE_FS_ROOT)); if (!Directory.Exists(mbPath)) { throw new Exception("Specified metabase path not found"); } var fromHost = app.CommandArgs["host", "from"].AttrByIndex(0).Value; if (fromHost.IsNullOrWhiteSpace()) { fromHost = System.Environment.GetEnvironmentVariable(BootConfLoader.ENV_VAR_HOST_NAME); } if (!silent) { ConsoleUtils.Info("Metabase path: " + mbPath); ConsoleUtils.Info("Host (this machine): " + fromHost); } var w = System.Diagnostics.Stopwatch.StartNew(); using (var fs = new LocalFileSystem(app)) { using (var skyApp = new SkyApplication(app, SystemApplicationType.Tool, fs, new FileSystemSessionConnectParams(), mbPath, fromHost, allowNesting: false, cmdArgs: null, rootConfig: null)) { if (app.CommandArgs["gbm"].Exists) { generateManifests(skyApp.Metabase, silent); } else { validate(skyApp.Metabase, silent); } } } if (!silent) { Console.WriteLine(); ConsoleUtils.Info("Run time: " + w.Elapsed.ToString()); } }//using APP }
public void OnConnectedToMaster() { ConsoleUtils.Log($"[Client #{ClientIndex}] Connected to Region Master USW"); this.SetCustomProperties(Token, User, Avatar); ConsoleUtils.Log($"[Client #{ClientIndex}] Set Custom Properties"); }
public void PerformTask() { var resources = new ResourceManager("Win10BloatRemover.resources.Resources", typeof(Program).Assembly); ConsoleUtils.WriteLine(resources.GetString("LicenseText"), ConsoleColor.Cyan); }
public void OnJoinedRoom() { GeneralUtils.CurrentRoom = CurrentRoom.Name; ConsoleUtils.Log($"[Client #{ClientIndex}] Joined Room."); }
private static void run(string[] args) { var config = new CommandArgsConfiguration(args); if (config.Root["?"].Exists || config.Root["h"].Exists || config.Root["help"].Exists) { ConsoleUtils.WriteMarkupContent(typeof(Program).GetText("Help.txt")); return; } if (!config.Root.AttrByIndex(0).Exists) { Console.WriteLine("Specify ';'-delimited assembly list"); return; } var manager = new InventorizationManager(config.Root.AttrByIndex(0).Value); var fnode = config.Root["f"]; if (!fnode.Exists) { fnode = config.Root["filter"]; } if (fnode.Exists) { ConfigAttribute.Apply(manager, fnode); } foreach (var n in config.Root.Children.Where(chi => chi.IsSameName("s") || chi.IsSameName("strat") || chi.IsSameName("strategy"))) { var tname = n.AttrByIndex(0).Value ?? "<unspecified>"; Type t = Type.GetType(tname); if (t == null) { throw new NFXException("Can not create strategy type: " + tname); } var strategy = Activator.CreateInstance(t) as IInventorization; if (strategy == null) { throw new NFXException("The supplied type is not strategy: " + tname); } manager.Strategies.Add(strategy); } if (manager.Strategies.Count == 0) { manager.Strategies.Add(new BasicInventorization()); } // if (config.Root["any"].Exists) // manager.OnlyAttributed = false; var result = new XMLConfiguration(); result.Create("inventory"); manager.Run(result.Root); Console.WriteLine(result.SaveToString()); }
public void Run(string[] args) { if (!ParseCommonCommandLineArgs(ref args, out var credential)) { return; } bool dryrun = false; var categoryModifications = new List <CategoryModification>(); for (var i = 0; i < args.Length; i++) { switch (args[i]) { case "--dry-run": case "-n": dryrun = true; break; default: { var pos = args[i].IndexOf(':'); if (0 <= pos) { var categoriesOld = args[i].Substring(0, pos).Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); var categoriesNew = args[i].Substring(pos + 1).Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (0 < categoriesOld.Length || 0 < categoriesNew.Length) { categoryModifications.Add(new CategoryModification(new CategorySet(categoriesOld, StringComparer.Ordinal), new CategorySet(categoriesNew, StringComparer.Ordinal))); } } break; } } } if (categoryModifications.Count <= 0) { Usage("変更するカテゴリを指定してください"); } Console.WriteLine("以下のカテゴリを変更します"); foreach (var modification in categoryModifications) { if (modification.Old.Count == 0) { Console.WriteLine("(新規設定) -> {0}", Join(modification.New)); } else if (modification.New.Count == 0) { Console.WriteLine("{0} -> (削除)", Join(modification.Old)); } else { Console.WriteLine("{0} -> {1}", Join(modification.Old), Join(modification.New)); } } Console.WriteLine(); if (!Login(credential, out var hatenaBlog)) { return; } Console.WriteLine("エントリを取得中 ..."); List <PostedEntry> entries = null; try { entries = hatenaBlog.EnumerateEntries().ToList(); } catch (WebException ex) { Console.Error.WriteLine(ex.Message); return; } Console.WriteLine("以下のエントリのカテゴリが変更されます"); var modifiedEntries = new List <PostedEntry>(entries.Count); foreach (var entry in entries) { var prevCategories = new CategorySet(entry.Categories, entry.Categories.Comparer); foreach (var modification in categoryModifications) { modification.Apply(entry.Categories); } if (prevCategories.SetEquals(entry.Categories)) { continue; // 変更なし } modifiedEntries.Add(entry); Console.WriteLine("{0} \"{1}\" {2} -> {3}", entry.EntryUri, entry.Title, Join(prevCategories), Join(entry.Categories)); } if (modifiedEntries.Count == 0) { Console.WriteLine("カテゴリが変更されるエントリはありません"); return; } if (dryrun) { return; } if (!ConsoleUtils.AskYesNo("変更しますか ")) { Console.WriteLine("変更を中断しました"); return; } Console.WriteLine(); foreach (var entry in modifiedEntries) { Console.Write("変更を更新中: {0} \"{1}\" [{2}] ... ", entry.DatePublished, entry.Title, string.Join("][", entry.Categories)); var statusCode = hatenaBlog.UpdateEntry(entry, out _); if (statusCode == HttpStatusCode.OK) { hatenaBlog.WaitForCinnamon(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("更新しました"); Console.ResetColor(); } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("失敗しました ({0})", statusCode); Console.ResetColor(); return; } } Console.WriteLine("変更が完了しました"); }
public static int Main(string[] arguments) { int widthMaximum = Console.LargestWindowWidth - 4; int widthMinimum = 8; int heightMaximum = Console.LargestWindowHeight - 1; int heightMinimum = 1; string file; Settings settings; int value; StringBuilder error = new StringBuilder(); int? width = new int?(); int? height = new int?(); bool?center = new bool?(); bool writeToConfig = false; bool skipWidth = false; bool skipHeight = false; bool skipCenter = false; app = Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location); appLen = Math.Max((app + ".exe").Length, 9); appPadding = new string(' ', appLen); file = Assembly.GetEntryAssembly().Location + ".settings"; settings = new Settings(file); settings.read(); for (int i = 0; i < arguments.Length; i++) { string a = arguments[i].Trim(); if (int.TryParse(a, out value)) { value = Math.Max(value, 4); if (!width.HasValue && !skipWidth) { if (value > widthMaximum) { Console.WriteLine("{0," + appLen + "} | the maximum width allowed for the current screen is {1} columns. using maximum instead.", "** error", widthMaximum); value = widthMaximum; } else if (value < widthMinimum) { Console.WriteLine("{0," + appLen + "} | the minimum width allowed is {1} columns. using minimum instead.", "** error", widthMinimum); value = widthMinimum; } width = value; } else if (!height.HasValue && !skipHeight) { if (value > heightMaximum) { Console.WriteLine("{0," + appLen + "} | the maximum height allowed for the current screen is {1} rows. using maximum instead.", "** error", heightMaximum); value = heightMaximum; } else if (value < heightMinimum) { Console.WriteLine("{0," + appLen + "} | the minimum height allowed is {1} rows. using minimum instead.", "** error", heightMinimum); value = heightMinimum; } height = value; } else { DisplayError(settings, "unknown argument value."); return(2); } } else { if (a.Equals("-")) { // This separator allows the user to skip (not set) the width parameter. // For example: 'shrink.exe - 60' will only change the height and not the width, // much like: 'shrink.exe 100' will only change the width. (a trailing '-' here will be ignored.) if (!width.HasValue) { skipWidth = true; } else if (!height.HasValue) { skipHeight = true; } else { skipCenter = true; } continue; } while (a.StartsWith("-") || a.StartsWith("/")) { a = a.TrimStart('-').TrimStart('/'); } if (a.Equals("?") || a.StartsWith("h", StringComparison.CurrentCultureIgnoreCase)) { DisplayCopyright(); DisplayHelp(settings); DisplayConfig(settings); return(0); } else if (a.Equals("debug", StringComparison.CurrentCultureIgnoreCase)) { DEBUG = true; } else if (a.Equals("clear", StringComparison.CurrentCultureIgnoreCase)) { settings.clear(); settings.write(); } else if (a.Equals("config", StringComparison.CurrentCultureIgnoreCase)) { writeToConfig = true; } else if (a.Equals("!config", StringComparison.CurrentCultureIgnoreCase)) { writeToConfig = false; } else if (a.Equals("center", StringComparison.CurrentCultureIgnoreCase)) { center = true; } else if (a.StartsWith("e", StringComparison.CurrentCultureIgnoreCase)) { LaunchUrl("mailto:Kody Brown <*****@*****.**>"); } else if (a.StartsWith("w", StringComparison.CurrentCultureIgnoreCase)) { LaunchUrl("http://bricksoft.com"); } else if (a.StartsWith("s", StringComparison.CurrentCultureIgnoreCase)) { LaunchUrl("http://github.com/kodybrown/" + app); } else if (a.StartsWith("l", StringComparison.CurrentCultureIgnoreCase)) { LaunchUrl("http://opensource.org/licenses/MIT"); } else { DisplayError(settings, "unknown argument."); return(1); } } } DisplayAppName(); // If '--config' was specified without any other arguments, // it will only output the current values from config. if (writeToConfig && !width.HasValue && !height.HasValue && !center.HasValue) { DisplayCopyright(); DisplayConfig(settings); return(0); } // Write config values before they are (possibly) overwritten below. if (writeToConfig) { if (width.HasValue) { settings.attr <int>("width", width.Value); } if (height.HasValue) { settings.attr <int>("height", height.Value); } if (center.HasValue) { settings.attr <bool>("center", center.Value); } settings.write(); } // If a value was not specified: use the value from config, // otherwise use its current value. if (!width.HasValue) { width = settings.contains("width") ? settings.attr <int>("width") : Console.WindowWidth; } if (!height.HasValue) { height = settings.contains("height") ? settings.attr <int>("height") : Console.WindowHeight; } // If center was not specified, use the value from config, // or default it to defaultCenter. if (!center.HasValue) { center = settings.contains("center") ? settings.attr <bool>("center") : defaultCenter; } // // Update the console. // try { Console.WindowWidth = Math.Min(widthMaximum, Math.Max(widthMinimum, width.Value)); Console.BufferWidth = Console.WindowWidth; } catch (Exception ex) { error.AppendLine(string.Format("{0," + appLen + "} | Could not set the width.", "** error")).AppendLine(ex.Message); } try { Console.WindowHeight = Math.Min(heightMaximum, Math.Max(heightMinimum, height.Value)); } catch (Exception ex) { error.AppendLine(string.Format("{0," + appLen + "} | Could not set the height.", "** error")).AppendLine(ex.Message); } if (!skipCenter && center.HasValue && center.Value) { try { ConsoleUtils.CenterWindow(); } catch (Exception ex) { error.AppendLine(string.Format("{0," + appLen + "} | Could not center the window.", "** error")).AppendLine(ex.Message); } } if (error.Length > 0) { Console.Write(error.ToString()); } if (DEBUG) { Console.Write("press any key to continue: "); Console.ReadKey(true); Console.CursorLeft = 0; Console.Write(" "); Console.CursorLeft = 0; } return(0); }
private Action <CpuThreadState> CreateDelegateForMethodInfo(MethodInfo MethodInfo, HlePspFunctionAttribute HlePspFunctionAttribute) { if (!MethodInfo.DeclaringType.IsAssignableFrom(this.GetType())) { throw (new Exception($"Invalid {MethodInfo.DeclaringType} != {this.GetType()}")); } bool SkipLog = HlePspFunctionAttribute.SkipLog; var NotImplementedAttribute = (HlePspNotImplementedAttribute)MethodInfo .GetCustomAttributes(typeof(HlePspNotImplementedAttribute), true).FirstOrDefault(); bool NotImplementedFunc = (NotImplementedAttribute != null) && NotImplementedAttribute.Notice; List <ParamInfo> ParamInfoList; var AstNodes = AstOptimizerPsp.GlobalOptimize( CpuProcessor, ast.Statements( // Do stuff before CreateDelegateForMethodInfoPriv(MethodInfo, HlePspFunctionAttribute, out ParamInfoList) // Do stuff after ) ); var Delegate = AstNodeExtensions.GeneratorIlPsp.GenerateDelegate <Action <CpuThreadState> >( $"Proxy_{this.GetType().Name}_{MethodInfo.Name}", AstNodes ); //return Delegate; return((CpuThreadState) => { bool Trace = (!SkipLog && CpuThreadState.CpuProcessor.CpuConfig.DebugSyscalls); bool NotImplemented = NotImplementedFunc && HleConfig.DebugNotImplemented; if (Trace && (MethodInfo.DeclaringType.Name == "Kernel_Library")) { Trace = false; } //Console.WriteLine("aaaaaaaaaaaaa"); if (NotImplemented) { Trace = true; ConsoleUtils.SaveRestoreConsoleState(() => { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine( "Not implemented {0}.{1}", MethodInfo.DeclaringType.Name, MethodInfo.Name ); }); } var Out = Console.Out; if (NotImplemented) { Out = Console.Error; } if (Trace) { if (ThreadManager.Current != null) { Out.Write( "Thread({0}:'{1}') : RA(0x{2:X})", ThreadManager.Current.Id, ThreadManager.Current.Name, ThreadManager.Current.CpuThreadState.Ra ); } else { Out.Write("NoThread:"); } Out.Write(" : {0}.{1}", MethodInfo.DeclaringType.Name, MethodInfo.Name); Out.Write("("); int Count = 0; var NormalRegisterReader = new NormalRegisterReader(CpuThreadState); foreach (var ParamInfo in ParamInfoList) { if (Count > 0) { Out.Write(", "); } Out.Write("{0}:", ParamInfo.ParameterInfo.Name); switch (ParamInfo.RegisterType) { case HleModuleHost.ParamInfo.RegisterTypeEnum.Fpr: case HleModuleHost.ParamInfo.RegisterTypeEnum.Gpr: var Object = NormalRegisterReader.Read <uint>(ParamInfo.ParameterInfo); Out.Write("{0}", ToNormalizedTypeString(ParamInfo.ParameterInfo.ParameterType, CpuThreadState, Object)); break; default: throw (new NotImplementedException()); } Count++; } Out.Write(")"); //Console.WriteLine(""); } try { CpuThreadState.Pc = CpuThreadState.Ra; Delegate(CpuThreadState); } catch (InvalidProgramException) { Console.WriteLine("CALLING: {0}", MethodInfo); Console.WriteLine("{0}", (new GeneratorCSharp()).GenerateRoot(AstNodes).ToString()); foreach (var Line in AstNodeExtensions.GeneratorIlPsp.GenerateToStringList(MethodInfo, AstNodes)) { Console.WriteLine(Line); } throw; } catch (MemoryPartitionNoMemoryException) { CpuThreadState.Gpr[2] = (int)SceKernelErrors.ERROR_ERRNO_NO_MEMORY; } catch (SceKernelException SceKernelException) { CpuThreadState.Gpr[2] = (int)SceKernelException.SceKernelError; } catch (SceKernelSelfStopUnloadModuleException) { throw; } #if !DO_NOT_PROPAGATE_EXCEPTIONS catch (Exception Exception) { throw (new Exception( $"ERROR calling {MethodInfo.DeclaringType.Name}.{MethodInfo.Name}!", Exception )); } #endif finally { if (Trace) { Out.WriteLine(" : {0}", ToNormalizedTypeString(MethodInfo.ReturnType, CpuThreadState, ((MethodInfo.ReturnType == typeof(float)) ? (object)CpuThreadState.Fpr[0] : (object)CpuThreadState.Gpr[2]))); Out.WriteLine(""); } } }); }
static void run(string[] args) { const string FROM = "AHGOV.Program"; using (var app = new SkyApplication(SystemApplicationType.HostGovernor, args, null)) { try { var fromARD = app.CommandArgs[SysConsts.ARD_PARENT_CMD_PARAM].Exists; var updateProblem = app.CommandArgs[SysConsts.ARD_UPDATE_PROBLEM_CMD_PARAM].Exists; using (var governor = new HostGovernorService(app, fromARD, updateProblem)) { governor.Configure(null); governor.Start(); try { // WARNING: Do not modify what this program reads/writes from/to standard IO streams because // ARD uses those particular string messages for its protocol Console.WriteLine("OK."); //<-- ARD protocol, ARD waits for this token to assess startup situation ConsoleUtils.WriteMarkupContent(typeof(ProgramBody).GetText("Welcome.txt")); Console.WriteLine("Waiting for line to terminate..."); var abortableConsole = new TerminalUtils.AbortableLineReader(); try { while (app.Active && !governor.NeedsProcessRestart) { if (abortableConsole.Line != null) { app.Log.Write(new Message { Type = MessageType.Info, Topic = SysConsts.LOG_TOPIC_APP_MANAGEMENT, From = FROM, Text = "Main loop received CR|LF. Exiting..." }); break; //<-- ARD protocol, ARD sends a <CRLF> when it is time to shut down } Thread.Sleep(250); } } finally { abortableConsole.Abort(); } } finally { governor.WaitForCompleteStop(); } }//using governor } catch (Exception error) { app.Log.Write(new Message { Type = MessageType.CatastrophicError, Topic = SysConsts.LOG_TOPIC_APP_MANAGEMENT, From = FROM, Text = "Exception leaked in run(): " + error.ToMessageWithType(), Exception = error }); throw error; } }//using APP }
protected void RunFile(bool runTestsViewOut, string pspAutoTestsFolder, string fileNameExecutable, string fileNameExpected, string fileNameBase) { ConsoleUtils.SaveRestoreConsoleColor(ConsoleColor.DarkCyan, () => { Console.Write("{0}...", fileNameExecutable); }); var expectedOutput = File.ReadAllText(fileNameExpected, Encoding.ASCII); var realOutput = ""; var capturedOutput = ""; // Execute. { realOutput = RunExecutableAndGetOutput(runTestsViewOut, pspAutoTestsFolder, fileNameExecutable, out capturedOutput, fileNameBase); } var expectedOutputLines = expectedOutput.Trim().Replace("\r\n", "\n").Split('\n'); var realOutputLines = realOutput.Trim().Replace("\r\n", "\n").Split('\n'); var result = Diff.DiffTextProcessed(expectedOutputLines, realOutputLines); File.WriteAllText( Path.ChangeExtension(fileNameExpected, ".lastoutput"), realOutput ); File.WriteAllText( Path.ChangeExtension(fileNameExpected, ".lastdebug"), capturedOutput ); var hadAnError = false; for (var n = 0; n < 10; n++) { var imageReferenceFile = $"{fileNameBase}.reference.{n}.png"; var imageOutputFile = $"{fileNameBase}.lastoutput.{n}.png"; if (File.Exists(imageReferenceFile)) { if (File.Exists(imageOutputFile)) { var referenceBitmap = new Bitmap(imageReferenceFile); var outputBitmap = new Bitmap(imageOutputFile); if (referenceBitmap.Size == outputBitmap.Size) { var compareResult = BitmapUtils.CompareBitmaps(referenceBitmap, outputBitmap, 0.01); if (compareResult.Equal) { Console.Error.WriteLine( "Files '{0}:{1}' and '{2}:{3}' have different contents {4}/{5} different pixels {6}%", imageReferenceFile, referenceBitmap.Size, imageOutputFile, outputBitmap.Size, compareResult.DifferentPixelCount, compareResult.TotalPixelCount, compareResult.PixelTotalDifferencePercentage ); hadAnError = true; } } else { Console.Error.WriteLine( "Files '{0}:{1}' and '{2}:{3}' have different sizes", imageReferenceFile, referenceBitmap.Size, imageOutputFile, outputBitmap.Size ); hadAnError = true; } } else { Console.Error.WriteLine( "File '{0}' exists, but not exists '{1}'", imageReferenceFile, imageOutputFile ); hadAnError = true; } } } if (result.Items.Any(item => item.Action != Diff.ProcessedItem.ActionEnum.Keep)) { hadAnError = true; } if (!hadAnError) { ConsoleUtils.SaveRestoreConsoleColor(ConsoleColor.Green, () => { Console.WriteLine("Ok"); }); } else { ConsoleUtils.SaveRestoreConsoleColor(ConsoleColor.Red, () => { Console.WriteLine("Error"); }); result.Print(avoidKeep: true); } File.WriteAllText( Path.ChangeExtension(fileNameExpected, ".lastdiff"), result.ToString() ); }
private Action <CpuThreadState> CreateDelegateForMethodInfo(MethodInfo MethodInfo, HlePspFunctionAttribute HlePspFunctionAttribute) { var MipsMethodEmiter = new MipsMethodEmiter(HleState.MipsEmiter, HleState.CpuProcessor); int GprIndex = 4; int FprIndex = 0; var NotImplementedAttribute = (HlePspNotImplementedAttribute)MethodInfo.GetCustomAttributes(typeof(HlePspNotImplementedAttribute), true).FirstOrDefault(); bool NotImplemented = (NotImplementedAttribute != null) ? NotImplementedAttribute.Notice : false; bool SkipLog = HlePspFunctionAttribute.SkipLog; var ParamInfoList = new List <ParamInfo>(); Action CallAction = () => { MipsMethodEmiter.ILGenerator.Emit(OpCodes.Ldarg_0); MipsMethodEmiter.ILGenerator.Emit(OpCodes.Ldfld, typeof(CpuThreadState).GetField("ModuleObject")); MipsMethodEmiter.ILGenerator.Emit(OpCodes.Castclass, this.GetType()); foreach (var ParameterInfo in MethodInfo.GetParameters()) { var ParameterType = ParameterInfo.ParameterType; // The CpuThreadState if (ParameterType == typeof(CpuThreadState)) { MipsMethodEmiter.ILGenerator.Emit(OpCodes.Ldarg_0); } // A stringz else if (ParameterType == typeof(string)) { ParamInfoList.Add(new ParamInfo() { ParameterName = ParameterInfo.Name, RegisterType = ParamInfo.RegisterTypeEnum.Gpr, RegisterIndex = GprIndex, ParameterType = ParameterType, }); MipsMethodEmiter.ILGenerator.Emit(OpCodes.Ldarg_0); MipsMethodEmiter.LoadGPR_Unsigned(GprIndex); MipsMethodEmiter.ILGenerator.Emit(OpCodes.Call, typeof(HleModuleHost).GetMethod("StringFromAddress")); GprIndex++; } // A pointer else if (ParameterType.IsPointer) { ParamInfoList.Add(new ParamInfo() { ParameterName = ParameterInfo.Name, RegisterType = ParamInfo.RegisterTypeEnum.Gpr, RegisterIndex = GprIndex, ParameterType = typeof(uint), }); MipsMethodEmiter._getmemptr(() => { MipsMethodEmiter.LoadGPR_Unsigned(GprIndex); }, Safe: true); GprIndex++; } // A long type else if (ParameterType == typeof(long) || ParameterType == typeof(ulong)) { while (GprIndex % 2 != 0) { GprIndex++; } ParamInfoList.Add(new ParamInfo() { ParameterName = ParameterInfo.Name, RegisterType = ParamInfo.RegisterTypeEnum.Gpr, RegisterIndex = GprIndex, ParameterType = ParameterType, }); MipsMethodEmiter.LoadGPRLong_Signed(GprIndex + 0); /* * MipsMethodEmiter.LoadGPR_Unsigned(GprIndex + 0); * MipsMethodEmiter.LoadGPR_Unsigned(GprIndex + 1); * MipsMethodEmiter.ILGenerator.Emit(OpCodes.Ldc_I4, 32); * MipsMethodEmiter.ILGenerator.Emit(OpCodes.Shl); * MipsMethodEmiter.ILGenerator.Emit(OpCodes.Or); */ GprIndex += 2; } // A float register. else if (ParameterType == typeof(float)) { ParamInfoList.Add(new ParamInfo() { ParameterName = ParameterInfo.Name, RegisterType = ParamInfo.RegisterTypeEnum.Fpr, RegisterIndex = FprIndex, ParameterType = ParameterType, }); MipsMethodEmiter.LoadFPR(FprIndex); FprIndex++; } // An integer register else { ParamInfoList.Add(new ParamInfo() { ParameterName = ParameterInfo.Name, RegisterType = ParamInfo.RegisterTypeEnum.Gpr, RegisterIndex = GprIndex, ParameterType = ParameterType, }); MipsMethodEmiter.LoadGPR_Unsigned(GprIndex); GprIndex++; } //MipsMethodEmiter.ILGenerator.Emit(OpCodes.ld } MipsMethodEmiter.ILGenerator.Emit(OpCodes.Call, MethodInfo); }; if (MethodInfo.ReturnType == typeof(void)) { CallAction(); } else if (MethodInfo.ReturnType == typeof(long)) { MipsMethodEmiter.SaveGPRLong(2, CallAction); } else { MipsMethodEmiter.SaveGPR(2, CallAction); } var Delegate = MipsMethodEmiter.CreateDelegate(); return((CpuThreadState) => { bool Trace = (!SkipLog && CpuThreadState.CpuProcessor.PspConfig.DebugSyscalls); if (NotImplemented) { Trace = true; ConsoleUtils.SaveRestoreConsoleState(() => { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine( "Not implemented {0}.{1}", MethodInfo.DeclaringType.Name, MethodInfo.Name ); }); } var Out = Console.Out; if (NotImplemented) { Out = Console.Error; } if (Trace) { if (HleState.ThreadManager.Current != null) { Out.Write( "Thread({0}:'{1}') : RA(0x{2:X})", HleState.ThreadManager.Current.Id, HleState.ThreadManager.Current.Name, HleState.ThreadManager.Current.CpuThreadState.RA ); } else { Out.Write("NoThread:"); } Out.Write(" : {0}.{1}", MethodInfo.DeclaringType.Name, MethodInfo.Name); Out.Write("("); int Count = 0; foreach (var ParamInfo in ParamInfoList) { if (Count > 0) { Out.Write(", "); } Out.Write("{0}:", ParamInfo.ParameterName); switch (ParamInfo.RegisterType) { case HleModuleHost.ParamInfo.RegisterTypeEnum.Fpr: case HleModuleHost.ParamInfo.RegisterTypeEnum.Gpr: uint Int4 = (uint)CpuThreadState.GPR[ParamInfo.RegisterIndex]; uint Float4 = (uint)CpuThreadState.FPR[ParamInfo.RegisterIndex]; Out.Write("{0}", ToNormalizedTypeString(ParamInfo.ParameterType, CpuThreadState, Int4, Float4)); break; default: throw(new NotImplementedException()); } Count++; } Out.Write(")"); //Console.WriteLine(""); } CpuThreadState.ModuleObject = this; try { Delegate(CpuThreadState); } catch (SceKernelException SceKernelException) { CpuThreadState.GPR[2] = (int)SceKernelException.SceKernelError; } catch (SceKernelSelfStopUnloadModuleException SceKernelSelfStopUnloadModuleException) { throw (SceKernelSelfStopUnloadModuleException); } catch (Exception Exception) { throw (new Exception( String.Format("ERROR calling {0}.{1}!", MethodInfo.DeclaringType.Name, MethodInfo.Name), Exception )); } finally { if (Trace) { Out.WriteLine(" : {0}", ToNormalizedTypeString(MethodInfo.ReturnType, CpuThreadState, (uint)CpuThreadState.GPR[2], (float)CpuThreadState.FPR[0])); Out.WriteLine(""); } } }); }