Exemplo n.º 1
0
        private OrganizationResponse CallOrganizationServiceRequestForExecuteRequest(OrganizationRequest request)
        {
            OrganizationResponse response = null;
            var associate = request as AssociateRequest;

            if (associate != null)
            {
                response = new AssociateResponse();
                Associate(associate.Target.LogicalName, associate.Target.Id, associate.Relationship, associate.RelatedEntities);
            }

            var create = request as CreateRequest;

            if (create != null)
            {
                response       = new CreateResponse();
                response["id"] = Create(create.Target);
            }

            var delete = request as DeleteRequest;

            if (delete != null)
            {
                response = new DeleteResponse();
                Delete(delete.Target.LogicalName, delete.Target.Id);
            }

            var disassociate = request as DisassociateRequest;

            if (disassociate != null)
            {
                response = new AssociateResponse();
                Disassociate(disassociate.Target.LogicalName, disassociate.Target.Id, disassociate.Relationship, disassociate.RelatedEntities);
            }

            var retrieve = request as RetrieveRequest;

            if (retrieve != null)
            {
                response           = new RetrieveResponse();
                response["Entity"] = Retrieve(retrieve.Target.LogicalName, retrieve.Target.Id, retrieve.ColumnSet);
            }

            var retrieveMultiple = request as RetrieveMultipleRequest;

            if (retrieveMultiple != null)
            {
                response = new RetrieveMultipleResponse();
                response["EntityCollection"] = RetrieveMultiple(retrieveMultiple.Query);
            }

            var update = request as UpdateRequest;

            if (update != null)
            {
                response = new UpdateResponse();
                Update(update.Target);
            }
            return(response);
        }
Exemplo n.º 2
0
        private AssociateResponse HandleAssociate(OrganizationRequest orgRequest, EntityReference userRef)
        {
            var request = MakeRequest <AssociateRequest>(orgRequest);
            var resp    = new AssociateResponse();

            dataMethods.Associate(request.Target, request.Relationship, request.RelatedEntities, userRef);
            return(resp);
        }
        private AssociateResponse AssociateInternal(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)
        {
            if (!relatedEntities.Any())
            {
                throw new ArgumentException("Must contain at least one related entity!", nameof(relatedEntities));
            }

            if (relatedEntities.Any(e => e.LogicalName != relatedEntities.First().LogicalName))
            {
                throw new NotImplementedException("Don't currently Support different Entity Types for related Entities!");
            }

            if (relationship.PrimaryEntityRole.GetValueOrDefault(EntityRole.Referenced) == EntityRole.Referencing)
            {
                throw new NotImplementedException("Referencing Not Currently Implemented");
            }

            var response = new AssociateResponse();

            if (Info.ManyToManyAssociationProvider.IsManyToManyRelationship(relationship.SchemaName))
            {
                var originalValue = EnforceValidForOperationCheck;
                EnforceValidForOperationCheck = false;
                try
                {
                    response["CreatedIds"] = Info.ManyToManyAssociationProvider.CreateAssociation(Service, entityName, entityId, relationship, relatedEntities);
                }
                finally
                {
                    EnforceValidForOperationCheck = originalValue;
                }
            }
            else if (EntityHelper.IsTypeDefined(Info.EarlyBoundEntityAssembly, Info.EarlyBoundNamespace, relationship.SchemaName))
            {
                var referencedIdName  = EntityHelper.GetIdAttributeName(entityName);
                var referencingIdName = EntityHelper.GetIdAttributeName(relatedEntities.First().LogicalName);
                if (referencedIdName == referencingIdName)
                {
                    referencedIdName  += "one";
                    referencingIdName += "two";
                }

                Associate1ToN(entityId, relationship, relatedEntities, referencedIdName, referencingIdName);
            }
            else
            {
                throw new NotImplementedException($"No entity found with logical name '{relationship.SchemaName}' for 1:N relationship!  {Info.ManyToManyAssociationProvider.GetNotFoundErrorMessage()}");
            }
            return(response);
        }
        private OrganizationResponse CallOrganizationServiceRequestForExecuteRequest(OrganizationRequest request)
        {
            OrganizationResponse response = null;

            if (request is AssociateRequest associate)
            {
                response = new AssociateResponse();
                Associate(associate.Target.LogicalName, associate.Target.Id, associate.Relationship, associate.RelatedEntities);
            }

            if (request is CreateRequest create)
            {
                response = new CreateResponse {
                    ["id"] = Create(create.Target)
                };
            }

            if (request is DeleteRequest delete)
            {
                response = new DeleteResponse();
                Delete(delete.Target.LogicalName, delete.Target.Id);
            }

            if (request is DisassociateRequest disassociate)
            {
                response = new AssociateResponse();
                Disassociate(disassociate.Target.LogicalName, disassociate.Target.Id, disassociate.Relationship, disassociate.RelatedEntities);
            }

            if (request is RetrieveRequest retrieve)
            {
                response = new RetrieveResponse {
                    ["Entity"] = Retrieve(retrieve.Target.LogicalName, retrieve.Target.Id, retrieve.ColumnSet)
                };
            }

            if (request is RetrieveMultipleRequest retrieveMultiple)
            {
                response = new RetrieveMultipleResponse {
                    ["EntityCollection"] = RetrieveMultiple(retrieveMultiple.Query)
                };
            }

            if (request is UpdateRequest update)
            {
                response = new UpdateResponse();
                Update(update.Target);
            }
            return(response);
        }
