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);
        }
示例#2
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;
        }
示例#3
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);

            }
        }
        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;
        }
        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;
        }
        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;
        }
        public async Task <List <PatientProcedure> > getPatientOrder(string patientguid, string patientEncounter, string SearchFilters, string searchOrder, DateTime startDate, DateTime endDate, bool forFulfillment, string orderId, string caseId = null, bool isCancel = true, int pageNumber = 0)
        {
            if (string.IsNullOrEmpty(patientguid) && string.IsNullOrEmpty(caseId) && string.IsNullOrEmpty(patientEncounter) && string.IsNullOrEmpty(orderId))
            {
                throw new ValidationException("Parameter missing");
            }

            List <PatientProcedure> PatientProcedure   = new List <PatientProcedure>();
            mzk_patientorder        patientOrderEntity = new mzk_patientorder();

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

            if (!string.IsNullOrEmpty(orderId))
            {
                childFilter.AddCondition("mzk_patientorderid", ConditionOperator.Equal, new Guid(orderId));
            }
            if (SearchFilters != mzk_orderstatus.Cancelled.ToString())
            {
                childFilter.AddCondition("mzk_orderstatus", ConditionOperator.NotEqual, (int)mzk_orderstatus.Cancelled);
            }
            if (!string.IsNullOrEmpty(caseId))
            {
                childFilter.AddCondition("mzk_caseid", ConditionOperator.Equal, new Guid(caseId));
            }
            if (!string.IsNullOrEmpty(patientguid))
            {
                childFilter.AddCondition("mzk_customer", ConditionOperator.Equal, new Guid(patientguid));
            }
            else if (!string.IsNullOrEmpty(patientEncounter))
            {
                childFilter.AddCondition("mzk_patientencounterid", ConditionOperator.Equal, new Guid(patientEncounter));
            }

            if (isCancel == false)
            {
                childFilter.AddCondition("mzk_orderstatus", ConditionOperator.NotEqual, Convert.ToInt32(mzk_orderstatus.Cancelled));
            }

            //Search Filter
            if (!string.IsNullOrEmpty(SearchFilters))
            {
                if (SearchFilters == Convert.ToString(mzk_procedurefilter.Ordered))
                {
                    childFilter.AddCondition("mzk_orderstatus", ConditionOperator.Equal, Convert.ToInt32(mzk_orderstatus.Ordered));
                }
                if (SearchFilters == Convert.ToString(mzk_procedurefilter.Started))
                {
                    childFilter.AddCondition("mzk_orderstatus", ConditionOperator.Equal, Convert.ToInt32(mzk_orderstatus.Started));
                }
                if (SearchFilters == Convert.ToString(mzk_procedurefilter.Canceled))
                {
                    childFilter.AddCondition("mzk_orderstatus", ConditionOperator.Equal, Convert.ToInt32(mzk_orderstatus.Cancelled));
                }
            }

            //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 :: Procedure
            childFilter.AddCondition("mzk_type", ConditionOperator.Equal, (int)mzk_patientordermzk_Type.Procedure);
            query.ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("mzk_patientorderid",
                                                                    "mzk_productid",
                                                                    "mzk_patientencounterid",
                                                                    "mzk_patientordernumber",
                                                                    "mzk_orderdate",
                                                                    "mzk_orderstatus",
                                                                    "mzk_comments",
                                                                    "mzk_userid", "createdon",
                                                                    "mzk_statusmanagerdetail",
                                                                    "mzk_treatmentlocation", "mzk_orderinglocation");

            LinkEntity EntityProduct = new LinkEntity("mzk_patientorder", "product", "mzk_productid", "productid", JoinOperator.LeftOuter);
            EntityProduct.Columns = new Microsoft.Xrm.Sdk.Query.ColumnSet("mzk_cptcodeid");

            LinkEntity EntityUser = new LinkEntity("mzk_patientorderid", "systemuser", "mzk_userid", "systemuserid", JoinOperator.LeftOuter);
            EntityUser.Columns = new Microsoft.Xrm.Sdk.Query.ColumnSet("positionid");

            query.LinkEntities.Add(EntityProduct);
            query.LinkEntities.Add(EntityUser);

            if (!forFulfillment && pageNumber > 0)
            {
                query.PageInfo                        = new Microsoft.Xrm.Sdk.Query.PagingInfo();
                query.PageInfo.Count                  = Convert.ToInt32(AppSettings.GetByKey("PageSize"));
                query.PageInfo.PageNumber             = pageNumber;
                query.PageInfo.PagingCookie           = null;
                query.PageInfo.ReturnTotalRecordCount = true;
            }
            #endregion
            SoapEntityRepository entityRepository = SoapEntityRepository.GetService();

            EntityCollection entitycollection = entityRepository.GetEntityCollection(query);

            foreach (Entity entity in entitycollection.Entities)
            {
                PatientProcedure model = new PatientProcedure();

                if (!this.getPatientOrder(model, entity, forFulfillment, orderId, mzk_entitytype.ProcedureOrder))
                {
                    continue;
                }

                if (entity.Attributes.Contains("mzk_productid"))
                {
                    model.Title = ((EntityReference)entity.Attributes["mzk_productid"]).Name;
                }

                if (entity.Attributes.Contains("product3.mzk_cptcodeid"))
                {
                    model.CPTCode = ((EntityReference)(entity.Attributes["product3.mzk_cptcodeid"] as AliasedValue).Value).Name;
                }
                else
                if (entity.Attributes.Contains("product1.mzk_cptcodeid"))
                {
                    model.CPTCode = ((EntityReference)(entity.Attributes["product1.mzk_cptcodeid"] as AliasedValue).Value).Name;
                }

                if (entity.Attributes.Contains("mzk_userid"))
                {
                    model.CareProvider   = ((EntityReference)entity.Attributes["mzk_userid"]).Name;
                    model.CareProviderId = ((EntityReference)entity.Attributes["mzk_userid"]).Id.ToString();
                }
                if (entity.Attributes.Contains("systemuser4.positionid"))
                {
                    model.Designation = ((EntityReference)(entity.Attributes["systemuser4.positionid"] as AliasedValue).Value).Name;
                }
                else
                if (entity.Attributes.Contains("systemuser2.positionid"))
                {
                    model.Designation = ((EntityReference)(entity.Attributes["systemuser2.positionid"] as AliasedValue).Value).Name;
                }
                if (entity.Attributes.Contains("mzk_comments"))
                {
                    model.Notes = entity.Attributes["mzk_comments"].ToString();
                }

                if (entity.Attributes.Contains("mzk_treatmentlocation"))
                {
                    model.treatmentLocationId = entity.GetAttributeValue <EntityReference>("mzk_treatmentlocation").Id.ToString();
                    model.treatmentLocation   = entity.GetAttributeValue <EntityReference>("mzk_treatmentlocation").Name;
                }

                PatientOrderLog log = this.getOrderStatusLogDetails(Convert.ToInt32(model.OrderStatus), model.Id);

                if (log != null)
                {
                    model.StatusNotes = log.Comments;
                }

                PatientProcedure.Add(model);
            }

            if (pageNumber > 0 && entitycollection != null)
            {
                Pagination.totalCount = entitycollection.TotalRecordCount;
            }

            return(PatientProcedure);
        }
示例#8
0
        public async Task <List <PatientTherapy> > getPatientOrder(string patientguid, string patientEncounter, string SearchFilters, string searchOrder, DateTime startDate, DateTime endDate, bool forFulfillment, string orderId, string caseId = null)
        {
            if (string.IsNullOrEmpty(patientguid) && string.IsNullOrEmpty(caseId) && string.IsNullOrEmpty(patientEncounter) && string.IsNullOrEmpty(orderId))
            {
                throw new ValidationException("Parameter missing");
            }

            List <PatientTherapy> PatientTherapy = new List <PatientTherapy>();

            #region Patient Therapies Query
            QueryExpression query = new QueryExpression("mzk_patientorder");

            FilterExpression childFilter = query.Criteria.AddFilter(LogicalOperator.And);

            childFilter.AddCondition("mzk_type", ConditionOperator.Equal, Convert.ToInt32(mzk_patientordermzk_Type.Thrapy));

            if (!string.IsNullOrEmpty(orderId))
            {
                childFilter.AddCondition("mzk_patientorderid", ConditionOperator.Equal, new Guid(orderId));
            }
            if (SearchFilters != mzk_orderstatus.Cancelled.ToString())
            {
                childFilter.AddCondition("mzk_orderstatus", ConditionOperator.NotEqual, (int)mzk_orderstatus.Cancelled);
            }
            if (!string.IsNullOrEmpty(caseId))
            {
                childFilter.AddCondition("mzk_caseid", ConditionOperator.Equal, new Guid(caseId));
            }

            if (!string.IsNullOrEmpty(patientguid))
            {
                childFilter.AddCondition("mzk_customer", ConditionOperator.Equal, new Guid(patientguid));
            }
            else if (!string.IsNullOrEmpty(patientEncounter))
            {
                childFilter.AddCondition("mzk_patientencounterid", ConditionOperator.Equal, new Guid(patientEncounter));
            }

            if (!string.IsNullOrEmpty(SearchFilters))
            {
                //if (SearchFilters == Convert.ToString(mzk_labfilter.Ordered))
                //    childFilter.AddCondition("mzk_orderstatus", ConditionOperator.Equal, Convert.ToInt32(mzk_orderstatus.Ordered));
                //if (SearchFilters == Convert.ToString(mzk_labfilter.Paid))
                //    childFilter.AddCondition("mzk_orderstatus", ConditionOperator.Equal, Convert.ToInt32(mzk_orderstatus.Paid));
                //if (SearchFilters == Convert.ToString(mzk_labfilter.Cancelled))
                //    childFilter.AddCondition("mzk_orderstatus", ConditionOperator.Equal, Convert.ToInt32(mzk_orderstatus.Cancelled));
            }
            //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) });
            }



            query.ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("mzk_patientorderid",
                                                                    "mzk_productid",
                                                                    "mzk_patientencounterid",
                                                                    "mzk_patientordernumber",
                                                                    "mzk_orderdate",
                                                                    "mzk_orderstatus",
                                                                    "mzk_comments", "mzk_frequencyid", "createdon");

            LinkEntity EntityFrequecy = new LinkEntity("mzk_patientorder", "mzk_ordersetup", "mzk_frequencyid", "mzk_ordersetupid", JoinOperator.LeftOuter);
            EntityFrequecy.Columns = new Microsoft.Xrm.Sdk.Query.ColumnSet("mzk_description");
            query.LinkEntities.Add(EntityFrequecy);

            #endregion
            SoapEntityRepository entityRepository = SoapEntityRepository.GetService();

            EntityCollection entitycollection = entityRepository.GetEntityCollection(query);

            foreach (Entity entity in entitycollection.Entities)
            {
                PatientTherapy model = new PatientTherapy();

                if (!this.getPatientOrder(model, entity, forFulfillment, orderId, mzk_entitytype.TherapyOrder))
                {
                    continue;
                }

                if (entity.Attributes.Contains("mzk_productid"))
                {
                    model.Therapy = ((EntityReference)entity["mzk_productid"]).Name;
                }

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

                if (entity.Attributes.Contains("mzk_frequencyid"))
                {
                    model.FrequencyId = ((EntityReference)entity.Attributes["mzk_frequencyid"]).Id.ToString();
                }

                if (entity.Attributes.Contains("mzk_ordersetup3.mzk_description"))
                {
                    model.Frequency = ((AliasedValue)entity.Attributes["mzk_ordersetup3.mzk_description"]).Value.ToString();
                }

                PatientTherapy.Add(model);
            }

            return(PatientTherapy);
        }
