コード例 #1
0
 public override void PrepareBasic()
 {
     this.container = new Injector();
     this.RegisterDummies();
     this.RegisterStandard();
     this.RegisterComplex();
 }
コード例 #2
0
ファイル: Program.cs プロジェクト: McSimp/driver-sf-modtools
        static bool InjectDLL()
        {
            Console.WriteLine("Waiting for process");
            Process driver = null;
            while (driver == null)
            {
                Process[] procs = Process.GetProcessesByName("Driver");
                if (procs.Length != 0)
                {
                    driver = procs[0];
                }
                else
                {
                    Console.Write(".");
                    System.Threading.Thread.Sleep(1000);
                }
            }
            Console.WriteLine();

            syringe = new Injector(driver);
            try
            {
                syringe.InjectLibrary(LIB_NAME);
            }
            catch (Exception e)
            {
                Console.WriteLine("INJECTION ERROR: " + e.Message);
                return false;
            }

            return true;
        }
コード例 #3
0
        public void TestAfterInject()
        {
            var eventCalled = false;

            IReflectionCache cache = new ReflectionCache();
            IBinder binder = new Binder();
            IInjector injector = new Injector(cache, binder);
            var instanceToInject = new MockClassVerySimple();

            injector.afterInject += delegate(IInjector source, ref object instance, ReflectedClass reflectedClass) {
                //The if below is just to avoid checking when injecting on MockIClass.
                if (reflectedClass.type != typeof(MockClassVerySimple)) return;

                Assert.AreEqual(injector, source);
                Assert.AreEqual(instanceToInject, instance);
                Assert.AreEqual(typeof(MockIClass), instanceToInject.field.GetType());

                eventCalled = true;
            };

            binder.Bind<IMockInterface>().To<MockIClass>();
            injector.Inject(instanceToInject);

            Assert.IsTrue(eventCalled);
        }
コード例 #4
0
        public void TestAfterResolve()
        {
            var eventCalled = false;

            IReflectionCache cache = new ReflectionCache();
            IBinder binder = new Binder();
            IInjector injector = new Injector(cache, binder);
            IMockInterface resolvedInstance = null;

            injector.afterResolve += delegate(IInjector source,
                Type type,
                InjectionMember member,
                object parentInstance,
              	object identifier,
                ref object resolutionInstance) {
                Assert.AreEqual(injector, source);
                Assert.AreEqual(typeof(IMockInterface), type);
                Assert.AreEqual(InjectionMember.None, member);
                Assert.IsNull(parentInstance);
                Assert.IsNull(identifier);
                Assert.IsNotNull(resolutionInstance);

                resolvedInstance = (IMockInterface)resolutionInstance;
                eventCalled = true;

                return false;
            };

            binder.Bind<IMockInterface>().To<MockIClass>();
            var instance = injector.Resolve<IMockInterface>();

            Assert.IsTrue(eventCalled);
            Assert.AreEqual(typeof(MockIClass), instance.GetType());
            Assert.AreEqual(resolvedInstance, instance);
        }
コード例 #5
0
        public object Apply(Type targetType, Injector activeInjector, Dictionary<string, object> injectParameters)
        {
            if (parentObject == null)
            {
                object contextViewObj = (IContextView) activeInjector.GetInstance(typeof(IContextView));
                if(contextViewObj != null)
                {
                    object contextView = ((IContextView) contextViewObj).view;
                    if(contextView != null)
                    {
                        if (contextView is Transform) parentObject = (Transform) contextView;
                        else if (contextView is GameObject) parentObject = ((GameObject) contextView).transform;
                    }
                }
            }
            if (parentObject == null)
            {
                destroyGameObjectWhenComplete = true;
                parentObject = new GameObject("Unity Component Provider").transform;
            }
            component = parentObject.gameObject.AddComponent(componentType);

            //TODO: Make auto InjectInto configurable
            activeInjector.InjectInto(component);

            if (_postApply != null)
            {
                _postApply(this, component);
            }
            return component;
        }
