예제 #1
0
        /// <summary>
        /// Obtains all users corresponding to the search filter
        /// </summary>
        /// <param name="value">Search filter</param>
        /// <returns>List of users matching the search filter</returns>
        public List<Entity> GetUsers(string value)
        {
            var users = new List<Entity>();

            var ceStatus = new ConditionExpression("isdisabled", ConditionOperator.Equal, false);

            var feStatus = new FilterExpression();
            feStatus.AddCondition(ceStatus);

            var qe = new QueryExpression("systemuser");
            qe.ColumnSet = new ColumnSet("systemuserid", "fullname", "lastname", "firstname", "domainname", "businessunitid");
            qe.AddOrder("lastname", OrderType.Ascending);
            qe.Criteria = new FilterExpression();
            qe.Criteria.Filters.Add(new FilterExpression());
            qe.Criteria.Filters[0].FilterOperator = LogicalOperator.And;
            qe.Criteria.Filters[0].Filters.Add(feStatus);
            qe.Criteria.Filters[0].Filters.Add(new FilterExpression());
            qe.Criteria.Filters[0].Filters[1].FilterOperator = LogicalOperator.Or;

            if (value.Length > 0)
            {
                bool isGuid = false;

                try
                {
                    Guid g = new Guid(value);
                    isGuid = true;
                }
                catch
                { }

                if (isGuid)
                {
                    var ce = new ConditionExpression("systemuserid", ConditionOperator.Equal, value);
                    qe.Criteria.Filters[0].Filters[1].AddCondition(ce);
                }
                else
                {
                    var ce = new ConditionExpression("fullname", ConditionOperator.Like, value.Replace("*", "%"));
                    var ce2 = new ConditionExpression("firstname", ConditionOperator.Like, value.Replace("*", "%"));
                    var ce3 = new ConditionExpression("lastname", ConditionOperator.Like, value.Replace("*", "%"));
                    var ce4 = new ConditionExpression("domainname", ConditionOperator.Like, value.Replace("*", "%"));

                    qe.Criteria.Filters[0].Filters[1].AddCondition(ce);
                    qe.Criteria.Filters[0].Filters[1].AddCondition(ce2);
                    qe.Criteria.Filters[0].Filters[1].AddCondition(ce3);
                    qe.Criteria.Filters[0].Filters[1].AddCondition(ce4);
                }
            }

            foreach (var record in service.RetrieveMultiple(qe).Entities)
            {
                users.Add(record);
            }

            return users;
        }
 internal static ConditionExpression CreateEqualsCondition(string attributeName, object value)
 {
     var condition = new ConditionExpression
     {
         AttributeName = attributeName,
         Operator = ConditionOperator.Equal
     };
     condition.Values.Add(value);
     return condition;
 }
        internal static ConditionExpression CreatePublisherNameBeginsWithCondition(string name)
        {
            var condition = new ConditionExpression
                {
                    AttributeName = "name",
                    Operator = ConditionOperator.BeginsWith
                };

            condition.Values.Add(name);
            return condition;
        }
예제 #4
0
        /// <summary>
        /// Executes the plug-in.
        /// </summary>
        /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the
        /// <see cref="IPluginExecutionContext"/>,
        /// <see cref="IOrganizationService"/>
        /// and <see cref="ITracingService"/>
        /// </param>
        /// <remarks>
        /// For improved performance, Microsoft Dynamics CRM caches plug-in instances.
        /// The plug-in's Execute method should be written to be stateless as the constructor
        /// is not called for every invocation of the plug-in. Also, multiple system threads
        /// could execute the plug-in at the same time. All per invocation state information
        /// is stored in the context. This means that you should not use global variables in plug-ins.
        /// </remarks>
        protected void ExecutePricingTypeUpdate(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

            // TODO: Implement your custom Plug-in business logic.

            IPluginExecutionContext context = localContext.PluginExecutionContext;
            IOrganizationService service = localContext.OrganizationService;
            Guid quoteProductID = (Guid)((Entity)context.InputParameters["Target"]).Id;
            ColumnSet set = new ColumnSet();
            set.AllColumns = true;
            var quote = service.Retrieve("quote", quoteProductID, set);


            if (context.Depth > 1)
            {
                return;
            }
            else
            {

                //First I get the base values that I need for the calculations

                var pricingType = (OptionSetValue)quote["new_pricingtype"];

                ConditionExpression condition = new ConditionExpression();
                condition.AttributeName = "quoteid";
                condition.Operator = ConditionOperator.Equal;
                condition.Values.Add(quoteProductID);

                FilterExpression filter = new FilterExpression();
                filter.AddCondition(condition);

                QueryExpression query = new QueryExpression();
                query.EntityName = "quotedetail";
                query.ColumnSet = new ColumnSet(true);
                query.Criteria = filter;

                EntityCollection quotedetails = service.RetrieveMultiple(query);

                foreach (var detail in quotedetails.Entities)
                {
                    detail["new_pricingtype"] = new OptionSetValue(pricingType.Value);
                    service.Update(detail);
                }


                service.Update(quote);

            }
        }
        static IBusActivityMonitor CreateBusActivityMonitorInternal(IBus bus, BusActivityReceiveIndicator receiveIndicator, BusActivityConsumeIndicator consumeIndicator,
            BusActivitySendIndicator sendIndicator, BusActivityPublishIndicator publishIndicator)
        {
            BusActivityMonitor activityMonitor = new BusActivityMonitor();
            ConditionExpression conditionExpression = new ConditionExpression(activityMonitor);
            conditionExpression.AddConditionBlock(receiveIndicator, consumeIndicator, sendIndicator, publishIndicator);

            bus.ConnectReceiveObserver(receiveIndicator);
            bus.ConnectConsumeObserver(consumeIndicator);

            return activityMonitor;
        }
 protected XrmAggregate(string recordTypeWithAggregate, string aggregateField, string recordTypeAggregated,
     string aggregatedField, AggregateType aggregateType)
 {
     RecordTypeWithAggregate = recordTypeWithAggregate;
     AggregateField = aggregateField;
     RecordTypeAggregated = recordTypeAggregated;
     AggregateType = aggregateType;
     AggregatedField = aggregatedField;
     Filters = new ConditionExpression[] { };
     AddFilter("statecode", XrmPicklists.State.Active);
     LinkEntity = null;
 }
    public override int DeleteInactiveProfiles(ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate)
    {
        //MAS
        using (OrganizationService service = new OrganizationService(OurConnect()))
        {
            ConditionExpression appCondition = new ConditionExpression();
            ConditionExpression authenticationCondition = new ConditionExpression();

            appCondition.AttributeName = consts.appname;
            appCondition.Operator = ConditionOperator.Equal;
            appCondition.Values.Add(_ApplicationName);

            switch (authenticationOption)
            {
                case ProfileAuthenticationOption.Anonymous:
                    authenticationCondition.AttributeName = consts.isanonymous;
                    authenticationCondition.Operator = ConditionOperator.Equal;
                    authenticationCondition.Values.Add(true);
                    break;
                case ProfileAuthenticationOption.Authenticated:
                    authenticationCondition.AttributeName = consts.isanonymous;
                    authenticationCondition.Operator = ConditionOperator.Equal;
                    authenticationCondition.Values.Add(false);
                    break;
                default:
                    break;
            }

            FilterExpression filter = new FilterExpression();
            filter.Conditions.Add(appCondition);
            filter.Conditions.Add(authenticationCondition);

            QueryExpression query = new QueryExpression(consts.userprofile);
            query.ColumnSet.AddColumn(consts.username);
            query.Criteria.AddFilter(filter);
            EntityCollection collection = service.RetrieveMultiple(query);

            string[] usersToDelete = null;
            int j = 0;
            for(int i=0;i<collection.TotalRecordCount;i++)
            {
                if (DateTime.Compare(lastActivity((string)collection.Entities[i][consts.username], String.Empty), userInactiveSinceDate) < 0)
                {
                    usersToDelete[j] = (string)collection.Entities[i][consts.username];
                    j++;
                }
            }

            return DeleteProfiles(usersToDelete);
        }
    }
        /// <summary>
        /// 検索条件を作成します。
        /// </summary>
        /// <param name="attr"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public ConditionExpression CreateCondition(string attr, CmbOperator operatorValue, string value)
        {
            if (String.IsNullOrEmpty(attr) || string.IsNullOrEmpty(value))
            {
                return null;
            }

            ConditionExpression cond = new ConditionExpression();
            cond.AttributeName = attr;
            cond.Operator = operatorValue.GetOpeator();
            cond.Values.Add(value);

            return cond;
        }
예제 #9
0
        public static FilterExpression CreateFilterExpression(CrmQuery crmQuery)
        {
            if (crmQuery == null)
                return null;

            FilterExpression filterExpression =
                new FilterExpression(OperatorMapper.GetMappedOperator(crmQuery.LogicalOperator));

            foreach (CrmAttributeCriterion condition in crmQuery.Conditions)
            {
                ConditionOperator conditionOperator = OperatorMapper.GetMappedOperator(condition.ConditionOperator);
                ConditionExpression conditionExpression = new ConditionExpression(condition.AttributeName, conditionOperator, condition.AttributeValue);
                filterExpression.AddCondition(conditionExpression);
            }
            return filterExpression;
        }
예제 #10
0
        public void TestFilters()
        {
            ConditionExpression cond = new ConditionExpression( "address1_name", ConditionOperator.Equal, new string[] { "Dan" } );
            ConditionExpression cond2 = new ConditionExpression( "address1_city", ConditionOperator.Equal, new string[] { "Bethesda" } );
            FilterExpression fe = new FilterExpression();
            fe.FilterOperator = LogicalOperator.And;
            fe.Conditions.Add( cond );
            fe.Conditions.Add( cond2 );

            QueryExpression qe = new QueryExpression( "contact" );
            qe.Criteria = fe;

            BusinessEntityCollection bec = m_service.RetrieveMultiple( qe );
            Console.WriteLine( "TestFilters() found: " + bec.BusinessEntities.Count + " entity. " );
            Fest.AssertTrue( bec.BusinessEntities.Count > 0, "found more than zero entities" );
        }
        public void When_executing_a_query_expression_with_a_not_implemented_operator_pull_request_exception_is_thrown()
        {
            var context = new XrmFakedContext();
            var contact1 = new Entity("contact") { Id = Guid.NewGuid() }; contact1["fullname"] = "Contact 1"; contact1["firstname"] = "First 1";
            var contact2 = new Entity("contact") { Id = Guid.NewGuid() }; contact2["fullname"] = "Contact 2"; contact2["firstname"] = "First 2";

            context.Initialize(new List<Entity>() { contact1, contact2 });

            var qe = new QueryExpression() { EntityName = "contact" };
            qe.ColumnSet = new ColumnSet(true);
            qe.Criteria = new FilterExpression(LogicalOperator.And);
            var condition = new ConditionExpression("fullname", ConditionOperator.LastXFiscalPeriods, "Contact 1");
            qe.Criteria.AddCondition(condition);

            Assert.Throws<PullRequestException>(() => XrmFakedContext.TranslateQueryExpressionToLinq(context, qe).ToList());
        }
        bool CheckDuplicateNumber(IOrganizationService service, string ivg_contactnumber)
        {
            var qe = new QueryExpression("contact");
            string[] col = { "ivg_contactnumber" };
            qe.ColumnSet = new ColumnSet(col);

            ConditionExpression con = new ConditionExpression();
            con.AttributeName = "ivg_contactnumber";
            con.Operator = ConditionOperator.Equal;
            con.Values.Add(ivg_contactnumber);

            qe.Criteria.Conditions.Add(con);

            EntityCollection ens = service.RetrieveMultiple(qe);
            if (ens != null && ens.Entities.Count > 0) return true;
            return false;
        }
        public void When_executing_a_query_expression_with_equals_operator_right_result_is_returned()
        {
            var context = new XrmFakedContext();
            var contact1 = new Entity("contact") { Id = Guid.NewGuid() }; contact1["fullname"] = "Contact 1"; contact1["firstname"] = "First 1";
            var contact2 = new Entity("contact") { Id = Guid.NewGuid() }; contact2["fullname"] = "Contact 2"; contact2["firstname"] = "First 2";
            
            context.Initialize(new List<Entity>() {  contact1, contact2 });

            var qe = new QueryExpression() { EntityName = "contact" };
            qe.ColumnSet = new ColumnSet(true);
            qe.Criteria = new FilterExpression(LogicalOperator.And);
            var condition = new ConditionExpression("fullname", ConditionOperator.Equal, "Contact 1");
            qe.Criteria.AddCondition(condition);
            
            var result = XrmFakedContext.TranslateQueryExpressionToLinq(context, qe).ToList();

            Assert.True(result.Count() == 1);
        }
예제 #14
0
 public bool CheckDuplicateBase(IOrganizationService service, string EntityName, string[] AttributeName, string[] ValuesCheck, string[] ColumnName)
 {
     try
     {
         flagErr = new StringBuilder();
         if (!(IDOldErr == ValuesCheck))
         {
             ConditionExpression[] condi = new ConditionExpression[ValuesCheck.Length];
             for (int i = 0; i < ValuesCheck.Length; i++)
             {
                 condi[i] = new ConditionExpression();
                 condi[i].AttributeName = AttributeName[i];
                 condi[i].Operator = ConditionOperator.Equal;
                 condi[i].Values.Add(ValuesCheck[i].ToString());
             }
             var qe = new QueryExpression(EntityName);
             qe.ColumnSet = new ColumnSet(ColumnName);
             FilterExpression filter = new FilterExpression();
             foreach (var item in condi)
             {
                 filter.FilterOperator = LogicalOperator.Or;
                 filter.Conditions.Add(item);
                 qe.Criteria = filter;
             }
             EntityCollection ens = service.RetrieveMultiple(qe);
             if (ens != null && ens.Entities.Count > 0)
             {
                 flagErr.Append(ens.Entities[0].Attributes[ConvertStringArrayToString(AttributeName)]);
                 _IdGui = ens.Entities[0].Id;
                 IDOldErr = ValuesCheck;
                 str = true;
             }
             else
             {
                 str = false;
             }
         }
         return str;
     }
     catch (Exception ex)
     {
         throw new InvalidPluginExecutionException(ex.StackTrace);
     }
 }
예제 #15
0
        public void Experiment_For_Filters_1()
        {
            // var sql = string.Format("Select C.firstname, C.lastname From contact Where firstname Like '%ax%' ");

            var connectionString = ConfigurationManager.ConnectionStrings["CrmOrganisation"];
            var serviceProvider = new CrmServiceProvider(new ExplicitConnectionStringProviderWithFallbackToConfig() { OrganisationServiceConnectionString = connectionString.ConnectionString },
                                                         new CrmClientCredentialsProvider());

            var orgService = serviceProvider.GetOrganisationService();
            using (orgService as IDisposable)
            {

                var query = new QueryExpression("contact");
                query.ColumnSet.AddColumn("firstname");
                query.ColumnSet.AddColumn("lastname");

                // so link in customer address.
                query.AddLink("customeraddress", "contactid", "parentid", JoinOperator.Inner);
                var addressLink = query.LinkEntities[0];
                addressLink.EntityAlias = "A";
                addressLink.IncludeAllColumns();

                // conditions for max planck
                var firstName1Condition = new ConditionExpression("firstname", ConditionOperator.Equal, "Max");
                var lastname1Condition = new ConditionExpression("lastname", ConditionOperator.Equal, "Planck");

                // Groups those conditions using an "AND" conjunction.
                var maxPlankFilter = new FilterExpression(LogicalOperator.And);
                maxPlankFilter.AddCondition(firstName1Condition);
                maxPlankFilter.AddCondition(lastname1Condition);

                // conditions for albert einstein
                var firstname2Condition = new ConditionExpression("firstname", ConditionOperator.Equal, "Albert");
                var lastname2Condition = new ConditionExpression("lastname", ConditionOperator.Equal, "Einstein");

                // Groups those conditions using an "AND" conjunction.
                var albertEinsteinFilter = new FilterExpression(LogicalOperator.And);
                albertEinsteinFilter.AddCondition(firstname2Condition);
                albertEinsteinFilter.AddCondition(lastname2Condition);

                // could optionally chain the 2 filters so we get Albert's contitions chained (using AND) to max's conditions
                //  albertEinsteinFilter.AddFilter(maxPlankFilter);

                // conditions for address line 1 moonbase
                var addressLine1Filter = new FilterExpression(LogicalOperator.And); // dictates that this filter is chained to
                var line1Condition = new ConditionExpression("A", "line1", ConditionOperator.Equal, "The secret moonbase");
                addressLine1Filter.AddCondition(line1Condition);

                // add filters to query
                // ensures each filter that we add to our queries criteria is chained together using an OR.
                query.Criteria.FilterOperator = LogicalOperator.Or;
                query.Criteria.AddFilter(albertEinsteinFilter);
                query.Criteria.AddFilter(maxPlankFilter);
                query.Criteria.AddFilter(addressLine1Filter);

                var results = orgService.RetrieveMultiple(query);
                int resultCount = 0;
                foreach (var r in results.Entities)
                {
                    resultCount++;
                    Console.WriteLine(string.Format("{0} {1}", (string)r["firstname"], (string)r["lastname"]));
                }
                Console.WriteLine("There were " + resultCount + " results..");

            }
        }
예제 #16
0
 /// <inheritdoc />
 protected override void DoSerialize(BuildXLWriter writer)
 {
     ConditionExpression.Serialize(writer);
     ThenExpression.Serialize(writer);
     ElseExpression.Serialize(writer);
 }
예제 #17
0
        /// <summary>
        /// 考勤记录列表
        /// </summary>
        /// <param name="name"></param>
        /// <param name="projectName"></param>
        /// <param name="oilName"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public ActionResult GetSignInfoList(string name, string projectName, string oilName, string time, string endtime, int pageIndex = 1, int pageSize = 10)
        {
            ViewBag.name        = name;
            ViewBag.projectName = projectName;
            ViewBag.oilName     = oilName;
            ViewBag.time        = time;
            Result <List <Epm_SignInformation> > result = new Result <List <Epm_SignInformation> >();

            using (AdminClientProxy proxy = new AdminClientProxy(ProxyEx(Request)))
            {
                QueryCondition      qc = new QueryCondition();
                ConditionExpression ce = new ConditionExpression();
                if (!string.IsNullOrEmpty(name))
                {
                    ce             = new ConditionExpression();
                    ce.ExpName     = "userName";
                    ce.ExpValue    = "%" + name + "%";
                    ce.ExpOperater = eConditionOperator.Like;
                    ce.ExpLogical  = eLogicalOperator.And;
                    qc.ConditionList.Add(ce);
                }
                if (!string.IsNullOrEmpty(projectName))
                {
                    ce             = new ConditionExpression();
                    ce.ExpName     = "projectName";
                    ce.ExpValue    = "%" + projectName + "%";
                    ce.ExpOperater = eConditionOperator.Like;
                    ce.ExpLogical  = eLogicalOperator.And;
                    qc.ConditionList.Add(ce);
                }
                if (!string.IsNullOrEmpty(oilName))
                {
                    ce             = new ConditionExpression();
                    ce.ExpName     = "gasstationName";
                    ce.ExpValue    = "%" + oilName + "%";
                    ce.ExpOperater = eConditionOperator.Like;
                    ce.ExpLogical  = eLogicalOperator.And;
                    qc.ConditionList.Add(ce);
                }
                if (!string.IsNullOrWhiteSpace(time))
                {
                    DateTime stime = Convert.ToDateTime(Convert.ToDateTime(time).ToString("yyyy-MM-dd"));
                    qc.ConditionList.Add(new ConditionExpression()
                    {
                        ExpName     = "SignTime",
                        ExpValue    = stime,
                        ExpLogical  = eLogicalOperator.And,
                        ExpOperater = eConditionOperator.GreaterThanOrEqual
                    });
                }
                if (!string.IsNullOrEmpty(endtime))
                {
                    DateTime etime = Convert.ToDateTime(Convert.ToDateTime(endtime).ToString("yyyy-MM-dd") + " 23:59:59");
                    qc.ConditionList.Add(new ConditionExpression()
                    {
                        ExpName     = "SignTime",
                        ExpValue    = etime,
                        ExpLogical  = eLogicalOperator.And,
                        ExpOperater = eConditionOperator.LessThanOrEqual
                    });
                }
                qc.PageInfo       = GetPageInfo(pageIndex, pageSize);
                result            = proxy.GetSignInformationList(qc);
                ViewBag.Total     = result.AllRowsCount;
                ViewBag.pageIndex = pageIndex;
            }
            return(View(result.Data));
        }
예제 #18
0
        /// <summary>
        /// Gets the marketing lists.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        /// <param name="conditionOperator">Condition operator.</param>
        /// <param name="values">The values of the property.</param>
        /// <returns>The marketing lists.</returns>
        protected IEnumerable <Entity> GetMarketingLists(string propertyName, ConditionOperator conditionOperator, params object[] values)
        {
            var propertyConditionExpression = new ConditionExpression();

            propertyConditionExpression.AttributeName = propertyName;
            propertyConditionExpression.Operator      = conditionOperator;
            propertyConditionExpression.Values.AddRange(values);

            var memberTypeConditionExpression = new ConditionExpression();

            memberTypeConditionExpression.AttributeName = "membertype";
            memberTypeConditionExpression.Operator      = ConditionOperator.Equal;
            memberTypeConditionExpression.Values.Add(2);

            var stateCodeConditionExpression = new ConditionExpression();

            stateCodeConditionExpression.AttributeName = "statecode";
            stateCodeConditionExpression.Operator      = ConditionOperator.Equal;
            stateCodeConditionExpression.Values.Add("Active");

            var filterExpression = new FilterExpression();

            filterExpression.Conditions.AddRange
            (
                propertyConditionExpression,
                memberTypeConditionExpression,
                stateCodeConditionExpression
            );
            filterExpression.FilterOperator = LogicalOperator.And;

            var pagingInfo = new PagingInfo
            {
                PageNumber = 1,
                Count      = Configuration.Settings.FetchThrottlingPageSize
            };

            var queryExpression = new QueryExpression();

            queryExpression.PageInfo   = pagingInfo;
            queryExpression.ColumnSet  = new ColumnSet(this.Attributes);
            queryExpression.Criteria   = filterExpression;
            queryExpression.EntityName = "list";
            queryExpression.NoLock     = true;
            queryExpression.Distinct   = false;

            var returnValue = new HashSet <Entity>(new EntityEqualityComparer());

            try
            {
                while (true)
                {
                    var entities = this.organizationServiceCache.GetOrganizationService().RetrieveMultiple(queryExpression);
                    if (entities == null)
                    {
                        break;
                    }

                    foreach (var entity in entities.Entities)
                    {
                        returnValue.Add(entity);
                    }

                    if (!entities.MoreRecords)
                    {
                        break;
                    }

                    pagingInfo.PageNumber++;
                    pagingInfo.PagingCookie = entities.PagingCookie;
                }
            }
            catch (Exception e)
            {
                ConditionalLog.Error("Couldn't get the marketing list(s) from CRM.", e, this);
            }

            return(returnValue.ToArray());
        }
예제 #19
0
        public override string[] GetRolesForUser(string userName)
        {
            Assert.ArgumentNotNull(userName, "userName");

            const string GetRolesForUserKey = "getRolesForUser";

            ConditionalLog.Info(String.Format("GetRolesForUser({0}). Started.", userName), this, TimerAction.Start, GetRolesForUserKey);

            var roles = this.CacheService.MemberOfCache.Get(userName);

            if (roles != null)
            {
                ConditionalLog.Info(String.Format("GetRolesForUser({0}). Finished (roles have been retrieved from cache).", userName), this, TimerAction.Stop, GetRolesForUserKey);
                return(roles.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries));
            }

            var listStateCodeConditionExpression = new ConditionExpression();

            listStateCodeConditionExpression.AttributeName = "statecode";
            listStateCodeConditionExpression.Operator      = ConditionOperator.Equal;
            listStateCodeConditionExpression.Values.Add("Active");

            var listFilterExpression = new FilterExpression();

            listFilterExpression.Conditions.Add(listStateCodeConditionExpression);
            listFilterExpression.FilterOperator = LogicalOperator.And;

            var contactNameConditionExpression = new ConditionExpression();

            contactNameConditionExpression.AttributeName = Configuration.Settings.UniqueKeyProperty;
            contactNameConditionExpression.Operator      = ConditionOperator.Equal;
            contactNameConditionExpression.Values.Add(userName);

            var contactFilterExpression = new FilterExpression();

            contactFilterExpression.Conditions.Add(contactNameConditionExpression);
            contactFilterExpression.FilterOperator = LogicalOperator.And;

            var listMemberContactLinkEntity = new LinkEntity();

            listMemberContactLinkEntity.JoinOperator          = JoinOperator.Inner;
            listMemberContactLinkEntity.LinkCriteria          = contactFilterExpression;
            listMemberContactLinkEntity.LinkFromAttributeName = "entityid";
            listMemberContactLinkEntity.LinkFromEntityName    = "listmember";
            listMemberContactLinkEntity.LinkToAttributeName   = "contactid";
            listMemberContactLinkEntity.LinkToEntityName      = "contact";

            var listListMemberLinkEntity = new LinkEntity();

            listListMemberLinkEntity.JoinOperator = JoinOperator.Inner;
            listListMemberLinkEntity.LinkEntities.Add(listMemberContactLinkEntity);
            listListMemberLinkEntity.LinkFromAttributeName = "listid";
            listListMemberLinkEntity.LinkFromEntityName    = "list";
            listListMemberLinkEntity.LinkToAttributeName   = "listid";
            listListMemberLinkEntity.LinkToEntityName      = "listmember";

            var pagingInfo = new PagingInfo
            {
                PageNumber = 1,
                Count      = Configuration.Settings.FetchThrottlingPageSize
            };

            var queryExpression = new QueryExpression();

            queryExpression.PageInfo   = pagingInfo;
            queryExpression.ColumnSet  = new ColumnSet("listname");
            queryExpression.Criteria   = listFilterExpression;
            queryExpression.EntityName = "list";
            queryExpression.LinkEntities.Add(listListMemberLinkEntity);
            queryExpression.NoLock   = true;
            queryExpression.Distinct = false;

            var request = new RetrieveMultipleRequest();

            request.Query = queryExpression;

            var result = new HashSet <string>();

            try
            {
                while (true)
                {
                    var service = this.organizationServiceCache.GetOrganizationService();
                    if (service == null)
                    {
                        ConditionalLog.Error("[CRM_GetRolesForUser]Service is null", this);
                        return(result.ToArray());
                    }
                    var response = service.Execute(request) as RetrieveMultipleResponse;
                    if (response == null || response.EntityCollection == null)
                    {
                        break;
                    }

                    ConditionalLog.Info(String.Format("GetRolesForUser({0}). Retrieved {1} roles from CRM.", userName, response.EntityCollection.Entities.Count), this, TimerAction.Tick, GetRolesForUserKey);

                    foreach (var entity in response.EntityCollection.Entities)
                    {
                        result.Add((string)entity["listname"]);
                    }

                    if (!response.EntityCollection.MoreRecords)
                    {
                        break;
                    }

                    pagingInfo.PageNumber++;
                    pagingInfo.PagingCookie = response.EntityCollection.PagingCookie;
                }
            }
            catch (Exception e)
            {
                ConditionalLog.Error(String.Format("Couldn't get roles of {0} contact from CRM.", userName), e, this);
            }

            var returnValue = result.ToArray();

            this.CacheService.MemberOfCache.Add(userName, String.Join("|", returnValue));

            ConditionalLog.Info(String.Format("GetRolesForUser({0}). Finished.", userName), this, TimerAction.Stop, GetRolesForUserKey);

            return(returnValue);
        }
