public void When_executing_a_query_expression_with_2_filters_combined_with_an_or_filter_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);
            

            var filter1 = new FilterExpression();
            filter1.AddCondition(new ConditionExpression("fullname", ConditionOperator.Equal, "Contact 1"));

            var filter2 = new FilterExpression();
            filter2.AddCondition(new ConditionExpression("fullname", ConditionOperator.Equal, "Contact 2"));

            qe.Criteria = new FilterExpression(LogicalOperator.Or);
            qe.Criteria.AddFilter(filter1);
            qe.Criteria.AddFilter(filter2);

            var result = XrmFakedContext.TranslateQueryExpressionToLinq(context, qe).ToList();

            Assert.True(result.Count == 2);
        }
        private IEnumerable<HistoryItem> Build(HistoryRequest request, Action<ClarifyGeneric, WorkflowObjectInfo> genericAction)
        {
            var clarifyDataSet = _session.CreateDataSet();

            var workflowObjectInfo = WorkflowObjectInfo.GetObjectInfo(request.WorkflowObject.Type);
            var workflowGeneric = clarifyDataSet.CreateGenericWithFields(workflowObjectInfo.ObjectName);
            if (workflowObjectInfo.HasIDFieldName)
            {
                workflowGeneric.DataFields.Add(workflowObjectInfo.IDFieldName);
            }

            genericAction(workflowGeneric, workflowObjectInfo);

            var inverseActivityRelation = workflowObjectInfo.ActivityRelation;
            var activityRelation = _schemaCache.GetRelation("act_entry", inverseActivityRelation).InverseRelation;

            var actEntryGeneric = workflowGeneric.Traverse(activityRelation.Name);
            actEntryGeneric.AppendSort("entry_time", false);

            if (request.Since.HasValue)
            {
                var filter = new FilterExpression().MoreThan("entry_time", request.Since.Value);
                actEntryGeneric.Filter.AddFilter(filter);
            }

            var templateDictionary = _templatePolicyConfiguration.RenderPolicies(request.WorkflowObject);

            //query generic hierarchy and while using act entry templates transform the results into HistoryItems
            return _historyItemAssembler.Assemble(actEntryGeneric, templateDictionary, request);
        }
        public static EntityReference GetAccountReferenceByNameFuzzy(this IOrganizationService service, string companyName)
        {
            var name = CompanyNameHelper.RemoveCommonCompanySuffixes(companyName);
            var nameCondition = ConditionExpressionHelper.CreatePublisherNameBeginsWithCondition(name);

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

            var query = new QueryExpression(Account.EntityLogicalName);
            query.Criteria.AddFilter(filter);

            var accounts = service.RetrieveMultiple(query).Entities;

            if (accounts.Count() > 1)
            {
                throw new CrmAmbiguousMatchException(
                    string.Format("Found multiple fuzzy matches when searching for {0}.  Fuzzy match search: {1}", companyName, name));
            }

            var account = accounts.FirstOrDefault();
            if (account == null)
            {
                throw new CrmEntityNotFoundException("Account not found with name: " + companyName);
            }

            return new EntityReference(Account.EntityLogicalName, account.Id);
        }
        public virtual Expression Translate(FilterExpression filter)
        {
            Expression result;

            switch (filter.ExpressionType)
            {
                case FilterExpressionType.Constant:
                    result = TranslateConstant((ConstantFilterExpression) filter);
                    break;
                case FilterExpressionType.Unary:
                    result = TranslateUnary((UnaryFilterExpression)filter);
                    break;
                case FilterExpressionType.Binary:
                    result = TranslateBinary((BinaryFilterExpression)filter);
                    break;
                case FilterExpressionType.MethodCall:
                    result = TranslateMethodCall((MethodCallFilterExpression)filter);
                    break;
                case FilterExpressionType.MemberAccess:
                    result = TranslateMemberAccess((MemberAccessFilterExpression)filter);
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            return result;
        }
        public static EntityReference GetCompanyClassificationReferenceByName(this IOrganizationService service, string companyClassification)
        {
            Guard.ArgumentNotNullOrEmpty(companyClassification, "companyClassification");

            if (companyClassification == "Uncategorized")
            {
                return null;
            }

            var productTypeNameCondition = ConditionExpressionHelper.CreateEqualsCondition("xv_name", companyClassification);
            var filter = new FilterExpression();
            filter.Conditions.Add(productTypeNameCondition);

            var query = new QueryExpression(xv_firmenklassifizierung.EntityLogicalName);
            query.Criteria.AddFilter(filter);

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

            if (productTypeEntity == null)
            {
                throw new CrmEntityNotFoundException(string.Format("Company classification '{0}' was not found.", companyClassification));
            }

            return productTypeEntity.ToEntityReference();
        }
        public static EntityReference GetCompanyReferenceById(this IOrganizationService service, string companyName)
        {
            var compayNameCondition = ConditionExpressionHelper.CreateCompanyNameCondition(companyName);
            var filter = new FilterExpression();
            filter.Conditions.Add(compayNameCondition);

            var query = new QueryExpression(Account.EntityLogicalName)
            {
                ColumnSet = new ColumnSet(true)
            };

            query.Criteria.AddFilter(filter);

            var companies = service.RetrieveMultiple(query)
                .Entities.ToList();

            if (!companies.Any())
            {
                throw new CrmEntityNotFoundException(string.Format("Company '{0}' was not found.", companyName));
            }

            if (companies.Count > 1)
            {
                throw new CrmAmbiguousMatchException(string.Format("{0} companies found with name '{1}'.", companies.Count, companyName));
            }

            return companies.Single().ToEntityReference();
        }
        private HttpResponse BrowseGenres()
        {
            var filter = new FilterExpression<ITrack>(Request.QueryString["filter"]);
            var includeSortHeaders = "1".Equals(Request.QueryString["include-sort-headers"]);

            using (Player.MediaLibrary.BeginRead())
            {
                var rawItems = filter.Filter(Player.MediaLibrary.Tracks);

                var items = rawItems.Where(x => !string.IsNullOrEmpty(x.GenreName))
                                    .GroupBy(x => x.GenreName, StringComparer.InvariantCultureIgnoreCase)
                                    .Select(x => x.Key)
                                    .OrderBy(x => x, LatinFirstSortComparer.Instance)
                                    .ToArray();

                return new DmapResponse(new
                {
                    abro = new
                    {
                        mstt = 200,
                        muty = (byte)0,
                        abgn = items,
                        mshl = includeSortHeaders ? items.GetShortcuts(x => x) : null
                    }
                });
            }
        }
 public override SqlFragment Visit(FilterExpression expression)
 {
     SelectStatement select = VisitInputExpressionEnsureSelect(expression.Input.Expression,
         expression.Input.VariableName, expression.Input.VariableType);
     select = WrapIfNotCompatible(select, expression.ExpressionKind);
     select.Where = expression.Predicate.Accept(this);
     return select;
 }
Exemplo n.º 9
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;
        }
        public void ResultExpressionTestHelper5()
        {
            var target = new FilterExpression<Person>();

            var persons = _peoples.Where(target.Start(p => p is Int32).ResultExpression);
            var expected = _peoples.Where(p => p is Person);
            bool result = AreCollectionsEquals(persons.ToList(), expected.ToList());
            Assert.IsFalse(result);
        }
        public static ClarifyGeneric Filter(this ClarifyGeneric generic, Func<FilterExpression, Filter> filterFunction)
        {
            var filterExpression = new FilterExpression();

            var filter = filterFunction(filterExpression);

            generic.Filter.AddFilter(filter);

            return generic;
        }
Exemplo n.º 12
0
        public SQLEditorAndResults(string filePath, string sql, bool temp)
        {
            InitializeComponent();

            btnSave.Text = "";

            imageListTabs.Images.Add("Results", FamFamFam.application_split);
            imageListTabs.Images.Add("Output", FamFamFam.application_xp_terminal);
            imageListTabs.Images.Add("SQLLog", FamFamFam.clock);
            imageListTabs.Images.Add("Info", FamFamFam.information);
            imageListTabs.Images.Add("TableData", FamFamFam.table);

            tpResults.ImageKey = "Results";
            tpOutput.ImageKey = "Output";
            tpSQLLog.ImageKey = "SQLLog";
            tpInfo.ImageKey = "Info";
            tpTableData.ImageKey = "TableData";

            this.filePath = temp ? "" : filePath;
            this.tempFilePath = temp ? filePath : "";

            if (!string.IsNullOrEmpty(filePath))
            {
                txtSQL.LoadFile(filePath);
                InitialText = txtSQL.Text;
            }
            else if (!string.IsNullOrEmpty(tempFilePath))
            {
                txtSQL.LoadFile(tempFilePath);
                InitialText = "this is not a saved file. just a temp file. this sentence is not for warning, just to be sure that InitialText is not equal to txtSQL.Text. (to keep the editor in Modified state)";
            }
            else if (!string.IsNullOrEmpty(sql))
            {
                txtSQL.Text = sql;
                InitialText = txtSQL.Text;
            }
            else
            {
                InitialText = txtSQL.Text = "";
            }

            txtSQLLog.Document.ReadOnly = true;

            gridShowTable.ColumnHeaderMouseClick += new DataGridViewCellMouseEventHandler(gridShowTable_ColumnHeaderMouseClick);
            gridShowTable.CellValueChanged += delegate { btnSave.Text = "Click to save!"; };
            gridShowTable.UserAddedRow += delegate { btnSave.Text = "Click to save!"; };
            btnNextPage.Click += new EventHandler(btnNextPage_Click);
            btnPrevPage.Click += new EventHandler(btnPrevPage_Click);
            btnSave.Click += new EventHandler(btnSave_Click);
            btnRefresh.Click += delegate { bindTableData(); };
            btnDeleteSelectedRows.Click += delegate { deleteSelectedRows(); };
            btnFilter.Click += new EventHandler(btnFilter_Click);

            fExp = new FilterExpression();
        }
