Example #1
0
        /// <inheritdoc />
        protected override DependencyObject GetContainerForItemOverride()
        {
            ProxyGenerator proxyGen = new ProxyGenerator();
            var            containerForItemOverride = new MyRibbonTab();

            if (EnableProxy)
            {
                var interceptor = new BaseInterceptorImpl(UseLogMethod, ProxyGeneratorHelper.ProxyGenerator);
                interceptor.Callback = ProxyCallback;
                var tabPRoxy = proxyGen.CreateClassProxyWithTarget(containerForItemOverride,
                                                                   new ProxyGenerationOptions(new MyRibbonGenHook()),
                                                                   interceptor);

                return(tabPRoxy);
            }



            return(containerForItemOverride);
        }
Example #2
0
            T IProxyBuilderOptionsContext <T> .Build()
            {
                T   result  = null;
                var options = CreateOptions();

                if (_proxyType == ProxyTypes.Interface)
                {
                    if (options != null)
                    {
                        result = _target != null?
                                 ProxyGenerator.CreateInterfaceProxyWithTarget <T>(_target, options, _interceptors.ToArray()) :
                                     _targetInterface != null?
                                     ProxyGenerator.CreateInterfaceProxyWithTargetInterface <T>(_target, options, _interceptors.ToArray()) :
                                         ProxyGenerator.CreateInterfaceProxyWithoutTarget <T>(options, _interceptors.ToArray());
                    }
                    else
                    {
                        result = _target != null?
                                 ProxyGenerator.CreateInterfaceProxyWithTarget <T>(_target, _interceptors.ToArray()) :
                                     _targetInterface != null?
                                     ProxyGenerator.CreateInterfaceProxyWithTargetInterface <T>(_target, _interceptors.ToArray()) :
                                         ProxyGenerator.CreateInterfaceProxyWithoutTarget <T>(_interceptors.ToArray());
                    }
                }
                if (_proxyType == ProxyTypes.Class)
                {
                    if (options != null)
                    {
                        result = _target != null?
                                 ProxyGenerator.CreateClassProxyWithTarget <T>(_target, options, _interceptors.ToArray()) :
                                     ProxyGenerator.CreateClassProxy <T>(options, _interceptors.ToArray());
                    }
                    else
                    {
                        result = _target != null?
                                 ProxyGenerator.CreateClassProxyWithTarget <T>(_target, _interceptors.ToArray()) :
                                     ProxyGenerator.CreateClassProxy <T>(_interceptors.ToArray());
                    }
                }
                return(result);
            }
        public static object AsTrackable(this object obj)
        {
            //is the object already a trackable object?
            if (obj is ITrackableObject)
            {
                return(obj);
            }

            ObjectTrackingState objectTrackingState = new ObjectTrackingState(obj);

            object result = Generator.CreateClassProxyWithTarget(
                obj.GetType(),
                new[] { typeof(ITrackableObject), typeof(INotifyPropertyChanging), typeof(INotifyPropertyChanged) },
                obj,
                new PropertyChangingInterceptor(objectTrackingState),
                new PropertyChangedInterceptor(objectTrackingState),
                new ObjectInterceptor(objectTrackingState)
                );

            return(result);
        }
        /// <summary>
        ///     Enables automatic saving when changing any <b>virtual properties</b>.
        /// </summary>
        /// <typeparam name="TSettings">A settings class implementing <see cref="JsonSettings"/></typeparam>
        /// <param name="settings">The settings class to wrap in a proxy.</param>
        /// <returns></returns>
        public static TSettings EnableAutosave <TSettings>(this TSettings settings) where TSettings : JsonSettings
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

            //if it doesn't contain any virtual methods, notify developer about it.
            if (!settings.GetType().GetProperties().Where(p => _jsonSettingsAbstractionVirtuals.All(av => !p.Name.Equals(av))).Any(p => p.GetGetMethod().IsVirtual))
            {
                var msg = $"JsonSettings: During proxy creation of {settings.GetType().Name}, no virtual properties were found which will make Autosaving redundant.";
                Debug.WriteLine(msg);
                if (Debugger.IsAttached)
                {
                    Console.Error.WriteLine(msg);
                }
                return(settings);
            }

            _generator = _generator ?? new ProxyGenerator();
            return(_generator.CreateClassProxyWithTarget <TSettings>(settings, new JsonSettingsInterceptor((nucs.JsonSettings.JsonSettings)(object) settings)));
        }
Example #5
0
        public void DynamicProxy_NonIntercepted_Property_Leaked()
        {
            var instance = new TestClassForCache();
            var toProxy  = instance.GetType();

            var proxyGenerationOptions = new ProxyGenerationOptions(
                new TestCacheProxyGenerationHook()
                );

            var generator = new ProxyGenerator();
            var proxy     = generator.CreateClassProxyWithTarget(
                toProxy,
                instance,
                proxyGenerationOptions
                );

            var accessor = (ITestCacheInterface)proxy;

            accessor.InstanceProperty = 1;

            Assert.AreEqual(accessor.InstanceProperty, instance.InstanceProperty);
        }
