Esempio n. 1
0
        protected object InvokeStaticMethod(String_OR_InvokeMemberName name, object[] args)
        {
            var staticType = InvokeContext.CreateStatic;
            var nameArgs   = InvokeMemberName.Create;

            var tList = new List <object> {
                CallTarget
            };

            tList.AddRange(args);

            object result        = null;
            var    sucess        = false;
            var    exceptionList = new List <Exception>();

            var tGenericPossibles = new List <Type[]>();

            if (name.GenericArgs != null && name.GenericArgs.Length > 0)
            {
                var tInterface    = CallTarget.GetType().GetInterface(_extendedType.Name, false);
                var tTypeGenerics = (tInterface.IsGenericType ? tInterface.GetGenericArguments()
                                            : new Type[] { }).Concat(name.GenericArgs).ToArray();

                tGenericPossibles.Add(tTypeGenerics);
                tGenericPossibles.Add(name.GenericArgs);
            }
            else
            {
                tGenericPossibles.Add(null);
            }



            foreach (var sType in _staticTypes)
            {
                foreach (var tGenericPossible in tGenericPossibles)
                {
                    try
                    {
                        result = Impromptu.InvokeMember(staticType(sType), nameArgs(name.Name, tGenericPossible), tList.ToArray());
                        sucess = true;
                        break;
                    }
                    catch (RuntimeBinderException ex)
                    {
                        exceptionList.Add(ex);
                    }
                }
            }

            if (!sucess)
            {
#if SILVERLIGHT && !SILVERLIGHT5
                throw exceptionList.First();
#else
                throw new AggregateException(exceptionList);
#endif
            }


            Type tOutType;
            if (TryTypeForName(name.Name, out tOutType))
            {
                if (tOutType.IsInterface)
                {
                    var tIsGeneric = tOutType.IsGenericType;
                    if (tOutType.IsGenericType)
                    {
                        tOutType = tOutType.GetGenericTypeDefinition();
                    }

                    if (InstanceHints.Select(it => tIsGeneric && it.IsGenericType ? it.GetGenericTypeDefinition() : it)
                        .Contains(tOutType))
                    {
                        result = CreateSelf(result, _extendedType, _staticTypes, _instanceHints);
                    }
                }
            }
            else
            {
                if (IsExtendedType(result))
                {
                    result = CreateSelf(result, _extendedType, _staticTypes, _instanceHints);
                }
            }

            return(result);
        }
Esempio n. 2
0
        /// <summary>
        /// Create a new instance of a python algorithm
        /// </summary>
        /// <param name="assemblyPath"></param>
        /// <param name="algorithmInstance"></param>
        /// <param name="errorMessage"></param>
        /// <returns></returns>
        private bool TryCreatePythonAlgorithm(string assemblyPath, out IAlgorithm algorithmInstance, out string errorMessage)
        {
            var success = false;

            algorithmInstance = null;
            errorMessage      = "";

            try
            {
                //Create the python engine
                var engine = Python.CreateEngine();
                var paths  = engine.GetSearchPaths();
                paths.Add(_ironPythonLibrary);
                engine.SetSearchPaths(paths);

                //Load the dll - built with clr.Compiler()
                Log.Trace("Loader.TryCreatePythonAlgorithm(): Loading python assembly: " + assemblyPath);
                var library = Assembly.LoadFile(Path.GetFullPath(assemblyPath));
                engine.Runtime.LoadAssembly(library);

                //Import the python dll: requires a main.py file to serve as starting point for the algorithm.
                var items = new List <KeyValuePair <string, dynamic> >();
                try
                {
                    Log.Trace("Loader.TryCreatePythonAlgorithm(): Importing python module...");
                    var algorithmName = Config.Get("algorithm-type-name");
                    var scope         = engine.Runtime.ImportModule(string.IsNullOrEmpty(algorithmName) ? "main" : algorithmName);
                    items = (List <KeyValuePair <string, dynamic> >)scope.GetItems();
                }
                catch (Exception err)
                {
                    Log.Error(err);
                    errorMessage = err.Message + " - could not locate 'main' module. Please make sure you have a main.py file in your project.";
                    return(false);
                }

                //Loop through the types in the dll, see if we can find a "QCAlgorithm" base class
                Log.Trace("Loader.TryCreatePythonAlgorithm(): Finding QCAlgorithm...");
                dynamic dynamicAlgorithm = null;
                foreach (var item in items)
                {
                    try
                    {
                        string baseName = item.Value.__bases__.ToString().ToString();
                        if (baseName.Contains("QCAlgorithm"))
                        {
                            dynamicAlgorithm = item.Value;
                        }
                    }
                    catch (Exception)
                    {
                        //Suppress the error messages
                    }
                }

                //If we haven't found it yet
                if (dynamicAlgorithm == null)
                {
                    errorMessage = "Could not find QCAlgorithm class in your project";
                    return(false);
                }

                //Cast DLR object to an IAlgorithm instance with Impromptu
                Log.Trace("Loader.TryCreatePythonAlgorithm(): Creating IAlgorithm instance...");
                dynamic instance = engine.Operations.CreateInstance(dynamicAlgorithm);
                algorithmInstance = Impromptu.ActLike <IAlgorithm>(instance);
                success           = true;
            }
            catch (Exception err)
            {
                Log.Error(err);
            }

            return(success && (algorithmInstance != null));
        }