コード例 #6
0
        public void InjectFromCecilSecurityAttributeDefinitions()
        {
            var assembly = AssemblyCompiler.CompileTempAssembly(@"
            class Foo {
                public void CriticalMethod() {}
                public void Bar(int value) {}
                public void Bar(string value) {}
                public void SafeCriticalMethod() {}
                public Foo(string value) {}
            }

            class CriticalType {
            }
            ");

            var finder = new CecilDefinitionFinder(assembly);
            var safecriticalmethod = finder.FindMethod("System.Void Foo::SafeCriticalMethod()");
            var criticalmethod = finder.FindMethod("System.Void Foo::CriticalMethod()");
            var criticaltype = finder.FindType("CriticalType");

            var instructions = new List<CecilSecurityAttributeDescriptor>()
                                   {
                                       new CecilSecurityAttributeDescriptor(criticalmethod,SecurityAttributeType.Critical),
                                       new CecilSecurityAttributeDescriptor(safecriticalmethod,SecurityAttributeType.SafeCritical),
                                       new CecilSecurityAttributeDescriptor(criticaltype, SecurityAttributeType.Critical),
                                   };

            var injector = new Injector(assembly);
            injector.InjectAll(instructions);

            new AssemblySecurityVerifier(assembly.AssemblyPath()).Verify(instructions);
        }
コード例 #7
0
 static void Main(string[] args)
 {
     var injector = new Injector();
     injector.Bind<IClock, SystemClock>();
     injector.Bind<DateTimeZone>(DateTimeZone.Utc);
     injector.Bind<Instant>(Instant.FromUtc(2000, 1, 1, 0, 0, 0));
     injector.Bind<CalendarSystem>(CalendarSystem.Iso);
 }
コード例 #8
0
        public override object provide(Injector injector)
        {
            if ( provider == null ) {
                provider = (Provider)injector.getInstance(providerTypeDefinition);
            }

            return provider.get();
        }
コード例 #9
0
        public override object provide(Injector injector)
        {
            if (instance == null) {
                instance = sourceAbstractBinding.provide(injector);
            }

            return instance;
        }
            public object GetInstance(Injector.TypeIndex typeIndex)
            {
                // a type already created is always returned
                if (m_currentCallObjectList.ContainsKey(typeIndex))
                    return m_currentCallObjectList[typeIndex];

                return null;
            }
コード例 #11
0
        internal ModdingEnvironmentWriter(IMod[] mods_to_use, IMod[] dependencies_to_use, bool useHiDefProfile)
        {

            config = ModdingEnvironmentConfiguration.Create();

            ModEnvironment.RequestSetupDataReset();

            all_mods_to_process = mods_to_use;
            all_possible_dependencies = dependencies_to_use;

            var source_exe = ModManager.GameDirectory.ContainingFile(ModManager.OriginalExecutable);
                //new System.IO.FileInfo(System.IO.Path.Combine(base_directoy.FullName, source_exe_name));
            var modded_exe = ModManager.GameDirectory.ContainingFile(ModManager.ModdedExecutable);
                //new System.IO.FileInfo(System.IO.Path.Combine(base_directoy.FullName, modded_exe_name));
            var source_lib = ModManager.GameDirectory.ContainingFile(ModManager.OriginalLibrary);
            var modded_lib = ModManager.GameDirectory.ContainingFile(ModManager.ModdedLibrary);



            
            game_injector = new GnomoriaExeInjector(source_exe);
            lib_injector = new Injector(source_lib);
            config.Hashes.SourceExecutable = source_exe.GenerateMD5Hash();
            config.Hashes.SourceLibrary = source_lib.GenerateMD5Hash();

            // may switch those 2 later to have it outside...
            game_injector.Inject_SetContentRootDirectoryToCurrentDir_InsertAtStartOfMain();
            game_injector.Inject_CallTo_ModRuntimeController_Initialize_AtStartOfMain(ModManager.GameDirectory.ContainingFile(ModManager.ModController));
            //game_injector.Inject_TryCatchWrapperAroundEverthingInMain_WriteCrashLog();
            //game_injector.Inject_CurrentAppDomain_AddResolveEventAtStartOfMain();
            game_injector.Inject_SaveLoadCalls();
            //game_injector.Inject_TryCatchWrapperAroundGnomanEmpire_LoadGame();
            game_injector.Debug_ManipulateStuff();
            if (useHiDefProfile)
            {
                game_injector.Inject_AddHighDefXnaProfile();
            }


            foreach (var mod in mods_to_use)
            {
                ProcessMod(mod);
            }

            var allLoadedStuff = processedMods.Select(mod => Tuple.Create(mod, mod.Dependencies.Union(mod.InitAfter.Where(befor => processedMods.Contains(befor.GetInstance()))).Select(type => type.GetInstance())));
            var processedMods_sortedByDependencyAndInitAfter = DependencySort.Sort(allLoadedStuff);

            config.SetModReferences(processedMods_sortedByDependencyAndInitAfter.Select(mod => new ModReference(mod)).ToArray());

            //Mono.Cecil.WriterParameters
            game_injector.Write(modded_exe);
            lib_injector.Write(modded_lib);
            config.Hashes.ModdedExecutable = modded_exe.GenerateMD5Hash();
            config.Hashes.ModdedLibrary = modded_lib.GenerateMD5Hash();
        }
コード例 #12
0
        static int Main(string[] args)
        {
            #if DEBUG
            //I only have VS Express at home and this is the easiest way to debug
            //the unit tests since there's no test runner and I can't attach to NUnit.
            if (args.Length == 1 && args[0] == "/runtests")
            {
                return TestRunner.RunTests();
            }
            #endif
            var injector = new Injector();
            if (args.Length == 0 || args.Length > 3 || Regex.IsMatch(args[0], @"^((/|--?)(\?|h|help))$"))
            {
                PrintHelp();
                return 1;
            }

            Version version = Assembly.GetExecutingAssembly().GetName().Version;
            Console.WriteLine("InjectModuleInitializer v{0}.{1}", version.Major, version.Minor);
            Console.WriteLine("");

            string assemblyFile, moduleInitializer=null, keyfile=null;
            assemblyFile = args[args.Length - 1];

            for (int i = 0; i < args.Length - 1; i++)
            {
                var initMatch = Regex.Match(args[i], "^/m(oduleinitializer)?:(.+)", RegexOptions.IgnoreCase);
                if (initMatch.Success)
                {
                    moduleInitializer = initMatch.Groups[2].Value;
                }
                var keyMatch = Regex.Match(args[i], "^/k(eyfile)?:(.+)", RegexOptions.IgnoreCase);
                if (keyMatch.Success)
                {
                    keyfile = keyMatch.Groups[2].Value;
                }
                if (!initMatch.Success && !keyMatch.Success)
                {
                    Console.Error.WriteLine("error: Invalid argument '{0}', type InjectModuleInitializer /? for help", args[0]);
                    return 1;
                }
            }

            try
            {
                injector.Inject(assemblyFile, moduleInitializer, keyfile);
                Console.WriteLine("Module Initializer successfully injected in assembly " + assemblyFile);
                return 0;
            }
            catch (InjectionException ex)
            {
                Console.Error.WriteLine("error: " + ex.Message);
                return 1;
            }
        }
コード例 #13
0
        public void Main_With_Generic_Injector()
        {
            var injector = new Injector();
            injector.Bind<IClock, SystemClock>();
            injector.Bind<DateTimeZone>(DateTimeZone.GetSystemDefault());
            injector.Bind<Instant>(Instant.FromUtc(2000, 1,1,0,0,0));
            injector.Bind<CalendarSystem>(CalendarSystem.Iso);

            var presenter = injector.Resolve<DiaryPresenter>();
            presenter.Start();
        }
コード例 #14
0
ファイル: Executor.cs プロジェクト: emist/Eryan
        public void Inject(String dll, String process)
        {
            //String dll = "C:\\Users\\emist\\Documents\\Visual Studio 2008\\Projects\\InjectDLL\\Debug\\InjectDLL.dll";

            Console.WriteLine("Trying to inject " + dll + " into " + process);
            MessageStruct messageData = new MessageStruct() { Text = "Custom Message", Caption = "Custom Message Box" };
            Process[] processes = Process.GetProcessesByName(process);
            Array.Sort(processes, delegate(Process x, Process y) { return -1 * (x.StartTime.CompareTo(y.StartTime)); });
            syringe = new Injector(processes[0]);
            syringe.InjectLibrary(dll);
            Console.WriteLine(dll + " injected into " + process);
        }
 public object GetInstance(Injector.TypeIndex typeIndex)
 {
     // a type configured as singleton always returns the same object, independently of the configuration
     if (m_singletonList.ContainsKey(typeIndex))
     {
         return m_singletonList[typeIndex];
     }
     else
     {
         return null;
     }
 }
コード例 #16
0
ファイル: Player.cs プロジェクト: jhurliman/d3research
        public Player(Injector injector, uint actorPtr, uint acdPtr, int snoID, uint worldID, uint sceneID)
            : base(snoID)
        {
            Injector = injector;
            ActorPtr = actorPtr;
            AcdPtr = acdPtr;
            SkillSlots = new SkillSlots();
            Outfit = new PlayerOutfit();
            WorldID = worldID;
            SceneID = sceneID;

            PrimaryResourceType = ResourceType.None;
            SecondaryResourceType = ResourceType.None;
        }
コード例 #17
0
        public void OutputDirectory()
        {
            var assembly = GetType ().Assembly.ManifestModule.FullyQualifiedName;
            var tempPath = Path.GetTempPath ();
            var outputFile = Path.Combine (tempPath, Path.GetFileName (assembly));

            File.Delete(outputFile);

            var injector = new Injector(assembly);
            injector.OutputDirectory = tempPath;
            injector.InjectAll(ParseSecurityAttributeDescriptors(""));

            Assert.IsTrue(File.Exists(outputFile));
        }
コード例 #18
0
ファイル: Program.cs プロジェクト: AdamosX/D3DWindower
        static void Main(string[] args)
        {
            Console.WriteLine("Trying to inject dll into notepad.exe");
            MessageStruct messageData = new MessageStruct() { Text = "Custom Message", Caption = "Custom Message Box" };
            using (Injector syringe = new Injector(Process.GetProcessesByName("notepad")[0]))
            {
                syringe.InjectLibrary("Stub.dll");

                Console.WriteLine("Stub.dll injected into notepad, trying to call void Initialise() with no parameters");
                Console.ReadLine();
                syringe.CallExport("Stub.dll", "Initialise");
                Console.WriteLine("Waiting...");
                Console.ReadLine();
                Console.WriteLine("Trying to call InitWithMessage( PVOID ) with custom data {0}", messageData);
                Console.ReadLine();
                syringe.CallExport("Stub.dll", "InitWithMessage", messageData);
                Console.WriteLine("Waiting...");
                Console.ReadLine();
            }
            Console.WriteLine("Stub.dll should be ejected");
            Console.ReadLine();
        }
コード例 #19
0
 static bool InRangeOnEval(int value, [EvalOnInjection] int start, [EvalOnInjection] int count)
 {
     return(Injector.Inject(() => Enumerable.Range(start, count).Contains(value)));
 }
コード例 #20
0
 public override void Prepare()
 {
     this.injector = new Injector();
     this.RegisterDummies();
 }
コード例 #21
0
ファイル: InjectionModel.cs プロジェクト: mrousavy/Jellyfish
 public InjectionModel()
 {
     Injector = new Injector();
 }
コード例 #22
0
 public static T GetOrAddSingleton <T>(this Injector self, object caller)
 {
     return(GetOrAddSingleton(self, caller, () => CreateNewInstance <T>()));
 }
コード例 #23
0
 public override object Construct(Injector injector)
 {
     return(Instance);
 }
コード例 #24
0
 public override object provide(Injector injector)
 {
     return instance;
 }
コード例 #25
0
        /// <summary>
        /// Creates a new UniversalApp instance.
        /// </summary>
        /// <param name="defaultPage">The default page to navigate to when the app is started.</param>
        /// <param name="backButtonBehaviour">The back button behaviour on the root level.</param>
        /// <param name="useAppShell">Defines whether the app shell is used.</param>
        /// <param name="modules">The ninject modules.</param>
        public UniversalApp(Type defaultPage, AppBackButtonBehaviour backButtonBehaviour, bool useAppShell, params NinjectModule[] modules)
        {
            Current             = this;
            DefaultPage         = defaultPage;
            BackButtonBehaviour = backButtonBehaviour;
            UseAppShell         = useAppShell;
            AppAssemblyName     = GetType().GetTypeInfo().Assembly.GetName().Name;

            Injector = IoC.Injector.Instance;

            if (modules == null)
            {
                Injector.Init(new DefaultModule());
            }
            else
            {
                Injector.Init(modules);
            }

            Resuming += (s, e) =>
            {
                Logger.WriteLine("RESUMING");
                OnResuming(e);

                var rootPage = NavigationService.FrameFacade.Content as UniversalPage;

                if (rootPage != null)
                {
                    rootPage.OnResume();
                }
            };
            Suspending += async(s, e) =>
            {
                var globalDeferral = e.SuspendingOperation.GetDeferral();
                Logger.WriteLine("SUSPENDING");
                try
                {
                    // call system-level suspend
                    await OnSuspendingAsync(e);

                    foreach (var service in WindowWrapper.ActiveWrappers.SelectMany(x => x.NavigationServices))
                    {
                        try
                        {
                            // date the cache (which marks the date/time it was suspended)
                            service.FrameFacade.SetFrameState(CACHE_DATE_KEY, DateTime.Now.ToString());

                            // call view model suspend (OnNavigatedfrom)
                            await service.SuspendingAsync();
                        }
                        catch (Exception ex)
                        {
                            // FrameFacade.SetFrameState() causes en error sometimes:
                            // State Manager failed to write the setting. (Exception from HRESULT: 0x80073DC0)
                            Logger.WriteLine(ex, "Suspending failed: FrameFacade.SetFrameState(CACHE_DATE_KEY)");
                        }
                    }
                }
                finally
                {
                    globalDeferral.Complete();
                }
            };

            // handle exceptions from external libraries
            UnhandledException += (s, e) =>
            {
                if (e != null)
                {
                    Exception exception = e.Exception;

                    // smatoo advertising (recommanded by MSDN)
                    if (exception is NullReferenceException && exception.ToString().ToUpper().Contains("SOMA"))
                    {
                        Logger.WriteLine("Handled Smaato null reference exception {0}", exception);
                        e.Handled = true;
                        return;
                    }
                }

                // APP SPECIFIC HANDLING HERE

                if (Debugger.IsAttached)
                {
                    // An unhandled exception has occurred; break into the debugger
                    Debugger.Break();
                }
            };
        }
コード例 #26
0
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to CsharpInjector demo for DllExport library");
            Console.WriteLine("Just a small reminder - you cannot inject to every process using this injector");
            Console.WriteLine("Be sure to inject only to processes that match process configuration you use for this project (x86, x64)");

            Console.Write("Put in name (without .exe) or id of the process you want to inject in: ");
            string read = Console.ReadLine();
            RemoteProcessHandle processHandle;

            if (int.TryParse(read, out int processId))
            {
                processHandle = Injector.GetRemoteProcess(processId);
            }
            else
            {
                processHandle = Injector.GetRemoteProcess(read);
            }

            if (processHandle == null)
            {
                Console.WriteLine("Process not found.");
                Console.Read();
                return;
            }

            string dllPath = "DllExportLibrary.dll";

            if (!File.Exists(dllPath))
            {
                Console.WriteLine("Dll to inject not found.");
            }

            InjectedModule injectedModule = processHandle.Inject(dllPath);

            Console.WriteLine("Module injected");

            Console.WriteLine("Calling Main function to alloc console");
            FunctionResult result     = injectedModule.ExecuteFunction("Main");
            int            mainResult = result.To <int>();

            Console.WriteLine($"Result from main: {mainResult} (should be 1)");

            Console.WriteLine($"Sleeping for 1 second");
            Thread.Sleep(1000);

            // Execute addition function and get its params
            Console.WriteLine("Calling Addition with params of 10 and 5; Expected result: 15");
            result = injectedModule.ExecuteFunction("Add", new AddParams
            {
                First  = 5,
                Second = 10
            });

            int additionResult = result.To <int>();

            Console.WriteLine("Result: " + additionResult);

            injectedModule.ExecuteFunction("MyFunction", new MyFunctionParams
            {
                Param  = "Injected string!",
                Number = 1000
            });

            // Get result struct
            result = injectedModule.ExecuteFunction("Calc", new AddParams
            {
                First  = 15,
                Second = 5
            });
            CalculationResult calculationResult = result.To <CalculationResult>();

            injectedModule.Process.Close();
            Console.ReadLine();
        }