Example #6
0
        /// <summary>
        /// Decoration request
        /// </summary>
        /// <param name="context">Context info</param>
        /// <remarks>do not have to decorate, but may if it wants to. sorta..</remarks>
        public void Decorate(DecoratorContext context)
        {
            if (!CanDecorate(context))
            {
                return;
            }

            var options = new ProxyGenerationOptions();

            var services = context.Services;

            if (IgnoreClassAsService && services.Length > 1)
            {
                services = services.Where(x => !x.IsClass).ToArray();
            }

            var generator = new ProxyGenerator();

            if (services.Any(x => x.IsClass))
            {
                if (services.Length > 1)
                {
                    throw new InvalidOperationException(
                              "A class that register itself as a service may not also be registered with interfaces. See the remarks in the IgnoreClassAsService property.");
                }

                var clazz = context.Services.Single(x => x.IsClass);
                context.Instance = generator.CreateClassProxyWithTarget(clazz, context.Instance,
                                                                        CreateInterceptor(context));
            }
            else
            {
                var others = services.Where(x => x.IsInterface).Skip(1);
                var first  = services.First();
                context.Instance = generator.CreateInterfaceProxyWithTarget
                                       (first, others.ToArray(), context.Instance,
                                       CreateInterceptor(context));
            }
        }
Example #7
0
        /// <summary>
        /// Creates a proxy for the given object based on the type specified.
        ///
        /// If the type given is:
        ///   - a class, then a class proxy is used
        ///   - an interface, then an interface proxy is used
        ///
        /// Will assign IDecorator.Self=proxy on |obj| if possible.
        /// </summary>
        /// <param name="type">The proxy type to create.</param>
        /// <param name="obj">The object to decorate.  Can be null.</param>
        /// <returns>A decorator proxy of the requested type, or null if |obj| is null.</returns>
        /// <exception cref="ArgumentException">
        /// Thrown if unable to decorate |obj| for any reason.  Some examples include:
        ///   - type is not a class or interface
        ///   - |type| is not assignable from obj.GetType()
        /// </exception>
        public object Decorate(Type type, object obj)
        {
            if (obj == null)
            {
                return(obj);
            }

            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            if (!type.IsAssignableFrom(obj.GetType()))
            {
                throw new ArgumentException("Decorate should only be used on " +
                                            $"classes or interfaces. It was called on type '{type.FullName}'.");
            }

            object proxy = null;

            if (type.IsClass)
            {
                proxy = proxyGenerator.CreateClassProxyWithTarget(type, obj, options, aspects);
            }
            else if (type.IsInterface)
            {
                proxy = proxyGenerator.CreateInterfaceProxyWithTarget(
                    type, obj, options, aspects);
            }
            else
            {
                throw new ArgumentException("Decorate should only be used on " +
                                            $"classes or interfaces. It was called on type '{type.FullName}'.");
            }
            DecoratorSelfUtil.TrySetSelf(obj, proxy);
            return(proxy);
        }
Example #8
0
 public TProxy GenerateProxyFrom <TProxy>(TProxy target) where TProxy : class, IChangeTrackable
 {
     return(_proxy.CreateClassProxyWithTarget(target, new ChangeTrackingInterceptor()));
 }
