public override void ReplaceUse(Temp.Temp oldTemp, Temp.Temp newTemp) { if (Left == oldTemp) Left = newTemp; if (Right == oldTemp) Right = newTemp; }
public BinOpInt(BINOP.Op op, Temp.Temp dst, Temp.Temp left, int right) { Op = op; Dst = dst; Left = left; Right = right; }
public void GetValueTest() { var t = new Temp { Value = null }; PropertyInfo propertyInfo = t.GetType().GetProperty("Value"); Stopwatch watch1 = new Stopwatch(); watch1.Start(); for (var i = 0; i < 1000000; i++) { var value = propertyInfo.GetValue(t, null); } watch1.Stop(); Trace.WriteLine("Reflection: " + watch1.Elapsed); DynamicPropertyAccessor property = new DynamicPropertyAccessor(t.GetType(), "Value"); Stopwatch watch2 = new Stopwatch(); watch2.Start(); for (var i = 0; i < 1000000; i++) { var value = property.GetValue(t); } watch2.Stop(); Trace.WriteLine("Lambda: " + watch2.Elapsed); Stopwatch watch3 = new Stopwatch(); watch3.Start(); for (var i = 0; i < 1000000; i++) { var value = t.Value; } watch3.Stop(); Trace.WriteLine("Direct: " + watch3.Elapsed); }
public void DeleteBackingFile() { var temp = new Temp("DeleteBackingFile.txt"); Assert.True(temp.File.Exists); temp.Dispose(); Assert.False(File.Exists(temp.File.FullName)); }
public void SerializeDeserialize2() { var TestObj = new Temp() { A = 100 }; string Value = TestObj.Serialize<string, Temp>(SerializationType.JSON); Temp TestObj2 = Value.Deserialize<Temp, string>(SerializationType.JSON); Assert.Equal("{\"A\":100}", Value); Assert.Equal(TestObj.A, TestObj2.A); Value = TestObj.Serialize<string, Temp>(SerializationType.SOAP); TestObj2 = Value.Deserialize<Temp, string>(SerializationType.SOAP); Assert.Equal(@"<SOAP-ENV:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:SOAP-ENC=""http://schemas.xmlsoap.org/soap/encoding/"" xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:clr=""http://schemas.microsoft.com/soap/encoding/clr/1.0"" SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/""> <SOAP-ENV:Body> <a1:SerializationExtensions_x002B_Temp id=""ref-1"" xmlns:a1=""http://schemas.microsoft.com/clr/nsassem/UnitTests.IO.ExtensionMethods/UnitTests%2C%20Version%3D1.0.0.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull""> <_x003C_A_x003E_k__BackingField>100</_x003C_A_x003E_k__BackingField> </a1:SerializationExtensions_x002B_Temp> </SOAP-ENV:Body> </SOAP-ENV:Envelope> ", Value); Assert.Equal(TestObj.A, TestObj2.A); Value = TestObj.Serialize<string, Temp>(SerializationType.XML); TestObj2 = Value.Deserialize<Temp, string>(SerializationType.XML); Assert.Equal(@"<?xml version=""1.0""?> <Temp xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""> <A>100</A> </Temp>", Value); Assert.Equal(TestObj.A, TestObj2.A); byte[] Value2 = TestObj.Serialize<byte[], Temp>(SerializationType.Binary); TestObj2 = Value2.Deserialize<Temp, byte[]>(SerializationType.Binary); Assert.Equal(new byte[] { 0, 1, 0, 0, 0, 255, 255, 255, 255, 1, 0, 0, 0, 0, 0, 0, 0, 12, 2, 0, 0, 0, 64, 85, 110, 105, 116, 84, 101, 115, 116, 115, 44, 32, 86, 101, 114, 115, 105, 111, 110, 61, 49, 46, 48, 46, 48, 46, 48, 44, 32, 67, 117, 108, 116, 117, 114, 101, 61, 110, 101, 117, 116, 114, 97, 108, 44, 32, 80, 117, 98, 108, 105, 99, 75, 101, 121, 84, 111, 107, 101, 110, 61, 110, 117, 108, 108, 5, 1, 0, 0, 0, 58, 85, 110, 105, 116, 84, 101, 115, 116, 115, 46, 73, 79, 46, 69, 120, 116, 101, 110, 115, 105, 111, 110, 77, 101, 116, 104, 111, 100, 115, 46, 83, 101, 114, 105, 97, 108, 105, 122, 97, 116, 105, 111, 110, 69, 120, 116, 101, 110, 115, 105, 111, 110, 115, 43, 84, 101, 109, 112, 1, 0, 0, 0, 18, 60, 65, 62, 107, 95, 95, 66, 97, 99, 107, 105, 110, 103, 70, 105, 101, 108, 100, 0, 8, 2, 0, 0, 0, 100, 0, 0, 0, 11 }, Value2); Assert.Equal(TestObj.A, TestObj2.A); }
public Day(Outlook outlook, Temp temp, Humidity humidity, bool windy) { Outlook = outlook.ToString(); Temp = temp.ToString(); Humidity = humidity.ToString(); Windy = windy; }
public void Insert(string CompanyName,int? TotalCount) { Temp item = new Temp(); item.CompanyName = CompanyName; item.TotalCount = TotalCount; item.Save(UserName); }
/// <summary> /// Overriding to generate OpCode /// </summary> /// <returns>Temp object</returns> public override Expr Gen() { var falseExit = this.NewLable(); var after = this.NewLable(); var temp = new Temp(this.Type); this.Jumping(0, falseExit); this.Emit(temp.ToString() + " = true"); this.Emit("goto L" + after); this.EmitLabel(falseExit); this.Emit(temp.ToString() + " = false"); this.EmitLabel(after); return temp; }
public void SourceSearchPaths_Change1() { var dir = Temp.CreateDirectory(); var main = dir.CreateFile("a.csx").WriteAllText("int X = 1;"); var runner = CreateRunner(input: $@"SourcePaths #load ""a.csx"" SourcePaths.Add(@""{dir.Path}"") #load ""a.csx"" X "); runner.RunInteractive(); AssertEx.AssertEqualToleratingWhitespaceDifferences($@" Microsoft (R) Visual C# Interactive Compiler version {s_compilerVersion} Copyright (C) Microsoft Corporation. All rights reserved. Type ""#help"" for more information. > SourcePaths SearchPaths {{ }} > #load ""a.csx"" «Red» (1,7): error CS1504: Source file 'a.csx' could not be opened -- Could not find file. «Gray» > SourcePaths.Add(@""{dir.Path}"") > #load ""a.csx"" > X 1 > ", runner.Console.Out.ToString()); AssertEx.AssertEqualToleratingWhitespaceDifferences( @"(1,7): error CS1504: Source file 'a.csx' could not be opened -- Could not find file.", runner.Console.Error.ToString()); }
public void ReferenceSearchPaths_Change1() { var dir = Temp.CreateDirectory(); var main = dir.CreateFile("C.dll").WriteAllBytes(TestResources.General.C1); var runner = CreateRunner(input: $@"ReferencePaths #r ""C.dll"" ReferencePaths.Add(@""{dir.Path}"") #r ""C.dll"" new C() "); runner.RunInteractive(); AssertEx.AssertEqualToleratingWhitespaceDifferences($@" Microsoft (R) Visual C# Interactive Compiler version {s_compilerVersion} Copyright (C) Microsoft Corporation. All rights reserved. Type ""#help"" for more information. > ReferencePaths SearchPaths {{ }} > #r ""C.dll"" «Red» (1,1): error CS0006: Metadata file 'C.dll' could not be found «Gray» > ReferencePaths.Add(@""{dir.Path}"") > #r ""C.dll"" > new C() C {{ }} > ", runner.Console.Out.ToString()); AssertEx.AssertEqualToleratingWhitespaceDifferences( @"(1,1): error CS0006: Metadata file 'C.dll' could not be found", runner.Console.Error.ToString()); }
private bool LoadCompletedCsv(IWebDriver driver, DateTime date, string email) { Temp.EmptyFolder(Config.I.TempDirectory); _logger.Info("Looking for completed transactions"); var completedResult = AirBnbTransactionHistory.DownloadCompletedTransaction(driver, date.Year); if (!completedResult) { _logger.Warn(string.Format("{0} doesn't have completed transactions", email)); return(true); } _logger.Info("downloading csv file"); driver.JustWait(5); var completedTransactionFileName = email + "-airbnb.csv"; var completedCsvFile = Temp.WaitFotTheFirstFile("*.csv", Config.I.TempDirectory, 1000 * 60 * 5); //TODO: check is file have size 0kb then redo downloading if (completedCsvFile == null) { _logger.Error("Error during file download"); N.Note("error downloading file"); return(false); } var completedTransactionsDirPath = Config.I.ExportCompletedTransactionsDirectory + @"\" + date.ToString("MMMM d yyyy") + @"\"; Temp.TouchDirectory(completedTransactionsDirPath); var completedCsvFullPath = completedTransactionsDirPath + @"\" + completedTransactionFileName; Temp.Move(completedCsvFile, completedCsvFullPath); N.Note(completedTransactionFileName + " downloaded"); _logger.Info(completedTransactionFileName + " downloaded"); return(true); }
public void AssemblyLoading() { StringBuilder sb = new StringBuilder(); var directory = Temp.CreateDirectory(); var alphaDll = Temp.CreateDirectory().CreateFile("Alpha.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Alpha); var betaDll = Temp.CreateDirectory().CreateFile("Beta.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Beta); var gammaDll = Temp.CreateDirectory().CreateFile("Gamma.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Gamma); var deltaDll = Temp.CreateDirectory().CreateFile("Delta.dll").WriteAllBytes(TestResources.AssemblyLoadTests.Delta); var loader = new DesktopAnalyzerAssemblyLoader(); loader.AddDependencyLocation(alphaDll.Path); loader.AddDependencyLocation(betaDll.Path); loader.AddDependencyLocation(gammaDll.Path); loader.AddDependencyLocation(deltaDll.Path); Assembly alpha = loader.LoadFromPath(alphaDll.Path); var a = alpha.CreateInstance("Alpha.A"); a.GetType().GetMethod("Write").Invoke(a, new object[] { sb, "Test A" }); Assembly beta = loader.LoadFromPath(betaDll.Path); var b = beta.CreateInstance("Beta.B"); b.GetType().GetMethod("Write").Invoke(b, new object[] { sb, "Test B" }); var expected = @"Delta: Gamma: Alpha: Test A Delta: Gamma: Beta: Test B "; var actual = sb.ToString(); Assert.Equal(expected, actual); }
public void AnalyzerDiagnosticsWithAndWithoutLocation() { var source = @" public class C { }"; var sourceFile = Temp.CreateFile().WriteAllText(source).Path; var outputDir = Temp.CreateDirectory(); var errorLogFile = Path.Combine(outputDir.Path, "ErrorLog.txt"); var outputFilePath = Path.Combine(outputDir.Path, "test.dll"); var cmd = new MockCSharpCompiler(null, _baseDirectory, new[] { "/nologo", "/t:library", $"/out:{outputFilePath}", sourceFile, "/preferreduilang:en", $"/errorlog:{errorLogFile}" }, analyzer: new AnalyzerForErrorLogTest()); var outWriter = new StringWriter(CultureInfo.InvariantCulture); var exitCode = cmd.Run(outWriter); var actualConsoleOutput = outWriter.ToString().Trim(); Assert.Contains(AnalyzerForErrorLogTest.Descriptor1.Id, actualConsoleOutput); Assert.Contains(AnalyzerForErrorLogTest.Descriptor2.Id, actualConsoleOutput); Assert.NotEqual(0, exitCode); var actualOutput = File.ReadAllText(errorLogFile).Trim(); var expectedHeader = GetExpectedErrorLogHeader(actualOutput, cmd); var expectedIssues = AnalyzerForErrorLogTest.GetExpectedErrorLogResultsText(cmd.Compilation); var expectedText = expectedHeader + expectedIssues; Assert.Equal(expectedText, actualOutput); CleanupAllGeneratedFiles(sourceFile); CleanupAllGeneratedFiles(outputFilePath); CleanupAllGeneratedFiles(errorLogFile); }
public void ResponseFile() { var rsp = Temp.CreateFile().WriteAllText(@" /r:System /r:System.Core /r:System.Data /r:System.Data.DataSetExtensions /r:System.Xml /r:System.Xml.Linq /r:Microsoft.CSharp /u:System /u:System.Collections.Generic /u:System.Linq /u:System.Text"); var csi = CreateRunner(new[] { "b.csx" }, responseFile: rsp.Path); var arguments = ((CSharpInteractiveCompiler)csi.Compiler).Arguments; AssertEx.Equal(new[] { "System", "System.Core", "System.Data", "System.Data.DataSetExtensions", "System.Xml", "System.Xml.Linq", "Microsoft.CSharp", }, arguments.MetadataReferences.Select(r => r.Reference)); AssertEx.Equal(new[] { "System", "System.Collections.Generic", "System.Linq", "System.Text", }, arguments.CompilationOptions.Usings.AsEnumerable()); }
public static string ClearHtmlTag(this string data) { string Temp; Temp = data.ToLower(); Temp = Temp.Replace(" ", "-"); Temp = Temp.Replace("\"", ""); Temp = Temp.Replace("/", ""); Temp = Temp.Replace("(", ""); Temp = Temp.Replace(")", ""); Temp = Temp.Replace("{", ""); Temp = Temp.Replace("}", ""); Temp = Temp.Replace("%", ""); Temp = Temp.Replace("&", ""); Temp = Temp.Replace("+", ""); Temp = Temp.Replace("?", ""); Temp = Temp.Replace(",", ""); Temp = Temp.Replace("%20", ""); Temp = Temp.Replace("'", ""); Temp = Temp.Replace(":", ""); Temp = Temp.Replace("!", ""); Temp = Temp.Replace(";", ""); Temp = Temp.Replace("#", ""); Temp = Temp.Replace("*", ""); Temp = Temp.Replace("&", ""); Temp = Temp.Replace("″", "-"); Temp = Temp.Replace(">", ""); Temp = Temp.Replace("<", ""); Temp = Temp.Replace("=", ""); Temp = Temp.Replace("|", ""); Temp = Temp.Replace("~", ""); Temp = Temp.Replace("€", ""); Temp = Temp.Replace("£", ""); Temp = Temp.Replace("$", ""); return(Temp); }
public void References_Versioning_WeakNames3() { var c1 = Temp.CreateFile(extension: ".dll").WriteAllBytes(CreateCompilationWithMscorlib(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.0"")] public class C {}", assemblyName: "C").EmitToArray()); var c2 = Temp.CreateFile(extension: ".dll").WriteAllBytes(CreateCompilationWithMscorlib(@"[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")] public class C {}", assemblyName: "C").EmitToArray()); var script0 = CSharpScript.Create($@" #r ""{c1.Path}"" var c1 = new C(); "); script0.GetCompilation().VerifyAssemblyVersionsAndAliases( "C, Version=1.0.0.0", "mscorlib, Version=4.0.0.0"); var script1 = script0.ContinueWith($@" #r ""{c2.Path}"" var c2 = new C(); "); script1.GetCompilation().VerifyAssemblyVersionsAndAliases( "C, Version=2.0.0.0", "C, Version=1.0.0.0: <superseded>", "mscorlib, Version=4.0.0.0"); var script2 = script1.ContinueWith(@" c1 = c2; "); script2.GetCompilation().VerifyAssemblyVersionsAndAliases( "C, Version=2.0.0.0", "C, Version=1.0.0.0: <superseded>", "mscorlib, Version=4.0.0.0"); DiagnosticExtensions.VerifyEmitDiagnostics(script2.GetCompilation(), // (2,6): error CS0029: Cannot implicitly convert type 'C [{c2.Path}]' to 'C [{c1.Path}]' Diagnostic(ErrorCode.ERR_NoImplicitConv, "c2").WithArguments($"C [{c2.Path}]", $"C [{c1.Path}]")); }
public void ReferencesVersioning() { using (MetadataCache.LockAndClean()) { var dir1 = Temp.CreateDirectory(); var dir2 = Temp.CreateDirectory(); var dir3 = Temp.CreateDirectory(); var file1 = dir1.CreateFile("C.dll").WriteAllBytes(TestResources.SymbolsTests.General.C1); var file2 = dir2.CreateFile("C.dll").WriteAllBytes(TestResources.SymbolsTests.General.C2); var file3 = dir3.CreateFile("main.dll"); var b = CreateCompilationWithMscorlib( @"public class B { public static int Main() { return C.Main(); } }", assemblyName: "b", references: new[] { MetadataReference.CreateFromImage(TestResources.SymbolsTests.General.C2) }, options: TestOptions.ReleaseDll); using (MemoryStream output = new MemoryStream()) { var emitResult = b.Emit(output); Assert.True(emitResult.Success); file3.WriteAllBytes(output.ToArray()); } var a = CreateCompilationWithMscorlib( @"class A { public static void Main() { B.Main(); } }", assemblyName: "a", references: new[] { new MetadataFileReference(file1.Path), new MetadataFileReference(file2.Path), new MetadataFileReference(file3.Path) }, options: TestOptions.ReleaseDll); using (var stream = new MemoryStream()) { a.Emit(stream); } } }
public void AddReference_Dependencies_Versions() { var dir1 = Temp.CreateDirectory(); var dir2 = Temp.CreateDirectory(); var dir3 = Temp.CreateDirectory(); // [assembly:AssemblyVersion("1.0.0.0")] public class C { public static int Main() { return 1; } }"); var file1 = dir1.CreateFile("c.dll").WriteAllBytes(TestResources.General.C1); // [assembly:AssemblyVersion("2.0.0.0")] public class C { public static int Main() { return 2; } }"); var file2 = dir2.CreateFile("c.dll").WriteAllBytes(TestResources.General.C2); Assert.True(LoadReference(file1.Path)); Assert.True(LoadReference(file2.Path)); var main = CompileLibrary(dir3, "main.exe", "Main", @"public class Program { public static int Main() { return C.Main(); } }", MetadataReference.CreateFromImage(TestResources.General.C2.AsImmutableOrNull())); Assert.True(LoadReference(main.Path)); Assert.True(Execute("Program.Main()")); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("2", ReadOutputToEnd().Trim()); }
public void DifferingMvids() { var directory = Temp.CreateDirectory(); // Load Beta.dll from the future Alpha.dll path to prime the assembly loader var alphaDll = directory.CopyFile(TestFixture.Beta.Path, name: "Alpha.dll"); var assemblyLoader = new InMemoryAssemblyLoader(); var betaAssembly = assemblyLoader.LoadFromPath(alphaDll.Path); // now overwrite the {directory}/Alpha.dll file with the content from our Alpha.dll test resource alphaDll.CopyContentFrom(TestFixture.Alpha.Path); directory.CopyFile(TestFixture.Gamma.Path); directory.CopyFile(TestFixture.Delta1.Path); var analyzerReferences = ImmutableArray.Create( new CommandLineAnalyzerReference("Alpha.dll"), new CommandLineAnalyzerReference("Gamma.dll"), new CommandLineAnalyzerReference("Delta.dll")); var result = AnalyzerConsistencyChecker.Check(directory.Path, analyzerReferences, assemblyLoader, Logger); Assert.False(result); }
public void DefaultUsings() { var source = @" dynamic d = new ExpandoObject(); Process p = new Process(); Expression<Func<int>> e = () => 1; var squares = from x in new[] { 1, 2, 3 } select x * x; var sb = new StringBuilder(); var list = new List<int>(); var stream = new MemoryStream(); await Task.Delay(10); Console.Write(""OK""); "; var cwd = Temp.CreateDirectory(); cwd.CreateFile("a.csx").WriteAllText(source); var result = ProcessUtilities.Run(CsiPath, "a.csx", workingDirectory: cwd.Path); AssertEx.AssertEqualToleratingWhitespaceDifferences("OK", result.Output); Assert.False(result.ContainsErrors); }
public void When_dotnet_test_is_invoked_Then_tests_run_without_errors() { var rootPath = Temp.CreateDirectory().Path; new TestCommand("dotnet") { WorkingDirectory = rootPath } .Execute("new --type nunittest"); new TestCommand("dotnet") { WorkingDirectory = rootPath } .Execute("restore"); var buildResult = new TestCommand("dotnet") .WithWorkingDirectory(rootPath) .ExecuteWithCapturedOutput("test") .Should() .Pass() .And .NotHaveStdErr(); }
private async Task <(byte[] assemblyBytes, string finalFlags)> CompileAndGetBytes(string source) { // Setup var tempDir = Temp.CreateDirectory(); var srcFile = tempDir.CreateFile("test.cs").WriteAllText(source).Path; var outFile = srcFile.Replace("test.cs", "test.dll"); try { string finalFlags = null; using (var serverData = await ServerUtil.CreateServer()) { finalFlags = $"{ _flags } /shared:{ serverData.PipeName } /pathmap:{tempDir.Path}=/ /out:{ outFile } { srcFile }"; var result = CompilerServerUnitTests.RunCommandLineCompiler( CompilerServerUnitTests.CSharpCompilerClientExecutable, finalFlags, currentDirectory: tempDir); if (result.ExitCode != 0) { AssertEx.Fail($"Deterministic compile failed \n stdout: { result.Output }"); } var listener = await serverData.Complete().ConfigureAwait(false); Assert.Equal(CompletionData.RequestCompleted, listener.CompletionDataList.Single()); } var bytes = File.ReadAllBytes(outFile); AssertEx.NotNull(bytes); return(bytes, finalFlags); } finally { File.Delete(srcFile); File.Delete(outFile); } }
static void Main(string[] args) { Logger.Setup(); Config.I.UseProxy = true; AirBnbAccounts.Load(); var yesterday = DateTime.Now.AddDays(-1); var yesterdayLockHash = yesterday.ToString("yyyy\\MMMM-d") + @"\lock"; var jsonLogger = new OperationsJsonLogger <LoginAttempt>(Config.I.LoginAttemptsLogFile); Temp.UnlockFolder(yesterdayLockHash); var logger = LogManager.GetLogger(typeof(Program)); var accounts = AirBnbAccounts.Accounts.Where(x => !string.IsNullOrEmpty(x.Password)).ToList(); foreach (var airAccount in accounts) { logger.Info(string.Format("processing {0} is started", airAccount.Email)); var transactionLoader = new TransactionLoader(airAccount, jsonLogger, logger); transactionLoader.DownloadTransactions(); } }
public IQueryable <Temp> GetMetaData(string tableName) { switch (tableName) { case "SystemUsers": SystemUser systemUser = new SystemUser(); return(systemUser.GetMetaData().AsQueryable()); case "SystemUsersTypes": SystemUserType systemUserTypes = new SystemUserType(); return(systemUserTypes.GetMetaData().AsQueryable()); case "SystemUserCodes": SystemUserCode systemUserCode = new SystemUserCode(); return(systemUserCode.GetMetaData().AsQueryable()); case "SystemUserSecurities": SystemUserSecurity systemUserSecurity = new SystemUserSecurity(); return(systemUserSecurity.GetMetaData().AsQueryable()); case "SecurityGroups": SecurityGroup securityGroup = new SecurityGroup(); return(securityGroup.GetMetaData().AsQueryable()); default: //no table exists for the given tablename given... List <Temp> tempList = new List <Temp>(); Temp temp = new Temp(); temp.ID = 0; temp.Int_1 = 0; temp.Bool_1 = true; //bool_1 will flag it as an error... temp.Name = "Error"; temp.ShortChar_1 = "Table " + tableName + " Is Not A Valid Table Within The Given Entity Collection, Or Meta Data Is Not Publc For The Given Table Name"; tempList.Add(temp); return(tempList.AsQueryable()); } }
public void ChoqueCuerpo() { Cola Temp; try { Temp = CabezaVibora.VerSiguiente().VerSiguiente(); } catch (Exception Error) { Temp = null; } while (Temp != null) { if (CabezaVibora.Interseccion(Temp)) { FinJuego(); } else { Temp = Temp.VerSiguiente(); } } }
public void MigratingWebProjectJsonWithServerGCTrueDoesNotProduceServerGarbageCollectionProperty() { var testDirectory = Temp.CreateDirectory().Path; var pj = @" { ""buildOptions"": { ""emitEntryPoint"": true }, ""dependencies"": { ""Microsoft.AspNetCore.Mvc"": ""1.0.0"" }, ""runtimeOptions"": { ""configProperties"": { ""System.GC.Server"": true } } }"; var mockProj = RunMigrateRuntimeOptionsRulePj(pj, testDirectory); var props = mockProj.Properties.Where(p => p.Name.Equals("ServerGarbageCollection", StringComparison.Ordinal)); props.Count().Should().Be(0); }
public void It_migrates_csproj_ProjectReference_in_xproj_including_condition_on_ProjectReference_parent_and_item() { var projectReference = "some/to.csproj"; var xproj = ProjectRootElement.Create(); var csprojReferenceItem = xproj.AddItem("ProjectReference", projectReference); csprojReferenceItem.Parent.Condition = " '$(Foo)' == 'bar' "; csprojReferenceItem.Condition = " '$(Bar)' == 'foo' "; var projectReferenceName = Path.GetFileNameWithoutExtension(projectReference); var projectJson = @" { ""dependencies"": {" + $"\"{projectReferenceName}\"" + @": { ""target"" : ""project"" } } } "; var testDirectory = Temp.CreateDirectory().Path; var migratedProj = TemporaryProjectFileRuleRunner.RunRules(new IMigrationRule[] { new MigrateProjectDependenciesRule() }, projectJson, testDirectory, xproj); var migratedProjectReferenceItems = migratedProj.Items.Where(i => i.ItemType == "ProjectReference"); migratedProjectReferenceItems.Should().HaveCount(1); var migratedProjectReferenceItem = migratedProjectReferenceItems.First(); migratedProjectReferenceItem.Include.Should().Be(projectReference); migratedProjectReferenceItem.Condition.Should().Be(" '$(Bar)' == 'foo' and '$(Foo)' == 'bar' "); }
public void GetMetadata() { var dir = Temp.CreateDirectory(); var dll = dir.CreateFile("a.dll").WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSClasses01); var doc = dir.CreateFile("a.xml").WriteAllText("<hello>"); var sc1 = _provider.GetMetadataShadowCopy(dll.Path, MetadataImageKind.Assembly); var sc2 = _provider.GetMetadataShadowCopy(dll.Path, MetadataImageKind.Assembly); var md1 = _provider.GetMetadata(dll.Path, MetadataImageKind.Assembly); Assert.NotNull(md1); Assert.Equal(MetadataImageKind.Assembly, md1.Kind); // This needs to be in different folder from referencesdir to cause the other code path // to be triggered for NeedsShadowCopy method var dir2 = Temp.CreateDirectory(); var dll2 = dir2.CreateFile("a2.dll").WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSClasses01); Assert.Equal(1, _provider.CacheSize); var sc3a = _provider.GetMetadataShadowCopy(dll2.Path, MetadataImageKind.Module); Assert.Equal(2, _provider.CacheSize); }
public void RuleSet_SpecificOptions_CPS() { var ruleSetFile = Temp.CreateFile().WriteAllText( @"<?xml version=""1.0"" encoding=""utf-8""?> <RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0""> <IncludeAll Action=""Warning"" /> <Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed""> <Rule Id=""CA1012"" Action=""Error"" /> </Rules> </RuleSet> "); using (var environment = new TestEnvironment()) using (var project = CSharpHelpers.CreateCSharpCPSProject(environment, "Test")) { // Verify SetRuleSetFile updates the ruleset. project.SetOptions($"/ruleset:{ruleSetFile.Path}"); // We need to explicitly update the command line arguments so the new ruleset is used to update options. project.SetOptions($"/ruleset:{ruleSetFile.Path}"); var ca1012DiagnosticOption = environment.Workspace.CurrentSolution.Projects.Single().CompilationOptions.SpecificDiagnosticOptions["CA1012"]; Assert.Equal(expected: ReportDiagnostic.Error, actual: ca1012DiagnosticOption); } }
public static string Md5(byte[] data) { try { StringBuilder Result = new StringBuilder(); foreach (byte Temp in new MD5CryptoServiceProvider().ComputeHash(data)) { if (Temp < 16) { Result.Append("0"); Result.Append(Temp.ToString("x")); } else { Result.Append(Temp.ToString("x")); } } return(Result.ToString()); } catch { return("0000000000000000"); } }
public void TestLibraryCross() { var rootPath = Temp.CreateDirectory().Path; TestAssets.CopyDirTo("TestLibraryCross", rootPath); TestAssets.CopyDirTo("TestSuiteProps", rootPath); Func <string, TestCommand> test = name => new TestCommand(name) { WorkingDirectory = rootPath }; test("dotnet") .Execute($"restore {RestoreDefaultArgs} {RestoreSourcesArgs(NugetConfigSources)} {RestoreProps()}") .Should().Pass(); test("dotnet") .Execute($"build {LogArgs}") .Should().Pass(); test("dotnet") .Execute($"pack {LogArgs}") .Should().Pass(); }
public void TestXmlDoc() { var rootPath = Temp.CreateDirectory().Path; TestAssets.CopyDirTo("TestLibrary", rootPath); TestAssets.CopyDirTo("TestSuiteProps", rootPath); Func <string, TestCommand> test = name => new TestCommand(name) { WorkingDirectory = rootPath }; test("dotnet") .Execute($"restore {RestoreDefaultArgs} {RestoreSourcesArgs(NugetConfigSources)} {RestoreProps()}") .Should().Pass(); Assert.Equal(false, File.Exists(Path.Combine(rootPath, "doc.xml"))); test("dotnet") .Execute($"build {LogArgs} /p:DocumentationFile=doc.xml") .Should().Pass(); Assert.Equal(true, File.Exists(Path.Combine(rootPath, "doc.xml"))); }
public void TestImplicitConfigurationDefines() { var rootPath = Temp.CreateDirectory().Path; TestAssets.CopyDirTo("netcoreapp1.0/TestConsoleAppTemplate", rootPath); TestAssets.CopyDirTo("TestAppDefines", rootPath); TestAssets.CopyDirTo("TestSuiteProps", rootPath); Func <string, TestCommand> test = name => new TestCommand(name) { WorkingDirectory = rootPath }; test("dotnet") .Execute($"restore {RestoreDefaultArgs} {RestoreSourcesArgs(NugetConfigSources)} {RestoreProps()}") .Should().Pass(); var configurations = new Dictionary <string, string> { { "release", "RELEASE" }, { "debug", "DEBUG" }, }; foreach (var kv in configurations) { test("dotnet") .Execute($"build {LogArgs} -c {kv.Key}") .Should().Pass(); var result = test("dotnet").ExecuteWithCapturedOutput($"run -c {kv.Key} {LogArgs}"); result.Should().Pass(); Assert.NotNull(result.StdOut); Assert.Contains($"CONF: '{kv.Value}'", result.StdOut.Trim()); } }
public void TestLibraryBindingRedirectGeneration() { // Set up Test Staging in Temporary Directory var root = Temp.CreateDirectory(); root.CopyDirectory(Path.Combine(_testProjectsRoot, "TestBindingRedirectGeneration")); var testProjectsRootDir = Path.Combine(root.Path, "TestBindingRedirectGeneration"); var greaterTestLibDir = Path.Combine(testProjectsRootDir, "TestLibraryGreater"); var lesserTestLibDir = Path.Combine(testProjectsRootDir, "TestLibraryLesser"); var lesserTestProject = Path.Combine(lesserTestLibDir, "project.json"); var publishCommand = new PublishCommand(lesserTestProject, "net451"); publishCommand.Execute().Should().Pass(); publishCommand.GetOutputDirectory().Should().HaveFile("TestLibraryLesser.dll"); publishCommand.GetOutputDirectory().Should().HaveFile("TestLibraryLesser.pdb"); publishCommand.GetOutputDirectory().Should().HaveFile("TestLibraryLesser.dll.config"); publishCommand.GetOutputDirectory().Should().NotHaveFile("TestLibraryLesser.deps"); // dependencies should also be copied publishCommand.GetOutputDirectory().Should().HaveFile("Newtonsoft.Json.dll"); publishCommand.GetOutputDirectory().Delete(true); publishCommand = new PublishCommand(lesserTestProject, "dnxcore50", PlatformServices.Default.Runtime.GetLegacyRestoreRuntimeIdentifier()); publishCommand.Execute().Should().Pass(); publishCommand.GetOutputDirectory().Should().HaveFile("TestLibraryLesser.dll"); publishCommand.GetOutputDirectory().Should().HaveFile("TestLibraryLesser.pdb"); publishCommand.GetOutputDirectory().Should().NotHaveFile("TestLibraryLesser.dll.config"); publishCommand.GetOutputDirectory().Should().HaveFile("TestLibraryLesser.deps"); // dependencies should also be copied publishCommand.GetOutputDirectory().Should().HaveFile("Newtonsoft.Json.dll"); }
public IEnumerator <Temp> Use() { List <Temp> activeTemps = new List <Temp>(); if (kind == Kind.IDIV) { activeTemps.Add(I386CodeGenerator.EDX); } if (op is Operand.Reg reg) { //if (Temp.IsSpecialReg(reg.reg)) //{ // return Enumerable.Empty<Temp>().GetEnumerator(); //} //activeTemps.Add(reg.reg); if (!Temp.IsSpecialReg(reg.reg)) { activeTemps.Add(reg.reg); } } else if (op is Operand.Mem mem) { //if (Temp.IsSpecialReg(mem.bas)) //{ // return Enumerable.Empty<Temp>().GetEnumerator(); //} //activeTemps.Add(mem.bas); if (!Temp.IsSpecialReg(mem.bas)) { activeTemps.Add(mem.bas); } } return(activeTemps.GetEnumerator()); }
public void MultiModuleAssembly() { var dir = Temp.CreateDirectory(); var dll = dir.CreateFile("MultiModule.dll").WriteAllBytes(TestResources.SymbolsTests.MultiModule.MultiModule); dir.CreateFile("mod2.netmodule").WriteAllBytes(TestResources.SymbolsTests.MultiModule.mod2); dir.CreateFile("mod3.netmodule").WriteAllBytes(TestResources.SymbolsTests.MultiModule.mod3); var task = Host.ExecuteAsync(@" #r """ + dll.Path + @""" new object[] { new Class1(), new Class2(), new Class3() } "); task.Wait(); var error = ReadErrorOutputToEnd(); Assert.Equal("", error); var output = ReadOutputToEnd(); Assert.Equal("object[3] { Class1 { }, Class2 { }, Class3 { } }\r\n", output); }
protected void Page_Load(object sender, EventArgs e) { HttpCookie cookie = Request.Cookies["login_adm"]; if (cookie == null || cookie.Value != "ok") { Response.Redirect("Login.aspx"); return; } List <Maquina> maquinas = new List <Maquina>(); string url = "https://jsonplaceholder.typicode.com/posts"; WebRequest request = WebRequest.Create(url); request.Credentials = CredentialCache.DefaultCredentials; WebResponse response = request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); JavaScriptSerializer js = new JavaScriptSerializer(); var objText = reader.ReadToEnd(); Temp myojb = (Temp)js.Deserialize(objText, typeof(Temp)); //Console.WriteLine(myojb.Title); Label1.Text = myojb.Title; reader.Close(); response.Close(); }
public void ReferencePaths() { var directory = Temp.CreateDirectory(); var assemblyName = GetUniqueName(); CompileLibrary(directory, assemblyName + ".dll", assemblyName, @"public class C { }"); var rspFile = Temp.CreateFile(); rspFile.WriteAllText("/lib:" + directory.Path); Host.ResetAsync(new InteractiveHostOptions(initializationFile: rspFile.Path, culture: CultureInfo.InvariantCulture)).Wait(); Execute( $@"#r ""{assemblyName}.dll"" typeof(C).Assembly.GetName()"); Assert.Equal("", ReadErrorOutputToEnd()); var output = SplitLines(ReadOutputToEnd()); Assert.Equal(2, output.Length); Assert.Equal("Loading context from '" + Path.GetFileName(rspFile.Path) + "'.", output[0]); Assert.Equal($"[{assemblyName}, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", output[1]); }
public void SetValueTest() { int expected = 100; var t = new Temp { Value = null }; PropertyInfo propertyInfo = t.GetType().GetProperty("Value"); Stopwatch watch1 = new Stopwatch(); watch1.Start(); for (var i = 0; i < 1000000; i++) { propertyInfo.SetValue(t, expected, null); } watch1.Stop(); Trace.WriteLine("Reflection: " + watch1.Elapsed); Assert.AreEqual(expected, t.Value.Value); t.Value = 555; DynamicPropertyAccessor property = new DynamicPropertyAccessor(t.GetType(), "Value"); Stopwatch watch2 = new Stopwatch(); watch2.Start(); for (var i = 0; i < 1000000; i++) { property.SetValue(t,expected); } watch2.Stop(); Trace.WriteLine("Lambda: " + watch2.Elapsed); Assert.AreEqual(expected, t.Value.Value); t.Value = 555; Stopwatch watch3 = new Stopwatch(); watch3.Start(); for (var i = 0; i < 1000000; i++) { t.Value = expected; } watch3.Stop(); Trace.WriteLine("Direct: " + watch3.Elapsed); Assert.AreEqual(expected, t.Value.Value); }
public override void ReplaceDef(Temp.Temp oldTemp, Temp.Temp newTemp) { throw new FatalError("No ReplaceDef method for Store"); }
public abstract string String(Temp.Label label, string values);
public void AddToTemps(Temp temp) { base.AddObject("Temps", temp); }
public Store(Temp.Temp mem, int offset, Temp.Temp src) { Mem = mem; Offset = offset; Src = src; }
//Computes or "reduce" an expression down to a single address; //That is, it returns a constant, an identifier, or a temproary name. public override Expr Reduce() { Expr expr = this.Gen(); //Note: the method Gen is virtual, so polymorphism will happen here. Temp temp = new Temp(this.Type); this.Emit(temp.ToString() + " = " + expr.ToString()); return temp; }
private List<Temp> ReadTemps(DateTime date) { List<Temp> temps = new List<Temp>(); StreamReader data = ReadTempFile(date); if (data != null) { while (!data.EndOfStream) { string line = data.ReadLine(); if (!String.IsNullOrWhiteSpace(line)) { string[] parts = line.Split('|'); string sensorId = parts[1]; Temp temp = new Temp() { time = date.Date.Add(TimeSpan.Parse(parts[0])), sensor=parts[2], C = Decimal.Parse(parts[3]) }; temps.Add(temp); } } data.Close(); } return temps; }
public override void ReplaceUse(Temp.Temp oldTemp, Temp.Temp newTemp) { if (Mem == oldTemp) Mem = newTemp; if (Src == oldTemp) Src = newTemp; }
private HashSet<PairInt> SetOf(Dictionary<TempPairInt, HashSet<PairInt>> chain, Temp.Temp t, PairInt p) { TempPairInt key = new TempPairInt(t, p); if (chain[key] == null) chain.Add(key, new HashSet<PairInt>()); return chain[key]; }
public static Temp CreateTemp(string cartonBoxNumber, decimal quantity, string color, string size, string name) { Temp temp = new Temp(); temp.CartonBoxNumber = cartonBoxNumber; temp.Quantity = quantity; temp.Color = color; temp.Size = size; temp.Name = name; return temp; }
public string TempMap(Temp temp) { return temp.ToString(); }
public string TempMap(Temp temp) { string s = TempMap1.TempMap(temp); if (s != null) return s; return TempMap2.TempMap(temp); }
static void Main(string[] args) { Temp obj = new Temp(); obj.callCamp(); }
public TempList(Temp head, TempList tail) { Head = head; Tail = tail; }
public override void ReplaceDef(Temp.Temp oldTemp, Temp.Temp newTemp) { if (Dst == oldTemp) Dst = newTemp; }
public TempPairInt(Temp.Temp temp, PairInt pair) { Temp = temp; Pair = pair; }
public TEMP(Temp.Temp temp) { Temp = temp; }
public void Update(int TempID,string CompanyName,int? TotalCount) { Temp item = new Temp(); item.MarkOld(); item.IsLoaded = true; item.TempID = TempID; item.CompanyName = CompanyName; item.TotalCount = TotalCount; item.Save(UserName); }
public abstract Frame NewFrame(Temp.Label name, BoolList formals);
public override void ReplaceUse(Temp.Temp oldTemp, Temp.Temp newTemp) { throw new FatalError("No ReplaceUse method for Call"); }
public abstract string TempMap(Temp.Temp temp);
private Temp ReadTemp(String sensor) { Temp retval = new Temp() { Valid = false }; //first line = 5c 01 4b 46 7f ff 04 10 a1 : crc=a1 YES //second line = 5c 01 4b 46 7f ff 04 10 a1 t=21750 FileInfo sfi = new FileInfo(String.Format("{0}/{1}/w1_slave", ROOT, sensor)); using (StreamReader sr = sfi.OpenText()) { if (!sr.EndOfStream) { String line = sr.ReadLine(); //Console.WriteLine(line); string[] parts = line.Split(new string[] { "crc=" }, StringSplitOptions.None); if (parts.Length == 2 && parts[1].EndsWith("YES")) { retval.Valid = true; //crc is ok so temp is valid if (!sr.EndOfStream) { line = sr.ReadLine(); //Console.WriteLine(line); parts = line.Split(new string[] { "t=" }, StringSplitOptions.None); if (parts.Length == 2) { retval.C = decimal.Parse(parts[1]) / 1000; } } } } sr.Close(); } return retval; }