コード例 #27
0
 public InjectionActivity(Injector <T> injector)
 {
     Requires.NotNull(injector, "injector");
     _injector = injector;
 }
コード例 #28
0
 public static bool IsEven(int value)
 => Injector.Inject(() => (value % 2) == 0);
コード例 #29
0
 public static bool IsHigherThanAndEven(int value, int threshold)
 => Injector.Inject(() => IsEven(value) && value > threshold);
コード例 #30
0
        protected void RefreshRemotePlayProcess()
        {
            Process RemotePlayProcess = Injector.FindProcess(RemotePlayConstants.TARGET_PROCESS_NAME);

            InstanceSettings.GetInstance().SetRemotePlayProcess(RemotePlayProcess);
        }
コード例 #31
0
 public RemotePlayStarter()
 {
     Injector.FindProcess(RemotePlayConstants.TARGET_PROCESS_NAME)?.Kill();
 }
コード例 #32
0
ファイル: HM3Engine.cs プロジェクト: OrfeasZ/Statman
        public void Update()
        {
            if (m_GameProcess == null || m_GameProcess.HasExited)
            {
                if (m_SkipUpdates > 0)
                {
                    --m_SkipUpdates;
                    return;
                }

                m_SkipUpdates = 4;

                m_GameProcess = null;
                Active = false;

                if (Reader != null)
                {
                    Reader.CloseHandle();
                    Reader = null;
                }

                if (m_Injector != null)
                {
                    m_Injector.Dispose();
                    m_Injector = null;
                }

                var s_Processes = Process.GetProcessesByName("HitmanBloodMoney");

                if (s_Processes.Length == 0)
                    return;

                // We always select the first process.
                m_GameProcess = s_Processes[0];

                // Setup our Memory Reader.
                Reader = new ProcessMemoryReader(m_GameProcess);

                try
                {
                    if (Reader.OpenProcess())
                    {
                        m_SkipUpdates = 0;
                        Active = true;

                        // Create our injector and inject our stat module.
                        m_Injector = new Injector(m_GameProcess, false);
                        m_Injector.InjectLibrary("HM3.dll");

                        // Setup our main control.
                        MainApp.MainWindow.Dispatcher.Invoke(() =>
                        {
                            Control = new MainControl();
                        });

                        // Setup our engine-specific classes.
                        StatTracker = new StatTracker(this);
                        TimeTracker = new TimeTracker(this);

                        // Update level labels.
                        CurrentLevel = "No Level";
                        CurrentLevelScene = "No Level";
                        InGame = false;

                        Control.SetCurrentLevel(CurrentLevel);
                        Control.SetCurrentLevelScene(CurrentLevelScene);

                        // Set our control in the main window.
                        InitMenuItems();
                        MainApp.MainWindow.SetEngineControl(Control, m_MenuItems);
                    }
                }
                catch (Exception)
                {
                    m_GameProcess = null;
                    Active = false;
                }
            }

            if (!Active)
                return;

            // Update our trackers.
            TimeTracker.Update();
            StatTracker.Update();

            // Set game time.
            if (StatTracker.CurrentStats.m_Time > 0 || !InGame)
                Control.SetCurrentTime(StatTracker.CurrentStats.m_Time);
            else
                Control.SetCurrentTime(TimeTracker.CurrentTime);
        }