Example #9
0
        public void Select_Interceptors_For_Methods_For_ClassProxy_With_Target()
        {
            var generator = new ProxyGenerator();
            var options   = new ProxyGeneratorOptions();

            options.InterceptorSelector = new IS1();
            var target = new TypeIS1();
            var proxy  = generator.CreateClassProxyWithTarget <TypeIS1>(target, options, new IntGetForIS1(), new IntSetForIS1(), new IntMethForIS1(), new IntAddForIS1(), new IntRemoveForIS1());

            Assert.AreEqual(false, IntGetForIS1.IsCalled);
            Assert.AreEqual(false, IntSetForIS1.IsCalled);
            Assert.AreEqual(false, IntMethForIS1.IsCalled);
            Assert.AreEqual(0, TypeIS1.States.Count);

            // set
            proxy.MyProperty = "New value";

            Assert.AreEqual(false, IntGetForIS1.IsCalled);
            Assert.AreEqual(true, IntSetForIS1.IsCalled);
            Assert.AreEqual(false, IntMethForIS1.IsCalled);
            Assert.AreEqual(false, IntAddForIS1.IsCalled);
            Assert.AreEqual(false, IntRemoveForIS1.IsCalled);
            Assert.AreEqual(1, TypeIS1.States.Count);
            Assert.AreEqual(StateTypes.Set_Called, TypeIS1.States[0]);

            IntSetForIS1.IsCalled    = false;
            IntGetForIS1.IsCalled    = false;
            IntMethForIS1.IsCalled   = false;
            IntAddForIS1.IsCalled    = false;
            IntRemoveForIS1.IsCalled = false;
            TypeIS1.States.Clear();

            // get
            var p = proxy.MyProperty;

            Assert.AreEqual(true, IntGetForIS1.IsCalled);
            Assert.AreEqual(false, IntSetForIS1.IsCalled);
            Assert.AreEqual(false, IntMethForIS1.IsCalled);
            Assert.AreEqual(false, IntAddForIS1.IsCalled);
            Assert.AreEqual(false, IntRemoveForIS1.IsCalled);
            Assert.AreEqual("New value", p);
            Assert.AreEqual(1, TypeIS1.States.Count);
            Assert.AreEqual(StateTypes.Get_Called, TypeIS1.States[0]);

            IntSetForIS1.IsCalled    = false;
            IntGetForIS1.IsCalled    = false;
            IntMethForIS1.IsCalled   = false;
            IntAddForIS1.IsCalled    = false;
            IntRemoveForIS1.IsCalled = false;
            TypeIS1.States.Clear();

            // method
            proxy.Method();

            Assert.AreEqual(false, IntGetForIS1.IsCalled);
            Assert.AreEqual(false, IntSetForIS1.IsCalled);
            Assert.AreEqual(true, IntMethForIS1.IsCalled);
            Assert.AreEqual(false, IntAddForIS1.IsCalled);
            Assert.AreEqual(false, IntRemoveForIS1.IsCalled);
            Assert.AreEqual(1, TypeIS1.States.Count);
            Assert.AreEqual(StateTypes.Class_Method, TypeIS1.States[0]);

            IntSetForIS1.IsCalled    = false;
            IntGetForIS1.IsCalled    = false;
            IntMethForIS1.IsCalled   = false;
            IntAddForIS1.IsCalled    = false;
            IntRemoveForIS1.IsCalled = false;
            TypeIS1.States.Clear();

            // method with parameter

            proxy.Method("My paramete");

            Assert.AreEqual(false, IntGetForIS1.IsCalled);
            Assert.AreEqual(false, IntSetForIS1.IsCalled);
            Assert.AreEqual(true, IntMethForIS1.IsCalled);
            Assert.AreEqual(false, IntAddForIS1.IsCalled);
            Assert.AreEqual(false, IntRemoveForIS1.IsCalled);
            Assert.AreEqual(1, TypeIS1.States.Count);
            Assert.AreEqual(StateTypes.Class_Method_2, TypeIS1.States[0]);

            IntSetForIS1.IsCalled    = false;
            IntGetForIS1.IsCalled    = false;
            IntMethForIS1.IsCalled   = false;
            IntAddForIS1.IsCalled    = false;
            IntRemoveForIS1.IsCalled = false;
            TypeIS1.States.Clear();

            EventHandler ev = null;

            ev = (s, e) => { };

            proxy.MyEvent += ev;

            Assert.AreEqual(false, IntGetForIS1.IsCalled);
            Assert.AreEqual(false, IntSetForIS1.IsCalled);
            Assert.AreEqual(false, IntMethForIS1.IsCalled);
            Assert.AreEqual(true, IntAddForIS1.IsCalled);
            Assert.AreEqual(false, IntRemoveForIS1.IsCalled);
            Assert.AreEqual(1, TypeIS1.States.Count);
            Assert.AreEqual(StateTypes.AddEvent_IsCalled, TypeIS1.States[0]);

            IntSetForIS1.IsCalled    = false;
            IntGetForIS1.IsCalled    = false;
            IntMethForIS1.IsCalled   = false;
            IntAddForIS1.IsCalled    = false;
            IntRemoveForIS1.IsCalled = false;
            TypeIS1.States.Clear();

            proxy.MyEvent -= ev;

            Assert.AreEqual(false, IntGetForIS1.IsCalled);
            Assert.AreEqual(false, IntSetForIS1.IsCalled);
            Assert.AreEqual(false, IntMethForIS1.IsCalled);
            Assert.AreEqual(false, IntAddForIS1.IsCalled);
            Assert.AreEqual(true, IntRemoveForIS1.IsCalled);
            Assert.AreEqual(1, TypeIS1.States.Count);
            Assert.AreEqual(StateTypes.RemoveEvent_IsCalled, TypeIS1.States[0]);
        }
Example #10
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="TClass"></typeparam>
        /// <param name="class"></param>
        /// <param name="interceptors"></param>
        /// <returns></returns>
        public static TClass GenerateClassProxy <TClass>(this TClass @class, params IInterceptor[] interceptors) where TClass : class
        {
            var proxyGenerator = new ProxyGenerator();

            return(proxyGenerator.CreateClassProxyWithTarget(@class, interceptors));
        }