Esempio n. 3
0
 /// <summary>
 /// Allows ActLike to be called via dynamic invocation
 /// </summary>
 /// <typeparam name="TInterface">The type of the interface.</typeparam>
 /// <param name="otherInterfaces">The other interfaces.</param>
 /// <returns></returns>
 public virtual TInterface ActLike <TInterface>(params Type[] otherInterfaces) where TInterface : class
 {
     return(Impromptu.ActLike <TInterface>(this, otherInterfaces));
 }
Esempio n. 4
0
        public void TestStaticGet()
        {
            var tDate = Impromptu.InvokeGet(typeof(DateTime).WithStaticContext(), "Today");

            Assert.AreEqual(DateTime.Today, tDate);
        }
            public object GetResult(Invocation invocation)
            {
                (new PermissionSet(PermissionState.Unrestricted)).Assert();
                object result = null;
                string name   = invocation.Name.Name;

                object[] args       = invocation.Args;
                Type[]   paramTypes = args.Select(o => o.GetType()).ToArray();
                try
                {
                    if (invocation.Kind == InvocationKind.NotSet && invocation.Name.Name == "_BinaryOperator")
                    { // We use that for operators
                        var    exp   = (ExpressionType)args[0];
                        object other = args[1];
                        result = Impromptu.InvokeBinaryOperator(_component, exp, other);
                    }
                    else if (invocation.Kind == InvocationKind.NotSet && invocation.Name.Name == "_UnaryOperator")
                    { // We use that for operators
                        var exp = (ExpressionType)args[0];
                        result = Impromptu.InvokeUnaryOperator(exp, _component);
                    }
                    else
                    {
                        // First we try to resolve via DLR
                        dynamic target = _component;
                        result = invocation.InvokeWithStoredArgs(_component);
                    }
                }
                catch (RuntimeBinderException)
                {
                    // DLR doesn't like some kind of functions,
                    // expecially because we have casted the component to object...
                    bool found = false;
                    switch (invocation.Kind)
                    {
                    case InvocationKind.Convert:
                        var  targetType = (Type)args[0];
                        bool tExplict   = false;
                        if (args.Length == 2)
                        {
                            tExplict = (bool)args[1];
                        }
                        // try to find explicit or implicit operator.
                        try
                        {
                            result = DynamicCast(_component, targetType);
                            found  = true;
                        }
                        catch (Exception)
                        {
                            found = false;
                        }
                        break;

                    //case InvocationKind.IsEvent:
                    //case InvocationKind.AddAssign:
                    //case InvocationKind.SubtractAssign:
                    //case InvocationKind.Invoke:
                    //case InvocationKind.InvokeAction:
                    //case InvocationKind.InvokeUnknown:
                    //case InvocationKind.InvokeMember: // TODO: add testcase
                    //case InvocationKind.InvokeMemberAction: // TODO: add testcase
                    //case InvocationKind.GetIndex: // TODO: add testcase
                    //case InvocationKind.SetIndex: // TODO: add testcase
                    case InvocationKind.Get:
                    case InvocationKind.Set:
                    case InvocationKind.InvokeMemberUnknown:
                    {
                        if (!found)
                        {
                            if (!TryFindInvokeMember(_runtimeType, name, args, paramTypes, out result))
                            {
                                // search all interfaces as well
                                foreach (var @interface in _runtimeType.GetInterfaces().Where(i => i.IsPublic))
                                {
                                    if (TryFindInvokeMember(@interface, name, args, paramTypes, out result))
                                    {
                                        found = true;
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                found = true;
                            }
                        }
                    }
                    break;

                    default:
                        break;
                    }

                    if (!found)
                    {
                        if (_allowMissing)
                        {
                            return(RazorDynamicObject.Create("", _allowMissing));
                        }
                        throw;
                    }
                }
                if (RazorDynamicObject.IsPrimitive(result))
                {
                    return(result);
                }
                else
                {
                    return(RazorDynamicObject.Create(result, _disposables.Add, _allowMissing));
                }
            }
Esempio n. 6
0
        public void TestConstructDateTimeNoParams()
        {
            var tCast = Impromptu.InvokeConstructor(typeof(DateTime));

            Assert.AreEqual(default(DateTime), tCast);
        }
Esempio n. 7
0
        public void TestConstructNullableprimativetype()
        {
            var tCast = Impromptu.InvokeConstructor(typeof(Nullable <Int32>));

            Assert.AreEqual(null, tCast);
        }
        public void ThenObjectShouldHavePropertyContaingString(string propName, string expectedValue)
        {
            IEnumerable collection = Impromptu.InvokeGet(Entity, propName);

            Assert.That(collection, Contains.Item(expectedValue));
        }
Esempio n. 9
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)));
        }
        public void ThenObjectShouldHavePropertyEqualTo(string propertyName, string expectedValue)
        {
            var actualValue = Impromptu.InvokeGet(Entity, propertyName);

            Assert.That(actualValue, Is.EqualTo(expectedValue));
        }
