Click here to Skip to main content
15,886,066 members
Articles / Desktop Programming / WPF

Dynamic LINQ to Entities Queries Using WCF/WPF Demo Code

Rate me:
Please Sign up or sign in to vote.
4.93/5 (86 votes)
30 Nov 2008CPOL22 min read 249.1K   4.5K   230  
Demonstrates a method of dynamic query across WCF Service boundaries.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Data;


namespace WpfClient
{
    /// <summary>
    /// ViewModel for the SearchClauseControl
    /// </summary>
    public class SearchClauseViewModel : INotifyPropertyChanged
    {

        #region Data
        private String clauseResult = String.Empty;
        private Boolean isFirst = false;
        private List<String> availableOperators = null;
        private List<String> availableConditions = null;
        private List<PropertyInfo> availableProperties = null;
        private Type boundType = null;

        private PropertyInfo currentProperty = null;
        private ICollectionView propertiesCollectionView = null;


        private String currentOperator = null;
        private ICollectionView operatorCollectionView = null;


        private String currentCondition = null;
        private ICollectionView conditionCollectionView = null;

        #endregion

        #region Ctor
        public SearchClauseViewModel()
        {
        }
        #endregion

        #region Public Properties

        public Boolean IsCollectionProperty { get; private set; }

        public Boolean IsOperatorComparable { get; private set; }

        public Boolean IsString { get; private set; }

        public Boolean IsNumeric { get; private set; }

        public Int32 ParameterNumber { get; set; }


        public Type BoundType
        {
            get { return boundType; }
            set
            {
                boundType = value;
                CreateFormValues();
                NotifyPropertyChanged("BoundType");
            }
        }

        public Boolean IsFirst
        {
            get { return isFirst; }
            set
            {
                isFirst = value;
                NotifyPropertyChanged("IsFirst");
            }
        }

        public List<String> AvailableOperators
        {
            get { return availableOperators; }
            set
            {
                availableOperators = value;
                NotifyPropertyChanged("AvailableOperators");
            }
        }

        public List<String> AvailableConditions
        {
            get { return availableConditions; }
            set
            {
                availableConditions = value;
                NotifyPropertyChanged("AvailableConditions");
            }
        }

        public List<PropertyInfo> AvailableProperties
        {
            get { return availableProperties; }
            set
            {
                availableProperties = value;
                NotifyPropertyChanged("AvailableProperties");
            }
        }


        public String ClauseResult
        {
            get
            {

                StringBuilder sb = new StringBuilder(1000);

                if (!IsFirst)
                    sb.Append(String.Format("{0} ", currentOperator));

                if (IsCollectionProperty)
                    sb.Append(String.Format("{0}.Count ", currentProperty.Name));
                else
                {
                    if (IsString)
                        sb.Append(String.Format("{0}.", currentProperty.Name));
                    else
                        sb.Append(String.Format("{0} ", currentProperty.Name));
                }

                if (IsOperatorComparable)
                {
                    sb.Append(String.Format("{0} ", currentCondition));
                    sb.Append(String.Format("@{0} ", ParameterNumber));
                }

                if (IsString)
                {
                    sb.Append(String.Format("{0}(@{1})",
                        currentCondition,
                        ParameterNumber));
                }


                return sb.ToString();
            }
        }

        #endregion

        #region Private Methods


        private void propertiesCollectionView_CurrentChanged(object sender, EventArgs e)
        {
            currentProperty = propertiesCollectionView.CurrentItem as PropertyInfo;
            if (currentProperty != null)
                if (currentProperty.PropertyType.AssemblyQualifiedName.Contains("Collections"))
                    IsCollectionProperty = true;
                else
                    IsCollectionProperty = false;


            AvailableConditions = GetPossibleConditionsForProperty();

            if (this.AvailableOperators != null && this.AvailableOperators.Count > 0)
            {
                operatorCollectionView = CollectionViewSource.GetDefaultView(this.AvailableOperators);
                operatorCollectionView.MoveCurrentTo(this.AvailableOperators[0]);
                currentOperator = operatorCollectionView.CurrentItem.ToString();
                operatorCollectionView.CurrentChanged += operatorCollectionView_CurrentChanged;
            }

            if (this.AvailableOperators != null && this.AvailableOperators.Count > 0)
            {
                conditionCollectionView = CollectionViewSource.GetDefaultView(this.AvailableConditions);
                conditionCollectionView.MoveCurrentTo(this.AvailableConditions[0]);
                currentCondition = conditionCollectionView.CurrentItem.ToString();
                conditionCollectionView.CurrentChanged += conditionCollectionView_CurrentChanged;
            }
        }


        private void conditionCollectionView_CurrentChanged(object sender, EventArgs e)
        {
            currentCondition = conditionCollectionView.CurrentItem.ToString();

        }

