Example #1
0
        public void Inject()
        {
            var context = _yukkuriContext;

            var ass = AppDomain.CurrentDomain.GetAssemblies()
                      .SingleOrDefault(assembly => assembly.GetName().Name == "ACT.TTSYukkuri.Core");

            if (context == null || context.YukkuriAssembly != ass)
            {
                context                  = new YukkuriContext(injector._plugin, ass);
                _yukkuriContext          = context;
                _originalYukkuriInstance = null;
            }

            lock (context.SpeechControllerLockObject)
            {
                var instance = context.SpeechControllerInstanceObject;
                if (instance == null || !(instance is IActLikeProxyInitialize))
                {
                    _originalYukkuriInstance = instance;
                    var myInterface = Impromptu.DynamicActLike(this, context.ISpeechControllerType);
                    _yukkuriContext.SpeechControllerInstanceObject = myInterface;
                    injector._plugin.Controller.NotifyLogMessageAppend(false, "TTSYukkuri injected!");
                }
            }
        }
Example #2
0
        private static object GetMSpecRunListener(SessionResults sessionResults)
        {
            var specificationRunListenerType = MSpecTypes.Types.First(x => x.Name == "ISpecificationRunListener");

            return(Impromptu.DynamicActLike(GilesMSpecRunListener.GetAnonymousListener(sessionResults, new List <TestResult>(), new ResultFormatterFactory()),
                                            specificationRunListenerType));
        }
        public void RazorEngineService_ActLikeTest()
        {
            dynamic m = new ExpandoObject();

            m.Test = new Func <string>(() => "mytest");
            m.More = new Func <string>(() => "mymore");
            dynamic _m = Impromptu.DynamicActLike(m, typeof(IMyInterface));

            Assert.AreEqual("mytest", _m.Test());
            var __m = (IMyInterface)_m;

            Assert.AreEqual("mytest", __m.Test());


            dynamic o  = new MyClass();
            dynamic _o = Impromptu.DynamicActLike(o, typeof(IMyInterface));

            Assert.AreEqual("test", _o.Test());
            var __o = (IMyInterface)_o;

            Assert.AreEqual("test", __o.Test());

            Assert.AreEqual("more", _o.More());
            Assert.AreEqual("mymore", _m.More());
        }
Example #4
0
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            Type tType;

            Activate tBuildType;

            if (!_buildType.TryGetValue(binder.Name, out tBuildType))
            {
                tBuildType = null;
            }

            if (tBuildType == null && !_buildType.TryGetValue("Object", out tBuildType))
            {
                tBuildType = null;
            }

            result = InvokeHelper(binder.CallInfo, args, tBuildType);
            if (TryTypeForName(binder.Name, out tType))
            {
                if (tType.IsInterface && result != null && !tType.IsAssignableFrom(result.GetType()))
                {
                    result = Impromptu.DynamicActLike(result, tType);
                }
            }
            return(true);
        }
Example #5
0
        /// <summary>
        /// Tries to convert the current instance.
        /// </summary>
        /// <param name="binder">The binder.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        public override bool TryConvert(System.Dynamic.ConvertBinder binder, out object result)
        {
            var targetType = binder.Type;
            var isExplicit = binder.Explicit;

            result = null;
            object tempResult;

            if (RemoteInvoke(new Invocation(InvocationKind.Convert, (isExplicit ? "op_Explicit" : "op_Implicit"), targetType, isExplicit), out tempResult))
            {
                if (tempResult.GetType() == targetType)
                { // Not wrapped, so most likely a primitive?
                    result = tempResult;
                }
                else
                {
                    if (targetType.IsInterface)
                    {
                        result = Impromptu.DynamicActLike(tempResult, targetType);
                    }
                    else
                    {
                        // We can not present ourself as any class so we just try keep beeing dynamic.
                        result = tempResult;
                    }
                }
                return(true);
            }
            return(false);
        }
