protected override void OnHandleIntent(Intent intent) { try { Context context = this.ApplicationContext; string action = intent.Action; if (action.Equals("com.google.android.c2dm.intent.REGISTRATION")) { ServiceHelper helper = ServiceHelper.GetInstance(); helper.SetPushIdentifier(intent.GetStringExtra("registration_id")); } else if (action.Equals("com.google.android.c2dm.intent.RECEIVE")) { //HandleMessage(context, intent); PlatformSpecific.GetInstance().LogInfo("Push received!"); } } finally { lock (LOCK) { //Sanity check for null as this is a public method if (sWakeLock != null) { sWakeLock.Release(); } } } }
/// <summary> /// Utility method used to compare execution log with arithmetic operations results (8 bits arithmetic) /// </summary> private static void CompareExecutionResultsWithSample(string sampleProgramFileName, string sampleResultFileName, int instructionsPerLine, int accColumn) { TestSystem testSystem = new TestSystem(); testSystem.LoadProgramInMemory(sampleProgramFileName, Encoding.UTF8, false); Stream stream = PlatformSpecific.GetStreamForProjectFile(sampleResultFileName); using (StreamReader reader = new StreamReader(stream)) { string line = null; while ((line = reader.ReadLine()) != null) { testSystem.ExecuteInstructionCount(instructionsPerLine); string[] columns = line.Split(';'); string AHexValue = columns[accColumn]; byte AByteValue = Convert.ToByte(AHexValue, 16); string FBinValue = columns[accColumn + 1]; byte FByteValue = Convert.ToByte(FBinValue, 2); if (testSystem.CPU.A != AByteValue) { throw new Exception(String.Format("Error line {0}, A = {1}", line, String.Format("{0:X}", testSystem.CPU.A))); } else if ((testSystem.CPU.F) != FByteValue) { throw new Exception(String.Format("Error line {0}, F = {1}", line, Convert.ToString(testSystem.CPU.F, 2))); } } } }
protected override bool ReleaseHandle() { bool result = true; try { NativeMethods.DestroyClientLibDelegate destroyClientLib; GetLibraryMethod("ts3client_destroyClientLib", out destroyClientLib); destroyClientLib(); } catch { result = false; } try { PlatformSpecific.UnloadDynamicLibrary(Platform, handle); } catch { result = false; } try { DllUnloaded.Set(); } catch (ObjectDisposedException) { /* nop */ } return(result); }
public static void CheckTapFileStructure(string fileName) { TapFile tapFile = TapFileReader.ReadTapFile(PlatformSpecific.GetStreamForProjectFile("TapeFiles/SampleTapFiles/" + fileName + ".tap"), fileName); string testResult = tapFile.ToString(); string expectedResult = null; using (StreamReader reader = new StreamReader(PlatformSpecific.GetStreamForProjectFile("TapeFiles/SampleTapFiles/" + fileName + ".txt"))) { expectedResult = reader.ReadToEnd(); } if (testResult != expectedResult) { throw new Exception("Tap file load test failed for file " + fileName); } /*string testOverview = tapFile.GetContentsOverview(); * * string expectedOverview = null; * using (StreamReader reader = new StreamReader(PlatformSpecific.GetStreamForProjectFile("TapeFiles/SampleTapFiles/" + fileName + ".overview.txt"))) * { * expectedOverview = reader.ReadToEnd(); * } * * if (testOverview != expectedOverview) * { * throw new Exception("Tap file overview test failed for file " + fileName); * }*/ }
public async Task ShouldSetWorkingDirectoryWhenContainerStarts() { // act var(stdout, _) = await Container.ExecuteCommand(PlatformSpecific.PwdCommand()); // assert Assert.Equal(_workingDirectory, stdout.TrimEndNewLine()); }
// This is the main entry point of the application. static void Main(string[] args) { CurrentPlatform.Init(); PlatformSpecific.SetPlatform(new iOSSpecific()); // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main(args, null, "AppDelegate"); }
static void Main() { PlatformSpecific.GetPlatform(); RegisterIcon.RegisterHASMIcon(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Editor()); }
public async Task ShouldFailToRunPrivilegedOperations() { // act var(stdout, stderr) = await Container.ExecuteCommand(PlatformSpecific.PrivilegedCommand()); // assert Assert.NotEmpty(stderr); Assert.Empty(stdout); }
public static SdkHandle Load(SupportedPlatform platform, string[] possibleNames) { DllUnloaded.WaitOne(); IntPtr handle; string location; PlatformSpecific.LoadDynamicLibrary(platform, possibleNames, out handle, out location); return(new SdkHandle(handle, platform, location)); }
public async Task ShouldBeAvailableWhenTheyAreSet() { // act var(stdout, _) = await Container.ExecuteCommand( PlatformSpecific.EchoCommand(PlatformSpecific.EnvVarFormat(_injectedEnvVar.Key))); // assert Assert.Equal(_injectedEnvVar.Value, stdout.TrimEndNewLine()); }
public async Task ShouldRunCommandWhenContainerStarts() { // act var(stdout, _) = await Container.ExecuteCommand( PlatformSpecific.ShellCommand( PlatformSpecific.IfExistsThenFormat($"{_fileTouchedByCommand}", $"{PlatformSpecific.Echo} 1"))); // assert Assert.Equal("1", stdout.TrimEndNewLine()); }
public static void LoadScreenInVideoMemory(string screenFilePath, byte[] videoMemory, int startIndex) { // Load sample picture in memory and set green border color using (Stream stream = PlatformSpecific.GetStreamForProjectFile(screenFilePath)) { using (BinaryReader reader = new BinaryReader(stream)) { reader.Read(videoMemory, startIndex, 6912); } } }
public static byte[] Check_CompleteScreenCycle() { ULATestSystem testSystem = new ULATestSystem(); testSystem.LoadScreenInVideoMemory("ULA/Video/ScreenSamples/BuggyBoy.scr"); testSystem.ULA.Debug_SetBorderColor(4); ULAStateLogger logger = new ULAStateLogger(testSystem.ULA); logger.StartLogging( ULAStateLogger.ULAStateElements.MasterCounters | ULAStateLogger.ULAStateElements.DataIO | ULAStateLogger.ULAStateElements.VideoOutput | ULAStateLogger.ULAStateElements.VideoRegisters, new ULA.LifecycleEventType[] { ULA.LifecycleEventType.ClockCycle }); for (int i = 0; i < ULA.ONE_FRAME_TICKS_COUNT + 7; i++) { testSystem.PixelClock.Tick(); } logger.StopLogging(); if (!logger.CompareWithSavedLog("ULA/Video/Logs/Check_CompleteScreenCycle")) { throw new Exception("Log compare failed"); } ZXSpectrumComputer computer = new ZXSpectrumComputer(); // Load a program that does nothing in computer ROM StringBuilder testProgram = new StringBuilder(); testProgram.AppendLine("JP 0"); computer.LoadProgramInROM(testProgram.ToString()); // Load sample picture in video memory and set green border color using (Stream stream = PlatformSpecific.GetStreamForProjectFile("ULA/Video/ScreenSamples/BuggyBoy.scr")) { using (BinaryReader reader = new BinaryReader(stream)) { reader.Read(computer.RAM16K.Cells, 0, 6912); } } computer.ULA.Debug_SetBorderColor(4); // Render the same screen with the complete computer for (int i = 0; i < ULA.ONE_FRAME_TICKS_COUNT + 7; i++) { computer.Clock.Tick(); } string testScreenValues = GetDisplayAsString(testSystem.Screen.Display); string computerScreenValues = GetDisplayAsString(computer.Screen.Display); if (!testScreenValues.Equals(computerScreenValues)) { throw new Exception("Screen compare failed for complete computer"); } return(testSystem.Screen.Display); }
static bool Prefix(EnvironmentEngine __instance) { if (MainGame.game_starting || MainGame.paused || !MainGame.game_started || __instance.IsTimeStopped()) { return(true); } Config.Options opts = Config.GetOptions(); float mult = Time.timeScale == 10f ? opts.SleepTimeMult : opts.TimeMult; if (mult != 1) { float accountableDelta = Time.deltaTime / 225f; // since this._cur_time += deltaTime / 225f float adjDelta = accountableDelta * mult - accountableDelta; EnvironmentEngine.SetTime(__instance.time_of_day.time_of_day + adjDelta); } if (opts.ConfigReloadKey.IsPressed()) { Config.GetOptions(true); EffectBubblesManager.ShowImmediately(MainGame.me.player.pos3, "NKN configuration reloaded"); } else if (opts.AddMoneyKey.IsPressed()) { MainGame.me.player.data.money += 100; EffectBubblesManager.ShowImmediately(MainGame.me.player.pos3, "1 gold coin granted"); } else if (opts.ResetPrayKey.IsPressed()) { MainGame.me.player.SetParam("prayed_this_week", 0f); EffectBubblesManager.ShowImmediately(MainGame.me.player.pos3, "Weekly pray count reset"); } else if (opts.TimeScaleSwitchKey.IsPressed()) { if (opts.TimeScaleSwitchKey.State == 0) { opts.TimeMult /= 10; } else { opts.TimeMult *= 10; } EffectBubblesManager.ShowImmediately(MainGame.me.player.pos3, "Timescale is set to " + opts.TimeMult); } else if (opts.AllowSaveEverywhere) { if (opts.SaveGameKey.IsPressed()) { PlatformSpecific.SaveGame(MainGame.me.save_slot, MainGame.me.save, (PlatformSpecific.OnSaveCompleteDelegate)(slot => { EffectBubblesManager.ShowImmediately(MainGame.me.player.pos3, "Saved succesfully"); })); } } return(true); }
public bool CompareWithSavedLog(string filename) { string filePath = String.Format("{0}.csv", filename); Stream stream = PlatformSpecific.GetStreamForProjectFile(filePath); string referenceLog = null; using (StreamReader reader = new StreamReader(stream)) { referenceLog = reader.ReadToEnd(); } return(Log == referenceLog); }
public async Task ShouldReturnSuccessfulResponseInStdOut() { // arrange const string hello = "hello-world"; // act var(stdout, stderr) = await Container.ExecuteCommand(PlatformSpecific.EchoCommand(hello)); // assert Assert.Equal(hello, stdout.TrimEndNewLine()); Assert.True(string.IsNullOrEmpty(stderr)); }
public static void Check_Flags(int launchAddress, string testDescription) { Console.Write(testDescription + "..."); TestSystem testSystem = new TestSystem(); string testSourcePath = "FlagsAndMemptr/z80tests-Flags.asm"; using (Stream stream = PlatformSpecific.GetStreamForProjectFile(testSourcePath)) { testSystem.LoadProgramInMemory(testSourcePath, stream, Encoding.UTF8, false); ((TestSystem._TestMemory)testSystem.Memory).SetReadOnlySection(0x500, 0x5FF); } testSystem.CPU.InitProgramCounter((ushort)launchAddress); testSystem.CPU.InitRegister(Z80Simulator.Instructions.Register.I, 63); testSystem.AddBreakpointOnProgramLine(619); /*StringBuilder sb = new StringBuilder(); * int counter = 1; * foreach (string variable in testSystem.ProgramInMemory.Variables.Keys) * { * if (variable.Contains("LAUNCH")) * { * sb.AppendLine("public static int " + variable.Replace("LAUNCH", "ADDR") + " = 0x" + testSystem.ProgramInMemory.Variables[variable].GetValue(testSystem.ProgramInMemory.Variables, null).ToString("X4") +";"); * sb.AppendLine("public static string " + variable.Replace("LAUNCH", "DESC") + " = \"" + testSystem.ProgramInMemory.Lines.First(line => (line.Comment !=null && line.Comment.Contains("test "+counter.ToString("D2")+" : "))).Comment.Split(':')[1].Trim() + "\";"); * counter++; * } * } * sb.Clear(); * for (counter = 1; counter <= 45; counter++) * { * sb.AppendLine("FlagsAndMemptrTests.Check_Flags(FlagsAndMemptrTests.FLAGS_TEST_" + counter.ToString("D2") + "_ADDR, FlagsAndMemptrTests.FLAGS_TEST_" + counter.ToString("D2") + "_DESC);"); * }*/ /*CPUStateLogger logger = new CPUStateLogger(testSystem.CPU); * logger.StartLogging( * CPUStateLogger.CPUStateElements.InternalState | * CPUStateLogger.CPUStateElements.Registers, * new Z80CPU.LifecycleEventType[] { * Z80CPU.LifecycleEventType.InstructionEnd * });*/ testSystem.ExecuteUntilNextBreakpoint(); //logger.StopLogging(); if (!(testSystem.CPU.A == 0 || (launchAddress == FLAGS_TEST_27_ADDR && testSystem.CPU.HL == 0x3063))) { throw new Exception("Flags test for " + testDescription + " failed : expected checksum " + testSystem.CPU.BC.ToString("X4") + " / computed checksum " + testSystem.CPU.HL.ToString("X4")); } Console.WriteLine("OK"); }
public static void CheckTapeRecorderPlayback() { TapeRecorder tapeRecorder = new _TapeRecorder(); Tape testTape = new Tape("TestTape", new TapeSection("section 1", new ToneSequence("tone", 4, 5), // 20 TStates new PulsesSequence("pulses", new ushort[] { 1, 2, 3, 4 }), // 10 TStates new DataSequence("data", new byte[] { 15, 175 }, 1, 2, 4)), // 36 TStates new TapeSection("section 2", new PauseSequence("pause", 1)), // 3500 TStates new TapeSection("section 3", new SamplesSequence("samples", new byte[] { 15, 175 }, 2, 7))); // 30 TStates tapeRecorder.InsertTape(testTape); StringBuilder sbResult = new StringBuilder(); tapeRecorder.Start(); sbResult.AppendLine(tapeRecorder.PlayingTime + "," + tapeRecorder.SoundSignal.Level + "," + tapeRecorder.GetPosition()); for (int i = 1; i < 70; i++) { tapeRecorder.Tick(); sbResult.AppendLine(tapeRecorder.PlayingTime + "," + tapeRecorder.SoundSignal.Level + "," + tapeRecorder.GetPosition()); } for (int i = 1; i <= 3492; i++) { tapeRecorder.Tick(); } for (int i = 1; i <= 35; i++) { tapeRecorder.Tick(); sbResult.AppendLine(tapeRecorder.PlayingTime + "," + tapeRecorder.SoundSignal.Level + "," + tapeRecorder.GetPosition()); } string testResult = sbResult.ToString(); string expectedResult = null; using (StreamReader reader = new StreamReader(PlatformSpecific.GetStreamForProjectFile("TapeFiles/Logs/CheckTapeRecorderPlayback.csv"))) { expectedResult = reader.ReadToEnd(); } if (testResult != expectedResult) { throw new Exception("TapeRecorder playback test failed"); } }
private async void InitNotificationsAsync() { // Request a push notification channel. var channel = await PushNotificationChannelManager .CreatePushNotificationChannelForApplicationAsync(); // Register for notifications using the new channel //await MobileService.GetPush().RegisterNativeAsync(channel.Uri); ServiceHelper.GetInstance().SetPushIdentifier(channel.Uri); PlatformSpecific.GetInstance().LogInfo("Push uri: " + channel.Uri); }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); CurrentPlatform.Init(); PlatformSpecific.SetPlatform(new AndroidSpecific()); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById <Button>(Resource.Id.MyButton); Button btnSend = FindViewById <Button>(Resource.Id.btnSend); Button btnGetContacts = FindViewById <Button>(Resource.Id.btnGetContacts); mBtnLogin = FindViewById <Button>(Resource.Id.btnLogin); mTxtMessage = FindViewById <EditText>(Resource.Id.txtMessage); mTxtRecipient = FindViewById <EditText>(Resource.Id.txtSendTo); mTxtUsername = FindViewById <EditText>(Resource.Id.txtUsername); mDdlContacts = FindViewById <Spinner>(Resource.Id.ddlContacts); mDdlContacts.ItemSelected += (sender, e) => { selectedContact((Spinner)sender, e); }; button.Click += delegate { button.Text = string.Format("{0} clicks!", count++); ServiceHelper.GetInstance().RecordClick(count, "Android"); }; btnSend.Click += (sender, e) => { tappedSend((View)sender); }; mBtnLogin.Click += delegate { tappedLogin(); }; btnGetContacts.Click += delegate { tappedGetContacts(); }; string senders = "540255930025"; Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER"); intent.SetPackage("com.google.android.gsf"); intent.PutExtra("app", PendingIntent.GetBroadcast(this, 0, new Intent(), 0)); intent.PutExtra("sender", senders); this.StartService(intent); }
private static HttpRequestMessage CreateLtiOutcomesRequest(imsx_POXEnvelopeType imsxEnvelope, string url, string consumerKey, string consumerSecret) { var webRequest = new HttpRequestMessage(HttpMethod.Post, url); var parameters = new NameValueCollection(); parameters.AddParameter(OAuthConstants.ConsumerKeyParameter, consumerKey); parameters.AddParameter(OAuthConstants.NonceParameter, Guid.NewGuid().ToString()); parameters.AddParameter(OAuthConstants.SignatureMethodParameter, OAuthConstants.SignatureMethodHmacSha1); parameters.AddParameter(OAuthConstants.VersionParameter, OAuthConstants.Version10); // Calculate the timestamp var ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); var timestamp = Convert.ToInt64(ts.TotalSeconds); parameters.AddParameter(OAuthConstants.TimestampParameter, timestamp); // Calculate the body hash var ms = new MemoryStream(); using (var sha1 = PlatformSpecific.GetSha1Provider()) { ImsxRequestSerializer.Serialize(ms, imsxEnvelope); ms.Position = 0; webRequest.Content = new StreamContent(ms); webRequest.Content.Headers.ContentType = HttpContentType.Xml; var hash = sha1.ComputeHash(ms.ToArray()); var hash64 = Convert.ToBase64String(hash); parameters.AddParameter(OAuthConstants.BodyHashParameter, hash64); } // Calculate the signature var signature = OAuthUtility.GenerateSignature(webRequest.Method.Method.ToUpper(), webRequest.RequestUri, parameters, consumerSecret); parameters.AddParameter(OAuthConstants.SignatureParameter, signature); // Build the Authorization header var authorization = new StringBuilder(OAuthConstants.AuthScheme).Append(" "); foreach (var key in parameters.AllKeys) { authorization.AppendFormat("{0}=\"{1}\",", key, WebUtility.UrlEncode(parameters[key])); } webRequest.Headers.Add(OAuthConstants.AuthorizationHeader, authorization.ToString(0, authorization.Length - 1)); return(webRequest); }
internal static MemoryStream GetResourceStream(string path) { if (_appResolver == null) { throw new NullReferenceException("The Blazor app resolver was not set! Please call WebApplicationFactory.RegisterAppStreamResolver method before launching your app"); } //Specific use cases here ! if (path.EndsWith(PlatformSpecific.BlazorWebAssemblyFileName) && PlatformSpecific.UseAlternateBlazorWASMScript()) { return(PlatformSpecific.GetAlternateBlazorWASMScript()); } //End specific cases MemoryStream data = null; lock (_zipLock) { try { ZipArchive archive = GetZipArchive(); //Data will contain the found file, outputed as a stream data = new MemoryStream(); ZipArchiveEntry entry = archive.GetEntry(path); if (entry != null) { Stream entryStream = entry.Open(); entryStream.CopyTo(data); entryStream.Dispose(); data.Seek(0, SeekOrigin.Begin); } else { data?.Dispose(); data = null; } } catch (Exception ex) { ConsoleHelper.WriteException(ex); } } return(data); }
private static void SignRequest(HttpRequestMessage request, byte[] body, string consumerKey, string consumerSecret) { if (body == null) { body = new byte[0]; } if (body.Length > 0 && request.Content.Headers.ContentLength != body.Length) { throw new ArgumentException("body length does not match request.ContentLength", "body"); } var parameters = new NameValueCollection(); parameters.AddParameter(OAuthConstants.ConsumerKeyParameter, consumerKey); parameters.AddParameter(OAuthConstants.NonceParameter, Guid.NewGuid().ToString()); parameters.AddParameter(OAuthConstants.SignatureMethodParameter, OAuthConstants.SignatureMethodHmacSha1); parameters.AddParameter(OAuthConstants.VersionParameter, OAuthConstants.Version10); // Calculate the timestamp var ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); var timestamp = Convert.ToInt64(ts.TotalSeconds); parameters.AddParameter(OAuthConstants.TimestampParameter, timestamp); // Calculate the body hash using (var sha1 = PlatformSpecific.GetSha1Provider()) { var hash = sha1.ComputeHash(body); var hash64 = Convert.ToBase64String(hash); parameters.AddParameter(OAuthConstants.BodyHashParameter, hash64); } // Calculate the signature var signature = OAuthUtility.GenerateSignature(request.Method.Method.ToUpper(), request.RequestUri, parameters, consumerSecret); parameters.AddParameter(OAuthConstants.SignatureParameter, signature); // Build the Authorization header var authorization = new StringBuilder(OAuthConstants.AuthScheme).Append(" "); foreach (var key in parameters.AllKeys) { authorization.AppendFormat("{0}=\"{1}\",", key, WebUtility.UrlEncode(parameters[key])); } request.Headers.Add(OAuthConstants.AuthorizationHeader, authorization.ToString(0, authorization.Length - 1)); }
public static void CheckTzxFileStructure(string fileName) { TzxFile tzxFile = TzxFileReader.ReadTzxFile(PlatformSpecific.GetStreamForProjectFile("TapeFiles/SampleTzxFiles/" + fileName + ".tzx"), fileName); string testResult = tzxFile.ToString(); string expectedResult = null; using (StreamReader reader = new StreamReader(PlatformSpecific.GetStreamForProjectFile("TapeFiles/SampleTzxFiles/" + fileName + ".txt"))) { expectedResult = reader.ReadToEnd(); } if (testResult != expectedResult) { throw new Exception("Tzx file load test failed for file " + fileName); } }
public async Task ShouldContainFileCreatedInHostBindingDirectory() { // arrange var content = Guid.NewGuid().ToString(); const string filename = "my_file"; var filepath = Path.Combine(_hostPathBinding.Key, filename); File.WriteAllText(filepath, content); // act var(stdout, stderr) = await Container.ExecuteCommand( PlatformSpecific.CatCommand(Path.Combine(_hostPathBinding.Value, filename))); // assert Assert.Equal(content, stdout.TrimEndNewLine()); }
public static void Check_Memptr(int launchAddress, string testDescription) { TestSystem testSystem = new TestSystem(); string testSourcePath = "FlagsAndMemptr/z80tests-Memptr.asm"; using (Stream stream = PlatformSpecific.GetStreamForProjectFile(testSourcePath)) { testSystem.LoadProgramInMemory(testSourcePath, stream, Encoding.UTF8, false); } testSystem.CPU.InitProgramCounter((ushort)launchAddress); testSystem.AddBreakpointOnProgramLine(1974); /*StringBuilder sb = new StringBuilder(); * int counter = 1; * foreach (string variable in testSystem.ProgramInMemory.Variables.Keys) * { * if (variable.Contains("LAUNCH")) * { * sb.AppendLine("public static int " + variable.Replace("LAUNCH", "ADDR") + " = 0x" + testSystem.ProgramInMemory.Variables[variable].GetValue(testSystem.ProgramInMemory.Variables, null).ToString("X4") +";"); * sb.AppendLine("public static string " + variable.Replace("LAUNCH", "DESC") + " = \"" + testSystem.ProgramInMemory.Lines.First(line => (line.Comment !=null && line.Comment.Contains("test "+counter.ToString("D2")+" : "))).Comment.Split(':')[1].Trim() + "\";"); * counter++; * } * } * sb.Clear(); * for (counter = 1; counter <= 58; counter++) * { * sb.AppendLine("FlagsAndMemptrTests.Check_Memptr(FlagsAndMemptrTests.MEMPTR_TEST_" + counter.ToString("D2") + "_ADDR, FlagsAndMemptrTests.MEMPTR_TEST_" + counter.ToString("D2") + "_DESC);"); * }*/ /*CPUStateLogger logger = new CPUStateLogger(testSystem.CPU); * logger.StartLogging( * CPUStateLogger.CPUStateElements.InternalState | * CPUStateLogger.CPUStateElements.Registers, * new Z80CPU.LifecycleEventType[] { * Z80CPU.LifecycleEventType.InstructionEnd * });*/ testSystem.ExecuteUntilNextBreakpoint(); //logger.StopLogging(); if (testSystem.CPU.A != 0) { throw new Exception("Memptr test for " + testDescription + " failed"); } }
public static WorkingFolder FromFile(string filename, string directory) { XmlSerializer ser = new XmlSerializer(typeof(WorkingFolder)); FileStream fs = new FileStream(filename, FileMode.Open); XmlReader reader = XmlReader.Create(fs); WorkingFolder cfg = (WorkingFolder)ser.Deserialize(reader); cfg.Path = new DirectoryInfo(directory).Parent.Parent.FullName; cfg.PreferedToCompile.Path = PlatformSpecific.CombinePath(cfg.Path, cfg.PreferedToCompile.Path); cfg.CompileConfigPath = PlatformSpecific.CombinePath(cfg.Path, cfg.CompileConfigPath); cfg.UserConfigPath = PlatformSpecific.CombinePath(cfg.Path, cfg.UserConfigPath); fs.Close(); return(cfg); }
public static void CheckProgram(string filename) { string objFilePath = String.Format("Assembly/Samples/{0}.obj", filename); Stream objStream = PlatformSpecific.GetStreamForProjectFile(objFilePath); string asmFilePath = String.Format("Assembly/Samples/{0}.asm", filename); Stream asmStream = PlatformSpecific.GetStreamForProjectFile(asmFilePath); byte[] referenceMemory = ReadToEnd(objStream); Program program = Assembler.ParseProgram(filename, asmStream, Encoding.UTF8, false); MemoryMap compiledMemory = new MemoryMap(referenceMemory.Length); Assembler.CompileProgram(program, 0, compiledMemory); for (int i = 0; i < referenceMemory.Length; i++) { if (compiledMemory.MemoryCells[i] != referenceMemory[i]) { ProgramLine errorLine = null; foreach (ProgramLine prgLine in program.Lines) { if (prgLine.LineAddress > i) { break; } else if (prgLine.Type != ProgramLineType.CommentOrWhitespace) { errorLine = prgLine; } } if (errorLine.Type == ProgramLineType.OpCodeInstruction) { throw new Exception(String.Format("Compilation result different from reference at address {0} - compiled {1:X} / expected {2:X} - line {3} starting at address {4}, {5}+{6} bytes : {7}", i, compiledMemory.MemoryCells[i], referenceMemory[i], errorLine.LineNumber, errorLine.LineAddress, errorLine.InstructionCode.OpCodeByteCount, errorLine.InstructionCode.OperandsByteCount, errorLine.Text)); } else { throw new Exception(String.Format("Compilation result different from reference at address {0} - compiled {1:X} / expected {2:X} - line {3} starting at address {4}, {5}+{6} bytes : {7}", i, compiledMemory.MemoryCells[i], referenceMemory[i], errorLine.LineNumber, errorLine.LineAddress, errorLine.Text)); } } } }
public GenericContainerFixture() { HostPathBinding = new KeyValuePair <string, string>(Directory.GetCurrentDirectory(), PlatformSpecific.BindPath); FileTouchedByCommand = PlatformSpecific.TouchedFilePath; WorkingDirectory = PlatformSpecific.WorkingDirectory; Container = new ContainerBuilder <GenericContainer>() .ConfigureHostConfiguration(builder => builder.AddInMemoryCollection()) .ConfigureAppConfiguration((context, builder) => builder.AddInMemoryCollection()) .ConfigureDockerImageName(PlatformSpecific.TinyDockerImage) .ConfigureLogging(builder => builder.AddConsole()) .ConfigureContainer((context, container) => { container.Labels.Add(CustomLabel.Key, CustomLabel.Value); container.Env[InjectedEnvVar.Key] = InjectedEnvVar.Value; container.ExposedPorts.Add(ExposedPort); /* * to do something like `docker run -p 2345:34567 alpine:latest`, * both expose port and port binding must be set */ container.ExposedPorts.Add(PortBinding.Key); container.PortBindings.Add(PortBinding.Key, PortBinding.Value); container.BindMounts.Add(new Bind { HostPath = HostPathBinding.Key, ContainerPath = HostPathBinding.Value, AccessMode = AccessMode.ReadOnly }); container.WorkingDirectory = WorkingDirectory; container.Command = PlatformSpecific.ShellCommand( $"{PlatformSpecific.Touch} {FileTouchedByCommand}; {PlatformSpecific.Shell}") .ToList(); }) .Build(); DockerClient = new DockerClientFactory().Create(); }
/// <summary> /// Utility method used to compare execution log with arithmetic operations results (16 bits arithmetic) /// </summary> private static void Compare16bitsExecutionResultsWithSample(string sampleProgramFileName, string sampleResultFileName, int instructionsPerLine) { TestSystem testSystem = new TestSystem(); testSystem.LoadProgramInMemory(sampleProgramFileName, Encoding.UTF8, false); Stream stream = PlatformSpecific.GetStreamForProjectFile(sampleResultFileName); using (StreamReader reader = new StreamReader(stream)) { string line = null; while ((line = reader.ReadLine()) != null) { testSystem.ExecuteInstructionCount(instructionsPerLine); string[] columns = line.Split(';'); string HHexValue = columns[3]; byte HByteValue = Convert.ToByte(HHexValue, 16); string LHexValue = columns[4]; byte LByteValue = Convert.ToByte(LHexValue, 16); string FBinValue = columns[5]; byte FByteValue = Convert.ToByte(FBinValue, 2); if (testSystem.CPU.L != LByteValue) { throw new Exception(String.Format("Error line {0}, L = {1}", line, String.Format("{0:X}", testSystem.CPU.L))); } else if (testSystem.CPU.H != HByteValue) { throw new Exception(String.Format("Error line {0}, H = {1}", line, String.Format("{0:X}", testSystem.CPU.H))); } // Ignore undocumented flags 3 and 5 : 11010111 = 215 else if ((testSystem.CPU.F & 215) != (FByteValue & 215)) { throw new Exception(String.Format("Error line {0}, F = {1}", line, Convert.ToString(testSystem.CPU.F, 2))); } } } }