コード例 #33
0
        public void TestBindingEvaluation()
        {
            var eventCalled = false;

            IReflectionCache cache = new ReflectionCache();
            IBinder binder = new Binder();
            IInjector injector = new Injector(cache, binder);

            injector.bindingEvaluation += delegate(IInjector source, ref BindingInfo binding) {
                Assert.AreEqual(injector, source);
                Assert.NotNull(binding);

                eventCalled = true;

                return new MockIClassWithoutAttributes();
            };

            binder.Bind<IMockInterface>().To<MockIClass>();
            var instance = injector.Resolve<IMockInterface>();

            Assert.IsTrue(eventCalled);
            Assert.AreEqual(typeof(MockIClassWithoutAttributes), instance.GetType());
        }
コード例 #34
0
ファイル: App.xaml.cs プロジェクト: SoloJr/ASSE
 /// <summary>
 /// Raises the <see cref="E:System.Windows.Application.Startup" /> event.
 /// </summary>
 /// <param name="e">A <see cref="T:System.Windows.StartupEventArgs" /> that contains the event data.</param>
 protected override void OnStartup(StartupEventArgs e)
 {
     Injector.Inject(new Bindings());
     base.OnStartup(e);
 }
コード例 #35
0
        public static void Monitor(string processName, byte[] dllContent, AutoResetEvent injectionEvent, string namespaceString)
        {
            IntPtr assembly = IntPtr.Zero;

            string lastPid = null;
            string pidPath = processName + "enabler.lastppid";
            string pidfile = Path.Combine(Path.GetTempPath(), pidPath);

            InjectionManager.minimizeMemory();
            if (File.Exists(pidfile))
            {
                lastPid = File.ReadAllText(pidfile);
            }
            for (; ;)
            {
                try
                {
                    InjectionManager.minimizeMemory();
                    Thread.Sleep(1000);
                    Process process = Process.GetProcessesByName(processName).FirstOrDefault <Process>();
                    if (process != null)
                    {
                        InjectionManager.SetStatus("Game process found.", State.GameProcessFound);
                        injectionEvent.Set();

                        if (process.Id.ToString() == lastPid)
                        {
                            InjectionManager.SetStatus("Telemetry plugin already running in the current game.", State.Success);
                            injectionEvent.Set();
                        }
                        else
                        {
                            InjectionManager.SetStatus("Waiting 5s before plugin injection.", State.Waiting);
                            injectionEvent.Set();
                            Thread.Sleep(5000);
                            Injector injector;
                            Injector enabler = injector = new Injector(process.Id);
                            try
                            {
                                assembly = IntPtr.Zero;
                                try
                                {
                                    assembly = enabler.Inject(dllContent, namespaceString, "Loader", "Init");
                                    InjectionManager.minimizeMemory();
                                }
                                catch (InjectorException ie)
                                {
                                    string            str = "Failed to add assembly: ";
                                    InjectorException ex  = ie;
                                    InjectionManager.SetStatus(str + ((ex != null) ? ex.ToString() : null), State.Failed);
                                    injectionEvent.Set();
                                }
                                catch (Exception exc)
                                {
                                    string    str2 = "Failed to add assembly (unknown error): ";
                                    Exception ex2  = exc;
                                    InjectionManager.SetStatus(str2 + ((ex2 != null) ? ex2.ToString() : null), State.Failed);
                                    injectionEvent.Set();
                                }
                                if (assembly == IntPtr.Zero)
                                {
                                    break;
                                }
                                InjectionManager.SetStatus("Telemetry plugin successfully injected", State.Success);
                                File.WriteAllText(pidfile, process.Id.ToString());
                                injectionEvent.Set();
                                while (!process.HasExited)
                                {
                                    Thread.Sleep(1);
                                }
                                try
                                {
                                    if (!process.HasExited)
                                    {
                                        enabler.Eject(assembly, "TelemetryExporter", "Loader", "Unload");
                                    }
                                    File.Delete(pidfile);
                                }
                                catch
                                {
                                }
                            }
                            finally
                            {
                                if (injector != null)
                                {
                                    ((IDisposable)injector).Dispose();
                                }
                            }
                        }
                        Thread.Sleep(1000);
                    }
                    continue;
                }
                catch
                {
                    continue;
                }
                break;
            }
        }