示例#9
0
        /// <summary>
        /// 根据关键字生成过滤条件
        /// </summary>
        /// <param name="queryExpression"></param>
        /// <param name="keyword"></param>
        /// <param name="fields"></param>
        private void MakeFilterByKeyword(QueryExpression queryExpression, string keyword, params string[] fields)
        {
            FilterExpression filter = new FilterExpression(LogicalOperator.Or);
            int i = 1;

            if (fields.NotEmpty())
            {
                var mainQFields = fields.Where(n => n.IndexOf('.') < 0).ToList();
                if (mainQFields.NotEmpty())
                {
                    foreach (var column in queryExpression.ColumnSet.Columns)//主表
                    {
                        if (mainQFields.NotEmpty() && !mainQFields.Contains(column))
                        {
                            if (i > mainQFields.Count())
                            {
                                break;
                            }

                            continue;
                        }
                        var attr = this.QueryResolver.AttributeList.Find(x => x.Name.IsCaseInsensitiveEqual(column) && x.EntityName.IsCaseInsensitiveEqual(this.QueryExpression.EntityName));
                        filter.AddCondition(GetCondition(attr, keyword));
                        i++;
                    }
                }
            }
            else
            {
                foreach (var column in queryExpression.ColumnSet.Columns)//主表
                {
                    var attr = this.QueryResolver.AttributeList.Find(x => x.Name.IsCaseInsensitiveEqual(column) && x.EntityName.IsCaseInsensitiveEqual(this.QueryExpression.EntityName));
                    filter.AddCondition(GetCondition(attr, keyword));
                    i++;
                }
            }
            if (i > 1)
            {
                queryExpression.Criteria.AddFilter(filter);
            }
            if (fields.NotEmpty() && i > fields.Count())//如果在主实体已匹配完则返回
            {
                return;
            }
            if (queryExpression.LinkEntities.NotEmpty())
            {
                foreach (var le in queryExpression.LinkEntities)//关联表
                {
                    var leColumns   = queryExpression.GetAllColumns(le, this.QueryResolver.AttributeList);
                    var linkQFields = leColumns.Where(n => n.IndexOf('.') > 0 && n.Split('.')[0].IsCaseInsensitiveEqual(le.EntityAlias)).ToList();//.Select(n => n.Split('.')[1]).ToArray();
                    if (linkQFields.IsEmpty())
                    {
                        continue;
                    }

                    foreach (var column in linkQFields)
                    {
                        var field = column.Split('.')[1];
                        var attr  = this.QueryResolver.AttributeList.Find(x => x.Name.IsCaseInsensitiveEqual(field) && x.EntityName.IsCaseInsensitiveEqual(le.LinkToEntityName));
                        if (attr == null)
                        {
                            continue;
                        }

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

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

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


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

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

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

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

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

                EntityCollection invoicedetails = service.RetrieveMultiple(query);

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

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

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

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

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

                    service.Update(detail);
                }

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

                service.Update(invoice);
            }
        }
示例#11
0
        public void Execute(IServiceProvider serviceProvider)
        {
            // Create a tracing service to add instrumentation.
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            tracingService.Trace("Starting DoNotAllowBookingAtSameTime at " + DateTime.Now.ToString());
            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = (IPluginExecutionContext)
                                              serviceProvider.GetService(typeof(IPluginExecutionContext));
            // Obtain the organization service reference.
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                //Confirm that the input from the execution pipeline is the right type to work with.
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    // Obtain the target entity from the input parameters.
                    Entity entity = (Entity)context.InputParameters["Target"];
                    //Check to see if this is a create of a new employee booking.
                    if (context.MessageName == "Create")
                    {
                        QueryExpression query = new QueryExpression();
                        query.ColumnSet  = new ColumnSet(true);
                        query.EntityName = "msft_employeebooking";

                        FilterExpression fe = new FilterExpression();
                        fe.FilterOperator = LogicalOperator.And;
                        ConditionExpression ceArea = new ConditionExpression();
                        ceArea.AttributeName = "msft_areaid";
                        ceArea.Operator      = ConditionOperator.Equal;
                        ceArea.Values.Add(((EntityReference)entity.Attributes["msft_areaid"]).Id);

                        ConditionExpression ceFacility = new ConditionExpression();
                        ceFacility.AttributeName = "msft_facilityid";
                        ceFacility.Operator      = ConditionOperator.Equal;
                        ceFacility.Values.Add(((EntityReference)entity.Attributes["msft_facilityid"]).Id);

                        //On or After Arrival Start Time
                        ConditionExpression ceStartTime = new ConditionExpression();
                        ceStartTime.AttributeName = "msft_arrivaltimestart";
                        ceStartTime.Operator      = ConditionOperator.OnOrAfter;
                        ceStartTime.Values.Add(entity.Attributes["msft_arrivaltimestart"]);

                        //On or before Arrival End Time
                        ConditionExpression ceDepartTime = new ConditionExpression();
                        ceDepartTime.AttributeName = "msft_arrivaltimeend";
                        ceDepartTime.Operator      = ConditionOperator.OnOrBefore;
                        ceDepartTime.Values.Add(entity.Attributes["msft_arrivaltimeend"]);

                        fe.AddCondition(ceArea);
                        fe.AddCondition(ceFacility);
                        fe.AddCondition(ceStartTime);
                        fe.AddCondition(ceDepartTime);
                        query.Criteria = new FilterExpression();
                        query.Criteria = fe;
                        //Order by Start Arrival Time ascending
                        query.AddOrder("msft_arrivaltimestart", OrderType.Ascending);

                        RetrieveMultipleRequest request = new RetrieveMultipleRequest();
                        request.Query = query;

                        tracingService.Trace("Executing the Query for entity {0}", query.EntityName);
                        Collection <Entity> entityList = ((RetrieveMultipleResponse)service.Execute(request)).EntityCollection.Entities;
                        tracingService.Trace("Returned the Query Response for entity {0}", query.EntityName);
                        if (entityList.Count > 0)
                        {
                            //Get Area Capacity
                            Entity area = service.Retrieve("msft_area", ((EntityReference)entity.Attributes["msft_areaid"]).Id, new ColumnSet("msft_capacity"));
                            tracingService.Trace(String.Format("Found Area with capacity of {0}", (int)area.Attributes["msft_capacity"]));
                            //Define counter to count current active bookings.
                            int      currentBookingsWithinRequest = 0;
                            DateTime requestedStartTime           = (DateTime)entity.Attributes["msft_arrivaltimestart"];
                            DateTime requestedDepartTime          = (DateTime)entity.Attributes["msft_arrivaltimeend"];
                            foreach (Entity previousBooking in entityList)
                            {
                                //Does the current requested booking start date equal or greater?
                                bool isRequestedStartTimeValid  = true;
                                bool isRequestedDepartTimeValid = true;
                                if (requestedStartTime >= (DateTime)previousBooking.Attributes["msft_arrivaltimestart"])
                                {
                                    //If so, does it start before the depart time of this booking?
                                    if (requestedDepartTime <= (DateTime)previousBooking.Attributes["msft_arrivaltimeend"])
                                    {
                                        tracingService.Trace(String.Format("Found existing arrival time of {0} this matches requested {1}", (DateTime)previousBooking.Attributes["msft_arrivaltimestart"], (DateTime)previousBooking.Attributes["msft_arrivaltimestart"]));
                                        isRequestedStartTimeValid = false;
                                    }
                                }//Is the request depart time later than the previous start time?
                                if (requestedDepartTime > (DateTime)previousBooking.Attributes["msft_arrivaltimestart"])
                                {
                                    if (requestedStartTime < (DateTime)previousBooking.Attributes["msft_arrivaltimeend"])
                                    {
                                        tracingService.Trace(String.Format("Found existing arrival time of {0} this matches requested {1}", (DateTime)previousBooking.Attributes["msft_arrivaltimestart"], (DateTime)previousBooking.Attributes["msft_arrivaltimestart"]));
                                        isRequestedDepartTimeValid = false;
                                    }
                                    else
                                    {
                                    }
                                }
                                if (!isRequestedStartTimeValid || !isRequestedDepartTimeValid)
                                {
                                    currentBookingsWithinRequest++;
                                }
                            }
                            //if current bookings are greater than capacity, do not allow.
                            if ((int)area.Attributes["msft_capacity"] <= currentBookingsWithinRequest)
                            {
                                throw new Exception("Unable to book due to max capacity");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }
示例#12
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 ExecuteQuoteCreateOrder(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

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

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

            //throw new InvalidPluginExecutionException("It's the quote order creation that stinks!");
            if (context.Depth > 1)
            {
                return;
            }
            else
            {

                var customerID = (EntityReference)quote["customerid"];

                var customer = service.Retrieve(customerID.LogicalName, customerID.Id,
                    new ColumnSet() { AllColumns = true });

                if (quote.Contains("new_createinvoice"))
                {
                    var salesorderType = (OptionSetValue)quote["new_createinvoice"];

                    if (salesorderType.Value == 1)
                    {
                        string quoteName = "";

                        if (quote.Contains("name"))
                        {
                            quoteName = (string)quote["name"];

                        }
                        else
                        {
                            quoteName = "New";
                        }
                        bool isTaxed = ((OptionSetValue)quote["new_vat"]).Value == 20;

                        string orderProductName = "Advance payment for " + quoteName;
                        var prepayedAmount = (Money)quote["new_prepayedamount"];
                        var advanceProductId = "14";
                        var currency = (EntityReference)quote["transactioncurrencyid"];
                        decimal taxer = new Decimal(1.20);
                        var prepaymentwithTax = new Money(prepayedAmount.Value * taxer);
                        var salesorder = new Entity("salesorder");
                        salesorder["name"] = quoteName + " Invoice Order for the Prepayment";
                        salesorder["quoteid"] = new EntityReference(quote.LogicalName, quote.Id);
                        salesorder["transactioncurrencyid"] = new EntityReference(currency.LogicalName, currency.Id);
                        salesorder["customerid"] = new EntityReference(customer.LogicalName, customer.Id);
                        salesorder["pricelevelid"] = (EntityReference)quote["pricelevelid"];
                        salesorder["new_recommendedtotal"] = prepayedAmount;
                        salesorder["new_vat"] = new OptionSetValue(((OptionSetValue)quote["new_vat"]).Value);
                        salesorder["new_pricingtype"] = new OptionSetValue(((OptionSetValue)quote["new_pricingtype"]).Value);
                        salesorder["new_reloadflag"] = false;
                        if (isTaxed)
                        {
                            salesorder["new_totalamountincludingvat"] = prepaymentwithTax;
                        }
                        else
                        {
                            salesorder["new_totalamountincludingvat"] = prepayedAmount;
                        }

                        var orderID = (Guid)service.Create(salesorder);


                        //Create the order detail
                        var orderProduct = new Entity("salesorderdetail");

                        orderProduct["salesorderid"] = new EntityReference("salesorder", orderID);

                        //////retrieve product

                        ConditionExpression condition = new ConditionExpression();
                        condition.AttributeName = "name";
                        condition.Operator = ConditionOperator.Equal;
                        condition.Values.Add("pc");

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

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


                        // Query for the UOM

                        ConditionExpression conditionProduct = new ConditionExpression();
                        conditionProduct.AttributeName = "productnumber";
                        conditionProduct.Operator = ConditionOperator.Equal;
                        conditionProduct.Values.Add(advanceProductId);

                        FilterExpression filterProduct = new FilterExpression();
                        filterProduct.AddCondition(conditionProduct);

                        QueryExpression queryProduct = new QueryExpression();
                        queryProduct.EntityName = "product";
                        queryProduct.ColumnSet = new ColumnSet(true);
                        queryProduct.Criteria = filterProduct;


                        EntityCollection uomCollection = service.RetrieveMultiple(query);
                        EntityCollection productCollection = service.RetrieveMultiple(queryProduct);
                        //uom.Entities.F

                        var firstUom = uomCollection.Entities.FirstOrDefault();
                        var firstProduct = productCollection.Entities.FirstOrDefault();
                        //foreach (var product in uom.Entities)
                        //{
                        //    orderProduct["productid"] = product.ToEntityReference();
                        //}


                        //EntityCollection uoms = service.RetrieveMultiple(unitQuery);
                        //var uomProduct = uoms.Entities[0];
                        //var uom = service.Retrieve("uom", new Guid("06EBB338-468D-437B-B547-A3E600EB9A97"), new ColumnSet(){AllColumns=true});
                        var uom = service.Retrieve(firstUom.LogicalName, firstUom.Id, new ColumnSet() { AllColumns = true });
                        //throw new InvalidPluginExecutionException(firstProduct.Id.ToString());

                        //var product = service.Retrieve("product", new Guid("0DD28827-C9D5-E311-9397-00155D0A4E33"), new ColumnSet(){AllColumns=true});
                        var product = service.Retrieve(firstProduct.LogicalName, firstProduct.Id, new ColumnSet() { AllColumns = true });
                        orderProduct["productid"] = new EntityReference("product", product.Id);
                        orderProduct["uomid"] = new EntityReference("uom", uom.Id);
                        orderProduct["description"] = (string)orderProductName;
                        orderProduct["tax"] = (decimal)0;
                        orderProduct["new_pricingtype"] = new OptionSetValue(((OptionSetValue)quote["new_pricingtype"]).Value);
                        orderProduct["priceperunit"] = new Money(prepayedAmount.Value);
                        orderProduct["quantity"] = (decimal)1;
                        //rderProduct["new_pricingtype"] = new OptionSetValue(3);
                        orderProduct["new_ratio"] = (decimal)1;
                        orderProduct["manualdiscountamount"] = new Money(0);
                        orderProduct["new_specificdiscountpercentage"] = (decimal)0;
                        orderProduct["new_grossannualincome"] = new Money(prepayedAmount.Value);
                        orderProduct["new_gaixratio"] = new Money(prepayedAmount.Value);
                        orderProduct["new_recommendedvalue"] = new Money(prepayedAmount.Value);
                        orderProduct["new_fixedpriceplusratio"] = new Money(prepayedAmount.Value);


                        service.Create(orderProduct);
                        //throw new InvalidPluginExecutionException(prepayedAmount.Value.ToString());

                        //service.Update(salesorder);


                    }
                    else if (salesorderType.Value == 2)
                    {

                        string quoteName = (string)quote["name"];
                        string orderProductName = "Advance payment for " + quoteName;
                        var prepayedAmount = (Money)quote["new_prepayedamount"];

                        var salesorder = new Entity("salesorder");
                        salesorder["name"] = quote["name"] + " Invoice Order for the Residual";
                        salesorder["quoteid"] = new EntityReference(quote.LogicalName, quote.Id);
                        salesorder["customerid"] = new EntityReference(customer.LogicalName, customer.Id);
                        salesorder["pricelevelid"] = (EntityReference)quote["pricelevelid"];
                        salesorder["new_recommendedtotal"] = (Money)quote["new_prepayedamount"];
                        salesorder["new_vat"] = new OptionSetValue(((OptionSetValue)quote["new_vat"]).Value);
                        salesorder["new_pricingtype"] = new OptionSetValue(((OptionSetValue)quote["new_pricingtype"]).Value);
                        salesorder["new_reloadflag"] = false;

                        var orderID = (Guid)service.Create(salesorder);


                        //Create the order detail
                        var orderProduct = new Entity("salesorderdetail");

                        orderProduct["salesorderid"] = new EntityReference("salesorder", orderID);

                        //////retrieve product

                        ConditionExpression condition = new ConditionExpression();
                        condition.AttributeName = "name";
                        condition.Operator = ConditionOperator.Equal;
                        condition.Values.Add("pc");

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

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


                        // Query for the UOM

                        ConditionExpression conditionProduct = new ConditionExpression();
                        conditionProduct.AttributeName = "productnumber";
                        conditionProduct.Operator = ConditionOperator.Equal;
                        conditionProduct.Values.Add("14");

                        FilterExpression filterProduct = new FilterExpression();
                        filterProduct.AddCondition(conditionProduct);

                        QueryExpression queryProduct = new QueryExpression();
                        queryProduct.EntityName = "product";
                        queryProduct.ColumnSet = new ColumnSet(true);
                        queryProduct.Criteria = filterProduct;


                        EntityCollection uomCollection = service.RetrieveMultiple(query);
                        EntityCollection productCollection = service.RetrieveMultiple(queryProduct);
                        //uom.Entities.F

                        var firstUom = uomCollection.Entities.FirstOrDefault();
                        var firstProduct = productCollection.Entities.FirstOrDefault();

                        var uom = service.Retrieve(firstUom.LogicalName, firstUom.Id, new ColumnSet() { AllColumns = true });

                        var product = service.Retrieve(firstProduct.LogicalName, firstProduct.Id, new ColumnSet() { AllColumns = true });
                        orderProduct["productid"] = new EntityReference("product", product.Id);
                        orderProduct["uomid"] = new EntityReference("uom", uom.Id);
                        orderProduct["description"] = (string)orderProductName;
                        orderProduct["tax"] = (decimal)0;
                        orderProduct["new_pricingtype"] = new OptionSetValue(((OptionSetValue)quote["new_pricingtype"]).Value);
                        orderProduct["priceperunit"] = new Money(prepayedAmount.Value);
                        orderProduct["quantity"] = (decimal)1;
                        orderProduct["new_pricingtype"] = new OptionSetValue(1);
                        orderProduct["new_ratio"] = (decimal)1;
                        orderProduct["manualdiscountamount"] = new Money(0);
                        orderProduct["new_specificdiscountpercentage"] = (decimal)0;
                        orderProduct["new_grossannualincome"] = new Money(prepayedAmount.Value);
                        orderProduct["new_gaixratio"] = new Money(prepayedAmount.Value);
                        orderProduct["new_recommendedvalue"] = new Money(prepayedAmount.Value);
                        orderProduct["new_fixedpriceplusratio"] = new Money(prepayedAmount.Value);

                        service.Create(orderProduct);
                    };
                }
            }
        }
        private void PerformSyncActions(Entity targetGeneric)
        {
            targetGeneric.Require(nameof(targetGeneric));

            var customJob = new CustomJob();

            // post
            if ((Context as IPluginExecutionContext)?.Stage == 40)
            {
                Log.Log("Processing post-operation actions ...");

                var postImage = Context.PostEntityImages.FirstOrDefault().Value?.ToEntity <CustomJob>();

                if (postImage == null && Context.MessageName == "Update")
                {
                    throw new InvalidPluginExecutionException("A full post image must be registered on this plugin step.");
                }

                postImage = postImage ?? targetGeneric.ToEntity <CustomJob>();

                foreach (var attribute in postImage.Attributes)
                {
                    customJob[attribute.Key] = attribute.Value;
                }

                ValidateJobParams(customJob);

                if (string.IsNullOrEmpty(customJob.Name))
                {
                    Log.Log("Name is empty, updating ...");
                    Service.Update(
                        new CustomJob
                    {
                        Id   = customJob.Id,
                        Name = BuildJobName(customJob)
                    });
                    Log.Log("Name was empty, updated.");
                }

                return;
            }

            if (Context.MessageName == "Update")
            {
                Log.Log("Update message, fetching target job from CRM ...");
                customJob = Service.Retrieve(targetGeneric.LogicalName, targetGeneric.Id, new ColumnSet(true))
                            .ToEntity <CustomJob>();
                Log.Log("Fetched target job from CRM.");
            }

            foreach (var attribute in targetGeneric.Attributes)
            {
                customJob[attribute.Key] = attribute.Value;
            }

            // fill page if empty
            if (customJob.RecordsPerPage != null && customJob.PageNumber == null)
            {
                Log.Log("Records per page set, but not the page number; setting to '1'.");
                targetGeneric[CustomJob.Fields.PageNumber] = 1;
            }

            // clear failed targets as we are starting over and reset retry runs
            if (customJob.StatusReason == CustomJob.StatusReasonEnum.Draft)
            {
                Log.Log("Draft status.");
                Log.Log("Clearing retry run, page number, cookie, and last message.");
                targetGeneric[CustomJob.Fields.CurrentRetryRun]  = null;
                targetGeneric[CustomJob.Fields.PageNumber]       = null;
                targetGeneric[CustomJob.Fields.PagingCookie]     = null;
                targetGeneric[CustomJob.Fields.LatestRunMessage] = null;

                Log.Log("Loading failed targets for this job ...");
                var tempJob =
                    new CustomJob
                {
                    Id = customJob.Id
                };
                tempJob.LoadRelation(CustomJob.RelationNames.CustomJobFailedTargetsOfCustomJob, Service);
                Log.Log("Loaded failed targets for this job.");

                if (tempJob.CustomJobFailedTargetsOfCustomJob != null)
                {
                    Log.Log($"Failed targets: {tempJob.CustomJobFailedTargetsOfCustomJob.Length}.");
                    var failures = tempJob.CustomJobFailedTargetsOfCustomJob;

                    var request =
                        new ExecuteMultipleRequest
                    {
                        Requests = new OrganizationRequestCollection(),
                        Settings =
                            new ExecuteMultipleSettings
                        {
                            ContinueOnError = true,
                            ReturnResponses = false
                        }
                    };

                    Log.Log($"Deleting failed targets ...");
                    for (var i = 0; i < Math.Ceiling(failures.Length / 1000d); i++)
                    {
                        request.Requests.Clear();
                        request.Requests.AddRange(failures.Skip(i * 1000).Take(1000)
                                                  .Select(failure =>
                                                          new DeleteRequest
                        {
                            Target = new EntityReference(CustomJobFailedTarget.EntityLogicalName,
                                                         failure.Id)
                        }));

                        Service.Execute(request);
                    }
                    Log.Log($"Deleted failed targets.");
                }
            }

            // cancel active sub-jobs
            if (customJob.StatusReason == CustomJob.StatusReasonEnum.Draft ||
                customJob.StatusReason == CustomJob.StatusReasonEnum.Cancelled)
            {
                Log.Log($"{customJob.StatusReason} status.");
                var tempJob =
                    new CustomJob
                {
                    Id = customJob.Id
                };

                Log.Log("Loading active children of this job ...");
                var filter = new FilterExpression();
                filter.AddCondition(CustomJob.Fields.Status, ConditionOperator.Equal, (int)CustomJob.StatusEnum.Active);
                tempJob.LoadRelation(CustomJob.RelationNames.CustomJobsOfParentJob, Service, false, filter);
                Log.Log("Loaded active children of this job.");

                if (tempJob.CustomJobsOfParentJob != null)
                {
                    Log.Log($"Active children: {tempJob.CustomJobsOfParentJob.Length}.");
                    foreach (var job in tempJob.CustomJobsOfParentJob)
                    {
                        Log.Log($"Setting sub job '{job.Id}' to cancelled ...");
                        Service.Update(
                            new CustomJob
                        {
                            Id           = job.Id,
                            Status       = CustomJob.StatusEnum.Inactive,
                            StatusReason = CustomJob.StatusReasonEnum.Cancelled
                        });
                        Log.Log($"Set sub job '{job.Id}' to cancelled.");
                    }
                }
            }

            var isNamingFieldsUpdated = targetGeneric.Attributes.Keys
                                        .Any(key => new[]
            {
                CustomJob.Fields.TargetLogicalName,
                CustomJob.Fields.ActionName,
                CustomJob.Fields.Workflow,
                CustomJob.Fields.TargetID,
                CustomJob.Fields.TargetXML
            }.Contains(key));

            if (string.IsNullOrEmpty(customJob.Name) || isNamingFieldsUpdated)
            {
                targetGeneric[CustomJob.Fields.Name] = BuildJobName(customJob);
                Log.Log($"Set job name to '{targetGeneric[CustomJob.Fields.Name]}'.");
            }

            if (customJob.StatusReason == CustomJob.StatusReasonEnum.Draft &&
                customJob.MarkForWaiting == true && customJob.TargetDate != null &&
                Context.MessageName != "Create")
            {
                Log.Log("Setting job to waiting because of flag ...");
                targetGeneric[CustomJob.Fields.MarkForWaiting] = false;
                targetGeneric[CustomJob.Fields.StatusReason]   = CustomJob.StatusReasonEnum.Waiting.ToOptionSetValue();
                Log.Log("Set job to waiting because of flag.");
            }
        }
示例#14
0
        public void ProcessExport(IEnumerable <ExportRecordType> exports, bool includeNotes, bool includeNNBetweenEntities, LogController controller
                                  , Action <Entity> processEntity, Action <Entity> processAssociation)
        {
            if (exports == null || !exports.Any())
            {
                throw new Exception("Error No Record Types To Export");
            }
            var countToExport  = exports.Count();
            var countsExported = 0;
            var exported       = new Dictionary <string, List <Entity> >();

            foreach (var exportType in exports)
            {
                var type           = exportType.RecordType == null ? null : exportType.RecordType.Key;
                var thisTypeConfig = XrmRecordService.GetTypeConfigs().GetFor(type);
                controller.UpdateProgress(countsExported++, countToExport, string.Format("Querying {0} Records", type));
                var conditions = new List <ConditionExpression>();
                if (type == "list")
                {
                    conditions.Add(new ConditionExpression("type", ConditionOperator.Equal, XrmPicklists.ListType.Dynamic));
                }
                if (type == "knowledgearticle")
                {
                    conditions.Add(new ConditionExpression("islatestversion", ConditionOperator.Equal, true));
                }
                //doesn't work for too many notes
                //should have option on each or all entities for notes maybe
                IEnumerable <Entity> entities;
                switch (exportType.Type)
                {
                case ExportType.AllRecords:
                {
                    entities = XrmService.RetrieveAllAndClauses(type, conditions)
                               .Where(e => !CheckIgnoreForExport(exportType, e))
                               .ToArray();
                    break;
                }

                case ExportType.FetchXml:
                {
                    var queryExpression = XrmService.ConvertFetchToQueryExpression(exportType.FetchXml);
                    queryExpression.ColumnSet = new ColumnSet(true);
                    entities = queryExpression.PageInfo != null && queryExpression.PageInfo.Count > 0
                                ? XrmService.RetrieveFirstX(queryExpression, queryExpression.PageInfo.Count)
                                : XrmService.RetrieveAll(queryExpression);
                    entities = entities
                               .Where(e => !CheckIgnoreForExport(exportType, e))
                               .ToArray();
                    break;
                }

                case ExportType.SpecificRecords:
                {
                    var primaryKey = XrmService.GetPrimaryKeyField(type);
                    var ids        = exportType.SpecificRecordsToExport == null
                                ? new HashSet <string>()
                                : new HashSet <string>(exportType.SpecificRecordsToExport
                                                       .Select(r => r.Record == null ? null : r.Record.Id)
                                                       .Where(s => !s.IsNullOrWhiteSpace()).Distinct());
                    entities = ids.Any()
                                ? XrmService.RetrieveAllOrClauses(type,
                                                                  ids.Select(
                                                                      i => new ConditionExpression(primaryKey, ConditionOperator.Equal, new Guid(i))))
                                : new Entity[0];
                    entities = entities.Where(e => ids.Contains(e.Id.ToString())).ToArray();
                    break;
                }

                default:
                {
                    throw new NotImplementedException(string.Format("No Export Implemented For {0} {1} For {2} Records", typeof(ExportType).Name, exportType.Type, type));
                }
                }

                var excludeFields = exportType.IncludeAllFields
                    ? new string[0]
                    : XrmService.GetFields(exportType.RecordType.Key).Except(exportType.IncludeOnlyTheseFields.Select(f => f.RecordField == null ? null : f.RecordField.Key).Distinct().ToArray());

                if (thisTypeConfig != null)
                {
                    //which need to include the fields if they are needed for parentchild configs
                    excludeFields = excludeFields.Except(new[] { thisTypeConfig.ParentLookupField }).ToArray();
                    if (thisTypeConfig.UniqueChildFields != null)
                    {
                        foreach (var item in entities)
                        {
                            excludeFields = excludeFields.Except(thisTypeConfig.UniqueChildFields).ToArray();
                            foreach (var uniqueField in thisTypeConfig
                                     .UniqueChildFields
                                     .Where(ucf => XrmService.IsLookup(ucf, thisTypeConfig.Type)))
                            {
                                AddReferencedFieldsConfigFields(item, item, uniqueField);
                            }
                        }
                    }

                    var fieldsToIncludeInParent = XrmRecordService.GetTypeConfigs().GetParentFieldsRequiredForComparison(type);
                    var thisTypesParentsConfig  = XrmRecordService.GetTypeConfigs().GetFor(thisTypeConfig.ParentLookupType);
                    if (fieldsToIncludeInParent != null)
                    {
                        //if the parent also has a config then we need to use it when matching the parent
                        //e.g. portal web page access rules -> web page where the web page may be a master or child web page
                        //so lets include the parents config fields as aliased fields in the exported entity
                        foreach (var item in entities)
                        {
                            AddReferencedFieldsConfigFields(item, item, thisTypeConfig.ParentLookupField);
                        }
                    }

                    var lookupFieldsEnsureNamePopulated = new List <string>();
                    if (thisTypeConfig.ParentLookupField != null)
                    {
                        lookupFieldsEnsureNamePopulated.Add(thisTypeConfig.ParentLookupField);
                    }
                    if (thisTypeConfig.UniqueChildFields != null)
                    {
                        lookupFieldsEnsureNamePopulated.AddRange(thisTypeConfig.UniqueChildFields.Where(f => XrmService.IsLookup(f, thisTypeConfig.Type)));
                    }
                    foreach (var field in lookupFieldsEnsureNamePopulated)
                    {
                        controller.UpdateProgress(countsExported, countToExport, string.Format("Populating Empty Lookups For {0} Records", type));
                        foreach (var item in entities)
                        {
                            var entityReference = item.GetField(field) as EntityReference;
                            if (entityReference != null && entityReference.Name == null)
                            {
                                var referencedTypeNameField = XrmService.GetPrimaryNameField(entityReference.LogicalName);
                                var referencedRecord        = XrmService.Retrieve(entityReference.LogicalName, entityReference.Id, new[] { referencedTypeNameField });
                                entityReference.Name = referencedRecord.GetStringField(referencedTypeNameField);
                            }
                        }
                    }
                }

                var primaryField = XrmService.GetPrimaryNameField(exportType.RecordType.Key);
                if (excludeFields.Contains(primaryField))
                {
                    excludeFields = excludeFields.Except(new[] { primaryField }).ToArray();
                }

                if (exportType.ExplicitValuesToSet != null)
                {
                    foreach (var field in exportType.ExplicitValuesToSet)
                    {
                        var parseFieldValue = XrmRecordService.ToEntityValue(field.ClearValue ? null : field.ValueToSet);
                        foreach (var entity in entities)
                        {
                            entity.SetField(field.FieldToSet.Key, parseFieldValue, XrmService);
                        }
                        if (excludeFields.Contains(field.FieldToSet.Key))
                        {
                            excludeFields = excludeFields.Except(new[] { field.FieldToSet.Key }).ToArray();
                        }
                    }
                }

                var fieldsAlwaysExclude = new[] { "calendarrules" };
                excludeFields = excludeFields.Union(fieldsAlwaysExclude).ToArray();

                var toDo = entities.Count();
                var done = 0;

                var typesDontInlcudeNull = new[] { AttributeTypeCode.Uniqueidentifier };
                var fieldsPopulateIfNull = exportType.IncludeAllFields
                    ? XrmService.GetFields(exportType.RecordType.Key)
                                           .Select(f => XrmService.GetFieldMetadata(f, exportType.RecordType.Key))
                                           .Where(fm => fm.AttributeType.HasValue && !typesDontInlcudeNull.Contains(fm.AttributeType.Value))
                                           .Select(fm => fm.LogicalName)
                                           .ToArray()
                    : exportType.IncludeOnlyTheseFields.Select(f => f.RecordField.Key);

                foreach (var entity in entities)
                {
                    controller.UpdateLevel2Progress(done++, toDo, string.Format("Processing {0} Records", type));
                    entity.RemoveFields(excludeFields.Union(new[] { "safedescription" }));
                    var fieldsSetNull = fieldsPopulateIfNull
                                        .Where(k => entity.GetField(k) == null)
                                        .ToArray();
                    foreach (var setNull in fieldsSetNull)
                    {
                        entity.SetField(setNull, null);
                    }
                    processEntity(entity);
                }
                controller.TurnOffLevel2();
                if (!exported.ContainsKey(type))
                {
                    exported.Add(type, new List <Entity>());
                }
                exported[type].AddRange(entities);
                if (includeNotes)
                {
                    controller.LogLiteral(string.Format("Querying Notes For {0} Records", type));
                    //if less than 10k entities query matching ids, else just get all for entity type
                    var notes = entities.Count() < 10000
                        ? XrmService.RetrieveAllOrClauses(Entities.annotation,
                                                          entities.Select(e =>
                    {
                        var filter = new FilterExpression(LogicalOperator.And);
                        filter.AddCondition(new ConditionExpression(Fields.annotation_.objecttypecode, ConditionOperator.Equal, type));
                        filter.AddCondition(new ConditionExpression(Fields.annotation_.objectid, ConditionOperator.Equal, e.Id));
                        return(filter);
                    }), null)
                        : XrmService
                                .RetrieveAllOrClauses(Entities.annotation,
                                                      new[] { new ConditionExpression(Fields.annotation_.objecttypecode, ConditionOperator.Equal, type) });

                    toDo = notes.Count();
                    done = 0;
                    XrmService.PopulateReferenceNames(notes
                                                      .Select(n => n.GetField(Fields.annotation_.objectid))
                                                      .Where(rf => rf != null)
                                                      .Cast <EntityReference>());
                    foreach (var note in notes)
                    {
                        var objectId = note.GetLookupGuid(Fields.annotation_.objectid);
                        if (objectId.HasValue && entities.Select(e => e.Id).Contains(objectId.Value))
                        {
                            AddReferencedFieldsConfigFields(note, note, Fields.annotation_.objectid);
                            controller.UpdateLevel2Progress(done++, toDo, string.Format("Processing Notes For {0} Records", type));
                            processEntity(note);
                        }
                    }
                    controller.TurnOffLevel2();

                    if (type == Entities.email)
                    {
                        controller.LogLiteral("Querying Email Attachments");
                        //if less than 10k entities query matching ids, else just get all for entity type
                        var attachments = entities.Count() < 10000
                            ? XrmService.RetrieveAllOrClauses(Entities.activitymimeattachment,
                                                              entities.Select(e => new ConditionExpression(Fields.activitymimeattachment_.activityid, ConditionOperator.Equal, e.Id)))
                            : XrmService
                                          .RetrieveAllOrClauses(Entities.activitymimeattachment,
                                                                new[] { new ConditionExpression(Fields.activitymimeattachment_.objecttypecode, ConditionOperator.Equal, type) });

                        toDo = attachments.Count();
                        done = 0;
                        XrmService.PopulateReferenceNames(attachments
                                                          .Select(n => n.GetField(Fields.activitymimeattachment_.activityid))
                                                          .Union(attachments.Select(n => n.GetField(Fields.activitymimeattachment_.objectid)))
                                                          .Where(rf => rf != null)
                                                          .Cast <EntityReference>());
                        foreach (var attachment in attachments)
                        {
                            var objectId = attachment.GetLookupGuid(Fields.activitymimeattachment_.activityid);
                            if (objectId.HasValue && entities.Select(e => e.Id).Contains(objectId.Value))
                            {
                                controller.UpdateLevel2Progress(done++, toDo, "Querying Email Attachments");
                                processEntity(attachment);
                            }
                        }
                    }

                    controller.TurnOffLevel2();
                }
                controller.TurnOffLevel2();
            }
            var relationshipsDone = new List <string>();

            if (includeNNBetweenEntities)
            {
                countToExport  = exports.Count();
                countsExported = 0;
                foreach (var type in exported.Keys)
                {
                    controller.UpdateProgress(countsExported++, countToExport, string.Format("Exporting {0} Associations", type));
                    var nnRelationships = XrmService.GetEntityManyToManyRelationships(type)
                                          .Where(
                        r =>
                        exported.Keys.Contains(r.Entity1LogicalName) && exported.Keys.Contains(r.Entity2LogicalName));

                    foreach (var item in nnRelationships)
                    {
                        var type1 = item.Entity1LogicalName;
                        var type2 = item.Entity2LogicalName;
                        if (!relationshipsDone.Contains(item.SchemaName))
                        {
                            controller.LogLiteral(string.Format("Querying {0} Associations", item.SchemaName));
                            var associations = XrmService.RetrieveAllEntityType(item.IntersectEntityName, null);
                            var toDo         = associations.Count();
                            var done         = 0;
                            foreach (var association in associations)
                            {
                                controller.UpdateLevel2Progress(done++, toDo, string.Format("Processing Notes For {0} Records", type));
                                if (exported[type1].Any(e => e.Id == association.GetGuidField(item.Entity1IntersectAttribute)) &&
                                    exported[type2].Any(e => e.Id == association.GetGuidField(item.Entity2IntersectAttribute)))
                                {
                                    processAssociation(association);
                                }
                            }
                            relationshipsDone.Add(item.SchemaName);
                            controller.TurnOffLevel2();
                        }
                    }
                }
            }
            controller.TurnOffLevel2();
        }
示例#15
0
        public async Task <List <PatientReferral> > viewReferrals(string patientId)
        {
            try
            {
                List <PatientReferral> patientReferrals = new List <PatientReferral>();
                if (!string.IsNullOrEmpty(patientId))
                {
                    QueryExpression  query       = new QueryExpression(xrm.Opportunity.EntityLogicalName);
                    FilterExpression childFilter = query.Criteria.AddFilter(LogicalOperator.And);
                    childFilter.AddCondition("parentcontactid", ConditionOperator.Equal, new Guid(patientId));
                    childFilter.AddCondition("mzk_opportunitytype", ConditionOperator.Equal, 275380000);
                    query.ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("opportunityid", "name", "mzk_contract", "createdon", "mzk_referringprescriber", "mzk_referringhealthcareprovider", "mzk_diagnosis");//"estimatedclosedate"
                    SoapEntityRepository entityRepository = SoapEntityRepository.GetService();
                    EntityCollection     entitycollection = entityRepository.GetEntityCollection(query);
                    foreach (Entity entity in entitycollection.Entities)
                    {
                        PatientReferral patientReferral = new PatientReferral();
                        if (entity.Attributes.Contains("opportunityid"))
                        {
                            patientReferral.referralId = entity["opportunityid"].ToString();
                        }
                        if (entity.Attributes.Contains("name"))
                        {
                            patientReferral.name = entity["name"].ToString();
                        }
                        if (entity.Attributes.Contains("mzk_contract"))
                        {
                            EntityReference contractLookUp = (EntityReference)entity.Attributes["mzk_contract"];
                            patientReferral.contract = contractLookUp.Name;
                        }
                        if (entity.Attributes.Contains("mzk_diagnosis"))
                        {
                            EntityReference diagnosisLookUp = (EntityReference)entity.Attributes["mzk_diagnosis"];
                            patientReferral.diagnosis = diagnosisLookUp.Name;
                        }

                        if (entity.Attributes.Contains("createdon"))
                        {
                            patientReferral.requestedDateTime = (DateTime)entity["createdon"];
                        }
                        if (entity.Attributes.Contains("mzk_referringprescriber"))
                        {
                            EntityReference referringPrescriberLookUp = (EntityReference)entity.Attributes["mzk_referringprescriber"];
                            patientReferral.referringPrescriber = referringPrescriberLookUp.Name;
                        }
                        if (entity.Attributes.Contains("mzk_referringhealthcareprovider"))
                        {
                            EntityReference healthCareProviderLookUp = (EntityReference)entity.Attributes["mzk_referringhealthcareprovider"];
                            patientReferral.referringHealthCareProvider = healthCareProviderLookUp.Name;
                        }

                        patientReferrals.Add(patientReferral);
                    }
                    return(patientReferrals);
                }
                else
                {
                    throw new ValidationException("Patient Id not found");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public void Execute(IServiceProvider serviceProvider)
        {
            // Obtain the tracing service
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = (IPluginExecutionContext)
                                              serviceProvider.GetService(typeof(IPluginExecutionContext));

            // The InputParameters collection contains all the data passed in the message request.
            if (context.InputParameters.Contains("Query"))
            {
                try
                {
                    var thisQuery             = context.InputParameters["Query"];
                    var fetchExpressionQuery  = thisQuery as FetchExpression;
                    var queryExpressionQuery  = thisQuery as QueryExpression;
                    var queryByAttributeQuery = thisQuery as QueryByAttribute;

                    if (fetchExpressionQuery != null)
                    {
                        tracingService.Trace("Found FetchExpression Query");

                        XDocument fetchXmlDoc = XDocument.Parse(fetchExpressionQuery.Query);
                        //The required entity element
                        var entityElement = fetchXmlDoc.Descendants("entity").FirstOrDefault();
                        var entityName    = entityElement.Attributes("name").FirstOrDefault().Value;

                        //Only applying to the account entity
                        if (entityName == "account")
                        {
                            tracingService.Trace("Query on Account confirmed");

                            //Get all filter elements
                            var filterElements = entityElement.Descendants("filter");

                            //Find any existing statecode conditions
                            var stateCodeConditions = from c in filterElements.Descendants("condition")
                                                      where c.Attribute("attribute").Value.Equals("statecode")
                                                      select c;

                            if (stateCodeConditions.Count() > 0)
                            {
                                tracingService.Trace("Removing existing statecode filter conditions.");
                            }
                            //Remove statecode conditions
                            stateCodeConditions.ToList().ForEach(x => x.Remove());


                            //Add the condition you want in a new filter
                            entityElement.Add(
                                new XElement("filter",
                                             new XElement("condition",
                                                          new XAttribute("attribute", "statecode"),
                                                          new XAttribute("operator", "neq"), //not equal
                                                          new XAttribute("value", "1")       //Inactive
                                                          )
                                             )
                                );
                        }


                        fetchExpressionQuery.Query = fetchXmlDoc.ToString();
                    }
                    if (queryExpressionQuery != null)
                    {
                        tracingService.Trace("Found Query Expression Query");
                        if (queryExpressionQuery.EntityName.Equals("account"))
                        {
                            tracingService.Trace("Query on Account confirmed");

                            //Recursively remove any conditions referring to the statecode attribute
                            foreach (FilterExpression fe in queryExpressionQuery.Criteria.Filters)
                            {
                                //Remove any existing criteria based on statecode attribute
                                RemoveAttributeConditions(fe, "statecode", tracingService);
                            }

                            //Define the filter
                            var stateCodeFilter = new FilterExpression();
                            stateCodeFilter.AddCondition("statecode", ConditionOperator.NotEqual, 1);
                            //Add it to the Criteria
                            queryExpressionQuery.Criteria.AddFilter(stateCodeFilter);
                        }
                    }
                    if (queryByAttributeQuery != null)
                    {
                        tracingService.Trace("Found Query By Attribute Query");
                        //Query by attribute doesn't provide a complex query model that
                        // can be manipulated
                    }
                }

                catch (FaultException <OrganizationServiceFault> ex)
                {
                    throw new InvalidPluginExecutionException("An error occurred in RetrieveMultipleAccountPreOperation.", ex);
                }

                catch (Exception ex)
                {
                    tracingService.Trace("RetrieveMultipleAccountPreOperation: {0}", ex.ToString());
                    throw;
                }
            }
        }
        private IEnumerable<FilterExpression> GetFiltersRelacionesCuentaPersonaFisica(IEnumerable<RelacionCuentaPersona> sqlRelacionesCuentaPersonaFisica)
        {
            var filters = GetFilters<RelacionCuentaPersona>(
                sqlRelacionesCuentaPersonaFisica,
                sqlRelacionCuentaPersonaFisica =>
                {
                    var filter = new FilterExpression(LogicalOperator.And);
                    var nroCuenta = BuildNumeroCuenta(sqlRelacionCuentaPersonaFisica);
                    filter.AddCondition(new ConditionExpression("bsv_numero_de_cuenta", ConditionOperator.Equal, nroCuenta));
                    var moneda = this.crmMonedaDao.GetObjectByCode(sqlCajaDeAhorro.MonedaId.ToString());
                    filter.AddCondition(new ConditionExpression("bsv_moneda", ConditionOperator.Equal, moneda.Id));
                    var modulo = this.crmModuloDao.GetObjectByCode(sqlCajaDeAhorro.ModuloId.ToString());
                    filter.AddCondition(new ConditionExpression("bsv_mdoulo", ConditionOperator.Equal, modulo));
                    var tipoOperacion = this.crmTipoOperacionDao.GetObjectByCode(sqlCajaDeAhorro.TipoOperacionId.ToString());
                    filter.AddCondition(new ConditionExpression("bsv_tipo_operacion", ConditionOperator.Equal, tipoOperacion));

                    return filter;
                });

            return filters;
        }
        /// <summary>
        ///     Retrieves the name of the multiple by entity.
        /// </summary>
        /// <param name="crmService">The CRM service.</param>
        /// <param name="entityName">Name of the entity.</param>
        /// <param name="allColumns">if set to <c>true</c> [all columns].</param>
        /// <param name="columns">The columns.</param>
        /// <returns>Dictionary&lt;Guid, Entity&gt;.</returns>
        public static Dictionary<Guid, Entity> RetrieveMultipleByEntityName(IOrganizationService crmService,
            string entityName,
            bool allColumns = false,
            params string[] columns)
        {
            var keycolumns = XrmMetadataHelperFunctions.GetEntityPrimaryColumns(crmService, entityName);

            var criteria = new FilterExpression();

            if (string.CompareOrdinal(entityName, EntityName.connection) == 0)
            {
                criteria.AddCondition(systementity.ismaster, ConditionOperator.Equal, true);
            }

            return RetrieveMultiple(crmService,
                new QueryExpression(entityName)
                {
                    ColumnSet = columns.Length == 0
                        ? ((!allColumns && !string.IsNullOrEmpty(keycolumns.Value))
                            ? new ColumnSet(keycolumns.Key, keycolumns.Value, systementity.createdon,
                                systementity.createdby)
                            : new ColumnSet(XrmMetadataHelperFunctions.GetNonSystemColumns(crmService, entityName,
                                DiffXrmXml.Exceptions)))
                        : new ColumnSet(columns),
                    Distinct = true,
                    Criteria = criteria
                }
                );
        }
示例#19
0
        /// <summary>
        /// Executes the plug-in.
        /// </summary>
        /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the
        /// <see cref="IPluginExecutionContext"/>,
        /// <see cref="IOrganizationService"/>
        /// and <see cref="ITracingService"/>
        /// </param>
        /// <remarks>
        /// For improved performance, Microsoft Dynamics CRM caches plug-in instances.
        /// The plug-in's Execute method should be written to be stateless as the constructor
        /// is not called for every invocation of the plug-in. Also, multiple system threads
        /// could execute the plug-in at the same time. All per invocation state information
        /// is stored in the context. This means that you should not use global variables in plug-ins.
        /// </remarks>
        /// 
        protected void ExecutegetPricingType(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

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

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

            Guid quoteDetailID = (Guid)((Entity)context.InputParameters["Target"]).Id;
            ColumnSet set = new ColumnSet();
            set.AllColumns = true;
            var quoteDetail = service.Retrieve("quotedetail", quoteDetailID, set);

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

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

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

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

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


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

                //Currency check

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

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

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

                EntityCollection productpricelevels = service.RetrieveMultiple(query);
                var productpriceLevel = productpricelevels.Entities[0];
                //var productPricing = from c in context.ContactSetjoin a in context.AccountSet on c.ContactId equals a.PrimaryContactId.Id
                var productPrice = (Money)productpriceLevel["amount"];
                var priceperunit = (Money)quoteDetail["priceperunit"];
                if (productPrice.Value > priceperunit.Value)
                {
                    quoteDetail["priceperunit"] = new Money(productPrice.Value);
                }
                //quoteDetail["new_jobdescription"] = price;
                service.Update(quoteDetail);
            }
        }
示例#20
0
        public async Task <List <UITemplate> > getChartTemplate(string userId)
        {
            List <UITemplate> listModel = new List <UITemplate>();
            UITemplate        model;

            try
            {
                SoapEntityRepository repo = SoapEntityRepository.GetService();

                QueryExpression query = new QueryExpression(mzk_uitemplatesmenulist.EntityLogicalName);

                query.ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("mzk_ordering");
                query.AddOrder("mzk_ordering", OrderType.Ascending);

                LinkEntity linkEntity = new LinkEntity(mzk_uitemplatesmenulist.EntityLogicalName, mzk_uitemplate.EntityLogicalName, "mzk_uitemplateid", "mzk_uitemplateid", JoinOperator.Inner);

                linkEntity.LinkCriteria.AddCondition("mzk_type", ConditionOperator.Equal, 2);

                FilterExpression childFilter = linkEntity.LinkCriteria.AddFilter(LogicalOperator.Or);

                childFilter.AddCondition("mzk_role", ConditionOperator.Null);

                List <Role> roleList = new Role().getRoles(userId);

                foreach (Role entity in roleList)
                {
                    if (entity.roleid != null && entity.roleid != Guid.Empty)
                    {
                        childFilter.AddCondition("mzk_role", ConditionOperator.Equal, entity.roleid);
                    }
                }

                query.LinkEntities.Add(linkEntity);

                LinkEntity EntityList = new LinkEntity(mzk_uitemplatesmenulist.EntityLogicalName, mzk_menulist.EntityLogicalName, "mzk_menulist", "mzk_menulistid", JoinOperator.Inner);

                EntityList.Columns     = new Microsoft.Xrm.Sdk.Query.ColumnSet(true);
                EntityList.EntityAlias = mzk_menulist.EntityLogicalName;

                query.LinkEntities.Add(EntityList);

                EntityCollection entitycollection = repo.GetEntityCollection(query);

                foreach (Entity entity in entitycollection.Entities)
                {
                    model = new UITemplate();

                    if (entity.Attributes.Contains("mzk_menulist.mzk_chartmenulist"))
                    {
                        model.controlName = entity.FormattedValues["mzk_menulist.mzk_chartmenulist"].ToString();

                        if (entity.Attributes.Contains("mzk_ordering"))
                        {
                            model.order = Convert.ToInt32(entity.Attributes["mzk_ordering"].ToString());
                        }
                        else
                        {
                            model.order = 0;
                        }

                        listModel.Add(model);
                    }
                }
            }
            catch (CustomException ex)
            {
                throw ex;
            }

            return(listModel);
        }
        private IEnumerable<FilterExpression> GetFiltersPersonasFisicas(IEnumerable<PersonaFisica> sqlPersonasFisicas)
        {
            var filters = GetFilters<PersonaFisica>(
                sqlPersonasFisicas,
                sqlPersonaFisica =>
                {
                    var filter = new FilterExpression(LogicalOperator.And);

                    var pais = this.crmPaisDao.GetObjectByCode(sqlPersonaFisica.PaisId.ToString());
                    filter.AddCondition(new ConditionExpression("bsv_pais", ConditionOperator.Equal, pais.Id));
                    var tipoDocumentoId = sqlPersonaFisica.TipoDocumentoId;
                    filter.AddCondition(new ConditionExpression("bsv_tipo_de_documento", ConditionOperator.Equal, tipoDocumentoId));
                    var numeroDocumento = sqlPersonaFisica.NumeroDocumento;
                    filter.AddCondition(new ConditionExpression("bsv_no_de_documento", ConditionOperator.Equal, numeroDocumento));

                    return filter;
                });

            return filters;
        }
示例#22
0
        public List <Products> getProduct(Products product, int pageNumber = 0)
        {
            try
            {
                List <Products> Products = new List <Products>();
                #region Product
                QueryExpression query = new QueryExpression("product");

                query.Criteria.AddCondition("productstructure", ConditionOperator.NotEqual, (int)ProductProductStructure.ProductFamily);
                query.Criteria.AddCondition("statecode", ConditionOperator.Equal, (int)ProductState.Active);

                ConditionExpression condition1 = new ConditionExpression();
                condition1.AttributeName = "name";
                condition1.Operator      = ConditionOperator.Like;


                ConditionExpression condition2 = new ConditionExpression();
                condition2.AttributeName = "mzk_producttype";
                condition2.Operator      = ConditionOperator.Equal;
                if (!string.IsNullOrEmpty(product.Type))
                {
                    condition2.Values.Add(product.Type);
                }

                FilterExpression filter1 = new FilterExpression(LogicalOperator.And);
                FilterExpression filter2 = new FilterExpression();

                if (!string.IsNullOrEmpty(product.Name.ToLower()))
                {
                    if (product.Type == "4")
                    {
                        if (product.Name.Contains(' '))
                        {
                            try
                            {
                                string[] words = product.Name.Split(new Char[] { ' ' });

                                if (words.Length > 1 && words.Length < 3)
                                {
                                    //   filter1 = entityTypeDetails.LinkCriteria.AddFilter(LogicalOperator.Or);

                                    condition1.Values.Add("%" + words[0] + "%");
                                    filter1.Conditions.Add(new ConditionExpression("name", ConditionOperator.Like, "%" + words[1] + "%"));
                                    filter1.Conditions.Add(condition1);
                                }
                                else if (words.Length > 2)
                                {
                                    condition1.Values.Add("%" + words[0] + "%");

                                    filter1.Conditions.Add(condition1);
                                    filter1.Conditions.Add(new ConditionExpression("name", ConditionOperator.Like, "%" + words[1] + "%"));
                                    filter1.Conditions.Add(new ConditionExpression("name", ConditionOperator.Like, "%" + words[2] + "%"));
                                }
                            }
                            catch (Exception ex)
                            {
                                condition1.Values.Add("%" + product.Name + "%");
                                filter1.Conditions.Add(condition1);
                            }
                        }
                        else
                        {
                            condition1.Values.Add("%" + product.Name + "%");
                            filter1.Conditions.Add(condition1);
                        }
                    }
                    else if (product.Type == ((int)Productmzk_ProductType.Lab).ToString())
                    {
                        filter1 = new FilterExpression(LogicalOperator.Or);

                        filter1.AddCondition("name", ConditionOperator.Like, ("%" + product.Name.ToLower() + "%"));
                        filter1.AddCondition("productnumber", ConditionOperator.Like, ("%" + product.Name.ToLower() + "%"));
                    }
                    else
                    {
                        condition1.Values.Add("%" + product.Name + "%");
                        filter1.Conditions.Add(condition1);
                    }
                }
                filter2.Conditions.Add(condition2);

                query.Criteria.AddFilter(filter1);
                query.Criteria.AddFilter(filter2);
                query.ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("name", "mzk_dosageid", "productnumber", "productid", "mzk_available", "mzk_diagnosisid", "mzk_frequencyid", "mzk_unitid", "mzk_routeid", "mzk_duration", "mzk_instruction", "parentproductid", "mzk_contrast", "mzk_specimensource", "mzk_axitemid");

                LinkEntity EntityDiagnosis = new LinkEntity("product", "mzk_concept", "mzk_diagnosisid", "mzk_conceptid", JoinOperator.LeftOuter);
                EntityDiagnosis.Columns = new Microsoft.Xrm.Sdk.Query.ColumnSet("mzk_conceptname");

                LinkEntity EntityFrequency = new LinkEntity("product", "mzk_ordersetup", "mzk_frequencyid", "mzk_ordersetupid", JoinOperator.LeftOuter);
                EntityFrequency.Columns = new Microsoft.Xrm.Sdk.Query.ColumnSet("mzk_description");

                LinkEntity EntityRoute = new LinkEntity("product", "mzk_ordersetup", "mzk_routeid", "mzk_ordersetupid", JoinOperator.LeftOuter);
                EntityRoute.Columns = new Microsoft.Xrm.Sdk.Query.ColumnSet("mzk_description");

                LinkEntity EntityUnit = new LinkEntity("product", "mzk_unit", "mzk_unitid", "mzk_unitid", JoinOperator.LeftOuter);
                EntityUnit.Columns = new Microsoft.Xrm.Sdk.Query.ColumnSet("mzk_description");

                LinkEntity EntityDosage = new LinkEntity("product", "mzk_dosageform", "mzk_dosageid", "mzk_dosageformid", JoinOperator.LeftOuter);
                EntityDosage.Columns     = new Microsoft.Xrm.Sdk.Query.ColumnSet("mzk_dosageformid");
                EntityDosage.EntityAlias = "Dosage";

                LinkEntity EntityUserFavourite;
                if (!string.IsNullOrEmpty(product.filter) && product.filter == "favourite")
                {
                    EntityUserFavourite = new LinkEntity("product", "mzk_userfavourite", "productid", "mzk_productid", JoinOperator.Inner);
                }

                else
                {
                    EntityUserFavourite = new LinkEntity("product", "mzk_userfavourite", "productid", "mzk_productid", JoinOperator.LeftOuter);
                }
                EntityUserFavourite.Columns = new Microsoft.Xrm.Sdk.Query.ColumnSet(true);

                EntityUserFavourite.EntityAlias = "ProductFavourite";



                LinkEntity EntityFamily = new LinkEntity("product", "product", "parentproductid", "productid", JoinOperator.LeftOuter);
                EntityFamily.EntityAlias = "ProductFamily";
                EntityFamily.Columns     = new Microsoft.Xrm.Sdk.Query.ColumnSet("mzk_antibioticmandatory", "mzk_commentsmandatory", "mzk_controlleddrug", "mzk_sedation", "mzk_agefromunit", "mzk_agefromvalue", "mzk_agetounit", "mzk_agetovalue");


                query.LinkEntities.Add(EntityDiagnosis);
                query.LinkEntities.Add(EntityFrequency);
                query.LinkEntities.Add(EntityRoute);
                query.LinkEntities.Add(EntityUnit);
                // query.LinkEntities.Add(EntityImportance);
                query.LinkEntities.Add(EntityFamily);
                query.LinkEntities.Add(EntityDosage);
                if (!string.IsNullOrEmpty(product.UserId))
                {
                    EntityUserFavourite.LinkCriteria.AddCondition("mzk_userid", ConditionOperator.Equal, product.UserId);
                    query.LinkEntities.Add(EntityUserFavourite);
                }

                if (pageNumber > 0)
                {
                    query.PageInfo                        = new PagingInfo();
                    query.PageInfo.Count                  = Convert.ToInt32(AppSettings.GetByKey("PageSize"));
                    query.PageInfo.PageNumber             = product.currentpage;
                    query.PageInfo.PagingCookie           = null;
                    query.PageInfo.ReturnTotalRecordCount = true;
                }

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

                CaseParameter caseParm      = null;
                List <string> prodExistList = new List <string>();

                if (!string.IsNullOrEmpty(product.EncounterId))
                {
                    caseParm = CaseParameter.getDefaultUrgency(PatientCase.getCaseType(product.EncounterId));

                    query = new QueryExpression(mzk_patientorder.EntityLogicalName);

                    query.ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(true);
                    query.Criteria.AddCondition("mzk_patientencounterid", ConditionOperator.Equal, product.EncounterId);
                    query.Criteria.AddCondition("mzk_orderstatus", ConditionOperator.Equal, (int)mzk_orderstatus.Ordered);
                    query.Criteria.AddCondition("mzk_productid", ConditionOperator.NotNull);

                    EntityCollection entitycollectionOrders = entityRepository.GetEntityCollection(query);

                    foreach (Entity entity in entitycollectionOrders.Entities)
                    {
                        mzk_patientorder order = (mzk_patientorder)entity;

                        prodExistList.Add(order.mzk_ProductId.Id.ToString());
                    }
                }

                foreach (Entity entity in entitycollection.Entities)
                {
                    Products model = new Products();
                    if (entity.Attributes.Contains("name"))
                    {
                        model.Name = entity.Attributes["name"].ToString();
                    }
                    if (entity.Attributes.Contains("productnumber"))
                    {
                        model.ProductNumber = entity.Attributes["productnumber"].ToString();
                    }
                    if (entity.Attributes.Contains("productid"))
                    {
                        model.ProductId = entity.Id.ToString();
                    }

                    if (entity.Attributes.Contains("mzk_available"))
                    {
                        model.Available = Convert.ToBoolean(entity.Attributes["mzk_available"].ToString());
                    }

                    if (entity.Attributes.Contains("mzk_contrast"))
                    {
                        model.contrastOrder = Convert.ToBoolean(entity.Attributes["mzk_contrast"].ToString());
                    }

                    //Diagnosis
                    if (entity.Attributes.Contains("mzk_diagnosisid"))
                    {
                        model.DiagnosisId = ((EntityReference)entity.Attributes["mzk_diagnosisid"]).Id.ToString();
                    }
                    if (entity.Attributes.Contains("mzk_concept1.mzk_conceptname"))
                    {
                        model.DiagnosisName = (entity.Attributes["mzk_concept1.mzk_conceptname"] as AliasedValue).Value.ToString();
                    }

                    //Frequency
                    if (entity.Attributes.Contains("mzk_frequencyid"))
                    {
                        model.FrequencyId = ((EntityReference)entity.Attributes["mzk_frequencyid"]).Id.ToString();
                    }
                    if (entity.Attributes.Contains("mzk_ordersetup2.mzk_description"))
                    {
                        model.FrequencyName = (entity.Attributes["mzk_ordersetup2.mzk_description"] as AliasedValue).Value.ToString();
                    }

                    //Route
                    if (entity.Attributes.Contains("mzk_routeid"))
                    {
                        model.RouteId = ((EntityReference)entity.Attributes["mzk_routeid"]).Id.ToString();
                    }
                    if (entity.Attributes.Contains("mzk_ordersetup3.mzk_description"))
                    {
                        model.RouteName = (entity.Attributes["mzk_ordersetup3.mzk_description"] as AliasedValue).Value.ToString();
                    }

                    //Unit
                    if (entity.Attributes.Contains("mzk_unitid"))
                    {
                        model.UnitId = ((EntityReference)entity.Attributes["mzk_unitid"]).Id.ToString();
                    }
                    if (entity.Attributes.Contains("mzk_unit4.mzk_description"))
                    {
                        model.UnitName = (entity.Attributes["mzk_unit4.mzk_description"] as AliasedValue).Value.ToString();
                    }

                    if (!string.IsNullOrEmpty(product.EncounterId) && caseParm != null)
                    {
                        model.UrgencyId   = caseParm.urgencyId;
                        model.UrgencyName = caseParm.urgencyName;
                    }

                    //Instruction
                    if (entity.Attributes.Contains("mzk_instruction"))
                    {
                        model.Instruction = entity.Attributes["mzk_instruction"].ToString();
                    }

                    if (entity.Attributes.Contains("mzk_specimensource"))
                    {
                        model.IsSpecimenSource = (bool)entity.Attributes["mzk_specimensource"];
                    }

                    if (model.IsSpecimenSource == false)
                    {
                        if (!string.IsNullOrEmpty(product.EncounterId))
                        {
                            model.isAdded = !prodExistList.Exists(item => item == entity.Id.ToString());
                            //model.isAdded = new PatientEncounter().DuplicateDetection(product.EncounterId, entity.Id.ToString());
                        }
                    }
                    else
                    {
                        model.isAdded = true;
                    }

                    if (entity.Attributes.Contains("ProductFavourite.mzk_userfavouriteid"))
                    {
                        model.FavouriteId = (entity.Attributes["ProductFavourite.mzk_userfavouriteid"] as AliasedValue).Value.ToString();
                    }

                    //Parameters
                    if (entity.Attributes.Contains("ProductFamily.mzk_antibioticmandatory"))
                    {
                        model.antiBioticRequired = (bool)((AliasedValue)entity.Attributes["ProductFamily.mzk_antibioticmandatory"]).Value;
                    }

                    if (entity.Attributes.Contains("ProductFamily.mzk_controlleddrug"))
                    {
                        model.controlledDrugs = (bool)((AliasedValue)entity.Attributes["ProductFamily.mzk_controlleddrug"]).Value;
                    }

                    if (entity.Attributes.Contains("ProductFamily.mzk_commentsmandatory"))
                    {
                        model.commentsRequired = (bool)((AliasedValue)entity.Attributes["ProductFamily.mzk_commentsmandatory"]).Value;
                    }

                    if (entity.Attributes.Contains("ProductFamily.mzk_sedation") && !string.IsNullOrEmpty(product.patientId))
                    {
                        model.sedationOrder = (bool)((AliasedValue)entity.Attributes["ProductFamily.mzk_sedation"]).Value;

                        if (model.sedationOrder)
                        {
                            AgeHelper ageHelper = new AgeHelper(DateTime.Now);
                            DateTime  patientBirthDate;
                            Patient   patient = new Patient();
                            Helper.Enum.DayWeekMthYr ageFromUnit = Helper.Enum.DayWeekMthYr.Days, ageToUnit = Helper.Enum.DayWeekMthYr.Days;
                            int ageFromValue = 0, ageToValue = 0;

                            patientBirthDate = patient.getPatientDetails(product.patientId).Result.dateOfBirth;

                            if (entity.Attributes.Contains("ProductFamily.mzk_agefromunit") && (entity.Attributes["ProductFamily.mzk_agefromunit"] as AliasedValue) != null)
                            {
                                ageFromUnit = (Helper.Enum.DayWeekMthYr)((entity.Attributes["ProductFamily.mzk_agefromunit"] as AliasedValue).Value as OptionSetValue).Value;
                            }

                            if (entity.Attributes.Contains("ProductFamily.mzk_agetounit") && (entity.Attributes["ProductFamily.mzk_agetounit"] as AliasedValue) != null)
                            {
                                ageToUnit = (Helper.Enum.DayWeekMthYr)((entity.Attributes["ProductFamily.mzk_agetounit"] as AliasedValue).Value as OptionSetValue).Value;
                            }

                            if (entity.Attributes.Contains("ProductFamily.mzk_agefromvalue") && (entity.Attributes["ProductFamily.mzk_agefromvalue"] as AliasedValue) != null)
                            {
                                ageFromValue = (int)((entity.Attributes["ProductFamily.mzk_agefromvalue"] as AliasedValue).Value);
                            }

                            if (entity.Attributes.Contains("ProductFamily.mzk_agetovalue") && (entity.Attributes["ProductFamily.mzk_agetovalue"] as AliasedValue) != null)
                            {
                                ageToValue = (int)((entity.Attributes["ProductFamily.mzk_agetovalue"] as AliasedValue).Value);
                            }

                            model.sedationOrder = ageHelper.isAgeMatched(patientBirthDate, ageFromUnit, ageFromValue, ageToUnit, ageToValue);
                        }
                    }

                    if (entity.Attributes.Contains("mzk_dosageid"))
                    {
                        model.Dosage = ((EntityReference)entity.Attributes["mzk_dosageid"]).Id.ToString();
                    }

                    if (AppSettings.GetByKey("OperationsIntegration").ToLower() == true.ToString().ToLower())
                    {
                        if (!string.IsNullOrEmpty(product.clinicId) && entity.Attributes.Contains("mzk_axitemid") && !string.IsNullOrEmpty(entity.Attributes["mzk_axitemid"].ToString()))
                        {
                            CommonRepository comRepo = new CommonRepository();

                            Clinic clinic = new Clinic().getClinicDetails(product.clinicId);

                            Dictionary <int, int> retStock = comRepo.checkItemInStock(entity.Attributes["mzk_axitemid"].ToString(), clinic.mzk_axclinicrefrecid);

                            if (retStock != null && retStock.Count > 0)
                            {
                                int availableValue = 0;

                                if (retStock.TryGetValue(0, out availableValue))
                                {
                                    model.availableForClinic = availableValue == 0 ? false : true;
                                }

                                if (retStock.TryGetValue(1, out availableValue))
                                {
                                    model.availableForPharmacy = availableValue == 0 ? false : true;
                                }
                            }
                        }
                    }

                    Products.Add(model);
                }

                if (pageNumber > 0 && entitycollection != null)
                {
                    Pagination.totalCount = entitycollection.TotalRecordCount;
                }

                return(Products);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#23
0
        protected override void Execute(CodeActivityContext context)
        {
            try
            {
                // Get the context service.
                IWorkflowContext            Icontext       = context.GetExtension <IWorkflowContext>();
                IOrganizationServiceFactory serviceFactory = context.GetExtension <IOrganizationServiceFactory>();

                // Use the context service to create an instance of IOrganizationService.
                IOrganizationService service = serviceFactory.CreateOrganizationService(Icontext.InitiatingUserId);

                //get input fields
                var BirthDate      = birthdate.Get(context) == new DateTime(0001, 01, 01) ? new DateTime(1753, 01, 01) : birthdate.Get(context);
                var FirstNameInput = firstname.Get(context);
                var LastNameInput  = lastname.Get(context);
                var Username       = username.Get(context) == null ? "" : username.Get(context);

                /* // lav query
                 * var query = new QueryExpression("contact");
                 * query.ColumnSet.AddColumns("sdu_brugernavn", "fullname", "birthdate", "contactid", "firstname", "lastname");
                 *
                 * // alle skal have de samme fødselsdato
                 * query.Criteria = new FilterExpression();
                 * query.Criteria.AddCondition("birthdate", ConditionOperator.Equal, BirthDate);
                 *
                 * // enten brugernavn eller fuldt navn match
                 * FilterExpression userNameAndNameOr = new FilterExpression(LogicalOperator.Or);
                 * userNameAndNameOr.AddCondition("sdu_brugernavn", ConditionOperator.Equal, Username);
                 *
                 * FilterExpression UserNameAndNameAnd = new FilterExpression(LogicalOperator.Or);
                 *
                 * UserNameAndNameAnd.AddCondition("fullname", ConditionOperator.Like, "%" + FullnameInput + "%");*/

                // made in fetchXML builder
                // Instantiate QueryExpression QEcontact
                var QEcontact = new QueryExpression("contact");

                // Add columns to QEcontact.ColumnSet
                QEcontact.ColumnSet.AddColumns("fullname", "firstname", "lastname", "birthdate", "sdu_brugernavn", "sdu_domne", "emailaddress1", "address1_city", "jobtitle", "sdu_crmomkostningssted", "sdu_brugernavn", "address1_line1");

                // Define filter QEcontact.Criteria // all must match birthdate + sdu_crmudlb + opdateret fra fim
                var QEcontact_Criteria = new FilterExpression();
                QEcontact.Criteria.AddFilter(QEcontact_Criteria);

                // Define filter QEcontact_Criteria // either match on username, or firstname + lastname
                QEcontact_Criteria.FilterOperator = LogicalOperator.Or;
                QEcontact_Criteria.AddCondition("sdu_brugernavn", ConditionOperator.Equal, Username);

                var QEcontact_Criteria_name = new FilterExpression();
                QEcontact_Criteria.AddFilter(QEcontact_Criteria_name);

                // Define filter QEcontact_Criteria_name_birthdate
                QEcontact_Criteria_name.AddCondition("firstname", ConditionOperator.Like, "%" + FirstNameInput + "%");
                QEcontact_Criteria_name.AddCondition("lastname", ConditionOperator.Like, "%" + LastNameInput + "%");
                QEcontact_Criteria_name.AddCondition("birthdate", ConditionOperator.On, BirthDate);

                var QEcontact_Criteria_state = new FilterExpression();
                QEcontact.Criteria.AddFilter(QEcontact_Criteria_state);

                // Define filter QEcontact_Criteria_state
                QEcontact_Criteria_state.FilterOperator = LogicalOperator.Or;
                QEcontact_Criteria_state.AddCondition("statecode", ConditionOperator.Equal, 1); // kontoen er inaktiv

                var QEcontact_Criteria_dates = new FilterExpression();
                QEcontact_Criteria_state.AddFilter(QEcontact_Criteria_dates);

                // define filter QEcontact_Criteria_dates
                QEcontact_Criteria_dates.AddCondition("sdu_crmudlb", ConditionOperator.OnOrAfter, DateTime.Today.AddMonths(-13)); // CRM udløb er maksimalt 13 måneder gammelt
                QEcontact_Criteria_dates.AddCondition("sdu_crmudlb", ConditionOperator.OnOrBefore, DateTime.Today.AddDays(-1));   // CRM er igår eller før


                //find records
                var queryResult = service.RetrieveMultiple(QEcontact);

                if (queryResult.Entities.Count == 1)
                {
                    foreach (var record in queryResult.Entities)
                    {
                        // fullname
                        fullnameOutput.Set(context, record.GetAttributeValue <string>("fullname"));

                        // contactid
                        contactID.Set(context, record.GetAttributeValue <Guid>("contactid").ToString());

                        // omkostningssted
                        var omkStedIdLocal = searchForRecord(service, "sdu_brugeradmomksted",
                                                             new KeyValuePair <string, string>("sdu_omksted", record.GetAttributeValue <EntityReference>("sdu_crmomkostningssted").Id.ToString()),
                                                             new KeyValuePair <string, string>("", ""),
                                                             "sdu_brugeradmomkstedid");

                        omkStedId.Set(context, omkStedIdLocal);

                        // domæne
                        String[] seperator_domaene = { "_" };

                        if (omkStedIdLocal != "")
                        {
                            domaene.Set(context, searchForRecord(service,
                                                                 "sdu_domner",
                                                                 new KeyValuePair <string, string>("sdu_brugeradmomksted", omkStedIdLocal.Split(seperator_domaene, StringSplitOptions.RemoveEmptyEntries).GetValue(0).ToString()),
                                                                 new KeyValuePair <string, string>("sdu_name", record.GetAttributeValue <string>("sdu_domne")),
                                                                 "sdu_domnerid"));

                            // email domæne
                            String[] seperator_emailDomaene = { "@" };
                            var      emailDomainFromContact = "@" + record.GetAttributeValue <string>("emailaddress1").Split(seperator_emailDomaene, StringSplitOptions.RemoveEmptyEntries).GetValue(1).ToString();

                            emailDomaene.Set(context, searchForRecord(service,
                                                                      "sdu_emaildomne",
                                                                      new KeyValuePair <string, string>("sdu_brugeradmomksted", omkStedIdLocal.Split(seperator_domaene, StringSplitOptions.RemoveEmptyEntries).GetValue(0).ToString()),
                                                                      new KeyValuePair <string, string>("sdu_name", emailDomainFromContact.Replace(" ", "")), // remove whitespaces
                                                                      "sdu_emaildomneid"));
                        }
                        else
                        {
                            // set output parameters to empty strings, if no omk sted
                            domaene.Set(context, "");
                            emailDomaene.Set(context, "");
                        }

                        // lokation + arbejdsadresse
                        var LokationOptionSetValue = "";

                        switch (record.GetAttributeValue <string>("address1_city"))
                        {
                        case "Odense":
                            LokationOptionSetValue = "100000000";
                            break;

                        case "Odense M":
                            LokationOptionSetValue = "100000000";
                            break;

                        case "Sønderborg":
                            LokationOptionSetValue = "100000001";
                            break;

                        case "Esbjerg":
                            LokationOptionSetValue = "100000002";
                            break;

                        case "Slagelse":
                            LokationOptionSetValue = "100000003";
                            break;

                        case "Kolding":
                            LokationOptionSetValue = "100000004";
                            break;

                        default:
                            break;
                        }

                        var workAddress = record.GetAttributeValue <string>("address1_line1");

                        if (workAddress.Contains("Campusvej"))
                        {
                            LokationOptionSetValue = LokationOptionSetValue + "_" + "100000000";
                        }
                        else if (workAddress.Contains("J.B. Winsløws Vej"))
                        {
                            LokationOptionSetValue = LokationOptionSetValue + "_" + "100000001";
                        }

                        lokation.Set(context, LokationOptionSetValue);


                        // stillingsbetegnelse
                        stillingsBetegnelse.Set(context, searchForRecord(service,
                                                                         "sdu_stikogruppe",
                                                                         new KeyValuePair <string, string>("sdu_name", record.GetAttributeValue <string>("jobtitle")),
                                                                         new KeyValuePair <string, string>("", ""),
                                                                         "sdu_stikogruppeid"));

                        // fødselsdato
                        birthDateOutput.Set(context, record.GetAttributeValue <DateTime>("birthdate"));

                        // brugernavn
                        usernameOutput.Set(context, record.GetAttributeValue <string>("sdu_brugernavn"));
                    }
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
示例#24
0
        public List <T> ListarPor(Guid unidadeNegocioId, List <Guid> lstEstados, Guid?listaGuid, DateTime dtInicio, DateTime dtFim)
        {
            var query = GetQueryExpression <T>(true);

            #region Condições

            query.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0);
            query.Criteria.AddCondition("itbc_businessunitid", ConditionOperator.Equal, unidadeNegocioId.ToString());

            if (lstEstados != null && lstEstados.Count > 0)
            {
                query.AddLink("itbc_pricelevel_itbc_estado", "pricelevelid", "pricelevelid");

                //Adicionamos o OR para pegar qualquer lista PSD que esteja em um determinado range de data e que seja de um estado que ja tenha sido adicionado
                FilterExpression filterExp = new FilterExpression(LogicalOperator.Or);
                foreach (var item in lstEstados)
                {
                    filterExp.AddCondition("itbc_pricelevel_itbc_estado", "itbc_estadoid", ConditionOperator.Equal, item);
                }
                query.Criteria.AddFilter(filterExp);
            }
            else
            {
                query.AddLink("itbc_pricelevel_itbc_estado", "pricelevelid", "pricelevelid", JoinOperator.LeftOuter);
                query.Criteria.AddCondition("itbc_pricelevel_itbc_estado", "pricelevelid", ConditionOperator.Null);
            }

            //Ignoramos o proprio registro da consulta
            if (listaGuid.HasValue)
            {
                query.Criteria.AddCondition("pricelevelid", ConditionOperator.NotEqual, listaGuid.Value.ToString());
            }

            //Consulta pra basicamente pegar todos os intervalos possiveis que já possuem uma data no intervalo
            //Basicamente A B é o intervalo que o usuario ta tentando cadastrar
            // 1 e 2 são as datas que devemos verificar com base no A B para ver se já existem
            //valor a esquerda do A quer dizer <= A a direita de B é >= B

            /*
             * 1     -    2
             *  1 -  2
             *    A 1-2 B
             *        1  -  2
             */
            FilterExpression filtroPai = new FilterExpression(LogicalOperator.Or);

            FilterExpression filtro = new FilterExpression(LogicalOperator.And);
            filtro.AddCondition("begindate", ConditionOperator.LessEqual, dtInicio);
            FilterExpression filtroFilho = new FilterExpression(LogicalOperator.And);
            filtroFilho.AddCondition("enddate", ConditionOperator.GreaterEqual, dtInicio);
            filtroFilho.AddCondition("enddate", ConditionOperator.LessEqual, dtFim);
            filtro.AddFilter(filtroFilho);

            FilterExpression filtro2 = new FilterExpression(LogicalOperator.And);
            filtro2.AddCondition("begindate", ConditionOperator.GreaterEqual, dtInicio);
            filtro2.AddCondition("enddate", ConditionOperator.LessEqual, dtFim);

            FilterExpression filtro3 = new FilterExpression(LogicalOperator.And);
            filtro3.AddCondition("begindate", ConditionOperator.LessEqual, dtInicio);
            filtro3.AddCondition("enddate", ConditionOperator.GreaterEqual, dtFim);

            FilterExpression filtro4      = new FilterExpression(LogicalOperator.And);
            FilterExpression filtroFilho2 = new FilterExpression(LogicalOperator.And);
            filtroFilho2.AddCondition("begindate", ConditionOperator.LessEqual, dtFim);
            filtroFilho2.AddCondition("begindate", ConditionOperator.GreaterEqual, dtInicio);
            filtro4.AddFilter(filtroFilho2);
            filtro4.AddCondition("enddate", ConditionOperator.GreaterEqual, dtFim);

            filtroPai.AddFilter(filtro);
            filtroPai.AddFilter(filtro2);
            filtroPai.AddFilter(filtro3);
            filtroPai.AddFilter(filtro4);

            query.Criteria.AddFilter(filtroPai);

            #endregion

            #region Ordenações
            query.AddOrder("modifiedon", Microsoft.Xrm.Sdk.Query.OrderType.Descending);
            #endregion

            return((List <T>) this.RetrieveMultiple(query).List);
        }
示例#25
0
        public void Experiment_For_Filters_1()
        {
            // var sql = string.Format("Select C.firstname, C.lastname From contact Where firstname Like '%ax%' ");

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

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

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

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

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

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

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

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

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

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

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

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

            }
        }
示例#26
0
        /// <summary>
        /// This sample demonstrates how to audit user access to Microsoft Dynamics CRM.
        /// The sample first enables user access auditing on an organization. Next, it
        /// creates and modifies an entity. Finally, the sample displays a report of the
        /// audited information.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            _sampleStartTime = DateTime.Now;
            using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
            {
                // This statement is required to enable early-bound type support.
                _serviceProxy.EnableProxyTypes();

                #region Enable Auditing

                // Enable auditing on the organization and for user access by editing the
                // organization's settings.
                // First, get the organization's ID from the system user record.
                var whoAmIReq = new WhoAmIRequest();
                var whoAmIRes = (WhoAmIResponse)_serviceProxy.Execute(whoAmIReq);
                Guid orgId = whoAmIRes.OrganizationId;
                _systemUserId = whoAmIRes.UserId;

                // Next, retrieve the organization's record.
                var org = (Organization)_serviceProxy.Retrieve(
                    Organization.EntityLogicalName, orgId,
                    new ColumnSet("organizationid", "isauditenabled", "isuseraccessauditenabled", "useraccessauditinginterval"));

                // Finally, enable auditing on the organization, including auditing for
                // user access.
                bool organizationAuditingFlag = org.IsAuditEnabled.Value;
                bool userAccessAuditingFlag = org.IsUserAccessAuditEnabled.Value;
                if (!organizationAuditingFlag || !userAccessAuditingFlag)
                {
                    org.IsAuditEnabled = true;
                    org.IsUserAccessAuditEnabled = true;
                    _serviceProxy.Update(org);
                    Console.WriteLine("Enabled auditing for the organization and for user access.");
                    Console.WriteLine("Auditing interval is set to {0} hours.", org.UserAccessAuditingInterval);
                }
                else
                {
                    Console.WriteLine("Auditing was enabled before the sample began, so no auditing settings were changed.");
                }

                // Enable auditing on the account entity, since no audits will be created
                // when we create/update an account entity, otherwise.
                var oldAccountAuditing = EnableEntityAuditing(Account.EntityLogicalName, true);

                #endregion Enable Auditing

                #region Make Audited Service Calls

                CreateRequiredRecords();

                // Make an update request to the Account entity to be tracked by auditing.
                var newAccount = new Account();
                newAccount.AccountId = _newAccountId;
                newAccount.AccountNumber = "1-A";
                newAccount.AccountCategoryCode = new OptionSetValue(
                    (int)AccountAccountCategoryCode.PreferredCustomer);
                newAccount.Telephone1 = "555-555-5555";

                _serviceProxy.Update(newAccount);

                Console.WriteLine("Created an account and made updates which should be captured by auditing.");

                #endregion Make Audited Service Calls

                #region Revert auditing

                // Set the organization and account auditing flags back to the old values
                if (!organizationAuditingFlag || !userAccessAuditingFlag)
                {
                    // Only revert them if they were actually changed to begin with.
                    org.IsAuditEnabled = organizationAuditingFlag;
                    org.IsUserAccessAuditEnabled = userAccessAuditingFlag;
                    _serviceProxy.Update(org);
                    Console.WriteLine("Reverted organization and user access auditing to their previous values.");
                }
                else
                {
                    Console.WriteLine("Auditing was enabled before the sample began, so no auditing settings were reverted.");
                }

                // Revert the account entity auditing.
                EnableEntityAuditing(Account.EntityLogicalName, oldAccountAuditing);

                #endregion Revert auditing

                #region Show Audited Records

                // Select all columns for convenience.
                var query = new QueryExpression(Audit.EntityLogicalName)
                {
                    ColumnSet = new ColumnSet(true),
                    Criteria = new FilterExpression(LogicalOperator.And)
                };

                // Only retrieve audit records that track user access.
                query.Criteria.AddCondition("action", ConditionOperator.In,
                    (int)AuditAction.UserAccessAuditStarted,
                    (int)AuditAction.UserAccessAuditStopped,
                    (int)AuditAction.UserAccessviaWebServices,
                    (int)AuditAction.UserAccessviaWeb);

                // Change this to false in order to retrieve audit records for all users
                // when running the sample.
                var filterAuditsRetrievedByUser = true;
                if (filterAuditsRetrievedByUser)
                {
                    // Only retrieve audit records for the current user or the "SYSTEM"
                    // user.
                    var userFilter = new FilterExpression(LogicalOperator.Or);
                    userFilter.AddCondition(
                        "userid", ConditionOperator.Equal, _systemUserId);
                    userFilter.AddCondition(
                        "useridname", ConditionOperator.Equal, "SYSTEM");
                }
                // Only retrieve records for this sample run, so that we don't get too
                // many results if auditing was enabled previously.
                query.Criteria.AddCondition(
                    "createdon", ConditionOperator.GreaterEqual, _sampleStartTime);

                var results = _serviceProxy.RetrieveMultiple(query);
                Console.WriteLine("Retrieved audit records:");
                foreach (Audit audit in results.Entities)
                {
                    Console.Write("\r\n  Action: {0},  User: {1},"
                        + "\r\n    Created On: {2}, Operation: {3}",
                        (AuditAction)audit.Action.Value,
                        audit.UserId.Name,
                        audit.CreatedOn.Value.ToLocalTime(),
                        (AuditOperation)audit.Operation.Value);

                    // Display the name of the related object (which will be the user
                    // for audit records with Action UserAccessviaWebServices.
                    if (!String.IsNullOrEmpty(audit.ObjectId.Name))
                    {
                        Console.WriteLine(
                            ",\r\n    Related Record: {0}", audit.ObjectId.Name);
                    }
                    else
                    {
                        Console.WriteLine();
                    }
                }

                #endregion Show Audited Records

                DeleteRequiredRecords(promptforDelete);
            }
        }
示例#27
0
        /// <summary>
        /// Gom lại những truck nào giống nhau thành 1 (sum quantity)
        /// </summary>
        public void JoinTruck(Guid DelivereScheduleId)
        {
            EntityCollection list_truck;

            #region Lấy list truck
            QueryExpression q = new QueryExpression("bsd_deliveryplantruck");
            q.ColumnSet = new ColumnSet(true);
            FilterExpression f = new FilterExpression(LogicalOperator.And);
            f.AddCondition(new ConditionExpression("bsd_deliveryplan", ConditionOperator.Equal, DelivereScheduleId));
            f.AddCondition(new ConditionExpression("bsd_status", ConditionOperator.Equal, 861450001));
            q.Criteria = f;
            list_truck = myService.service.RetrieveMultiple(q);
            #endregion

            int CountTruck = list_truck.Entities.Count;
            foreach (Entity deliveryplantruck_target in list_truck.Entities)
            {
                int deliverytruck_type = ((OptionSetValue)deliveryplantruck_target["bsd_deliverytrucktype"]).Value;

                StringBuilder sb = new StringBuilder();
                sb.Append("<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>");
                sb.Append("<entity name='bsd_deliveryplantruck'>");
                sb.Append("<attribute name='bsd_deliveryplantruckid' />");
                sb.Append("<attribute name='bsd_quantity' />");
                sb.Append("<attribute name='bsd_driver' />");
                sb.Append("<filter type='and'>");
                sb.Append("<condition attribute='bsd_deliveryplanproduct' operator='eq' uitype='bsd_deliveryplanproduct' value='" + ((EntityReference)deliveryplantruck_target["bsd_deliveryplanproduct"]).Id + "' />");
                sb.Append("<condition attribute='bsd_licenseplate' operator='eq' value='" + deliveryplantruck_target["bsd_licenseplate"].ToString() + "' />");
                sb.Append("<condition attribute='bsd_status' operator='eq' value='861450001' />");
                sb.Append("<condition attribute='bsd_deliverytrucktype' operator='eq' value='" + deliverytruck_type + "' />");
                sb.Append("<condition attribute='bsd_deliveryplantruckid' operator='ne' uitype='bsd_deliveryplantruck' value='" + deliveryplantruck_target.Id + "' />");
                if (deliveryplantruck_target.HasValue("bsd_carrierpartner"))
                {
                    Guid bsd_carrierpartner_id = ((EntityReference)deliveryplantruck_target["bsd_carrierpartner"]).Id;
                    sb.Append("<condition attribute='bsd_carrierpartner' operator='eq' uitype='account' value='" + bsd_carrierpartner_id + "' />");
                }
                if (deliveryplantruck_target.HasValue("bsd_shippingdeliverymethod"))
                {
                    int method = ((OptionSetValue)deliveryplantruck_target["bsd_shippingdeliverymethod"]).Value;
                    sb.Append("<condition attribute='bsd_shippingdeliverymethod' operator='eq' value='" + method + "' />");
                }
                if (deliveryplantruck_target.HasValue("bsd_shippingoption"))
                {
                    bool shipping = ((bool)deliveryplantruck_target["bsd_shippingoption"]);
                    sb.Append("<condition attribute='bsd_shippingoption' operator='eq' value='" + shipping + "' />");
                }
                if (deliveryplantruck_target.HasValue("bsd_truckload"))
                {
                    Guid bsd_truckload = ((EntityReference)deliveryplantruck_target["bsd_truckload"]).Id;
                    sb.Append("<condition attribute='bsd_truckload' uitype='bsd_truckload' operator='eq' value='" + bsd_truckload + "' />");
                }
                sb.Append("</filter>");
                sb.Append("</entity>");
                sb.Append("</fetch>");
                EntityCollection list_deliveryproducttruck = myService.service.RetrieveMultiple(new FetchExpression(sb.ToString()));
                if (list_deliveryproducttruck.Entities.Any())
                {
                    Entity  deliveryplantruck = list_deliveryproducttruck.Entities.First();
                    decimal quantity          = (decimal)deliveryplantruck["bsd_quantity"];
                    Entity  new_target        = new Entity(deliveryplantruck_target.LogicalName, deliveryplantruck_target.Id);
                    new_target["bsd_quantity"] = (decimal)deliveryplantruck_target["bsd_quantity"] + quantity;

                    myService.service.Update(new_target);
                    myService.service.Delete(deliveryplantruck.LogicalName, deliveryplantruck.Id);
                    break;
                }
            }
        }
        /// <summary>
        ///     Gets the plugins steps.
        /// </summary>
        /// <param name="crmSerivce">The CRM serivce.</param>
        /// <param name="conditions">The conditions.</param>
        /// <returns>EntityCollection.</returns>
        public static EntityCollection GetPluginsSteps(IOrganizationService crmSerivce,
            params ConditionExpression[] conditions)
        {
            var query = new QueryExpression
            {
                EntityName = EntityName.sdkmessageprocessingstep,
                ColumnSet = new ColumnSet(true)
            };

            query.Criteria.AddCondition(sdkmessageprocessingstep.ishidden, ConditionOperator.Equal, false);
            query.Criteria.AddCondition(sdkmessageprocessingstep.iscustomizable, ConditionOperator.Equal, true);
            query.Criteria.AddCondition(sdkmessageprocessingstep.customizationlevel, ConditionOperator.GreaterEqual, 1);

            var orFilter = new FilterExpression
            {
                FilterOperator = LogicalOperator.Or
            };

            orFilter.AddCondition(sdkmessageprocessingstep.name, ConditionOperator.DoesNotBeginWith, "Workflow");
            orFilter.AddCondition(sdkmessageprocessingstep.name, ConditionOperator.DoesNotBeginWith, "ObjectModel");
            orFilter.Conditions.AddRange(conditions);

            query.Criteria.Filters.AddRange(orFilter);
            return crmSerivce.RetrieveMultiple(query);
        }
        /// <summary>
        ///     Enables or disable workflow steps.
        /// </summary>
        /// <param name="crmService">The CRM service.</param>
        /// <param name="enableWorkflow">if set to <c>true</c> [enable workflow].</param>
        /// <param name="conditions">The conditions.</param>
        public static void EnableOrDisableWorkflowSteps(IOrganizationService crmService, bool enableWorkflow,
            params ConditionExpression[] conditions)
        {
            const string fetchWorkflow =
                @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
              <entity name='workflow'>
                <attribute name='workflowid' />
                <attribute name='name' />
                <order attribute='name' descending='false' />
                <filter type='and'>
                  <condition attribute='type' operator='eq' value='1' />
                  <filter type='or'>
                    <condition attribute='category' operator='eq' value='0' />
                    <filter type='and'>
                      <condition attribute='category' operator='eq' value='1' />
                      <condition attribute='languagecode' operator='eq-userlanguage' />
                    </filter>
                  </filter>
                  <condition attribute='statecode' operator='eq' value='1' />
                </filter>
              </entity>
            </fetch>";

            var request = new FetchXmlToQueryExpressionRequest
            {
                FetchXml = fetchWorkflow
            };
            var response = crmService.Execute(request) as FetchXmlToQueryExpressionResponse;
            if (response == null) return;

            var orFilter = new FilterExpression
            {
                FilterOperator = LogicalOperator.Or
            };

            orFilter.AddCondition(workflow.name, ConditionOperator.DoesNotBeginWith, "Workflow");
            orFilter.AddCondition(workflow.name, ConditionOperator.DoesNotBeginWith, "ObjectModel");
            orFilter.Conditions.AddRange(conditions);

            response.Query.Criteria.Filters.AddRange(orFilter);

            var results = crmService.RetrieveMultiple(response.Query);
            var activatedWorkflowIds = results.Entities.ToList();

            // Enable auditing on the organization.
            // First, get the organization's ID from the system user record.
            var currentUserId = ((WhoAmIResponse) crmService.Execute(new WhoAmIRequest())).UserId;

            activatedWorkflowIds.ForEach(workflowRecord =>
            {
                try
                {
                    crmService.Execute(new AssignRequest
                    {
                        Assignee = new EntityReference(EntityName.systemuser, currentUserId),
                        Target = new EntityReference(EntityName.workflow, workflowRecord.Id)
                    });

                    var statecode = enableWorkflow
                        ? new OptionSetValue((int) sdkmessageprocessingstep_enums.statecode.Enabled)
                        : new OptionSetValue((int) sdkmessageprocessingstep_enums.statecode.Disabled);

                    var statuscode = enableWorkflow
                        ? new OptionSetValue((int) sdkmessageprocessingstep_enums.statuscode.Enabled)
                        : new OptionSetValue((int) sdkmessageprocessingstep_enums.statuscode.Disabled);

                    crmService.Execute(new SetStateRequest
                    {
                        EntityMoniker = new EntityReference(EntityName.workflow, workflowRecord.Id),
                        State = statecode,
                        Status = statuscode
                    });
                }
                catch (FaultException<OrganizationServiceFault> orgex)
                {
                    orgex.Message.TraceError(orgex);
                }
            });
        }
示例#30
0
        public async Task <bool> addRelationship(Relationship relationship)
        {
            try
            {
                SoapEntityRepository repo = SoapEntityRepository.GetService();
                if (relationship.patientId != null)
                {
                    QueryExpression  query       = new QueryExpression(xrm.Contact.EntityLogicalName);
                    FilterExpression childFilter = query.Criteria.AddFilter(LogicalOperator.And);
                    if (!string.IsNullOrEmpty(relationship.firstname))
                    {
                        childFilter.AddCondition("firstname", ConditionOperator.Equal, relationship.firstname);
                    }
                    if (!string.IsNullOrEmpty(relationship.lastname))
                    {
                        childFilter.AddCondition("lastname", ConditionOperator.Equal, relationship.lastname);
                    }
                    if (!string.IsNullOrEmpty(relationship.mobile))
                    {
                        childFilter.AddCondition("mobilephone", ConditionOperator.Equal, relationship.mobile);
                    }
                    if (!string.IsNullOrEmpty(relationship.email))
                    {
                        childFilter.AddCondition("emailaddress1", ConditionOperator.Equal, relationship.email);
                    }
                    //childFilter.AddCondition("mzk_carer", ConditionOperator.Equal, relationship.carer);
                    //childFilter.AddCondition("mzk_nextofkin", ConditionOperator.Equal, relationship.nextOfKin);

                    EntityCollection entityCollection = repo.GetEntityCollection(query);
                    if (entityCollection.Entities.Count > 0)
                    {
                        Entity relation = new Entity(xrm.mzk_relationship.EntityLogicalName);

                        relation["mzk_customer"] = new EntityReference(xrm.Contact.EntityLogicalName, new Guid(relationship.patientId));
                        if (!string.IsNullOrEmpty(relationship.type))
                        {
                            relation["mzk_role"] = new EntityReference(xrm.mzk_masterdata.EntityLogicalName, new Guid(relationship.type));
                        }

                        if (entityCollection.Entities[0].Attributes.Contains("contactid"))
                        {
                            relation["mzk_connectedto"] = new EntityReference(xrm.Contact.EntityLogicalName, new Guid(entityCollection.Entities[0]["contactid"].ToString()));
                        }

                        relation["mzk_carer"]     = relationship.carer;
                        relation["mzk_nextofkin"] = relationship.nextOfKin;
                        repo.CreateEntity(relation);
                        return(true);
                    }
                    else
                    {
                        Entity contact = new Entity(xrm.Contact.EntityLogicalName);
                        if (!string.IsNullOrEmpty(relationship.firstname))
                        {
                            contact["firstname"] = relationship.firstname;
                        }
                        if (!string.IsNullOrEmpty(relationship.lastname))
                        {
                            contact["lastname"] = relationship.lastname;
                        }
                        if (!string.IsNullOrEmpty(relationship.mobile))
                        {
                            contact["mobilephone"] = relationship.mobile;
                        }
                        if (!string.IsNullOrEmpty(relationship.email))
                        {
                            contact["emailaddress1"] = relationship.email;
                        }
                        contact["mzk_contacttype"] = new OptionSetValue(275380000);

                        Guid contactid = new Guid();
                        contactid = repo.CreateEntity(contact);

                        if (contactid != null)
                        {
                            Entity relation = new Entity(xrm.mzk_relationship.EntityLogicalName);
                            relation["mzk_customer"] = new EntityReference(xrm.Contact.EntityLogicalName, new Guid(relationship.patientId));
                            if (!string.IsNullOrEmpty(relationship.type))
                            {
                                relation["mzk_role"] = new EntityReference(xrm.mzk_masterdata.EntityLogicalName, new Guid(relationship.type));
                            }
                            relation["mzk_connectedto"] = new EntityReference(xrm.Contact.EntityLogicalName, contactid);
                            relation["mzk_carer"]       = relationship.carer;
                            relation["mzk_nextofkin"]   = relationship.nextOfKin;
                            repo.CreateEntity(relation);
                            return(true);
                        }
                        return(false);
                    }
                }
                else
                {
                    throw new ValidationException("Patient Id missing");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public void GenerateEncryptedFieldQuery(ref QueryExpression queryExpression)
        {
            ThrowErrorIfNotPreOp("Query modification must be done in the PreOp pipeline stage.");

            if (!IsValid() || this.Configuration.EncryptedSearchTrigger is null)
            {
                return;
            }


            var searchValue = GetEncryptedSearchString(queryExpression.Criteria, this.Configuration.EncryptedSearchTrigger);

            if (searchValue is null)
            {
                return;
            }


            var recordConfig = this.Configuration.RecordConfiguration(RecordType);

            FilterExpression encryptedSearchFilter = null;

            foreach (var fieldConfig in recordConfig.ConfiguredFields)
            {
                var fieldSearchValue = CreatePreparedFieldValue(fieldConfig, searchValue);

                if (IsMatch(fieldConfig, fieldSearchValue) &&
                    RoleEvaluator.IsAssignedRole(ExecutionContext, ExecutionContext.InitiatingUserId, fieldConfig.SearchRoles))
                {
                    encryptedSearchFilter = GenerateEncryptedSearchFilterIfNull(encryptedSearchFilter);

                    fieldSearchValue = EncryptionService.Encrypt(fieldSearchValue, null);

                    // the fieldFilter sets up a condition where the field name of encrypted field
                    // must equal the encrypted search value. An additional condition to only return
                    // records if active is added unless the field configuration allows inactive record
                    // search.
                    var fieldFilter = new FilterExpression
                    {
                        FilterOperator = LogicalOperator.And,
                        Conditions     =
                        {
                            new ConditionExpression {
                                AttributeName = fieldConfig.FieldName,
                                Operator      = ConditionOperator.Equal,
                                Values        =     { fieldSearchValue}
                            }
                        }
                    };

                    if (!fieldConfig.AllowInactiveRecordSearch)
                    {
                        fieldFilter.AddCondition(new ConditionExpression
                        {
                            AttributeName = "statecode",
                            Operator      = ConditionOperator.Equal,
                            Values        = { 0 }
                        });
                    }

                    encryptedSearchFilter.AddFilter(fieldFilter);
                }
            }

            if (encryptedSearchFilter != null)
            {
                queryExpression.Criteria = encryptedSearchFilter;
                SetSearchLoggingVariable();
            }
        }
示例#32
0
        public async Task <List <PatientVisitAppointment> > getVisitAppointments(string patientId, VisitAppointmentFilterBy filterBy)
        {
            SoapEntityRepository repo          = SoapEntityRepository.GetService();
            Configuration        configuration = new Configuration();

            configuration = configuration.getConfiguration();
            List <PatientVisitAppointment> listObj = new List <PatientVisitAppointment>();
            QueryExpression query = new QueryExpression("msdyn_workorder");

            query.ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("mzk_visitnumber", "mzk_visitstatus",
                                                                    "mzk_visittype", "mzk_proposedvisitdatetime", "mzk_scheduledenddatetime", "mzk_scheduledstartdatetime",
                                                                    "msdyn_servicerequest", "mzk_actualvisitstartdatetime", "mzk_actualvisitenddatetime", "mzk_schedulestatus");

            query.Criteria.AddCondition("mzk_visittype", ConditionOperator.NotNull);
            query.Criteria.AddCondition("mzk_visitstatus", ConditionOperator.NotEqual, 275380003);//Cancelled



            if (filterBy == VisitAppointmentFilterBy.Today)
            {
                FilterExpression filterExpMain = query.Criteria.AddFilter(LogicalOperator.Or);

                FilterExpression filterExp1    = filterExpMain.AddFilter(LogicalOperator.And);
                FilterExpression subFilterExp1 = filterExp1.AddFilter(LogicalOperator.Or);
                subFilterExp1.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380000); //Proposed
                subFilterExp1.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380001); //Confirmed
                filterExp1.AddCondition("mzk_proposedvisitdatetime", ConditionOperator.GreaterEqual, new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 00, 00, 00));
                filterExp1.AddCondition("mzk_proposedvisitdatetime", ConditionOperator.LessEqual, new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 23, 59, 59));

                FilterExpression filterExp2 = filterExpMain.AddFilter(LogicalOperator.And);
                filterExp2.AddCondition("mzk_schedulestatus", ConditionOperator.Equal, 275380001);//Scheduled
                FilterExpression typeFilter  = filterExp2.AddFilter(LogicalOperator.Or);
                FilterExpression nurseFilter = typeFilter.AddFilter(LogicalOperator.And);
                nurseFilter.AddCondition("mzk_visittype", ConditionOperator.Equal, 275380000);//Nurse Visit
                nurseFilter.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.GreaterEqual, new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 00, 00, 00));
                nurseFilter.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.LessEqual, new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 23, 59, 59));
                FilterExpression deliveryFilter = typeFilter.AddFilter(LogicalOperator.And);
                deliveryFilter.AddCondition("mzk_visittype", ConditionOperator.Equal, 275380001);//Delivery Visit
                deliveryFilter.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.GreaterEqual, new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 00, 00, 00));
                deliveryFilter.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.LessEqual, new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 23, 59, 59));

                FilterExpression filterExp3    = filterExpMain.AddFilter(LogicalOperator.And);
                FilterExpression subFilterExp3 = filterExp3.AddFilter(LogicalOperator.Or);
                subFilterExp3.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380002); //Completed
                subFilterExp3.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380016); //Delivered
                subFilterExp3.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380015); //Visit Started
                filterExp3.AddCondition("mzk_actualvisitstartdatetime", ConditionOperator.GreaterEqual, new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 00, 00, 00));
                filterExp3.AddCondition("mzk_actualvisitstartdatetime", ConditionOperator.LessEqual, new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 23, 59, 59));

                //filterExp = filterExpMain.AddFilter(LogicalOperator.And);
                //filterExp.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380001);//Confirmed
                //filterExp.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.GreaterEqual, new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 00, 00, 00));
                //filterExp.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.LessEqual, new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59));

                //filterExp = filterExpMain.AddFilter(LogicalOperator.And);
                //filterExp.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380002);//Completed
                //filterExp.AddCondition("mzk_actualvisitstartdatetime", ConditionOperator.GreaterEqual, new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 00, 00, 00));
                //filterExp.AddCondition("mzk_actualvisitstartdatetime", ConditionOperator.LessEqual, new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59));
            }
            else if (filterBy == VisitAppointmentFilterBy.Past)
            {
                FilterExpression filterExpMain = query.Criteria.AddFilter(LogicalOperator.Or);

                FilterExpression filterExp1    = filterExpMain.AddFilter(LogicalOperator.And);
                FilterExpression subFilterExp1 = filterExp1.AddFilter(LogicalOperator.Or);
                subFilterExp1.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380000); //Proposed
                subFilterExp1.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380001); //Confirmed
                if (configuration.pastVisitMonths != 0)
                {
                    filterExp1.AddCondition("mzk_proposedvisitdatetime", ConditionOperator.GreaterThan, DateTime.UtcNow.Date.AddMonths(-configuration.pastVisitMonths));
                }
                filterExp1.AddCondition("mzk_proposedvisitdatetime", ConditionOperator.LessThan, DateTime.UtcNow.Date);

                FilterExpression filterExp2 = filterExpMain.AddFilter(LogicalOperator.And);
                filterExp2.AddCondition("mzk_schedulestatus", ConditionOperator.Equal, 275380001);//Scheduled
                FilterExpression typeFilter  = filterExp2.AddFilter(LogicalOperator.Or);
                FilterExpression nurseFilter = typeFilter.AddFilter(LogicalOperator.And);
                nurseFilter.AddCondition("mzk_visittype", ConditionOperator.Equal, 275380000);//Nurse Visit
                if (configuration.pastVisitMonths != 0)
                {
                    nurseFilter.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.GreaterThan, DateTime.UtcNow.Date.AddMonths(-configuration.pastVisitMonths));
                }
                nurseFilter.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.LessThan, DateTime.UtcNow.Date);
                FilterExpression deliveryFilter = typeFilter.AddFilter(LogicalOperator.And);
                deliveryFilter.AddCondition("mzk_visittype", ConditionOperator.Equal, 275380001);//Delivery Visit
                if (configuration.pastVisitMonths != 0)
                {
                    deliveryFilter.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.GreaterThan, DateTime.UtcNow.Date.AddMonths(-configuration.pastVisitMonths));
                }
                deliveryFilter.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.LessThan, DateTime.UtcNow.Date);
                //nurseFilter.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.GreaterEqual, new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 00, 00, 00));
                //nurseFilter.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.LessEqual, new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 23, 59, 59));

                FilterExpression filterExp3    = filterExpMain.AddFilter(LogicalOperator.And);
                FilterExpression subFilterExp3 = filterExp3.AddFilter(LogicalOperator.Or);
                subFilterExp3.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380002); //Completed
                subFilterExp3.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380016); //Delivered
                subFilterExp3.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380015); //Visit Started
                if (configuration.pastVisitMonths != 0)
                {
                    filterExp3.AddCondition("mzk_actualvisitstartdatetime", ConditionOperator.GreaterThan, DateTime.UtcNow.Date.AddMonths(-configuration.pastVisitMonths));
                }
                filterExp3.AddCondition("mzk_actualvisitstartdatetime", ConditionOperator.LessThan, DateTime.UtcNow.Date);
                #region Old Filter
                //FilterExpression filterExpMain = query.Criteria.AddFilter(LogicalOperator.Or);

                //FilterExpression filterExp = filterExpMain.AddFilter(LogicalOperator.And);
                //filterExp.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380000);//Proposed
                //if (configuration.pastVisitMonths != 0)
                //    filterExp.AddCondition("mzk_proposedvisitdatetime", ConditionOperator.GreaterThan, DateTime.Now.AddMonths(-configuration.pastVisitMonths));
                //filterExp.AddCondition("mzk_proposedvisitdatetime", ConditionOperator.LessThan, DateTime.Now.Date);

                //filterExp = filterExpMain.AddFilter(LogicalOperator.And);
                //filterExp.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380001);//Confirmed
                //if (configuration.pastVisitMonths != 0)
                //    filterExp.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.GreaterThan, DateTime.Now.AddMonths(-configuration.pastVisitMonths));
                //filterExp.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.LessThan, DateTime.Now.Date);

                //filterExp = filterExpMain.AddFilter(LogicalOperator.And);
                //filterExp.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380002);//Completed
                //if (configuration.pastVisitMonths != 0)
                //    filterExp.AddCondition("mzk_actualvisitstartdatetime", ConditionOperator.GreaterThan, DateTime.Now.AddMonths(-configuration.pastVisitMonths));
                //filterExp.AddCondition("mzk_actualvisitstartdatetime", ConditionOperator.LessThan, DateTime.Now.Date);
                #endregion
            }
            else if (filterBy == VisitAppointmentFilterBy.Future)
            {
                FilterExpression filterExpMain = query.Criteria.AddFilter(LogicalOperator.Or);

                FilterExpression filterExp1    = filterExpMain.AddFilter(LogicalOperator.And);
                FilterExpression subFilterExp1 = filterExp1.AddFilter(LogicalOperator.Or);
                subFilterExp1.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380000); //Proposed
                subFilterExp1.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380001); //Confirmed
                //if (configuration.pastVisitMonths != 0)
                //    filterExp1.AddCondition("mzk_proposedvisitdatetime", ConditionOperator.LessThan, DateTime.UtcNow.Date.AddMonths(-configuration.futureVisitMonths));
                filterExp1.AddCondition("mzk_proposedvisitdatetime", ConditionOperator.GreaterThan, DateTime.UtcNow.Date);

                FilterExpression filterExp2 = filterExpMain.AddFilter(LogicalOperator.And);
                filterExp2.AddCondition("mzk_schedulestatus", ConditionOperator.Equal, 275380001);//Scheduled
                FilterExpression typeFilter  = filterExp2.AddFilter(LogicalOperator.Or);
                FilterExpression nurseFilter = typeFilter.AddFilter(LogicalOperator.And);
                nurseFilter.AddCondition("mzk_visittype", ConditionOperator.Equal, 275380000);//Nurse Visit
                if (configuration.futureVisitMonths != 0)
                {
                    nurseFilter.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.LessThan, DateTime.UtcNow.Date.AddMonths(configuration.futureVisitMonths));
                }
                nurseFilter.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.GreaterThan, DateTime.UtcNow.Date);
                FilterExpression deliveryFilter = typeFilter.AddFilter(LogicalOperator.And);
                deliveryFilter.AddCondition("mzk_visittype", ConditionOperator.Equal, 275380001);//Delivery Visit
                if (configuration.futureVisitMonths != 0)
                {
                    deliveryFilter.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.LessThan, DateTime.UtcNow.Date.AddMonths(configuration.futureVisitMonths));
                }
                deliveryFilter.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.GreaterThan, DateTime.UtcNow.Date);
                //nurseFilter.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.GreaterEqual, new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 00, 00, 00));
                //nurseFilter.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.LessEqual, new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 23, 59, 59));

                FilterExpression filterExp3    = filterExpMain.AddFilter(LogicalOperator.And);
                FilterExpression subFilterExp3 = filterExp3.AddFilter(LogicalOperator.Or);
                subFilterExp3.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380002); //Completed
                subFilterExp3.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380016); //Delivered
                subFilterExp3.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380015); //Visit Started
                if (configuration.futureVisitMonths != 0)
                {
                    filterExp3.AddCondition("mzk_actualvisitstartdatetime", ConditionOperator.LessThan, DateTime.UtcNow.Date.AddMonths(configuration.futureVisitMonths));
                }
                filterExp3.AddCondition("mzk_actualvisitstartdatetime", ConditionOperator.GreaterThan, DateTime.UtcNow.Date);
                #region Old Filter
                //FilterExpression filterExpMain = query.Criteria.AddFilter(LogicalOperator.Or);

                //FilterExpression filterExp = filterExpMain.AddFilter(LogicalOperator.And);
                //filterExp.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380000);//Proposed
                //filterExp.AddCondition("mzk_proposedvisitdatetime", ConditionOperator.GreaterThan, DateTime.Now.Date);
                //if (configuration.futureVisitMonths != 0)
                //    filterExp.AddCondition("mzk_proposedvisitdatetime", ConditionOperator.LessThan, DateTime.Now.AddMonths(configuration.futureVisitMonths));

                //filterExp = filterExpMain.AddFilter(LogicalOperator.And);
                //filterExp.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380001);//Confirmed
                //filterExp.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.GreaterThan, DateTime.Now.Date);
                //if (configuration.futureVisitMonths != 0)
                //    filterExp.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.LessThan, DateTime.Now.AddMonths(configuration.futureVisitMonths));

                //filterExp = filterExpMain.AddFilter(LogicalOperator.And);
                //filterExp.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380002);//Completed
                //filterExp.AddCondition("mzk_actualvisitstartdatetime", ConditionOperator.GreaterThan, DateTime.Now.Date);
                //if (configuration.futureVisitMonths != 0)
                //    filterExp.AddCondition("mzk_actualvisitstartdatetime", ConditionOperator.LessThan, DateTime.Now.AddMonths(configuration.futureVisitMonths));
                #endregion

                //FilterExpression filterExp = query.Criteria.AddFilter(LogicalOperator.Or);

                //filterExp.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380001);//Confirmed
                //filterExp.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380004);//Ready for Dispense

                //filterExp.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380000);//Proposed
            }



            //if (filterBy == VisitAppointmentFilterBy.Today)
            //{
            //    FilterExpression filterExpMain = query.Criteria.AddFilter(LogicalOperator.Or);

            //    FilterExpression filterExp = filterExpMain.AddFilter(LogicalOperator.And);
            //    filterExp.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380000);//Proposed
            //    filterExp.AddCondition("mzk_proposedvisitdatetime", ConditionOperator.GreaterEqual, new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 00, 00, 00));
            //    filterExp.AddCondition("mzk_proposedvisitdatetime", ConditionOperator.LessEqual, new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59));

            //    filterExp = filterExpMain.AddFilter(LogicalOperator.And);
            //    filterExp.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380001);//Confirmed
            //    filterExp.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.GreaterEqual, new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 00, 00, 00));
            //    filterExp.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.LessEqual, new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59));

            //    filterExp = filterExpMain.AddFilter(LogicalOperator.And);
            //    filterExp.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380002);//Completed
            //    filterExp.AddCondition("mzk_actualvisitstartdatetime", ConditionOperator.GreaterEqual, new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 00, 00, 00));
            //    filterExp.AddCondition("mzk_actualvisitstartdatetime", ConditionOperator.LessEqual, new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59));
            //}
            //else if (filterBy == VisitAppointmentFilterBy.Past)
            //{
            //    FilterExpression filterExpMain = query.Criteria.AddFilter(LogicalOperator.Or);

            //    FilterExpression filterExp = filterExpMain.AddFilter(LogicalOperator.And);
            //    filterExp.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380000);//Proposed
            //    if (configuration.pastVisitMonths != 0)
            //        filterExp.AddCondition("mzk_proposedvisitdatetime", ConditionOperator.GreaterThan, DateTime.Now.AddMonths(-configuration.pastVisitMonths));
            //    filterExp.AddCondition("mzk_proposedvisitdatetime", ConditionOperator.LessThan, DateTime.Now.Date);

            //    filterExp = filterExpMain.AddFilter(LogicalOperator.And);
            //    filterExp.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380001);//Confirmed
            //    if (configuration.pastVisitMonths != 0)
            //        filterExp.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.GreaterThan, DateTime.Now.AddMonths(-configuration.pastVisitMonths));
            //    filterExp.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.LessThan, DateTime.Now.Date);

            //    filterExp = filterExpMain.AddFilter(LogicalOperator.And);
            //    filterExp.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380002);//Completed
            //    if (configuration.pastVisitMonths != 0)
            //        filterExp.AddCondition("mzk_actualvisitstartdatetime", ConditionOperator.GreaterThan, DateTime.Now.AddMonths(-configuration.pastVisitMonths));
            //    filterExp.AddCondition("mzk_actualvisitstartdatetime", ConditionOperator.LessThan, DateTime.Now.Date);
            //}
            //else if (filterBy == VisitAppointmentFilterBy.Future)
            //{
            //    FilterExpression filterExpMain = query.Criteria.AddFilter(LogicalOperator.Or);

            //    FilterExpression filterExp = filterExpMain.AddFilter(LogicalOperator.And);
            //    filterExp.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380000);//Proposed
            //    filterExp.AddCondition("mzk_proposedvisitdatetime", ConditionOperator.GreaterThan, DateTime.Now.AddHours(5));
            //    if (configuration.futureVisitMonths != 0)
            //        filterExp.AddCondition("mzk_proposedvisitdatetime", ConditionOperator.LessThan, DateTime.Now.AddMonths(configuration.futureVisitMonths));

            //    filterExp = filterExpMain.AddFilter(LogicalOperator.And);
            //    filterExp.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380001);//Confirmed
            //    filterExp.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.GreaterThan, DateTime.Now.AddHours(5));
            //    if (configuration.futureVisitMonths != 0)
            //        filterExp.AddCondition("mzk_scheduledstartdatetime", ConditionOperator.LessThan, DateTime.Now.AddMonths(configuration.futureVisitMonths));

            //    filterExp = filterExpMain.AddFilter(LogicalOperator.And);
            //    filterExp.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380002);//Completed
            //    filterExp.AddCondition("mzk_actualvisitstartdatetime", ConditionOperator.GreaterThan, DateTime.Now.Date.AddHours(5));
            //    if (configuration.futureVisitMonths != 0)
            //        filterExp.AddCondition("mzk_actualvisitstartdatetime", ConditionOperator.LessThan, DateTime.Now.AddMonths(configuration.futureVisitMonths));


            //    //FilterExpression filterExp = query.Criteria.AddFilter(LogicalOperator.Or);

            //    //filterExp.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380001);//Confirmed
            //    //filterExp.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380004);//Ready for Dispense

            //    //filterExp.AddCondition("mzk_visitstatus", ConditionOperator.Equal, 275380000);//Proposed
            //}


            query.AddOrder("mzk_visitnumber", OrderType.Ascending);
            //query.AddOrder("mzk_scheduledstartdatetime", OrderType.Descending);
            LinkEntity workOrderType = new LinkEntity("msdyn_workorder", "msdyn_workordertype", "msdyn_workordertype", "msdyn_workordertypeid", JoinOperator.Inner);
            workOrderType.Columns     = new ColumnSet("mzk_duration", "mzk_durationunit");
            workOrderType.EntityAlias = "WorkOrderType";
            query.LinkEntities.Add(workOrderType);

            LinkEntity entityTypePatient = new LinkEntity("msdyn_workorder", "account", "msdyn_serviceaccount", "accountid", JoinOperator.Inner);

            entityTypePatient.Columns     = new Microsoft.Xrm.Sdk.Query.ColumnSet(false);
            entityTypePatient.EntityAlias = "Patient";
            entityTypePatient.LinkCriteria.AddCondition("primarycontactid", ConditionOperator.Equal, new Guid(patientId));

            query.LinkEntities.Add(entityTypePatient);

            LinkEntity entityTypeResource = new LinkEntity("msdyn_workorder", "bookableresource", "mzk_resource", "bookableresourceid", JoinOperator.LeftOuter);

            entityTypeResource.Columns     = new Microsoft.Xrm.Sdk.Query.ColumnSet("name", "userid", "bookableresourceid");
            entityTypeResource.EntityAlias = "BookingResource";

            query.LinkEntities.Add(entityTypeResource);

            LinkEntity entityTypeUser = new LinkEntity("bookableresource", "systemuser", "userid", "systemuserid", JoinOperator.LeftOuter);

            entityTypeUser.Columns     = new Microsoft.Xrm.Sdk.Query.ColumnSet("entityimage");
            entityTypeUser.EntityAlias = "ResourceUser";

            entityTypeResource.LinkEntities.Add(entityTypeUser);

            EntityCollection entitycol = repo.GetEntityCollection(query);

            if (entitycol != null && entitycol.Entities != null)
            {
                foreach (Entity entity in entitycol.Entities)
                {
                    PatientVisitAppointment modelObj = new PatientVisitAppointment();

                    modelObj.WorkOrderId = entity.Id.ToString();

                    if (entity.Attributes.Contains("mzk_visitnumber"))
                    {
                        modelObj.VisitNumber = entity["mzk_visitnumber"].ToString();
                    }
                    if (entity.Attributes.Contains("mzk_visitstatus"))
                    {
                        modelObj.VisitStatus = entity.FormattedValues["mzk_visitstatus"].ToString();
                    }

                    if (entity.Attributes.Contains("mzk_visittype"))
                    {
                        modelObj.VisitType = entity.FormattedValues["mzk_visittype"].ToString();
                    }


                    if (entity.Attributes.Contains("mzk_proposedvisitdatetime"))
                    {
                        modelObj.VisitStartDate = Convert.ToDateTime(entity["mzk_proposedvisitdatetime"]);
                    }

                    if (modelObj.VisitStatus.Equals("Proposed"))
                    {
                        if (entity.Attributes.Contains("mzk_proposedvisitdatetime"))
                        {
                            modelObj.VisitStartDate = Convert.ToDateTime(entity["mzk_proposedvisitdatetime"]);
                            if (entity.Attributes.Contains("WorkOrderType.mzk_duration"))
                            {
                                if (entity.Attributes.Contains("WorkOrderType.mzk_durationunit"))
                                {
                                    if (entity.FormattedValues["WorkOrderType.mzk_durationunit"].Equals("Minutes"))
                                    {
                                        modelObj.VisitEndDate = modelObj.VisitStartDate.AddMinutes(Convert.ToDouble(entity.GetAttributeValue <AliasedValue>("WorkOrderType.mzk_duration").Value));
                                    }
                                    else if (entity.FormattedValues["WorkOrderType.mzk_durationunit"].Equals("Hours"))
                                    {
                                        modelObj.VisitEndDate = modelObj.VisitStartDate.AddHours(Convert.ToDouble(entity.GetAttributeValue <AliasedValue>("WorkOrderType.mzk_duration").Value));
                                    }
                                }
                            }
                        }
                    }
                    //if (modelObj.VisitStatus.Equals("Scheduled"))
                    //{
                    //    if (entity.Attributes.Contains("mzk_scheduledenddatetime"))
                    //    {
                    //        modelObj.VisitEndDate = Convert.ToDateTime(entity["mzk_scheduledenddatetime"]);
                    //    }

                    //    if (entity.Attributes.Contains("mzk_scheduledstartdatetime"))
                    //    {
                    //        modelObj.VisitStartDate = Convert.ToDateTime(entity["mzk_scheduledstartdatetime"]);
                    //    }
                    //}
                    if (modelObj.VisitStatus.Equals("Completed"))
                    {
                        if (entity.Attributes.Contains("mzk_actualvisitenddatetime"))
                        {
                            modelObj.VisitEndDate = Convert.ToDateTime(entity["mzk_actualvisitenddatetime"]);
                        }

                        if (entity.Attributes.Contains("mzk_actualvisitstartdatetime"))
                        {
                            modelObj.VisitStartDate = Convert.ToDateTime(entity["mzk_actualvisitstartdatetime"]);
                        }
                    }

                    //if (modelObj.VisitType != null && modelObj.VisitType.Equals("Nursing Visit"))
                    //{
                    //    if (entity.Attributes.Contains("mzk_expectedarrivalstarttimewindow"))
                    //        modelObj.VisitStartDate = Convert.ToDateTime(entity["mzk_expectedarrivalstarttimewindow"]);
                    //    if (entity.Attributes.Contains("mzk_expectedarrivalendtimewindow"))
                    //        modelObj.VisitEndDate = Convert.ToDateTime(entity["mzk_expectedarrivalendtimewindow"]);
                    //}

                    if (entity.Attributes.Contains("msdyn_servicerequest"))
                    {
                        modelObj.CaseId = (entity["msdyn_servicerequest"] as EntityReference).Id.ToString();
                    }

                    if (entity.Attributes.Contains("BookingResource.bookableresourceid"))
                    {
                        modelObj.ResourceId = (entity["BookingResource.bookableresourceid"] as AliasedValue).Value.ToString();
                    }

                    if (entity.Attributes.Contains("ResourceUser.entityimage") && entity["ResourceUser.entityimage"] != null)
                    {
                        modelObj.ResourceImage = Convert.ToBase64String((entity["ResourceUser.entityimage"] as AliasedValue).Value as Byte[]);
                    }

                    if (entity.Attributes.Contains("BookingResource.name"))
                    {
                        modelObj.ResourceName = (entity["BookingResource.name"] as AliasedValue).Value.ToString();
                    }

                    if (entity.Attributes.Contains("BookingResource.userid"))
                    {
                        modelObj.UserId = ((entity["BookingResource.userid"] as AliasedValue).Value as EntityReference).Id.ToString();
                    }
                    if (entity.Attributes.Contains("mzk_schedulestatus"))
                    {
                        if ((entity["mzk_schedulestatus"] as OptionSetValue).Value.Equals(275380001))
                        {
                            if (entity.Attributes.Contains("mzk_scheduledenddatetime"))
                            {
                                modelObj.VisitEndDate = Convert.ToDateTime(entity["mzk_scheduledenddatetime"]);
                            }

                            if (entity.Attributes.Contains("mzk_scheduledstartdatetime"))
                            {
                                modelObj.VisitStartDate = Convert.ToDateTime(entity["mzk_scheduledstartdatetime"]);
                            }
                        }
                    }

                    listObj.Add(modelObj);
                }
            }

            return(listObj);
        }