Example #6
0
        public async Task <object> ResolveCustomersServiceAsync(Type serviceType)
        {
            var type  = Type.GetType($"WasmReload.Shared.Interfaces.{serviceType.Name}, WasmReload.Shared");
            var props = type.GetMethods();

            var expando = new ExpandoObject() as IDictionary <string, object>;

            foreach (var prop in props)
            {
                var parameters = prop.GetParameters();
                if (parameters.Length == 0)
                {
                    expando.Add(prop.Name, Return <Task <dynamic> > .Arguments(async() => await InvokeRemoteMethodAsync(prop.Name, 0)));
                }
                if (parameters.Length == 1)
                {
                    //expando.Add(prop.Name, Return<Task<Customer>>.Arguments<dynamic>(async (p1) => await InvokeRemoteMethodAsync(prop.Name, 1, p1)));
                    expando.Add(prop.Name, Return <Task <dynamic> > .Arguments <dynamic>(async(p1) => await InvokeRemoteMethodAsync(prop.Name, 1, p1)));
                }
                if (parameters.Length == 2)
                {
                    expando.Add(prop.Name, Return <Task <dynamic> > .Arguments <dynamic, dynamic>(async(p1, p2) => await InvokeRemoteMethodAsync(prop.Name, 2, p1, p2)));
                }
                if (parameters.Length == 3)
                {
                    expando.Add(prop.Name, Return <Task <dynamic> > .Arguments <dynamic, dynamic, dynamic>(async(p1, p2, p3) => await InvokeRemoteMethodAsync(prop.Name, 3, p1, p2, p3)));
                }
            }

            dynamic myInterface = Impromptu.DynamicActLike(expando, type);

            InstanceId = await client.GetStringAsync($"Services?Service={serviceType.Name.TrimStart('I')}&InstanceId={Guid.NewGuid()}");

            return(myInterface);
        }
Example #7
0
        /// <summary>
        /// Casts this object to an instance of the demanded type as long as it is an interface
        /// </summary>
        ///// <param name="targetType">the target interface type</param>
        /// <returns>the representation of the given interface wrapping this instance</returns>
        public object Cast(Type targetType)
        {
            if (targetType.IsInterface)
            {
                return(Impromptu.DynamicActLike(this, targetType));
            }

            return(null);
        }
Example #8
0
        /// <summary>Stellt die Implementierung für Typkonvertierungsvorgänge bereit.Von der <see cref="T:System.Dynamic.DynamicObject" />-Klasse abgeleitete Klassen können diese Methode überschreiben, um dynamisches Verhalten für Operationen anzugeben, die ein Objekt von einem Typ in einen anderen konvertieren.</summary>
        /// <returns>true, wenn der Vorgang erfolgreich ist, andernfalls false.Wenn die Methode false zurückgibt, wird das Verhalten vom Laufzeitbinder der Sprache bestimmt.(In den meisten Fällen wird eine sprachspezifische Laufzeitausnahme ausgelöst.)</returns>
        /// <param name="binder">Stellt Informationen zur Konvertierungsoperation bereit.Die binder.Type-Eigenschaft stellt den Typ bereit, in den das Objekt konvertiert werden muss.Für die Anweisung (String)sampleObject in C# (CType(sampleObject, Type) in Visual Basic), bei der sampleObject eine Instanz der von der <see cref="T:System.Dynamic.DynamicObject" />-Klasse abgeleiteten Klasse ist, gibt binder.Type z. B. den <see cref="T:System.String" />-Typ zurück.Die binder.Explicit-Eigenschaft stellt Informationen zur Art der ausgeführten Konvertierung bereit.Für die explizite Konvertierung wird true und für die implizite Konvertierung wird false zurückgegeben.</param>
        /// <param name="result">Das Ergebnis des Typkonvertierungsvorgangs.</param>
        public override bool TryConvert(ConvertBinder binder, out object result)
        {
            if (binder.Type.IsInterface)
            {
                result = Impromptu.DynamicActLike(this, binder.Type);
                return(true);
            }

            result = this;
            return(false);
        }
Example #9
0
        /// <summary>
        /// Construct GeneratedAPI Class
        /// </summary>
        /// <param name="objectResult">The properties for this Generated API Object</param>
        /// <param name="session">The current enigma Session for this Generated API Object</param>
        /// <param name="proxyType">Optional a proxyType</param>
        internal GeneratedAPI(ObjectResult objectResult, Session session, Type proxyType = null)
        {
            this.qGenericId = objectResult.QGenericId;
            this.qType      = objectResult.QType;
            this.qGenericId = objectResult.QGenericType;
            this.qHandle    = objectResult.QHandle;
            this.Session    = session;

            if (proxyType != null)
            {
                this.ProxyClass = Impromptu.DynamicActLike(this, proxyType);
            }
            else
            {
                this.ProxyClass = null;
            }
        }