コード例 #36
0
 public HelloWorldFixture()
 {
     Target32   = Process.Start("HelloWorld32");
     Injector32 = new Injector(Target32);
     Injector32.Inject(InjectModule32);
 }
コード例 #37
0
#pragma warning restore CS0809 // Obsolete member overrides non-obsolete member

        /// <summary>
        /// The internal launch handler that is called when when the app has been launched.
        /// </summary>
        /// <param name="e">The launch activated event args.</param>
        private async void InternalLaunchAsync(ILaunchActivatedEventArgs e)
        {
            // now handle normal activation
            UIElement splashScreen = default(UIElement);

            if (SplashFactory != null)
            {
                splashScreen           = SplashFactory(e.SplashScreen);
                Window.Current.Content = splashScreen;
            }

            InitRootFrameAndNavigation();

            // expire state (based on expiry)
            DateTime cacheDate;
            var      otherwise = DateTime.MinValue.ToString();

            if (DateTime.TryParse(NavigationService.FrameFacade.GetFrameState(CACHE_DATE_KEY, otherwise), out cacheDate))
            {
                var cacheAge = DateTime.Now.Subtract(cacheDate);
                if (cacheAge >= CacheMaxDuration)
                {
                    // clear state in every nav service in every view
                    foreach (var service in WindowWrapper.ActiveWrappers.SelectMany(x => x.NavigationServices))
                    {
                        service.FrameFacade.ClearFrameState();
                    }
                }
            }
            else
            {
                // no date, also fine...
            }

            // the user may override to set custom content
            await OnInitializeAsync(e);

            _statusBarService = Injector.Get <IStatusBarService>();

            if (UseAppShell &&
                e.PreviousExecutionState != ApplicationExecutionState.Running &&
                e.PreviousExecutionState != ApplicationExecutionState.Suspended)
            {
                Window.Current.Content = new AppShell(
                    RootFrame,
                    CreateNavigationMenuItems(),
                    CreateBottomDockedNavigationMenuItems());
            }

            switch (e.PreviousExecutionState)
            {
            case ApplicationExecutionState.NotRunning:
            case ApplicationExecutionState.Running:
            case ApplicationExecutionState.Suspended:
            case ApplicationExecutionState.ClosedByUser:
            {
                // launch if not restored
                await OnStartAsync(StartKind.Launch, e);

                break;
            }

            case ApplicationExecutionState.Terminated:
            {
                /*
                 *  Restore state if you need to/can do.
                 *  Remember that only the primary tile should restore.
                 *  (this includes toast with no data payload)
                 *  The rest are already providing a nav path.
                 *  In the event that the cache has expired, attempting to restore
                 *  from state will fail because of missing values.
                 *  This is okay & by design.
                 */
                if (DetermineStartCause(e) == AdditionalKinds.Primary || DetermineStartCause(e) == AdditionalKinds.Toast)
                {
                    var restored = NavigationService.RestoreSavedNavigation();
                    if (!restored)
                    {
                        await OnStartAsync(StartKind.Launch, e);
                    }
                    else
                    {
                        UpdateShellBackButton();
                    }
                }
                else
                {
                    await OnStartAsync(StartKind.Launch, e);
                }
                break;
            }
            }

            // if the user didn't already set custom content use rootframe
            if (Window.Current.Content == null || Window.Current.Content == splashScreen)
            {
                Window.Current.Content = RootFrame;
            }

            // Update the app theme
            UpdateTheme();

            // ensure active
            Window.Current.Activate();
        }
コード例 #38
0
ファイル: MethodBindingHandler.cs プロジェクト: Keswiik/Juicy
 /// <summary>
 /// Creates a new handler with the specified parent injector and method invoker.
 /// </summary>
 /// <param name="injector">The parent injector to use.</param>
 /// <param name="loggerFactory">The logger factory used to create an ILogger.</param>
 /// <param name="methodInvoker">The method invoker to use.</param>
 internal MethodBindingHandler(Injector injector, ILoggerFactory loggerFactory, IMethodInvoker methodInvoker) : base(injector, loggerFactory)
 {
     MethodInvoker = methodInvoker;
 }
コード例 #39
0
 public static V SetSingleton <V>(this Injector self, object caller, V singletonInstance, bool overrideExisting = false)
 {
     self.SetSingleton <V, V>(caller, singletonInstance, overrideExisting);
     return(singletonInstance);
 }
コード例 #40
0
 private void Start()
 {
     presenter = Injector.injectSettingsPresenter(this);
     presenter.getDifficulties();
 }
コード例 #41
0
 public override sealed void Dispose()
 {
     // Allow the container and everything it references to be disposed.
     this.injector = null;
 }
コード例 #42
0
 public NewTournamentForm()
 {
     InitializeComponent();
     _presenter = Injector.provideNewTournamentPresenter(this);
 }
コード例 #43
0
 public void TestInitialize() => Injector.CleanSessionContext();
