Example #1
0
 public virtual Entity Retrieve(string entityName, Guid id, ColumnSet columnSet)
 {
     CapturedInput.EntityName = entityName;
     CapturedInput.EntityId = id;
     CapturedInput.ColumnSet = columnSet;
     return RespondWith.RetrieveEntity;
 }
Example #2
0
		public static CrmQuery Select( ColumnSet in_columns ) {
#endif
			QueryExpression query = new QueryExpression();
			query.ColumnSet = in_columns;
			CrmQuery dsl = new CrmQuery();
			dsl.m_query = query;
			return dsl;
		}
        /// <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 ExecutePostAttachmentSearchUpdate(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 searchID = (Guid)((Entity)context.InputParameters["Target"]).Id;
            ColumnSet set = new ColumnSet();
            set.AllColumns = true;


            var searchEntity = service.Retrieve("new_attachmentsearch", searchID, set);

            if (context.Depth > 1)
            {
                searchEntity["new_results"] = "This created a loop!";
                return;
            }
            else
            {
                //acquires the keyword

                string keywordToLook = (string)searchEntity["new_searchword"];
                var countPerPage = 20;
                    //(int)searchEntity["new_countperpage"];
                var pagesCount = (int)searchEntity["new_numberofpages"];
                var lastPage = 1;
                var firstPage = 1;

                //creates the critieria of the query
                ColumnSet NoteSet = new ColumnSet(new string[] { "filename", "documentbody", "subject" });
                QueryExpression Notes = new QueryExpression { EntityName = "annotation", ColumnSet = NoteSet };
                Notes.PageInfo = new PagingInfo();
                Notes.PageInfo.Count = countPerPage;
                Notes.Criteria.AddCondition("documentbody", ConditionOperator.NotNull);

                //retrieve the Notes that fulfill the condition
                searchEntity["new_results"] = "";

                for (int i = firstPage; i < lastPage; i++)
                {
                      var NotesRetrieved = fillCollection(Notes, pagesCount, service);
                      searchForKeyWord(keywordToLook, searchEntity, NotesRetrieved, pagesCount);
                }

                //EntityCollection fullListOfEntities = new EntityCollection();
                // searchEntity["new_results"] += "\r\n" + keywordToLook;
            }
            service.Update(searchEntity);
        }
 /// <summary>
 /// Creates a ColumnSet object based on the keys in the mapping dictionary
 /// </summary>
 /// <returns>A ColumnSet</returns>
 public static ColumnSet GetColumnsBasedOnMapping(Dictionary<PropertyInfo, string> mapping)
 {
     // Create the column set object that indicates the properties to be retrieved.
     ColumnSet cols = new ColumnSet();
     foreach (string attribute in mapping.Values)
     {
         cols.AddColumn(attribute);
     }
     return cols;
 }
Example #5
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);

            }
        }
Example #6
0
        public Result Create(Item  ObjItem )
        {
            try
            {
                if (service == null)
                {
                    LogError.log.Error("Service is null");
                    throw new Exception("Service is null");
                }
                //lay ve Entity ivg_itemtype
                QueryExpression query = new QueryExpression("ivg_itemtype");
                query.Criteria.AddCondition("ivg_id", ConditionOperator.Equal, ObjItem.Ivg_itemtypeid);
                query.ColumnSet = new ColumnSet(true);
                EntityCollection entityes= service.RetrieveMultiple(query);
                Entity type = entityes.Entities[0];

                //lay ve Entity ivg_itemgroup
                QueryExpression queryitemgroup = new QueryExpression("ivg_itemgroup");
                queryitemgroup.Criteria.AddCondition("ivg_groupid", ConditionOperator.Equal, ObjItem.Ivg_itemgroupid);
                queryitemgroup.ColumnSet = new ColumnSet(true);
                EntityCollection entityesitemgroup = service.RetrieveMultiple(queryitemgroup);
                Entity typeitemgroup = entityesitemgroup.Entities[0];

                Entity objEntity = new Entity("ivg_item");
                objEntity.Attributes["ivg_itemtypeid"] = new EntityReference("ivg_itemtype", type.Id);
                objEntity.Attributes["ivg_itemgroupid"] = new EntityReference("ivg_itemgroup", typeitemgroup.Id);
                objEntity.Attributes["ivg_name"] = ObjItem.Ivg_name;
                OutIDcheck = new StringBuilder();
                if (CheckDuplicateGroupID(service, "ivg_item", "ivg_code", ObjItem.Ivg_code, "ivg_code"))
                {
                    //update cac truong lien quan neu trung
                    ColumnSet attributes = new ColumnSet(new string[] { "ivg_name", "ivg_code", "ivg_itemtypeid", "ivg_itemgroupid" });
                    GuidTemp=Guid.Parse(OutIDcheck.ToString());
                    objEntity = service.Retrieve(objEntity.LogicalName, GuidTemp, attributes);
                    objEntity.Attributes["ivg_name"] = ObjItem.Ivg_name;
                    service.Update(objEntity);
                    OutIDcheck.Clear();
                    //End Update
                    return new Result("", true, ObjItem.Ivg_code);
                }
                else
                {
                    Guid EntityID = service.Create(objEntity);
                    return new Result("", false, EntityID);
                }

            }
            catch (Exception ex)
            {
                LogError.log.Error(ex.StackTrace);
                return new Result(ex.StackTrace, true);
            }
        }
        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;
        }
Example #8
0
        private static IEnumerable<Entity> GetDefinitions(Entity email, IOrganizationService service)
        {
            var subject = (string)email.Attributes["subject"];
            if (subject == null) throw new ArgumentNullException("email");

            var epmappings = new QueryExpression("new_emailparserdefinition");
            var cols = new ColumnSet("new_name", "new_emailparserdefinitionid", "new_crmentityname", "new_subjectpattern", "new_senderaddress");
            epmappings.ColumnSet = cols;
            epmappings.Criteria.AddCondition(new ConditionExpression("statecode", ConditionOperator.Equal, "Active"));
            IEnumerable<Entity> result = service.RetrieveMultiple(epmappings).Entities;

            return result
                .Where(element => Regex.IsMatch(subject, (string)element.Attributes["new_subjectpattern"]))
                    .Select(element => element);
        }
        /// <summary>
        /// Demonstrates how to programmatically create a Workflow from an existing
        /// Process Template.
        /// </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
            {
                //<snippetCreateProcessFromTemplate1>
                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,
                                                                     serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    OrganizationServiceContext _orgContext = new OrganizationServiceContext(_serviceProxy);

                    CreateRequiredRecords();

                    CreateWorkflowFromTemplateRequest request = new CreateWorkflowFromTemplateRequest()
                    {
                        WorkflowName = "Workflow From Template",
                        WorkflowTemplateId = _processTemplateId
                    };

                    // Execute request.
                    CreateWorkflowFromTemplateResponse response = (CreateWorkflowFromTemplateResponse)_serviceProxy.Execute(request);
                    _processId = response.Id;

                    // Verify success.
                    // Retrieve the name of the workflow.
                    ColumnSet cols = new ColumnSet("name");
                    Workflow newWorkflow = (Workflow)_serviceProxy.Retrieve(Workflow.EntityLogicalName, response.Id, cols);
                    if (newWorkflow.Name == "Workflow From Template")
                    {
                        Console.WriteLine("Created {0}.", request.WorkflowName);
                    }

                    DeleteRequiredRecords(promptforDelete);
                }
                //</snippetCreateProcessFromTemplate1>
            }

            // 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;
            }
        }
Example #10
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            //Create the tracing service
            ITracingService tracingService = executionContext.GetExtension<ITracingService>();

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

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

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

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

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

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

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

            EntityCollection productPriceLevelList = service.RetrieveMultiple(productPriceLevelExpression);

            // Create new product price level records
            for (int index = 0; productPriceLevelList.Entities != null && index < productPriceLevelList.Entities.Count; index++)
            {
                Entity newProductPriceLevelEntity = new Entity("productpricelevel");
                newProductPriceLevelEntity["pricelevelid"] = new EntityReference("pricelevel", newPriceLevelId);
                newProductPriceLevelEntity["productid"] = productPriceLevelList.Entities[index]["productid"];
                newProductPriceLevelEntity["uomid"] = productPriceLevelList.Entities[index]["uomid"];
                newProductPriceLevelEntity["amount"] = productPriceLevelList.Entities[index]["amount"];
                service.Create(newProductPriceLevelEntity);
            }
        }