Exemplo n.º 13
0
        public SelectEntityDialog(Type entityType, List<ColumnDefinition> visibleColumns, FilterExpression filter, string searchFieldName, Func<BaseEntity, string, BaseEntity> getCurrentEntity)
        {
            InitializeComponent();
            PageSize = 20;

            this.EntityType = entityType;
            this.VisibleColumns = visibleColumns;
            this.Filter = filter;
            this.SearchFieldName = searchFieldName;
            this.GetCurrentEntity = getCurrentEntity;
        }
Exemplo n.º 14
0
        public FilterExpression ConditionHelper(LogicalOperator op, Dictionary<string, object> keyValues)
        {
            FilterExpression filter = new FilterExpression();
            filter.FilterOperator = op;

            foreach (KeyValuePair<string, object> item in keyValues)
            {
                filter.Conditions.Add(new ConditionExpression(item.Key, ConditionOperator.Equal, item.Value));
            }
            return filter;
        }
Exemplo n.º 15
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);

            }
        }
        public void ResultExpressionTestHelper2()
        {
            var target = new FilterExpression<Person>();

            var filterExpression = target.Start(p => p.Name.Contains("berto")).And(p => p.Age <= 25);

            var persons = _peoples.Where(filterExpression.ResultExpression);
            var expected = _peoples.Where(p => p.Name.Contains("berto") && p.Age <= 25);
            bool result = AreCollectionsEquals(persons.ToList(), expected.ToList());
            Assert.IsTrue(result);
        }
        private HttpResponse AddTracks()
        {
            // source is set by filter
            var editParams = Request.QueryString["edit-params"];
            if (!string.IsNullOrEmpty(editParams))
            {
                var filter = new FilterExpression<ITrack>(editParams);

                using (Player.BeginWrite())
                {
                    var playlist = Player.Playlists.Where(x => x.Id == id2.Value).FirstOrDefault() as IEditablePlaylist;
                    if (playlist != null)
                    {
                        using (Player.MediaLibrary.BeginRead())
                        {
                            var items = filter.Filter(Player.MediaLibrary.Tracks).Except(playlist.Tracks).ToArray();
                            if (items.Length > 0)
                                playlist.AddTrackRange(items);
                        }
                    }
                }

                return new NoContentResponse();
            }

            // source is set by playlist id
            var addSrc = Request.QueryString["edit-add-src"];
            int playlistId;
            if (!string.IsNullOrEmpty(addSrc) && int.TryParse(addSrc, out playlistId))
            {
                using (Player.BeginWrite())
                {
                    var source = Player.Playlists.Where(x => x.Id == playlistId).FirstOrDefault();
                    if (source != null)
                    {
                        var playlist = Player.Playlists.Where(x => x.Id == id2.Value).FirstOrDefault() as IEditablePlaylist;
                        if (playlist != null)
                        {
                            using (Player.MediaLibrary.BeginRead())
                            {
                                var items = source.Tracks.Except(playlist.Tracks).ToArray();
                                if (items.Length > 0)
                                    playlist.AddTrackRange(items);
                            }
                        }
                    }
                }

                return new NoContentResponse();
            }

            return null;
        }
Exemplo n.º 18
0
        public QueryExpression ConditionHelper(QueryExpression qe, string key, List<string> values)
        {
            FilterExpression filter = new FilterExpression();
            filter.FilterOperator = LogicalOperator.Or;

            foreach (string item in values)
            {
                filter.Conditions.Add(new ConditionExpression(key, ConditionOperator.Equal, item));
            }

            qe.Criteria.Filters.Add(filter);
            return qe;
        }
    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);
        }
    }
Exemplo n.º 20
0
        /// <summary>
        /// The class constructor.
        /// It initializes the connection parameters
        /// </summary>
        public ESC_CRM(string crmURL, string crmURLMD, string crmName, string crmLogin, string crmPassword, string crmDomain)
        {
            m_crmService = new CrmService();
            m_crmURL = crmURL; 				//ex : http://crm.domain.net/[OrganizationName]/XRMServices/2011/Organization.svc
            m_crmURL_MD = crmURLMD;			//ex : https://crm.domain.net/mscrmservices/2007/metadataservice.asmx
            m_crmName = crmName;			//OrganizationName
            m_crmLogin = crmLogin;
            m_crmPassword = crmPassword;
            m_crmDomain = crmDomain;
            m_isconnected = false;

            m_propertyList = new ArrayList();
            m_filterExpression = new FilterExpression();
        }
Exemplo n.º 21
0
        private static bool isDuplicate(string clientid, IOrganizationService orgservice)
        {
            //we search CRM to see if clientid is already in use and return true if it is and false otherwise
            var query = new QueryExpression("account");
            var columns = new ColumnSet();
            var filter = new FilterExpression();

            columns.AddColumn("ergo_clientid");
            filter.AddCondition("ergo_clientid", ConditionOperator.Equal, clientid);
            query.ColumnSet = columns;
            query.Criteria.AddFilter(filter);

            if(orgservice.RetrieveMultiple(query).Entities.Any()) return true;
            return false;
        }
Exemplo n.º 22
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;
        }
Exemplo n.º 23
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" );
        }
Exemplo n.º 24
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            //Create the tracing service
            ITracingService tracingService = executionContext.GetExtension<ITracingService>();

            //Create the context
            IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            // Create a column set to define which attributes should be retrieved.
            ColumnSet attributes = new ColumnSet(true);

            Entity currentPriceLevelEntity = new Entity("pricelevel");
            currentPriceLevelEntity = service.Retrieve("pricelevel", CurrentPriceList.Get<EntityReference>(executionContext).Id, attributes);

            // Create New Price List
            Entity newPriceLevel = new Entity("pricelevel");
            newPriceLevel["name"] = NewPriceListName.Get<string>(executionContext);
            newPriceLevel["begindate"] = NewPriceListStartDate.Get<DateTime>(executionContext);
            newPriceLevel["enddate"] = NewPriceListEndDate.Get<DateTime>(executionContext);
            newPriceLevel["transactioncurrencyid"] = currentPriceLevelEntity["transactioncurrencyid"];
            Guid newPriceLevelId = service.Create(newPriceLevel);

            // Get current product price level
            QueryExpression productPriceLevelExpression = new QueryExpression("productpricelevel");

            FilterExpression productPriceLevelFilterExpression = new FilterExpression();
            productPriceLevelFilterExpression.Conditions.Add(new ConditionExpression("pricelevelid", ConditionOperator.Equal, currentPriceLevelEntity["pricelevelid"]));

            productPriceLevelExpression.ColumnSet = new ColumnSet(true);
            productPriceLevelExpression.Criteria = productPriceLevelFilterExpression;

            EntityCollection productPriceLevelList = service.RetrieveMultiple(productPriceLevelExpression);

            // Create new product price level records
            for (int index = 0; productPriceLevelList.Entities != null && index < productPriceLevelList.Entities.Count; index++)
            {
                Entity newProductPriceLevelEntity = new Entity("productpricelevel");
                newProductPriceLevelEntity["pricelevelid"] = new EntityReference("pricelevel", newPriceLevelId);
                newProductPriceLevelEntity["productid"] = productPriceLevelList.Entities[index]["productid"];
                newProductPriceLevelEntity["uomid"] = productPriceLevelList.Entities[index]["uomid"];
                newProductPriceLevelEntity["amount"] = productPriceLevelList.Entities[index]["amount"];
                service.Create(newProductPriceLevelEntity);
            }
        }
        public void ResultExpressionTestHelper()
        {
            var target = new FilterExpression<Person>();

            var filterExpression = target.Start(p => p.Name.Contains("o"));
            filterExpression = filterExpression.And(p => p.Age <= 25);
            filterExpression = filterExpression.And(p => p.Tasks.Any(x => x.When == DateTime.Today));
            filterExpression = filterExpression.And(p => p.Working);

            var persons = _peoples.Where(filterExpression.ResultExpression);
            var expected = _peoples.Where(p1 => p1.Name.Contains("o") &&
                                                p1.Age <= 25 &&
                                                p1.Tasks.Any(x => x.When == DateTime.Today) &&
                                                p1.Working);
            var result = AreCollectionsEquals(persons.ToList(), expected.ToList());

            Assert.IsTrue(result);
        }
Exemplo n.º 26
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);
     }
 }