コード例 #44
0
 private void OnEnable()
 {
     presenter = Injector.injectHomePresenter(this);
     presenter.getUserState();
 }
 public void NewInstance(Injector.TypeIndex typeIndex, object instance)
 {
     m_currentCallObjectList.Add(typeIndex, instance);
 }
コード例 #46
0
 public static void Start()
 {
     Injector.Run();
 }
コード例 #47
0
ファイル: HM3Engine.cs プロジェクト: OrfeasZ/Statman
        public void Dispose()
        {
            if (Reader != null)
            {
                Reader.CloseHandle();
                Reader = null;
            }

            if (m_Injector != null)
            {
                m_Injector.Dispose();
                m_Injector = null;
            }
        }
コード例 #48
0
 static void Main()
 {
     using var injector = new Injector();
     using var game     = injector.Get <GameBootstrapper>();
     game.Run();
 }
コード例 #49
0
 static bool InRangeDynamic(int value, int start, int count)
 => Injector.Inject(() => Enumerable.Range(start, count).Contains(value));
コード例 #50
0
        // Apply PostSpawnOrbit patches
        private void ApplyOrbitPatches()
        {
            // Bodies
            Dictionary <String, KeyValuePair <CelestialBody, CelestialBody> > fixes = new Dictionary <String, KeyValuePair <CelestialBody, CelestialBody> >();

            for (Int32 i = 0; i < PSystemManager.Instance.localBodies.Count; i++)
            {
                CelestialBody body = PSystemManager.Instance.localBodies[i];

                // Post spawn patcher
                if (!body.Has("orbitPatches"))
                {
                    continue;
                }

                ConfigNode    orbitNode = body.Get <ConfigNode>("orbitPatches");
                OrbitLoader   loader    = new OrbitLoader(body);
                CelestialBody oldRef    = body.referenceBody;
                Parser.LoadObjectFromConfigurationNode(loader, orbitNode, "Kopernicus");
                oldRef.orbitingBodies.Remove(body);

                if (body.referenceBody == null)
                {
                    // Log the exception
                    Debug.Log("Exception: PostSpawnOrbit reference body for \"" + body.name +
                              "\" could not be found. Missing body name is \"" + loader.ReferenceBody + "\".");

                    // Open the Warning popup
                    Injector.DisplayWarning();
                    Destroy(this);
                    return;
                }

                fixes.Add(body.transform.name,
                          new KeyValuePair <CelestialBody, CelestialBody>(oldRef, body.referenceBody));
                body.referenceBody.orbitingBodies.Add(body);
                body.referenceBody.orbitingBodies =
                    body.referenceBody.orbitingBodies.OrderBy(cb => cb.orbit.semiMajorAxis).ToList();
                body.orbit.Init();

                //body.orbitDriver.UpdateOrbit();

                // Calculations
                if (!body.Has("sphereOfInfluence"))
                {
                    body.sphereOfInfluence = body.orbit.semiMajorAxis *
                                             Math.Pow(body.Mass / body.orbit.referenceBody.Mass, 0.4);
                }

                if (!body.Has("hillSphere"))
                {
                    body.hillSphere = body.orbit.semiMajorAxis * (1 - body.orbit.eccentricity) *
                                      Math.Pow(body.Mass / body.orbit.referenceBody.Mass, 0.333333333333333);
                }

                if (!body.solarRotationPeriod)
                {
                    continue;
                }

                Double rotationPeriod = body.rotationPeriod;
                Double orbitalPeriod  = body.orbit.period;
                body.rotationPeriod = rotationPeriod * orbitalPeriod / (orbitalPeriod + rotationPeriod);
            }

            // Update the order in the tracking station
            List <MapObject> trackingstation = new List <MapObject>();

            Utility.DoRecursive(PSystemManager.Instance.localBodies[0], cb => cb.orbitingBodies, cb =>
            {
                trackingstation.Add(PlanetariumCamera.fetch.targets.Find(t => t.celestialBody == cb));
            });
            PlanetariumCamera.fetch.targets = trackingstation.Where(m => m != null).ToList();

            // Undo stuff
            foreach (CelestialBody b in PSystemManager.Instance.localBodies.Where(b => b.Has("orbitPatches")))
            {
                String transformName = b.transform.name;
                fixes[transformName].Value.orbitingBodies.Remove(b);
                fixes[transformName].Key.orbitingBodies.Add(b);
                fixes[transformName].Key.orbitingBodies = fixes[transformName].Key.orbitingBodies
                                                          .OrderBy(cb => cb.orbit.semiMajorAxis).ToList();
            }
        }
コード例 #51
0
        private static void Main(string[] args)
        {
            Injector injector = new Injector("ProjectWinter");

            Inject(injector);
        }
コード例 #52
0
        void InjectSteamOverlayIfNeeded() {
            if (_spec.SteamDRM || !_isSteamValid)
                return;

            Environment.SetEnvironmentVariable("SteamAppID", Convert.ToString(_spec.SteamID));
            Environment.SetEnvironmentVariable("SteamGameID", Convert.ToString(_spec.SteamID));

            var injector = new Injector(_launchedGame);
            TryInject(injector);
            Launch(new ProcessStartInfo(Path.Combine(_spec.SteamPath, "GameOverlayUI.exe"),
                "-pid " + _launchedGame.Id));

            if (_spec.SteamID != 0)
                TrySteamApiInit();
        }
 public void SetupFixture() {
     _injector = new Injector(new MyBinder());
 }
コード例 #54
0
 void TryInject64(Injector injector) {
     try {
         injector.InjectLibrary(Path.Combine(_spec.SteamPath,
             "GameOverlayRenderer64.dll"));
     } catch (Win32Exception e) {
         MainLog.Logger.FormattedWarnException(e);
     }
 }