示例#33
0
        public void Execute(IServiceProvider serviceProvider)
        {
            // Obtain the tracing service
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = (IPluginExecutionContext)
                                              serviceProvider.GetService(typeof(IPluginExecutionContext));

            // The InputParameters collection contains all the data passed in the message request.
            if (context.InputParameters.Contains("Target") &&
                context.InputParameters["Target"] is EntityReference)
            {
                // Obtain the target entity from the input parameters.
                EntityReference reference = (EntityReference)context.InputParameters["Target"];

                // Obtain the organization service reference which you will need for
                // web service calls.
                IOrganizationServiceFactory serviceFactory =
                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
                try
                {
                    Entity entity = new Entity();
                    entity = service.Retrieve(reference.LogicalName, reference.Id, new ColumnSet(true));// ("ss_application");


                    string fetchXml = @"<fetch distinct='false' mapping='logical' returntotalrecordcount='true' page='1' count='50' no-lock='false'>
                                     <entity name='salesorder'>
                                         <attribute name='entityimage_url'/>
                                         <attribute name='name'/>
                                         <attribute name='statecode'/>
                                         <attribute name='totalamount'/>
                                         <attribute name='salesorderid'/>
                                         <order attribute='name' descending='true'/>
                                         <link-entity name='ss_application' from='ss_applicationid' to='ss_application' alias='bb'>
                                             <filter type='and'>
                                                <condition attribute='ss_applicationid' operator='eq' uitype='ss_application' value='" + entity.Id + @"'/>
                                             </filter>  
                                         </link-entity>
                                     </entity>
                                 </fetch>";

                    EntityCollection appOrders = service.RetrieveMultiple(new FetchExpression(fetchXml));

                    if (appOrders.TotalRecordCount == 0)
                    {
                        Guid   orderId   = Guid.NewGuid();
                        Entity order     = new Entity("salesorder", orderId);
                        Entity orderLine = new Entity("salesorderdetail");

                        if (entity.Contains("ss_applicationid"))
                        {
                            ConditionExpression condition = new ConditionExpression
                            {
                                AttributeName = "name",
                                Operator      = ConditionOperator.Equal
                            };
                            condition.Values.Add("Primary Unit");

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

                            QueryExpression query = new QueryExpression("uom");
                            query.ColumnSet.AddColumn("name");
                            query.Criteria.AddFilter(filter);

                            EntityCollection uomList = service.RetrieveMultiple(query);

                            if (uomList.Entities.Count > 0)
                            {
                                Guid uomId = uomList[0].Id;

                                //@"<Fetch mapping='logical'>
                                //    <entity name='uom'>
                                //        <attribute name='uomid'/>
                                //        <attribute name='name'/>
                                //        <filter type='and'>
                                //            <condition attribute='name' operator='eq' value='Primary Unit'/>
                                //        </filter>
                                //    </entity>
                                //</fetch>";

                                order["name"]                  = ("Order for " + entity.Attributes["ss_name"]);
                                order["ss_application"]        = new EntityReference("ss_application", entity.Id);
                                order["pricelevelid"]          = entity.Attributes["ss_pricelist"];
                                order["customerid"]            = entity.Attributes["ss_customer"];
                                order["ss_destinationaddress"] = entity.Attributes["ss_destinationaddress"];

                                // Create the Order in Microsoft Dynamics CRM.
                                tracingService.Trace("AppOrderPlugin: Creating the Order.");
                                service.Create(order);

                                orderLine["isproductoverridden"] = false;
                                orderLine["productid"]           = entity.Attributes["ss_product"];
                                orderLine["uomid"]        = new EntityReference("uom", uomId); //uoms
                                orderLine["salesorderid"] = new EntityReference("salesorder", orderId);
                                orderLine["quantity"]     = Convert.ToDecimal(1);

                                // Create the Order Line in Microsoft Dynamics CRM.
                                tracingService.Trace("AppOrderPlugin: Creating the Product Order Line.");
                                service.Create(orderLine);

                                if (entity.FormattedValues["ss_applicationtype"].Equals("Package Submission"))
                                {
                                    Entity shippingLine = new Entity("salesorderdetail");
                                    Entity primaryUnit  = new Entity("uom");


                                    shippingLine["isproductoverridden"] = false;
                                    shippingLine["productid"]           = entity.Attributes["ss_shippingspeed"];
                                    shippingLine["uomid"]        = new EntityReference("uom", uomId); //Guid.Parse("46d8b737-2339-4011-984a-5e54126ccdb2") /uoms
                                    shippingLine["salesorderid"] = new EntityReference("salesorder", orderId);
                                    shippingLine["quantity"]     = Convert.ToDecimal(1);;

                                    // Create the Order Line in Microsoft Dynamics CRM.
                                    tracingService.Trace("AppOrderPlugin: Creating the Shipping Speed Order Line.");
                                    service.Create(shippingLine);
                                }

                                //close application
                                if (order.Id == orderId)
                                {
                                    entity["statuscode"] = new OptionSetValue(2);
                                    entity["statecode"]  = new OptionSetValue(1);
                                    service.Update(entity);
                                }
                            }
                            else
                            {
                                throw new InvalidPluginExecutionException("UoM not found");
                            }
                        }
                    }
                    else
                    {
                        throw new InvalidPluginExecutionException("An order already exists for this application");
                    }
                }
                catch (FaultException <OrganizationServiceFault> ex)
                {
                    throw new InvalidPluginExecutionException("An error occurred in FollowUpPlugin.", ex);
                }
                catch (Exception ex)
                {
                    tracingService.Trace("FollowUpPlugin: {0}", ex.ToString());
                    throw;
                }
            }
        }
        public static FilterExpression ToFilterExpression(this XElement elem, XrmFakedContext ctx)
        {
            var filterExpression = new FilterExpression();

            filterExpression.FilterOperator = elem.GetAttribute("type").Value.Equals("and") ? 
                                                    LogicalOperator.And : LogicalOperator.Or;

            //Process other filters recursively
            var otherFilters = elem
                        .Elements() //child nodes of this filter
                        .Where(el => el.Name.LocalName.Equals("filter"))
                        .Select(el => el.ToFilterExpression(ctx))
                        .ToList();


            //Process conditions
            var conditions = elem
                        .Elements() //child nodes of this filter
                        .Where(el => el.Name.LocalName.Equals("condition"))
                        .Select(el => el.ToConditionExpression(ctx))
                        .ToList();

            foreach (var c in conditions)
                filterExpression.AddCondition(c);

            foreach (var f in otherFilters)
                filterExpression.AddFilter(f);

            return filterExpression;
        }