Exemplo n.º 27
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            FilterExpression fExp = new FilterExpression()
            {
                Orders = new OrderList { new Order { ColumnName = "Name", Ascending = true } }
            };
            grid.DataSource = DMT.Provider.Db.ReadList<Report>(fExp);
            var columns = new List<ColumnDefinition>
                {
                    new ColumnDefinition{Name = "Name", DisplayName = "Rapor", Width = 300}
                };
            DMT.Provider.PopulateGridColumns(
                columns,
                gridView);

            cbDocumentType.Visible = ShowRaporButton();
            btnRaporOlustur.Visible = ShowRaporButton();
        }
        private HttpResponse ContainerItems()
        {
            if (!id2.HasValue || id2.Value == 100)
                return LibraryItems();

            var filter = new FilterExpression<ITrack>(Request.QueryString["query"]);
            var includeSortHeaders = "1".Equals(Request.QueryString["include-sort-headers"]);
            var sort = new SortExpression(Request.QueryString["sort"]);

            using (Player.MediaLibrary.BeginRead())
            {
                var pl = Player.GetContainers().FirstOrDefault(x => x.Id == id2.Value);
                if (pl != null)
                {
                    lock (pl)
                    {
                        var rawItems = filter.Filter(pl.Tracks);

                        var items = rawItems.Select<ITrack, object>(GetTrackItem).ToArray();

                        return new DmapResponse(new
                        {
                            apso = new
                            {
                                mstt = 200,
                                muty = (byte)0,
                                mlcl = items
                            }
                        });
                    }
                }
            }

            return new DmapResponse(new
            {
                apso = new
                {
                    mstt = 200,
                    muty = (byte)0,
                    mlcl = new object[0]
                }
            });
        }
        protected override Expression VisitMethodCall(MethodCallExpression m)
        {
            if (m.Method.DeclaringType == typeof(Queryable))
            {
                if (m.Method.Name == "Where")
                {
                    if (_queryExpression.Criteria.FilterOperator != LogicalOperator.And
                        && _queryExpression.Criteria.Conditions.Any())
                    {
                        _filterExpression = new FilterExpression();
                        _queryExpression.Criteria.Filters.Add(_filterExpression);
                    }
                    else
                    {
                        _filterExpression = _queryExpression.Criteria;
                    }


                    if (_queryExpression.EntityName == null)
                    {
                        this.Visit(m.Arguments[0]);
                    }
                    else
                        throw new NotImplementedException("Cannot visit a second element type");

                    //        sb.Append(") AS T WHERE ");
                    LambdaExpression lambda = (LambdaExpression)StripQuotes(m.Arguments[1]);
                    this.Visit(lambda.Body);
                    return m;
                }
                else
                {
                    throw new NotImplementedException();
                }
            }
            else if (typeof(IQueryable).IsAssignableFrom(m.Method.ReturnType))
            {
                //evaluate this method call, it should eventually get back down to linq
                return Visit(((IQueryable)Expression.Lambda(m).Compile().DynamicInvoke(null)).Expression);
            }
            throw new NotImplementedException("Method not supported");
        }
        private IEnumerable<FilterExpression> GetConditionExpressionCollection(
            IEnumerable<Domain.Sql.DynamicRecord> originRecords, 
            IEnumerable<string> compoundKey, 
            AvailableValueConfiguration availableValueConfiguration)
        {
            var filters = new List<FilterExpression>();

            foreach (var record in originRecords)
            {
                var filter = new FilterExpression(LogicalOperator.And);

                foreach (var destinationAttribute in compoundKey)
                {
                    var currentField =availableValueConfiguration.Fields.First(x => x.DestinationAttribute == destinationAttribute);

                    if (record.Values[currentField.OriginColumn] == null)
                    {
                        filter.AddCondition(new ConditionExpression(destinationAttribute, ConditionOperator.Null));
                    }
                    else if (currentField.DestinationType == DestinationType.DateTime)
                    {
                        filter.AddCondition(new ConditionExpression(destinationAttribute, ConditionOperator.On, record.Values[currentField.OriginColumn]));
                    }
                    else if (currentField.DestinationType == DestinationType.EntityReference)
                    {
                        filter.AddCondition(new ConditionExpression(destinationAttribute, ConditionOperator.On, null));
                    }
                    else
                    {
                        filter.AddCondition(new ConditionExpression(destinationAttribute, ConditionOperator.Equal, record.Values[currentField.OriginColumn]));
                    }
                }

                filters.Add(filter);
            }

            return filters;
        }