コード例 #55
0
 public abstract object provide(Injector injector);
コード例 #56
0
        /// <summary>
        /// Inits the root frame and the navigation.
        /// </summary>
        private void InitRootFrameAndNavigation()
        {
            // setup frame
            if (RootFrame == null)
            {
                RootFrame = new Frame
                {
                    Language = ApplicationLanguages.Languages[0]
                };
                RootFrame.Navigated += (s, args) =>
                {
                    UpdateShellBackButton();
                };

                // register back button
                SystemNavigationManager.GetForCurrentView().BackRequested += (s, args) =>
                {
                    var handledByAppShell = false;
                    if (UseAppShell)
                    {
                        var appshell = Window.Current.Content as AppShell;
                        if (appshell != null)
                        {
                            appshell.BackRequested(ref handledByAppShell);
                        }
                    }

                    if (!handledByAppShell)
                    {
                        var handled = false;

                        if (ApiInformation.IsApiContractPresent("Windows.Phone.PhoneContract", 1, 0))
                        {
                            if (NavigationService.CanGoBack)
                            {
                                handled = true;
                            }
                            else if (BackButtonBehaviour == AppBackButtonBehaviour.Terminate)
                            {
                                args.Handled = true;
                                Current.Exit();
                            }
                        }
                        else
                        {
                            handled = !NavigationService.CanGoBack;
                        }

                        args.Handled = handled;
                        RaiseBackRequested(ref handled);
                    }
                    else
                    {
                        args.Handled = true;
                    }
                };

                // hook up keyboard and mouse Back handler
                _keyboardService = Injector.Get <IKeyboardService>();
                _keyboardService.AfterBackGesture = () =>
                {
                    //the result is no matter
                    var handled = false;
                    RaiseBackRequested(ref handled);
                };

                // Hook up keyboard and house Forward handler
                _keyboardService.AfterForwardGesture = RaiseForwardRequested;
            }

            // setup default view
            var view = WindowWrapper.ActiveWrappers.First();
            var navigationService = new NavigationService(RootFrame);

            view.NavigationServices.Add(navigationService);

            // requrest minimum size, to be like the MSN apps
            var applicationView = ApplicationView.GetForCurrentView();

            applicationView.SetPreferredMinSize(new Size(500, 500));
        }
コード例 #57
0
 void TryInject(Injector injector) {
     try {
         injector.InjectLibrary(Path.Combine(_spec.SteamPath, "GameOverlayRenderer.dll"));
     } catch (Win32Exception) {
         TryInject64(injector);
     }
 }
コード例 #58
0
 public static object SetSingleton <V>(this Injector self, V singletonInstance, bool overrideExisting = false)
 {
     return(self.SetSingleton <V, V>(new object(), singletonInstance, overrideExisting));
 }
コード例 #59
0
 public static void AddDIConfiguration(this IServiceCollection services)
 {
     Injector.RegisterServices(services);
 }
コード例 #60
0
#pragma warning restore CS0809 // Obsolete member overrides non-obsolete member

        /// <summary>
        /// This handles all the prelimimary stuff unique to Activated before calling OnStartAsync()
        /// This is private because it is a specialized prelude to OnStartAsync().
        /// OnStartAsync will not be called if state restore is determined.
        /// </summary>
        /// <param name="e">The event args.</param>
        private async Task InternalActivatedAsync(IActivatedEventArgs e)
        {
            if (e.Kind == ActivationKind.ShareTarget)
            {
                var shareArgs = e as ShareTargetActivatedEventArgs;

                if (e.PreviousExecutionState == ApplicationExecutionState.Running ||
                    e.PreviousExecutionState == ApplicationExecutionState.Suspended)
                {
                    var frame = new Frame();
                    frame.Tag = FRAME_IN_SHARE_CONTEXT;
                    Window.Current.Content = frame;

                    var view = WindowWrapper.Current(Window.Current);
                    var navigationService = new NavigationService(frame);
                    view.NavigationServices.Add(navigationService);

                    if (frame.Content == null)
                    {
                        navigationService.Navigate(ShareTargetPage, shareArgs.ShareOperation);
                    }
                }
                else
                {
                    InitRootFrameAndNavigation();
                    Window.Current.Content = RootFrame;

                    await WindowWrapper.Current(NavigationService).Dispatcher.DispatchAsync(() =>
                    {
                        NavigationService.Navigate(ShareTargetPage, shareArgs.ShareOperation);
                    });
                }

                Window.Current.Activate();
                return;
            }

            // sometimes activate requires a frame to be built, such as after a launch using a toast notification
            if (Window.Current.Content == null)
            {
                InitRootFrameAndNavigation();

                await OnInitializeAsync(e);

                _statusBarService = Injector.Get <IStatusBarService>();

                if (UseAppShell &&
                    e.PreviousExecutionState != ApplicationExecutionState.Running &&
                    e.PreviousExecutionState != ApplicationExecutionState.Suspended &&
                    e.Kind != ActivationKind.ShareTarget)
                {
                    Window.Current.Content = new AppShell(
                        RootFrame,
                        CreateNavigationMenuItems(),
                        CreateBottomDockedNavigationMenuItems());
                }
            }

            // onstart is shared with activate and launch
            await OnStartAsync(StartKind.Activate, e);

            // if the user didn't already set custom content use rootframe
            if (Window.Current.Content == null)
            {
                Window.Current.Content = RootFrame;
            }

            UpdateTheme();

            // ensure active (this will hide any custom splashscreen)
            Window.Current.Activate();
        }