        private void operatorCollectionView_CurrentChanged(object sender, EventArgs e)
        {
            currentOperator = operatorCollectionView.CurrentItem.ToString();
        }


        private void CreateFormValues()
        {


            //get a list of properties
            AvailableProperties = this.BoundType.GetProperties().ToList();

            AvailableOperators = new List<string>() { "AND", "OR" };

            AvailableConditions = GetPossibleConditionsForProperty();

            propertiesCollectionView = CollectionViewSource.GetDefaultView(this.AvailableProperties);
            propertiesCollectionView.CurrentChanged += propertiesCollectionView_CurrentChanged;

            operatorCollectionView = CollectionViewSource.GetDefaultView(this.AvailableOperators);
            operatorCollectionView.CurrentChanged += operatorCollectionView_CurrentChanged;

            conditionCollectionView = CollectionViewSource.GetDefaultView(this.AvailableConditions);
            conditionCollectionView.CurrentChanged += conditionCollectionView_CurrentChanged;
        }




        private List<string> ApplyNewConditions()
        {
            //default values
            List<String> conds = new List<string>()
                                     {
                                         "=<",
                                         ">=",
                                         "<",
                                         ">",
                                         "==",
                                         "!="
                                     };

            //should we change from default
            if (IsString)
                conds = new List<string>()
                                     {
                                         "Equals",
                                         "StartsWith",
                                         "EndsWith",
                                         "Contains"
                                     };
            return conds;
        }

        private List<string> GetPossibleConditionsForProperty()
        {
            if (currentProperty != null)
            {

                if (currentProperty.PropertyType.FullName.Contains("Collection"))
                {
                    IsNumeric = true;
                    IsOperatorComparable = true;
                    IsString = false;
                }
                else
                {
                    String name = GetGenericsForType(currentProperty.PropertyType);

                    switch (name)
                    {
                        case "Int32":
                            IsNumeric = true;
                            IsOperatorComparable = true;
                            IsString = false;
                            break;
                        case "DateTime":
                            IsNumeric = false;
                            IsOperatorComparable = true;
                            IsString = false;
                            break;
                        case "String":
                            IsNumeric = false;
                            IsOperatorComparable = false;
                            IsString = true;
                            break;
                        default:
                            IsNumeric = false;
                            IsOperatorComparable = false;
                            IsString = true;
                            break;
                    }
                }


            }

            return ApplyNewConditions();
        }


        private string GetGenericsForType(Type t)
        {
            string name = "";
            if (!t.GetType().IsGenericType)
            {
                //see if there is a ' char, which there is for
                //generic types
                int idx = t.Name.IndexOfAny(new char[] { '`', '\'' });
                if (idx >= 0)
                {
                    name = t.Name.Substring(0, idx);
                    //get the generic arguments
                    Type[] genTypes = t.GetGenericArguments();
                    //and build the list of types for the result string
                    if (genTypes.Length == 1)
                    {
                        name += "<" + GetGenericsForType(genTypes[0]) + ">";
                    }
                    else
                    {
                        name += "<";
                        foreach (Type gt in genTypes)
                        {
                            name += GetGenericsForType(gt) + ", ";
                        }
                        if (name.LastIndexOf(",") > 0)
                        {
                            name = name.Substring(0,
                                name.LastIndexOf(","));
                        }
                        name += ">";
                    }
                }
                else
                {
                    name = t.Name;
                }
                return name;
            }
            else
            {
                return t.Name;
            }
        }




        #endregion

        #region INotifyPropertyChanged


        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }


        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United Kingdom United Kingdom
I currently hold the following qualifications (amongst others, I also studied Music Technology and Electronics, for my sins)

- MSc (Passed with distinctions), in Information Technology for E-Commerce
- BSc Hons (1st class) in Computer Science & Artificial Intelligence

Both of these at Sussex University UK.

Award(s)

I am lucky enough to have won a few awards for Zany Crazy code articles over the years

  • Microsoft C# MVP 2016
  • Codeproject MVP 2016
  • Microsoft C# MVP 2015
  • Codeproject MVP 2015
  • Microsoft C# MVP 2014
  • Codeproject MVP 2014
  • Microsoft C# MVP 2013
  • Codeproject MVP 2013
  • Microsoft C# MVP 2012
  • Codeproject MVP 2012
  • Microsoft C# MVP 2011
  • Codeproject MVP 2011
  • Microsoft C# MVP 2010
  • Codeproject MVP 2010
  • Microsoft C# MVP 2009
  • Codeproject MVP 2009
  • Microsoft C# MVP 2008
  • Codeproject MVP 2008
  • And numerous codeproject awards which you can see over at my blog

Comments and Discussions