Esempio n. 12
0
 public static IList <Type> GetTypeArguments(this InvokeMemberBinder binder)
 {
     return(Impromptu.InvokeGet(binder, "Microsoft.CSharp.RuntimeBinder.ICSharpInvokeOrInvokeMemberBinder.TypeArguments") as IList <Type>);
 }
Esempio n. 13
0
 /// <summary>
 /// Given there is a list of items of the same type.
 /// </summary>
 public void given_there_is_a_list_of_same_type_items()
 {
     Console.WriteLine("Given there is a list of items of the same type.");
     this.items = this.CreateItems().Select(item => Impromptu.ActLike <ITestItemInterface>(item)).Cast <ITestItemInterface>().ToList();
 }
Esempio n. 14
0
        /// <summary>
        ///   Invokes the invocation on specified target with specific args.
        /// </summary>
        /// <param name="target"> The target. </param>
        /// <param name="args"> The args. </param>
        /// <returns> </returns>
        public virtual object Invoke(object target, params object[] args)
        {
            switch (Kind)
            {
            case InvocationKind.Constructor:
                return(Impromptu.InvokeConstructor((Type)target, args));

            case InvocationKind.Convert:
                bool tExplict = false;
                if (Args.Length == 2)
                {
                    tExplict = (bool)args[1];
                }
                return(Impromptu.InvokeConvert(target, (Type)args[0], tExplict));

            case InvocationKind.Get:
                return(Impromptu.InvokeGet(target, Name.Name));

            case InvocationKind.Set:
                Impromptu.InvokeSet(target, Name.Name, args.FirstOrDefault());
                return(null);

            case InvocationKind.GetIndex:
                return(Impromptu.InvokeGetIndex(target, args));

            case InvocationKind.SetIndex:
                Impromptu.InvokeSetIndex(target, args);
                return(null);

            case InvocationKind.InvokeMember:
                return(Impromptu.InvokeMember(target, Name, args));

            case InvocationKind.InvokeMemberAction:
                Impromptu.InvokeMemberAction(target, Name, args);
                return(null);

            case InvocationKind.InvokeMemberUnknown: {
                try {
                    return(Impromptu.InvokeMember(target, Name, args));
                } catch (RuntimeBinderException) {
                    Impromptu.InvokeMemberAction(target, Name, args);
                    return(null);
                }
            }

            case InvocationKind.Invoke:
                return(Impromptu.Invoke(target, args));

            case InvocationKind.InvokeAction:
                Impromptu.InvokeAction(target, args);
                return(null);

            case InvocationKind.InvokeUnknown: {
                try {
                    return(Impromptu.Invoke(target, args));
                } catch (RuntimeBinderException) {
                    Impromptu.InvokeAction(target, args);
                    return(null);
                }
            }

            case InvocationKind.AddAssign:
                Impromptu.InvokeAddAssign(target, Name.Name, args.FirstOrDefault());
                return(null);

            case InvocationKind.SubtractAssign:
                Impromptu.InvokeSubtractAssign(target, Name.Name, args.FirstOrDefault());
                return(null);

            case InvocationKind.IsEvent:
                return(Impromptu.InvokeIsEvent(target, Name.Name));

            default:
                throw new InvalidOperationException("Unknown Invocation Kind: " + Kind);
            }
        }
