/// <summary> /// Weaves the notification mechanism into the assembly /// </summary> /// <param name="debug">if set to <c>true</c> [debug].</param> public void InsertNotifications(bool debug = false) { var assemblyDef = null as AssemblyDefinition; var readParameters = new ReaderParameters { ReadSymbols = debug, AssemblyResolver = resolver }; var writeParameters = new WriterParameters { WriteSymbols = debug }; var assemblyProcessor = new AssemblyProcessor(mdResolver); //Load the assembly. using (var stream = File.OpenRead(assemblyPath)) { assemblyDef = AssemblyDefinition.ReadAssembly(stream, readParameters); } assemblyProcessor.Process(assemblyDef); //If the assembly has been altered then rewrite it. if (assemblyProcessor.ContainsChanges) { using (var stream = File.OpenWrite(assemblyPath)) { assemblyDef.Write(stream, writeParameters); } } }
public void Execute() { var freezableTypeFinder = new FreezableTypeFinder(ModuleDefinition, AssemblyResolver); freezableTypeFinder.Execute(); var exceptionFinder = new ExceptionFinder(ModuleDefinition, AssemblyResolver); exceptionFinder.Execute(); var volatileFinder = new VolatileTypeFinder(ModuleDefinition, AssemblyResolver); volatileFinder.Execute(); var volatileFieldFixer = new VolatileFieldFixer(volatileFinder); var fieldInjector = new FieldInjector(volatileFinder, ModuleDefinition.TypeSystem, volatileFieldFixer); var checkIsFrozenBuilder = new CheckIsFrozenBuilder(ModuleDefinition.TypeSystem, exceptionFinder); var freezeCheckerInjector = new FreezeCheckerInjector(ModuleDefinition, fieldInjector, checkIsFrozenBuilder); var typeResolver = new TypeResolver(); var implementsInterfaceFinder = new ImplementsInterfaceFinder(typeResolver); var classes = ModuleDefinition.GetTypes() .Where(x => x.IsClass) .ToList(); var assemblyProcessor = new AssemblyProcessor(freezeCheckerInjector, implementsInterfaceFinder, LogInfo); assemblyProcessor.Execute(classes); volatileFieldFixer.Execute(classes); }
public void Execute() { var freezableTypeFinder = new FreezableTypeFinder(ModuleDefinition, AssemblyResolver); freezableTypeFinder.Execute(); var exceptionFinder = new ExceptionFinder(ModuleDefinition, AssemblyResolver); exceptionFinder.Execute(); var volatileFinder = new VolatileTypeFinder(ModuleDefinition, AssemblyResolver); volatileFinder.Execute(); var volatileFieldFixer = new VolatileFieldFixer(volatileFinder); var fieldInjector = new FieldInjector(volatileFinder, ModuleDefinition.TypeSystem, volatileFieldFixer); var checkIsFrozenBuilder = new CheckIsFrozenBuilder(ModuleDefinition.TypeSystem, exceptionFinder); var freezeCheckerInjector = new FreezeCheckerInjector(ModuleDefinition, fieldInjector, checkIsFrozenBuilder); var typeResolver = new TypeResolver(); var implementsInterfaceFinder = new ImplementsInterfaceFinder(typeResolver); var classes = ModuleDefinition.GetTypes() .Where(x => x.IsClass) .ToList(); var assemblyProcessor = new AssemblyProcessor(freezeCheckerInjector, implementsInterfaceFinder, LogInfo); assemblyProcessor.Execute(classes); volatileFieldFixer.Execute(classes); }
public void Init() { var type = GetType(); var tag = new TestAssemblyGenerator(type); _asm = tag.CreateTestAssembly(); var asmproc = new AssemblyProcessor(Configuration.GetProcessorsTree()); asmproc.Process(_asm); }
public void ProcessTestAssembly() { var processor = new AssemblyProcessor(); var asmPath = typeof(ProcessTests).Assembly.CodeBase; var asmName = $"{Path.GetFileNameWithoutExtension(asmPath)}-ref{Path.GetExtension(asmPath)}"; var output = Path.Combine(Environment.CurrentDirectory, asmName !); File.Delete(output); processor.Process(new Options { AssemblyPath = new Uri(asmPath !).LocalPath, OutputFile = output });
private void Run() { if (args.Length == 0) { ShowNoArgumentsErrorAndExit(); } foreach (var arg in args) { ProcessArgument(arg); } var processor = new AssemblyProcessor(configuration, new ConsoleMessageWriter()); var result = processor.Execute(); ExitAccordingToResult(result); }
public static int Startup() { double pi = 3.1428; int retValue = 0; try { /* * Before starting implementation, check how to start the assembly with full part load option; * currently the load options only enabled for partial loading. See how to set it permanently or * for session start with API. * * First part of the trial task is to load and change the parameter of the bolt. * For test change clamping distance. (27/12) */ theProgram = new Program(); //System.IO.StreamWriter SW = new System.IO.StreamWriter("D:\\GIT\\AUTO_BOLTS_PLACE\\NXDebugLog.log"); AssemblyProcessor Processor = new AssemblyProcessor(ref theSession); Processor.LoadAssmbly(); Processor.ConstraintCreate(); theUfSession.Part.CloseAll(); //SW.Close(); theProgram.Dispose(); } catch (NXOpen.NXException ex) { System.IO.StreamWriter SW = new System.IO.StreamWriter("D:\\GIT\\AUTO_BOLTS_PLACE\\NXErrorLog.log"); SW.WriteLine(ex.Message.ToString()); SW.Close(); theUfSession.Part.CloseAll(); theSession.ListingWindow.Open(); theSession.ListingWindow.WriteLine("Error occurred"); theSession.ListingWindow.WriteLine(ex.Message.ToString()); } return(retValue); }
static void Main(string[] args) { var outPath = "C:\\Program Files (x86)\\Steam\\steamapps\\common\\Cities_Skylines\\Cities_Data\\Managed\\Assembly-CSharp.dll"; var inPath = "C:\\Program Files (x86)\\Steam\\steamapps\\common\\Cities_Skylines\\Cities_Data\\Managed\\PatchLib.dll"; File.Delete(outPath); File.Copy("C:\\Program Files (x86)\\Steam\\steamapps\\common\\Cities_Skylines\\Cities_Data\\Managed\\Assembly-CSharp.bak.dll", outPath); var outputAssembly = new AssemblyProcessor(outPath); var inputAssembly = new AssemblyProcessor(inPath); /* * outputAssembly.SubstituteTypes * ( * outputAssembly.FindTypeByName("", "TreeManager"), * inputAssembly.FindTypeByName("PatchLib", "TreeManager_v2") * ); */ outputAssembly.SubstituteLiteral(outputAssembly.FindTypeByName("", "TreeManager"), 262144, 262144 * 2); outputAssembly.SubstituteLiteral(outputAssembly.FindTypeByName("", "NaturalResourceManager"), 262144, 262144 * 2); // outputAssembly.SubstituteLiteral(outputAssembly.FindTypeByName("", "TreeManager"), 250000, 250000 * 2); //outputAssembly.SubstituteLiteral(outputAssembly.FindTypeByName("", "TreeManager"), 262139, 262139 * 2); outputAssembly.SubstituteLiteral(outputAssembly.FindTypeByName("", "BuildingDecoration"), 262144, 262144 * 2); //outputAssembly.SubstituteLiteral(outputAssembly.FindTypeByName("", "BuildingDecoration"), 250000, 250000 * 2); // outputAssembly.SubstituteLiteral(outputAssembly.FindTypeByName("", "BuildingDecoration"), 262139, 262139 * 2); outputAssembly.Write("C:\\Program Files (x86)\\Steam\\steamapps\\common\\Cities_Skylines\\Cities_Data\\Managed\\Assembly-CSharp.dll"); Console.WriteLine("Assembly patched"); for (;;) { ; } }
public OutsideRuntimeClient(ClientConfiguration cfg, bool secondary = false) { this.typeCache = new TypeMetadataCache(); this.assemblyProcessor = new AssemblyProcessor(this.typeCache); this.grainFactory = new GrainFactory(this, this.typeCache); if (cfg == null) { Console.WriteLine("An attempt to create an OutsideRuntimeClient with null ClientConfiguration object."); throw new ArgumentException("OutsideRuntimeClient was attempted to be created with null ClientConfiguration object.", "cfg"); } this.config = cfg; if (!LogManager.IsInitialized) { LogManager.Initialize(config); } StatisticsCollector.Initialize(config); SerializationManager.Initialize(cfg.SerializationProviders, cfg.FallbackSerializationProvider); this.assemblyProcessor.Initialize(); logger = LogManager.GetLogger("OutsideRuntimeClient", LoggerType.Runtime); appLogger = LogManager.GetLogger("Application", LoggerType.Application); BufferPool.InitGlobalBufferPool(config); this.handshakeClientId = GrainId.NewClientId(); try { LoadAdditionalAssemblies(); callbacks = new ConcurrentDictionary <CorrelationId, CallbackData>(); localObjects = new ConcurrentDictionary <GuidId, LocalObjectData>(); if (!secondary) { UnobservedExceptionsHandlerClass.SetUnobservedExceptionHandler(UnhandledException); } AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload; // Ensure SerializationManager static constructor is called before AssemblyLoad event is invoked SerializationManager.GetDeserializer(typeof(String)); clientProviderRuntime = new ClientProviderRuntime(grainFactory, null); statisticsProviderManager = new StatisticsProviderManager("Statistics", clientProviderRuntime); var statsProviderName = statisticsProviderManager.LoadProvider(config.ProviderConfigurations) .WaitForResultWithThrow(initTimeout); if (statsProviderName != null) { config.StatisticsProviderName = statsProviderName; } responseTimeout = Debugger.IsAttached ? Constants.DEFAULT_RESPONSE_TIMEOUT : config.ResponseTimeout; var localAddress = ClusterConfiguration.GetLocalIPAddress(config.PreferredFamily, config.NetInterface); // Client init / sign-on message logger.Info(ErrorCode.ClientInitializing, string.Format( "{0} Initializing OutsideRuntimeClient on {1} at {2} Client Id = {3} {0}", BARS, config.DNSHostName, localAddress, handshakeClientId)); string startMsg = string.Format("{0} Starting OutsideRuntimeClient with runtime Version='{1}' in AppDomain={2}", BARS, RuntimeVersion.Current, PrintAppDomainDetails()); startMsg = string.Format("{0} Config= " + Environment.NewLine + " {1}", startMsg, config); logger.Info(ErrorCode.ClientStarting, startMsg); if (TestOnlyThrowExceptionDuringInit) { throw new InvalidOperationException("TestOnlyThrowExceptionDuringInit"); } config.CheckGatewayProviderSettings(); var generation = -SiloAddress.AllocateNewGeneration(); // Client generations are negative var gatewayListProvider = GatewayProviderFactory.CreateGatewayListProvider(config) .WithTimeout(initTimeout).Result; transport = new ProxiedMessageCenter(config, localAddress, generation, handshakeClientId, gatewayListProvider); if (StatisticsCollector.CollectThreadTimeTrackingStats) { incomingMessagesThreadTimeTracking = new ThreadTrackingStatistic("ClientReceiver"); } } catch (Exception exc) { if (logger != null) { logger.Error(ErrorCode.Runtime_Error_100319, "OutsideRuntimeClient constructor failed.", exc); } ConstructorReset(); throw; } }
internal void ConsumeServices(IServiceProvider services) { this.ServiceProvider = services; var connectionLostHandlers = services.GetServices <ConnectionToClusterLostHandler>(); foreach (var handler in connectionLostHandlers) { this.ClusterConnectionLost += handler; } var clientInvokeCallbacks = services.GetServices <ClientInvokeCallback>(); foreach (var handler in clientInvokeCallbacks) { this.ClientInvokeCallback += handler; } this.InternalGrainFactory = this.ServiceProvider.GetRequiredService <IInternalGrainFactory>(); this.ClientStatistics = this.ServiceProvider.GetRequiredService <ClientStatisticsManager>(); this.SerializationManager = this.ServiceProvider.GetRequiredService <SerializationManager>(); this.messageFactory = this.ServiceProvider.GetService <MessageFactory>(); this.config = services.GetRequiredService <ClientConfiguration>(); this.GrainReferenceRuntime = this.ServiceProvider.GetRequiredService <IGrainReferenceRuntime>(); if (!LogManager.IsInitialized) { LogManager.Initialize(config); } StatisticsCollector.Initialize(config); this.assemblyProcessor = this.ServiceProvider.GetRequiredService <AssemblyProcessor>(); this.assemblyProcessor.Initialize(); logger = LogManager.GetLogger("OutsideRuntimeClient", LoggerType.Runtime); this.AppLogger = LogManager.GetLogger("Application", LoggerType.Application); BufferPool.InitGlobalBufferPool(config); try { LoadAdditionalAssemblies(); if (!UnobservedExceptionsHandlerClass.TrySetUnobservedExceptionHandler(UnhandledException)) { logger.Warn(ErrorCode.Runtime_Error_100153, "Unable to set unobserved exception handler because it was already set."); } AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload; clientProviderRuntime = this.ServiceProvider.GetRequiredService <ClientProviderRuntime>(); statisticsProviderManager = new StatisticsProviderManager("Statistics", clientProviderRuntime); var statsProviderName = statisticsProviderManager.LoadProvider(config.ProviderConfigurations) .WaitForResultWithThrow(initTimeout); if (statsProviderName != null) { config.StatisticsProviderName = statsProviderName; } responseTimeout = Debugger.IsAttached ? Constants.DEFAULT_RESPONSE_TIMEOUT : config.ResponseTimeout; this.localAddress = ClusterConfiguration.GetLocalIPAddress(config.PreferredFamily, config.NetInterface); // Client init / sign-on message logger.Info(ErrorCode.ClientInitializing, string.Format( "{0} Initializing OutsideRuntimeClient on {1} at {2} Client Id = {3} {0}", BARS, config.DNSHostName, localAddress, handshakeClientId)); string startMsg = string.Format("{0} Starting OutsideRuntimeClient with runtime Version='{1}' in AppDomain={2}", BARS, RuntimeVersion.Current, PrintAppDomainDetails()); startMsg = string.Format("{0} Config= " + Environment.NewLine + " {1}", startMsg, config); logger.Info(ErrorCode.ClientStarting, startMsg); if (TestOnlyThrowExceptionDuringInit) { throw new InvalidOperationException("TestOnlyThrowExceptionDuringInit"); } this.gatewayListProvider = this.ServiceProvider.GetRequiredService <IGatewayListProvider>(); if (StatisticsCollector.CollectThreadTimeTrackingStats) { incomingMessagesThreadTimeTracking = new ThreadTrackingStatistic("ClientReceiver"); } } catch (Exception exc) { if (logger != null) { logger.Error(ErrorCode.Runtime_Error_100319, "OutsideRuntimeClient constructor failed.", exc); } ConstructorReset(); throw; } }
public OutsideRuntimeClient(ClientConfiguration cfg, bool secondary = false) { if (cfg == null) { Console.WriteLine("An attempt to create an OutsideRuntimeClient with null ClientConfiguration object."); throw new ArgumentException("OutsideRuntimeClient was attempted to be created with null ClientConfiguration object.", "cfg"); } var services = new ServiceCollection(); services.AddSingleton(cfg); services.AddSingleton <TypeMetadataCache>(); services.AddSingleton <AssemblyProcessor>(); services.AddSingleton(this); services.AddSingleton <IRuntimeClient>(this); services.AddSingleton <GrainFactory>(); services.AddFromExisting <IGrainFactory, GrainFactory>(); services.AddFromExisting <IInternalGrainFactory, GrainFactory>(); services.AddFromExisting <IGrainReferenceConverter, GrainFactory>(); services.AddSingleton <ClientProviderRuntime>(); services.AddFromExisting <IMessagingConfiguration, ClientConfiguration>(); services.AddSingleton <IGatewayListProvider>( sp => ActivatorUtilities.CreateInstance <GatewayProviderFactory>(sp).CreateGatewayListProvider()); services.AddSingleton <SerializationManager>(); services.AddSingleton <MessageFactory>(); services.AddSingleton <Func <string, Logger> >(LogManager.GetLogger); services.AddSingleton <StreamProviderManager>(); services.AddSingleton <ClientStatisticsManager>(); services.AddFromExisting <IStreamProviderManager, StreamProviderManager>(); services.AddSingleton <CodeGeneratorManager>(); this.ServiceProvider = services.BuildServiceProvider(); this.InternalGrainFactory = this.ServiceProvider.GetRequiredService <IInternalGrainFactory>(); this.ClientStatistics = this.ServiceProvider.GetRequiredService <ClientStatisticsManager>(); this.SerializationManager = this.ServiceProvider.GetRequiredService <SerializationManager>(); this.messageFactory = this.ServiceProvider.GetService <MessageFactory>(); this.config = cfg; if (!LogManager.IsInitialized) { LogManager.Initialize(config); } StatisticsCollector.Initialize(config); this.assemblyProcessor = this.ServiceProvider.GetRequiredService <AssemblyProcessor>(); this.assemblyProcessor.Initialize(); logger = LogManager.GetLogger("OutsideRuntimeClient", LoggerType.Runtime); appLogger = LogManager.GetLogger("Application", LoggerType.Application); BufferPool.InitGlobalBufferPool(config); this.handshakeClientId = GrainId.NewClientId(); tryResendMessage = TryResendMessage; unregisterCallback = msg => UnRegisterCallback(msg.Id); try { LoadAdditionalAssemblies(); callbacks = new ConcurrentDictionary <CorrelationId, CallbackData>(); localObjects = new ConcurrentDictionary <GuidId, LocalObjectData>(); if (!secondary) { UnobservedExceptionsHandlerClass.SetUnobservedExceptionHandler(UnhandledException); } AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload; clientProviderRuntime = this.ServiceProvider.GetRequiredService <ClientProviderRuntime>(); statisticsProviderManager = new StatisticsProviderManager("Statistics", clientProviderRuntime); var statsProviderName = statisticsProviderManager.LoadProvider(config.ProviderConfigurations) .WaitForResultWithThrow(initTimeout); if (statsProviderName != null) { config.StatisticsProviderName = statsProviderName; } responseTimeout = Debugger.IsAttached ? Constants.DEFAULT_RESPONSE_TIMEOUT : config.ResponseTimeout; var localAddress = ClusterConfiguration.GetLocalIPAddress(config.PreferredFamily, config.NetInterface); // Client init / sign-on message logger.Info(ErrorCode.ClientInitializing, string.Format( "{0} Initializing OutsideRuntimeClient on {1} at {2} Client Id = {3} {0}", BARS, config.DNSHostName, localAddress, handshakeClientId)); string startMsg = string.Format("{0} Starting OutsideRuntimeClient with runtime Version='{1}' in AppDomain={2}", BARS, RuntimeVersion.Current, PrintAppDomainDetails()); startMsg = string.Format("{0} Config= " + Environment.NewLine + " {1}", startMsg, config); logger.Info(ErrorCode.ClientStarting, startMsg); if (TestOnlyThrowExceptionDuringInit) { throw new InvalidOperationException("TestOnlyThrowExceptionDuringInit"); } config.CheckGatewayProviderSettings(); var generation = -SiloAddress.AllocateNewGeneration(); // Client generations are negative var gatewayListProvider = this.ServiceProvider.GetRequiredService <IGatewayListProvider>(); gatewayListProvider.InitializeGatewayListProvider(cfg, LogManager.GetLogger(gatewayListProvider.GetType().Name)) .WaitWithThrow(initTimeout); transport = ActivatorUtilities.CreateInstance <ProxiedMessageCenter>(this.ServiceProvider, localAddress, generation, handshakeClientId); if (StatisticsCollector.CollectThreadTimeTrackingStats) { incomingMessagesThreadTimeTracking = new ThreadTrackingStatistic("ClientReceiver"); } } catch (Exception exc) { if (logger != null) { logger.Error(ErrorCode.Runtime_Error_100319, "OutsideRuntimeClient constructor failed.", exc); } ConstructorReset(); throw; } }
public override bool Execute() { try { #if ATTACH_DEBUGGER System.Diagnostics.Debugger.Launch(); #endif var cacheFolder = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(typeof(AspectInjectorBuildTask).Assembly.Location)), "_assemblycache", ConfigurationName); if (!Directory.Exists(cacheFolder)) { Directory.CreateDirectory(cacheFolder); } Console.WriteLine("Aspect Injector has started for {0}", Assembly); var assemblyResolver = new CachedAssemblyResolver(cacheFolder); foreach (var r in References) { assemblyResolver.RegisterAssembly(r); } string assemblyFile = Path.Combine(OutputPath, Assembly); File.Copy(assemblyFile, Path.Combine(cacheFolder, Assembly), true); string pdbFile = Path.Combine(OutputPath, Path.GetFileNameWithoutExtension(Assembly) + ".pdb"); var assembly = AssemblyDefinition.ReadAssembly(assemblyFile, new ReaderParameters { ReadingMode = Mono.Cecil.ReadingMode.Deferred, AssemblyResolver = assemblyResolver, ReadSymbols = true }); Console.WriteLine("Assembly has been loaded"); var injector = new AssemblyProcessor(Configuration.GetProcessorsTree()); injector.Process(assembly); Console.WriteLine("Assembly has been patched"); assembly.Write(assemblyFile, new WriterParameters() { WriteSymbols = true, ////StrongNameKeyPair = Sing && !DelaySing ? new StrongNameKeyPair(StrongKeyPath) : null }); Console.WriteLine("Assembly has been written"); } catch (CompilationException ce) { this.Log.LogError("Compilation exception", null, null, ce.SequencePoint.Document.Url, ce.SequencePoint.StartLine, ce.SequencePoint.StartColumn, ce.SequencePoint.EndLine, ce.SequencePoint.EndColumn, ce.Message); Console.Error.WriteLine(ce.Message); return(false); } catch (Exception e) { this.Log.LogErrorFromException(e, true, true, null); Console.Error.WriteLine(e.Message); return(false); } return(true); }