示例#35
0
        public List <Unit> getUnit(string Type, string Dosage)
        {
            List <Unit> Unit = new List <Unit>();

            if (!string.IsNullOrEmpty(Dosage))
            {
                #region Dosage
                //QueryExpression query = new QueryExpression("mzk_dosageform");
                //FilterExpression childFilter = query.Criteria.AddFilter(LogicalOperator.And);
                //childFilter.AddCondition("mzk_dosageformid", ConditionOperator.Equal, Dosage);
                //LinkEntity UnitEntity = new LinkEntity("mzk_dosageform", "mzk_unit", "mzk_dosageformid", "mzk_doseunit", JoinOperator.Inner);
                //UnitEntity.Columns = new Microsoft.Xrm.Sdk.Query.ColumnSet("mzk_description", "mzk_unitid");
                //UnitEntity.EntityAlias = "Unit";
                //query.LinkEntities.Add(UnitEntity);

                string          entity1 = "mzk_dosageform";
                string          entity2 = "mzk_unit";
                string          relationshipEntityName = "mzk_mzk_dosageform_mzk_unit";
                QueryExpression query       = new QueryExpression(entity1);
                LinkEntity      linkEntity1 = new LinkEntity(entity1, relationshipEntityName, "mzk_dosageformid", "mzk_dosageformid", JoinOperator.Inner);
                LinkEntity      linkEntity2 = new LinkEntity(relationshipEntityName, entity2, "mzk_unitid", "mzk_unitid", JoinOperator.Inner);
                linkEntity2.Columns     = new Microsoft.Xrm.Sdk.Query.ColumnSet("mzk_description", "mzk_unitid");
                linkEntity2.EntityAlias = "Unit";
                linkEntity1.LinkEntities.Add(linkEntity2);
                query.LinkEntities.Add(linkEntity1);
                linkEntity1.LinkCriteria = new FilterExpression();
                linkEntity1.LinkCriteria.AddCondition(new ConditionExpression("mzk_dosageformid", ConditionOperator.Equal, Dosage));

                #endregion
                SoapEntityRepository entityRepository = SoapEntityRepository.GetService();
                EntityCollection     entitycollection = entityRepository.GetEntityCollection(query);
                foreach (Entity entity in entitycollection.Entities)
                {
                    Unit model = new Unit();
                    model.UnitId      = ((AliasedValue)entity.Attributes["Unit.mzk_unitid"]).Value.ToString();
                    model.Description = ((AliasedValue)entity.Attributes["Unit.mzk_description"]).Value.ToString();

                    Unit.Add(model);
                }
            }
            else
            {
                #region Unit
                QueryExpression query = new QueryExpression("mzk_unit");
                query.ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet("mzk_description", "mzk_unitid", "mzk_code");
                FilterExpression childFilter = query.Criteria.AddFilter(LogicalOperator.And);
                childFilter.AddCondition("mzk_type", ConditionOperator.Equal, Type);

                #endregion
                SoapEntityRepository entityRepository = SoapEntityRepository.GetService();
                EntityCollection     entitycollection = entityRepository.GetEntityCollection(query);
                foreach (Entity entity in entitycollection.Entities)
                {
                    Unit model = new Unit();
                    model.UnitId      = entity.Id.ToString();//.Attributes["mzk_ordersetupid"].ToString();
                    model.Description = entity.Attributes["mzk_description"].ToString();
                    model.Code        = entity.Attributes["mzk_code"].ToString();
                    //model.Address = entity.Attributes["address1_composite"].ToString();
                    Unit.Add(model);
                }
            }
            return(Unit);
        }