Esempio n. 15
0
        public void TestConstructValueType()
        {
            var tCast = Impromptu.InvokeConstructor(typeof(DateTime), 2009, 1, 20);

            Assert.AreEqual(20, tCast.Day);
        }
Esempio n. 16
0
        public IGlobal GetGlobelContext()
        {
            try
            {
                logger.Debug("Create global context");
                var config = new EnigmaConfigurations()
                {
                    Url          = ConnectUri.AbsoluteUri,
                    CreateSocket = async(Url) =>
                    {
                        var webSocket = new ClientWebSocket();
                        webSocket.Options.Cookies = new CookieContainer();

                        var callback = ServicePointManager.ServerCertificateValidationCallback;
                        if (callback == null)
                        {
                            throw new NotImplementedException(".NET has no certificate check");
                        }

                        var credentials = Config?.Credentials ?? null;
                        var credType    = Config?.Credentials?.Type ?? QlikCredentialType.NONE;
                        switch (credType)
                        {
                        case QlikCredentialType.CERTIFICATE:
                            var domainUser = new DomainUser(credentials.Value);
                            var options    = new CookieConnectionOptions()
                            {
                                CertificatePath = credentials?.Cert ?? null,
                                HeaderName      = "X-Qlik-User",
                                HeaderValue     = $"UserDirectory={domainUser.UserDirectory};UserId={domainUser.UserId}",
                                UseCertificate  = true,
                            };

                            var qlikClientCert = new X509Certificate2();
                            qlikClientCert = qlikClientCert.GetQlikClientCertificate(options.CertificatePath);
                            webSocket.Options.ClientCertificates.Add(qlikClientCert);
                            webSocket.Options.SetRequestHeader(options.HeaderName, options.HeaderValue);
                            logger.Debug($"Credential type: {credentials?.Type}");
                            break;

                        case QlikCredentialType.WINDOWSAUTH:
                            webSocket.Options.Credentials = new NetworkCredential(credentials?.Key, credentials?.Value);
                            logger.Debug($"WinAuth type: {credentials?.Type} with User {credentials?.Key}");
                            break;

                        case QlikCredentialType.SESSION:
                            logger.Debug($"Session-Cookie {credentials?.Key}={credentials?.Value}.");
                            ConnectCookie = new Cookie(credentials?.Key, credentials?.Value)
                            {
                                Secure = true,
                                Domain = ConnectUri.Host,
                                Path   = "/",
                            };
                            webSocket.Options.Cookies.Add(ConnectCookie);
                            logger.Debug($"Session type: {credentials?.Type} with Session {credentials?.Value}");
                            break;

                        case QlikCredentialType.NONE:
                            logger.Debug($"None type: No Authentication.");
                            // No Authentication for DESKTOP and DOCKER
                            break;

                        default:
                            throw new Exception("Unknown Qlik connection type.");
                        }
                        webSocket.Options.KeepAliveInterval = TimeSpan.FromDays(48);
                        await webSocket.ConnectAsync(new Uri(Url), CancellationToken.None);

                        return(webSocket);
                    },
                };

                SocketSession = Enigma.Create(config);
                var globalTask = SocketSession.OpenAsync();
                globalTask.Wait();
                logger.Debug("Found globel context");
                return(Impromptu.ActLike <IGlobal>(globalTask.Result));
            }
            catch (Exception ex)
            {
                logger.Debug(ex, "No Global context");
                return(null);
            }
        }