Exemplo n.º 31
0
        //Please write your properties and functions here. This part will not be replaced.

        /// <summary>
        /// Gets site identifier by its domain name
        /// </summary>
        /// <param name="hostName">host name</param>
        /// <returns>SiteID or if it couldn't find null</returns>
        public int?GetSiteIDByHostName(string hostName)
        {
            if (string.IsNullOrEmpty(hostName))
            {
                return(null);
            }

            hostName = hostName.ToLower();

            FilterExpression filter = new FilterExpression();

            filter.AddFilter(vSiteDomain.ColumnNames.SiteDomainName, hostName);

            var list = GetByFilterV(new GetByFilterParameters(filter));

            if (list.Count > 0)
            {
                return(list[0].SiteID);
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 32
0
        private Guid GetSubParticipationSource(string code, IOrganizationService service)//Alt katılım kaynağı bul
        {
            ConditionExpression con1 = new ConditionExpression();

            con1.AttributeName = "new_code";
            con1.Operator      = ConditionOperator.Equal;
            con1.Values.Add(code);

            ConditionExpression con2 = new ConditionExpression();

            con2.AttributeName = "statecode";
            con2.Operator      = ConditionOperator.Equal;
            con2.Values.Add(0);

            FilterExpression filter = new FilterExpression();

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

            QueryExpression Query = new QueryExpression("new_subsourceofparticipation");

            Query.ColumnSet = new ColumnSet(true);
            Query.Criteria.FilterOperator = LogicalOperator.And;
            Query.Criteria.Filters.Add(filter);
            EntityCollection Result = service.RetrieveMultiple(Query);

            if (Result.Entities.Count > 0)
            {
                return(Result.Entities[0].Id);
            }
            else
            {
                return(Guid.Empty);
            }
        }
Exemplo n.º 33
0
        private Guid GetUtmCampaign(string attributeName, string attributeValue, IOrganizationService service)
        {
            ConditionExpression con1 = new ConditionExpression();

            con1.AttributeName = attributeName;
            con1.Operator      = ConditionOperator.Equal;
            con1.Values.Add(attributeValue);

            ConditionExpression con2 = new ConditionExpression();

            con2.AttributeName = "statecode";
            con2.Operator      = ConditionOperator.Equal;
            con2.Values.Add(0);

            FilterExpression filter = new FilterExpression();

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

            QueryExpression Query = new QueryExpression("new_utmcampaign");

            Query.ColumnSet = new ColumnSet("new_utmcampaignid");
            Query.Criteria.FilterOperator = LogicalOperator.And;
            Query.Criteria.Filters.Add(filter);
            EntityCollection Result = service.RetrieveMultiple(Query);

            if (Result.Entities.Count > 0)
            {
                return(Result.Entities[0].Id);
            }
            else
            {
                return(Guid.Empty);
            }
        }
Exemplo n.º 34
0
        private EntityCollection GetExceptionalWorkingHours()
        {
            try
            {
                log.LogFunctionStart();
                var query = new QueryExpression
                {
                    EntityName = "ldv_workinghours",
                    ColumnSet  = new ColumnSet(true)
                };

                var workingHoursTypeCondition = new ConditionExpression("ldv_type", ConditionOperator.Equal, 2);

                // Build the filter based on the condition.
                var filter = new FilterExpression {
                    FilterOperator = LogicalOperator.And
                };
                filter.Conditions.Add(workingHoursTypeCondition);

                // Set the Criteria property.
                query.Criteria = filter;

                var result = service.RetrieveMultiple(query);

                return(result);
            }
            catch (Exception ex)
            {
                log.Log(ex);
                throw;
            }
            finally
            {
                log.LogFunctionEnd();
            }
        }
Exemplo n.º 35
0
        private List <Report> GetList(string name, ColumnSet columnSet)
        {
            QueryExpression query = new QueryExpression()
            {
                NoLock     = true,
                EntityName = Report.EntityLogicalName,

                ColumnSet = columnSet ?? new ColumnSet(true),

                Criteria =
                {
                    Conditions =
                    {
                        //new ConditionExpression(Report.Schema.Attributes.iscustomizable, ConditionOperator.Equal, true),
                        new ConditionExpression(Report.Schema.Attributes.reporttypecode, ConditionOperator.NotEqual, 3),
                    },
                },

                Orders =
                {
                    new OrderExpression(Report.Schema.Attributes.name, OrderType.Ascending),
                },
            };

            if (!string.IsNullOrEmpty(name))
            {
                FilterExpression filter = new FilterExpression(LogicalOperator.Or);

                filter.AddCondition(Report.Schema.Attributes.name, ConditionOperator.Like, "%" + name + "%");
                filter.AddCondition(Report.Schema.Attributes.filename, ConditionOperator.Like, "%" + name + "%");

                query.Criteria.Filters.Add(filter);
            }

            return(_service.RetrieveMultipleAll <Report>(query));
        }
Exemplo n.º 36
0
        private string GetAccountIntegrationURL(IOrganizationService service)
        {
            string configName = "Account Integration Scribe URL";

            FilterExpression filter = new FilterExpression(LogicalOperator.And);

            filter.AddCondition("cf_key", ConditionOperator.Equal, configName);

            QueryExpression query = new QueryExpression()
            {
                EntityName = "cf_integrationconfiguration",
                Criteria   = filter,
                ColumnSet  = new ColumnSet("cf_value", "cf_key", "cf_description")
            };

            EntityCollection configurations = service.RetrieveMultiple(query);

            if (configurations.Entities.Count > 0 && configurations[0].Contains("cf_value"))
            {
                return(configurations[0].GetAttributeValue <string>("cf_value"));
            }

            return(string.Empty);
        }
Exemplo n.º 37
0
        private QueryExpression queryMoj()
        {
            QueryExpression     query          = new QueryExpression("pi_mojhistory");
            ConditionExpression conditionOne   = new ConditionExpression("pi_name", ConditionOperator.Equal, "Stage Changed to Liability Admitted");
            ConditionExpression conditionAdOne = new ConditionExpression("pi_name", ConditionOperator.Equal, "Stage Changed to Liability admitted (child claim)");
            ConditionExpression conditionAdTwo = new ConditionExpression("pi_name", ConditionOperator.Equal, "Stage Changed to Liability admitted with negligence (other than seatbelt)");

            ConditionExpression conditionTwo   = new ConditionExpression("pi_name", ConditionOperator.Equal, "Successfully Submitted CNF");
            ConditionExpression conditionThree = new ConditionExpression("pi_name", ConditionOperator.Equal, "Successfully Submitted Settlement Pack");
            ConditionExpression conditionFour  = new ConditionExpression("pi_name", ConditionOperator.Equal, "Successfully Added Court Proceedings Pack");
            ConditionExpression conditionFive  = new ConditionExpression("pi_name", ConditionOperator.Equal, "Stage Changed to Exit Process");

            FilterExpression mojfilter = new FilterExpression();

            mojfilter.FilterOperator = LogicalOperator.Or;
            mojfilter.Conditions.AddRange(conditionOne, conditionAdOne, conditionAdTwo, conditionTwo, conditionThree, conditionFour, conditionFive);

            query.Criteria.AddFilter(mojfilter);

            query.ColumnSet.AddColumns("createdon", "pi_claiminformation", "pi_name");
            query.Orders.Add(new OrderExpression("pi_claiminformation", OrderType.Descending));

            return(query);
        }
Exemplo n.º 38
0
        public Guid getEmployeID(string nomEmploye, string prenomEmploye)
        {
            QueryExpression queryExp = new QueryExpression();

            queryExp.EntityName = "new_employeuniversietjkwe";
            queryExp.ColumnSet  = new ColumnSet();
            queryExp.ColumnSet.Columns.Add("new_employeuniversietjkweid");
            ConditionExpression conExp1 = new ConditionExpression();

            conExp1.AttributeName = "new_name";
            conExp1.Operator      = ConditionOperator.Equal;
            conExp1.Values.Add(nomEmploye);
            ConditionExpression conExp2 = new ConditionExpression();

            conExp2.AttributeName = "new_prenom";
            conExp2.Operator      = ConditionOperator.Equal;
            conExp2.Values.Add(prenomEmploye);
            FilterExpression fep = new FilterExpression();

            fep.Conditions.Add(conExp1);
            fep.Conditions.Add(conExp2);
            queryExp.Criteria.AddFilter(fep);
            EntityCollection contCollection = orgService.RetrieveMultiple(queryExp);

            if (contCollection.Entities.Count > 0)
            {
                Console.WriteLine("Tu as trouvé l'employé \"" + nomEmploye + ", " + prenomEmploye + "\".");
                Entity recordId = contCollection.Entities[0];
                return(recordId.Id);
            }
            else
            {
                Console.WriteLine("L'employé \"" + nomEmploye + ", " + prenomEmploye + "\" est introuvable");
                return(new Entity().Id);
            }
        }
Exemplo n.º 39
0
        public static EntityReference GetPublisherReferenceByNameExact(this IOrganizationService service, string companyName)
        {
            var nameCondition        = ConditionExpressionHelper.CreatePublisherNameExactCondition(companyName);
            var isPublisherCondition = ConditionExpressionHelper.CreateIsPublisherCondition();

            var filter = new FilterExpression();

            filter.Conditions.Add(nameCondition);
            filter.Conditions.Add(isPublisherCondition);

            var query = new QueryExpression(Account.EntityLogicalName);

            query.Criteria.AddFilter(filter);

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

            if (account == null)
            {
                throw new CrmEntityNotFoundException("Account not found with name: " + companyName);
            }

            return(new EntityReference(Account.EntityLogicalName, account.Id));
        }
Exemplo n.º 40
0
        public int ValidateLicense(string licenseFileName, string productName)
        {
            QueryExpression qe = new QueryExpression();

            qe.EntityName = EntityName.Webresource;
            qe.ColumnSet  = new ColumnSet()
            {
                AllColumns = true
            };

            ConditionExpression ce = new ConditionExpression();

            ce.AttributeName = EntityAttributes.Name;
            ce.Operator      = ConditionOperator.Equal;
            ce.Values.Add(licenseFileName);
            FilterExpression fe = new FilterExpression();

            fe.Conditions.Add(ce);
            qe.Criteria = fe;

            int result = LicenseRetrieve(_crmService.RetrieveMultiple(qe), productName);

            return(result);
        }
Exemplo n.º 41
0
        internal static void UpdateFinancialAccount(Guid quoteId, Guid financialAccountId, IOrganizationService service)
        {
            ConditionExpression con1 = new ConditionExpression();

            con1.AttributeName = "new_quoteid";
            con1.Operator      = ConditionOperator.Equal;
            con1.Values.Add(quoteId);

            ConditionExpression con2 = new ConditionExpression();

            con2.AttributeName = "statecode";
            con2.Operator      = ConditionOperator.Equal;
            con2.Values.Add(0);

            FilterExpression filter = new FilterExpression();

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

            QueryExpression Query = new QueryExpression("new_payment");

            Query.ColumnSet = new ColumnSet("new_paymentid");
            Query.Criteria.FilterOperator = LogicalOperator.And;
            Query.Criteria.Filters.Add(filter);

            EntityCollection Result = service.RetrieveMultiple(Query);

            foreach (Entity p in Result.Entities)
            {
                Entity payment = new Entity("new_payment");
                payment.Id = p.Id;
                payment["new_financialaccountid"] = new EntityReference("new_financialaccount", financialAccountId);
                service.Update(payment);
            }
        }
Exemplo n.º 42
0
        public void TestQueryExpressionNotInEmpty()
        {
            var leadCount = 0;

            using (var context = new Xrm(orgAdminUIService))
            {
                leadCount = context.LeadSet.Select(x => x.LeadId).ToList().Count();
            }

            var query = new QueryExpression("lead")
            {
                ColumnSet = new ColumnSet(true)
            };

            var filter = new FilterExpression(LogicalOperator.And);

            filter.AddCondition(new ConditionExpression("parentcontactid", ConditionOperator.NotIn, new Guid[] { }));

            query.Criteria = filter;

            var res = orgAdminService.RetrieveMultiple(query).Entities.Cast <Lead>();

            Assert.AreEqual(leadCount, res.Count());
        }
Exemplo n.º 43
0
        private Guid findConsultantID(string consultantName, IOrganizationService service)
        {
            consultantName = findConsultantName(consultantName, service);
            EventLog.saveMessage("The consultant full name is " + consultantName);

            ConditionExpression condition = new ConditionExpression();

            condition.AttributeName = "fullname";
            condition.Operator      = ConditionOperator.Equal;
            condition.Values.Add(consultantName);

            FilterExpression filter = new FilterExpression();

            filter.AddCondition(condition);

            QueryExpression query = new QueryExpression();

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


            try
            {
                EntityCollection result = service.RetrieveMultiple(query);
                var accountid           = Guid.Empty;

                accountid = result.Entities.FirstOrDefault().Id;
                return(accountid);
            }
            catch (Exception)
            {
                EventLog.saveMessage("No such user exist in the CRM Database - " + consultantName);
                return(new Guid("64FA3858-E5B8-E311-ABB3-00155D0A4E33"));
            }
        }
Exemplo n.º 44
0
        /// <summary>
        /// retrieve a CRM entity based on a simple query (generally the Id)
        /// </summary>
        /// <param name="service">IOrganizationService to execute requests</param>
        /// <param name="entityName">Name of CRM entity</param>
        /// <param name="columnNames">Column Names</param>
        /// <param name="attributeName">The "column" name that will be searched</param>
        /// <param name="keyValue">The Search Key/Id</param>
        /// <returns>returns CRM Entity record requested</returns>
        public static Entity GetCrmEntityUsingKey(IOrganizationService service, string entityName, string[] columnNames, string attributeName, string keyValue)
        {
            if (service != null)
            {
                QueryExpression query = new QueryExpression(entityName);
                query.ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(columnNames);
                ConditionExpression con = new ConditionExpression();
                con.AttributeName = attributeName;
                con.Operator      = ConditionOperator.Equal;
                con.Values.Add(keyValue);

                FilterExpression filter = new FilterExpression();
                filter.Conditions.Add(con);

                query.Criteria.AddFilter(filter);
                EntityCollection resultSet = service.RetrieveMultiple(query);
                if (resultSet.HasRecords() && resultSet.Entities.Count > 0)
                {
                    return(resultSet.Entities[0]);
                }
            }

            return(null);
        }
Exemplo n.º 45
0
        public void When_executing_a_query_expression_with_1_filters_combined_with_1_condition_and_or_filter_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.Or);
            qe.Criteria.AddCondition(new ConditionExpression("fullname", ConditionOperator.Equal, "Contact 1"));

            var filter1 = new FilterExpression();

            filter1.AddCondition(new ConditionExpression("fullname", ConditionOperator.Equal, "Contact 2"));

            qe.Criteria.AddFilter(filter1);

            var result = XrmFakedContext.TranslateQueryExpressionToLinq(context, qe).ToList();

            Assert.True(result.Count == 2);
        }
Exemplo n.º 46
0
        public static string GetProcessStageName(IOrganizationService _service, Guid stageid)
        {
            string          stageName = null;
            QueryExpression query     = new QueryExpression("processstage");

            ColumnSet col = new ColumnSet("stagename");

            query.ColumnSet = col;
            ConditionExpression ce1    = new ConditionExpression("primaryentitytypecode", ConditionOperator.Equal, "incident");
            ConditionExpression ce2    = new ConditionExpression("processstageid", ConditionOperator.Equal, stageid);
            FilterExpression    filter = new FilterExpression(LogicalOperator.And);

            filter.Conditions.Add(ce1);
            filter.Conditions.Add(ce2);
            query.Criteria.AddFilter(filter);

            EntityCollection collection = _service.RetrieveMultiple(query);

            if (collection.Entities.Count > 0)
            {
                stageName = collection.Entities[0].Attributes["stagename"].ToString();
            }
            return(stageName);
        }
Exemplo n.º 47
0
        private Guid GetChannelOfAwareness(string code, IOrganizationService service)//haberdar olma kanalı bul
        {
            ConditionExpression con1 = new ConditionExpression();

            con1.AttributeName = "new_code";
            con1.Operator      = ConditionOperator.Equal;
            con1.Values.Add(code);

            ConditionExpression con2 = new ConditionExpression();

            con2.AttributeName = "statecode";
            con2.Operator      = ConditionOperator.Equal;
            con2.Values.Add(0);

            FilterExpression filter = new FilterExpression();

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

            QueryExpression Query = new QueryExpression("new_channelofawareness");

            Query.ColumnSet = new ColumnSet(true);
            Query.Criteria.FilterOperator = LogicalOperator.And;
            Query.Criteria.Filters.Add(filter);
            EntityCollection Result = service.RetrieveMultiple(Query);

            if (Result.Entities.Count > 0)
            {
                return(Result.Entities[0].Id);
            }
            else
            {
                return(Guid.Empty);
            }
        }
Exemplo n.º 48
0
        /// <summary>
        /// Generic retrieve function to retrieve records by validating a field equality to a certain value
        /// </summary>
        public static EntityCollection RetrieveRecordsByOneValue(string entity, string field, object value, IOrganizationService service, string orderField = null, OrderType orderType = OrderType.Ascending, params string[] columns)
        {
            var query = new QueryExpression(entity)
            {
                ColumnSet = new ColumnSet()
            };

            if (columns.Length > 0)
            {
                query.ColumnSet.AddColumns(columns);
            }

            var filter = new FilterExpression(LogicalOperator.And);

            filter.AddCondition(new ConditionExpression(field, ConditionOperator.Equal, value));
            query.Criteria.Filters.Add(filter);

            if (!string.IsNullOrEmpty(orderField))
            {
                query.Orders.Add(new OrderExpression(orderField, orderType));
            }

            return(service.RetrieveMultiple(query));
        }
Exemplo n.º 49
0
        private bool UserHasPrivilege(IOrganizationService service, Guid userId, string privilegeName)
        {
            bool userHasPrivilege = false;

            try
            {
                QueryExpression privilegeQuery = new QueryExpression("privilege");
                privilegeQuery.ColumnSet = new ColumnSet(true);
                LinkEntity privilegeLink1 = new LinkEntity("privilege", "roleprivileges", "privilegeid", "privilegeid", JoinOperator.Inner);
                LinkEntity privilegeLink2 = new LinkEntity("roleprivileges", "role", "roleid", "roleid", JoinOperator.Inner);
                LinkEntity privilegeLink3 = new LinkEntity("role", "systemuserroles", "roleid", "roleid", JoinOperator.Inner);
                LinkEntity privilegeLink4 = new LinkEntity("systemuserroles", "systemuser", "systemuserid", "systemuserid", JoinOperator.Inner);

                ConditionExpression userCondition      = new ConditionExpression("systemuserid", ConditionOperator.Equal, userId);            // // Id of the User
                ConditionExpression privilegeCondition = new ConditionExpression("name", ConditionOperator.Equal, privilegeName);             // name of the privilege

                privilegeLink4.LinkCriteria.AddCondition(userCondition);
                FilterExpression privilegeFilter = new FilterExpression(LogicalOperator.And);
                privilegeFilter.Conditions.Add(privilegeCondition);
                privilegeQuery.Criteria = privilegeFilter;

                privilegeLink3.LinkEntities.Add(privilegeLink4);
                privilegeLink2.LinkEntities.Add(privilegeLink3);
                privilegeLink1.LinkEntities.Add(privilegeLink2);
                privilegeQuery.LinkEntities.Add(privilegeLink1);

                EntityCollection retrievedPrivileges = service.RetrieveMultiple(privilegeQuery);
                if (retrievedPrivileges.Entities.Count > 0)
                {
                    userHasPrivilege = true;
                }
            }
            catch { }

            return(userHasPrivilege);
        }
Exemplo n.º 50
0
 public Property Equals_should_be_commutative(NonNull <DurationExpression> first, FilterExpression second)
 => (first.Item.Equals(second) == second.Equals(first.Item)).ToProperty();
Exemplo n.º 51
0
        internal static void SetProductAndProjectOnQuote(Entity entity, IOrganizationService adminService)
        {
            Guid quoteId = ((EntityReference)entity.Attributes["quoteid"]).Id;

            ConditionExpression con1 = new ConditionExpression();

            con1.AttributeName = "quoteid";
            con1.Operator      = ConditionOperator.Equal;
            con1.Values.Add(quoteId);

            FilterExpression filter = new FilterExpression();

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

            QueryExpression Query = new QueryExpression("quotedetail");

            Query.ColumnSet = new ColumnSet("quotedetailid");
            Query.Criteria.FilterOperator = LogicalOperator.And;
            Query.Criteria.Filters.Add(filter);
            EntityCollection Result   = adminService.RetrieveMultiple(Query);
            Entity           q        = adminService.Retrieve("quote", quoteId, new ColumnSet("new_taxrate", "new_taxofstamp", "totalamount", "discountamount", "revisionnumber", "quotenumber"));
            Entity           oldQuote = GetPreviousQuoteByRevisionAndQuoteNumber(Convert.ToInt32(q["revisionnumber"]), Convert.ToString(q["quotenumber"]), adminService);

            if (Convert.ToInt32(q["revisionnumber"]) > 0)
            {
                Entity qd = new Entity("quotedetail");
                qd.Id = Result.Entities[0].Id;
                qd["ispriceoverridden"] = true;
                qd["priceperunit"]      = oldQuote["totallineitemamount"];
                adminService.Update(qd);
            }
            else if (Result.Entities.Count > 0)
            {
                Entity qd = new Entity("quotedetail");
                qd.Id = Result.Entities[0].Id;
                qd["ispriceoverridden"] = false;
                adminService.Update(qd);
            }

            Guid productId = entity.Contains("productid") ? ((EntityReference)entity.Attributes["productid"]).Id : Guid.Empty;
            Guid projectId = Guid.Empty;

            if (productId != Guid.Empty)
            {
                Entity product = adminService.Retrieve("product", productId, new ColumnSet("new_projectid", "new_grossm2"));
                projectId = product.Contains("new_projectid") ? ((EntityReference)product.Attributes["new_projectid"]).Id : Guid.Empty;
                Entity quote = new Entity("quote");
                quote.Id = quoteId;
                quote.Attributes.Add("new_productid", new EntityReference("product", productId));
                if (projectId != Guid.Empty)
                {
                    quote.Attributes.Add("new_projectid", new EntityReference("new_project", projectId));
                }

                if (!(Convert.ToInt32(q["revisionnumber"]) > 0))
                {
                    decimal totalAmount = q.Contains("totalamount") ? ((Money)q.Attributes["totalamount"]).Value : 0;

                    decimal taxRate          = q.Contains("new_taxrate") ? (decimal)q.Attributes["new_taxrate"] : 0;
                    decimal taxOfStamp       = q.Contains("new_taxofstamp") ? (decimal)q.Attributes["new_taxofstamp"] : 0;
                    decimal taxAmount        = (totalAmount * taxRate) / 100;
                    decimal amountWithTax    = totalAmount + taxAmount;
                    decimal taxOfStampAmount = (totalAmount * taxOfStamp) / 100;
                    quote.Attributes["new_taxamount"]             = new Money(taxAmount);
                    quote.Attributes["new_amountwithtax"]         = new Money(amountWithTax);
                    quote.Attributes["new_taxofstampamount"]      = new Money(taxOfStampAmount);
                    quote.Attributes["new_totalsalesamountbytax"] = new Money(amountWithTax + taxOfStampAmount);

                    //Birim metrekare fiyatı
                    Entity detail = GetProductFromQuoteDetail(quoteId, adminService);
                    if (detail != null)
                    {
                        if (product.Contains("new_grossm2"))
                        {
                            decimal grossM2        = (decimal)product.Attributes["new_grossm2"];
                            decimal perSquareMeter = totalAmount / grossM2;
                            quote["new_persquaremeter"] = new Money(perSquareMeter);
                        }
                    }
                }
                adminService.Update(quote);
            }
        }