Example #11
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 ExecutePricingOrderCreate(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 orderDetail = service.Retrieve("salesorderdetail", quoteDetailID, set);
            const decimal minimumValue = 0;
            const decimal minimumRatio = 1;

            if (context.Depth > 1)
            {
                return;
            }
            else
            {
                var priceperunit = (Money)orderDetail["priceperunit"];
                orderDetail["new_specificdiscountpercentage"] = minimumValue;
                orderDetail["new_ratio"] = minimumRatio;
                orderDetail["new_grossannualincome"] = new Money(minimumValue);
                orderDetail["new_gaixratio"] = new Money(minimumValue);
                orderDetail["new_recommendedvalue"] = priceperunit;
                //orderDetail["new_fixedpriceplusratio"] = priceperunit;

                //This sets the current pricing type of the quote product, to the default pricing type of the quote
                var parentOrder = (EntityReference)orderDetail["salesorderid"];

                var quote = service.Retrieve(parentOrder.LogicalName, parentOrder.Id, new ColumnSet(true));

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

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

                service.Update(orderDetail);
            }
        }
 private static string GetColumns(ColumnSet columns, string LineStart)
 {
     var code = new StringBuilder();
     if (columns.AllColumns)
     {
         code.AppendLine();
         code.AppendLine("// Add all columns to " + LineStart);
         code.AppendLine(LineStart + ".AllColumns = true;");
     }
     else if (columns.Columns.Count > 0)
     {
         code.AppendLine();
         code.AppendLine("// Add columns to " + LineStart);
         var cols = "\"" + string.Join("\", \"", columns.Columns) + "\"";
         code.AppendLine(LineStart + ".AddColumns(" + cols + ");");
     }
     return code.ToString();
 }
        public Result Create(ItemType ObjItemType)
        {
            try
            {
                if (service == null)
                {
                    LogError.log.Error("Service is null");
                    throw new Exception("Service is null");
                }
                Entity objEntity = new Entity("ivg_itemtype");
                objEntity.Attributes["ivg_id"] = ObjItemType.Ivg_id;
                objEntity.Attributes["ivg_name"] = ObjItemType.Ivg_name;

                CheckDuplicate objcheck = new CheckDuplicate();
                string[] columName = { "ivg_id" };
                string[] att = { "ivg_id" };
                string[] values = { objEntity.Attributes["ivg_id"].ToString() };

                 if (objcheck.CheckDuplicateBase(service, objEntity.LogicalName, att, values, columName))
                //if (CheckDuplicateID(service, "ivg_itemtype", "ivg_id", ObjItemType.Ivg_id, "ivg_id"))
                {
                    //Update Name neu ID trung
                    //objEntity.Attributes["ivg_id"] = ObjItemType.Ivg_id;
                    ColumnSet attributes = new ColumnSet(new string[] { "ivg_id", "ivg_name" });
                    GuidTemp = objcheck.IdGui;
                    objEntity = service.Retrieve(objEntity.LogicalName, GuidTemp, attributes);
                    objEntity.Attributes["ivg_name"] = ObjItemType.Ivg_name;
                    service.Update(objEntity);

                    //End Update
                    return new Result("", true, ObjItemType.Ivg_id);
                }
                else
                {
                    Guid EntityID = service.Create(objEntity);
                    return new Result("", false, EntityID);
                }
            }
            catch (Exception ex)
            {
                LogError.log.Error(ex.StackTrace);
                return new Result(ex.StackTrace, true);
            }
        }
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService tracer = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = factory.CreateOrganizationService(context.UserId);

            try
            {

                EntityReference leadid = (EntityReference)context.InputParameters["LeadId"];
                ColumnSet attributes2 = new ColumnSet(new string[] { "subject"});
                Entity lead = service.Retrieve(leadid.LogicalName, leadid.Id, attributes2);
                //throw new InvalidPluginExecutionException(lead.Attributes["subject"].ToString());

                context.InputParameters["CreateContact"] = false;

                //if (context.InputParameters.Contains("Target"))
                //{
                //    Entity entity = (Entity)context.InputParameters["Target"];
                //}

                //else
                //{
                //    throw new InvalidPluginExecutionException("Hi");
                //}

                //TODO: Do stuff

                //if (entity.Attributes["mobilephone"].ToString()=="" || entity.Attributes["mobilephone"]==null)
                //{}
                    //context.InputParameters["CreateContact"] = false;

            }
            catch (Exception e)
            {
                throw new InvalidPluginExecutionException(e.Message);
            }
        }
Example #15
0
        static public bool TeamMasterLogicMethod(IOrganizationService service, Guid User)
        {
            QueryExpression teamQuery = new QueryExpression("team");
            ColumnSet teamColumnSet = new ColumnSet("name");

            teamQuery.ColumnSet = teamColumnSet;
            teamQuery.Criteria = new FilterExpression();
            teamQuery.Criteria.FilterOperator = LogicalOperator.And;
            // teamQuery.Criteria.AddCondition("name", ConditionOperator.Equal, "Sales");
            teamQuery.AddLink("teammembership", "teamid", "teamid").AddLink("systemuser", "systemuserid", "systemuserid").LinkCriteria.AddCondition("systemuserid", ConditionOperator.Equal, User);

            EntityCollection teamDetail = service.RetrieveMultiple(teamQuery);

            foreach (Entity ent in teamDetail.Entities)
            {
                string query = generateFetchForTeamMaster(ent.Id.ToString());
                if (retrievePermision(service, query))
                    return true;
            }

            return false;
        }
Example #16
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate the method to create any data that this sample requires.
        /// Share a queue to the team.
        /// Optionally delete any entity records that were created for this sample.
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        /// </summary>

        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 = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    ////<snippetAddPrincipalToQueue1>                
                    ColumnSet columnSet = new ColumnSet("name");
                    Entity team = _serviceProxy.Retrieve(Team.EntityLogicalName, _teamId, columnSet);
                    AddPrincipalToQueueRequest addPrincipalToQueueRequest = new AddPrincipalToQueueRequest
                    {
                        Principal = team,
                        QueueId = _queueId
                    };

                    _serviceProxy.Execute(addPrincipalToQueueRequest);

                    //</snippetAddPrincipalToQueue1>  

                    Console.WriteLine("The team has been added to the queue.");

                    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;
            }
        }
        /// <summary>
        /// Активировать карточку
        /// </summary>
        /// <param name="organizationService"></param>
        /// <param name="record"></param>
        public static void ActivateRecord(this IOrganizationService organizationService, Entity record)
        {
            var cols = new ColumnSet("statecode", "statuscode");

            //Check if it is Inactive or not
            var entity = organizationService.Retrieve(record.LogicalName, record.Id, cols);

            if (entity != null && entity.GetAttributeValue<OptionSetValue>("statecode").Value != 0)
            {
                //StateCode = 0 and StatusCode = 1 for activating Account or Contact
                SetStateRequest setStateRequest = new SetStateRequest()
                {
                    EntityMoniker = new EntityReference
                    {
                        Id = record.Id,
                        LogicalName = record.LogicalName,
                    },

                    State = new OptionSetValue(0),
                    Status = new OptionSetValue(1)
                };
                organizationService.Execute(setStateRequest);
            }
        }
        internal void SetOrgProperties(OrganizationDetail detail)
        {
            // Create the column set object that indicates the properties to be retrieved and retrieve the current organization.
            ColumnSet cols = new ColumnSet(new string[] { "languagecode" });
            Entity org = this.InstallAdapter.OrganizationService.Retrieve("organization", detail.OrganizationId, cols) as Entity;

            if (org != null)
            {
                this.BaseLangCode = org.GetAttributeValue<int>("languagecode");
                TraceLog.Info(string.Format(CultureInfo.CurrentCulture, Resources.OrganizationBaseLanguageMessage, detail.FriendlyName, this.BaseLangCode));
            }
        }
Example #19
0
 /// <summary>
 /// Gets all Entities where the columnNameAndValue Pairs match
 /// </summary>
 /// <param name="service"></param>
 /// <param name="logicalName">LogicalName of the Entity.</param>
 /// <param name="columnSet">Columns to retrieve</param>
 /// <param name="columnNameAndValuePairs">List of pairs that look like this:
 /// (string name of the column, value of the column) ie. "name", "John Doe" </param>
 /// <returns></returns>
 public static IEnumerable <Entity> GetAllEntities(this IOrganizationService service, string logicalName, ColumnSet columnSet,
                                                   params object[] columnNameAndValuePairs)
 {
     return(service.GetAllEntities <Entity>(QueryExpressionFactory.Create(logicalName, columnSet, columnNameAndValuePairs)));
 }
 public IEnumerable <IEntityWrapper <Entity> > GetAllRelated(string relatedEntityName, string relatedToParentAttribute, ColumnSet relatedColumnSet)
 => _currentWrapper.Value.GetAllRelated(relatedEntityName, relatedToParentAttribute, relatedColumnSet);
Example #21
0
        private IList <Entity> GetEntitiesByField(string linkName, string field, object value, ColumnSet columns)
        {
            var queryByAttribute = new QueryByAttribute(linkName)
            {
                ColumnSet  = columns,
                Attributes = { field },
                Values     = { value }
            };

            return(_service.RetrieveMultiple(queryByAttribute).Entities);
        }
 public Task <List <SdkMessageResponseField> > GetListAsync(ColumnSet columnSet)
 {
     return(Task.Run(() => GetList(columnSet)));
 }
 public Task <List <SdkMessageResponseField> > GetListByPairAsync(Guid idPair, ColumnSet columnSet)
 {
     return(Task.Run(() => GetListByPair(idPair, columnSet)));
 }
        private async Task RetrieveEntityInformation()
        {
            try
            {
                foreach (var entity in _entityCollection)
                {
                    ToggleControls(false, Properties.OutputStrings.FilteringEntityInstanceAttributesFormat2, _entityMetadata.LogicalName, entity.Id);

                    foreach (var attributeKey in entity.Attributes.Keys.ToList())
                    {
                        var attributeMetadata = _entityMetadata.Attributes.FirstOrDefault(a => string.Equals(attributeKey, a.LogicalName, StringComparison.InvariantCultureIgnoreCase));

                        if (attributeMetadata == null)
                        {
                            if (_cacheMessageEntityAttributeNotExists.Add(attributeKey))
                            {
                                this._iWriteToOutput.WriteToOutput(_service.ConnectionData, Properties.OutputStrings.EntityAttributeNotExistsInConnectionFormat3, _entityMetadata.LogicalName, attributeKey, _service.ConnectionData.Name);
                            }

                            entity.Attributes.Remove(attributeKey);
                            continue;
                        }

                        if (!attributeMetadata.IsValidForCreate.GetValueOrDefault() &&
                            !attributeMetadata.IsValidForUpdate.GetValueOrDefault()
                            )
                        {
                            entity.Attributes.Remove(attributeKey);
                            continue;
                        }

                        if (entity.Attributes[attributeKey] != null &&
                            entity.Attributes[attributeKey] is EntityReference entityReference &&
                            attributeMetadata is LookupAttributeMetadata lookupAttributeMetadata &&
                            !_dictLookupMapping.ContainsKey(entityReference)
                            )
                        {
                            var targetEntityMetadata = await GetEntityMetadata(entityReference.LogicalName);

                            if (targetEntityMetadata == null)
                            {
                                entity.Attributes.Remove(attributeKey);
                                continue;
                            }

                            EntityReference targetEntityReference = null;

                            var repositoryGeneric = new GenericRepository(_service, targetEntityMetadata);

                            ColumnSet columnSet = ColumnSetInstances.None;

                            if (!string.IsNullOrEmpty(targetEntityMetadata.PrimaryNameAttribute))
                            {
                                columnSet.AddColumn(targetEntityMetadata.PrimaryNameAttribute);
                            }

                            if (targetEntityReference == null)
                            {
                                ToggleControls(false, Properties.OutputStrings.TryingToFindEntityByIdFormat2, entityReference.LogicalName, entityReference.Id);

                                var targetEntity = await repositoryGeneric.GetEntityByIdAsync(entityReference.Id, columnSet);

                                if (targetEntity != null)
                                {
                                    targetEntityReference = targetEntity.ToEntityReference();

                                    if (!string.IsNullOrEmpty(targetEntityMetadata.PrimaryNameAttribute) &&
                                        targetEntity.Attributes.ContainsKey(targetEntityMetadata.PrimaryNameAttribute) &&
                                        targetEntity.Attributes[targetEntityMetadata.PrimaryNameAttribute] != null &&
                                        targetEntity.Attributes[targetEntityMetadata.PrimaryNameAttribute] is string entityReferenceName
                                        )
                                    {
                                        targetEntityReference.Name = entityReferenceName;
                                    }

                                    ToggleControls(true, Properties.OutputStrings.TryingToFindEntityByIdFoundedFormat2, entityReference.LogicalName, entityReference.Id);
                                }
                                else
                                {
                                    ToggleControls(true, Properties.OutputStrings.TryingToFindEntityByIdNotFoundedFormat2, entityReference.LogicalName, entityReference.Id);
                                }
                            }

                            if (targetEntityReference == null &&
                                !string.IsNullOrEmpty(targetEntityMetadata.PrimaryNameAttribute) &&
                                !string.IsNullOrEmpty(entityReference.Name)
                                )
                            {
                                ToggleControls(false, Properties.OutputStrings.TryingToFindEntityByNameFormat4, entityReference.LogicalName, entityReference.Id, targetEntityMetadata.PrimaryNameAttribute, entityReference.Name);

                                var targetEntity = await repositoryGeneric.GetEntityByNameFieldAsync(entityReference.Name, columnSet);

                                if (targetEntity != null)
                                {
                                    targetEntityReference = targetEntity.ToEntityReference();

                                    if (targetEntity.Attributes.ContainsKey(targetEntityMetadata.PrimaryNameAttribute) &&
                                        targetEntity.Attributes[targetEntityMetadata.PrimaryNameAttribute] != null &&
                                        targetEntity.Attributes[targetEntityMetadata.PrimaryNameAttribute] is string entityReferenceName
                                        )
                                    {
                                        targetEntityReference.Name = entityReferenceName;
                                    }

                                    ToggleControls(true, Properties.OutputStrings.TryingToFindEntityByNameFoundedFormat4, entityReference.LogicalName, entityReference.Id, targetEntityMetadata.PrimaryNameAttribute, entityReference.Name);
                                }
                                else
                                {
                                    ToggleControls(true, Properties.OutputStrings.TryingToFindEntityByNameNotFoundedFormat4, entityReference.LogicalName, entityReference.Id, targetEntityMetadata.PrimaryNameAttribute, entityReference.Name);
                                }
                            }

                            EntityReferenceMappingControl control = null;

                            this.Dispatcher.Invoke(() =>
                            {
                                control = new EntityReferenceMappingControl(this._iWriteToOutput, _service, lookupAttributeMetadata, entityReference, targetEntityReference);
                            });

                            _dictLookupMapping.Add(entityReference, control);
                            _listLookupMappingControls.Add(control);
                        }
                    }

                    ToggleControls(true, Properties.OutputStrings.FilteringEntityInstanceAttributesCompletedFormat2, _entityMetadata.LogicalName, entity.Id);
                }

                this.lstVwLookupMapping.Dispatcher.Invoke(() =>
                {
                    int index = 0;

                    foreach (var item in _listLookupMappingControls.OrderBy(a => a.AttributeMetadata.LogicalName))
                    {
                        if (item is UserControl control)
                        {
                            var itemRowDef = new RowDefinition()
                            {
                                Height = new GridLength(10, GridUnitType.Auto),
                            };

                            lstVwLookupMapping.RowDefinitions.Add(itemRowDef);

                            control.VerticalAlignment   = VerticalAlignment.Stretch;
                            control.HorizontalAlignment = HorizontalAlignment.Stretch;

                            Grid.SetRow(control, index);
                            lstVwLookupMapping.Children.Add(control);

                            index++;
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                _iWriteToOutput.WriteErrorToOutput(_service.ConnectionData, ex);
            }
        }
Example #25
0
 /// <summary>
 /// Same as non generic GetEntity but cast to a early bound type
 /// </summary>
 /// <typeparam name="T">The poroxy type</typeparam>
 /// <param name="columnSet">The columns to retrieve</param>
 /// <param name="forceRefresh">Mark as true if you want to query CRM for each call and not get from the cache</param>
 /// <returns>The early bound entity with the attributes specified</returns>
 public T GetEntity <T>(ColumnSet columnSet, bool forceRefresh = false) where T : Entity
 {
     return(GetEntity(columnSet, forceRefresh).ToEntity <T>());
 }
Example #26
0
/// <summary>
/// <para><b>Entity ()</b></para>
/// <para>Schema Name: userentityinstancedata_columnmapping</para>
/// </summary>
        public List <Entity> GetUserEntityInstanceData(IOrganizationService Service, ColumnSet Columns)
        {
            return(BaseProxyClass.GetRelatedOneToManyEntities(Service, this.Id, "userentityinstancedata", "objectid", Columns));
        }
Example #27
0
/// <summary>
/// <para><b>Entity ()</b></para>
/// <para>Schema Name: PickListMapping_ColumnMapping</para>
/// </summary>
        public List <Entity> GetListValueMappings(IOrganizationService Service, ColumnSet Columns)
        {
            return(BaseProxyClass.GetRelatedOneToManyEntities(Service, this.Id, "picklistmapping", "columnmappingid", Columns));
        }
Example #28
0
 public T GetCrmEntityById(Guid id, ColumnSet columns)
 {
     return((T)_service.Retrieve(entityName, id, columns));
 }
Example #29
0
        /// <summary>
        /// This method first connects to the Organization service. Afterwards,
        /// basic create, retrieve, update, and delete entity operations are performed.
        /// </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
            {
                //<snippetCRUDOperations1>
                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    // Instantiate an account object.
                    // See the Entity Metadata topic in the SDK documentation to determine 
                    // which attributes must be set for each entity.
                    Account account = new Account { Name = "Fourth Coffee" };

                    // Create an account record named Fourth Coffee.
                    _accountId = _serviceProxy.Create(account);
                    Console.Write("{0} {1} created, ", account.LogicalName, account.Name);

                    // Retrieve the account containing several of its attributes.
                    ColumnSet cols = new ColumnSet(
                        new String[] { "name", "address1_postalcode", "lastusedincampaign", "versionnumber" });

                    Account retrievedAccount = (Account)_serviceProxy.Retrieve("account", _accountId, cols);
                    Console.Write("retrieved ");

                    // Retrieve version number of the account. Shows BigInt attribute usage.
                    long? versionNumber = retrievedAccount.VersionNumber;

                    if (versionNumber != null)
                        Console.WriteLine("version # {0}, ", versionNumber);

                    // Update the postal code attribute.
                    retrievedAccount.Address1_PostalCode = "98052";

                    // The address 2 postal code was set accidentally, so set it to null.
                    retrievedAccount.Address2_PostalCode = null;

                    // Shows usage of option set (picklist) enumerations defined in OptionSets.cs.
                    retrievedAccount.Address1_AddressTypeCode = new OptionSetValue((int)AccountAddress1_AddressTypeCode.Primary);
                    retrievedAccount.Address1_ShippingMethodCode = new OptionSetValue((int)AccountAddress1_ShippingMethodCode.DHL);
                    retrievedAccount.IndustryCode = new OptionSetValue((int)AccountIndustryCode.AgricultureandNonpetrolNaturalResourceExtraction);

                    // Shows use of a Money value.
                    retrievedAccount.Revenue = new Money(5000000);

                    // Shows use of a Boolean value.
                    retrievedAccount.CreditOnHold = false;

                    // Shows use of EntityReference.
                    retrievedAccount.ParentAccountId = new EntityReference(Account.EntityLogicalName, _parentAccountId);

                    // Shows use of Memo attribute.
                    retrievedAccount.Description = "Account for Fourth Coffee.";

                    // Update the account record.
                    _serviceProxy.Update(retrievedAccount);
                    Console.WriteLine("and updated.");                    

                    DeleteRequiredRecords(promptforDelete);
                }
                //</snippetCRUDOperations1>
            }

            // 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;
            }
        }
Example #30
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);
            }
        }
 public Task <SdkMessageResponseField> GetByIdAsync(Guid idSdkMessageResponseField, ColumnSet columnSet)
 {
     return(Task.Run(() => GetById(idSdkMessageResponseField, columnSet)));
 }
 public IEntityWrapper <Entity> GetRelated(string relatedAttribute, ColumnSet relatedColumnSet)
 => _currentWrapper.Value.GetRelated(relatedAttribute, relatedColumnSet);
 public Task <List <SdkMessageResponseField> > GetListByResponseIdAsync(Guid idResponse, ColumnSet columnSet)
 {
     return(Task.Run(() => GetListByResponseId(idResponse, columnSet)));
 }
Example #34
0
        public static Entity JoinAttributes(this Entity e, IEnumerable <Entity> otherEntities, ColumnSet columnSet, string alias, XrmFakedContext context)
        {
            foreach (var otherEntity in otherEntities)
            {
                var otherClonedEntity = otherEntity.Clone(); //To avoid joining entities from/to the same entities, which would cause collection modified exceptions

                if (columnSet.AllColumns)
                {
                    foreach (var attKey in otherClonedEntity.Attributes.Keys)
                    {
                        e[alias + "." + attKey] = new AliasedValue(otherEntity.LogicalName, attKey, otherClonedEntity[attKey]);
                    }
                }
                else
                {
                    //Return selected list of attributes
                    foreach (var attKey in columnSet.Columns)
                    {
                        if (!context.AttributeExistsInMetadata(otherEntity.LogicalName, attKey))
                        {
                            OrganizationServiceFaultQueryBuilderNoAttributeException.Throw(attKey);
                        }

                        if (otherClonedEntity.Attributes.ContainsKey(attKey))
                        {
                            e[alias + "." + attKey] = new AliasedValue(otherEntity.LogicalName, attKey, otherClonedEntity[attKey]);
                        }
                        else
                        {
                            e[alias + "." + attKey] = new AliasedValue(otherEntity.LogicalName, attKey, null);
                        }
                    }
                }
            }
            return(e);
        }
 public Task <List <EntityMap> > GetListForEntitiesAsync(string[] entities, ColumnSet columnSet)
 {
     return(Task.Run(() => GetListForEntities(entities, columnSet)));
 }
Example #36
0
        /// <summary>
        /// </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 = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Creates required records for this sample.
                    CreateRequiredRecords();

                    // Qualify a lead to create an opportunity
                    QualifyLeadRequest qualifyRequest = new QualifyLeadRequest
                    {
                        LeadId            = new EntityReference(Lead.EntityLogicalName, _leadId),
                        Status            = new OptionSetValue((int)lead_statuscode.Qualified),
                        CreateOpportunity = true
                    };
                    QualifyLeadResponse qualifyResponse = (QualifyLeadResponse)_serviceProxy.Execute(qualifyRequest);
                    _opportunityId = qualifyResponse.CreatedEntities[0].Id;
                    if (_opportunityId != Guid.Empty)
                    {
                        Console.WriteLine("\nQualified Lead to create an Opportunity record.");
                    }

                    // Verify the curently active BPF instance for the qualified Opportunity record
                    RetrieveProcessInstancesRequest procOpp1Req = new RetrieveProcessInstancesRequest
                    {
                        EntityId          = _opportunityId,
                        EntityLogicalName = Opportunity.EntityLogicalName
                    };
                    RetrieveProcessInstancesResponse procOpp1Resp = (RetrieveProcessInstancesResponse)_serviceProxy.Execute(procOpp1Req);

                    // Declare variables to store values returned in response
                    Entity activeProcessInstance = null;

                    if (procOpp1Resp.Processes.Entities.Count > 0)
                    {
                        activeProcessInstance = procOpp1Resp.Processes.Entities[0]; // First record is the active process instance
                        _processOpp1Id        = activeProcessInstance.Id;           // Id of the active process instance, which will be used
                                                                                    // later to retrieve the active path of the process instance

                        Console.WriteLine("Current active process instance for the Opportunity record: '{0}'", activeProcessInstance["name"].ToString());
                        _procInstanceLogicalName = activeProcessInstance["name"].ToString().Replace(" ", string.Empty).ToLower();
                    }
                    else
                    {
                        Console.WriteLine("No process instances found for the opportunity record; aborting the sample.");
                        Environment.Exit(1);
                    }

                    // Retrieve the active stage ID of the active process instance
                    _activeStageId = new Guid(activeProcessInstance.Attributes["processstageid"].ToString());

                    // Retrieve the process stages in the active path of the current process instance
                    RetrieveActivePathRequest pathReq = new RetrieveActivePathRequest
                    {
                        ProcessInstanceId = _processOpp1Id
                    };
                    RetrieveActivePathResponse pathResp = (RetrieveActivePathResponse)_serviceProxy.Execute(pathReq);
                    Console.WriteLine("\nRetrieved stages in the active path of the process instance:");
                    for (int i = 0; i < pathResp.ProcessStages.Entities.Count; i++)
                    {
                        Console.WriteLine("\tStage {0}: {1} (StageId: {2})", i + 1,
                                          pathResp.ProcessStages.Entities[i].Attributes["stagename"], pathResp.ProcessStages.Entities[i].Attributes["processstageid"]);


                        // Retrieve the active stage name and active stage position based on the activeStageId for the process instance
                        if (pathResp.ProcessStages.Entities[i].Attributes["processstageid"].ToString() == _activeStageId.ToString())
                        {
                            _activeStageName     = pathResp.ProcessStages.Entities[i].Attributes["stagename"].ToString();
                            _activeStagePosition = i;
                        }
                    }

                    // Display the active stage name and Id
                    Console.WriteLine("\nActive stage for the process instance: '{0}' (StageID: {1})", _activeStageName, _activeStageId);

                    // Prompt the user to move to the next stage. If user choses to do so:
                    // Set the next stage (_activeStagePosition + 1) as the active stage for the process instance
                    bool moveToNextStage = true;
                    Console.WriteLine("\nDo you want to move to the next stage (y/n):");
                    String answer = Console.ReadLine();
                    moveToNextStage = (answer.StartsWith("y") || answer.StartsWith("Y"));
                    if (moveToNextStage)
                    {
                        // Retrieve the stage ID of the next stage that you want to set as active
                        _activeStageId = (Guid)pathResp.ProcessStages.Entities[_activeStagePosition + 1].Attributes["processstageid"];

                        // Retrieve the process instance record to update its active stage
                        ColumnSet cols1 = new ColumnSet();
                        cols1.AddColumn("activestageid");
                        Entity retrievedProcessInstance = _serviceProxy.Retrieve(_procInstanceLogicalName, _processOpp1Id, cols1);

                        // Update the active stage to the next stage
                        retrievedProcessInstance["activestageid"] = new EntityReference(ProcessStage.EntityLogicalName, _activeStageId);
                        _serviceProxy.Update(retrievedProcessInstance);


                        // Retrieve the process instance record again to verify its active stage information
                        ColumnSet cols2 = new ColumnSet();
                        cols2.AddColumn("activestageid");
                        Entity retrievedProcessInstance1 = _serviceProxy.Retrieve(_procInstanceLogicalName, _processOpp1Id, cols2);

                        EntityReference activeStageInfo = retrievedProcessInstance1["activestageid"] as EntityReference;
                        if (activeStageInfo.Id == _activeStageId)
                        {
                            Console.WriteLine("\nChanged active stage for the process instance to: '{0}' (StageID: {1})",
                                              activeStageInfo.Name, activeStageInfo.Id);
                        }
                    }

                    // Prompts to delete the required records
                    DeleteRequiredRecords(promptForDelete);
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics 365 throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
 public Task <List <EntityMap> > GetListByIdListAsync(IEnumerable <Guid> ids, ColumnSet columnSet)
 {
     return(Task.Run(() => GetListByIdList(ids, columnSet)));
 }
 public Task <CustomControl> GetByIdAsync(Guid idCustomControl, ColumnSet columnSet)
 {
     return(Task.Run(() => GetById(idCustomControl, columnSet)));
 }
Example #39
0
 public RowToken (SQLiteVdbe statement) {
   Statement = statement;
   Columns = new ColumnSet { Row = this };
 }
 public Task <List <CustomControl> > GetListAsync(string filter, ColumnSet columnSet)
 {
     return(Task.Run(() => GetList(filter, columnSet)));
 }
Example #41
0
 public static T RetrieveByGuid <T>(this IOrganizationService service, string entityName, Guid id, ColumnSet columns)
 {
     try
     {
         var      entity = service.Retrieve(entityName, id, columns);
         object[] args   = new object[] { entity };
         return((T)Activator.CreateInstance(typeof(T), args));
     }
     catch
     {
         return(default(T));
     }
 }
Example #42
0
 public Task <List <FieldSecurityProfile> > GetListByIdListAsync(IEnumerable <Guid> ids, ColumnSet columnSet)
 {
     return(Task.Run(() => GetListByIdList(ids, columnSet)));
 }
Example #43
0
        protected Result[] PreGenerateCode(JObject data)
        {
            CSParameter entry = new CSParameter();

            DataSet ds = RunProcedureDataSet(data, "vdp_get_page_for_gen_client", "sys");

            if (ds.Tables.Count >= 2)
            {
                entry.page                  = new Page();
                entry.page.Author           = CurrentUser.RealName;
                entry.page.id               = (int)ds.Tables[0].Rows[0]["id"];
                entry.page.template_id      = (int)ds.Tables[0].Rows[0]["template_id"];
                entry.page.page_name        = (string)ds.Tables[0].Rows[0]["page_name"];
                entry.page.description      = (string)ds.Tables[0].Rows[0]["description"];
                entry.page.parent_menu_code = (string)ds.Tables[0].Rows[0]["parent_menu_code"];
                entry.page.page_name_text   = (string)ds.Tables[0].Rows[0]["page_name_text"];
                entry.page.controller_area  = (string)ds.Tables[0].Rows[0]["controller_area"];
                entry.page.controller       = (string)ds.Tables[0].Rows[0]["controller"];


                entry.page_detail = new List <PageDetail>();
                //   ds.Tables[1];

                //  entry.columns = new List<ColumnSet>();
                foreach (DataRow r in ds.Tables[1].Rows)
                {
                    PageDetail tmpPageDetail = new PageDetail();
                    //   tmpPageDetail.columns = new List<ColumnSet>();
                    tmpPageDetail.id                  = (int)r["id"];
                    tmpPageDetail.area                = (string)r["area"];
                    tmpPageDetail.table_name          = (string)r["table_name"];
                    tmpPageDetail.module_id           = (int)r["module_id"];
                    tmpPageDetail.comments            = (string)r["comments"];
                    tmpPageDetail.name_text           = (string)r["name_text"];
                    tmpPageDetail.class_name          = (string)r["class_name"];;
                    tmpPageDetail.RelatedChildenTable = (string)r["related_childen_table"];
                    tmpPageDetail.table_description   = "";
                    //  tmpPageDetail.edit_flag = (int)r["edit_flag"];
                    entry.page_detail.Add(tmpPageDetail);
                    data["page_detail_id"] = tmpPageDetail.id;
                    DataSet ds2 = RunProcedureDataSet(data, "vdp_get_page_detail_for_gen_client", "sys");
                    int     w   = 0;

                    ColumnSet cs;
                    tmpPageDetail.columns = new List <ColumnSet>();
                    foreach (DataRow r2 in ds2.Tables[0].Rows)
                    {
                        cs            = new ColumnSet();
                        cs.isInsert   = r2["is_insert"].ToString() == "0" ? false : true;
                        cs.isShow     = r2["is_show"].ToString() == "0" ? false : true;
                        cs.isUpdate   = r2["is_update"].ToString() == "0" ? false : true;
                        cs.isRequired = r2["is_required"].ToString() == "0" ? false : true;
                        cs.isWhere    = r2["is_where"].ToString() == "0" ? false : true;
                        tmpPageDetail.table_description = (string)r2["table_description"];
                        if (r2["size"].ToString() == "")
                        {
                            w = 0;
                        }
                        else
                        {
                            w = int.Parse(r2["length"].ToString()) * 10;
                        }
                        if (w > 500)
                        {
                            w = 500;
                        }
                        cs.width        = w;
                        cs.data         = (string)r2["data"];
                        cs.valid        = (string)r2["valid"];
                        cs.staticValue  = (string)r2["static_value"];
                        cs.FlagIdentity = int.Parse(r2["flag_identity"].ToString());
                        cs.FlagPrimary  = int.Parse(r2["flag_primary"].ToString());// (int)r2["flag_primary"];
                        cs.ColumnName   = (string)r2["column_name"];
                        cs.Type         = (string)r2["type"];
                        if (r2["size"].ToString() == "")
                        {
                            cs.Size = 0;
                        }
                        else
                        {
                            string tmpstr = r2["size"].ToString();
                            if (tmpstr.Length >= 5)
                            {
                                tmpstr = "50000";
                            }
                            if (int.Parse(tmpstr) > 6000)
                            {
                                cs.Size = 6000;
                            }
                            else
                            {
                                cs.Size = Int16.Parse(tmpstr);//(Int16)r2["size"];
                            }
                        }
                        if (r2["length"].ToString() == "")
                        {
                            cs.Length = 0;
                        }
                        else
                        {
                            cs.Length = int.Parse(r2["length"].ToString());// (int)r2["length"];
                        }
                        cs.htmlType           = (string)r2["html_type"];
                        cs.ColumnCaption      = (string)r2["column_caption"];
                        cs.ColumnDescription  = (string)r2["column_description"];
                        cs.RelatedParentTable = (string)r2["related_table"];
                        cs.staticValue        = (string)r2["static_value"];
                        cs.PrimaryField       = (string)r2["primary_field"];
                        if (r2["is_identity"].ToString() == "1")
                        {
                            cs.IsIdentity = true;
                        }
                        else
                        {
                            cs.IsIdentity = false;
                        }
                        tmpPageDetail.columns.Add(cs);
                    }
                }
            }



            //string p2 = Server.MapPath("\\") + "\\templates\\test2.data";

            //FileStream fs3 = new FileStream(p2, FileMode.Create);

            //BinaryFormatter bf = new BinaryFormatter();
            //bf.Serialize(fs3, entry);
            //fs3.Close();


            Result[] r3 = mycs.CreateCode(JSToken, entry);
            return(r3);
        }
 public Entity Retrieve(Entity entity, ColumnSet columnSet)
 {
     return(this.service.Retrieve(entity.LogicalName, entity.Id, columnSet));
 }
Example #45
0
        public List <string> GetEntityValidationStatus(Entity invoice, IOrganizationService service, Microsoft.Xrm.Sdk.ITracingService trace)
        {
            List <string> validationMessages = new List <string>();

            MShared       sharedMethods = new MShared();
            ContactEntity contactEntity = new ContactEntity();

            try
            {
                Entity contact = null;
                if (invoice.Attributes.Contains(InvoiceFields.Customer))
                {
                    EntityReference contactReference = invoice.GetAttributeValue <EntityReference>(InvoiceFields.Customer);

                    string[] columnsToGet = new string[] { ContactFields.IdAboxPatient, ContactFields.Country };
                    var      columnSet    = new ColumnSet(columnsToGet);
                    contact = service.Retrieve(contactEntity.EntitySingularName, contactReference.Id, columnSet);

                    if (contact != null)
                    {
                        if (!contact.Attributes.Contains(ContactFields.IdAboxPatient))
                        {
                            validationMessages.Add($"Este contacto no posee un Id de paciente Abox registrado");
                        }
                    }
                }

                if (!invoice.Attributes.Contains(InvoiceFields.Pharmacy))
                {
                    validationMessages.Add($"La farmacia es requerida.");
                }


                if (invoice.Attributes.Contains(InvoiceFields.InvoiceImageWebUrl))
                {
                    if (String.IsNullOrEmpty(invoice.GetAttributeValue <string>(InvoiceFields.InvoiceImageWebUrl)))
                    {
                        validationMessages.Add($"La imagen de la factura es requerida.");
                    }
                }
                else
                {
                    validationMessages.Add($"La imagen de la factura es requerida.");
                }

                if (invoice.Attributes.Contains(InvoiceFields.ProductsSelectedJson))
                {
                    if (String.IsNullOrEmpty(invoice.GetAttributeValue <string>(InvoiceFields.ProductsSelectedJson)))
                    {
                        validationMessages.Add($"No se han podido identificar los productos requeridos para guardar esta factura.");
                    }
                }
                else
                {
                    validationMessages.Add($"No se han podido identificar los productos requeridos para guardar esta factura.");
                }



                if (invoice.Attributes.Contains(InvoiceFields.PurchaseDate))
                {
                    DateTime date = new DateTime();
                    date = invoice.GetAttributeValue <DateTime>(InvoiceFields.PurchaseDate);
                    if (date != null)
                    {
                        DateTime today = DateTime.Now;

                        if (date > today)
                        {
                            validationMessages.Add("La fecha de la factura no puede ser mayor a la fecha actual.");
                        }
                    }
                }
                else
                {
                    validationMessages.Add($"La fecha de la factura es requerida.");
                }



                //if (invoice.Attributes.Contains(InvoiceFields.PurchaseDate))
                //{
                //    DateTime date = new DateTime();
                //    date = invoice.GetAttributeValue<DateTime>(InvoiceFields.PurchaseDate);
                //    if (date != null)
                //    {
                //        DateTime today = DateTime.Now;

                //        if (DateTime.)
                //        {

                //        }

                //    }
                //}



                return(validationMessages);
            }
            catch (Exception ex)
            {
                sharedMethods.LogPluginFeedback(new LogClass
                {
                    Exception  = ex.ToString(),
                    Level      = "error",
                    ClassName  = this.GetType().ToString(),
                    MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name,
                    Message    = $"Error validando los datos de la entidad.",
                    ProcessId  = ""
                }, trace);
                trace.Trace($"MethodName: {new StackTrace(ex).GetFrame(0).GetMethod().Name}|--|Exception: " + ex.ToString());

                throw ex;
            }
        }
        public void Execute(IServiceProvider serviceProvider)
        {
            //Create the context
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            SourceCode.Workflow.Client.Connection conn = null;
            SourceCode.Workflow.Client.ProcessInstance procInst = null;
            string K2EntityIdDataField = string.Empty;
            string K2EntityNameDataField = string.Empty;
            string K2ContextXMLDataField = string.Empty;
            Entity currentEntity = new Entity();

            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                // Obtain the target business entity from the input parameters.
                currentEntity = (Entity)context.InputParameters["Target"];
            }

            if (context.OutputParameters.Contains("id"))
            {
                EntityID = new Guid(context.OutputParameters["id"].ToString());
            }
            else if (currentEntity.Id != null)
            {
                EntityID = currentEntity.Id;
            }

            // Get K2 Associations
            #region K2 Associations

            string K2AssociationsFetchXML = Resources.K2AssociationsFetchXML.Replace("[startoption]", context.MessageName);
            K2AssociationsFetchXML = K2AssociationsFetchXML.Replace("[entityname]", currentEntity.LogicalName.ToLower());
            EntityCollection k2associations = service.RetrieveMultiple(new FetchExpression(K2AssociationsFetchXML));
            
            #endregion

            // if an K2 Association is found then get K2 Settings and start K2 process for each association
            if (k2associations.Entities.Count > 0)
            {
                // Get K2 Settings
                #region K2 Settings
                //Get Connection Settings

                EntityCollection k2settings = service.RetrieveMultiple(new FetchExpression(Resources.K2SettingsFetchXML));

                foreach (Entity setting in k2settings.Entities)
                {
                    string name = setting["k2_name"].ToString();
                    string value = setting["k2_value"].ToString();

                    switch (name)
                    {
                        case "WorkflowServerConnectionString":
                            K2WorkflowServerConnectionString = value;
                            break;
                        case "HostServerConnectionString":
                            K2HostServerConnectionString = value;
                            break;
                        case "K2ServerName":
                            K2Server = value;
                            break;
                    }
                }
                #endregion K2 Settings

                bool StartProcess = false;

                // start process for each association returned
                foreach (Entity entity in k2associations.Entities)
                {
                    StartProcess = MustStartForMessage(entity["k2_startoption"].ToString(), context.MessageName);
                    if (StartProcess)
                    {
                        if (entity.Contains("k2_processfullname"))
                        {
                            K2ProcessName = entity["k2_processfullname"].ToString();
                        }
                        if (entity.Contains("k2_entityiddatafield"))
                        {
                            K2EntityIdDataField = entity["k2_entityiddatafield"].ToString();
                        }
                        if (entity.Contains("k2_entitynamedatafield"))
                        {
                            K2EntityNameDataField = entity["k2_entitynamedatafield"].ToString();
                        }
                        if (entity.Contains("k2_contextxmldatafield"))
                        {
                            K2ContextXMLDataField = entity["k2_contextxmldatafield"].ToString();
                        }


                        #region Create XML Context
                        XmlDocument EntityDoc = null;
                        ColumnSet allColumns = new ColumnSet(true);

                        //Entity currentEntity = service.Retrieve(CRMEntityName, EntityID, allColumns);

                        Entity originatorUserEntity = service.Retrieve("systemuser", context.InitiatingUserId, allColumns);

                        XmlDocument inputDataDoc = new XmlDocument();

                        //Create instantiation data for Entity
                        EntityDoc = new XmlDocument();
                        XmlElement EntElement = EntityDoc.CreateElement("CRMContext");

                        //Create Item element
                        XmlElement xmlItem = EntityDoc.CreateElement("Context");

                        //Create Name Element
                        XmlElement xmlName = EntityDoc.CreateElement("EntityId");
                        xmlName.InnerText = EntityID.HasValue ? EntityID.Value.ToString() : "";
                        xmlItem.AppendChild(xmlName);

                        xmlName = EntityDoc.CreateElement("EntityType");
                        xmlName.InnerText = currentEntity.LogicalName;
                        xmlItem.AppendChild(xmlName);

                        XmlElement xmlOrgName = EntityDoc.CreateElement("Organization");
                        xmlOrgName.InnerText = context.OrganizationName;
                        xmlItem.AppendChild(xmlOrgName);

                        xmlName = EntityDoc.CreateElement("CRMUserId");
                        xmlName.InnerText = context.InitiatingUserId.ToString();
                        xmlItem.AppendChild(xmlName);

                        xmlName = EntityDoc.CreateElement("UserFQN");
                        xmlName.InnerText = originatorUserEntity["domainname"] != null ? originatorUserEntity["domainname"].ToString() : "";
                        xmlItem.AppendChild(xmlName);

                        xmlName = EntityDoc.CreateElement("UserDisplayName");
                        xmlName.InnerText = originatorUserEntity["fullname"] != null ? originatorUserEntity["fullname"].ToString() : "";
                        xmlItem.AppendChild(xmlName);

                        //Add Item to main doc
                        EntElement.AppendChild(xmlItem);

                        EntityDoc.AppendChild(EntElement);

                        EntElement = null;
                        xmlName = null;

                        #endregion Create XML Context

                        #region Start K2 Process

                        conn = new SourceCode.Workflow.Client.Connection();

                        try
                        {
                            //Open connection to K2 Server
                            ConnectionSetup connectSetup = new ConnectionSetup();
                            connectSetup.ConnectionString = K2WorkflowServerConnectionString;

                            conn.Open(connectSetup);

                            // impersonate as originators if domainname retrieved from CRM systemuser
                            if (originatorUserEntity != null && originatorUserEntity.Contains("domainname"))
                            {
                                if (!string.IsNullOrEmpty(originatorUserEntity["domainname"].ToString()))
                                {
                                    conn.ImpersonateUser(originatorUserEntity["domainname"].ToString());
                                }
                            }

                            //Create new process instance
                            procInst = conn.CreateProcessInstance(K2ProcessName);

                            //Set CRM context field value
                            if (!string.IsNullOrEmpty(K2ContextXMLDataField))
                            {
                                try
                                {
                                    procInst.XmlFields[K2ContextXMLDataField].Value = EntityDoc.OuterXml.ToString();
                                }
                                catch (Exception ex)
                                {
                                    System.Diagnostics.EventLog.WriteEntry("SourceCode.Logging.Extension.EventLogExtension", "K2 CRM Plugin - Entity Name - " + context.PrimaryEntityName.ToString() + " - " + "Error writing to XMLField " + K2ContextXMLDataField + " :::: " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
                                }
                            }
                            if (!string.IsNullOrEmpty(K2EntityIdDataField))
                            {
                                try
                                {
                                    procInst.DataFields[K2EntityIdDataField].Value = context.PrimaryEntityId;
                                }
                                catch (Exception ex)
                                {
                                    System.Diagnostics.EventLog.WriteEntry("SourceCode.Logging.Extension.EventLogExtension", "K2 CRM Plugin - Entity Name - " + context.PrimaryEntityName.ToString() + " - " + "Error writing to DataField " + K2EntityIdDataField + " :::: " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
                                }

                            }
                            if (!string.IsNullOrEmpty(K2EntityNameDataField))
                            {
                                try
                                {
                                    procInst.DataFields[K2EntityNameDataField].Value = context.PrimaryEntityName.ToLower();
                                }
                                catch (Exception ex)
                                {
                                    System.Diagnostics.EventLog.WriteEntry("SourceCode.Logging.Extension.EventLogExtension", "K2 CRM Plugin - Entity Name - " + context.PrimaryEntityName.ToString() + " - " + "Error writing to DataField " + K2EntityNameDataField + " :::: " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
                                }
                            }

                            conn.StartProcessInstance(procInst);
                            try
                            {
                                System.Diagnostics.EventLog.WriteEntry("SourceCode.Logging.Extension.EventLogExtension", "Process Started: " + K2ProcessName, System.Diagnostics.EventLogEntryType.Information);
                            }
                            catch { }

                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.EventLog.WriteEntry("SourceCode.Logging.Extension.EventLogExtension", "Entity Name - " + context.PrimaryEntityName.ToString() + " - " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
                            throw;
                        }
                        finally
                        {
                            if (service != null)
                                service = null;

                            if (conn != null)
                                conn.Dispose();
                            conn = null;

                            if (procInst != null)
                                procInst = null;
                            EntityDoc = null;
                        }


                        #endregion  Start K2 Process

                    }
                }
            }
        }
Example #47
0
 public Task <List <MailMergeTemplate> > GetListByIdListAsync(IEnumerable <Guid> ids, ColumnSet columnSet)
 {
     return(Task.Run(() => GetListByIdList(ids, columnSet)));
 }
Example #48
0
 public Task <List <SdkMessagePair> > GetListAsync(ColumnSet columnSet)
 {
     return(Task.Run(() => GetList(columnSet)));
 }
Example #49
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="service"></param>
        /// <param name="parentID"></param>
        /// <param name="entityName"></param>
        /// <param name="columnSet"></param>
        /// <param name="throwZeroCountException">Throw InvalidPluginException if no records were found</param></param>
        /// <returns></returns>
        public static List <Entity> GetRelatedRecords(IOrganizationService service, Guid parentID, string entityName, ColumnSet columnSet, bool throwZeroCountException)
        {
            List <Entity> result = new List <Entity>();

            QueryExpression exp = new QueryExpression(entityName)
            {
                NoLock    = true,
                ColumnSet = columnSet
            };

            exp.Criteria.AddCondition("statecode", ConditionOperator.Equal, 0); //Active

            var coll = service.RetrieveMultiple(exp);

            if (coll != null && coll.Entities != null && coll.Entities.Count > 0)
            {
                result = coll.Entities.ToList();
            }

            if (result.Count < 1 && throwZeroCountException)
            {
                throw new InvalidPluginExecutionException(string.Format("Unable to fetch child entity records records for entity {0} ", entityName));
            }

            return(result);
        }
Example #50
0
 private EntityCollection getMappings(Entity def, IOrganizationService service)
 {
     var epmappings = new QueryExpression("new_emailparsermapping");
         var cols = new ColumnSet("new_emailstring", "new_crmfieldname", "new_emailstringdelimiter");
         epmappings.ColumnSet = cols;
         epmappings.Criteria.AddCondition( new ConditionExpression("new_definition", 0, def["new_emailparserdefinitionid"]));
         var result = service.RetrieveMultiple(epmappings);
         return result;
 }
Example #51
0
 public Task <List <SdkMessagePair> > GetListByMessageAsync(Guid idMessage, ColumnSet columnSet)
 {
     return(Task.Run(() => GetListByRequest(idMessage, columnSet)));
 }
 public static bool IsEqual(this ColumnSet cs, ColumnSet columnSet)
 {
     return new ColumnSetComparer().Equals(cs, columnSet);
 }
Example #53
0
 public Task <SdkMessagePair> GetByIdAsync(Guid idSdkMessagePair, ColumnSet columnSet)
 {
     return(Task.Run(() => GetById(idSdkMessagePair, columnSet)));
 }
Example #54
0
        /// <summary>
        /// This method is used to get attributes from a specified entity. It returns Dictionary containing all the required attributes values.
        /// </summary>
        /// <param name="entityGuid">GUID of the entity</param>
        /// <param name="entityName_">The entity name type (contact,lead,...)</param>
        ///<param name="entityAttributes">The ArrayList containing the attributes names types you want to retrieve (firstname,lastname,...)</param>
        public Dictionary<string, string> getEntity(Guid entityGuid, string entityName_, ArrayList entityAttributes)
        {
            Dictionary<string, string> arrayData = new Dictionary<string, string>();
            try
            {
                isconnected();

                ArrayList arrayResults = new ArrayList();
                // Create the retrieve target.
                TargetRetrieveDynamic targetRetrieve = new TargetRetrieveDynamic();

                // Set the properties of the target.
                targetRetrieve.EntityName = entityName_;
                targetRetrieve.EntityId = entityGuid;

                // Create the request object.
                RetrieveRequest retrieve = new RetrieveRequest();
                ColumnSet col = new ColumnSet();

                // Set the properties of the request object.
                retrieve.Target = targetRetrieve;
                for (int i = 0; i < entityAttributes.Count; i++)
                {
                    col.AddColumn(entityAttributes[i].ToString());
                }

                retrieve.ColumnSet = col;

                // Indicate that the BusinessEntity should be retrieved as a
                // DynamicEntity.
                retrieve.ReturnDynamicEntities = true;

                // Execute the request.
                RetrieveResponse retrieved = (RetrieveResponse)m_crmService.Execute(retrieve);

                // Extract the DynamicEntity from the request.
                DynamicEntity entity = (DynamicEntity)retrieved.BusinessEntity;

                Microsoft.Crm.Sdk.CrmDateTime crmDateTimeVar = new Microsoft.Crm.Sdk.CrmDateTime();
                Microsoft.Crm.Sdk.CrmNumber crmNumberVar = new Microsoft.Crm.Sdk.CrmNumber();
                Picklist crmPickList = new Picklist();
                Guid crmGuid = new Guid();
                Microsoft.Crm.Sdk.Key keyVar = new Microsoft.Crm.Sdk.Key();
                Lookup lookupVar = new Lookup();
                Microsoft.Crm.Sdk.CrmBoolean boolVar = new Microsoft.Crm.Sdk.CrmBoolean();
                for (int i = 0; i < entityAttributes.Count; i++)
                {
                    if (entity.Properties.Contains(entityAttributes[i].ToString()))
                    {
                        if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(crmDateTimeVar.GetType()))
                        {
                            crmDateTimeVar = (Microsoft.Crm.Sdk.CrmDateTime)entity.Properties[entityAttributes[i].ToString()];
                            arrayData.Add(entityAttributes[i].ToString(),crmDateTimeVar.date.ToString());
                        }
                        else
                        {
                            if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(crmNumberVar.GetType()))
                            {
                                crmNumberVar = (Microsoft.Crm.Sdk.CrmNumber)entity.Properties[entityAttributes[i].ToString()];
                                arrayData.Add(entityAttributes[i].ToString(), crmNumberVar.Value.ToString());
                            }
                            else
                            {
                                if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(keyVar.GetType()))
                                {
                                    keyVar = (Microsoft.Crm.Sdk.Key)entity.Properties[entityAttributes[i].ToString()];
                                    arrayData.Add(entityAttributes[i].ToString(), keyVar.Value.ToString());
                                }
                                else
                                {
                                    if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(lookupVar.GetType()))
                                    {
                                        lookupVar = (Microsoft.Crm.Sdk.Lookup)entity.Properties[entityAttributes[i].ToString()];
                                        arrayData.Add(entityAttributes[i].ToString(), lookupVar.Value.ToString());
                                    }
                                    else
                                    {
                                        if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(boolVar.GetType()))
                                        {
                                            boolVar = (Microsoft.Crm.Sdk.CrmBoolean)entity.Properties[entityAttributes[i].ToString()];
                                            arrayData.Add(entityAttributes[i].ToString(), boolVar.Value.ToString());
                                        }
                                        else
                                        {
                                            if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(crmPickList.GetType()))
                                            {
                                                crmPickList = (Microsoft.Crm.Sdk.Picklist)entity.Properties[entityAttributes[i].ToString()];
                                                arrayData.Add(entityAttributes[i].ToString(), crmPickList.Value.ToString());
                                            }
                                            else
                                            {
                                                if (entity.Properties[entityAttributes[i].ToString()].GetType().Equals(crmGuid.GetType()))
                                                {
                                                    crmGuid = (Guid)entity.Properties[entityAttributes[i].ToString()];
                                                    arrayData.Add(entityAttributes[i].ToString(), crmGuid.ToString());
                                                }
                                                else
                                                {
                                                    arrayData.Add(entityAttributes[i].ToString(), entity.Properties[entityAttributes[i].ToString()].ToString());
                                                }

                                            }

                                        }
                                    }
                                }

                            }
                        }

                    }
                    else
                    {
                        arrayData.Add(entityAttributes[i].ToString(), "");
                    }
                }
                return arrayData;
            }
            catch (SoapException ex)
            {
                throw new InvalidPluginExecutionException("!SoapException!\n" + ex.Detail.SelectSingleNode("//description").InnerText);
            }
            catch (Exception ex)
            {
                throw new ESC_CRM_EX.getEntityException(ex.Message, entityName_, entityGuid);
            }
        }
 public Entity Retrieve(string entityName, Guid entityId, ColumnSet columnSet)
 {
     return(this.service.Retrieve(entityName, entityId, columnSet));
 }
Example #56
0
        /// <summary>
        /// This method is used to find a record and return the GUID of records matching the criteria
        /// </summary>
        /// <param name="entityName_">CRM name of the entity you want to look for</param>
        /// <param name="primarykeyName">The attribute name containing the GUID for the entity (contactid,campaignid,...) that will be returned in an array</param>
        ///<param name="stringParams">The ArrayList containing the attributes names and their values. The research only work with string type attributes. You can use % to replace characters. A logical AND is used to concatenate the parameters in the search</param>
        public ArrayList findEntity(string entityName_, string primarykeyName, ArrayList stringParams, string attribute_order)
        {
            ArrayList arrayResults = new ArrayList();
            try
            {
                isconnected();

                ColumnSet cols = new ColumnSet();
                createStringConditionExpression(stringParams);
                cols.Attributes.Add(primarykeyName);

                m_filterExpression.FilterOperator = LogicalOperator.And;
                OrderExpression oe = new OrderExpression();
                oe.AttributeName = attribute_order;
                oe.OrderType = OrderType.Descending;
                QueryExpression query = new QueryExpression();
                query.EntityName = entityName_;
                query.ColumnSet = cols;
                query.Criteria = m_filterExpression;
                query.Orders.Add(oe);

                RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
                retrieve.Query = query;
                retrieve.ReturnDynamicEntities = true;

                RetrieveMultipleResponse retrieved = (RetrieveMultipleResponse)m_crmService.Execute(retrieve);
                int i = 0;
                foreach (DynamicEntity rec in retrieved.BusinessEntityCollection.BusinessEntities)
                {
                    Microsoft.Crm.Sdk.Key sp = (Microsoft.Crm.Sdk.Key)rec.Properties[primarykeyName];
                    arrayResults.Add(sp.Value);
                    i++;
                }
                if (i == 0) throw new entitynotfoundException();
                return arrayResults;
            }
            catch (SoapException ex)
            {
                throw new InvalidPluginExecutionException("!SoapException!\n" + ex.Detail.SelectSingleNode("//description").InnerText);
            }
            catch (entitynotfoundException)
            {
                throw new entitynotfoundException();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Example #57
0
        public bool campaignExists(string campaignID)
        {
            try
            {
                isconnected();

                ArrayList arrayResults = new ArrayList();
                // Create the retrieve target.
                TargetRetrieveDynamic targetRetrieve = new TargetRetrieveDynamic();

                // Set the properties of the target.
                targetRetrieve.EntityName = "campaign";
                targetRetrieve.EntityId = new Guid(campaignID);

                // Create the request object.
                RetrieveRequest retrieve = new RetrieveRequest();
                ColumnSet col = new ColumnSet();

                // Set the properties of the request object.
                retrieve.Target = targetRetrieve;
                col.AddColumn("name");

                retrieve.ColumnSet = col;

                // Indicate that the BusinessEntity should be retrieved as a
                // DynamicEntity.
                retrieve.ReturnDynamicEntities = true;

                // Execute the request.
                RetrieveResponse retrieved = (RetrieveResponse)m_crmService.Execute(retrieve);

                // Extract the DynamicEntity from the request.
                DynamicEntity entity = (DynamicEntity)retrieved.BusinessEntity;
                if (entity.Properties["name"].Equals(null)) return false;
                return true;
             }
            catch (Exception)
            {
                return false;
            }
        }
Example #58
0
        //<snippetCRUDOperations1>
        /// <summary>
        /// This method performs entity create, retrieve, and update operations.
        /// The delete operation is handled in the DeleteRequiredrecords() method.
        /// </summary>
        /// <param name="serviceProxy">An established connection to the Organization web service.</param>
        /// <param name="records">A collection of entity records created by this sample.</param>
        public void Run(OrganizationServiceProxy serviceProxy, EntityReferenceCollection records)
        {
            // Enable early-bound entity types. This enables use of IntelliSense in Visual Studio
            // and avoids spelling errors in attribute names when using the Entity property bag.
            serviceProxy.EnableProxyTypes();

            // Here we will use the interface instead of the proxy object.
            IOrganizationService service = (IOrganizationService)serviceProxy;

            // Display information about the logged on user.
            Guid userid = ((WhoAmIResponse)service.Execute(new WhoAmIRequest())).UserId;
            SystemUser systemUser = (SystemUser)service.Retrieve("systemuser", userid,
                new ColumnSet(new string[] { "firstname", "lastname" }));
            Console.WriteLine("Logged on user is {0} {1}.", systemUser.FirstName, systemUser.LastName);

            // Retrieve the version of Microsoft Dynamics CRM.
            RetrieveVersionRequest versionRequest = new RetrieveVersionRequest();
            RetrieveVersionResponse versionResponse =
                (RetrieveVersionResponse)service.Execute(versionRequest);
            Console.WriteLine("Microsoft Dynamics CRM version {0}.", versionResponse.Version);

            //<snippetCRUDOperations2>
            // Instantiate an account object. Note the use of the option set enumerations defined
            // in OptionSets.cs.
            Account account = new Account { Name = "Fourth Coffee" };
            account.AccountCategoryCode = new OptionSetValue((int)AccountAccountCategoryCode.PreferredCustomer);
            account.CustomerTypeCode = new OptionSetValue((int)AccountCustomerTypeCode.Investor);

            // Create an account record named Fourth Coffee.
            // Save the record reference so we can delete it during cleanup later.
            Guid accountId = service.Create(account);
            //</snippetCRUDOperations2>
            var eref = new EntityReference(Account.EntityLogicalName, accountId);
            eref.Name = account.Name;
            records.Add(eref);

            Console.Write("{0} {1} created, ", account.LogicalName, account.Name);

            // Retrieve the account containing several of its attributes. This results in
            // better performance compared to retrieving all attributes.
            ColumnSet cols = new ColumnSet(
                new String[] { "name", "address1_postalcode", "lastusedincampaign" });

            Account retrievedAccount = (Account)service.Retrieve("account", accountId, cols);
            Console.Write("retrieved, ");

            // Update the postal code attribute.
            retrievedAccount.Address1_PostalCode = "98052";

            // There is no address 2 postal code needed.
            retrievedAccount.Address2_PostalCode = null;

            // Shows use of a Money value.
            retrievedAccount.Revenue = new Money(5000000);

            // Shows use of a Boolean value.
            retrievedAccount.CreditOnHold = false;

            // Update the account record.
            service.Update(retrievedAccount);
            Console.WriteLine("and updated.");
        }
Example #59
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Create a queue record.
        /// Create a letter record.
        /// Create a queue item for queue record.
        /// Retrieves new owner's details. 
        /// Update the queue item record to assign it to new owner.
        /// </summary>
        public void CreateRequiredRecords()
        {
            // Create a private queue instance and set its property values.
            Queue newQueue = new Queue
            {
                Name = "Example Queue.",
                Description = "This is an example queue.",
                QueueViewType = new OptionSetValue((int)QueueQueueViewType.Private)
            };

            // Create a new queue and store its returned GUID in a variable 
            // for later use.
            _queueId = _serviceProxy.Create(newQueue);

            Console.WriteLine("Created {0}.", newQueue.Name);

            Letter newLetter = new Letter
            {
                Description = "Example Letter"
            };

            _letterId = _serviceProxy.Create(newLetter);

            Console.WriteLine("Created {0}.", newLetter.Description);

            // Create a new instance of a queueitem and initialize its 
            // properties.
            QueueItem item = new QueueItem
            {
                QueueId = new EntityReference(Queue.EntityLogicalName, _queueId),
                ObjectId = new EntityReference(Letter.EntityLogicalName, _letterId)
            };

            // Create the queueitem on the server, which will associate 
            // the letter with the queue.
            _queueItemId = _serviceProxy.Create(item);

            Console.WriteLine("Created the letter queue item for the queue.");

            //<snippetRemoveQueueItemWorker2>
            // Retrieve the user information.
            WhoAmIRequest whoAmIRequest = new WhoAmIRequest();
            WhoAmIResponse whoAmIResponse = (WhoAmIResponse)_serviceProxy.Execute(
                whoAmIRequest);

            ColumnSet columnSet = new ColumnSet("fullname");
            SystemUser currentUser = (SystemUser)_serviceProxy.Retrieve(
                SystemUser.EntityLogicalName,
                whoAmIResponse.UserId, columnSet);
            String currentUserName = currentUser.FullName;
            //</snippetRemoveQueueItemWorker2>

            // Create an instance of an existing queueitem in order to specify 
            // the user that will be working on it.
            QueueItem queueItem = new QueueItem
            {
                QueueItemId = _queueItemId,
                WorkerId = new EntityReference(SystemUser.EntityLogicalName,
                    whoAmIResponse.UserId)
            };

            _serviceProxy.Update(queueItem);

            Console.WriteLine("The letter queue item is queued for new owner {0}.",
                currentUserName);

            return;
        }
Example #60
-1
        /// <summary>
        /// Demonstrates how to programmatically execute a workflow.
        /// </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 = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    OrganizationServiceContext _orgContext = new OrganizationServiceContext(_serviceProxy);

                    CreateRequiredRecords();

                    //<snippetExecuteWorkflow1>
                    // Create an ExecuteWorkflow request.
                    ExecuteWorkflowRequest request = new ExecuteWorkflowRequest()
                    {
                        WorkflowId = _workflowId,
                        EntityId = _leadId
                    };
                    Console.Write("Created ExecuteWorkflow request, ");

                    // Execute the workflow.
                    ExecuteWorkflowResponse response =
                        (ExecuteWorkflowResponse)_serviceProxy.Execute(request);
                    Console.WriteLine("and sent request to service.");

                    //</snippetExecuteWorkflow1>

                    #region Check success

                    ColumnSet cols = new ColumnSet("statecode");
                    QueryByAttribute retrieveOpQuery = new QueryByAttribute();
                    retrieveOpQuery.EntityName = AsyncOperation.EntityLogicalName;
                    retrieveOpQuery.ColumnSet = cols;
                    retrieveOpQuery.AddAttributeValue("asyncoperationid", response.Id);

                    // Wait for the asyncoperation to complete.
                    // (wait no longer than 1 minute)
                    for (int i = 0; i < 60; i++)
                    {
                        System.Threading.Thread.Sleep(1000);

                        EntityCollection retrieveOpResults =
                            _serviceProxy.RetrieveMultiple(retrieveOpQuery);

                        if (retrieveOpResults.Entities.Count() > 0)
                        {
                            AsyncOperation op =
                                (AsyncOperation)retrieveOpResults.Entities[0];
                            if (op.StateCode == AsyncOperationState.Completed)
                            {
                                _asyncOperationId = op.AsyncOperationId.Value;
                                Console.WriteLine("AsyncOperation completed successfully.");
                                break;
                            }
                        }

                        if (i == 59)
                        {
                            throw new TimeoutException("AsyncOperation failed to complete in under one minute.");
                        }
                    }

                    // Retrieve the task that was created by the workflow.
                    cols = new ColumnSet("activityid");
                    QueryByAttribute retrieveActivityQuery = new QueryByAttribute();
                    retrieveActivityQuery.EntityName = PhoneCall.EntityLogicalName;
                    retrieveActivityQuery.ColumnSet = cols;
                    retrieveActivityQuery.AddAttributeValue("subject", "First call to Diogo Andrade");
                    
                    EntityCollection results = 
                        _serviceProxy.RetrieveMultiple(retrieveActivityQuery);

                    if (results.Entities.Count() == 0)
                    {
                        throw new InvalidOperationException("Phone call activity was not successfully created");
                    }
                    else
                    {
                        Console.WriteLine("Phone call activity successfully created from workflow.");
                    }

                    #endregion Check success

                    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;
            }
        }