Example #11
0
 /// <summary>
 /// Gets the class proxy.
 /// </summary>
 /// <typeparam name="TClass">The type of the class.</typeparam>
 /// <param name="target">The target.</param>
 /// <param name="proxyGenerationHook">The proxy generation hook.</param>
 /// <param name="interceptors">The interceptors.</param>
 /// <returns>
 /// A proxy from the class with the type <see cref="TClass"/>.
 /// </returns>
 public static TClass GetClassProxy <TClass>(TClass target, IProxyGenerationHook proxyGenerationHook, params IInterceptor[] interceptors) where TClass : class
 {
     return((TClass)proxyGenerator.CreateClassProxyWithTarget(typeof(TClass), target, new ProxyGenerationOptions(proxyGenerationHook), interceptors));
 }
Example #12
0
 public T MakeObject()
 {
     return(ProxyGenerator.CreateClassProxyWithTarget <T>(_object, new ClassInterceptor()));
 }
Example #13
0
 public static object NeverNull(object source, Type type)
 {
     return(_generator.CreateClassProxyWithTarget(type, new[] { typeof(IUnBoxProxy) }, source,
                                                  new NeverNullInterceptor(source)));
 }
Example #14
0
 public TService CreateClassProxy <TService>(TService implementationInstance, IInterceptronInterceptor[] interceptors) where TService : class
 {
     return(generator.CreateClassProxyWithTarget(implementationInstance, DynamicProxyGeneratorHelper.ToDynamicProxyInterceptors(interceptors)));
 }