Exemplo n.º 52
0
        internal void AddRelatedEntities(Entity entity, RelationshipQueryCollection relatedEntityQuery, EntityReference userRef)
        {
            foreach (var relQuery in relatedEntityQuery)
            {
                var relationship = relQuery.Key;
                var queryExpr    = relQuery.Value as QueryExpression;
                if (queryExpr == null)
                {
                    queryExpr = XmlHandling.FetchXmlToQueryExpression(((FetchExpression)relQuery.Value).Query);
                }
                var relationshipMetadata = Utility.GetRelatedEntityMetadata(metadata.EntityMetadata, queryExpr.EntityName, relationship.SchemaName);


                var oneToMany  = relationshipMetadata as OneToManyRelationshipMetadata;
                var manyToMany = relationshipMetadata as ManyToManyRelationshipMetadata;

                if (oneToMany != null)
                {
                    if (relationship.PrimaryEntityRole == EntityRole.Referencing)
                    {
                        var entityAttributes = db.GetEntityOrNull(entity.ToEntityReference()).Attributes;
                        if (entityAttributes.ContainsKey(oneToMany.ReferencingAttribute) && entityAttributes[oneToMany.ReferencingAttribute] != null)
                        {
                            var referencingGuid = Utility.GetGuidFromReference(entityAttributes[oneToMany.ReferencingAttribute]);
                            queryExpr.Criteria.AddCondition(
                                new ConditionExpression(oneToMany.ReferencedAttribute, ConditionOperator.Equal, referencingGuid));
                        }
                    }
                    else
                    {
                        queryExpr.Criteria.AddCondition(
                            new ConditionExpression(oneToMany.ReferencingAttribute, ConditionOperator.Equal, entity.Id));
                    }
                }

                if (manyToMany != null)
                {
                    if (db[manyToMany.IntersectEntityName].Count() > 0)
                    {
                        var conditions = new FilterExpression(LogicalOperator.Or);
                        if (entity.LogicalName == manyToMany.Entity1LogicalName)
                        {
                            queryExpr.EntityName = manyToMany.Entity2LogicalName;
                            var relatedIds = db[manyToMany.IntersectEntityName]
                                             .Where(row => row.GetColumn <Guid>(manyToMany.Entity1IntersectAttribute) == entity.Id)
                                             .Select(row => row.GetColumn <Guid>(manyToMany.Entity2IntersectAttribute));

                            foreach (var id in relatedIds)
                            {
                                conditions.AddCondition(
                                    new ConditionExpression(null, ConditionOperator.Equal, id));
                            }
                        }
                        else
                        {
                            queryExpr.EntityName = manyToMany.Entity1LogicalName;
                            var relatedIds = db[manyToMany.IntersectEntityName]
                                             .Where(row => row.GetColumn <Guid>(manyToMany.Entity2IntersectAttribute) == entity.Id)
                                             .Select(row => row.GetColumn <Guid>(manyToMany.Entity1IntersectAttribute));

                            foreach (var id in relatedIds)
                            {
                                conditions.AddCondition(
                                    new ConditionExpression(null, ConditionOperator.Equal, id));
                            }
                        }
                        queryExpr.Criteria = conditions;
                    }
                }
                var entities = new EntityCollection();

                if ((oneToMany != null || manyToMany != null) && queryExpr.Criteria.Conditions.Count > 0)
                {
                    var handler = RequestHandlers.Find(x => x is RetrieveMultipleRequestHandler);
                    var req     = new RetrieveMultipleRequest
                    {
                        Query = queryExpr
                    };
                    var resp = handler.Execute(req, userRef) as RetrieveMultipleResponse;
                    entities = resp.EntityCollection;
                }

                if (entities.Entities.Count() > 0)
                {
                    entity.RelatedEntities.Add(relationship, entities);
                }
            }
        }