예제 #20
0
        public void ImplicitOperatorTest()
        {
            ConditionExpression cond = "true and true";

            Assert.IsType <ConditionAndExpression>(cond);
        }
        /// <summary>
        /// The Execute method.
        /// </summary>
        /// <param name="serviceProvider"></param>
        public void Execute(IServiceProvider serviceProvider)
        {
            var organizationServiceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            var pluginContext  = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            var tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            var orgService     = organizationServiceFactory.CreateOrganizationService(pluginContext.UserId);

            if (pluginContext.PrimaryEntityName.Equals("savedquery") &&
                pluginContext.InputParameters.ContainsKey("Query") &&
                pluginContext.InputParameters["Query"] is QueryExpression)
            {
                var query = (QueryExpression)pluginContext.InputParameters["Query"];

                // get the returnedtypecode condition
                var returnedTypeCodeCondition = query.Criteria.Conditions.SingleOrDefault(c => c.AttributeName.Equals("returnedtypecode"));
                if (returnedTypeCodeCondition != null)
                {
                    if (returnedTypeCodeCondition.Values[0].GetType() != typeof(int))
                    {
                        return;
                    }

                    var objectTypeCode = (int)returnedTypeCodeCondition.Values[0];

                    try
                    {
                        // get the user configuration for role based views
                        var userConfiguration = PluginHelper.GetUserRoleViewConfigurationEntity(orgService, pluginContext.InitiatingUserId.ToString());
                        var isEnabled         = true;
                        if (userConfiguration != null)
                        {
                            isEnabled = userConfiguration.GetAttributeValue <bool>("rb_isenabled");
                        }

                        if (!isEnabled)
                        {
                            return;
                        }

                        // get user security roles
                        var userRoles = PluginHelper.GetUserSecurityRoles(orgService, pluginContext.InitiatingUserId.ToString());
                        // check to see whether the view configuration for the user has been done.

                        var viewConfigurations = PluginHelper.GetRoleViewConfigurationForEntity(orgService, userRoles, objectTypeCode);

                        if (viewConfigurations != null)
                        {
                            var hiddenViewsList = new List <string>();

                            foreach (var viewConfig in viewConfigurations)
                            {
                                var hiddenViewField = viewConfig.Attributes.ContainsKey("rb_hiddenviews") ? (string)viewConfig.Attributes["rb_hiddenviews"] : null;

                                if (hiddenViewField != null)
                                {
                                    hiddenViewsList.AddRange(hiddenViewField.Split('@'));
                                }
                            }

                            var results = from h in hiddenViewsList
                                          group h by h into g
                                          select new { Role = g.Key, RoleCount = g.ToList() };
                            hiddenViewsList = results.Where(r => r.RoleCount.Count == userRoles.Length).Select(r => r.Role).ToList();

                            if (hiddenViewsList.Count > default(int))
                            {
                                // set the condition for hiding the views
                                var hideViewCondition = new ConditionExpression("name", ConditionOperator.NotIn, hiddenViewsList.Distinct().ToArray());
                                query.Criteria.AddCondition(hideViewCondition);
                            }

                            if (userRoles.Length > 1)
                            {
                                if (userConfiguration != null)
                                {
                                    var userRole = userConfiguration.GetAttributeValue <string>("rb_rolename");

                                    // get the default view for the role
                                    var userRoleConfig = viewConfigurations.SingleOrDefault(v => v.GetAttributeValue <string>("rb_rolename").Equals(userRole, StringComparison.OrdinalIgnoreCase));

                                    if (userRoleConfig != null)
                                    {
                                        var defaultViewName = (string)userRoleConfig["rb_viewname"];

                                        if (!string.IsNullOrEmpty(defaultViewName))
                                        {
                                            pluginContext.SharedVariables.Add("DefaultViewName", defaultViewName);
                                        }
                                    }
                                }
                            }
                            else if (userRoles.Length == 1)
                            {
                                var defaultViewName = (string)viewConfigurations[0]["rb_viewname"];

                                if (defaultViewName != null)
                                {
                                    pluginContext.SharedVariables.Add("DefaultViewName", defaultViewName);
                                }
                            }
                        }
                    }
                    catch (FaultException <OrganizationServiceFault> ex)
                    {
                        throw ex;
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
        }
예제 #22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FilteringTargetWrapper" /> class.
 /// </summary>
 /// <param name="wrappedTarget">The wrapped target.</param>
 /// <param name="condition">The condition.</param>
 public FilteringTargetWrapper(Target wrappedTarget, ConditionExpression condition)
 {
     this.WrappedTarget       = wrappedTarget;
     this.Condition           = condition;
     this.OptimizeBufferReuse = GetType() == typeof(FilteringTargetWrapper);
 }
예제 #23
0
        /// <summary>
        /// Executes the plug-in.
        /// </summary>
        /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the
        /// <see cref="IPluginExecutionContext"/>,
        /// <see cref="IOrganizationService"/>
        /// and <see cref="ITracingService"/>
        /// </param>
        /// <remarks>
        /// For improved performance, Microsoft Dynamics CRM caches plug-in instances.
        /// The plug-in's Execute method should be written to be stateless as the constructor
        /// is not called for every invocation of the plug-in. Also, multiple system threads
        /// could execute the plug-in at the same time. All per invocation state information
        /// is stored in the context. This means that you should not use global variables in plug-ins.
        /// </remarks>
        protected void ExecuteVATUpdater(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

            // TODO: Implement your custom Plug-in business logic.

            IPluginExecutionContext context = localContext.PluginExecutionContext;
            IOrganizationService    service = localContext.OrganizationService;
            Guid      quoteProductID        = (Guid)((Entity)context.InputParameters["Target"]).Id;
            var       serviceContext        = new OrganizationServiceContext(service);
            ColumnSet set = new ColumnSet();

            set.AllColumns = true;
            var quote = service.Retrieve("quote", quoteProductID, set);

            if (context.Depth > 5)
            {
                return;
            }
            else
            {
                //First I get the base values that I need for the calculations

                var totalamount      = (Money)quote["totallineitemamount"];
                var totalamountValue = (Money)quote["totalamount"];
                var discount         = (Money)quote["totaldiscountamount"];
                var prepaymentValue  = (OptionSetValue)quote["new_prepayment"];
                var VAT         = (OptionSetValue)quote["new_vat"];
                var tax         = totalamount.Value * VAT.Value / 100;
                var pricingType = (OptionSetValue)quote["new_pricingtype"];

                var SUMOfRecommendedValues  = new Money();
                var currentRecommendedValue = new Money();

                quote["new_totalammountincludingvat"] = new Money((totalamount.Value) + tax);
                quote["new_prepayedamount"]           = new Money((prepaymentValue.Value * totalamountValue.Value) / 100);

                ConditionExpression condition = new ConditionExpression();
                condition.AttributeName = "quoteid";
                condition.Operator      = ConditionOperator.Equal;
                condition.Values.Add(quoteProductID);

                FilterExpression filter = new FilterExpression();
                filter.AddCondition(condition);

                QueryExpression query = new QueryExpression();
                query.EntityName = "quotedetail";
                query.ColumnSet  = new ColumnSet(true);
                query.Criteria   = filter;

                EntityCollection quotedetails = service.RetrieveMultiple(query);

                foreach (var detail in quotedetails.Entities)
                {
                    var quantity             = (decimal)detail["quantity"];
                    var priceperunit         = (Money)detail["priceperunit"];
                    var teamleader           = (OptionSetValue)detail["new_tldiscount"];
                    var manualdiscountamount = (Money)detail.Attributes["manualdiscountamount"];
                    var baseamount           = (Money)detail["baseamount"];

                    //finally I calculate the tax
                    detail["new_vat"] = new OptionSetValue(VAT.Value);
                    var taxDetail = (baseamount.Value - manualdiscountamount.Value) * VAT.Value / 100;
                    detail.Attributes["tax"] = new Money(taxDetail); //tax

                    service.Update(detail);

                    if (pricingType.Value == 2)
                    {
                        if (detail.Contains("new_recommendedvalue"))
                        {
                            currentRecommendedValue       = (Money)detail["new_recommendedvalue"];
                            SUMOfRecommendedValues.Value += ((currentRecommendedValue.Value * quantity) - manualdiscountamount.Value);
                        }
                        else
                        {
                            currentRecommendedValue       = new Money(priceperunit.Value * quantity);
                            SUMOfRecommendedValues.Value += (currentRecommendedValue.Value - manualdiscountamount.Value);
                        }
                    }
                    else if (pricingType.Value == 3)
                    {
                        if (detail.Contains("new_fixedpriceplusratio"))
                        {
                            currentRecommendedValue       = (Money)detail["new_fixedpriceplusratio"];
                            SUMOfRecommendedValues.Value += ((currentRecommendedValue.Value * quantity) - manualdiscountamount.Value);
                        }
                        else
                        {
                            currentRecommendedValue       = new Money(priceperunit.Value * quantity);
                            SUMOfRecommendedValues.Value += (currentRecommendedValue.Value - manualdiscountamount.Value);
                        }
                    }
                    else
                    {
                        if (detail.Contains("baseamount"))
                        {
                            currentRecommendedValue       = (Money)detail["baseamount"];
                            SUMOfRecommendedValues.Value += currentRecommendedValue.Value;
                        }
                        else
                        {
                            currentRecommendedValue       = new Money();
                            SUMOfRecommendedValues.Value += currentRecommendedValue.Value;
                        }
                    }

                    //I retrieve the new_recommendedvalue after the detail is updated because I don't want to update it
                    //currentRecommendedValue = (Money)detail["new_recommendedvalue"];
                    //SUMOfRecommendedValues.Value += currentRecommendedValue.Value;
                }
                quote["new_recommendedtotal"] = new Money(SUMOfRecommendedValues.Value);

                service.Update(quote);
            }
        }
예제 #24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FilteringTargetWrapper" /> class.
 /// </summary>
 /// <param name="name">Name of the target.</param>
 /// <param name="wrappedTarget">The wrapped target.</param>
 /// <param name="condition">The condition.</param>
 public FilteringTargetWrapper(string name, Target wrappedTarget, ConditionExpression condition)
     : this(wrappedTarget, condition)
 {
     this.Name = name;
 }
예제 #25
0
        public void GateActivity_Execute_GivenPassingConditionsOnFirstGateAndFailingSecondGate_ExpectDetailedLog()
        {
            var firstGateId  = Guid.NewGuid();
            var secondGateId = Guid.NewGuid();

            var failingCondition = new ConditionExpression
            {
                Left = "[[somebob]]",
                Cond = new ConditionMatch {
                    MatchType = enDecisionType.IsEqual, Right = "notbob"
                }
            };
            var failingConditions = new List <ConditionExpression>();

            failingConditions.Add(failingCondition);

            var thirdNode  = new Mock <IDev2Activity>().Object;
            var secondGate = new GateActivity
            {
                UniqueID          = secondGateId.ToString(),
                RetryEntryPointId = firstGateId,
                Conditions        = failingConditions,
                NextNodes         = new List <IDev2Activity> {
                    thirdNode
                },
            };

            //---------------Set up test pack-------------------
            var passingCondition = new ConditionExpression
            {
                Left = "[[a]]",
                Cond = new ConditionMatch {
                    MatchType = enDecisionType.IsEqual, Right = "bob"
                }
            };
            var passingConditions = new List <ConditionExpression>();

            passingConditions.Add(passingCondition);

            //------------Setup for test--------------------------
            var firstGate = new GateActivity
            {
                UniqueID   = firstGateId.ToString(),
                Conditions = passingConditions,
                NextNodes  = new List <IDev2Activity> {
                    secondGate
                },
                GateOptions = new GateOptions()
                {
                    GateOpts = new Continue()
                }
            };

            var mockStateNotifier = new Mock <IStateNotifier>();

            mockStateNotifier.Setup(stateNotifier => stateNotifier.LogActivityExecuteState(It.IsAny <IDev2Activity>()));

            firstGate.SetStateNotifier(mockStateNotifier.Object);

            var dataObject = new DsfDataObject("", Guid.NewGuid());

            dataObject.Environment.Assign("[[a]]", "bob", 0);

            var result = firstGate.Execute(dataObject, 0);

            dataObject.Environment.Assign("[[a]]", "ralph", 0);

            Assert.AreEqual("ralph", dataObject.Environment.EvalAsListOfStrings("[[a]]", 0)[0]);
            Assert.AreEqual(secondGate, result);

            result = result.Execute(dataObject, 0);

            Assert.AreEqual(firstGate, result);

            result = result.Execute(dataObject, 0);

            Assert.AreEqual("bob", dataObject.Environment.EvalAsListOfStrings("[[a]]", 0)[0]);
            Assert.AreEqual(secondGate, result);

            dataObject.Environment.Assign("[[somebob]]", "notbob", 0);

            result = result.Execute(dataObject, 0);

            Assert.AreEqual(thirdNode, result);

            mockStateNotifier.Verify(o => o.LogActivityExecuteState(It.IsAny <IDev2Activity>()), Times.Exactly(2));
        }
예제 #26
0
        public void GateActivity_Execute_GivenPassingConditionsOnFirstGateAndPassingSecondGate_ExpectThirdNode()
        {
            var firstGateId      = Guid.NewGuid();
            var secondGateId     = Guid.NewGuid();
            var failingCondition = new ConditionExpression
            {
                Left = "[[somebob]]",
                Cond = new ConditionMatch {
                    MatchType = enDecisionType.IsEqual, Right = "another bob"
                }
            };
            var failingConditions = new List <ConditionExpression>();

            failingConditions.Add(failingCondition);

            var thirdNode  = new Mock <IDev2Activity>().Object;
            var secondGate = new GateActivity
            {
                UniqueID          = secondGateId.ToString(),
                RetryEntryPointId = firstGateId,
                Conditions        = failingConditions,
                NextNodes         = new List <IDev2Activity> {
                    thirdNode
                },
            };

            //---------------Set up test pack-------------------
            var passingCondition = new ConditionExpression
            {
                Left = "[[a]]",
                Cond = new ConditionMatch {
                    MatchType = enDecisionType.IsEqual, Right = "bob"
                }
            };
            var passingConditions = new List <ConditionExpression>();

            passingConditions.Add(passingCondition);

            //------------Setup for test--------------------------
            var firstGate = new GateActivity
            {
                UniqueID   = firstGateId.ToString(),
                Conditions = passingConditions,
                NextNodes  = new List <IDev2Activity> {
                    secondGate
                },
            };

            var dataObject = new DsfDataObject("", Guid.NewGuid());

            dataObject.Environment.Assign("[[a]]", "bob", 0);

            var result = firstGate.Execute(dataObject, 0);

            Assert.AreEqual(secondGate, result);

            dataObject.Environment.Assign("[[somebob]]", "another bob", 0);
            result = result.Execute(dataObject, 0);

            Assert.AreEqual(thirdNode, result);
        }
예제 #27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ConditionNotExpression" /> class.
 /// </summary>
 /// <param name="expression">The expression.</param>
 public ConditionNotExpression(ConditionExpression expression)
 {
     this.Expression = expression;
 }
예제 #28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ConsoleRowHighlightingRule" /> class.
 /// </summary>
 /// <param name="condition">The condition.</param>
 /// <param name="foregroundColor">Color of the foreground.</param>
 /// <param name="backgroundColor">Color of the background.</param>
 public ConsoleRowHighlightingRule(ConditionExpression condition, ConsoleOutputColor foregroundColor, ConsoleOutputColor backgroundColor)
 {
     Condition       = condition;
     ForegroundColor = foregroundColor;
     BackgroundColor = backgroundColor;
 }
예제 #29
0
        /// <summary>
        /// Executes the plug-in.
        /// </summary>
        /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the
        /// <see cref="IPluginExecutionContext"/>,
        /// <see cref="IOrganizationService"/>
        /// and <see cref="ITracingService"/>
        /// </param>
        /// <remarks>
        /// For improved performance, Microsoft Dynamics CRM caches plug-in instances.
        /// The plug-in's Execute method should be written to be stateless as the constructor
        /// is not called for every invocation of the plug-in. Also, multiple system threads
        /// could execute the plug-in at the same time. All per invocation state information
        /// is stored in the context. This means that you should not use global variables in plug-ins.
        /// </remarks>
        protected void ExecuteInvoiceVATer(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

            // TODO: Implement your custom Plug-in business logic.

            IPluginExecutionContext context = localContext.PluginExecutionContext;
            IOrganizationService    service = localContext.OrganizationService;
            Guid      invoiceID             = (Guid)((Entity)context.InputParameters["Target"]).Id;
            ColumnSet set = new ColumnSet();

            set.AllColumns = true;
            var invoice = service.Retrieve("invoice", invoiceID, set);


            if (context.Depth > 1)
            {
                return;
            }
            else
            {
                var totalamount = (Money)invoice["totallineitemamount"];
                var discount    = (Money)invoice["totaldiscountamount"];

                var VAT = (OptionSetValue)invoice["new_vat"];
                var tax = totalamount.Value * VAT.Value / 100;

                ConditionExpression condition = new ConditionExpression();
                condition.AttributeName = "invoiceid";
                condition.Operator      = ConditionOperator.Equal;
                condition.Values.Add(invoiceID);

                FilterExpression filter = new FilterExpression();
                filter.AddCondition(condition);

                QueryExpression query = new QueryExpression();
                query.EntityName = "invoicedetail";
                query.ColumnSet  = new ColumnSet(true);
                query.Criteria   = filter;

                EntityCollection invoicedetails = service.RetrieveMultiple(query);

                foreach (var detail in invoicedetails.Entities)
                {
                    bool isLocked = (bool)detail.Attributes["invoiceispricelocked"];

                    if (isLocked)
                    {
                        //It is really important to unlock both the Invoice and the Order!
                        UnlockInvoicePricingRequest unlockInvoice = new UnlockInvoicePricingRequest();
                        unlockInvoice.InvoiceId = ((EntityReference)detail.Attributes["invoiceid"]).Id;
                        UnlockInvoicePricingResponse unlockInvoiceResponse = (UnlockInvoicePricingResponse)service.Execute(unlockInvoice);
                    }

                    var quantity     = (decimal)detail["quantity"];
                    var priceperunit = (Money)detail["priceperunit"];
                    var teamleader   = (OptionSetValue)detail["new_tldiscount"];

                    //Then I calculate the manual discount and baseamount, for the further calculations
                    detail.Attributes["manualdiscountamount"] = new Money((priceperunit.Value * teamleader.Value / 100) * quantity);
                    var manualdiscountamount = (Money)detail.Attributes["manualdiscountamount"];
                    detail.Attributes["baseamount"] = new Money(priceperunit.Value * quantity);
                    var baseamount = (Money)detail["baseamount"];

                    //finally I calculate the tax
                    detail["new_vat"] = new OptionSetValue(VAT.Value);
                    var taxDetail = (baseamount.Value - manualdiscountamount.Value) * VAT.Value / 100;
                    detail.Attributes["tax"] = new Money(taxDetail); //tax

                    service.Update(detail);
                }

                invoice["new_totalamountincludingvat"] = new Money((totalamount.Value - discount.Value) + tax);

                service.Update(invoice);
            }
        }
예제 #30
0
        public static void AssertFilterExpressionContion(string attributeName, string filterOperator, object value, ConditionExpression condition)
        {
            // var condition = filterExpression.Conditions[position];
            switch (filterOperator)
            {
            case "=":
                Assert.That(condition.Operator, Is.EqualTo(ConditionOperator.Equal));
                Assert.That(condition.Values, Contains.Item(value));
                break;

            case "<>":
                Assert.That(condition.Operator, Is.EqualTo(ConditionOperator.NotEqual));
                Assert.That(condition.Values, Contains.Item(value));
                break;

            case ">":
                Assert.That(condition.Operator, Is.EqualTo(ConditionOperator.GreaterThan));
                Assert.That(condition.Values, Contains.Item(value));
                break;

            case "<":
                Assert.That(condition.Operator, Is.EqualTo(ConditionOperator.LessThan));
                Assert.That(condition.Values, Contains.Item(value));
                break;

            case ">=":
                Assert.That(condition.Operator, Is.EqualTo(ConditionOperator.GreaterEqual));
                Assert.That(condition.Values, Contains.Item(value));
                break;

            case "<=":
                Assert.That(condition.Operator, Is.EqualTo(ConditionOperator.LessEqual));
                Assert.That(condition.Values, Contains.Item(value));
                break;

            case "IS NULL":
                Assert.That(condition.Operator, Is.EqualTo(ConditionOperator.Null));
                Assert.That(condition.Values, Is.Empty);
                break;

            case "IS NOT NULL":
                Assert.That(condition.Operator, Is.EqualTo(ConditionOperator.NotNull));
                Assert.That(condition.Values, Is.Empty);
                break;

            case "LIKE":
                if (value != null)
                {
                    bool startsWith = false;
                    bool endsWith   = false;
                    var  stringVal  = value.ToString();
                    startsWith = stringVal.EndsWith("%");
                    endsWith   = stringVal.StartsWith("%");
                    if (startsWith && !endsWith)
                    {
                        // starts with..
                        var actualValue = stringVal.Remove(stringVal.Length - 1, 1);
                        Assert.That(condition.Operator,
                                    Is.EqualTo(ConditionOperator.BeginsWith));
                        Assert.That(condition.Values, Contains.Item(actualValue));
                    }
                    else if (endsWith && !startsWith)
                    {
                        // ends with
                        var actualValue = stringVal.Remove(0, 1);
                        Assert.That(condition.Operator, Is.EqualTo(ConditionOperator.EndsWith));
                        Assert.That(condition.Values, Contains.Item(actualValue));
                    }
                    else
                    {
                        // like (will also do contains)
                        Assert.That(condition.Operator, Is.EqualTo(ConditionOperator.Like));
                        Assert.That(condition.Values, Contains.Item(value));
                    }
                }
                else
                {
                    Assert.Fail("Unhandled test case data");
                }

                break;

            case "NOT LIKE":
                if (value != null)
                {
                    bool startsWith = false;
                    bool endsWith   = false;
                    var  stringVal  = value.ToString();
                    startsWith = stringVal.EndsWith("%");
                    endsWith   = stringVal.StartsWith("%");
                    if (startsWith && !endsWith)
                    {
                        // starts with..
                        var actualValue = stringVal.Remove(stringVal.Length - 1, 1);
                        Assert.That(condition.Operator,
                                    Is.EqualTo(ConditionOperator.DoesNotBeginWith));
                        Assert.That(condition.Values, Contains.Item(actualValue));
                    }
                    else if (endsWith && !startsWith)
                    {
                        // ends with
                        var actualValue = stringVal.Remove(0, 1);
                        Assert.That(condition.Operator,
                                    Is.EqualTo(ConditionOperator.DoesNotEndWith));
                        Assert.That(condition.Values, Contains.Item(actualValue));
                    }
                    else
                    {
                        // not like (will also do not contains)
                        Assert.That(condition.Operator,
                                    Is.EqualTo(ConditionOperator.NotLike));
                        Assert.That(condition.Values, Contains.Item(value));
                    }
                }
                else
                {
                    Assert.Fail("Unhandled test case data");
                }
                break;

            case "IN":
                Assert.That(condition.Operator, Is.EqualTo(ConditionOperator.In));
                if (value != null && value.GetType().IsArray)
                {
                    foreach (var val in value as Array)
                    {
                        Guid guidVal;
                        if (val is string)
                        {
                            if (Guid.TryParse(val as string, out guidVal))
                            {
                                Assert.That(condition.Values, Contains.Item(guidVal));
                                continue;
                            }
                        }

                        Assert.That(condition.Values, Contains.Item(val));
                    }
                }
                else
                {
                    Assert.Fail("Unhandled test case for IN expression.");
                }
                break;

            case "NOT IN":
                Assert.That(condition.Operator, Is.EqualTo(ConditionOperator.NotIn));
                if (value != null && value.GetType().IsArray)
                {
                    foreach (var val in value as Array)
                    {
                        Guid guidVal;
                        if (val is string)
                        {
                            if (Guid.TryParse(val as string, out guidVal))
                            {
                                Assert.That(condition.Values, Contains.Item(guidVal));
                                continue;
                            }
                        }

                        Assert.That(condition.Values, Contains.Item(val));
                    }
                }
                else
                {
                    Assert.Fail("Unhandled test case for IN expression.");
                }

                break;

            case "CONTAINS":
                Assert.That(condition.Operator, Is.EqualTo(ConditionOperator.Contains));
                Assert.That(condition.Values, Contains.Item(value));
                break;

            case "NOT CONTAINS":
                Assert.That(condition.Operator, Is.EqualTo(ConditionOperator.DoesNotContain));
                Assert.That(condition.Values, Contains.Item(value));
                break;

            default:
                Assert.Fail("Unhandled test case.");
                break;
            }

            Assert.That(condition.AttributeName, Is.EqualTo(attributeName));
        }
예제 #31
0
        public List <T> FindBy(BaseExpression condition, BaseExpression order = null, BaseExpression limit = null)
        {
            List <T> ret = new List <T> ();

            if (0 == this.recordList.Count)
            {
                return(ret);
            }
            List <ConditionExpression> conditionList = new List <ConditionExpression>();

            if (condition is AndExpression || condition is OrExpression)
            {
                MultiConditionExpression mcexp = condition as MultiConditionExpression;
                conditionList = mcexp.conditionList;
            }
            else
            {
                ConditionExpression cexp = condition as ConditionExpression;
                conditionList.Add(cexp);
            }
            foreach (T record in this.recordList)
            {
                bool add = false;
                foreach (ConditionExpression cexp in conditionList)
                {
                    PropertyInfo pinfo = record.GetType().GetProperty(cexp.fieldName);
                    object       value = pinfo.GetValue(record, null);
                    if (cexp.comparisonOperator.Equals("=="))
                    {
                        add = cexp.field.Equal(value);
                    }
                    else if (cexp.comparisonOperator.Equals("!="))
                    {
                        add = !cexp.field.Equal(value);
                    }
                    else if (cexp.comparisonOperator.Equals(">"))
                    {
                        add = cexp.field.MoreThan(value);
                    }
                    else if (cexp.comparisonOperator.Equals(">="))
                    {
                        add = cexp.field.MoreThanEqual(value);
                    }
                    else if (cexp.comparisonOperator.Equals("<"))
                    {
                        add = cexp.field.LessThan(value);
                    }
                    else if (cexp.comparisonOperator.Equals("<="))
                    {
                        add = cexp.field.LessThanEqual(value);
                    }
                    if (condition is AndExpression && false == add)
                    {
                        break;
                    }
                    else if (condition is OrExpression && false != add)
                    {
                        break;
                    }
                }
                if (false != add)
                {
                    ret.Add(record);
                }
            }
            if (1 < ret.Count)
            {
                if (null != order && order is OrderByExpression)
                {
                    OrderByExpression orderExpression = order as OrderByExpression;
                    ret = this.OrderBy(orderExpression.orderFieldName, ret, orderExpression.orderType);
                }
                if (null != limit && limit is LimitExpression)
                {
                    LimitExpression limitExpression = limit as LimitExpression;
                    ret = this.Limit(ret, limitExpression.limit);
                }
            }
            return(ret);
        }
예제 #32
0
        public static DataCollection <Entity> RetrieveMultiple(IOrganizationService service, string entityName, ColumnSet columnSet, ConditionExpression condition, LogicalOperator logicalOperator = LogicalOperator.And)
        {
            List <ConditionExpression> conditions = new List <ConditionExpression>()
            {
                condition
            };

            return(RetrieveMultiple(service, entityName, columnSet, conditions, logicalOperator));
        }
예제 #33
0
        public override string[] GetUsersInRole(string roleName)
        {
            Assert.ArgumentNotNull(roleName, "roleName");

            const string GetUsersInRoleKey = "getUsersInRole";

            ConditionalLog.Info(string.Format("GetUsersInRole({0}). Started.", roleName), this, TimerAction.Start, GetUsersInRoleKey);

            var users = this.CacheService.MembersCache.Get(roleName);

            if (users != null)
            {
                ConditionalLog.Info(string.Format("GetUsersInRole({0}). Finished (users have been retrieved from cache).", roleName), this, TimerAction.Stop, GetUsersInRoleKey);
                return(users.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries));
            }

            var contactStateCodeConditionExpression = new ConditionExpression();

            contactStateCodeConditionExpression.AttributeName = "statecode";
            contactStateCodeConditionExpression.Operator      = ConditionOperator.Equal;
            contactStateCodeConditionExpression.Values.Add("Active");

            var contactUniquePropertyNotNullConditionExpression = new ConditionExpression();

            contactUniquePropertyNotNullConditionExpression.AttributeName = Configuration.Settings.UniqueKeyProperty;
            contactUniquePropertyNotNullConditionExpression.Operator      = ConditionOperator.NotNull;

            var contactUniquePropertyNotEmptyConditionExpression = new ConditionExpression();

            contactUniquePropertyNotEmptyConditionExpression.AttributeName = Configuration.Settings.UniqueKeyProperty;
            contactUniquePropertyNotEmptyConditionExpression.Operator      = ConditionOperator.NotEqual;
            contactUniquePropertyNotEmptyConditionExpression.Values.Add(string.Empty);

            var contactFilterExpression = new FilterExpression();

            contactFilterExpression.Conditions.AddRange(
                contactStateCodeConditionExpression,
                contactUniquePropertyNotNullConditionExpression,
                contactUniquePropertyNotEmptyConditionExpression);
            contactFilterExpression.FilterOperator = LogicalOperator.And;

            var listNameConditionExpression = new ConditionExpression();

            listNameConditionExpression.AttributeName = "listname";
            listNameConditionExpression.Operator      = ConditionOperator.Equal;
            listNameConditionExpression.Values.Add(roleName);

            var listFilterExpression = new FilterExpression();

            listFilterExpression.Conditions.Add(listNameConditionExpression);
            listFilterExpression.FilterOperator = LogicalOperator.And;

            var listMemberListLinkEntity = new LinkEntity();

            listMemberListLinkEntity.JoinOperator          = JoinOperator.Inner;
            listMemberListLinkEntity.LinkCriteria          = listFilterExpression;
            listMemberListLinkEntity.LinkFromAttributeName = "listid";
            listMemberListLinkEntity.LinkFromEntityName    = "listmember";
            listMemberListLinkEntity.LinkToAttributeName   = "listid";
            listMemberListLinkEntity.LinkToEntityName      = "list";

            var contactListMemberLinkEntity = new LinkEntity();

            contactListMemberLinkEntity.JoinOperator = JoinOperator.Inner;
            contactListMemberLinkEntity.LinkEntities.Add(listMemberListLinkEntity);
            contactListMemberLinkEntity.LinkFromAttributeName = "contactid";
            contactListMemberLinkEntity.LinkFromEntityName    = "contact";
            contactListMemberLinkEntity.LinkToAttributeName   = "entityid";
            contactListMemberLinkEntity.LinkToEntityName      = "listmember";

            var pagingInfo = new PagingInfo();

            pagingInfo.Count      = Configuration.Settings.FetchThrottlingPageSize;
            pagingInfo.PageNumber = 1;

            var queryExpression = new QueryExpression();

            queryExpression.ColumnSet  = new ColumnSet(Configuration.Settings.UniqueKeyProperty);
            queryExpression.Criteria   = contactFilterExpression;
            queryExpression.EntityName = "contact";
            queryExpression.LinkEntities.Add(contactListMemberLinkEntity);
            queryExpression.PageInfo = pagingInfo;
            queryExpression.NoLock   = true;
            queryExpression.Distinct = false;

            var request = new RetrieveMultipleRequest();

            request.Query = queryExpression;

            var result = new HashSet <string>();

            try
            {
                while (true)
                {
                    var response = (RetrieveMultipleResponse)this.organizationServiceCache.GetOrganizationService().Execute(request);
                    if ((response != null) && (response.EntityCollection != null))
                    {
                        ConditionalLog.Info(string.Format("GetUsersInRole({0}). Retrieved {1} users from CRM.", roleName, response.EntityCollection.Entities.Count), this, TimerAction.Tick, GetUsersInRoleKey);

                        foreach (var entity in response.EntityCollection.Entities)
                        {
                            result.Add((string)entity[Configuration.Settings.UniqueKeyProperty]);
                        }

                        if (response.EntityCollection.MoreRecords)
                        {
                            pagingInfo.PageNumber++;
                            pagingInfo.PagingCookie = response.EntityCollection.PagingCookie;
                        }
                        else
                        {
                            break;
                        }
                    }
                }

                this.CacheService.MembersCache.Add(roleName, string.Join("|", result.ToArray()));
            }
            catch (Exception e)
            {
                ConditionalLog.Error(string.Format("Couldn't get contacts of {0} marketing list from CRM.", roleName), e, this);
            }

            ConditionalLog.Info(string.Format("GetUsersInRole({0}). Finished.", roleName), this, TimerAction.Stop, GetUsersInRoleKey);
            return(result.ToArray());
        }
예제 #34
0
 bool CheckDuplicateGroupID(IOrganizationService service, string EntityName, string AttributeName, string ValuesCheck, string ColumnName)
 {
     var qe = new QueryExpression(EntityName);
     string[] col = { ColumnName };
      qe.ColumnSet = new ColumnSet(col);
     ConditionExpression con = new ConditionExpression();
     con.AttributeName = AttributeName;
     con.Operator = ConditionOperator.Equal;
     con.Values.Add(ValuesCheck);
     qe.Criteria.Conditions.Add(con);
     EntityCollection ens = service.RetrieveMultiple(qe);
     if (ens != null && ens.Entities.Count > 0)
     {
         OutIDcheck.Append(ens.Entities[0].Id.ToString());
         return true;
     }
     else
         return false;
 }
예제 #35
0
        public override bool IsUserInRole(string userName, string roleName)
        {
            Assert.ArgumentNotNull(userName, "userName");
            Assert.ArgumentNotNull(roleName, "roleName");

            const string IsUserInRoleKey = "isUserInRole";

            ConditionalLog.Info(String.Format("IsUserInRole({0}, {1}). Started.", userName, roleName), this, TimerAction.Start, IsUserInRoleKey);

            var contactUniquePropertyConditionExpression = new ConditionExpression();

            contactUniquePropertyConditionExpression.AttributeName = Configuration.Settings.UniqueKeyProperty;
            contactUniquePropertyConditionExpression.Operator      = ConditionOperator.Equal;
            contactUniquePropertyConditionExpression.Values.Add(userName);

            var contactStateCodeConditionExpression = new ConditionExpression();

            contactStateCodeConditionExpression.AttributeName = "statecode";
            contactStateCodeConditionExpression.Operator      = ConditionOperator.Equal;
            contactStateCodeConditionExpression.Values.Add("Active");

            var contactFilterExpression = new FilterExpression();

            contactFilterExpression.Conditions.AddRange(
                contactUniquePropertyConditionExpression,
                contactStateCodeConditionExpression);
            contactFilterExpression.FilterOperator = LogicalOperator.And;

            var listNameConditionExpression = new ConditionExpression();

            listNameConditionExpression.AttributeName = "listname";
            listNameConditionExpression.Operator      = ConditionOperator.Equal;
            listNameConditionExpression.Values.Add(roleName);

            var listFilterExpression = new FilterExpression();

            listFilterExpression.Conditions.Add(listNameConditionExpression);
            listFilterExpression.FilterOperator = LogicalOperator.And;

            var listMemberListLinkEntity = new LinkEntity();

            listMemberListLinkEntity.JoinOperator          = JoinOperator.Inner;
            listMemberListLinkEntity.LinkCriteria          = listFilterExpression;
            listMemberListLinkEntity.LinkFromAttributeName = "listid";
            listMemberListLinkEntity.LinkFromEntityName    = "listmember";
            listMemberListLinkEntity.LinkToAttributeName   = "listid";
            listMemberListLinkEntity.LinkToEntityName      = "list";

            var contactListMemberLinkEntity = new LinkEntity();

            contactListMemberLinkEntity.JoinOperator = JoinOperator.Inner;
            contactListMemberLinkEntity.LinkEntities.Add(listMemberListLinkEntity);
            contactListMemberLinkEntity.LinkFromAttributeName = "contactid";
            contactListMemberLinkEntity.LinkFromEntityName    = "contact";
            contactListMemberLinkEntity.LinkToAttributeName   = "entityid";
            contactListMemberLinkEntity.LinkToEntityName      = "listmember";

            var queryExpression = new QueryExpression();

            queryExpression.ColumnSet  = new ColumnSet(Configuration.Settings.UniqueKeyProperty);
            queryExpression.Criteria   = contactFilterExpression;
            queryExpression.EntityName = "contact";
            queryExpression.LinkEntities.Add(contactListMemberLinkEntity);
            queryExpression.NoLock   = true;
            queryExpression.Distinct = false;

            var request = new RetrieveMultipleRequest();

            request.Query = queryExpression;

            try
            {
                var response = (RetrieveMultipleResponse)this.organizationServiceCache.GetOrganizationService().Execute(request);
                if ((response != null) && (response.EntityCollection != null) && (response.EntityCollection.Entities.Count != 0))
                {
                    return(true);
                }
            }
            catch (Exception e)
            {
                ConditionalLog.Error(String.Format("Couldn't get {0} contact and {1} marketing list from CRM.", userName, roleName), e, this);
            }
            finally
            {
                ConditionalLog.Info(String.Format("IsUserInRole({0}, {1}). Finished.", userName, roleName), this, TimerAction.Stop, IsUserInRoleKey);
            }

            return(false);
        }
        public static Quote GetQuoteByPlatformId(this IOrganizationService service, int quoteId, IEnumerable<string> columnsToLoad = null)
        {
            // The double "t" is important in "xv_plattformid" here, that's why we do not use ConditionExpressionHelper.CreatePlatformIdEqualsCondition
            var platformIdCondition = new ConditionExpression
            {
                AttributeName = "xv_plattformid",
                Operator = ConditionOperator.Equal
            };

            platformIdCondition.Values.Add(quoteId);

            var filter = new FilterExpression();
            filter.Conditions.Add(platformIdCondition);

            var query = CreateQuery(Quote.EntityLogicalName, filter, columnsToLoad);

            var quote = service.RetrieveMultiple(query).Entities
                .FirstOrDefault();

            if (quote == null)
            {
                throw new CrmEntityNotFoundException("Quote not found.");
            }

            return (Quote)quote;
        }
예제 #37
0
        /// <summary>
        /// Perform the main action of the sample - issuing a BulkDeleteRequest.
        /// </summary>
        /// <param name="useRecurrence">
        /// whether or not to create a recurring BulkDeleteRequest.
        /// </param>
        private void PerformBulkDelete(bool useRecurrence, bool promptToDelete)
        {
            try
            {
                Console.WriteLine("Performing Bulk Delete Operation");

                // Query for a system user to send an email to after the bulk delete
                // operation completes.
                var userRequest = new WhoAmIRequest();
                var userResponse = (WhoAmIResponse)_serviceProxy.Execute(userRequest);
                Guid currentUserId = userResponse.UserId;

                Console.WriteLine("  Requesting user retrieved.");

                // Create a condition for a bulk delete request.
                // NOTE: If no records are found that match this condition, the bulk delete
                // will not fail.  It will succeed with 0 successes and 0 failures.
                var deleteCondition = new ConditionExpression(
                    "name", ConditionOperator.Equal, "Fourth Coffee");

                // Create a fiter expression for the bulk delete request.
                var deleteFilter = new FilterExpression();
                deleteFilter.Conditions.Add(deleteCondition);

                // Create the bulk delete query set.
                var bulkDeleteQuery = new QueryExpression
                {
                    EntityName = Account.EntityLogicalName,
                    Distinct = false,
                    Criteria = deleteFilter
                };

                // Create the bulk delete request.
                var bulkDeleteRequest = new BulkDeleteRequest
                {
                    JobName = "Sample Bulk Delete",
                    QuerySet = new[] { bulkDeleteQuery },
                    StartDateTime = DateTime.Now,
                    ToRecipients = new[] { currentUserId },
                    CCRecipients = new Guid[] {},
                    SendEmailNotification = true,
                    RecurrencePattern = String.Empty
                    
                };

                // Create a recurring BulkDeleteOperation.
                if (useRecurrence)
                {
                    bulkDeleteRequest.RecurrencePattern = "FREQ=DAILY;INTERVAL=1;";
                }

                // Submit the bulk delete job.
                // NOTE: Because this is an asynchronous operation, the response will be
                // immediate.
                var bulkDeleteResponse =
                    (BulkDeleteResponse)_serviceProxy.Execute(bulkDeleteRequest);
                _asyncOperationId = bulkDeleteResponse.JobId;

                Console.WriteLine("  The Bulk Delete Request was made and the Bulk\n" +
                                  "    Delete Operation should be created.");

                // To monitor the asynchronous operation, retrieve the
                // bulkdeleteoperation object.
                // NOTE: There will be a period of time from when the async operation
                // request was submitted to the time when a successful query for that
                // async operation can be made.  When using plug-ins, events can be
                // subscribed to that will fire when the async operation status changes.
                var bulkQuery = new QueryByAttribute();
                bulkQuery.ColumnSet = new ColumnSet(true);
                bulkQuery.EntityName = BulkDeleteOperation.EntityLogicalName;

                // NOTE: When the bulk delete operation was submitted, the GUID that was
                // returned was the asyncoperationid, not the bulkdeleteoperationid.
                bulkQuery.Attributes.Add("asyncoperationid");
                bulkQuery.Values.Add(bulkDeleteResponse.JobId);

                // With only the asyncoperationid at this point, a RetrieveMultiple is
                // required to get the bulk delete operation created above.
                var entityCollection =
                    _serviceProxy.RetrieveMultiple(bulkQuery);
                BulkDeleteOperation createdBulkDeleteOperation = null;
                
                // When creating a recurring BulkDeleteOperation, the BulkDeleteOperation
                // will be in suspended status after the current instance has completed.
                // When creating a non-recurring BulkDeleteOperation, it will be in
                // Completed status when it is finished.
                var bulkOperationEnded = useRecurrence
                    ? BulkDeleteOperationState.Suspended
                    : BulkDeleteOperationState.Completed;

                createdBulkDeleteOperation = RetrieveBulkDeleteOperation(
                    bulkQuery, entityCollection, bulkOperationEnded);
                _bulkDeleteOperationId = createdBulkDeleteOperation.Id;

                if (createdBulkDeleteOperation != null)
                {
                    // If the BulkDeleteOperation is recurring, the status will be
                    // "Waiting" after the operation completes this instance.  If it is
                    // non-recurring, the status will be "Succeeded".
                    var bulkOperationSuccess = useRecurrence
                        ? bulkdeleteoperation_statuscode.Waiting
                        : bulkdeleteoperation_statuscode.Succeeded;

                    InspectBulkDeleteOperation(createdBulkDeleteOperation,
                        bulkOperationEnded, bulkOperationSuccess, useRecurrence);

                    DeleteRecords(promptToDelete);
                }
                else
                {
                    Console.WriteLine("  The Bulk Delete Operation could not be retrieved.");
                }
            }
            catch (System.Web.Services.Protocols.SoapException)
            {
                // Perform error handling here.
                throw;
            }
        }
예제 #38
0
 public TestStatement(ConditionExpression expression)
 {
     _expression = expression;
 }
예제 #39
0
 /// <inheritdoc />
 public override string ToDebugString()
 {
     return(I($"{ConditionExpression.ToDebugString()} ? {ThenExpression.ToDebugString()} : {ElseExpression.ToDebugString()}"));
 }
        protected static string GetConditionFetchNode(ConditionExpression condition)
        {
            var conditionOperatorString = "";
            switch (condition.Operator)
            {
                case ConditionOperator.Equal:
                    {
                        conditionOperatorString = "eq";
                        break;
                    }
                case ConditionOperator.NotEqual:
                    {
                        conditionOperatorString = "ne";
                        break;
                    }
                case ConditionOperator.In:
                    {
                        conditionOperatorString = "in";

                        break;
                    }
            }
            if (conditionOperatorString.IsNullOrWhiteSpace())
                throw new InvalidPluginExecutionException(
                    string.Format("Error Getting Condition Operator String For Operator Type {0}",
                        condition.Operator));
            if (condition.Operator == ConditionOperator.In)
            {
                var stringBuilder = new StringBuilder();
                stringBuilder.Append(string.Format("<condition attribute='{0}' operator='{1}' >",
                    condition.AttributeName,
                    conditionOperatorString));
                foreach (var value in condition.Values)
                {
                    if (value is IEnumerable<object>)
                    {
                        foreach (var nestValue in (IEnumerable<object>)value)
                            stringBuilder.Append(string.Format("<value>{0}</value>", nestValue));
                    }
                    else
                        stringBuilder.Append(string.Format("<value>{0}</value>", value));
                }
                stringBuilder.Append("</condition>");
                return stringBuilder.ToString();
            }
            return string.Format("<condition attribute='{0}' operator='{1}' value='{2}' />", condition.AttributeName,
                conditionOperatorString, condition.Values[0]);
        }
예제 #41
0
        public void TestLinks()
        {
            ConditionExpression cond = new ConditionExpression( "title", ConditionOperator.Equal, new string[] { "child" } );
            FilterExpression fe = new FilterExpression();
            fe.FilterOperator = LogicalOperator.And;
            fe.Conditions.Add( cond );

            LinkEntity le = new LinkEntity( "subject", "subject", "subjectid", "parentsubject", JoinOperator.Inner );
            le.LinkCriteria = fe;

            QueryExpression qe = new QueryExpression( "subject" );
            qe.LinkEntities.Add( le );

            BusinessEntityCollection bec = m_service.RetrieveMultiple( qe );
            Console.WriteLine( "TestLinks() found: " + bec.BusinessEntities.Count + " entity. " );
            Fest.AssertTrue( bec.BusinessEntities.Count > 0, "found more than zero entities" );
        }
 /// <summary>
 ///     ONLY IMPLEMENTED FOR OPTION SETS
 /// </summary>
 public void ClearFilters()
 {
     Filters = new ConditionExpression[0];
 }
예제 #43
0
        public void Experiment_For_Filter_Groups()
        {
            // var sql = string.Format("Select C.firstname, C.lastname From contact Where firstname Like '%ax%' ");

            var connectionString = ConfigurationManager.ConnectionStrings["CrmOrganisation"];
            var serviceProvider = new CrmServiceProvider(new ExplicitConnectionStringProviderWithFallbackToConfig() { OrganisationServiceConnectionString = connectionString.ConnectionString },
                                                         new CrmClientCredentialsProvider());

            var orgService = serviceProvider.GetOrganisationService();
            using (orgService as IDisposable)
            {

                // var request = new RetrieveMultipleRequest();
                var query = new QueryExpression("contact");
                // request.Query = query;
                query.ColumnSet.AddColumn("firstname");
                query.ColumnSet.AddColumn("lastname");
                var condition1 = new ConditionExpression("firstname", ConditionOperator.Equal, "Max");
                var condition2 = new ConditionExpression("lastname", ConditionOperator.Equal, "Planck");
                var filter1 = new FilterExpression(LogicalOperator.And);
                filter1.AddCondition(condition1);
                filter1.AddCondition(condition2);

                var condition3 = new ConditionExpression("firstname", ConditionOperator.Equal, "Albert");
                var filter2 = new FilterExpression(LogicalOperator.Or);
                filter2.AddCondition(condition3);
                filter2.AddFilter(filter1);

                query.Criteria.Filters.Clear();
                query.Criteria.AddFilter(filter2);

                var results = orgService.RetrieveMultiple(query);
                int resultCount = 0;
                foreach (var r in results.Entities)
                {
                    resultCount++;
                    Console.WriteLine(string.Format("{0} {1}", (string)r["firstname"], (string)r["lastname"]));
                }
                Console.WriteLine("There were " + resultCount + " results..");

            }
        }
예제 #44
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ConditionOrExpression" /> class.
 /// </summary>
 /// <param name="left">Left hand side of the OR expression.</param>
 /// <param name="right">Right hand side of the OR expression.</param>
 public ConditionOrExpression(ConditionExpression left, ConditionExpression right)
 {
     this.LeftExpression = left;
     this.RightExpression = right;
 }
예제 #45
0
파일: FSM.cs 프로젝트: letmefly/unity
    private Expression CreateExpression(List<Token> tokens)
    {
        Expression currExpression = null;

        if (mTokenIdx >= tokens.Count)
        {
            return currExpression;
        }

        if (tokens[mTokenIdx].mType == eTokenType.TOK_CONDITION)
        {
            currExpression = new ConditionExpression(tokens[mTokenIdx].mIndex);
            mExpressions.Add(currExpression);
        }
        else if (tokens[mTokenIdx].mType == eTokenType.TOK_OPEN_PAREN)
        {
            mTokenIdx += 1;
            currExpression = CreateExpression(tokens);
        }
        else if (tokens[mTokenIdx].mType == eTokenType.TOK_NOT)
        {
            mTokenIdx += 1;
            Expression childExpression = CreateExpression(tokens);
            Expression expression = new NotExpression(childExpression);
            mExpressions.Add(expression);
            currExpression = expression;
        }

        // Right Expressions
        if (mTokenIdx + 1 >= tokens.Count)
        {
            return currExpression;
        }

        mTokenIdx += 1;
        if (tokens[mTokenIdx].mType == eTokenType.TOK_AND)
        {
            mTokenIdx += 1;
            Expression childA = currExpression;
            Expression childB = CreateExpression(tokens);
            Expression expression = new AndExpression(childA, childB);
            mExpressions.Add(expression);
            currExpression = expression;
        }
        else if (tokens[mTokenIdx].mType == eTokenType.TOK_OR)
        {
            mTokenIdx += 1;
            Expression childA = currExpression;
            Expression childB = CreateExpression(tokens);

            Expression expression = new OrExpression(childA, childB);
            mExpressions.Add(expression);
            currExpression = expression;
        }

        return currExpression;
    }
예제 #46
0
 public virtual void VisitConditionExpression(ConditionExpression node)
 {
     Visit(node.Condition);
     Visit(node.Then);
     Visit(node.Else);
 }
예제 #47
0
 public void ClearFilters()
 {
     Filters = new ConditionExpression[0];
 }
        /// <summary>
        /// Assigns the provider to service request.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="objectIncident">The object incident.</param>
        private void AssignProviderToServiceRequest(IOrganizationService service, Entity objectIncident, ITracingService trace)
        {
            try
            {
                ////Check if building, roomtype, floor, problem class and problem type is not null. To be added, floor
                if (objectIncident.Attributes.Contains(CRMAttributesResource.ProblemBuildingIdAttribute) && objectIncident.Attributes.Contains(CRMAttributesResource.ProblemClassIdAttribute) && objectIncident.Attributes.Contains(CRMAttributesResource.ProblemTypeIdAttribute))
                {
                    ConditionExpression condBuilding = new ConditionExpression
                    {
                        AttributeName = CRMAttributesResource.BuildingIdAttribute,
                        Operator      = ConditionOperator.Equal,
                        Values        = { ((EntityReference)objectIncident.Attributes[CRMAttributesResource.ProblemBuildingIdAttribute]).Id }
                    };
                    ConditionExpression condProblemClass = new ConditionExpression
                    {
                        AttributeName = CRMAttributesResource.ProblemClassIdAttribute,
                        Operator      = ConditionOperator.Equal,
                        Values        = { ((EntityReference)objectIncident.Attributes[CRMAttributesResource.ProblemClassIdAttribute]).Id }
                    };
                    ConditionExpression condProblemType = new ConditionExpression
                    {
                        AttributeName = CRMAttributesResource.ProblemTypeIdAttribute,
                        Operator      = ConditionOperator.Equal,
                        Values        = { ((EntityReference)objectIncident.Attributes[CRMAttributesResource.ProblemTypeIdAttribute]).Id }
                    };
                    ConditionExpression condStatus = new ConditionExpression
                    {
                        AttributeName = "statuscode",
                        Operator      = ConditionOperator.Equal,
                        Values        = { 1 }
                    };
                    QueryExpression providerMatrixQuery = new QueryExpression
                    {
                        EntityName = CRMAttributesResource.ProviderMatrixEntity,
                        ColumnSet  = new ColumnSet(CRMAttributesResource.PrimaryProviderIdAttribute, CRMAttributesResource.ProviderMatrixIsApprovalRequired, CRMAttributesResource.ProviderMatrixIOCode),
                        Criteria   =
                        {
                            FilterOperator = LogicalOperator.And,
                            Conditions     = { condBuilding,     condProblemClass,condProblemType, condStatus }
                        }
                    };
                    if (service != null)
                    {
                        EntityCollection provider_Matrix = service.RetrieveMultiple(providerMatrixQuery);
                        ////Entity providerMatrix = service.RetrieveMultiple(providerMatrixQuery) == null ? null : service.RetrieveMultiple(providerMatrixQuery).Entities.FirstOrDefault();
                        Entity providerMatrix = provider_Matrix.Entities.FirstOrDefault();
                        if (providerMatrix != null)
                        {
                            if (providerMatrix.Attributes.Contains(CRMAttributesResource.PrimaryProviderIdAttribute))
                            {
                                bool   approvalRequired = false;
                                string io_Code          = string.Empty;
                                if (this.ProviderIsActive(((EntityReference)providerMatrix.Attributes[CRMAttributesResource.PrimaryProviderIdAttribute]).Id, service))
                                {
                                    if (providerMatrix.Attributes.Contains(CRMAttributesResource.ProviderMatrixIsApprovalRequired))
                                    {
                                        approvalRequired = Convert.ToBoolean(providerMatrix.Attributes[CRMAttributesResource.ProviderMatrixIsApprovalRequired], CultureInfo.CurrentCulture);
                                    }
                                    else
                                    {
                                        approvalRequired = false;
                                    }

                                    if (objectIncident.Attributes.Contains(CRMAttributesResource.IoCode) == false || string.IsNullOrEmpty(Convert.ToString(objectIncident.Attributes[CRMAttributesResource.IoCode], CultureInfo.InvariantCulture)))
                                    {
                                        if (providerMatrix.Attributes.Contains(CRMAttributesResource.ProviderMatrixIOCode))
                                        {
                                            io_Code = Convert.ToString(providerMatrix.Attributes[CRMAttributesResource.ProviderMatrixIOCode], CultureInfo.InvariantCulture);
                                        }
                                        else
                                        {
                                            io_Code = string.Empty;
                                        }
                                    }

                                    this.AssignProvider(((EntityReference)providerMatrix.Attributes[CRMAttributesResource.PrimaryProviderIdAttribute]).Id, service, objectIncident, approvalRequired, io_Code, trace);
                                }
                            }
                            else
                            {
                                trace.Trace("In Default Provider as No primary Provider matrix is Found");
                                this.SetDefaultProvider(service, objectIncident);
                            }
                        }
                        else
                        {
                            trace.Trace("In Default Provider as not Provider matrix is Found");
                            this.SetDefaultProvider(service, objectIncident);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new CustomServiceManagementPortalException("Failed to assign provider with the service request on Pre Create.", ex);
            }
        }
예제 #49
0
        /// <summary>
        /// Executes the plug-in.
        /// </summary>
        /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the
        /// <see cref="IPluginExecutionContext"/>,
        /// <see cref="IOrganizationService"/>
        /// and <see cref="ITracingService"/>
        /// </param>
        /// <remarks>
        /// For improved performance, Microsoft Dynamics CRM caches plug-in instances.
        /// The plug-in's Execute method should be written to be stateless as the constructor
        /// is not called for every invocation of the plug-in. Also, multiple system threads
        /// could execute the plug-in at the same time. All per invocation state information
        /// is stored in the context. This means that you should not use global variables in plug-ins.
        /// </remarks>
        protected void ExecuteInvoiceVATer(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

            // TODO: Implement your custom Plug-in business logic.

            IPluginExecutionContext context = localContext.PluginExecutionContext;
            IOrganizationService service = localContext.OrganizationService;
            Guid invoiceID = (Guid)((Entity)context.InputParameters["Target"]).Id;
            ColumnSet set = new ColumnSet();
            set.AllColumns = true;
            var invoice = service.Retrieve("invoice", invoiceID, set);


            if (context.Depth > 1)
            {
                return;
            }
            else
            {
                var totalamount = (Money)invoice["totallineitemamount"];
                var discount = (Money)invoice["totaldiscountamount"];

                var VAT = (OptionSetValue)invoice["new_vat"];
                var tax = totalamount.Value * VAT.Value / 100;

                ConditionExpression condition = new ConditionExpression();
                condition.AttributeName = "invoiceid";
                condition.Operator = ConditionOperator.Equal;
                condition.Values.Add(invoiceID);

                FilterExpression filter = new FilterExpression();
                filter.AddCondition(condition);

                QueryExpression query = new QueryExpression();
                query.EntityName = "invoicedetail";
                query.ColumnSet = new ColumnSet(true);
                query.Criteria = filter;

                EntityCollection invoicedetails = service.RetrieveMultiple(query);

                foreach (var detail in invoicedetails.Entities)
                {
                    bool isLocked = (bool)detail.Attributes["invoiceispricelocked"];

                    if (isLocked)
                    {
                        //It is really important to unlock both the Invoice and the Order!
                        UnlockInvoicePricingRequest unlockInvoice = new UnlockInvoicePricingRequest();
                        unlockInvoice.InvoiceId = ((EntityReference)detail.Attributes["invoiceid"]).Id;
                        UnlockInvoicePricingResponse unlockInvoiceResponse = (UnlockInvoicePricingResponse)service.Execute(unlockInvoice);
                    }

                    var quantity = (decimal)detail["quantity"];
                    var priceperunit = (Money)detail["priceperunit"];
                    var teamleader = (OptionSetValue)detail["new_tldiscount"];

                    //Then I calculate the manual discount and baseamount, for the further calculations
                    detail.Attributes["manualdiscountamount"] = new Money((priceperunit.Value * teamleader.Value / 100) * quantity);
                    var manualdiscountamount = (Money)detail.Attributes["manualdiscountamount"];
                    detail.Attributes["baseamount"] = new Money(priceperunit.Value * quantity);
                    var baseamount = (Money)detail["baseamount"];

                    //finally I calculate the tax
                    detail["new_vat"] = new OptionSetValue(VAT.Value);
                    var taxDetail = (baseamount.Value - manualdiscountamount.Value) * VAT.Value / 100;
                    detail.Attributes["tax"] = new Money(taxDetail); //tax

                    service.Update(detail);
                }

                invoice["new_totalamountincludingvat"] = new Money((totalamount.Value - discount.Value) + tax);

                service.Update(invoice);
            }
        }
예제 #50
0
        internal static void UpdateContact(Entity entity, IOrganizationService service)
        {
            Guid productId     = entity.Contains("new_productid") ? ((EntityReference)entity.Attributes["new_productid"]).Id : Guid.Empty;
            Guid phoneCallId   = entity.Contains("new_phonecallid") ? ((EntityReference)entity.Attributes["new_phonecallid"]).Id : Guid.Empty;
            Guid appointmentId = entity.Contains("new_appointmentid") ? ((EntityReference)entity.Attributes["new_appointmentid"]).Id : Guid.Empty;

            if (productId == Guid.Empty)
            {
                return;
            }
            if (phoneCallId == Guid.Empty && appointmentId == Guid.Empty)
            {
                return;
            }
            Guid   contactId         = Guid.Empty;
            Entity product           = service.Retrieve("product", productId, new ColumnSet("new_unittypeid", "new_generaltypeofhomeid"));
            string unitType          = product.Contains("new_unittypeid") ? ((EntityReference)product.Attributes["new_unittypeid"]).Name : string.Empty;
            string generalTypeOfHome = product.Contains("new_generaltypeofhomeid") ? ((EntityReference)product.Attributes["new_generaltypeofhomeid"]).Name : string.Empty;

            #region GET CONTACT

            ConditionExpression con1 = new ConditionExpression();
            con1.AttributeName = "activityid";
            con1.Operator      = ConditionOperator.Equal;
            if (appointmentId != Guid.Empty)
            {
                con1.Values.Add(appointmentId);
            }
            else if (phoneCallId != Guid.Empty)
            {
                con1.Values.Add(phoneCallId);
            }

            ConditionExpression con2 = new ConditionExpression();
            con2.AttributeName = "partyobjecttypecode";
            con2.Operator      = ConditionOperator.Equal;
            con2.Values.Add(2);//Contact

            FilterExpression filter = new FilterExpression();
            filter.FilterOperator = LogicalOperator.And;
            filter.Conditions.Add(con1);
            filter.Conditions.Add(con2);

            QueryExpression Query = new QueryExpression("activityparty");
            Query.ColumnSet = new ColumnSet("partyid");
            Query.Criteria.FilterOperator = LogicalOperator.And;
            Query.Criteria.Filters.Add(filter);
            EntityCollection Result = service.RetrieveMultiple(Query);
            if (Result.Entities.Count > 0)
            {
                contactId = ((EntityReference)Result.Entities[0].Attributes["partyid"]).Id;
            }
            else
            {
                return;
            }

            #endregion GET CONTACT

            Entity c = new Entity("contact");
            c.Id = contactId;
            switch (unitType)
            {
            case "Ofis":
                c.Attributes["new_preferenceoffice"] = true;
                break;

            case "Konut":
                c.Attributes["new_preferencehome"] = true;
                break;

            case "Mağaza":
                c.Attributes["new_preferencestore"] = true;
                break;
            }
            if (generalTypeOfHome.Contains("1+1"))
            {
                c.Attributes["new_1plus1"] = true;
            }
            else if (generalTypeOfHome.Contains("2+1"))
            {
                c.Attributes["new_2plus1"] = true;
            }
            else if (generalTypeOfHome.Contains("3+1"))
            {
                c.Attributes["new_3plus1"] = true;
            }
            else if (generalTypeOfHome.Contains("4+1"))
            {
                c.Attributes["new_4plus1"] = true;
            }
            service.Update(c);
        }
        public static SalesOrder GetSalesOrderByPlatformId(this IOrganizationService service, int salesOrderId)
        {
            // The double "t" is important in "xv_plattformid" here, that's why we do not use ConditionExpressionHelper.CreatePlatformIdEqualsCondition
            var platformIdCondition = new ConditionExpression
                {
                    AttributeName = "xv_plattformid",
                    Operator = ConditionOperator.Equal
                };

            platformIdCondition.Values.Add(salesOrderId);

            var filter = new FilterExpression();
            filter.Conditions.Add(platformIdCondition);

            var query = new QueryExpression(SalesOrder.EntityLogicalName);

            query.Criteria.AddFilter(filter);

            var salesOrder = service.RetrieveMultiple(query).Entities
                .FirstOrDefault();

            if (salesOrder == null)
            {
                throw new CrmEntityNotFoundException("SalesOrder not found.");
            }

            return (SalesOrder)salesOrder;
        }
        private void AddRelationFilter(ShuffleBlocks blocks, string entityName, DataBlockRelation relation, FilterExpression filter, ILoggable log)
        {
            log.StartSection(MethodBase.GetCurrentMethod().Name);
            if (blocks != null && blocks.Count > 0)
            {
                var block       = relation.Block;
                var attribute   = relation.Attribute;
                var pkattribute = relation.PKAttribute;
                var includenull = relation.IncludeNull;

                var type = GetAttributeType(attribute, entityName);

                var cond = new ConditionExpression
                {
                    AttributeName = attribute,
                    Operator      = Microsoft.Xrm.Sdk.Query.ConditionOperator.In
                };

                var ids        = new List <object>();
                var parentcoll = blocks.ContainsKey(block) ? blocks[block] : null;
                if (parentcoll != null && parentcoll.Count > 0)
                {
                    foreach (var parent in parentcoll)
                    {
                        if (string.IsNullOrEmpty(pkattribute))
                        {
                            if (type == AttributeTypeCode.String)
                            {
                                ids.Add(parent.Id.ToString());
                            }
                            else
                            {
                                ids.Add(parent.Id);
                            }
                        }
                        else if (type == AttributeTypeCode.String)
                        {
                            ids.Add(parent.Property <EntityReference>(pkattribute, new EntityReference()).Id.ToString());
                        }
                        else
                        {
                            ids.Add(parent.Property <EntityReference>(pkattribute, new EntityReference()).Id);
                        }
                    }
                }
                else
                {
                    // Adding temp guid to indicate "no matches", as ConditionOperator.In will fail if no values are given
                    ids.Add(new Guid());
                }
                cond.Values.AddRange(ids);
                if (!includenull)
                {
                    filter.AddCondition(cond);
                }
                else
                {
                    var orfilter = new FilterExpression(LogicalOperator.Or);
                    orfilter.AddCondition(attribute, Microsoft.Xrm.Sdk.Query.ConditionOperator.Null);
                    orfilter.AddCondition(cond);
                    filter.AddFilter(orfilter);
                }
                log.Log("Adding relation condition for {0} in {1} values in {2}.{3}", attribute, ids.Count, block, pkattribute);
            }
            log.EndSection();
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ConditionAndExpression" /> class.
 /// </summary>
 /// <param name="left">Left hand side of the AND expression.</param>
 /// <param name="right">Right hand side of the AND expression.</param>
 public ConditionAndExpression(ConditionExpression left, ConditionExpression right)
 {
     this.Left = left;
     this.Right = right;
 }
예제 #54
0
        public void ImplicitOperatorTest()
        {
            ConditionExpression cond = "true and true";

            Assert.IsInstanceOfType(typeof(ConditionAndExpression), cond);
        }
예제 #55
0
        /// <summary>
        /// Executes the plug-in.
        /// </summary>
        /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the
        /// <see cref="IPluginExecutionContext"/>,
        /// <see cref="IOrganizationService"/>
        /// and <see cref="ITracingService"/>
        /// </param>
        /// <remarks>
        /// For improved performance, Microsoft Dynamics CRM caches plug-in instances.
        /// The plug-in's Execute method should be written to be stateless as the constructor
        /// is not called for every invocation of the plug-in. Also, multiple system threads
        /// could execute the plug-in at the same time. All per invocation state information
        /// is stored in the context. This means that you should not use global variables in plug-ins.
        /// </remarks>
        ///
        protected void ExecutegetPricingType(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

            // TODO: Implement your custom Plug-in business logic.

            IPluginExecutionContext context = localContext.PluginExecutionContext;
            IOrganizationService    service = localContext.OrganizationService;

            Guid      quoteDetailID = (Guid)((Entity)context.InputParameters["Target"]).Id;
            ColumnSet set           = new ColumnSet();

            set.AllColumns = true;
            var quoteDetail = service.Retrieve("quotedetail", quoteDetailID, set);

            if (context.Depth > 1)
            {
                return;
            }
            else
            {
                //var parentQuote = (Guid)quoteDetail["quoteid"];

                //var quote = service.Retrieve("quote", parentQuote, new ColumnSet(true));

                //var pricingType = (OptionSetValue)quote["new_pricingtype"];

                //quoteDetail["new_pricingtype"] = new OptionSetValue(pricingType.Value);

                var productID        = (EntityReference)quoteDetail["productid"];
                var currentProduct   = service.Retrieve(productID.LogicalName, productID.Id, new ColumnSet(true));
                var productPriceId   = (EntityReference)currentProduct["pricelevelid"];
                var priceListProduct = service.Retrieve(productPriceId.LogicalName, productPriceId.Id, set);
                //Quote & Currency
                var quoteId        = (EntityReference)quoteDetail["quoteid"];
                var parentQuote    = service.Retrieve(quoteId.LogicalName, quoteId.Id, set);
                var priceLevelId   = (EntityReference)parentQuote["pricelevelid"];
                var quotePriceList = service.Retrieve(priceLevelId.LogicalName, priceLevelId.Id, set);
                var priceCurrency  = (EntityReference)quotePriceList["transactioncurrencyid"];
                var currency       = service.Retrieve(priceCurrency.LogicalName, priceCurrency.Id, set);
                var price          = currency["currencyname"];


                //Check the productLists
                ConditionExpression condition = new ConditionExpression();
                condition.AttributeName = "productid";
                condition.Operator      = ConditionOperator.Equal;
                condition.Values.Add(productID.Id);

                //Currency check

                ConditionExpression priceType = new ConditionExpression();
                priceType.AttributeName = "transactioncurrencyid";
                priceType.Operator      = ConditionOperator.Equal;
                priceType.Values.Add(currency.Id);

                FilterExpression filter = new FilterExpression();
                //filter.FilterOperator = LogicalOperator.And;
                filter.AddCondition(condition);
                filter.AddCondition(priceType);

                QueryExpression query = new QueryExpression();
                query.EntityName = "productpricelevel";
                query.ColumnSet  = new ColumnSet(true);
                query.Criteria   = filter;

                EntityCollection productpricelevels = service.RetrieveMultiple(query);
                var productpriceLevel = productpricelevels.Entities[0];
                //var productPricing = from c in context.ContactSetjoin a in context.AccountSet on c.ContactId equals a.PrimaryContactId.Id
                var productPrice = (Money)productpriceLevel["amount"];
                var priceperunit = (Money)quoteDetail["priceperunit"];
                if (productPrice.Value > priceperunit.Value)
                {
                    quoteDetail["priceperunit"] = new Money(productPrice.Value);
                }
                //quoteDetail["new_jobdescription"] = price;
                service.Update(quoteDetail);
            }
        }
예제 #56
0
 /// <summary>
 /// Initializes a new instance of the FilteringRule class.
 /// </summary>
 /// <param name="whenExistsExpression">Condition to be tested against all events.</param>
 /// <param name="filterToApply">Filter to apply to all log events when the first condition matches any of them.</param>
 public FilteringRule(ConditionExpression whenExistsExpression, ConditionExpression filterToApply)
 {
     Exists = whenExistsExpression;
     Filter = filterToApply;
 }
예제 #57
0
        private void FillImageList()
        {
            ListViewDelegates.ClearItems(lstWebResources);

            if (webResourcesImageCache == null || webResourcesImageCache.Count == 0)
            {
                webResourcesImageCache = new List<Entity>();

                QueryExpression qe = new QueryExpression("webresource");

                ConditionExpression ce = new ConditionExpression();
                ce.AttributeName = "webresourcetype";

                if (requestedType == (int)WebResourceType.Image)
                {
                    ce.Operator = ConditionOperator.In;
                    ce.Values.AddRange(5, 6, 7);
                }
                else
                {
                    ce.Operator = ConditionOperator.Equal;
                    ce.Values.Add(requestedType);
                }

                qe.Criteria.AddCondition(ce);
                qe.ColumnSet.AllColumns = true;

                EntityCollection ec = service.RetrieveMultiple(qe);

                foreach (Entity webresource in ec.Entities)
                {
                    webResourcesImageCache.Add(webresource);
                }
            }

            foreach (Entity webresource in webResourcesImageCache)
            {
                ListViewItem item = new ListViewItem(webresource.Contains("displayname") ? webresource["displayname"].ToString() : "N/A");
                item.SubItems.Add(webresource["name"].ToString());
                item.Tag = webresource;

                ListViewDelegates.AddItem(lstWebResources, item);
            }

            ListViewDelegates.Sort(lstWebResources);
            ListViewDelegates.SetEnableState(lstWebResources, true);
            CommonDelegates.SetEnableState(btnWebResourcePickerCancel, true);
            CommonDelegates.SetEnableState(btnWebResourcePickerValidate, true);
            CommonDelegates.SetEnableState(btnNewResource, true);
            CommonDelegates.SetEnableState(btnRefresh, true);
        }
예제 #58
0
        protected ConditionExpression ConvertFunctionCallFromDynamic(dynamic filter)
        {
            var type = filter.func as string;


            var isLeftAProperty = IsPropertyType((filter.args[0].type as string));
            var isLeftALiteral  = IsLiteralType((filter.args[0].type as string));

            var isRightAProperty = IsPropertyType((filter.args[1].type as string));
            var isRightALiteral  = IsLiteralType((filter.args[1].type as string));

            if (type.Equals("substringof"))
            {
                if (!isLeftALiteral || !isRightAProperty)
                {
                    throw new Exception("Condition expression 'substringof' must have a literal in the left hand side of the expression and a property in the right hand side.");
                }
            }
            else
            {
                if (!isLeftAProperty || !isRightALiteral)
                {
                    throw new Exception("Condition expression must have a property in the left hand side of the expression and a literal in the right hand side.");
                }
            }

            string property;
            object literal;

            if (isLeftAProperty)
            {
                property = filter.args[0].name as string;
            }
            else
            {
                property = filter.args[1].name as string;
            }

            if (isLeftALiteral)
            {
                literal = filter.args[0].value as object;
            }
            else
            {
                literal = filter.args[1].value as object;
            }


            var newCondition = new ConditionExpression(property, ConditionOperator.Equal, literal);

            switch (type)
            {
            case "startswith":
                //Equals
                newCondition.Operator = ConditionOperator.BeginsWith;
                return(newCondition);

            case "endswith":
                //Equals
                newCondition.Operator = ConditionOperator.EndsWith;
                return(newCondition);

            case "substringof":
                //Equals
                literal = string.Format("%{0}%", literal);
                newCondition.Values[0] = literal;
                newCondition.Operator  = ConditionOperator.Like;
                return(newCondition);


            default:

                throw new Exception(string.Format("{0} function not yet supported", type));
            }
        }
예제 #59
0
 protected bool createStringConditionExpression(ArrayList stringParams)
 {
     try
     {
         for (int i = 0; i < stringParams.Count; i++)
         {
             ConditionExpression conditionEx = new ConditionExpression();
             ArrayList paramtab = (ArrayList)stringParams[i];
             //string[] paramtab = stringParams[i].ToString().Split('\0');
             conditionEx.AttributeName = paramtab[0].ToString();
             conditionEx.Operator = ConditionOperator.Like;
             conditionEx.Values = new object[] { paramtab[1].ToString() }; //replace object by string
             m_filterExpression.Conditions.Add(conditionEx);
         }
         return true;
     }
     catch (Exception ex)
     {
         throw new ESC_CRM_EX.createStringConditionException(ex.Message);
     }
 }
예제 #60
0
        public static void Should_Not_Fail_On_Conditions_In_Link_Entities_Multiple()
        {
            var fakedContext = new XrmFakedContext();
            var fakedService = fakedContext.GetOrganizationService();

            fakedContext.AddRelationship("new_invoicepaymentmethod_invoicedetail",
                                         new XrmFakedRelationship("new_invoicepaymentmethod_invoicedetail",
                                                                  "invoicedetailid", "new_invoicepaymentmethodid",
                                                                  "invoicedetail",
                                                                  "new_invoicepaymentmethod"));

            Entity product01 = new Entity("product");

            product01.Id = Guid.NewGuid();
            product01.Attributes.Add("name", "Test Product");

            Entity invoicedetail01 = new Entity("invoicedetail");

            invoicedetail01.Id = Guid.NewGuid();
            invoicedetail01.Attributes.Add("invoicedetailid", invoicedetail01.Id);
            invoicedetail01.Attributes.Add("new_productid", new EntityReference("product", product01.Id));

            Entity pmr01 = new Entity("new_invoicepaymentmethod");

            pmr01.Id = Guid.NewGuid();
            pmr01.Attributes.Add("new_invoicepaymentmethodid", pmr01.Id);
            pmr01.Attributes.Add("new_name", "PMR0000000001");

            Entity invoicedetail02 = new Entity("invoicedetail");

            invoicedetail02.Id = Guid.NewGuid();
            invoicedetail02.Attributes.Add("invoicedetailid", invoicedetail02.Id);
            invoicedetail02.Attributes.Add("new_productid", new EntityReference("product", product01.Id));

            Entity pmr02 = new Entity("new_invoicepaymentmethod");

            pmr02.Id = Guid.NewGuid();
            pmr02.Attributes.Add("new_invoicepaymentmethodid", pmr02.Id);
            pmr02.Attributes.Add("new_name", "PMR0000000002");

            fakedService.Create(product01);

            fakedService.Create(invoicedetail01);
            fakedService.Create(invoicedetail02);
            fakedService.Create(pmr01);
            fakedService.Create(pmr02);

            fakedService.Associate("invoicedetail", invoicedetail01.Id, new Relationship("new_invoicepaymentmethod_invoicedetail"), new EntityReferenceCollection()
            {
                pmr01.ToEntityReference()
            });
            fakedService.Associate("invoicedetail", invoicedetail02.Id, new Relationship("new_invoicepaymentmethod_invoicedetail"), new EntityReferenceCollection()
            {
                pmr02.ToEntityReference()
            });

            EntityCollection invoiceDetails = new EntityCollection();

            QueryExpression query = new QueryExpression("invoicedetail");

            query.ColumnSet = new ColumnSet(true);
            LinkEntity link1 = new LinkEntity();

            link1.JoinOperator          = JoinOperator.Natural;
            link1.LinkFromEntityName    = "invoicedetail";
            link1.LinkFromAttributeName = "invoicedetailid";
            link1.LinkToEntityName      = "new_invoicepaymentmethod_invoicedetail";
            link1.LinkToAttributeName   = "invoicedetailid";

            LinkEntity link2 = new LinkEntity();

            link2.JoinOperator          = JoinOperator.Natural;
            link2.LinkFromEntityName    = "new_invoicepaymentmethod_invoicedetail";
            link2.LinkFromAttributeName = "new_invoicepaymentmethodid";
            link2.LinkToEntityName      = "new_invoicepaymentmethod";
            link2.LinkToAttributeName   = "new_invoicepaymentmethodid";
            link2.LinkCriteria          = new FilterExpression(LogicalOperator.And);

            ConditionExpression condition1 = new ConditionExpression("new_invoicepaymentmethodid", ConditionOperator.Equal, pmr02.Id);

            link2.LinkCriteria.Conditions.Add(condition1);
            link1.LinkEntities.Add(link2);
            query.LinkEntities.Add(link1);

            invoiceDetails = fakedService.RetrieveMultiple(query);

            Assert.Equal(1, invoiceDetails.Entities.Count);
            Assert.Equal(invoicedetail02.Id, invoiceDetails.Entities[0].Id);
        }