Exemplo n.º 5
0
 public static void AddRelated(Entity PrimaryEntity, EntityCollection RelatedEntities, string RelationshipName, CrmConnection connection = null)
 {
     using (CrmOrganizationServiceContext service = new CrmOrganizationServiceContext(connection ?? XrmConnection.Connection))
     {
         EntityReferenceCollection col = new EntityReferenceCollection();
         foreach (Entity ent in RelatedEntities.Entities)
         {
             col.Add(ent.ToEntityReference());
         }
         AssociateRequest request = new AssociateRequest()
         {
             Target          = PrimaryEntity.ToEntityReference(),
             RelatedEntities = col,
             Relationship    = new Relationship(RelationshipName)
         };
         AssociateResponse response = (AssociateResponse)service.Execute(request);
     }
 }
Exemplo n.º 6
0
        public void CreateMultiEntityAssociationTest()
        {
            Mock <IOrganizationService> orgSvc = null;
            Mock <MoqHttpMessagehander> fakHttpMethodHander = null;
            ServiceClient cli = null;

            testSupport.SetupMockAndSupport(out orgSvc, out fakHttpMethodHander, out cli);


            AssociateResponse associateEntitiesResponse = new AssociateResponse();

            orgSvc.Setup(f => f.Execute(It.IsAny <AssociateRequest>())).Returns(associateEntitiesResponse);

            Guid        accountId = Guid.NewGuid();
            Guid        contactId = Guid.NewGuid();
            List <Guid> lst       = new List <Guid>();

            lst.Add(accountId);
            lst.Add(contactId);
            bool result = cli.CreateMultiEntityAssociation("account", contactId, "contact", lst, "some rel");

            Assert.True(result);
        }
        public ExecuteTransactionResponse GetTransactionResponse(ExecuteTransactionRequest request)
        {
            var requestDictionary = new Dictionary <int, string>();

            var batchid          = "batch_" + Guid.NewGuid().ToString();
            var batchContent     = new MultipartContent("mixed", batchid);
            var changesetID      = "changeset_" + Guid.NewGuid().ToString();
            var changeSetContent = new MultipartContent("mixed", changesetID);

            for (int contentId = 1; contentId <= request.Requests.Count; contentId++)
            {
                HttpMessageContent content = new HttpMessageContent(GetRequestMessage((OrganizationRequest)request.Requests[contentId - 1]));
                content.Headers.Remove("Content-Type");
                content.Headers.TryAddWithoutValidation("Content-Type", "application/http");
                content.Headers.TryAddWithoutValidation("Content-Transfer-Encoding", "binary");
                content.Headers.TryAddWithoutValidation("Content-ID", contentId.ToString());
                changeSetContent.Add(content);
                requestDictionary.Add(contentId, ((OrganizationRequest)request.Requests[contentId - 1]).RequestName);
            }

            batchContent.Add(changeSetContent);

            var batchRequest = new HttpRequestMessage(HttpMethod.Post, _endpoint + "$batch")
            {
                Content = batchContent
            };

            var batchstring = batchRequest.Content.ReadAsStringAsync();

            var httpClient = new HttpClient(new HttpClientHandler {
                Credentials = _credential ?? CredentialCache.DefaultNetworkCredentials
            });
            var response = httpClient.SendAsync(batchRequest)?.Result;

            if (response == null)
            {
                throw new Exception("Сервер вернул пустой ответ");
            }

            if (!response.IsSuccessStatusCode)
            {
                var exception = JsonSerializer.Deserialize <CrmException>(response.Content.ReadAsStringAsync().Result);
                throw new CrmException(exception.Error.Message, exception);
            }

            var responseString = response.Content.ReadAsStringAsync();
            MultipartMemoryStreamProvider batchStream = response.Content.ReadAsMultipartAsync().Result;
            var batchStreamContent = batchStream.Contents.FirstOrDefault();

            MultipartMemoryStreamProvider changesetStream = batchStreamContent.ReadAsMultipartAsync().Result;

            var transactionResponse = new ExecuteTransactionResponse();

            foreach (var changesetContent in changesetStream.Contents)
            {
                changesetContent.Headers.Remove("Content-Type");
                changesetContent.Headers.Add("Content-Type", "application/http; msgtype=response");

                var indivdualResponse = changesetContent.ReadAsHttpResponseMessageAsync().Result;

                if (!indivdualResponse.IsSuccessStatusCode)
                {
                    var exception = JsonSerializer.Deserialize <CrmException>(response.Content.ReadAsStringAsync().Result);
                    throw new CrmException(exception.Error.Message, exception);
                }

                var operationName = requestDictionary.FirstOrDefault(dic => dic.Key == int.Parse(changesetContent.Headers.GetValues("Content-ID").FirstOrDefault())).Value;

                if (operationName == Constants.CREATE)
                {
                    var idString = indivdualResponse.Headers.GetValues("OData-EntityId").FirstOrDefault();
                    idString = idString.Replace(_endpoint, "").Replace("(", "").Replace(")", "");
                    idString = idString.Substring(idString.Length - 36);

                    var createResponse = new CreateResponse {
                        Id = Guid.Parse(idString), ResponseName = operationName
                    };
                    transactionResponse.Responses.Add(createResponse);
                }

                if (operationName == Constants.UPDATE)
                {
                    var updateResponse = new UpdateResponse {
                        ResponseName = operationName
                    };
                    transactionResponse.Responses.Add(updateResponse);
                }

                if (operationName == Constants.DELETE)
                {
                    var deleteResponse = new DeleteResponse {
                        ResponseName = operationName
                    };
                    transactionResponse.Responses.Add(deleteResponse);
                }

                if (operationName == Constants.DISASSOCIATE)
                {
                    var deleteResponse = new DissacociateResponse {
                        ResponseName = operationName
                    };
                    transactionResponse.Responses.Add(deleteResponse);
                }

                if (operationName == Constants.ASSOCIATE)
                {
                    var deleteResponse = new AssociateResponse {
                        ResponseName = operationName
                    };
                    transactionResponse.Responses.Add(deleteResponse);
                }
            }

            return(transactionResponse);
        }
        private OrganizationResponse CallOrganizationServiceRequestForExecuteRequest(OrganizationRequest request)
        {
            OrganizationResponse response = null;
            var associate = request as AssociateRequest;
            if (associate != null)
            {
                response = new AssociateResponse();
                Associate(associate.Target.LogicalName, associate.Target.Id, associate.Relationship, associate.RelatedEntities);
            }

            var create = request as CreateRequest;
            if (create != null)
            {
                response = new CreateResponse();
                response["id"] = Create(create.Target);
            }

            var delete = request as DeleteRequest;
            if (delete != null)
            {
                response = new DeleteResponse();
                Delete(delete.Target.LogicalName, delete.Target.Id);
            }

            var disassociate = request as DisassociateRequest;
            if (disassociate != null)
            {
                response = new AssociateResponse();
                Disassociate(disassociate.Target.LogicalName, disassociate.Target.Id, disassociate.Relationship, disassociate.RelatedEntities);
            }

            var retrieve = request as RetrieveRequest;
            if (retrieve != null)
            {
                response = new RetrieveResponse();
                response["Entity"] = Retrieve(retrieve.Target.LogicalName, retrieve.Target.Id, retrieve.ColumnSet);
            }

            var retrieveMultiple = request as RetrieveMultipleRequest;
            if (retrieveMultiple != null)
            {
                response = new RetrieveMultipleResponse();
                response["EntityCollection"] = RetrieveMultiple(retrieveMultiple.Query);
            }

            var update = request as UpdateRequest;
            if (update != null)
            {
                response = new UpdateResponse();
                Update(update.Target);
            }
            return response;
        }