Esempio n. 17
0
        public void TestConstructprimativetype()
        {
            var tCast = Impromptu.InvokeConstructor(typeof(Int32));

            Assert.AreEqual(default(Int32), tCast);
        }
Esempio n. 18
0
 /// <summary>
 /// Tries to invoke.
 /// </summary>
 /// <param name="binder"></param>
 /// <param name="args"></param>
 /// <param name="result"></param>
 /// <returns></returns>
 public override bool TryInvoke(InvokeBinder binder, object[] args, out object result)
 {
     result = Impromptu.InvokeConstructor(_type, Util.NameArgsIfNecessary(binder.CallInfo, args));
     return(true);
 }
Esempio n. 19
0
        public void TestConstructOBjectNoParams()
        {
            var tCast = Impromptu.InvokeConstructor(typeof(object));

            Assert.AreEqual(typeof(object), tCast.GetType());
        }
Esempio n. 20
0
        public void TestDynamicMemberNamesExpando()
        {
            ExpandoObject tExpando = Build <ExpandoObject> .NewObject(One : 1);

            Assert.AreEqual("One", Impromptu.GetMemberNames(tExpando, dynamicOnly: true).Single());
        }
Esempio n. 21
0
        public void TestConstructGuid()
        {
            var tCast = Impromptu.InvokeConstructor(typeof(Guid));

            Assert.AreEqual(default(Guid), tCast);
        }
Esempio n. 22
0
        public void TestDynamicMemberNamesImpromput()
        {
            ImpromptuDictionary tDict = Build.NewObject(Two: 2);

            Assert.AreEqual("Two", Impromptu.GetMemberNames(tDict, dynamicOnly: true).Single());
        }
Esempio n. 23
0
        public void TestStaticGet2()
        {
            var tVal = Impromptu.InvokeGet(typeof(StaticType).WithStaticContext(), "Test");

            Assert.AreEqual(true, tVal);
        }
Esempio n. 24
0
 public void TestInvokeAdd()
 {
     Assert.AreEqual(Impromptu.InvokeBinaryOperator(1, ExpressionType.Add, 2), 3);
 }
Esempio n. 25
0
 protected TClient GetClient(IClientProxy c) => Impromptu.ActLike <TClient>(new DynamicClient(c));
Esempio n. 26
0
        public void TestInvokeAddDynamic()
        {
            var tMock = CreateMock(ExpressionType.Add);

            Impromptu.InvokeBinaryOperator(tMock, ExpressionType.Add, 4);
        }
Esempio n. 27
0
 /// <summary>设置ViewBag的值
 /// </summary>
 /// <param name="key">键</param>
 /// <param name="value">值</param>
 internal void AddViewBageValues(string key, object value)
 {
     Impromptu.InvokeSet(ViewBag, key, value);
 }
Esempio n. 28
0
 public void TestInvokeSubtract()
 {
     Assert.AreEqual(Impromptu.InvokeBinaryOperator(1, ExpressionType.Subtract, 2), -1);
 }
Esempio n. 29
0
 /// <summary>
 /// Creates this instance.
 /// </summary>
 /// <returns></returns>
 public virtual dynamic Create()
 {
     object[] tArgs = Arguments();
     return(Impromptu.InvokeConstructor(Type, tArgs));
 }
Esempio n. 30
0
 public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
 {
     result = new Invoker(_name, _genericParams, _genericMethodParameters, _parent, indexes.Select(it => Impromptu.InvokeConvert(it, typeof(Type), @explicit: true)).Cast <Type>().ToArray());
     return(true);
 }