Example #15
0
        /// <summary>Intercepts the specified invocation.</summary>
        /// <param name="invocation">The invocation.</param>
        /// <autogeneratedoc />
        /// TODO Edit XML Comment Template for Intercept
        public override void Intercept(IInvocation invocation)
        {
            Interlocked.Increment(ref _callDepth);
            var x   = _stack.Any( ) ? _stack.Peek( ) : null;
            var myX = new StackInfo( );

            _stack.Push(myX);
            var writeLine = WriteLine;

            if (x != null)
            {
                x.Written = true;
                writeLine("");
            }


            var formatted = FormatInvocation(invocation, "");
            var a         = new InvocationEventArgs {
                Formatted = formatted
            };

            DumpInvocation(invocation, _callDepth);
            invocation.Proceed( );
            try
            {
                DumpReturnValue(invocation, _callDepth, !myX.Written);
                if (ProxyGenerator != null &&
                    invocation.ReturnValue != null &&
                    !invocation.ReturnValue.GetType( ).IsSealed &&
                    !(invocation.ReturnValue is IProxyTargetAccessor))
                {
                    var r = invocation.ReturnValue;
                    if (r is XamlType typ)
                    {
                        var invoker =
                            ( XamlTypeInvoker )ProxyGenerator.CreateClassProxyWithTarget(
                                typeof(
                                    XamlTypeInvoker
                                    )
                                , typ
                                .Invoker
                                , new[]
                        {
                            r
                        }
                                , this
                                );
                        object[] args = { typ.UnderlyingType, typ.SchemaContext, invoker };


                        invocation.ReturnValue =
                            ProxyGenerator.CreateClassProxyWithTarget(
                                r.GetType( )
                                , r
                                , args
                                , this
                                );
                    }
                    else if (r.GetType( ).IsGenericType &&
                             r.GetType( ).GetGenericTypeDefinition( )
                             == typeof(XamlValueConverter <object>)
                             .GetGenericTypeDefinition( ))
                    {
                        object[] args = null;
                        switch (r)
                        {
                        case XamlValueConverter <ValueSerializer> q: args = new object[] { q.ConverterType, q.TargetType, q.Name };
                            break;

                        case XamlValueConverter <TypeConverter> z:   args = new object[] { z.ConverterType, z.TargetType, z.Name };
                            break;
                        }

                        if (args != null)
                        {
                            invocation.ReturnValue =
                                ProxyGenerator.CreateClassProxyWithTarget(
                                    r.GetType( )
                                    , r
                                    , args
                                    , this
                                    );
                        }
                    }
                    else if (r.GetType( ).IsGenericType &&
                             r.GetType( ).GetGenericTypeDefinition( )
                             == typeof(ReadOnlyCollection <object>)
                             .GetGenericTypeDefinition( ))
                    {
                        var propInfo = r.GetType( )
                                       .GetField(
                            "list"
                            , BindingFlags.NonPublic | BindingFlags.Instance
                            );
                        if (propInfo != null)
                        {
                            var args = new[] { propInfo.GetValue(r) };
                            invocation.ReturnValue =
                                ProxyGenerator.CreateClassProxyWithTarget(
                                    r.GetType( )
                                    , r
                                    , args
                                    , this
                                    );
                        }
                    }
                    else
                    {
                        switch (r)
                        {
                        case XamlDirective d:
                        {
                            object[] args =
                            {
                                d.GetXamlNamespaces( ), d.Name, d.Type, d.TypeConverter
                                ,                       d.AllowedLocation
                            };

                            invocation.ReturnValue =
                                ProxyGenerator.CreateClassProxyWithTarget(
                                    r.GetType( )
                                    , r
                                    , args
                                    , this
                                    );
                            break;
                        }

                        case NamespaceDeclaration ns:
                            invocation.ReturnValue =
                                ProxyGenerator.CreateClassProxyWithTarget(
                                    r.GetType( )
                                    , r
                                    , new object[]
                            {
                                ns.Namespace, ns.Prefix
                            }
                                    , this
                                    );
                            break;

                        default:
                            try
                            {
                                invocation.ReturnValue =
                                    ProxyGenerator.CreateClassProxyWithTarget(
                                        r.GetType( )
                                        , r
                                        , this
                                        );
                            }
                            catch (InvalidProxyConstructorArgumentsException)
                            {
                                writeLine("Constructors for ⮜" + FormatTyp(r.GetType( )) + "⮞");
                                foreach (var constructorInfo in r.GetType( ).GetConstructors( ))
                                {
                                    writeLine(
                                        FormatTyp(constructorInfo.DeclaringType)
                                        + " ( "
                                        + string.Join(
                                            " , "
                                            , constructorInfo
                                            .GetParameters( )
                                            .Select(
                                                (info, i)
                                                => FormatTyp(
                                                    info
                                                    .ParameterType
                                                    )
                                                + " "
                                                + info.Name
                                                + (info.HasDefaultValue
                                                                                         ? " = "
                                                   + info
                                                   .DefaultValue
                                                                                         : "")
                                                )
                                            )
                                        );
                                }
                            }

                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                writeLine("--Exception--");
                writeLine(ex.ToString( ));      //.GetType ( ) ) ;
                //Console.WriteLine ( ex.Message ) ;
                writeLine("--End Exception--");
            }
            finally
            {
                _stack.Pop( );
                Interlocked.Decrement(ref _callDepth);
            }
        }
Example #16
0
File: Model.cs Project: topazdb/api
 public static T create()
 {
     return((T)generator.CreateClassProxyWithTarget(typeof(T), new T(), new Interceptor()));
 }
Example #17
0
 protected override TProxy InvokeCastleProxyGenerator <TProxy>(ProxyGenerator proxyGenerator, TProxy target, IInterceptor interceptor)
 {
     return(proxyGenerator.CreateClassProxyWithTarget <TProxy>(target, interceptor));
 }
Example #18
0
        protected internal virtual object InstrumentClient(Type clientType, object client, IEnumerable <IInterceptor> preInterceptors)
        {
            if (client is IProxyTargetAccessor)
            {
                // Already instrumented
                return(client);
            }

            lock (s_clientValidation)
            {
                if (!s_clientValidation.TryGetValue(clientType, out var validationException))
                {
                    foreach (MethodInfo methodInfo in clientType.GetMethods(BindingFlags.Instance | BindingFlags.Public))
                    {
                        if (methodInfo.Name.EndsWith("Async") && !methodInfo.IsVirtual)
                        {
                            validationException = new InvalidOperationException($"Client type contains public non-virtual async method {methodInfo.Name}");

                            break;
                        }

                        if (methodInfo.Name.EndsWith("Client") &&
                            methodInfo.Name.StartsWith("Get") &&
                            !methodInfo.IsVirtual)
                        {
                            validationException = new InvalidOperationException($"Client type contains public non-virtual Get*Client method {methodInfo.Name}");

                            break;
                        }
                    }

                    s_clientValidation[clientType] = validationException;
                }

                if (validationException != null)
                {
                    throw validationException;
                }
            }

            List <IInterceptor> interceptors = new List <IInterceptor>();

            if (preInterceptors != null)
            {
                interceptors.AddRange(preInterceptors);
            }

            interceptors.Add(new GetOriginalInterceptor(client));

            if (TestDiagnostics)
            {
                interceptors.Add(s_diagnosticScopeValidatingInterceptor);
            }

            interceptors.Add(new InstrumentResultInterceptor(this));

            // Ignore the async method interceptor entirely if we're running a
            // a SyncOnly test
            TestContext.TestAdapter test = TestContext.CurrentContext.Test;
            bool?isSyncOnly = (bool?)test.Properties.Get(ClientTestFixtureAttribute.SyncOnlyKey);

            if (isSyncOnly != true)
            {
                interceptors.Add(IsAsync ? s_avoidSyncInterceptor : s_useSyncInterceptor);
            }

            return(ProxyGenerator.CreateClassProxyWithTarget(
                       clientType,
                       new[] { typeof(IInstrumented) },
                       client,
                       interceptors.ToArray()));
        }
Example #19
0
        static int DoInstall(string game, string filename, string installationPath, string profilePath, string gamePath,
                             List <string> additionalSearchPaths, string seVersion, ref string errorString)
        {
            if (game == null)
            {
                errorString = "no game specified";
                return(1);
            }
            if (filename == null)
            {
                errorString = "no file specified";
                return(1);
            }
            if (profilePath == null)
            {
                errorString = "no profile path specified";
                return(1);
            }
            if (gamePath == null)
            {
                errorString = "no game path specified";
                return(1);
            }
            try
            {
                EnvironmentInfo environmentInfo = new EnvironmentInfo(Properties.Settings.Default);

                string   exeLocation = Assembly.GetExecutingAssembly().Location;
                string   exePath     = System.IO.Path.GetDirectoryName(exeLocation);
                string[] gameModes   = Directory.GetFiles(Path.Combine(exePath, "GameModes"), String.Format("{0}.dll", game));
                if (gameModes.Count() == 0)
                {
                    errorString = "unknown game";
                    return(1);
                }

                Assembly         gameAssembly    = Assembly.LoadFrom(gameModes[0]);
                IGameModeFactory gameModeFactory = null;
                Type[]           exportedTypes   = gameAssembly.GetExportedTypes();
                foreach (Type type in exportedTypes)
                {
                    if (typeof(IGameModeFactory).IsAssignableFrom(type) && !type.IsAbstract)
                    {
                        ConstructorInfo constructor = type.GetConstructor(new Type[] { typeof(EnvironmentInfo) });
                        gameModeFactory = (IGameModeFactory)constructor.Invoke(new Object[] { environmentInfo });
                    }
                }
                if (gameModeFactory == null)
                {
                    errorString = "invalid game";
                    return(1);
                }

                string str7zPath = Path.Combine(environmentInfo.ProgrammeInfoDirectory, environmentInfo.Is64BitProcess ? "7z-64bit.dll" : "7z-32bit.dll");
                SevenZipCompressor.SetLibraryPath(str7zPath);

                FileUtil fileUtil = new NexusFileUtil(environmentInfo);

                environmentInfo.Settings.InstallationPaths[gameModeFactory.GameModeDescriptor.ModeId] = installationPath;
                environmentInfo.Settings.ModFolder[gameModeFactory.GameModeDescriptor.ModeId]         = installationPath;
                environmentInfo.Settings.InstallInfoFolder[gameModeFactory.GameModeDescriptor.ModeId] = environmentInfo.TemporaryPath;
                if (environmentInfo.Settings.DelayedSettings[gameModeFactory.GameModeDescriptor.ModeId] == null)
                {
                    environmentInfo.Settings.DelayedSettings[gameModeFactory.GameModeDescriptor.ModeId] = new KeyedSettings <string>();
                }
                if (environmentInfo.Settings.DelayedSettings["ALL"] == null)
                {
                    environmentInfo.Settings.DelayedSettings["ALL"] = new KeyedSettings <string>();
                }

                ViewMessage warning = null;

                IGameMode gameMode = gameModeFactory.BuildGameMode(fileUtil, out warning);

                // use a proxy so we can intercept accesses to the IGameMode interface. This allows us to make the additional search paths accessible from
                // the sandbox and feed in the script extender version even though the nmm lib won't find it.
                // This is a massive hack and there is an issue: nmm tries to look up the location of the assembly (for whatever reason) and the proxy
                // generated here is in a dynamic assembly and thus doesn't have a location. We will therefore feed the proxy only to the script executor
                // and hope for the best
                ProxyGenerator      generator   = new ProxyGenerator();
                GameModeInterceptor interceptor = new GameModeInterceptor(additionalSearchPaths, seVersion != null ? new Version(seVersion) : null);

                IGameMode gameModeProxied = (IGameMode)generator.CreateClassProxyWithTarget(gameMode.GetType(),
                                                                                            gameMode,
                                                                                            new object[] { environmentInfo, fileUtil },
                                                                                            new IInterceptor[] { interceptor });

                IModCacheManager cacheManager = new NexusModCacheManager(environmentInfo.TemporaryPath, gameMode.GameModeEnvironmentInfo.ModDirectory, fileUtil);

                IScriptTypeRegistry scriptTypeRegistry = ScriptTypeRegistry.DiscoverScriptTypes(Path.Combine(Path.GetDirectoryName(exeLocation), "ScriptTypes"), gameMode);
                if (scriptTypeRegistry.Types.Count == 0)
                {
                    errorString = "No script types were found.";
                    return(2);
                }

                IModFormatRegistry formatRegistry = ModFormatRegistry.DiscoverFormats(cacheManager, scriptTypeRegistry, Path.Combine(Path.GetDirectoryName(exeLocation), "ModFormats"));
                if (formatRegistry.Formats.Count == 0)
                {
                    errorString = "No formats were found.";
                    return(2);
                }

                // we install the mod from the temporary path. Unfortunately this requires the archive to be copied, otherwise the sandbox will
                // prevent the installer script from accessing the archive in its original location
                string fileNameTemporary = Path.Combine(environmentInfo.TemporaryPath, Path.GetFileName(filename));
                File.Copy(filename, fileNameTemporary);
                IMod mod = CreateMod(fileNameTemporary, formatRegistry, gameMode);
                if (mod == null)
                {
                    errorString = "failed to initialize mod";
                    return(3);
                }

                System.IO.File.WriteAllText(installationPath + "/__installInfo.txt", mod.ModName + "\n" + mod.HumanReadableVersion + "\n" + mod.Id);

                if (mod.HasInstallScript)
                {
                    DummyDataFileUtilFactory dummyFactory = null;
                    IDataFileUtil            dataFileUtility;
                    Logger.Info("Detected C# script that relies on files in the actual data folder");

                    string modlistFile = Path.Combine(profilePath, "modlist.txt");
                    // ASSUMED mods path is the parent directory of the gameMode.InstallationPath
                    string modsPath = Directory.GetParent(gameMode.InstallationPath).FullName;
                    // Prepare dummy data directory
                    dummyFactory    = new DummyDataFileUtilFactory(gameMode.GameModeEnvironmentInfo.InstallationPath, modlistFile, modsPath, gamePath, additionalSearchPaths);
                    dataFileUtility = dummyFactory.CreateDummyDataFileUtil();

                    TxFileManager  fileManager     = new TxFileManager();
                    IInstallLog    installLog      = new DummyInstallLog();
                    IIniInstaller  iniIniInstaller = new IniInstaller(mod, installLog, fileManager, delegate { return(OverwriteResult.No); });
                    IPluginManager pluginManager   = new DummyPluginManager(Path.Combine(profilePath, "plugins.txt"), gameMode, mod);
                    IGameSpecificValueInstaller gameSpecificValueInstaller = gameMode.GetGameSpecificValueInstaller(mod, installLog, fileManager, new NexusFileUtil(environmentInfo), delegate { return(OverwriteResult.No); });
                    IModFileInstaller           fileInstaller = new ModFileInstaller(gameMode.GameModeEnvironmentInfo, mod, installLog, pluginManager, dataFileUtility, fileManager, delegate { return(OverwriteResult.No); }, false);
                    InstallerGroup  installers = new InstallerGroup(dataFileUtility, fileInstaller, iniIniInstaller, gameSpecificValueInstaller, pluginManager);
                    IScriptExecutor executor   = mod.InstallScript.Type.CreateExecutor(mod, gameModeProxied, environmentInfo, installers, SynchronizationContext.Current);
                    // read-only transactions are waaaay faster, especially for solid archives) because the extractor isn't recreated for every extraction (why exactly would it be otherwise?)
                    mod.BeginReadOnlyTransaction(fileUtil);
                    // run the script in a second thread and start the main loop in the main thread to ensure we can handle message boxes and the like
                    ScriptRunner runner = new ScriptRunner(executor, mod.InstallScript);

                    runner.Execute();
                    runner.TaskEnded += delegate
                    {
                        iniIniInstaller.FinalizeInstall();
                        gameSpecificValueInstaller.FinalizeInstall();
                        mod.EndReadOnlyTransaction();

                        Application.Exit();
                    };

                    Application.Run();
                    switch (runner.Status)
                    {
                    case BackgroundTasks.TaskStatus.Cancelled: return(11);

                    case BackgroundTasks.TaskStatus.Error: return(6);

                    case BackgroundTasks.TaskStatus.Incomplete: return(10);

                    default: return(0);
                    }
                }
                else
                {
                    errorString = "no install script";
                    return(4);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("exception: " + e.Message);
                MessageBox.Show(e.Message, "Installation failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(5);
            }
        }
 /// <summary>
 ///     Initializes a new instance of the <see cref="T:System.Object" /> class.
 /// </summary>
 public InterfaceWrapper(T instance, MappingRules <T> rules)
 {
     Target = typeof(T).IsInterface ? Generator.CreateInterfaceProxyWithTarget(instance, new Interceptor(rules, this, instance)) : Generator.CreateClassProxyWithTarget(instance, new Interceptor(rules, this, instance));
 }
Example #21
0
 static TContextType CreateProxiedContext(TContextType context)
 {
     return(Generator.CreateClassProxyWithTarget(context,
                                                 new ScenarioContextInterceptor()));
 }
Example #22
0
        public void Intercept(IInvocation invocation)
        {
            bool modifiedAskToWait = false;

            if (IsLro(invocation.Method.ReturnType))
            {
                WaitUntil current = (WaitUntil)invocation.Arguments[0];
                if (current == WaitUntil.Completed)
                {
                    modifiedAskToWait       = true;
                    invocation.Arguments[0] = WaitUntil.Started;
                }
            }

            invocation.Proceed();

            if (modifiedAskToWait)
            {
                if (IsTaskFaulted(invocation.ReturnValue))
                {
                    return;
                }
                object lro = GetResultFromTask(invocation.ReturnValue);
                if (lro.GetType().IsSubclassOf(typeof(Operation)))
                {
                    _ = OperationInterceptor.InvokeWaitForCompletionResponse(lro as Operation, (CancellationToken)invocation.Arguments.Last());
                }
                else
                {
                    _ = OperationInterceptor.InvokeWaitForCompletion(lro, lro.GetType(), (CancellationToken)invocation.Arguments.Last());
                }
                return;
            }

            var result = invocation.ReturnValue;

            if (result == null)
            {
                return;
            }

            var type = result.GetType();

            if (IsTaskType(type))
            {
                if (IsTaskFaulted(result))
                {
                    return;
                }

                var taskResultType = type.GetGenericArguments()[0];
                if (taskResultType.Name.StartsWith("Response") || InheritsFromArmResource(taskResultType))
                {
                    var taskResult         = GetResultFromTask(result);
                    var instrumentedResult = _testBase.InstrumentClient(taskResultType, taskResult, new IInterceptor[] { new ManagementInterceptor(_testBase) });
                    invocation.ReturnValue = type.Name.StartsWith("ValueTask")
                        ? GetValueFromValueTask(taskResultType, instrumentedResult)
                        : GetValueFromOther(taskResultType, instrumentedResult);
                }
            }
            else if (invocation.Method.Name.EndsWith("Value") && InheritsFromArmResource(type))
            {
                invocation.ReturnValue = _testBase.InstrumentClient(type, result, new IInterceptor[] { new ManagementInterceptor(_testBase) });
            }
            else if (type.BaseType.Name.StartsWith("AsyncPageable"))
            {
                invocation.ReturnValue = s_proxyGenerator.CreateClassProxyWithTarget(type, result, new IInterceptor[] { new ManagementInterceptor(_testBase) });
            }
            else if (invocation.Method.Name.StartsWith("Get") &&
                     invocation.Method.Name.EndsWith("Enumerator") &&
                     type.IsGenericType &&
                     InheritsFromArmResource(type.GetGenericArguments().First()))
            {
                var wrapperType = typeof(AsyncPageableInterceptor <>);
                var genericType = wrapperType.MakeGenericType(type.GetGenericArguments()[0]);
                var ctor        = genericType.GetConstructor(new Type[] { typeof(ClientTestBase), result.GetType() });
                invocation.ReturnValue = ctor.Invoke(new object[] { _testBase, result });
            }
        }
Example #23
0
        public object Intercept(object objectToIntercept)
        {
            var interceptor = CreateInterceptor(objectToIntercept);

            return(Generator.CreateClassProxyWithTarget(objectToIntercept.GetType(), objectToIntercept, ProxyGenerationOptions.Default, interceptor));
        }
Example #24
0
        public void Intercept(IInvocation invocation)
        {
            invocation.Proceed();

            var result = invocation.ReturnValue;

            if (result == null)
            {
                return;
            }

            var type = result.GetType();

            if (type.Name.StartsWith("ValueTask") ||
                type.Name.StartsWith("Task") ||
                type.Name.StartsWith("AsyncStateMachineBox")) //in .net 5 the type is not task here
            {
                if ((bool)type.GetProperty("IsFaulted").GetValue(result))
                {
                    return;
                }

                var taskResultType = type.GetGenericArguments()[0];
                if (taskResultType.Name.StartsWith("Response"))
                {
                    try
                    {
                        var taskResult         = result.GetType().GetProperty("Result").GetValue(result);
                        var instrumentedResult = _testBase.InstrumentClient(taskResultType, taskResult, new IInterceptor[] { new ManagementInterceptor(_testBase) });
                        invocation.ReturnValue = type.Name.StartsWith("ValueTask")
                            ? GetValueFromValueTask(taskResultType, instrumentedResult)
                            : GetValueFromOther(taskResultType, instrumentedResult);
                    }
                    catch (TargetInvocationException e)
                    {
                        if (e.InnerException is AggregateException aggException)
                        {
                            throw aggException.InnerExceptions.First();
                        }
                        else
                        {
                            throw e.InnerException;
                        }
                    }
                }
            }
            else if (invocation.Method.Name.EndsWith("Value") && type.BaseType.Name.EndsWith("Operations"))
            {
                invocation.ReturnValue = _testBase.InstrumentClient(type, result, new IInterceptor[] { new ManagementInterceptor(_testBase) });
            }
            else if (type.BaseType.Name.StartsWith("AsyncPageable"))
            {
                invocation.ReturnValue = s_proxyGenerator.CreateClassProxyWithTarget(type, result, new IInterceptor[] { new ManagementInterceptor(_testBase) });
            }
            else if (invocation.Method.Name.StartsWith("Get") &&
                     invocation.Method.Name.EndsWith("Enumerator") &&
                     type.IsGenericType &&
                     InheritsFromOperationBase(type.GetGenericArguments().First()))
            {
                var wrapperType = typeof(AsyncPageableInterceptor <>);
                var genericType = wrapperType.MakeGenericType(type.GetGenericArguments()[0]);
                var ctor        = genericType.GetConstructor(new Type[] { typeof(ClientTestBase), result.GetType() });
                invocation.ReturnValue = ctor.Invoke(new object[] { _testBase, result });
            }
        }
        //This is how we get ActualClass items that are wrapped in the Dynamic Proxy
        public static ActualClass getActualClassInstance()
        {
            ActualClass instance = new ActualClass();

            return(pg.CreateClassProxyWithTarget <ActualClass>(instance, interceptor));
        }