public Expression Resolve(LinqCompiler _compiler)
        {
            UIForiaLinqCompiler compiler = (UIForiaLinqCompiler)_compiler;

            switch (variableType)
            {
            case AliasResolverType.ContextVariable: {
                ParameterExpression el     = compiler.GetElement();
                Expression          access = Expression.MakeMemberAccess(el, TemplateCompiler.s_UIElement_BindingNode);
                Expression          call   = ExpressionFactory.CallInstanceUnchecked(access, TemplateCompiler.s_LinqBindingNode_GetContextVariable, Expression.Constant(id));
                Type varType = ReflectionUtil.CreateGenericType(typeof(ContextVariable <>), type);

                UnaryExpression     convert  = Expression.Convert(call, varType);
                ParameterExpression variable = compiler.AddVariable(type, "ctxVar_resolve_" + GetName());

                compiler.Assign(variable, Expression.MakeMemberAccess(convert, varType.GetField("value")));
                return(variable);
            }

            case AliasResolverType.RepeatItem: {
                compiler.Comment(name);
                //var repeat_item_name = element.bindingNode.GetRepeatItem<T>(id).value;
                ParameterExpression el     = compiler.GetElement();
                Expression          access = Expression.MakeMemberAccess(el, TemplateCompiler.s_UIElement_BindingNode);

                ReflectionUtil.TypeArray1[0] = type;
                MethodInfo getItem = TemplateCompiler.s_LinqBindingNode_GetRepeatItem.MakeGenericMethod(ReflectionUtil.TypeArray1);
                Expression call    = ExpressionFactory.CallInstanceUnchecked(access, getItem, Expression.Constant(id));
                Type       varType = ReflectionUtil.CreateGenericType(typeof(ContextVariable <>), type);

                ParameterExpression variable = compiler.AddVariable(type, "repeat_item_" + GetName());

                compiler.Assign(variable, Expression.MakeMemberAccess(call, varType.GetField(nameof(ContextVariable <int> .value))));
                return(variable);
            }

            case AliasResolverType.RepeatIndex: {
                ParameterExpression el     = compiler.GetElement();
                Expression          access = Expression.MakeMemberAccess(el, TemplateCompiler.s_UIElement_BindingNode);
                Expression          call   = ExpressionFactory.CallInstanceUnchecked(access, TemplateCompiler.s_LinqBindingNode_GetContextVariable, Expression.Constant(id));

                UnaryExpression     convert  = Expression.Convert(call, typeof(ContextVariable <int>));
                ParameterExpression variable = compiler.AddVariable(type, "repeat_index_" + GetName());

                compiler.Assign(variable, Expression.MakeMemberAccess(convert, typeof(ContextVariable <int>).GetField(nameof(ContextVariable <int> .value))));
                return(variable);
            }

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Example #2
0
    public void CompileMethod_MissingMethodOverload()
    {
        LinqCompiler compiler = new LinqCompiler();

        compiler.SetSignature <int>();
        compiler.AddNamespace("UnityEngine");
        CompileException exception = Assert.Throws <CompileException>(() =>
                                                                      compiler.Return("Color.red.GetHashCode(14, 15)")
                                                                      );
        string expected = CompileException.UnresolvedInstanceMethodOverload(typeof(Color), "GetHashCode", new Type[] { typeof(int), typeof(int) }).Message;

        Assert.AreEqual(expected, exception.Message);
    }
Example #3
0
        private void toolStripButtonExecute_Click(object sender, EventArgs e)
        {
            try
            {
                string html      = string.Empty;
                bool   hasErrors = false;
                int    count;

                webBrowserResults.Document.OpenNew(true);
                if (Cell.Image != null)
                {
                    Cell.Image = null;
                }
                ShowProgress(true);
                tabPageResults.Text = "Results";
                using (WaitCursor wc = new WaitCursor())
                {
                    html = LinqCompiler.Execute(_Dataset, richTextBoxScript.Text, _Directory, out hasErrors, out count);
                }

                if (!hasErrors)
                {
                    if (count > 0)
                    {
                        webBrowserResults.Document.Write(html);
                        tabControl.SelectedTab = tabPageResults;
                        tabPageResults.Text    = "Results [" + count.ToString() + "]";
                    }
                    else
                    {
                        Messager.ShowInformation(this, "No Results Found");
                    }
                }
                else if (tabControl.SelectedTab != tabPageQuery)
                {
                    tabControl.SelectedTab = tabPageQuery;
                }
            }
            catch (Exception exception)
            {
                Messager.ShowError(this, exception);
            }
            finally
            {
                ShowProgress(false);
            }
        }
        public Expression ResolveType(LinqCompiler _compiler)
        {
            UIForiaLinqCompiler compiler = (UIForiaLinqCompiler)_compiler;

            switch (variableType)
            {
            case AliasResolverType.ContextVariable: {
                return(compiler.AddVariable(type, "ctxvar_" + GetName()));;
            }

            case AliasResolverType.RepeatItem: {
                return(compiler.AddVariable(type, "repeat_item_" + GetName()));
            }

            case AliasResolverType.RepeatIndex: {
                return(compiler.AddVariable(typeof(int), "ctxvar_" + GetName()));
            }

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        private const int DEFAULT_TIMEOUT       = 10000; // 10 seconds

        public IRecord[] Execute(string query,
                                 int?maximumResults,
                                 string OAuthConsumerKey,
                                 string OAuthConsumerSecret,
                                 string OAuthToken,
                                 string OAuthTokenSecret,
                                 System.Collections.Generic.IDictionary <string, object> parameters,
                                 System.Collections.Generic.IList <string> aliases)
        {
            Guard.ArgumentNotNull(query, "query");
            IRecord[] result = null;


            if (parameters != null)
            {
                foreach (System.Collections.Generic.KeyValuePair <string, object> parameter in parameters)
                {
                    if (parameter.Value != null)
                    {
                        query = query.Replace(":" + parameter.Key, parameter.Value.ToString());
                    }
                    else
                    if (query.IndexOf(":" + parameter.Key) >= 0)
                    {
                        // this means the query has the parameter, but no value was passed
                        // in that case best to not actually run the query since we don't have parameters filled in
                        return new IRecord[] {}
                    }
                    ;
                }
            }

            var auth = new SingleUserAuthorizer();

            auth.OAuthTwitter.OAuthConsumerKey    = OAuthConsumerKey;
            auth.OAuthTwitter.OAuthConsumerSecret = OAuthConsumerSecret;
            auth.OAuthTwitter.OAuthToken          = OAuthToken;
            auth.OAuthTwitter.OAuthTokenSecret    = OAuthTokenSecret;
            var twitterCtx = new TwitterContext(auth);

            twitterCtx.Timeout = DEFAULT_TIMEOUT;

            LinqCompiler lc = new LinqCompiler("");

            lc.Query = query;
            lc.AddSource("Status", twitterCtx.Status);
            lc.AddSource("User", twitterCtx.User);
            lc.AddSource("Search", twitterCtx.Search);

            object oresult = null;

            try
            {
                oresult = lc.Evaluate();

                if (oresult.GetType() == typeof(TwitterQueryable <LinqToTwitter.Status>))
                {
                    TwitterQueryable <LinqToTwitter.Status> q = (TwitterQueryable <LinqToTwitter.Status>)oresult;
                    //result = q.ToList().Cast<object>().SafeSelect((object item) => DefaultTwitterExecutor.CreateRecord(item, aliases)).ToArray<IRecord>();
                    result = q.ToList().SafeSelect(item => CreateStatusRecord(item)).ToArray <IRecord>();
                }
                else if (oresult.GetType() == typeof(TwitterQueryable <LinqToTwitter.User>))
                {
                    TwitterQueryable <LinqToTwitter.User> q = (TwitterQueryable <LinqToTwitter.User>)oresult;
                    result = q.ToList().Cast <object>().SafeSelect((object item) => DefaultTwitterExecutor.CreateRecord(item, aliases)).ToArray <IRecord>();
                }
                else if (oresult.GetType() == typeof(TwitterQueryable <LinqToTwitter.Search>))
                {
                    TwitterQueryable <LinqToTwitter.Search> q = (TwitterQueryable <LinqToTwitter.Search>)oresult;
                    // for the search operation, select the statuses as an array
                    result = q.ToList()[0].Statuses.SafeSelect(item => CreateStatusRecord(item)).ToArray <IRecord>();
                }
            }
            catch (TwitterQueryException ex)
            {
                WebException webEx = ex.InnerException as WebException;
                if (webEx != null)
                {
                    HttpWebResponse response = webEx.Response as HttpWebResponse;
                    if (response != null && response.StatusCode == HttpStatusCode.NotFound)
                    {
                        // twitter returns a 404 if no matching user
                        return(new IRecord[] { });
                    }
                }
                throw new MashupException(string.Format("{0}{1}{2}", Saleslogix.Social.Mashups.Properties.Resources.DefaultQueryExecutor_UnableToExecuteQuery, System.Environment.NewLine, ex.Message), ex);
            }
            catch (Exception ex)
            {
                throw new MashupException(string.Format("{0}{1}{2}", Saleslogix.Social.Mashups.Properties.Resources.DefaultQueryExecutor_UnableToExecuteQuery, System.Environment.NewLine, ex.Message), ex);
            }

            if (result != null)
            {
                return(result);
            }

            throw new MashupException(Saleslogix.Social.Mashups.Properties.Resources.DefaultQueryExecutor_UnableToExecuteQuery);



            //using (SessionScopeWrapper sessionScopeWrapper = new SessionScopeWrapper())
            //{
            //    IQuery query2 = sessionScopeWrapper.CreateQuery(query);
            //    if (maximumResults.HasValue)
            //    {
            //        query2.SetMaxResults(maximumResults.Value);
            //    }
            //    if (parameters != null)
            //    {
            //        ISessionFactoryImplementor sessionFactoryImplementor = (ISessionFactoryImplementor)sessionScopeWrapper.SessionFactory;
            //        ParameterMetadata parameterMetadata = (sessionFactoryImplementor != null && sessionFactoryImplementor.QueryPlanCache != null) ? sessionFactoryImplementor.QueryPlanCache.GetHQLQueryPlan(query, false, null).ParameterMetadata : null;
            //        foreach (System.Collections.Generic.KeyValuePair<string, object> current in parameters)
            //        {
            //            if (parameterMetadata != null)
            //            {
            //                NamedParameterDescriptor namedParameterDescriptor = parameterMetadata.GetNamedParameterDescriptor(current.Key);
            //                PrimitiveType primitiveType = namedParameterDescriptor.ExpectedType as PrimitiveType;
            //                object val = (primitiveType != null) ? ConvertEx.ChangeType(current.Value, primitiveType.PrimitiveClass, null) : current.Value;
            //                query2.SetParameter(current.Key, val, namedParameterDescriptor.ExpectedType);
            //            }
            //            else
            //            {
            //                query2.SetParameter(current.Key, current.Value);
            //            }
            //        }
            //    }
            //    try
            //    {
            //        result = query2.List().Cast<object>().SafeSelect((object item) => DefaultQueryExecutor.CreateRecord(item, aliases)).ToArray<IRecord>();
            //    }
            //    catch (QueryException ex)
            //    {
            //        throw new MashupException(string.Format("{0}{1}{2}", Resources.DefaultQueryExecutor_UnableToExecuteQuery, System.Environment.NewLine, ex.Message), ex);
            //    }
            //}
        }
        private void cmdRunQuery_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            lblStatus.Text = "Query running, please wait...";
            statusStrip.Refresh();

            Context = ClientFactory.GetContext(
                new SDataClientContextFactory(),
                new SDataContextConfiguration()
                {
                    Servername = Servername,
                    Port = Port,
                    Username = Username,
                    Password = Password,
                    MaxRequestSize = MaxRequestSize
                }
            );

            LQ = new LinqCompiler(txtQuery.Text);
            PopulateQuerySource();

            object result = null;
            try
            {
                result = LQ.Evaluate();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                lblStatus.Text = "Query Failed: " + ex.GetType().ToString() ;
                Cursor.Current = Cursors.Arrow;
                return;
            }

            try
            {
                BindingSource bs = new BindingSource();
                bs.DataSource = result;
                dgvResults.DataSource = bs;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                lblStatus.Text = "Binding Failed: " + ex.GetType().ToString();
                Cursor.Current = Cursors.Arrow;
                return;
            }

            foreach (DataGridViewColumn dgvc in dgvResults.Columns)
            {
                dgvResults.AutoResizeColumn(dgvc.Index);
            }

            lblStatus.Text = "Query complete, " + dgvResults.Rows.Count + " rows returned.";
            Cursor.Current = Cursors.Arrow;
        }
Example #7
0
 protected override void SetupClosure(LinqCompiler p)
 {
     this.parent = p as UIForiaLinqCompiler;
 }
        private void PopulateTree()
        {
            Type myType = cbxInterface.SelectedItem as Type;
            System.Collections.IEnumerator enumerator;

            Nodes = entityTreeView.Nodes;
            Nodes.Clear();

            lblStatus.Text = "Loading entities, please wait...";
            statusStrip.Refresh();
            if (chkEnableLINQ.Checked == false)
            {
                System.Reflection.MethodInfo method = Context.GetType().GetMethod("CreateQuery");
                System.Reflection.MethodInfo generic = method.MakeGenericMethod(myType);
                object result = generic.Invoke(Context, null);
                enumerator = (System.Collections.IEnumerator)result.GetType().InvokeMember("GetEnumerator", System.Reflection.BindingFlags.InvokeMethod, System.Type.DefaultBinder, result, null);
            }
            else
            {
                LQ = new LinqCompiler(txtLINQ.Text);
                PopulateQuerySource();
                object result = null;
                try
                {
                    result = LQ.Evaluate();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    lblStatus.Text = "Query error occured: " + ex.GetType().ToString();
                    statusStrip.Refresh();
                    return;
                }

                enumerator = (System.Collections.IEnumerator)result.GetType().InvokeMember("GetEnumerator", System.Reflection.BindingFlags.InvokeMethod, System.Type.DefaultBinder, result, null);
            }
            try {
                while (enumerator.MoveNext())
                {
                    Object obj = enumerator.Current;
                    TreeNode tnp = new TreeNode();
                    string svalue;
                    object value = obj.GetType().InvokeMember("DisplayValue", System.Reflection.BindingFlags.GetProperty, System.Type.DefaultBinder, obj, null);
                    if (value == null)
                        svalue = "NULL";
                    else
                        svalue = value.ToString();
                    tnp.Text = svalue;
                    System.Reflection.PropertyInfo[] PropertyInfoArray = myType.GetProperties();
                    foreach (System.Reflection.PropertyInfo pi in PropertyInfoArray)
                    {
                        try
                        {
                            string name = pi.Name;
                            value = obj.GetType().InvokeMember(pi.Name, System.Reflection.BindingFlags.GetProperty, System.Type.DefaultBinder, obj, null);
                            if (value == null)
                                svalue = "NULL";
                            else
                                svalue = value.ToString();
                            object tag = obj.GetType().InvokeMember(pi.Name, System.Reflection.BindingFlags.GetProperty, System.Type.DefaultBinder, obj, null);
                            TreeNode tn = new TreeNode(name + ": " + svalue);
                            tn.Tag = tag;
                            tn.Name = name;
                            tn.ToolTipText = svalue;
                            tnp.Nodes.Add(tn);

                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Trace.WriteLine(pi.Name + ": " + ex.Message);
                        }
                    }

                    Nodes.Add(tnp);
                }
                lblStatus.Text = "Loading complete.";
                statusStrip.Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                lblStatus.Text = "Loading error occured: " + ex.GetType().ToString();
                statusStrip.Refresh();
            }
        }
        public IRecord[] Execute(string query,
            int? maximumResults,
            string OAuthConsumerKey,
            string OAuthConsumerSecret,
            string OAuthToken,
            string OAuthTokenSecret,
            System.Collections.Generic.IDictionary<string, object> parameters,
            System.Collections.Generic.IList<string> aliases)
        {
            Guard.ArgumentNotNull(query, "query");
            IRecord[] result = null;

            if (parameters != null)
            {
                foreach (System.Collections.Generic.KeyValuePair<string, object> parameter in parameters)
                {
                    if (parameter.Value != null)
                        query = query.Replace(":" + parameter.Key, parameter.Value.ToString());
                    else
                        if (query.IndexOf(":" + parameter.Key) >= 0)
                            // this means the query has the parameter, but no value was passed
                            // in that case best to not actually run the query since we don't have parameters filled in
                            return new IRecord[] {};
                }
            }

            var auth = new SingleUserAuthorizer();
            auth.OAuthTwitter.OAuthConsumerKey = OAuthConsumerKey;
            auth.OAuthTwitter.OAuthConsumerSecret = OAuthConsumerSecret;
            auth.OAuthTwitter.OAuthToken = OAuthToken;
            auth.OAuthTwitter.OAuthTokenSecret = OAuthTokenSecret;
            var twitterCtx = new TwitterContext(auth);
            twitterCtx.Timeout = DEFAULT_TIMEOUT;

            LinqCompiler lc = new LinqCompiler("");
            lc.Query = query;
            lc.AddSource("Status", twitterCtx.Status);
            lc.AddSource("User", twitterCtx.User);
            lc.AddSource("Search", twitterCtx.Search);

            object oresult = null;
            try
            {
                oresult = lc.Evaluate();

                if (oresult.GetType() == typeof(TwitterQueryable<LinqToTwitter.Status>))
                {
                    TwitterQueryable<LinqToTwitter.Status> q = (TwitterQueryable<LinqToTwitter.Status>)oresult;
                    //result = q.ToList().Cast<object>().SafeSelect((object item) => DefaultTwitterExecutor.CreateRecord(item, aliases)).ToArray<IRecord>();
                    result = q.ToList().SafeSelect(item => CreateStatusRecord(item)).ToArray<IRecord>();
                } else if (oresult.GetType() == typeof(TwitterQueryable<LinqToTwitter.User>))
                {
                    TwitterQueryable<LinqToTwitter.User> q = (TwitterQueryable<LinqToTwitter.User>)oresult;
                    result = q.ToList().Cast<object>().SafeSelect((object item) => DefaultTwitterExecutor.CreateRecord(item, aliases)).ToArray<IRecord>();
                } else if (oresult.GetType() == typeof(TwitterQueryable<LinqToTwitter.Search>))
                {
                    TwitterQueryable<LinqToTwitter.Search> q = (TwitterQueryable<LinqToTwitter.Search>)oresult;
                    // for the search operation, select the statuses as an array
                    result = q.ToList()[0].Statuses.SafeSelect(item => CreateStatusRecord(item)).ToArray<IRecord>();
                }

            }
            catch (TwitterQueryException ex)
            {
                WebException webEx = ex.InnerException as WebException;
                if (webEx != null)
                {
                    HttpWebResponse response = webEx.Response as HttpWebResponse;
                    if (response != null && response.StatusCode == HttpStatusCode.NotFound)
                    {
                        // twitter returns a 404 if no matching user
                        return new IRecord[] { };
                    }
                }
                throw new MashupException(string.Format("{0}{1}{2}", Saleslogix.Social.Mashups.Properties.Resources.DefaultQueryExecutor_UnableToExecuteQuery, System.Environment.NewLine, ex.Message), ex);
            }
            catch (Exception ex)
            {
                throw new MashupException(string.Format("{0}{1}{2}", Saleslogix.Social.Mashups.Properties.Resources.DefaultQueryExecutor_UnableToExecuteQuery, System.Environment.NewLine, ex.Message), ex);
            }

            if(result != null)
                return result;

            throw new MashupException(Saleslogix.Social.Mashups.Properties.Resources.DefaultQueryExecutor_UnableToExecuteQuery);

            //using (SessionScopeWrapper sessionScopeWrapper = new SessionScopeWrapper())
            //{
            //    IQuery query2 = sessionScopeWrapper.CreateQuery(query);
            //    if (maximumResults.HasValue)
            //    {
            //        query2.SetMaxResults(maximumResults.Value);
            //    }
            //    if (parameters != null)
            //    {
            //        ISessionFactoryImplementor sessionFactoryImplementor = (ISessionFactoryImplementor)sessionScopeWrapper.SessionFactory;
            //        ParameterMetadata parameterMetadata = (sessionFactoryImplementor != null && sessionFactoryImplementor.QueryPlanCache != null) ? sessionFactoryImplementor.QueryPlanCache.GetHQLQueryPlan(query, false, null).ParameterMetadata : null;
            //        foreach (System.Collections.Generic.KeyValuePair<string, object> current in parameters)
            //        {
            //            if (parameterMetadata != null)
            //            {
            //                NamedParameterDescriptor namedParameterDescriptor = parameterMetadata.GetNamedParameterDescriptor(current.Key);
            //                PrimitiveType primitiveType = namedParameterDescriptor.ExpectedType as PrimitiveType;
            //                object val = (primitiveType != null) ? ConvertEx.ChangeType(current.Value, primitiveType.PrimitiveClass, null) : current.Value;
            //                query2.SetParameter(current.Key, val, namedParameterDescriptor.ExpectedType);
            //            }
            //            else
            //            {
            //                query2.SetParameter(current.Key, current.Value);
            //            }
            //        }
            //    }
            //    try
            //    {
            //        result = query2.List().Cast<object>().SafeSelect((object item) => DefaultQueryExecutor.CreateRecord(item, aliases)).ToArray<IRecord>();
            //    }
            //    catch (QueryException ex)
            //    {
            //        throw new MashupException(string.Format("{0}{1}{2}", Resources.DefaultQueryExecutor_UnableToExecuteQuery, System.Environment.NewLine, ex.Message), ex);
            //    }
            //}
        }