Example #10
0
        /// <summary>
        /// Create a wrapper around an dynamic object.
        /// This wrapper ensures that we can cross the <see cref="AppDomain"/>,
        /// call internal methods (to make Anonymous types work),
        /// or call missing methods (when allowMissingMembers is true).
        /// </summary>
        /// <param name="wrapped">The object to wrap.</param>
        /// <param name="allowMissingMembers">true when we should not throw when missing members are invoked.</param>
        /// <returns>the wrapped object.</returns>
        public static object Create(object wrapped, bool allowMissingMembers = false)
        {
            if (IsWrapped(wrapped))
            {
                return(wrapped);
            }
            var wrapper    = new RazorDynamicObject(wrapped, allowMissingMembers);
            var interfaces =
                wrapped.GetType().GetInterfaces()
                .Where(t => t.IsPublic && t != typeof(IDynamicMetaObjectProvider))
                .Select(MapInterface).ToArray();

            if (interfaces.Length > 0)
            {
                return(Impromptu.DynamicActLike(wrapper, interfaces));
            }
            return(wrapper);
        }
Example #11
0
        private void InjectYukkuri()
        {
            var c = _yukkuriContext;

            if (c != null)
            {
                lock (c.SpeechControllerLockObject)
                {
                    var instance = c.SpeechControllerInstanceObject;
                    if (instance == null || !(instance is IActLikeProxyInitialize))
                    {
                        _originalInstance = instance;
                        var myInterface = Impromptu.DynamicActLike(this, c.ISpeechControllerType);
                        _yukkuriContext.SpeechControllerInstanceObject = myInterface;
                        _plugin.Controller.NotifyLogMessageAppend(false, "TTSYukkuri injected!");
                    }
                }
            }
        }
        /// <summary>
        /// Create a wrapper around an dynamic object.
        /// This wrapper ensures that we can cross the <see cref="AppDomain"/>,
        /// call internal methods (to make Anonymous types work),
        /// or call missing methods (when allowMissingMembers is true).
        /// </summary>
        /// <param name="wrapped">The object to wrap.</param>
        /// <param name="allowMissingMembers">true when we should not throw when missing members are invoked.</param>
        /// <returns>the wrapped object.</returns>
        public static object Create(object wrapped, bool allowMissingMembers = false)
        {
            if (IsWrapped(wrapped))
            {
                return(wrapped);
            }
            var wrapper    = new RazorDynamicObject(wrapped, allowMissingMembers);
            var interfaces =
                wrapped.GetType().GetInterfaces()
                // remove IDynamicMetaObjectProvider and ISerializable interfaces because ActLikeProxy does already implement them
                .Where(t => t.IsPublic && t != typeof(IDynamicMetaObjectProvider) && t != typeof(ISerializable))
                .Select(MapInterface).ToArray();

            if (interfaces.Length > 0)
            {
                return(Impromptu.DynamicActLike(wrapper, interfaces));
            }
            return(wrapper);
        }
Example #13
0
        private static ExpandoObject GetProxy(Type type)
        {
            var proxy = new ExpandoObject();

            foreach (PropertyInfo prop in type.GetProperties())
            {
                if (prop.MemberType != MemberTypes.Property)
                {
                    continue;
                }
                if (!prop.CanWrite)
                {
                    continue;
                }

                object defaultValue = null;
                if (prop.PropertyType.FullName.StartsWith("System"))
                {
                    if (prop.PropertyType.IsValueType && Nullable.GetUnderlyingType(prop.PropertyType) == null)
                    {
                        defaultValue = Activator.CreateInstance(prop.PropertyType);
                    }
                }
                else
                {
                    if (prop.PropertyType.IsInterface)
                    {
                        defaultValue = Impromptu.DynamicActLike(GetProxy(prop.PropertyType), prop.PropertyType);
                    }
                    else
                    {
                        defaultValue = Activator.CreateInstance(prop.PropertyType);
                    }
                }
                ((IDictionary <String, object>)proxy)[prop.Name] = defaultValue;
            }
            return(proxy);
        }
 /// <summary>
 /// Becomes a Proxy object that acts like it implements all of the interfaces listed as being supported by this Entity
 /// </summary>
 /// <remarks>
 /// Because the returned object supports ALL of the interfaces that have ever been added to this object
 /// you can cast it to any of them.  This enables a type of polymorphism.
 /// </remarks>
 public object ActLikeAllInterfacesPresent()
 {
     return(Impromptu.DynamicActLike(this, this.GetAllInterfaces()));
 }
