How to use IsAssemblyRewritten method of Microsoft.Coyote.Rewriting.RewritingEngine class

Best Coyote code snippet using Microsoft.Coyote.Rewriting.RewritingEngine.IsAssemblyRewritten

RewritingEngine.cs

Source:RewritingEngine.cs Github

copy

Full Screen

...238 // and fix up the version numbers so the rewritten assemblies are bound to these versions.239 this.AddLocalDependencies(assemblyPath, assembly);240 }241 this.RewrittenAssemblies[assembly.Name.Name] = assembly.Name;242 if (IsAssemblyRewritten(assembly))243 {244 // The assembly has been already rewritten by this version of Coyote, so skip it.245 this.Logger.WriteLine(LogSeverity.Warning, $"..... Skipping assembly with reason: already rewritten by Coyote v{GetAssemblyRewritterVersion()}");246 return;247 }248 else if (IsMixedModeAssembly(assembly))249 {250 // Mono.Cecil does not support writing mixed-mode assemblies.251 this.Logger.WriteLine(LogSeverity.Warning, $"..... Skipping assembly with reason: rewriting a mixed-mode assembly is not supported");252 return;253 }254 this.FixAssemblyReferences(assembly);255 ApplyIsAssemblyRewrittenAttribute(assembly);256 foreach (var transform in this.Transforms)257 {258 // Traverse the assembly to apply each transformation pass.259 Debug.WriteLine($"..... Applying the '{transform.GetType().Name}' transform");260 foreach (var module in assembly.Modules)261 {262 RewriteModule(module, transform);263 }264 }265 // Write the binary in the output path with portable symbols enabled.266 this.Logger.WriteLine($"... Writing the modified '{assemblyName}' assembly to " +267 $"{(this.Options.IsReplacingAssemblies ? assemblyPath : outputPath)}");268 var writeParams = new WriterParameters()269 {270 WriteSymbols = readParams.ReadSymbols,271 SymbolWriterProvider = new PortablePdbWriterProvider()272 };273 if (!string.IsNullOrEmpty(this.Options.StrongNameKeyFile))274 {275 using FileStream fs = File.Open(this.Options.StrongNameKeyFile, FileMode.Open);276 writeParams.StrongNameKeyPair = new StrongNameKeyPair(fs);277 }278 assembly.Write(outputPath, writeParams);279 }280 if (this.Options.IsReplacingAssemblies)281 {282 string targetPath = Path.Combine(this.Options.AssembliesDirectory, assemblyName);283 this.CopyWithRetriesAsync(outputPath, assemblyPath).Wait();284 if (readParams.ReadSymbols)285 {286 string pdbFile = Path.ChangeExtension(outputPath, "pdb");287 string targetPdbFile = Path.ChangeExtension(targetPath, "pdb");288 this.CopyWithRetriesAsync(pdbFile, targetPdbFile).Wait();289 }290 }291 }292 private async Task CopyWithRetriesAsync(string srcFile, string targetFile)293 {294 for (int retries = 10; retries >= 0; retries--)295 {296 try297 {298 File.Copy(srcFile, targetFile, true);299 }300 catch (Exception)301 {302 if (retries is 0)303 {304 throw;305 }306 await Task.Delay(100);307 this.Logger.WriteLine(LogSeverity.Warning, $"... Retrying write to {targetFile}");308 }309 }310 }311 private void FixAssemblyReferences(AssemblyDefinition assembly)312 {313 foreach (var module in assembly.Modules)314 {315 for (int i = 0, n = module.AssemblyReferences.Count; i < n; i++)316 {317 var ar = module.AssemblyReferences[i];318 var name = ar.Name;319 if (this.RewrittenAssemblies.TryGetValue(name, out AssemblyNameDefinition rewrittenName))320 {321 // rewrite this reference to point to the newly rewritten assembly.322 var refName = AssemblyNameReference.Parse(rewrittenName.FullName);323 module.AssemblyReferences[i] = refName;324 }325 }326 }327 }328 /// <summary>329 /// Enqueue any dependent assemblies that also exist in the assemblyPath and have not330 /// already been rewritten.331 /// </summary>332 private void AddLocalDependencies(string assemblyPath, AssemblyDefinition assembly)333 {334 var assemblyDir = Path.GetDirectoryName(assemblyPath);335 foreach (var module in assembly.Modules)336 {337 foreach (var ar in module.AssemblyReferences)338 {339 var name = ar.Name + ".dll";340 var localName = Path.Combine(assemblyDir, name);341 if (!this.IsDisallowed(name) &&342 File.Exists(localName) && !this.Pending.Contains(localName))343 {344 this.Pending.Enqueue(localName);345 }346 }347 }348 }349 /// <summary>350 /// Rewrites the specified module definition using the specified transform.351 /// </summary>352 private static void RewriteModule(ModuleDefinition module, AssemblyTransform transform)353 {354 Debug.WriteLine($"....... Module: {module.Name} ({module.FileName})");355 transform.VisitModule(module);356 foreach (var type in module.GetTypes())357 {358 RewriteType(type, transform);359 }360 }361 /// <summary>362 /// Rewrites the specified type definition using the specified transform.363 /// </summary>364 private static void RewriteType(TypeDefinition type, AssemblyTransform transform)365 {366 Debug.WriteLine($"......... Type: {type.FullName}");367 transform.VisitType(type);368 foreach (var field in type.Fields.ToArray())369 {370 Debug.WriteLine($"........... Field: {field.FullName}");371 transform.VisitField(field);372 }373 foreach (var method in type.Methods.ToArray())374 {375 RewriteMethod(method, transform);376 }377 }378 /// <summary>379 /// Rewrites the specified method definition using the specified transform.380 /// </summary>381 private static void RewriteMethod(MethodDefinition method, AssemblyTransform transform)382 {383 if (method.Body is null)384 {385 return;386 }387 Debug.WriteLine($"........... Method {method.FullName}");388 transform.VisitMethod(method);389 }390 /// <summary>391 /// Applies the <see cref="IsAssemblyRewrittenAttribute"/> attribute to the specified assembly. This attribute392 /// indicates that the assembly has been rewritten with the current version of Coyote.393 /// </summary>394 private static void ApplyIsAssemblyRewrittenAttribute(AssemblyDefinition assembly)395 {396 CustomAttribute attribute = GetCustomAttribute(assembly, typeof(IsAssemblyRewrittenAttribute));397 var attributeArgument = new CustomAttributeArgument(398 assembly.MainModule.ImportReference(typeof(string)),399 GetAssemblyRewritterVersion().ToString());400 if (attribute is null)401 {402 MethodReference attributeConstructor = assembly.MainModule.ImportReference(403 typeof(IsAssemblyRewrittenAttribute).GetConstructor(new Type[] { typeof(string) }));404 attribute = new CustomAttribute(attributeConstructor);405 attribute.ConstructorArguments.Add(attributeArgument);406 assembly.CustomAttributes.Add(attribute);407 }408 else409 {410 attribute.ConstructorArguments[0] = attributeArgument;411 }412 }413 /// <summary>414 /// Creates the output directory, if it does not already exists, and copies all necessery files.415 /// </summary>416 /// <returns>The output directory path.</returns>417 private string CreateOutputDirectoryAndCopyFiles()418 {419 string sourceDirectory = this.Options.AssembliesDirectory;420 string outputDirectory = Directory.CreateDirectory(this.Options.IsReplacingAssemblies ?421 Path.Combine(this.Options.OutputDirectory, TempDirectory) : this.Options.OutputDirectory).FullName;422 if (!this.Options.IsReplacingAssemblies)423 {424 this.Logger.WriteLine($"... Copying all files to the '{outputDirectory}' directory");425 // Copy all files to the output directory, skipping any nested directory files.426 foreach (string filePath in Directory.GetFiles(sourceDirectory, "*"))427 {428 Debug.WriteLine($"..... Copying the '{filePath}' file");429 CopyFile(filePath, outputDirectory);430 }431 // Copy all nested directories to the output directory, while preserving directory structure.432 foreach (string directoryPath in Directory.GetDirectories(sourceDirectory, "*", SearchOption.AllDirectories))433 {434 // Avoid copying the output directory itself.435 if (!directoryPath.StartsWith(outputDirectory))436 {437 Debug.WriteLine($"..... Copying the '{directoryPath}' directory");438 string path = Path.Combine(outputDirectory, directoryPath.Remove(0, sourceDirectory.Length).TrimStart('\\', '/'));439 Directory.CreateDirectory(path);440 foreach (string filePath in Directory.GetFiles(directoryPath, "*"))441 {442 Debug.WriteLine($"....... Copying the '{filePath}' file");443 CopyFile(filePath, path);444 }445 }446 }447 }448 // Copy all the dependent assemblies449 foreach (var type in new Type[]450 {451 typeof(ControlledTask),452 typeof(RewritingEngine),453 typeof(TelemetryConfiguration),454 typeof(EventTelemetry),455 typeof(ITelemetry),456 typeof(TelemetryClient)457 })458 {459 string assemblyPath = type.Assembly.Location;460 CopyFile(assemblyPath, this.Options.OutputDirectory);461 }462 return outputDirectory;463 }464 /// <summary>465 /// Copies the specified file to the destination.466 /// </summary>467 private static void CopyFile(string filePath, string destination) =>468 File.Copy(filePath, Path.Combine(destination, Path.GetFileName(filePath)), true);469 /// <summary>470 /// Checks if the assembly with the specified name is not allowed.471 /// </summary>472 private bool IsDisallowed(string assemblyName) => this.DisallowedAssemblies is null ? false :473 this.DisallowedAssemblies.IsMatch(assemblyName);474 /// <summary>475 /// Checks if the specified assembly has been already rewritten with the current version of Coyote.476 /// </summary>477 /// <param name="assembly">The assembly to check.</param>478 /// <returns>True if the assembly has been rewritten, else false.</returns>479 public static bool IsAssemblyRewritten(Assembly assembly) =>480 assembly.GetCustomAttribute(typeof(IsAssemblyRewrittenAttribute)) is IsAssemblyRewrittenAttribute attribute &&481 attribute.Version == GetAssemblyRewritterVersion().ToString();482 /// <summary>483 /// Checks if the specified assembly has been already rewritten with the current version of Coyote.484 /// </summary>485 /// <param name="assembly">The assembly to check.</param>486 /// <returns>True if the assembly has been rewritten, else false.</returns>487 private static bool IsAssemblyRewritten(AssemblyDefinition assembly)488 {489 var attribute = GetCustomAttribute(assembly, typeof(IsAssemblyRewrittenAttribute));490 return attribute != null && (string)attribute.ConstructorArguments[0].Value == GetAssemblyRewritterVersion().ToString();491 }492 /// <summary>493 /// Checks if the specified assembly is a mixed-mode assembly.494 /// </summary>495 /// <param name="assembly">The assembly to check.</param>496 /// <returns>True if the assembly only contains IL, else false.</returns>497 private static bool IsMixedModeAssembly(AssemblyDefinition assembly)498 {499 foreach (var module in assembly.Modules)500 {501 if ((module.Attributes & ModuleAttributes.ILOnly) is 0)502 {503 return true;...