示例#36
0
        /// <summary>
        /// This method returns the GUID of a incident, by given Name.
        /// </summary>
        /// <param name="caseName">This is the string that holds the Name value of the entity</param>
        /// <param name="service">This is a reference to the service/context of the connection</param>
        /// <returns></returns>
        private Guid GetGUIDByName(string caseName, IOrganizationService service)
        {
            ConditionExpression condition = new ConditionExpression();
            condition.AttributeName = "new_supportrequestid";
            condition.Operator = ConditionOperator.Equal;
            condition.Values.Add(caseName);

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

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

            EntityCollection result = service.RetrieveMultiple(query);

            var accountid = Guid.Empty;
            try
            {
                accountid = result.Entities.FirstOrDefault().Id;
            }
            catch (Exception)
            {

                Console.WriteLine("No item with that SRID was found!");
            }

            return accountid;
        }
示例#37
0
        private List <SdkMessageProcessingStep> FindSdkMessageProcessingStep(List <PluginStage> listStages, string pluginName, string messageName, SdkMessageProcessingStep.Schema.OptionSets.statuscode?statuscode)
        {
            var linkPluginType = new LinkEntity()
            {
                LinkFromEntityName    = SdkMessageProcessingStep.EntityLogicalName,
                LinkFromAttributeName = SdkMessageProcessingStep.Schema.Attributes.eventhandler,

                LinkToEntityName    = PluginType.EntityLogicalName,
                LinkToAttributeName = PluginType.EntityPrimaryIdAttribute,

                EntityAlias = SdkMessageProcessingStep.Schema.Attributes.eventhandler,

                Columns = new ColumnSet(PluginType.Schema.Attributes.typename, PluginType.Schema.Attributes.assemblyname, PluginType.Schema.Attributes.pluginassemblyid),
            };

            var linkMessage = new LinkEntity()
            {
                LinkFromEntityName    = SdkMessageProcessingStep.EntityLogicalName,
                LinkFromAttributeName = SdkMessageProcessingStep.Schema.Attributes.sdkmessageid,

                LinkToEntityName    = SdkMessage.EntityLogicalName,
                LinkToAttributeName = SdkMessage.EntityPrimaryIdAttribute,

                EntityAlias = SdkMessageProcessingStep.Schema.Attributes.sdkmessageid,

                Columns = new ColumnSet(SdkMessage.Schema.Attributes.categoryname),
            };

            QueryExpression query = new QueryExpression()
            {
                NoLock = true,

                EntityName = SdkMessageProcessingStep.EntityLogicalName,

                ColumnSet = ColumnSetInstances.AllColumns,

                Criteria =
                {
                    Conditions =
                    {
                        new ConditionExpression(SdkMessageProcessingStep.Schema.Attributes.ishidden, ConditionOperator.Equal, false),
                    },
                },

                LinkEntities =
                {
                    linkPluginType,

                    linkMessage,

                    new LinkEntity()
                    {
                        LinkFromEntityName    = SdkMessageProcessingStep.EntityLogicalName,
                        LinkFromAttributeName = SdkMessageProcessingStep.Schema.Attributes.sdkmessagefilterid,

                        LinkToEntityName    = SdkMessageFilter.EntityLogicalName,
                        LinkToAttributeName = SdkMessageFilter.EntityPrimaryIdAttribute,

                        EntityAlias = SdkMessageProcessingStep.Schema.Attributes.sdkmessagefilterid,

                        JoinOperator = JoinOperator.LeftOuter,

                        Columns = new ColumnSet(SdkMessageFilter.Schema.Attributes.primaryobjecttypecode,SdkMessageFilter.Schema.Attributes.secondaryobjecttypecode),
                    },
                },
            };

            if (statuscode.HasValue)
            {
                query.Criteria.Conditions.Add(new ConditionExpression(SdkMessageProcessingStep.Schema.Attributes.statuscode, ConditionOperator.Equal, (int)statuscode.Value));
            }

            if (!string.IsNullOrEmpty(pluginName))
            {
                linkPluginType.LinkCriteria.Conditions.Add(new ConditionExpression(PluginType.Schema.Attributes.typename, ConditionOperator.Like, "%" + pluginName + "%"));
            }

            if (!string.IsNullOrEmpty(messageName))
            {
                linkMessage.LinkCriteria.Conditions.Add(new ConditionExpression(SdkMessage.Schema.Attributes.name, ConditionOperator.Like, messageName + "%"));
            }

            if (listStages != null && listStages.Count > 0)
            {
                FilterExpression filter = new FilterExpression(LogicalOperator.Or);

                if (listStages.Contains(PluginStage.PreValidation))
                {
                    var temp = new FilterExpression(LogicalOperator.And);

                    temp.AddCondition(SdkMessageProcessingStep.Schema.Attributes.stage, ConditionOperator.Equal, (int)SdkMessageProcessingStep.Schema.OptionSets.stage.Pre_validation_10);

                    filter.AddFilter(temp);
                }

                if (listStages.Contains(PluginStage.Pre))
                {
                    var temp = new FilterExpression(LogicalOperator.And);

                    temp.AddCondition(SdkMessageProcessingStep.Schema.Attributes.stage, ConditionOperator.Equal, (int)SdkMessageProcessingStep.Schema.OptionSets.stage.Pre_operation_20);

                    filter.AddFilter(temp);
                }

                if (listStages.Contains(PluginStage.PostSynch))
                {
                    var temp = new FilterExpression(LogicalOperator.And);

                    temp.AddCondition(SdkMessageProcessingStep.Schema.Attributes.stage, ConditionOperator.Equal, (int)SdkMessageProcessingStep.Schema.OptionSets.stage.Post_operation_40);
                    temp.AddCondition(SdkMessageProcessingStep.Schema.Attributes.mode, ConditionOperator.Equal, (int)SdkMessageProcessingStep.Schema.OptionSets.mode.Synchronous_0);

                    filter.AddFilter(temp);
                }

                if (listStages.Contains(PluginStage.PostAsych))
                {
                    var temp = new FilterExpression(LogicalOperator.And);

                    temp.AddCondition(SdkMessageProcessingStep.Schema.Attributes.stage, ConditionOperator.Equal, (int)SdkMessageProcessingStep.Schema.OptionSets.stage.Post_operation_40);
                    temp.AddCondition(SdkMessageProcessingStep.Schema.Attributes.mode, ConditionOperator.Equal, (int)SdkMessageProcessingStep.Schema.OptionSets.mode.Asynchronous_1);

                    filter.AddFilter(temp);
                }

                query.Criteria.Filters.Add(filter);
            }
            else
            {
                query.Criteria.AddCondition(SdkMessageProcessingStep.Schema.Attributes.stage, ConditionOperator.In
                                            , (int)SdkMessageProcessingStep.Schema.OptionSets.stage.Pre_validation_10
                                            , (int)SdkMessageProcessingStep.Schema.OptionSets.stage.Pre_operation_20
                                            , (int)SdkMessageProcessingStep.Schema.OptionSets.stage.Post_operation_40
                                            );
            }

            var result = _service.RetrieveMultipleAll <SdkMessageProcessingStep>(query);

            FullfillEntitiesSteps(result);

            return(result);
        }
示例#38
0
        private Guid findCustomer(string customerName, IOrganizationService service)
        {

            ConditionExpression condition = new ConditionExpression();
            condition.AttributeName = "name";
            condition.Operator = ConditionOperator.Contains;
            condition.Values.Add(customerName);

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

            QueryExpression query = new QueryExpression();
            query.EntityName = "account";
            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)
            {
                Entity newAccount = new Entity("account");

                newAccount["name"] = customerName;

                var newAccID = service.Create(newAccount);
                return newAccID;
            }
        }
        private IEnumerable<FilterExpression> GetFiltersPersonasJuridicas(IEnumerable<PersonaJuridica> sqlPersonasJuridicas)
        {
            var filters = GetFilters<PersonaJuridica>(
                sqlPersonasJuridicas,
                x =>
                {
                    var filter = new FilterExpression(LogicalOperator.And);

                    filter.AddCondition(new ConditionExpression("name", ConditionOperator.Equal, x.RazonSocial));

                    return filter;
                });

            return filters;
        }
示例#40
0
        public SortedDictionary<string, Guid?> IndexMatchingGuids(string entityName, string matchField,
            IEnumerable<string> matchValues)
        {
            var result = new SortedDictionary<string, Guid?>();
            if (matchValues != null && matchValues.Any())
            {
                var filterExpressions = new List<FilterExpression>();
                foreach (var matchValue in matchValues)
                {
                    var parseValue = ParseField(matchField, entityName, matchValue);
                    var stringValue = GetFieldAsMatchString(entityName, matchField, parseValue);
                    var filterExpression = new FilterExpression();
                    filterExpression.AddCondition(new ConditionExpression(matchField, ConditionOperator.Equal,
                        stringValue));
                    filterExpressions.Add(filterExpression);
                }
                var entities = RetrieveAllOrClauses(entityName, filterExpressions, new[] {matchField});

                foreach (var entity in entities)
                {
                    var matchValue = XrmEntity.GetStringField(entity,
                        GetFieldAsMatchString(entityName, matchField, matchField));
                    if (!result.ContainsKey(matchValue))
                        result.Add(matchValue, entity.Id);
                }
                foreach (var value in matchValues)
                {
                    if (!result.ContainsKey(value))
                        result.Add(value, null);
                }
            }
            return result;
        }
        public static void Run(CDSWebApiService svc, bool deleteCreatedRecords)
        {
            /*
             * Sample Goals
             * - Use ColumnSet to specify attributes
             * - Specify whether formatted values should be returned?
             * - Get a count of how many records are returned
             *
             * - Apply Conditions in a query https://docs.microsoft.com/en-us/powerapps/developer/common-data-service/org-service/use-conditionexpression-class
             * - Apply multiple conditions in a Filter Expression
             * - Page large result sets
             * - Page results with a cookie?
             * - Use a left outer join in QueryExpression to query for records "not in" https://docs.microsoft.com/en-us/powerapps/developer/common-data-service/org-service/use-left-outer-join-queryexpression-query-records-not-in
             * - Show how to use aggregates and grouping
             * - Send as $batch
             */

            Console.WriteLine("\n--Starting Query Data with Query Expression--");

            CreateRequiredRecords(svc);

            //Get the id and name of the account created to use as a filter.
            var    account1     = svc.Get($"{account1Uri}?$select=accountid,name");
            var    account1Id   = Guid.Parse(account1["accountid"].ToString());
            string account1Name = (string)account1["name"];

            //Header required to include formatted values
            var formattedValueHeaders = new Dictionary <string, List <string> > {
                { "Prefer", new List <string>
                  {
                      "odata.include-annotations=\"OData.Community.Display.V1.FormattedValue\""
                  } }
            };

            #region Use ColumnSet to specify attributes

            var query1 = new QueryExpression("contact")
            {
                ColumnSet = new ColumnSet("fullname", "jobtitle", "annualincome")
            };
            query1.Criteria.AddCondition("parentcustomerid", ConditionOperator.Equal, account1Id);

            var query1Results = svc.Get(
                $"contacts?queryExpression={query1.ToJSON()}",
                formattedValueHeaders);

            //Output results in formatted table
            WriteContactResultsTable(
                $"{((JContainer)query1Results["value"]).Count} Contacts related to the account '{account1Name}'",
                query1Results["value"]);

            #endregion Use ColumnSet to specify attributes

            #region Use PagingInfo
            //Re-use the previously defined query1
            query1.PageInfo = new PagingInfo()
            {
                PageNumber             = 1,
                Count                  = 4,
                ReturnTotalRecordCount = true
                                         //Bug 1686048: Unable to return count when using QueryExpression with Web API
            };

            var top4contactsRelatedToAccount1 = svc.Get(
                $"contacts?queryExpression={query1.ToJSON()}",
                formattedValueHeaders);

            //Output results in formatted table
            WriteContactResultsTable(
                $"Top 4 Contacts related to the account '{account1Name}'",
                top4contactsRelatedToAccount1["value"]);

            //Get next 4 contacts

            // You can't use the @odata.nextLink property
            // Bug 1686046: Error: 'The query parameter queryExpression is not supported' when using @odata.nextlink returned from Web API QueryExpression response
            //var next4contactsRelatedToAccount1 = svc.Get(
            //    top4contactsRelatedToAccount1["@odata.nextLink"].ToString(),
            //    formattedValueHeaders);

            //Update the PageNumber to get the next set of result
            query1.PageInfo.PageNumber = 2;

            var next4contactsRelatedToAccount1 = svc.Get(
                $"contacts?queryExpression={query1.ToJSON()}",
                formattedValueHeaders);

            //Output results in formatted table
            WriteContactResultsTable(
                $"Next 4 Contacts related to the account '{account1Name}'",
                next4contactsRelatedToAccount1["value"]);


            #endregion Use PagingInfo

            #region Apply multiple conditions in a Filter Expression

            var query2 = new QueryExpression("contact")
            {
                ColumnSet = new ColumnSet("fullname", "jobtitle", "annualincome")
            };
            //By default all criteria are evaluated using LogicalOperator.And
            query2.Criteria.AddCondition("parentcustomerid", ConditionOperator.Equal, account1Id);
            query2.Criteria.AddCondition("createdon", ConditionOperator.LastXHours, "1");

            var contactsRelatedToAccount1CreatedInLastHour = svc.Get(
                $"contacts?queryExpression={query2.ToJSON()}",
                formattedValueHeaders);

            //Output results in formatted table
            WriteContactResultsTable(
                $"Contacts created in the past hour related to '{account1Name}'",
                contactsRelatedToAccount1CreatedInLastHour["value"]);


            var query3 = new QueryExpression("contact")
            {
                ColumnSet = new ColumnSet("fullname", "jobtitle", "annualincome")
            };
            query3.Criteria.AddCondition("parentcustomerid", ConditionOperator.Equal, account1Id);
            query3.Criteria.AddCondition("annualincome", ConditionOperator.GreaterThan, "55000");
            FilterExpression childFilter = query3.Criteria.AddFilter(LogicalOperator.Or);
            childFilter.AddCondition("jobtitle", ConditionOperator.Like, "%senior%");
            childFilter.AddCondition("jobtitle", ConditionOperator.Like, "%manager%");

            var highValueContacts = svc.Get(
                $"contacts?queryExpression={query3.ToJSON()}",
                formattedValueHeaders);

            //Output results in formatted table
            WriteContactResultsTable(
                $"High salary contacts with 'senior' or 'manager' in job title:",
                highValueContacts["value"]);


            #endregion Apply multiple conditions in a Filter Expression

            #region Link Entities

            var query4 = new QueryExpression("task")
            {
                ColumnSet    = new ColumnSet("subject", "description"),
                LinkEntities =
                {
                    new LinkEntity()
                    {
                        Columns               = new ColumnSet("fullname"),
                        EntityAlias           = "c",
                        LinkFromAttributeName = "regardingobjectid",
                        LinkFromEntityName    = "task",
                        LinkToAttributeName   = "contactid",
                        LinkToEntityName      = "contact",
                        LinkCriteria          = new FilterExpression()
                        {
                            Conditions =
                            {
                                new ConditionExpression("parentcustomerid", ConditionOperator.Equal, account1Id)
                            }
                        }
                    }
                }
            };

            var tasksLinkedToContact = svc.Get(
                $"tasks?queryExpression={query4.ToJSON()}",
                formattedValueHeaders);

            //Output results in formatted table
            //Bug 1686153: Web API QueryExpression Link Entity response alias separator is '_x002e_' rather than '.'
            WriteTaskResultsTable("Tasks with linked Contacts", tasksLinkedToContact["value"], "c_x002e_fullname", "subject");

            var query4UsingFetchXml = $@"<fetch>
                <entity name='task' >
                <attribute name='description' />
                <attribute name='subject' />
                <link-entity name='contact' from='contactid' to='regardingobjectid' alias='c' >
                    <attribute name='fullname' />
                    <filter>
                    <condition attribute='parentcustomerid' operator='eq' value='{account1Id}' />
                    </filter>
                </link-entity>
                </entity>
            </fetch>";

            var tasksLinkedToContactFetch = svc.Get(
                $"tasks?fetchXml={WebUtility.UrlEncode(query4UsingFetchXml)}",
                formattedValueHeaders);

            //Output results in formatted table
            WriteTaskResultsTable(
                "Tasks with linked Contacts using FetchXMl",
                tasksLinkedToContactFetch["value"], "c.fullname", "subject");

            #endregion Link Entities

            #region Apply Aggregation and grouping

            #region Aggregate income data
            string avg_income_alias = "avg_income";
            string sum_income_alias = "sum_income";
            string max_income_alias = "max_income";
            string min_income_alias = "min_income";

            var query5 = new QueryExpression("contact")
            {
                ColumnSet = new ColumnSet("annualincome")
                {
                    AttributeExpressions =
                    {
                        new XrmAttributeExpression("annualincome", XrmAggregateType.Avg, avg_income_alias),
                        new XrmAttributeExpression("annualincome", XrmAggregateType.Sum, sum_income_alias),
                        new XrmAttributeExpression("annualincome", XrmAggregateType.Max, max_income_alias),
                        new XrmAttributeExpression("annualincome", XrmAggregateType.Min, min_income_alias)
                    }
                }
            };
            query5.Criteria.AddCondition("parentcustomerid", ConditionOperator.Equal, account1Id);

            var avgIncome = svc.Get(
                $"contacts?queryExpression={query5.ToJSON()}",
                formattedValueHeaders);

            var data = avgIncome["value"][0];

            string formattedSumIncome = (string)data
                                        [$"{sum_income_alias}@OData.Community.Display.V1.FormattedValue"];
            string formattedAvgIncome = (string)data
                                        [$"{avg_income_alias}@OData.Community.Display.V1.FormattedValue"];
            string formattedMaxIncome = (string)data
                                        [$"{max_income_alias}@OData.Community.Display.V1.FormattedValue"];
            string formattedMinIncome = (string)data
                                        [$"{min_income_alias}@OData.Community.Display.V1.FormattedValue"];


            Console.WriteLine($"\nIncome information for employees at'{account1Name}':");
            Console.WriteLine($"\tSum:\t{formattedSumIncome} ");
            Console.WriteLine($"\tAverage:{formattedAvgIncome} ");
            Console.WriteLine($"\tMax:\t{formattedMaxIncome} ");
            Console.WriteLine($"\tMin:\t{formattedMinIncome} ");
            #endregion Aggregate income data



            #endregion Apply Aggregation and grouping

            DeleteRequiredRecords(svc, deleteCreatedRecords);

            Console.WriteLine("\n--Query Data with Query Expression Completed--");
        }
        private void AddRelationFilter(ShuffleBlocks blocks, string entityName, DataBlockRelation relation, FilterExpression filter, ILoggable log)
        {
            log.StartSection(MethodBase.GetCurrentMethod().Name);
            if (blocks != null && blocks.Count > 0)
            {
                var block       = relation.Block;
                var attribute   = relation.Attribute;
                var pkattribute = relation.PKAttribute;
                var includenull = relation.IncludeNull;

                var type = GetAttributeType(attribute, entityName);

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

                var ids        = new List <object>();
                var parentcoll = blocks.ContainsKey(block) ? blocks[block] : null;
                if (parentcoll != null && parentcoll.Count > 0)
                {
                    foreach (var parent in parentcoll)
                    {
                        if (string.IsNullOrEmpty(pkattribute))
                        {
                            if (type == AttributeTypeCode.String)
                            {
                                ids.Add(parent.Id.ToString());
                            }
                            else
                            {
                                ids.Add(parent.Id);
                            }
                        }
                        else if (type == AttributeTypeCode.String)
                        {
                            ids.Add(parent.Property <EntityReference>(pkattribute, new EntityReference()).Id.ToString());
                        }
                        else
                        {
                            ids.Add(parent.Property <EntityReference>(pkattribute, new EntityReference()).Id);
                        }
                    }
                }
                else
                {
                    // Adding temp guid to indicate "no matches", as ConditionOperator.In will fail if no values are given
                    ids.Add(new Guid());
                }
                cond.Values.AddRange(ids);
                if (!includenull)
                {
                    filter.AddCondition(cond);
                }
                else
                {
                    var orfilter = new FilterExpression(LogicalOperator.Or);
                    orfilter.AddCondition(attribute, Microsoft.Xrm.Sdk.Query.ConditionOperator.Null);
                    orfilter.AddCondition(cond);
                    filter.AddFilter(orfilter);
                }
                log.Log("Adding relation condition for {0} in {1} values in {2}.{3}", attribute, ids.Count, block, pkattribute);
            }
            log.EndSection();
        }
示例#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");
            }
        }
示例#44
0
        /// <summary>
        /// Executes the plug-in.
        /// </summary>
        /// <param name="localContext">The <see cref="LocalPluginContext"/> which contains the
        /// <see cref="IPluginExecutionContext"/>,
        /// <see cref="IOrganizationService"/>
        /// and <see cref="ITracingService"/>
        /// </param>
        /// <remarks>
        /// For improved performance, Microsoft Dynamics CRM caches plug-in instances.
        /// The plug-in's Execute method should be written to be stateless as the constructor
        /// is not called for every invocation of the plug-in. Also, multiple system threads
        /// could execute the plug-in at the same time. All per invocation state information
        /// is stored in the context. This means that you should not use global variables in plug-ins.
        /// </remarks>
        protected void ExecuteVATUpdater(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }

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

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

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

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

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

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

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

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

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

                EntityCollection quotedetails = service.RetrieveMultiple(query);

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

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

                    service.Update(detail);

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

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

                service.Update(quote);
            }
        }
示例#45
0
 public IEnumerable<Entity> RetrieveAllOrClauses(string entityName, IEnumerable<ConditionExpression> orConditions,
     IEnumerable<string> fields)
 {
     var filters = orConditions
         .Select(c =>
         {
             var f = new FilterExpression();
             f.AddCondition(c);
             return f;
         }
         );
     return RetrieveAllOrClauses(entityName, filters, fields);
 }
        /// <summary>
        /// This sample demonstrates how to audit user access to Microsoft Dynamics CRM.
        /// The sample first enables user access auditing on an organization. Next, it
        /// creates and modifies an entity. Finally, the sample displays a report of the
        /// audited information.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            _sampleStartTime = DateTime.Now;
            using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
            {
                // This statement is required to enable early-bound type support.
                _serviceProxy.EnableProxyTypes();

                #region Enable Auditing

                // Enable auditing on the organization and for user access by editing the
                // organization's settings.
                // First, get the organization's ID from the system user record.
                var  whoAmIReq = new WhoAmIRequest();
                var  whoAmIRes = (WhoAmIResponse)_serviceProxy.Execute(whoAmIReq);
                Guid orgId     = whoAmIRes.OrganizationId;
                _systemUserId = whoAmIRes.UserId;

                // Next, retrieve the organization's record.
                var org = (Organization)_serviceProxy.Retrieve(
                    Organization.EntityLogicalName, orgId,
                    new ColumnSet("organizationid", "isauditenabled", "isuseraccessauditenabled", "useraccessauditinginterval"));

                // Finally, enable auditing on the organization, including auditing for
                // user access.
                bool organizationAuditingFlag = org.IsAuditEnabled.Value;
                bool userAccessAuditingFlag   = org.IsUserAccessAuditEnabled.Value;
                if (!organizationAuditingFlag || !userAccessAuditingFlag)
                {
                    org.IsAuditEnabled           = true;
                    org.IsUserAccessAuditEnabled = true;
                    _serviceProxy.Update(org);
                    Console.WriteLine("Enabled auditing for the organization and for user access.");
                    Console.WriteLine("Auditing interval is set to {0} hours.", org.UserAccessAuditingInterval);
                }
                else
                {
                    Console.WriteLine("Auditing was enabled before the sample began, so no auditing settings were changed.");
                }

                // Enable auditing on the account entity, since no audits will be created
                // when we create/update an account entity, otherwise.
                var oldAccountAuditing = EnableEntityAuditing(Account.EntityLogicalName, true);

                #endregion Enable Auditing

                #region Make Audited Service Calls

                CreateRequiredRecords();

                // Make an update request to the Account entity to be tracked by auditing.
                var newAccount = new Account();
                newAccount.AccountId           = _newAccountId;
                newAccount.AccountNumber       = "1-A";
                newAccount.AccountCategoryCode = new OptionSetValue(
                    (int)AccountAccountCategoryCode.PreferredCustomer);
                newAccount.Telephone1 = "555-555-5555";

                _serviceProxy.Update(newAccount);

                Console.WriteLine("Created an account and made updates which should be captured by auditing.");

                #endregion Make Audited Service Calls

                #region Revert auditing

                // Set the organization and account auditing flags back to the old values
                if (!organizationAuditingFlag || !userAccessAuditingFlag)
                {
                    // Only revert them if they were actually changed to begin with.
                    org.IsAuditEnabled           = organizationAuditingFlag;
                    org.IsUserAccessAuditEnabled = userAccessAuditingFlag;
                    _serviceProxy.Update(org);
                    Console.WriteLine("Reverted organization and user access auditing to their previous values.");
                }
                else
                {
                    Console.WriteLine("Auditing was enabled before the sample began, so no auditing settings were reverted.");
                }

                // Revert the account entity auditing.
                EnableEntityAuditing(Account.EntityLogicalName, oldAccountAuditing);

                #endregion Revert auditing

                #region Show Audited Records

                // Select all columns for convenience.
                var query = new QueryExpression(Audit.EntityLogicalName)
                {
                    ColumnSet = new ColumnSet(true),
                    Criteria  = new FilterExpression(LogicalOperator.And)
                };

                // Only retrieve audit records that track user access.
                query.Criteria.AddCondition("action", ConditionOperator.In,
                                            (int)AuditAction.UserAccessAuditStarted,
                                            (int)AuditAction.UserAccessAuditStopped,
                                            (int)AuditAction.UserAccessviaWebServices,
                                            (int)AuditAction.UserAccessviaWeb);

                // Change this to false in order to retrieve audit records for all users
                // when running the sample.
                var filterAuditsRetrievedByUser = true;
                if (filterAuditsRetrievedByUser)
                {
                    // Only retrieve audit records for the current user or the "SYSTEM"
                    // user.
                    var userFilter = new FilterExpression(LogicalOperator.Or);
                    userFilter.AddCondition(
                        "userid", ConditionOperator.Equal, _systemUserId);
                    userFilter.AddCondition(
                        "useridname", ConditionOperator.Equal, "SYSTEM");
                }
                // Only retrieve records for this sample run, so that we don't get too
                // many results if auditing was enabled previously.
                query.Criteria.AddCondition(
                    "createdon", ConditionOperator.GreaterEqual, _sampleStartTime);

                var results = _serviceProxy.RetrieveMultiple(query);
                Console.WriteLine("Retrieved audit records:");
                foreach (Audit audit in results.Entities)
                {
                    Console.Write("\r\n  Action: {0},  User: {1},"
                                  + "\r\n    Created On: {2}, Operation: {3}",
                                  (AuditAction)audit.Action.Value,
                                  audit.UserId.Name,
                                  audit.CreatedOn.Value.ToLocalTime(),
                                  (AuditOperation)audit.Operation.Value);

                    // Display the name of the related object (which will be the user
                    // for audit records with Action UserAccessviaWebServices.
                    if (!String.IsNullOrEmpty(audit.ObjectId.Name))
                    {
                        Console.WriteLine(
                            ",\r\n    Related Record: {0}", audit.ObjectId.Name);
                    }
                    else
                    {
                        Console.WriteLine();
                    }
                }

                #endregion Show Audited Records

                DeleteRequiredRecords(promptforDelete);
            }
        }
        public Int32 GetSearchList(IOrganizationService _Service, String sSearchString, String sEntity, String sNameAttribute, String sIDAttribute)
        {
            Int32 rV = 0;

            this.Cursor = Cursors.Wait;

            btnAccept.IsEnabled = false;
            btnClose.IsEnabled  = false;

            if (_Service != null)
            {
                if (sSearchString.IndexOf("%") == -1)
                {
                    sSearchString = "%" + sSearchString + "%";
                }

                FilterExpression    filterExpression = new FilterExpression();
                ConditionExpression condition        = new ConditionExpression(sNameAttribute, ConditionOperator.Like, sSearchString);
                ConditionExpression condition2       = new ConditionExpression("isdisabled", ConditionOperator.Equal, "false");

                filterExpression.FilterOperator = LogicalOperator.And;

                if (sEntity == SystemUser.EntityLogicalName)
                {
                    filterExpression.AddCondition(condition);
                    filterExpression.AddCondition(condition2);
                }
                else
                {
                    filterExpression.AddCondition(condition);
                }

                QueryExpression query = new QueryExpression()
                {
                    EntityName = sEntity,
                    ColumnSet  = new ColumnSet(new String[] { sNameAttribute, sIDAttribute }),
                    Criteria   = filterExpression,
                    Distinct   = false,
                    NoLock     = true
                };

                RetrieveMultipleRequest multipleRequest = new RetrieveMultipleRequest();
                multipleRequest.Query = query;

                _SearchResult.Rows.Clear();

                RetrieveMultipleResponse response = (RetrieveMultipleResponse)_Service.Execute(multipleRequest);

                foreach (Entity _e in response.EntityCollection.Entities)
                {
                    rV++;

                    if (_e.Attributes[sNameAttribute] != null && _e.Attributes[sIDAttribute] != null)
                    {
                        DataRow _dr = null;
                        if ((_dr = _SearchResult.NewRow()) != null)
                        {
                            _dr["id"]   = _e.Attributes[sIDAttribute].ToString();
                            _dr["name"] = _e.Attributes[sNameAttribute].ToString();
                            _SearchResult.Rows.Add(_dr);
                        }
                    }
                }

                SearchGrid.RefreshData();
            }

            btnAccept.IsEnabled = true;
            btnClose.IsEnabled  = true;

            this.Cursor = Cursors.Arrow;

            return(rV);
        }
示例#48
0
        private EntityCollection RetrievePastOrder(Guid customerId, IOrganizationService service)
        {
            try
            {
                QueryExpression orderQuery = new QueryExpression();
                orderQuery.EntityName = Constant.Order.EntityName;

                orderQuery.ColumnSet.AddColumn(Constant.Order.CustomerId);
                orderQuery.ColumnSet.AddColumn(Constant.Order.Type);
                orderQuery.ColumnSet.AddColumn(Constant.Order.OrderDate);
                //orderQuery.ColumnSet.AddColumn(Constant.Order.DispatchedLocked);
                orderQuery.ColumnSet.AddColumn(Constant.Order.OrderLocked);

                ConditionExpression customerIdCondition = new ConditionExpression();
                customerIdCondition.AttributeName = Constant.Order.CustomerId;
                customerIdCondition.Operator      = ConditionOperator.Equal;
                customerIdCondition.Values.Add(customerId);

                ConditionExpression typeCondition = new ConditionExpression();
                typeCondition.AttributeName = Constant.Order.Type;
                typeCondition.Operator      = ConditionOperator.Equal;
                typeCondition.Values.Add(Constant.Order.TypeValue.Standard);

                ConditionExpression statusCondition = new ConditionExpression();
                statusCondition.AttributeName = Constant.Order.Status;
                statusCondition.Operator      = ConditionOperator.Equal;
                statusCondition.Values.Add(Constant.Order.StatusValue.Open);

                ConditionExpression orderDeleteFlagCondition = new ConditionExpression();
                orderDeleteFlagCondition.AttributeName = Constant.Order.OrderDeleteFlag;
                orderDeleteFlagCondition.Operator      = ConditionOperator.Equal;
                orderDeleteFlagCondition.Values.Add(false);

                ConditionExpression orderLockedCondition = new ConditionExpression();
                orderLockedCondition.AttributeName = Constant.Order.OrderLocked;
                orderLockedCondition.Operator      = ConditionOperator.Equal;
                orderLockedCondition.Values.Add(false);

                ConditionExpression orderDateCondition = new ConditionExpression();
                orderDateCondition.AttributeName = Constant.Order.OrderDate;
                orderDateCondition.Operator      = ConditionOperator.OnOrAfter;
                orderDateCondition.Values.Add(DateTime.Now.AddDays(1));

                ConditionExpression businessSegmentCondition = new ConditionExpression();
                businessSegmentCondition.AttributeName = Constant.Order.BusinessSegment;
                businessSegmentCondition.Operator      = ConditionOperator.Equal;
                businessSegmentCondition.Values.Add(Constant.Order.BusinessSegmentValue);

                FilterExpression orderFilter1 = new FilterExpression();
                orderFilter1.AddCondition(customerIdCondition);
                orderFilter1.AddCondition(typeCondition);
                orderFilter1.AddCondition(statusCondition);
                orderFilter1.AddCondition(orderDeleteFlagCondition);
                orderFilter1.FilterOperator = LogicalOperator.And;

                FilterExpression orderFilter2_1 = new FilterExpression();
                orderFilter2_1.AddCondition(orderLockedCondition);
                orderFilter2_1.AddCondition(orderDateCondition);
                orderFilter2_1.FilterOperator = LogicalOperator.Or;

                FilterExpression orderFilter2_2 = new FilterExpression();
                //orderFilter2_2.AddCondition(businessSegmentCondition);
                orderFilter2_2.FilterOperator = LogicalOperator.And;

                FilterExpression orderFilter2 = new FilterExpression();
                orderFilter2.AddFilter(orderFilter2_1);
                orderFilter2.AddFilter(orderFilter2_2);
                orderFilter2.FilterOperator = LogicalOperator.And;

                FilterExpression orderFilter3 = new FilterExpression();
                orderFilter3.AddCondition(orderLockedCondition);
                //orderFilter3.AddCondition(businessSegmentCondition);
                orderFilter3.FilterOperator = LogicalOperator.And;

                FilterExpression orderFilter = new FilterExpression();
                orderFilter.AddFilter(orderFilter1);
                orderFilter.AddFilter(orderFilter2);
                orderFilter.AddFilter(orderFilter3);

                orderQuery.Criteria = orderFilter;
                orderQuery.AddOrder(Constant.Order.CreatedOn, OrderType.Descending);

                EntityCollection orderCollection = service.RetrieveMultiple(orderQuery);

                return(orderCollection);
            }

            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// This method first connects to the organization service. Afterwards,
        /// auditing is enabled on the organization, account entity, and a couple
        /// of attributes. Finally, display that information in Console, and creates
        /// an XML file.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            _sampleStartTime = DateTime.Now;
            using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
            {
                // This statement is required to enable early-bound type support.
                _serviceProxy.EnableProxyTypes();

                // You can access the service through the proxy, but this sample uses the interface instead.
                _service = _serviceProxy;

                #region Enable Auditing for an Account

                Console.WriteLine("Enabling auditing on the organization and account entities.");

                // Enable auditing on the organization.
                // First, get the organization's ID from the system user record.
                Guid orgId = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).OrganizationId;

                // Next, retrieve the organization's record.
                Organization org = _service.Retrieve(Organization.EntityLogicalName, orgId,
                                                     new ColumnSet(new string[] { "organizationid", "isauditenabled" })) as Organization;

                // Finally, enable auditing on the organization.
                bool organizationAuditingFlag = org.IsAuditEnabled.Value;
                bool usersAccessAuditingFlag  = org.IsUserAccessAuditEnabled.HasValue ?
                                                org.IsUserAccessAuditEnabled.Value : false;

                org.IsAuditEnabled           = true;
                org.IsUserAccessAuditEnabled = true;
                _service.Update(org);

                // Enable auditing on account entities.
                bool accountAuditingFlag = EnableEntityAuditing(Account.EntityLogicalName, true);

                #endregion Enable Auditing for an Account

                CreateRequiredRecords();

                #region Create and start XML file

                // Create the XML file
                String fileName = "auditReport.xml";
                textWriter = new XmlTextWriter(fileName, null);
                textWriter.WriteStartDocument();

                // Start Audit Node
                textWriter.WriteStartElement("auditReport", "");

                #endregion

                #region Retrive user access audit records

                var query = new QueryExpression(Audit.EntityLogicalName)
                {
                    ColumnSet = new ColumnSet("createdon", "action", "operation", "objectid"),
                    Criteria  = new FilterExpression(LogicalOperator.And)
                };

                // Only retrieve audit records that track user access.
                query.Criteria.AddCondition("action", ConditionOperator.In,
                                            (int)AuditAction.UserAccessAuditStarted,
                                            (int)AuditAction.UserAccessAuditStopped,
                                            (int)AuditAction.UserAccessviaWebServices,
                                            (int)AuditAction.UserAccessviaWeb);

                // Change this to false in order to retrieve audit records for all users
                // when running the sample.
                var filterAuditsRetrievedByUser = true;
                if (filterAuditsRetrievedByUser)
                {
                    // Only retrieve audit records for the current user.
                    var userFilter = new FilterExpression(LogicalOperator.Or);
                    userFilter.AddCondition(
                        "userid", ConditionOperator.Equal, _serviceProxy.CallerId);
                }
                // Only retrieve records for this sample run, so that we don't get too
                // many results if auditing was enabled previously.
                query.Criteria.AddCondition(
                    "createdon", ConditionOperator.GreaterEqual, _sampleStartTime);

                var results = _serviceProxy.RetrieveMultiple(query);
                foreach (Audit audit in results.Entities)
                {
                    // Display results
                    DisplayAndAddToXMLFileUserAccessDetails(audit);
                }

                #endregion

                #region Retrieve the Audit History
                Console.WriteLine("Retrieving the account change history.\n");

                DateTime startTime = DateTime.Now;

                // Retrieve the audit records for accounts.
                RetrieveRecordChangeHistoryRequest changeRequest = new RetrieveRecordChangeHistoryRequest();
                changeRequest.Target = new EntityReference(Account.EntityLogicalName, _newAccountId);

                RetrieveRecordChangeHistoryResponse changeResponse =
                    (RetrieveRecordChangeHistoryResponse)_service.Execute(changeRequest);

                AuditDetailCollection details = changeResponse.AuditDetailCollection;

                foreach (AttributeAuditDetail detail in details.AuditDetails)
                {
                    // Write out some of the information in each audit record.
                    DisplayAndAddToXMLFileAuditDetails(detail);
                }
                #endregion Retrieve the Audit History

                #region RetrieveAttributeChangeHistoryRequest
                // How to use message: RetrieveAttributeChangeHistoryRequest

                // Update Telephone1 in account entity
                Account accountToUpdate = new Account();
                accountToUpdate.AccountId  = _newAccountId;
                accountToUpdate.Telephone1 = "123-555-5555";
                _serviceProxy.Update(accountToUpdate);
                Console.WriteLine("Updated Telephone1 field in Account entity.");

                Console.WriteLine("Retrieving attribute change history for Telephone1.");
                // Create RetrieveAttributeChangeHistoryRequest
                var attributeChangeHistoryRequest = new RetrieveAttributeChangeHistoryRequest
                {
                    Target = new EntityReference(
                        Account.EntityLogicalName, _newAccountId),
                    AttributeLogicalName = "telephone1"
                };

                // Execute RetrieveAttributeChangeHistoryRequest
                var attributeChangeHistoryResponse =
                    (RetrieveAttributeChangeHistoryResponse)_service.Execute(attributeChangeHistoryRequest);

                // Set AuditDetailCollection and output to console
                details = attributeChangeHistoryResponse.AuditDetailCollection;

                foreach (var detail in details.AuditDetails)
                {
                    DisplayAndAddToXMLFileAuditDetails(detail);
                }

                // Create an Audit record
                // to store a sample for use with RetrieveAuditDetailsRequest
                Guid auditSampleId = details.AuditDetails.First().AuditRecord.Id;
                #endregion RetrieveAttributeChangeHistoryRequest

                #region RetrieveAuditDetailsRequest
                // How to use message: RetrieveAuditDetailsRequest

                Console.WriteLine("Retrieving audit details for an audit record.");
                // Create RetrieveAuditDetailsRequest
                var auditDetailsRequest = new RetrieveAuditDetailsRequest
                {
                    AuditId = auditSampleId
                };

                // Execute RetrieveAuditDetailsRequest
                var auditDetailsResponse =
                    (RetrieveAuditDetailsResponse)_service.Execute(auditDetailsRequest);

                // Display results
                DisplayAndAddToXMLFileAuditDetails(auditDetailsResponse.AuditDetail);

                #endregion RetrieveAuditDetailsRequest

                #region Retrieve AuditExtension details

                Console.WriteLine("Simulating a user reading records");
                _service.Retrieve(Account.EntityLogicalName, _newAccountId, new ColumnSet("accountid"));

                // creating read records is an async process - wait until the records have been created
                // wait a max of 30 seconds
                Console.WriteLine("Fetching read audit records for accounts");
                for (int i = 0; i < 30; i++)
                {
                    query = new QueryExpression
                    {
                        EntityName = "sample_auditextension",
                        ColumnSet  = new ColumnSet("createdon", "sample_objectlogicalname",
                                                   "sample_objectid", "sample_userid", "sample_action", "sample_operation"),
                        Criteria = new FilterExpression
                        {
                            Conditions =
                            {
                                new ConditionExpression("sample_objectlogicalname", ConditionOperator.Equal, Account.EntityLogicalName),
                                new ConditionExpression("sample_objectid",          ConditionOperator.Equal,
                                                        _newAccountId.ToString().TrimStart('{').TrimEnd('}'))
                            }
                        }
                    };
                    results = _service.RetrieveMultiple(query);
                    if (results.Entities.Count > 0)
                    {
                        break;
                    }
                    else if (i == 29)
                    {
                        throw new Exception("Exceeded maximum wait time");
                    }
                    System.Threading.Thread.Sleep(1000);
                }

                foreach (var record in results.Entities)
                {
                    _auditExtensionRecordIds.Add(record.Id);
                    DisplayAndAddToXmlFileAuditExtension(record);
                }

                #endregion

                #region Finish and close XML file

                // End auditReport Xml Node
                textWriter.WriteEndElement();
                textWriter.WriteEndDocument();

                // Close xml writer.
                textWriter.Close();

                Console.WriteLine("File name: " + fileName);

                #endregion

                #region Revert auditing
                // Set the organization and account auditing flags back to the old values
                org.IsAuditEnabled           = organizationAuditingFlag;
                org.IsUserAccessAuditEnabled = usersAccessAuditingFlag;
                _service.Update(org);

                EnableEntityAuditing(Account.EntityLogicalName, accountAuditingFlag);

                #endregion Revert auditing

                DeleteRequiredRecords(promptforDelete);
            }
        }
        private void loadViews()
        {
            WorkAsync(new WorkAsyncInfo
            {
                Message = string.Format("Retrieving Views for {0}...", cmbEntities.SelectedItem.ToString()),
                Work    = (w, e) =>
                {
                    #region Reset Variables

                    ExecutionRecordSet.Entities.Clear();
                    views.Entities.Clear();

                    this.Invoke((MethodInvoker) delegate()
                    {
                        lstViews.Items.Clear();
                        radFetchXML.Checked = false;
                        radViews.Checked    = true;
                        tsbCount.Enabled    = false;
                        tsbExecute.Enabled  = false;
                        txtRecordCount.Clear();
                        rtxtFetchXML.Clear();
                    });

                    #endregion Reset Variables

                    #region System Views Loop
                    string selectedEntity = "";
                    this.Invoke((MethodInvoker) delegate()
                    {
                        selectedEntity = cmbEntities.SelectedItem.ToString();
                    });

                    QueryExpression query      = new QueryExpression("savedquery");
                    query.ColumnSet.AllColumns = true;
                    query.AddOrder("name", OrderType.Ascending);
                    query.Criteria = new FilterExpression();
                    //query.Criteria.AddCondition("returnedtypecode", ConditionOperator.Equal, workflowEntity);

                    FilterExpression childFilter = query.Criteria.AddFilter(LogicalOperator.And);
                    childFilter.AddCondition("querytype", ConditionOperator.Equal, 0);
                    childFilter.AddCondition("returnedtypecode", ConditionOperator.Equal, EntityNameMap[selectedEntity]);
                    childFilter.AddCondition("statecode", ConditionOperator.Equal, 0);
                    childFilter.AddCondition("fetchxml", ConditionOperator.NotNull);

                    EntityCollection _ManagedViews = Service.RetrieveMultiple(query);
                    views.Entities.AddRange(_ManagedViews.Entities);

                    foreach (var item in _ManagedViews.Entities)
                    {
                        this.Invoke((MethodInvoker) delegate()
                        {
                            lstViews.Items.Add(item["name"]);
                        });
                    }
                    #endregion System Views Loop

                    #region Personal View Divider

                    this.Invoke((MethodInvoker) delegate()
                    {
                        lstViews.Items.Add("----------------------- Personal Views ----------------------------");
                    });

                    Entity _dummyView  = new Entity("userquery");
                    _dummyView.Id      = Guid.NewGuid();
                    _dummyView["name"] = "Dummy View";

                    views.Entities.Add(_dummyView);

                    #endregion Personal View Divider

                    #region Personal Views Loop
                    QueryExpression query2      = new QueryExpression("userquery");
                    query2.ColumnSet.AllColumns = true;
                    query.AddOrder("name", OrderType.Ascending);
                    query2.Criteria = new FilterExpression();
                    //query.Criteria.AddCondition("ismanaged", ConditionOperator.Equal, true);

                    FilterExpression childFilter2 = query2.Criteria.AddFilter(LogicalOperator.And);
                    childFilter2.AddCondition("querytype", ConditionOperator.Equal, 0);
                    childFilter2.AddCondition("returnedtypecode", ConditionOperator.Equal, EntityNameMap[selectedEntity]);
                    childFilter2.AddCondition("statecode", ConditionOperator.Equal, 0);
                    childFilter2.AddCondition("fetchxml", ConditionOperator.NotNull);

                    EntityCollection _UserViews = Service.RetrieveMultiple(query2);
                    views.Entities.AddRange(_UserViews.Entities);

                    foreach (var item in _UserViews.Entities)
                    {
                        this.Invoke((MethodInvoker) delegate()
                        {
                            lstViews.Items.Add(item["name"]);
                        });
                    }
                    #endregion Personal Views Loop

                    e.Result = views;
                },
                ProgressChanged = e =>
                {
                    // If progress has to be notified to user, use the following method:
                    SetWorkingMessage("Views retrieved!");
                },
                PostWorkCallBack = e =>
                {
                },
                AsyncArgument = null,
                IsCancelable  = true,
                MessageWidth  = 340,
                MessageHeight = 150
            });
        }
示例#51
0
        public void Experiment_For_Filter_Groups()
        {
            // var sql = string.Format("Select C.firstname, C.lastname From contact Where firstname Like '%ax%' ");

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

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

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

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

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

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

            }
        }
示例#52
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 ExecuteSalesOrderVat(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      orderID = (Guid)((Entity)context.InputParameters["Target"]).Id;
            ColumnSet set     = new ColumnSet();

            set.AllColumns = true;
            var order = service.Retrieve("salesorder", orderID, set);


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

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

                ConditionExpression condition = new ConditionExpression();
                condition.AttributeName = "salesorderid";
                condition.Operator      = ConditionOperator.Equal;
                condition.Values.Add(orderID);

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

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

                EntityCollection orderdetails = service.RetrieveMultiple(query);

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

                    if (isLocked)
                    {
                        //It is really important to unlock both the Invoice and the Order!
                        UnlockSalesOrderPricingRequest unlockRequest = new UnlockSalesOrderPricingRequest();
                        unlockRequest.SalesOrderId = ((EntityReference)detail.Attributes["salesorderid"]).Id;
                        UnlockSalesOrderPricingResponse unlockRequestResponse = (UnlockSalesOrderPricingResponse)service.Execute(unlockRequest);
                    }

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

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

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

                    service.Update(detail);
                }

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

                service.Update(order);
            }
        }
示例#53
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate the method to create any data that this sample requires.
        /// Delete a new queue instance.
        /// Optionally delete any entity records that were created for this sample.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Call the method to create any data that this sample requires.
                    CreateRequiredRecords();

                    #region Run a QC with marketing list as input

                    //<snippetQuickCampaign1>

                    List newList = new List()
                    {
                        ListName        = "TestList",
                        CreatedFromCode = new OptionSetValue((int)ListCreatedFromCode.Account)
                    };

                    _newListId = _serviceProxy.Create(newList);

                    for (int j = 0; j < 5; j++)
                    {
                        AddMemberListRequest addMemberListRequest = new AddMemberListRequest();
                        addMemberListRequest.EntityId = _accountIdArray[j];
                        addMemberListRequest.ListId   = _newListId;
                        AddMemberListResponse addMemberListResponse =
                            _serviceProxy.Execute(addMemberListRequest) as AddMemberListResponse;
                    }

                    Guid BOId = CreateAndRetrieveQuickCampaignForMarketingList(
                        _templateLetterActivity,
                        _newListId,
                        PropagationOwnershipOptions.ListMemberOwner,
                        true);

                    //</snippetQuickCampaign1>

                    #endregion

                    #region Run a QC with a list of accounts as input

                    // Construct a Query Expression(QE) which specifies which records QC should include
                    QueryExpression query = new QueryExpression("account");
                    query.ColumnSet = new ColumnSet("accountid");
                    query.Criteria  = new FilterExpression();
                    FilterExpression filter = query.Criteria.AddFilter(LogicalOperator.Or);
                    for (int j = 0; j < 5; j++)
                    {
                        filter.AddCondition("accountid", ConditionOperator.Equal, _accountIdArray[j]);
                    }
                    _qcBOId = CreateAndRetrieveQuickCampaignForQueryExpression(
                        _templateEmailActivity,
                        query,
                        PropagationOwnershipOptions.ListMemberOwner,
                        true);

                    #endregion

                    DeleteRequiredRecords(promptforDelete);
                }
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
        private void FillRequestList()
        {
            #region Create Table
            DataTable dtb = new DataTable();
            dtb.Columns.Add("ticketnumber");
            dtb.Columns.Add("title");
            dtb.Columns.Add("casetypecode");
            dtb.Columns.Add("description");
            dtb.Columns.Add("statecode");
            dtb.Columns.Add("state");
            dtb.Columns.Add("incidentid");
            dtb.Columns.Add("helpdesk_requesterconfirm");
            dtb.Columns.Add("helpdesk_statusdescription");
            #endregion

            #region Get Record From Crm
            QueryExpression query = new QueryExpression("incident");
            query.ColumnSet = new ColumnSet(true);
            OrderExpression _Order = new OrderExpression("createdon", OrderType.Descending);
            query.Orders.Add(_Order);
            FilterExpression _filterCustomer = new FilterExpression(LogicalOperator.And);
            _filterCustomer.AddCondition("customerid", ConditionOperator.Equal, new Guid("{" + Session["Personnelid"].ToString() + "}"));

            query.Criteria = new FilterExpression(LogicalOperator.And);
            query.Criteria.AddFilter(_filterCustomer);

            if (SelectType.SelectedValue.Trim() == "2" || SelectType.SelectedValue.Trim() == "3")
            {
                FilterExpression _filterState = new FilterExpression();
                if (SelectType.SelectedValue.Trim() == "2")
                {
                    _filterState.FilterOperator = LogicalOperator.And;
                    _filterState.AddCondition("statecode", ConditionOperator.Equal, 0);
                }
                else if (SelectType.SelectedValue.Trim() == "3")
                {
                    _filterState.FilterOperator = LogicalOperator.Or;
                    _filterState.AddCondition("statecode", ConditionOperator.Equal, 1);
                    _filterState.AddCondition("statecode", ConditionOperator.Equal, 2);
                }
                query.Criteria.AddFilter(_filterState);
            }
            EntityCollection retrieved = crmService.RetrieveMultiple(query);
            #endregion

            #region Fill DataTable
            if (retrieved != null && retrieved.Entities.Count > 0)
            {
                for (int i = 0; i < retrieved.Entities.Count; i++)
                {
                    DataRow dr = dtb.NewRow();
                    dr["ticketnumber"] = retrieved.Entities[i].Attributes["ticketnumber"].ToString();
                    if (retrieved.Entities[i].Contains("helpdesk_requesterconfirm") && retrieved.Entities[i].Attributes["helpdesk_requesterconfirm"] != null)
                        dr["helpdesk_requesterconfirm"] = retrieved.Entities[i].Attributes["helpdesk_requesterconfirm"].ToString();
                    else
                        dr["helpdesk_requesterconfirm"] = false;
                    if (retrieved.Entities[i].Attributes.Contains("title"))
                        dr["title"] = retrieved.Entities[i].Attributes["title"].ToString();

                    int CaseType = 0;
                    if (retrieved.Entities[i].Attributes.Contains("casetypecode"))
                    {
                        CaseType = ((OptionSetValue)retrieved.Entities[i].Attributes["casetypecode"]).Value;
                    }
                    dr["casetypecode"] = GetOptionsSetTextOnValue(crmService, "incident", "casetypecode", CaseType, 1065);
                    if (retrieved.Entities[i].Attributes.Contains("description"))
                        dr["description"] = retrieved.Entities[i].Attributes["description"].ToString();
                    if (((OptionSetValue)retrieved.Entities[i].Attributes["statecode"]).Value == 0)
                    {
                        dr["statecode"] = getStatuscode(((OptionSetValue)retrieved.Entities[i].Attributes["statuscode"]).Value);
                        dr["state"] = 0;
                    }
                    else
                    {
                        dr["statecode"] = GetStateTextOnValue(crmService, "incident", "statecode", ((OptionSetValue)retrieved.Entities[i].Attributes["statecode"]).Value, 1065);
                        dr["state"] = ((OptionSetValue)retrieved.Entities[i].Attributes["statecode"]).Value;
                    }
                    dr["incidentid"] = retrieved.Entities[i].Attributes["incidentid"].ToString();
                    if (retrieved.Entities[i].Contains("helpdesk_statusdescription") && retrieved.Entities[i].Attributes["helpdesk_statusdescription"] != null)
                        dr["helpdesk_statusdescription"] = getStatusDesccode(((OptionSetValue)retrieved.Entities[i].Attributes["helpdesk_statusdescription"]).Value);
                    if (((OptionSetValue)retrieved.Entities[i].Attributes["statecode"]).Value == 1)
                        dr["helpdesk_statusdescription"] = getStatusDesccode(3);
                    dtb.Rows.Add(dr);
                }
            }
            #endregion

            RequestView.DataSource = dtb;
            RequestView.DataBind();
        }
示例#55
0
        internal void AddRelatedEntities(Entity entity, RelationshipQueryCollection relatedEntityQuery,
                                         EntityReference userRef)
        {
            foreach (var relQuery in relatedEntityQuery)
            {
                var relationship = relQuery.Key;
                if (!(relQuery.Value is QueryExpression queryExpr))
                {
                    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);
                }
            }
        }
示例#56
0
        public EntityCollection GetVesselJobAsDestination(IOrganizationService service, EntityReference vessel, Entity jobEnt, Entity intakeEnt, ITracingService tracingService)
        {
            /*var query = new QueryExpression("dia_jobdestinationvessel");
             * query.ColumnSet.AddColumns("dia_vessel", "dia_quantity");
             * query.Criteria.AddCondition("dia_vessel", ConditionOperator.Equal, vessel.Id);
             * query.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0);
             * query.Criteria.AddCondition("dia_vessel", ConditionOperator.Equal, vessel.Id);
             * var query_dia_job = query.AddLink("dia_job", "dia_job", "dia_jobid");
             * query_dia_job.EntityAlias = "Job";
             * query_dia_job.Columns.AddColumns("dia_type");
             * query_dia_job.LinkCriteria.FilterOperator = LogicalOperator.Or;
             * query_dia_job.LinkCriteria.AddCondition("dia_type", ConditionOperator.Equal, 914440003);
             * query_dia_job.LinkCriteria.AddCondition("dia_type", ConditionOperator.Equal, 914440001);
             * //query_dia_job.LinkCriteria.AddCondition("statuscode", ConditionOperator.Equal, 914440001);
             * var query_dia_job_LinkCriteria_0 = new FilterExpression();
             * query_dia_job.LinkCriteria.AddFilter(query_dia_job_LinkCriteria_0);
             * // Define filter query_dia_job_LinkCriteria_0
             * //query_dia_job_LinkCriteria_0.AddCondition("statuscode", ConditionOperator.Equal, 914440000);
             * query_dia_job_LinkCriteria_0.AddCondition("dia_schelduledstart", ConditionOperator.LessEqual, jobEnt.GetAttributeValue<DateTime>("dia_schelduledstart"));
             */



            var query = new QueryExpression("dia_jobdestinationvessel");

            query.ColumnSet.AddColumns("dia_vessel", "dia_quantity");
            query.Criteria.AddCondition("dia_vessel", ConditionOperator.Equal, vessel.Id);
            query.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0);

            var query_dia_job = query.AddLink("dia_job", "dia_job", "dia_jobid");

            query_dia_job.Columns.AddColumns("dia_type");
            query_dia_job.LinkCriteria.FilterOperator = LogicalOperator.Or;
            query_dia_job.LinkCriteria.AddCondition("dia_type", ConditionOperator.Equal, 914440003);
            query_dia_job.LinkCriteria.AddCondition("dia_type", ConditionOperator.Equal, 914440001);

            if (jobEnt != null && jobEnt.GetAttributeValue <DateTime>("dia_schelduledstart") != DateTime.MinValue)
            {
                tracingService.Trace("jobent date: " + jobEnt.GetAttributeValue <DateTime>("dia_schelduledstart"));
                var query_dia_job_LinkCriteria_1 = new FilterExpression();
                query_dia_job.LinkCriteria.AddFilter(query_dia_job_LinkCriteria_1);
                query_dia_job_LinkCriteria_1.AddCondition("dia_schelduledstart", ConditionOperator.LessEqual, jobEnt.GetAttributeValue <DateTime>("dia_schelduledstart"));
            }

            var query_dia_intakebookings = query.AddLink("dia_intakebookings", "dia_intakebooking", "dia_intakebookingsid");

            query_dia_intakebookings.Columns.AddColumns("dia_type");
            query_dia_intakebookings.LinkCriteria.AddCondition("dia_type", ConditionOperator.Equal, 587800000);

            if (intakeEnt != null && intakeEnt.GetAttributeValue <DateTime>("dia_scheduledstart") != DateTime.MinValue)
            {
                tracingService.Trace("intake schedule: " + intakeEnt.GetAttributeValue <DateTime>("dia_scheduledstart"));
                var query_dia_intakebookings_LinkCriteria_1 = new FilterExpression();
                query_dia_intakebookings.LinkCriteria.AddFilter(query_dia_intakebookings_LinkCriteria_1);
                query_dia_intakebookings_LinkCriteria_1.AddCondition("dia_scheduledstart", ConditionOperator.LessEqual, intakeEnt.GetAttributeValue <DateTime>("dia_scheduledstart"));
            }

            EntityCollection resultsquery = service.RetrieveMultiple(query);

            return(resultsquery);
        }
        private string GetNumber(IOrganizationService service)
        {
            int suffix = 0;
            string contractNumber = string.Empty;
            QueryExpression query = new QueryExpression("ivg_autonumber");

            FilterExpression filter = new FilterExpression(LogicalOperator.And);

            filter.AddCondition("ivg_contactnumber", ConditionOperator.Equal, "contractnumber");
            filter.AddCondition("ivg_year", ConditionOperator.Equal, DateTime.Now.Year.ToString().Substring(2));
            filter.AddCondition("ivg_month", ConditionOperator.Equal, DateTime.Now.Month.ToString());
            query.Criteria.AddFilter(filter);

            query.ColumnSet = new ColumnSet(true);
            EntityCollection collection = null;
            try
            {
                collection = service.RetrieveMultiple(query);

                if (collection != null && collection.Entities.Count > 0)
                {
                    contractNumber = null;
                    string MM = collection.Entities[0].Attributes["ivg_month"].ToString();
                    if (MM.Length == 1)
                        MM = "0" + MM;
                    suffix = int.Parse(collection.Entities[0].Attributes["ivg_number"].ToString()) + 1;
                    string suffixString = suffix.ToString("0000");
                    //if (suffixString.Length == 1)
                    //    suffixString = "000" + suffixString;
                    //if (suffixString.Length == 2)
                    //    suffixString = "00" + suffixString;
                    //if (suffixString.Length == 3)
                    //    suffixString = "0" + suffixString;
                    contractNumber = collection.Entities[0].Attributes["ivg_year"].ToString() + MM + "-" + suffixString;

                    #region update auto number entity
                    Guid autonumberId = collection.Entities[0].Id;
                    Entity ivg_autonumber = new Entity("ivg_autonumber");
                    ivg_autonumber.Id = autonumberId;
                    ivg_autonumber.Attributes["ivg_number"] = suffix.ToString();

                    service.Update(ivg_autonumber);

                    #endregion
                }
                else
                {
                    suffix = 1;
                    Entity ivg_autonumber = new Entity("ivg_autonumber");
                    ivg_autonumber.Attributes["ivg_number"] = suffix.ToString();
                    ivg_autonumber.Attributes["ivg_contactnumber"] = "contractnumber";
                    ivg_autonumber.Attributes["ivg_year"] = DateTime.Now.Year.ToString().Substring(2);
                    ivg_autonumber.Attributes["ivg_month"] = DateTime.Now.Month.ToString();

                    service.Create(ivg_autonumber);
                    string MM = DateTime.Now.Month.ToString();
                    if (MM.Length == 1)
                        MM = "0" + MM;
                    contractNumber = DateTime.Now.Year.ToString().Substring(2) + MM + "-0001";
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.StackTrace);
            }
            return contractNumber;
        }
        private Guid findCvOwner(string customerName, IOrganizationService service)
        {

            ConditionExpression condition = new ConditionExpression();
            condition.AttributeName = "name";
            condition.Operator = ConditionOperator.Equal;
            condition.Values.Add(customerName);

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

            QueryExpression query = new QueryExpression();
            query.EntityName = "account";
            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)
            {
                throw new Exception("The user was not be found");
            }
        }