Example #15
0
        internal static bool MassageResultBasedOnInterface(this ImpromptuObject target, string binderName, bool resultFound, ref object result)
        {
            if (result is ImpromptuForwarderAddRemove) //Don't massage AddRemove Proxies
            {
                return(true);
            }

            Type tType;
            var  tTryType = target.TryTypeForName(binderName, out tType);

            if (tTryType && tType == typeof(void))
            {
                return(true);
            }

            if (resultFound)
            {
                if (result is IDictionary <string, object> && !(result is ImpromptuDictionaryBase) &&
                    (!tTryType || tType == typeof(object)))
                {
                    result = new ImpromptuDictionary((IDictionary <string, object>)result);
                }
                else if (tTryType)
                {
                    if (result != null && !tType.IsAssignableFrom(result.GetType()))
                    {
                        if (tType.IsInterface)
                        {
                            if (result is IDictionary <string, object> && !(result is ImpromptuDictionaryBase))
                            {
                                result = new ImpromptuDictionary((IDictionary <string, object>)result);
                            }
                            else
                            {
                                result = new ImpromptuGet(result);
                            }

                            result = Impromptu.DynamicActLike(result, tType);
                        }
                        else
                        {
                            try {
                                object tResult;

                                tResult = Impromptu.InvokeConvert(target, tType, explict: true);

                                result = tResult;
                            } catch (RuntimeBinderException) {
                                Type tReducedType = tType;
                                if (tType.IsGenericType && tType.GetGenericTypeDefinition().Equals(typeof(Nullable <>)))
                                {
                                    tReducedType = tType.GetGenericArguments().First();
                                }

                                if (result is IConvertible && typeof(IConvertible).IsAssignableFrom(tReducedType))
                                {
                                    result = Convert.ChangeType(result, tReducedType, Thread.CurrentThread.CurrentCulture);
                                }
                                else
                                {
                                    //finally check type converter since it's the slowest.

#if !SILVERLIGHT
                                    var tConverter = TypeDescriptor.GetConverter(tType);
#else
                                    TypeConverter tConverter  = null;
                                    var           tAttributes = tType.GetCustomAttributes(typeof(TypeConverterAttribute), false);
                                    var           tAttribute  = tAttributes.OfType <TypeConverterAttribute>().FirstOrDefault();
                                    if (tAttribute != null)
                                    {
                                        tConverter =
                                            Impromptu.InvokeConstructor(Type.GetType(tAttribute.ConverterTypeName));
                                    }
#endif
                                    if (tConverter != null && tConverter.CanConvertFrom(result.GetType()))
                                    {
                                        result = tConverter.ConvertFrom(result);
                                    }

#if SILVERLIGHT
                                    else if (result is string)
                                    {
                                        var tDC = new SilverConvertertDC(result as String);
                                        var tFE = new SilverConverterFE
                                        {
                                            DataContext = tDC
                                        };


                                        var tProp = SilverConverterFE.GetProperty(tType);

                                        tFE.SetBinding(tProp, new System.Windows.Data.Binding("StringValue"));

                                        var tResult = tFE.GetValue(tProp);

                                        if (tResult != null)
                                        {
                                            result = tResult;
                                        }
                                    }
#endif
                                }
                            }
                        }
                    }
                    else if (result == null && tType.IsValueType)
                    {
                        result = Impromptu.InvokeConstructor(tType);
                    }
                }
            }
            else
            {
                result = null;
                if (!tTryType)
                {
                    return(false);
                }
                if (tType.IsValueType)
                {
                    result = Impromptu.InvokeConstructor(tType);
                }
            }
            return(true);
        }
        public static T Match <T>(string inputString, Regex regex) where T : class
        {
            var tMatch = Match(inputString, regex);

            return(tMatch == null ? null : Impromptu.DynamicActLike(tMatch, typeof(T)));
        }