Exemplo n.º 53
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            ITracingService tracingService = executionContext.GetExtension<ITracingService>();

            IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            tracingService.Trace("{0}{1}", "Start Custom Workflow Activity: UpsertActualDraws", DateTime.Now.ToLongTimeString());
            try
            {
                //Get values from inputs
                var coaValue = this.coa.Get(executionContext);
                var revisionValue = this.revision.Get(executionContext);
                var processDateValue = this.processDate.Get(executionContext);
                var paymentDateValue = this.paymentDate.Get(executionContext);
                var amountValue = this.amount.Get(executionContext);
                var statusValue = (this.status.Get(executionContext) == "ACTUAL") ? (int)caps_ActualDraw_StatusCode.Approved : (int)caps_ActualDraw_StatusCode.Pending;

                tracingService.Trace("Processed Date: {0}", processDateValue);
                tracingService.Trace("Paid Date: {0}", paymentDateValue);

                //Parse values
                var dateProcessed = DateTime.ParseExact(processDateValue, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
                tracingService.Trace("Line {0}", "68");
                var datePaid = DateTime.ParseExact(paymentDateValue, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
                tracingService.Trace("Line {0}", "70");

                tracingService.Trace("Processed Date: {0}", dateProcessed.ToShortDateString());
                tracingService.Trace("Paid Date: {0}", datePaid.ToShortDateString());

                decimal paymentAmount = Convert.ToDecimal(amountValue) / 100;

                tracingService.Trace("Amount: {0}", paymentAmount);
                tracingService.Trace("COA: {0}", coaValue);
                tracingService.Trace("Revision: {0}", revisionValue);

                //Get Project by COA number
                QueryExpression query = new QueryExpression("caps_certificateofapproval");
                query.ColumnSet.AddColumns("caps_ptr");

                FilterExpression filterName = new FilterExpression();
                filterName.Conditions.Add(new ConditionExpression("caps_name", ConditionOperator.Equal, coaValue));
                filterName.Conditions.Add(new ConditionExpression("caps_ptr", ConditionOperator.NotNull));
                filterName.Conditions.Add(new ConditionExpression("caps_revisionnumber", ConditionOperator.Equal, revisionValue));
                filterName.Conditions.Add(new ConditionExpression("statuscode", ConditionOperator.In, (int)caps_CertificateofApproval_StatusCode.Registered, (int)caps_CertificateofApproval_StatusCode.Revised, (int)caps_CertificateofApproval_StatusCode.Closed ));
                query.Criteria.AddFilter(filterName);

                EntityCollection results = service.RetrieveMultiple(query);

                //Get top record and get project info
                if (results.Entities.Count > 0)
                {
                    var project = results.Entities[0].GetAttributeValue<EntityReference>("caps_ptr");
                    var coa = results.Entities[0].Id;

                    //Get School District Team from SD record
                    var fetchXML = "<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\" distinct=\"true\">"+
                                    "<entity name=\"edu_schooldistrict\" > "+
                                       "<attribute name=\"edu_name\" /> "+
                                            "<attribute name = \"caps_sddefaultteam\" /> "+
                                             "<order attribute = \"edu_name\" descending=\"false\" /> "+
                                                "<link-entity name = \"caps_projecttracker\" from=\"caps_schooldistrict\" to=\"edu_schooldistrictid\" link-type=\"inner\" alias=\"ac\" > "+
                                                               "<filter type=\"and\" > "+
                                                                  "<condition attribute=\"caps_projecttrackerid\" operator= \"eq\"  value = \"{"+project.Id+"}\" /> "+
                                                                        "</filter> "+
                                                                      "</link-entity> "+
                                                                    "</entity> "+
                                                                  "</fetch> ";
                    var sdRecords = service.RetrieveMultiple(new FetchExpression(fetchXML));

                    tracingService.Trace("Project: {0}", project.Id);

                    //check if actual draw already exists
                    QueryExpression queryDraw = new QueryExpression("caps_actualdraw");
                    queryDraw.ColumnSet.AddColumn("caps_actualdrawid");

                    FilterExpression filterDraw = new FilterExpression();
                    filterDraw.Conditions.Add(new ConditionExpression("caps_project", ConditionOperator.Equal, project.Id));
                    filterDraw.Conditions.Add(new ConditionExpression("caps_drawdate", ConditionOperator.Equal, datePaid));
                    queryDraw.Criteria.AddFilter(filterDraw);

                    EntityCollection resultsDraw = service.RetrieveMultiple(queryDraw);

                    if (resultsDraw.Entities.Count > 0)
                    {
                        tracingService.Trace("Update Existing Record:{0}", resultsDraw.Entities[0].Id);
                        //Update Record
                        caps_ActualDraw recordToUpdate = new caps_ActualDraw();
                        recordToUpdate.Id = resultsDraw.Entities[0].Id;
                        recordToUpdate.caps_Project = project;
                        recordToUpdate.caps_CertificateOfApproval = new EntityReference(caps_CertificateofApproval.EntityLogicalName, coa);
                        recordToUpdate.caps_DrawDate = datePaid;
                        recordToUpdate.caps_ProcessDate = dateProcessed;
                        recordToUpdate.caps_Amount = paymentAmount;
                        recordToUpdate.StatusCode = new OptionSetValue(statusValue);
                        if (sdRecords.Entities.Count > 0)
                        {
                            recordToUpdate.OwnerId = sdRecords.Entities[0].GetAttributeValue<EntityReference>("caps_sddefaultteam");
                        }
                        service.Update(recordToUpdate);
                    }
                    else
                    {
                        tracingService.Trace("New Record: {0}", "created");
                        //Create new record
                        caps_ActualDraw recordToCreate = new caps_ActualDraw();
                        recordToCreate.caps_Project = project;
                        recordToCreate.caps_CertificateOfApproval = new EntityReference(caps_CertificateofApproval.EntityLogicalName, coa);
                        recordToCreate.caps_DrawDate = datePaid;
                        recordToCreate.caps_ProcessDate = dateProcessed;
                        recordToCreate.caps_Amount = paymentAmount;
                        recordToCreate.StatusCode = new OptionSetValue(statusValue);
                        if (sdRecords.Entities.Count > 0)
                        {
                            recordToCreate.OwnerId = sdRecords.Entities[0].GetAttributeValue<EntityReference>("caps_sddefaultteam");
                        }

                        //Get fiscal year
                        QueryExpression queryYear = new QueryExpression("edu_year");
                        queryYear.ColumnSet.AddColumn("edu_yearid");

                        FilterExpression filterYear = new FilterExpression();
                        filterYear.Conditions.Add(new ConditionExpression("edu_startdate", ConditionOperator.OnOrBefore, datePaid));
                        filterYear.Conditions.Add(new ConditionExpression("edu_enddate", ConditionOperator.OnOrAfter, datePaid));
                        filterYear.Conditions.Add(new ConditionExpression("edu_type", ConditionOperator.Equal, 757500000));
                        queryYear.Criteria.AddFilter(filterYear);

                        EntityCollection resultsYear = service.RetrieveMultiple(queryYear);

                        tracingService.Trace("Number of Year Records:{0}", resultsYear.Entities.Count);

                        if (resultsYear.Entities.Count == 1)
                        {
                            recordToCreate.caps_FiscalYear = new EntityReference(edu_Year.EntityLogicalName, resultsYear.Entities[0].Id);
                        }

                        service.Create(recordToCreate);
                    }
                    this.failed.Set(executionContext, false);
                }
                else
                {
                    this.failed.Set(executionContext, true);
                    this.failureMessage.Set(executionContext, "Unable to find matching COA for: " + coaValue+" Revision: "+revisionValue);
                }
            }
            catch(Exception ex)
            {
                this.failed.Set(executionContext, true);
                this.failureMessage.Set(executionContext, "Error:" + ex.Message);
            }
        }
Exemplo n.º 54
0
        // Endpoint implementations

        /// <summary>
        /// Returns the entities as per the specifications in the get request
        /// </summary>
        protected virtual async Task <GetResponse <TEntity> > GetImplAsync(GetArguments args, Query <TEntity> queryOverride = null)
        {
            // Parse the parameters
            var filter  = FilterExpression.Parse(args.Filter);
            var orderby = OrderByExpression.Parse(args.OrderBy);
            var expand  = ExpandExpression.Parse(args.Expand);
            var select  = SelectExpression.Parse(args.Select);

            // Prepare the query
            var query = queryOverride ?? GetRepository().Query <TEntity>();

            // Retrieve the user permissions for the current view
            var permissions = await UserPermissions(Constants.Read);

            // Filter out permissions with masks that would be violated by the filter or order by arguments
            var defaultMask = GetDefaultMask() ?? new MaskTree();

            permissions = FilterViolatedPermissionsForFlatQuery(permissions, defaultMask, filter, orderby);

            // Apply read permissions
            var permissionsFilter = GetReadPermissionsCriteria(permissions);

            query = query.Filter(permissionsFilter);

            // Search
            query = Search(query, args, permissions);

            // Filter
            query = query.Filter(filter);

            // Before ordering or paging, retrieve the total count
            int totalCount = await query.CountAsync();

            // OrderBy
            query = OrderBy(query, orderby);

            // Apply the paging (Protect against DOS attacks by enforcing a maximum page size)
            var top  = args.Top;
            var skip = args.Skip;

            top   = Math.Min(top, MaximumPageSize());
            query = query.Skip(skip).Top(top);

            // Apply the expand, which has the general format 'Expand=A,B/C,D'
            var expandedQuery = query.Expand(expand);

            // Apply the select, which has the general format 'Select=A,B/C,D'
            expandedQuery = expandedQuery.Select(select);

            // Load the data in memory
            var result = await expandedQuery.ToListAsync();

            // Apply the permission masks (setting restricted fields to null) and adjust the metadata accordingly
            await ApplyReadPermissionsMask(result, query, permissions, defaultMask);

            // Flatten and Trim
            var relatedEntities = FlattenAndTrim(result, expand);

            // Prepare the result in a response object
            return(new GetResponse <TEntity>
            {
                Skip = skip,
                Top = result.Count(),
                OrderBy = args.OrderBy,
                TotalCount = totalCount,

                Result = result,
                RelatedEntities = relatedEntities,
                CollectionName = GetCollectionName(typeof(TEntity))
            });
        }
Exemplo n.º 55
0
        public ActionResult Subjects_Select(GridCommand command, long featureId)
        {
            FeaturePermissionManager featurePermissionManager = null;
            SubjectManager           subjectManager           = null;
            FeatureManager           featureManager           = null;

            try
            {
                featurePermissionManager = new FeaturePermissionManager();
                subjectManager           = new SubjectManager();
                featureManager           = new FeatureManager();

                var feature = featureManager.FindById(featureId);

                var featurePermissions = new List <FeaturePermissionGridRowModel>();

                if (feature == null)
                {
                    return(View(new GridModel <FeaturePermissionGridRowModel> {
                        Data = featurePermissions
                    }));
                }

                var subjects = new List <Subject>();
                int count    = subjectManager.Subjects.Count();
                ViewData["subjectsGridTotal"] = count;
                if (command != null)// filter subjects based on grid filter settings
                {
                    FilterExpression  filter  = TelerikGridHelper.Convert(command.FilterDescriptors.ToList());
                    OrderByExpression orderBy = TelerikGridHelper.Convert(command.SortDescriptors.ToList());

                    subjects = subjectManager.GetSubjects(filter, orderBy, command.Page, command.PageSize, out count);
                }
                else
                {
                    subjects = subjectManager.Subjects.ToList();
                }


                //foreach (var subject in subjects)
                //{
                //    var rightType = featurePermissionManager.GetPermissionType(subject.Id, feature.Id);
                //    var hasAccess = featurePermissionManager.HasAccess(subject.Id, feature.Id);

                //    featurePermissions.Add(FeaturePermissionGridRowModel.Convert(subject, featureId, rightType, hasAccess));
                //}

                var subjectIds        = subjects.Select(s => s.Id);
                var userPermissionDic = featurePermissionManager.GetPermissionType(subjectIds, feature.Id);
                var userHasAccessDic  = featurePermissionManager.HasAccess(subjects, feature.Id);

                foreach (var item in userPermissionDic)
                {
                    var subject   = subjects.Where(s => s.Id.Equals(item.Key)).FirstOrDefault();
                    var rightType = item.Value;
                    var hasAccess = userHasAccessDic[item.Key];

                    featurePermissions.Add(FeaturePermissionGridRowModel.Convert(subject, featureId, rightType, hasAccess));
                }


                return(View(new GridModel <FeaturePermissionGridRowModel> {
                    Data = featurePermissions, Total = count
                }));
            }
            finally
            {
                featureManager?.Dispose();
                featurePermissionManager?.Dispose();
                subjectManager?.Dispose();
            }
        }
Exemplo n.º 56
0
        /// <summary>
        /// Removes from the permissions all permissions that would be violated by the filter or aggregate select, the behavior
        /// of the system here is that when a user orders by a field that she has no full access too, she only sees the
        /// rows where she can see that field, sometimes resulting in a shorter list, this is to prevent the user gaining
        /// any insight over fields she has no access to by filter or order the data
        /// </summary>
        protected IEnumerable <AbstractPermission> FilterViolatedPermissionsForAggregateQuery(IEnumerable <AbstractPermission> permissions, MaskTree defaultMask, FilterExpression filter, AggregateSelectExpression select)
        {
            // Step 1 - Build the "User Mask", i.e the mask containing the fields mentioned in the relevant components of the user query
            var userMask = MaskTree.BasicFieldsMaskTree();

            userMask = UpdateUserMaskAsPerFilter(filter, userMask);
            userMask = UpdateUserMaskAsPerAggregateSelect(select, userMask);

            // Filter out those permissions whose mask does not cover the entire user mask
            return(FilterViolatedPermissionsInner(permissions, defaultMask, userMask));
        }
Exemplo n.º 57
0
        private LambdaExpression GetPredicateLambda(FilterExpression filter)
        {
            Expression body = Visit(filter, null);

            return(Expression.Lambda(body, LambdaScope.Parameter));
        }
Exemplo n.º 58
0
        public NotLikeOperator()
        {
            Func <string, string, bool> _filter = (str1, str2) => !str1.Contains(str2);

            Filter = FilterWrapper;
        }
Exemplo n.º 59
0
        public virtual async Task <AppPagedResultOutput <SoftLicenseListDto> > GetLicensePageList(long softId, GetPageListInput input)
        {
            var query = _softLicenseRepository.GetAll();

            var where = FilterExpression.FindByGroup <SoftLicense>(input.Filter);
            where     = where.And(t => t.SoftId == softId);


            var queryCount = query.Where(where)
                             .GroupJoin(_softUserRepository.GetAll(), softLicense => softLicense.SoftUserId, softUser => softUser.Id,
                                        (softLicense, softUser) => new
            {
                SoftLicense = softLicense,
                SoftUser    = softUser
            });

            if (FilterExpression.HasValue(input.Filter, "loginName"))
            {
                string value = FilterExpression.GetValue(input.Filter, "loginName");
                queryCount = queryCount.Where(t => t.SoftUser.FirstOrDefault().LoginName.Contains(value));
            }

            int count = await queryCount.CountAsync();


            var queryList = query.Where(where)
                            .GroupJoin(_softUserRepository.GetAll(), softLicense => softLicense.SoftUserId, softUser => softUser.Id,
                                       (softLicense, softUser) => new
            {
                SoftLicense = softLicense,
                SoftUser    = softUser
            });


            //queryList = queryList.Where(t => t.SoftUser.FirstOrDefault().LoginName.Contains("001"));
            if (FilterExpression.HasValue(input.Filter, "loginName"))
            {
                string value = FilterExpression.GetValue(input.Filter, "loginName");
                queryList = queryList.Where(t => t.SoftUser.FirstOrDefault().LoginName.Contains(value));
            }


            queryList = queryList.OrderByDescending(t => t.SoftLicense.CreationTime)
                        .PageBy(input);
            var list = await queryList.Select(t => new SoftLicenseListDto
            {
                Id                 = t.SoftLicense.Id,
                ApplyTime          = t.SoftLicense.ApplyTime,
                CreationTime       = t.SoftLicense.CreationTime,
                LicenseNo          = t.SoftLicense.LicenseNo,
                LicenseType        = t.SoftLicense.LicenseType,
                Price              = t.SoftLicense.Price,
                Status             = t.SoftLicense.Status,
                UseTime            = t.SoftLicense.UseTime,
                SoftUser_LoginName = t.SoftUser.FirstOrDefault().LoginName
            }).ToListAsync();

            var pageList = list;

            return(new AppPagedResultOutput <SoftLicenseListDto>(count, pageList, input.CurrentPage, input.PageSize));
        }
Exemplo n.º 60
0
        public async Task <List <PatientDisposition> > getPatientDisposition(string patientEncounter, string SearchFilters, string searchOrder, DateTime startDate, DateTime endDate)
        {
            List <PatientDisposition> PatientDisposition = new List <PatientDisposition>();
            mzk_patientorder          patientOrderEntity = new mzk_patientorder();

            #region Patient Procedure Query
            QueryExpression  query       = new QueryExpression(mzk_disposition.EntityLogicalName);
            FilterExpression childFilter = query.Criteria.AddFilter(LogicalOperator.And);

            if (patientEncounter != string.Empty)
            {
                childFilter.AddCondition("mzk_encounterid", ConditionOperator.Equal, new Guid(patientEncounter));
            }

            //Search Filter
            if (!string.IsNullOrEmpty(SearchFilters))
            {
                if (SearchFilters == Convert.ToString(mzk_dispositionfilter.InConsultation))
                {
                    childFilter.AddCondition("mzk_status", ConditionOperator.Equal, Convert.ToInt32(mzk_dispositionmzk_Status.InConsultation));
                }
                if (SearchFilters == Convert.ToString(mzk_dispositionfilter.ConsultationComplete))
                {
                    childFilter.AddCondition("mzk_status", ConditionOperator.Equal, Convert.ToInt32(mzk_dispositionmzk_Status.ConsultationComplete));
                }
                if (SearchFilters == Convert.ToString(mzk_dispositionfilter.EncounterSignedOff))
                {
                    childFilter.AddCondition("mzk_status", ConditionOperator.Equal, Convert.ToInt32(mzk_dispositionmzk_Status.EncounterSignedOff));
                }
            }

            //Search Order
            if (!string.IsNullOrEmpty(searchOrder))
            {
                // childFilter.AddCondition("mzk_productidname", ConditionOperator.Like, ("%" + searchOrder + "%"));

                //Search Date
                if (startDate != DateTime.MinValue && endDate != DateTime.MinValue)
                {
                    childFilter.AddCondition("createdon", ConditionOperator.Between, new Object[] { startDate, endDate.AddHours(12) });
                }
            }

            //Patient Order Type :: Disposition
            query.ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("mzk_followup",
                                                                    "mzk_comments", "mzk_asneeded",
                                                                    "mzk_descriptionofsicknotes",
                                                                    "mzk_sickstartdate",
                                                                    "mzk_sickenddate", "createdon", "modifiedon", "mzk_followupnumber", "mzk_outcome", "mzk_notes", "mzk_partnerhospitalid");

            #endregion
            SoapEntityRepository entityRepository = SoapEntityRepository.GetService();
            EntityCollection     entitycollection = entityRepository.GetEntityCollection(query);

            foreach (Entity entity in entitycollection.Entities)
            {
                if (Convert.ToDateTime(entity.Attributes["createdon"]) != Convert.ToDateTime(entity.Attributes["modifiedon"]))
                {
                    PatientDisposition model = new PatientDisposition();

                    if (entity.Attributes.Contains("mzk_asneeded") && Convert.ToBoolean(entity.Attributes["mzk_asneeded"]) == true)
                    {
                        model.Asneeded = "1";
                    }
                    else
                    {
                        model.Asneeded = "0";
                    }

                    if (entity.Attributes.Contains("mzk_followup"))
                    {
                        model.FollowUp     = ((OptionSetValue)entity.Attributes["mzk_followup"]).Value;
                        model.FollowUpText = entity.FormattedValues["mzk_followup"].ToString();
                    }

                    if (entity.Attributes.Contains("mzk_followupnumber"))
                    {
                        model.FollowUpNumber = ((OptionSetValue)entity.Attributes["mzk_followupnumber"]).Value;
                    }

                    if (entity.Attributes.Contains("mzk_comments"))
                    {
                        model.Comments = entity.Attributes["mzk_comments"].ToString();
                    }

                    if (entity.Attributes.Contains("mzk_descriptionofsicknotes"))
                    {
                        model.DescriptionofSickNotes = entity.Attributes["mzk_descriptionofsicknotes"].ToString();
                    }

                    if (entity.Attributes.Contains("mzk_sickstartdate"))
                    {
                        model.SickStartDate = Convert.ToDateTime(entity.Attributes["mzk_sickstartdate"]);
                    }


                    if (entity.Attributes.Contains("mzk_sickenddate"))
                    {
                        model.SickEndDate = Convert.ToDateTime(entity.Attributes["mzk_sickenddate"]);
                    }

                    if (entity.Attributes.Contains("mzk_dispositionid"))
                    {
                        model.Id = entity.Id.ToString();
                    }

                    if (entity.Attributes.Contains("createdon"))
                    {
                        model.CreatedOn = Convert.ToDateTime(entity.Attributes["createdon"]);
                    }

                    if (entity.Attributes.Contains("mzk_outcome"))
                    {
                        model.OutComeValue = ((OptionSetValue)entity.Attributes["mzk_outcome"]).Value;
                        model.OutComeName  = entity.FormattedValues["mzk_outcome"].ToString();
                    }

                    if (entity.Attributes.Contains("mzk_partnerhospitalid"))
                    {
                        model.PartnerHospitalId   = ((EntityReference)entity["mzk_partnerhospitalid"]).Id.ToString();
                        model.PartnerHospitalName = ((EntityReference)entity["mzk_partnerhospitalid"]).Name.ToString();
                    }

                    if (entity.Attributes.Contains("mzk_notes"))
                    {
                        model.Notes = entity.Attributes["mzk_notes"].ToString();
                    }

                    PatientDisposition.Add(model);
                }
            }

            return(PatientDisposition);
        }