Full Screen

Full Screen

Program.cs

Source:Program.cs Github

copy

Full Screen

...121 Task.WaitAll(tasks.ToArray());122 }123 private static void CheckRewritten()124 {125 if (!RunningMain && !Microsoft.Coyote.Rewriting.RewritingEngine.IsAssemblyRewritten(typeof(Program).Assembly))126 {127 throw new Exception(string.Format("Error: please rewrite this assembly using coyote rewrite {0}",128 typeof(Program).Assembly.Location));129 }130 }131 }132}...

Full Screen

Full Screen

BaseSystematicTest.cs

Source:BaseSystematicTest.cs Github

copy

Full Screen

...18 {19 get20 {21 var assembly = this.GetType().Assembly;22 bool result = RewritingEngine.IsAssemblyRewritten(assembly);23 Assert.True(result, $"Expected the '{assembly}' assembly to be rewritten.");24 return result;25 }26 }27 protected static void AssertSharedEntryValue(SharedEntry entry, int expected) =>28 Specification.Assert(entry.Value == expected, "Value is {0} instead of {1}.", entry.Value, expected);29 protected class SharedEntry30 {31 public volatile int Value = 0;32 public async Task<int> GetWriteResultAsync(int value)33 {34 this.Value = value;35 await Task.CompletedTask;36 return this.Value;...

Full Screen

Full Screen

IsAssemblyRewritten

Using AI Code Generation

copy

Full Screen

1using Microsoft.Coyote.Rewriting;2using System;3using System.Collections.Generic;4using System.Linq;5using System.Text;6using System.Threading.Tasks;7{8 {9 static void Main(string[] args)10 {11 if (RewritingEngine.IsAssemblyRewritten())12 {13 Console.WriteLine("Rewritten");14 }15 {16 Console.WriteLine("Not Rewritten");17 }18 }19 }20}21using Microsoft.Coyote.Rewriting;22using System;23using System.Collections.Generic;24using System.Linq;25using System.Text;26using System.Threading.Tasks;27{28 {29 static void Main(string[] args)30 {31 RewritingEngine.RewriteAssembly();32 }33 }34}

Full Screen

Full Screen

IsAssemblyRewritten

Using AI Code Generation

copy

Full Screen

1using System;2using Microsoft.Coyote.Rewriting;3{4 {5 static void Main(string[] args)6 {7 Console.WriteLine(RewritingEngine.IsAssemblyRewritten());8 Console.ReadLine();9 }10 }11}

Full Screen

Full Screen

IsAssemblyRewritten

Using AI Code Generation

copy

Full Screen

1using Microsoft.Coyote.Rewriting;2using System;3{4 {5 static void Main(string[] args)6 {7 Console.WriteLine("Is assembly rewritten? " + RewritingEngine.IsAssemblyRewritten());8 }9 }10}

Full Screen

Full Screen

IsAssemblyRewritten

Using AI Code Generation

copy

Full Screen

1using Microsoft.Coyote.Rewriting;2{3 public static void Main()4 {5 bool isRewritten = RewritingEngine.IsAssemblyRewritten(typeof(Program).Assembly);6 System.Console.WriteLine(isRewritten);7 }8}

Full Screen

Full Screen

IsAssemblyRewritten

Using AI Code Generation

copy

Full Screen

1using Microsoft.Coyote.Rewriting;2using System;3using System.Reflection;4{5 {6 static void Main(string[] args)7 {8 var assembly = Assembly.Load("TestApplication");9 var isRewritten = RewritingEngine.IsAssemblyRewritten(assembly);

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Coyote automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful