예제 #1
0
        /// <summary>
        /// This is native CRM behavior, to copy the content from Parent to Child record, using the Relationship ‘Mappings’ to avoid the overhead of manual data entry on child record.
        /// </summary>
        /// <param name="service"></param>
        /// <param name="accountId"></param>
        /// <param name="firstName"></param>
        /// <param name="lastName"></param>
        /// <see cref="https://rajeevpentyala.com/2017/01/26/create-a-child-record-by-copying-mapping-fields-from-parent-using-crm-sdk/"/>
        /// <returns></returns>
        public Guid CreateRecordFromAccount(IOrganizationService service, Guid accountId, string firstName, string lastName)
        {
            InitializeFromRequest initialize = new InitializeFromRequest
            {
                // Set the target entity (i.e.,Contact)
                TargetEntityName = "contact",

                // Create the EntityMoniker of Source (i.e.,Account)
                EntityMoniker = new EntityReference("account", accountId)
            };



            // Execute the request
            InitializeFromResponse initialized = (InitializeFromResponse)service.Execute(initialize);

            // Read Intitialized entity (i.e.,Contact with copied attributes from Account)
            if (initialized.Entity != null)
            {
                // Get entContact from the response
                var entContact = initialized.Entity;

                // Set the additional attributes of the Contact
                entContact.Attributes.Add("firstname", firstName);
                entContact.Attributes.Add("lastname", lastName);

                // Create a new contact
                return(service.Create(entContact));
            }
            else
            {
                return(new Guid());
            }
        }
예제 #2
0
        public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx)
        {
            var req = request as InitializeFromRequest;

            if (req == null)
            {
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), "Cannot execute InitializeFromRequest without the request");
            }

            //TODO: Implement logic to filter mapping attributes based on the req.TargetFieldType
            if (req.TargetFieldType != TargetFieldType.All)
            {
                throw PullRequestException.PartiallyNotImplementedOrganizationRequest(req.GetType(), "logic for filtering attributes based on TargetFieldType other than All is missing");
            }

            var service          = ctx.GetOrganizationService();
            var fetchXml         = string.Format(FetchMappingsByEntity, req.EntityMoniker.LogicalName, req.TargetEntityName);
            var mapping          = service.RetrieveMultiple(new FetchExpression(fetchXml));
            var sourceAttributes = mapping.Entities.Select(a => a.GetAttributeValue <AliasedValue>("attributemap.sourceattributename").Value.ToString()).ToArray();
            var columnSet        = sourceAttributes.Length == 0 ? new ColumnSet(true) : new ColumnSet(sourceAttributes);
            var source           = service.Retrieve(req.EntityMoniker.LogicalName, req.EntityMoniker.Id, columnSet);

            var entity = new Entity
            {
                LogicalName = req.TargetEntityName,
                Id          = Guid.NewGuid()
            };

            if (mapping.Entities.Count > 0)
            {
                foreach (var attr in source.Attributes)
                {
                    var mappingEntity = mapping.Entities.FirstOrDefault(e => e.GetAttributeValue <AliasedValue>("attributemap.sourceattributename").Value.ToString() == attr.Key);
                    if (mappingEntity == null)
                    {
                        continue;
                    }
                    var targetAttribute = mappingEntity.GetAttributeValue <AliasedValue>("attributemap.targetattributename").Value.ToString();
                    entity[targetAttribute] = attr.Value;
                }
            }

            var response = new InitializeFromResponse
            {
                Results =
                {
                    ["Entity"] = entity
                }
            };

            return(response);
        }
예제 #3
0
        /// <summary>
        /// This method first creates an account and a lead, then initializes a new
        /// account from the already existing account and a new opportunity from the
        /// already existing lead.
        /// </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();

                    CreateRequiredRecords();


                    #region Initialize Account from Account
                    Console.WriteLine();
                    Console.WriteLine("  Initializing new Account from the initial Account");

                    // Create the request object
                    InitializeFromRequest initialize = new InitializeFromRequest();

                    // Set the properties of the request object
                    initialize.TargetEntityName = Account.EntityLogicalName.ToString();

                    // Create the EntityMoniker
                    initialize.EntityMoniker = _initialAccount.ToEntityReference();

                    // Execute the request
                    InitializeFromResponse initialized =
                        (InitializeFromResponse)_serviceProxy.Execute(initialize);

                    if (initialized.Entity != null)
                    {
                        Console.WriteLine("  New Account initialized successfully");
                    }

                    Console.WriteLine();
                    #endregion

                    #region Initialize Opportunity from Lead
                    Console.WriteLine("  Initializing an Opportunity from the initial Lead");

                    // Create the request object
                    initialize.TargetEntityName = Opportunity.EntityLogicalName.ToString();

                    // Create the EntityMoniker
                    initialize.EntityMoniker = _initialLead.ToEntityReference();

                    // Execute the request
                    initialized =
                        (InitializeFromResponse)_serviceProxy.Execute(initialize);

                    if (initialized.Entity != null & amp; &amp;
                        initialized.Entity.LogicalName == Opportunity.EntityLogicalName)
                    {
                        var opportunity = (Opportunity)initialized.Entity;
                        Console.WriteLine("  New Opportunity initialized successfully (Name={0})",
                                          opportunity.Name);
                    }
                    #endregion

                    DeleteRequiredRecords(promptforDelete);
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
        public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx)
        {
            var req = request as InitializeFromRequest;

            if (req == null)
            {
                throw new FaultException <OrganizationServiceFault>(new OrganizationServiceFault(), "Cannot execute InitializeFromRequest without the request");
            }

            //TODO: Implement logic to filter mapping attributes based on the req.TargetFieldType
            if (req.TargetFieldType != TargetFieldType.All)
            {
                throw PullRequestException.PartiallyNotImplementedOrganizationRequest(req.GetType(), "logic for filtering attributes based on TargetFieldType other than All is missing");
            }

            var service          = ctx.GetOrganizationService();
            var fetchXml         = string.Format(FetchMappingsByEntity, req.EntityMoniker.LogicalName, req.TargetEntityName);
            var mapping          = service.RetrieveMultiple(new FetchExpression(fetchXml));
            var sourceAttributes = mapping.Entities.Select(a => a.GetAttributeValue <AliasedValue>("attributemap.sourceattributename").Value.ToString()).ToArray();
            var columnSet        = sourceAttributes.Length == 0 ? new ColumnSet(true) : new ColumnSet(sourceAttributes);
            var source           = service.Retrieve(req.EntityMoniker.LogicalName, req.EntityMoniker.Id, columnSet);

            // If we are using proxy types, and the appropriate proxy type is found in
            // the assembly create an instance of the appropiate class
            // Othersise return a simple Entity
            Entity entity = new Entity
            {
                LogicalName = req.TargetEntityName,
                Id          = Guid.Empty
            };

            if (ctx.ProxyTypesAssembly != null)
            {
                var subClassType = ctx.FindReflectedType(req.TargetEntityName);
                if (subClassType != null)
                {
                    var instance = Activator.CreateInstance(subClassType);
                    entity = (Entity)instance;
                }
            }

            if (mapping.Entities.Count > 0)
            {
                foreach (var attr in source.Attributes)
                {
                    var mappingEntity = mapping.Entities.FirstOrDefault(e => e.GetAttributeValue <AliasedValue>("attributemap.sourceattributename").Value.ToString() == attr.Key);
                    if (mappingEntity == null)
                    {
                        continue;
                    }
                    var targetAttribute = mappingEntity.GetAttributeValue <AliasedValue>("attributemap.targetattributename").Value.ToString();
                    entity[targetAttribute] = attr.Value;

                    var isEntityReference = string.Equals(attr.Key, source.LogicalName + "id", StringComparison.CurrentCultureIgnoreCase);
                    if (isEntityReference)
                    {
                        entity[targetAttribute] = new EntityReference(source.LogicalName, (Guid)attr.Value);
                    }
                    else
                    {
                        entity[targetAttribute] = attr.Value;
                    }
                }
            }

            var response = new InitializeFromResponse
            {
                Results =
                {
                    ["Entity"] = entity
                }
            };

            return(response);
        }
        [STAThread] // Required to support the interactive login experience
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    // Create any entity records that the demonstration code requires
                    SetUpSample(service);
                    #region Demonstrate

                    Console.WriteLine();
                    Console.WriteLine(" Initializing new Account from the initial Account");

                    // Create the request object
                    var initialize = new InitializeFromRequest();

                    // Set the properties of the request object
                    initialize.TargetEntityName = Account.EntityLogicalName.ToString();

                    // Create the EntityMoniker
                    initialize.EntityMoniker = _initialAccount.ToEntityReference();

                    // Execute the request
                    InitializeFromResponse initialized =
                        (InitializeFromResponse)service.Execute(initialize);

                    if (initialized.Entity != null)
                    {
                        Console.WriteLine("  New Account initialized successfully");
                    }

                    Console.WriteLine();

                    Console.WriteLine("  Initializing an Opportunity from the initial Lead");

                    // Create the request object
                    initialize.TargetEntityName = Opportunity.EntityLogicalName.ToString();

                    // Create the EntityMoniker
                    initialize.EntityMoniker = _initialLead.ToEntityReference();

                    // Execute the request
                    initialized =
                        (InitializeFromResponse)service.Execute(initialize);

                    if (initialized.Entity != null &&
                        initialized.Entity.LogicalName == Opportunity.EntityLogicalName)
                    {
                        var opportunity = (Opportunity)initialized.Entity;
                        Console.WriteLine("  New Opportunity initialized successfully (Name={0})",
                                          opportunity.Name);
                    }

                    #endregion Demonstrate

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }
            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }