/// <summary> /// This method creates any entity records that this sample requires. /// Create a new connectionrole instance. /// </summary> public void CreateRequiredRecords() { // Define some anonymous types to define the range // of possible connection property values. var Categories = new { Business = 1, Family = 2, Social = 3, Sales = 4, Other = 5 }; // Create a Connection Role ConnectionRole setupConnectionRole = new ConnectionRole { Name = "Example Connection Role", Description = "This is an example one sided connection role.", Category = new OptionSetValue(Categories.Business), }; _connectionRoleId = _serviceProxy.Create(setupConnectionRole); Console.WriteLine("Created {0}.", setupConnectionRole.Name); return; }
private IEnumerator IEJoinRoomWaitCheckingConnnection() { yield return(waitConnecting); if (socket.Connected) { connectionState = ConnectionState.Connect; connectionRole = ConnectionRole.Client; if (OnJoinRoomSuccess != null) { OnJoinRoomSuccess("Join room success"); } } else { if (OnJoinRoomFail != null) { OnJoinRoomFail("Join room fail"); } } isJoiningRoom = false; }
protected override void ExecuteCrmWorkFlowActivity(CodeActivityContext context, LocalWorkflowContext localContext) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (localContext == null) { throw new ArgumentNullException(nameof(localContext)); } Guid primaryEntityId = localContext.WorkflowExecutionContext.PrimaryEntityId; EntityReference emailToSend = EmailToSend.Get(context); EntityReference connectionRole = ConnectionRole.Get(context); bool includeOpposite = IncludeOppositeConnection.Get(context); bool sendEmail = SendEmail.Get(context); List <Entity> ccList = new List <Entity>(); Entity email = RetrieveEmail(localContext.OrganizationService, emailToSend.Id); if (email == null) { UsersAdded.Set(context, 0); return; } //Add any pre-defined recipients specified to the array foreach (Entity activityParty in email.GetAttributeValue <EntityCollection>("cc").Entities) { ccList.Add(activityParty); } EntityCollection records = GetConnectedRecords(localContext.OrganizationService, primaryEntityId, connectionRole.Id, includeOpposite); localContext.TracingService.Trace($"Found {records.Entities.Count} records"); ccList = ProcessRecords(localContext.OrganizationService, records, ccList, primaryEntityId); //Update the email email["cc"] = ccList.ToArray(); localContext.OrganizationService.Update(email); //Send if (sendEmail) { SendEmailRequest request = new SendEmailRequest { EmailId = emailToSend.Id, TrackingToken = string.Empty, IssueSend = true }; localContext.OrganizationService.Execute(request); } UsersAdded.Set(context, ccList.Count); }
public void Disconnect() { if (socket != null) { socket.Close(); } connectionState = ConnectionState.Disconnect; connectionRole = ConnectionRole.None; }
public void CallbackCreateServerSuccess(string msg) { callback = Callback; socket.BeginReceiveFrom(buffer, 0, byteSize, SocketFlags.None, ref endPoint, callback, socket); connectionState = ConnectionState.Connect; connectionRole = ConnectionRole.Server; }
/// <summary> /// Create and configure the organization service proxy. /// Call the method to create any data that this sample requires. /// Update the connectionrole instance. /// Optionally delete any entity records that were created for this sample. /// </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 = ServerConnection.GetOrganizationProxy(serverConfig)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); //<snippetUpdateConnectionRole1> // Define some anonymous types to define the range // of possible connection property values. var Categories = new { Business = 1, Family = 2, Social = 3, Sales = 4, Other = 5 }; // Update the connectionrole instance. ConnectionRole connectionRole = new ConnectionRole { ConnectionRoleId = _connectionRoleId, Name = "Updated Connection Role", Description = "This is an updated connection role.", Category = new OptionSetValue(Categories.Other) }; _serviceProxy.Update(connectionRole); //</snippetUpdateConnectionRole1> Console.WriteLine("Updated the connectionrole instance."); 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; } }
/// <inheritdoc /> public ICommunicationEndPoint Create(ConnectionRole role) { ICommunicationEndPoint endPoint; if (role == ConnectionRole.Host) { endPoint = new SocketServer(); } else { endPoint = new SocketClient(); } return(endPoint); }
/// <summary> /// This method creates any entity records that this sample requires. /// Creates the email activity. /// </summary> public static void CreateRequiredRecords(CrmServiceClient service) { // TODO Create entity records // Create a Connection Role for account and contact var Categories = new { Business = 1, Family = 2, Social = 3, Sales = 4, Other = 5 }; ConnectionRole newConnectionRole = new ConnectionRole { Name = "Example Connection Role", Category = new OptionSetValue(Categories.Business) }; _connectionRoleId = _serviceProxy.Create(newConnectionRole); Console.WriteLine("Created {0}.", newConnectionRole.Name); // Create a related Connection Role Object Type Code record for Account ConnectionRoleObjectTypeCode newAccountConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRoleId), AssociatedObjectTypeCode = Account.EntityLogicalName }; _serviceProxy.Create(newAccountConnectionRoleTypeCode); Console.WriteLine( "Created a related Connection Role Object Type Code record for Account."); // Create a related Connection Role Object Type Code record for Contact ConnectionRoleObjectTypeCode newContactConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRoleId), AssociatedObjectTypeCode = Contact.EntityLogicalName }; _serviceProxy.Create(newContactConnectionRoleTypeCode); Console.WriteLine("Created a related Connection Role Object Type Code record for Contact."); }
[STAThread] // Added to support UX static void Main(string[] args) { CrmServiceClient service = null; try { service = SampleHelpers.Connect("Connect"); if (service.IsReady) { #region Sample Code #region Set up SetUpSample(service); #endregion Set up #region Demonstrate // Create the Connection Role 1 ConnectionRole newConnectionRole1 = new ConnectionRole { Name = "Example Connection Role 1", Category = new OptionSetValue((int)connectionrole_category.Business), }; _connectionRole1Id = service.Create(newConnectionRole1); Console.WriteLine("Created {0}.", newConnectionRole1.Name); // Create a related Connection Role Object Type Code record for Account ConnectionRoleObjectTypeCode newAccountConnectionRole1TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole1Id), AssociatedObjectTypeCode = Account.EntityLogicalName }; service.Create(newAccountConnectionRole1TypeCode); Console.WriteLine( "Created a related Connection Role 1 Object Type Code record for Account." ); // Create a related Connection Role Object Type Code record for Contact ConnectionRoleObjectTypeCode newContactConnectionRole1TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole1Id), AssociatedObjectTypeCode = Contact.EntityLogicalName }; service.Create(newContactConnectionRole1TypeCode); Console.WriteLine( "Created a related Connection Role 1 Object Type Code record for Contact." ); // Create the Connection Role 2 ConnectionRole newConnectionRole2 = new ConnectionRole { Name = "Example Connection Role 2", Category = new OptionSetValue((int)connectionrole_category.Business), }; _connectionRole2Id = service.Create(newConnectionRole2); Console.WriteLine("Created {0}.", newConnectionRole2.Name); // Create a related Connection Role 2 Object Type Code record for Account ConnectionRoleObjectTypeCode newAccountConnectionRole2TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole2Id), AssociatedObjectTypeCode = Account.EntityLogicalName }; service.Create(newAccountConnectionRole2TypeCode); Console.WriteLine( "Created a related Connection Role 2 Object Type Code record for Account." ); // Create a related Connection Role 2 Object Type Code record for Contact ConnectionRoleObjectTypeCode newContactConnectionRole2TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole2Id), AssociatedObjectTypeCode = Contact.EntityLogicalName }; service.Create(newContactConnectionRole2TypeCode); Console.WriteLine( "Created a related Connection Role 2 Object Type Code record for Contact." ); // Associate the connection roles AssociateRequest associateConnectionRoles = new AssociateRequest { Target = new EntityReference(ConnectionRole.EntityLogicalName, _connectionRole1Id), RelatedEntities = new EntityReferenceCollection() { new EntityReference(ConnectionRole.EntityLogicalName, _connectionRole2Id) }, // The name of the relationship connection role association // relationship in MS CRM Relationship = new Relationship() { PrimaryEntityRole = EntityRole.Referencing, // Referencing or Referenced based on N:1 or 1:N reflexive relationship. SchemaName = "connectionroleassociation_association" } }; service.Execute(associateConnectionRoles); Console.WriteLine("Associated the connection roles."); #region Clean up CleanUpSample(service); #endregion Clean up } #endregion Demonstrate #endregion Sample Code 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(); } }
/// <summary> /// This sample creates a role that is not linked to any entity type. All /// connection roles that apply to all are found and shown. Then the role is /// linked to the account entity and it is demonstrated that the role only works /// for accounts at this point, not for all. Subsequently the link to the account /// entity is removed and it is shown that the role is now applicable to all /// entities again. /// </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 { //<snippetQueryConnectionRolesByEntityTypeCode1> // 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(); // Define some anonymous types to define the range // of possible connection property values. var Categories = new { Business = 1, Family = 2, Social = 3, Sales = 4, Other = 5 }; // Create a Connection Role. ConnectionRole setupConnectionRole = new ConnectionRole { Name = "Example Connection Role", Category = new OptionSetValue(Categories.Business), }; _connectionRoleId = _serviceProxy.Create(setupConnectionRole); setupConnectionRole.Id = _connectionRoleId; Console.WriteLine("Created {0}.", setupConnectionRole.Name); // Query for all Connection Roles. QueryExpression allQuery = new QueryExpression { EntityName = ConnectionRole.EntityLogicalName, ColumnSet = new ColumnSet("connectionroleid", "name"), Distinct = true, LinkEntities = { new LinkEntity { LinkToEntityName = ConnectionRoleObjectTypeCode.EntityLogicalName, LinkToAttributeName = "connectionroleid", LinkFromEntityName = ConnectionRole.EntityLogicalName, LinkFromAttributeName = "connectionroleid", LinkCriteria = new FilterExpression { FilterOperator = LogicalOperator.And, // Set a condition to only get connection roles // related to all entities (object type code = 0). Conditions = { new ConditionExpression { AttributeName = "associatedobjecttypecode", Operator = ConditionOperator.Equal, Values = { 0 } } } } } } }; EntityCollection results = _serviceProxy.RetrieveMultiple(allQuery); // Here you could perform operations on all of // the connectionroles found by the query. Console.WriteLine("Retrieved {0} unassociated connectionrole instance(s).", results.Entities.Count); // Query to find roles which apply only to accounts. QueryExpression accountQuery = new QueryExpression { EntityName = ConnectionRole.EntityLogicalName, ColumnSet = new ColumnSet("connectionroleid", "name"), Distinct = true, LinkEntities = { new LinkEntity { LinkToEntityName = ConnectionRoleObjectTypeCode.EntityLogicalName, LinkToAttributeName = "connectionroleid", LinkFromEntityName = ConnectionRole.EntityLogicalName, LinkFromAttributeName = "connectionroleid", LinkCriteria = new FilterExpression { FilterOperator = LogicalOperator.And, // Set a condition to only get connection roles // related to accounts (object type code = 1). Conditions = { new ConditionExpression { AttributeName = "associatedobjecttypecode", Operator = ConditionOperator.In, Values = { Account.EntityLogicalName } } } } } } }; results = _serviceProxy.RetrieveMultiple(accountQuery); Console.WriteLine("Retrieved {0} account-only connectionrole instance(s).", results.Entities.Count); // Create a related Connection Role Object Type Code record for // Account. ConnectionRoleObjectTypeCode setupAccountConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRoleId), AssociatedObjectTypeCode = Account.EntityLogicalName }; setupAccountConnectionRoleTypeCode.Id = _serviceProxy.Create(setupAccountConnectionRoleTypeCode); Console.Write("Created a related Connection Role Object Type Code"); Console.Write(" record for Account."); // Run the query to find unassociated connectionroles again. results = _serviceProxy.RetrieveMultiple(allQuery); Console.WriteLine(@"Retrieved {0} unassociated connectionrole instance(s).", results.Entities.Count); // Run the account-only query again. results = _serviceProxy.RetrieveMultiple(accountQuery); Console.WriteLine("Retrieved {0} account-only connectionrole instance(s).", results.Entities.Count); // Remove the link from account entity. _serviceProxy.Delete(ConnectionRoleObjectTypeCode.EntityLogicalName, setupAccountConnectionRoleTypeCode.Id); Console.WriteLine("Removed link from connectionrole to account entity."); // Run the query to find unassociated connectionroles again. results = _serviceProxy.RetrieveMultiple(allQuery); Console.WriteLine("Retrieved {0} unassociated connectionrole instance(s).", results.Entities.Count); // Run the account-only query again. results = _serviceProxy.RetrieveMultiple(accountQuery); Console.WriteLine("Retrieved {0} account-only connectionrole instance(s).", results.Entities.Count); DeleteRequiredRecords(promptForDelete); } //</snippetQueryConnectionRolesByEntityTypeCode1> } // 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> /// This sample creates a role that is not linked to any entity type. All /// connection roles that apply to all are found and shown. Then the role is /// linked to the account entity and it is demonstrated that the role only works /// for accounts at this point, not for all. Subsequently the link to the account /// entity is removed and it is shown that the role is now applicable to all /// entities again. /// </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 { //<snippetQueryConnectionRolesByEntityTypeCode1> // 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(); // Define some anonymous types to define the range // of possible connection property values. var Categories = new { Business = 1, Family = 2, Social = 3, Sales = 4, Other = 5 }; // Create a Connection Role. ConnectionRole setupConnectionRole = new ConnectionRole { Name = "Example Connection Role", Category = new OptionSetValue(Categories.Business), }; _connectionRoleId = _serviceProxy.Create(setupConnectionRole); setupConnectionRole.Id = _connectionRoleId; Console.WriteLine("Created {0}.", setupConnectionRole.Name); // Query for all Connection Roles. QueryExpression allQuery = new QueryExpression { EntityName = ConnectionRole.EntityLogicalName, ColumnSet = new ColumnSet("connectionroleid", "name"), Distinct = true, LinkEntities = { new LinkEntity { LinkToEntityName = ConnectionRoleObjectTypeCode.EntityLogicalName, LinkToAttributeName = "connectionroleid", LinkFromEntityName = ConnectionRole.EntityLogicalName, LinkFromAttributeName = "connectionroleid", LinkCriteria = new FilterExpression { FilterOperator = LogicalOperator.And, // Set a condition to only get connection roles // related to all entities (object type code = 0). Conditions = { new ConditionExpression { AttributeName = "associatedobjecttypecode", Operator = ConditionOperator.Equal, Values = { 0 } } } } } } }; EntityCollection results = _serviceProxy.RetrieveMultiple(allQuery); // Here you could perform operations on all of // the connectionroles found by the query. Console.WriteLine("Retrieved {0} unassociated connectionrole instance(s).", results.Entities.Count); // Query to find roles which apply only to accounts. QueryExpression accountQuery = new QueryExpression { EntityName = ConnectionRole.EntityLogicalName, ColumnSet = new ColumnSet("connectionroleid", "name"), Distinct = true, LinkEntities = { new LinkEntity { LinkToEntityName = ConnectionRoleObjectTypeCode.EntityLogicalName, LinkToAttributeName = "connectionroleid", LinkFromEntityName = ConnectionRole.EntityLogicalName, LinkFromAttributeName = "connectionroleid", LinkCriteria = new FilterExpression { FilterOperator = LogicalOperator.And, // Set a condition to only get connection roles // related to accounts (object type code = 1). Conditions = { new ConditionExpression { AttributeName = "associatedobjecttypecode", Operator = ConditionOperator.In, Values = { Account.EntityLogicalName } } } } } } }; results = _serviceProxy.RetrieveMultiple(accountQuery); Console.WriteLine("Retrieved {0} account-only connectionrole instance(s).", results.Entities.Count); // Create a related Connection Role Object Type Code record for // Account. ConnectionRoleObjectTypeCode setupAccountConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRoleId), AssociatedObjectTypeCode = Account.EntityLogicalName }; setupAccountConnectionRoleTypeCode.Id = _serviceProxy.Create(setupAccountConnectionRoleTypeCode); Console.Write("Created a related Connection Role Object Type Code"); Console.Write(" record for Account."); // Run the query to find unassociated connectionroles again. results = _serviceProxy.RetrieveMultiple(allQuery); Console.WriteLine(@"Retrieved {0} unassociated connectionrole instance(s).", results.Entities.Count); // Run the account-only query again. results = _serviceProxy.RetrieveMultiple(accountQuery); Console.WriteLine("Retrieved {0} account-only connectionrole instance(s).", results.Entities.Count); // Remove the link from account entity. _serviceProxy.Delete(ConnectionRoleObjectTypeCode.EntityLogicalName, setupAccountConnectionRoleTypeCode.Id); Console.WriteLine("Removed link from connectionrole to account entity."); // Run the query to find unassociated connectionroles again. results = _serviceProxy.RetrieveMultiple(allQuery); Console.WriteLine("Retrieved {0} unassociated connectionrole instance(s).", results.Entities.Count); // Run the account-only query again. results = _serviceProxy.RetrieveMultiple(accountQuery); Console.WriteLine("Retrieved {0} account-only connectionrole instance(s).", results.Entities.Count); DeleteRequiredRecords(promptForDelete); } //</snippetQueryConnectionRolesByEntityTypeCode1> } // 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> /// This method creates any entity records that this sample requires. /// Create a new connectionrole instance. /// </summary> public void CreateRequiredRecords() { // Define some anonymous types to define the range // of possible connection property values. var Categories = new { Business = 1, Family = 2, Social = 3, Sales = 4, Other = 5 }; // Create a Connection Role ConnectionRole setupConnectionRole = new ConnectionRole { Name = "Example Connection Role", Description = "This is an example one sided connection role.", Category = new OptionSetValue(Categories.Business), }; _connectionRoleId = _serviceProxy.Create(setupConnectionRole); Console.WriteLine("Created {0}.", setupConnectionRole.Name); // Create a related Connection Role Object Type Code record for Account ConnectionRoleObjectTypeCode newAccountConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRoleId), AssociatedObjectTypeCode = Account.EntityLogicalName }; _serviceProxy.Create(newAccountConnectionRoleTypeCode); Console.WriteLine( "Created a related Connection Role Object Type Code record for Account." ); // Create a related Connection Role Object Type Code record for Contact ConnectionRoleObjectTypeCode newContactConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRoleId), AssociatedObjectTypeCode = Contact.EntityLogicalName }; _serviceProxy.Create(newContactConnectionRoleTypeCode); Console.WriteLine( "Created a related Connection Role Object Type Code record for Contact." ); //Create a few account records for use in the connections. Account setupAccount1 = new Account { Name = "Example Account 1" }; _account1Id = _serviceProxy.Create(setupAccount1); Console.WriteLine("Created {0}.", setupAccount1.Name); Account setupAccount2 = new Account { Name = "Example Account 2" }; _account2Id = _serviceProxy.Create(setupAccount2); Console.WriteLine("Created {0}.", setupAccount2.Name); //Creates a contact used in the connection. Contact setupContact = new Contact { LastName = "Example Contact" }; _contactId = _serviceProxy.Create(setupContact); Console.WriteLine("Created {0}.", setupContact.LastName); // Create a new connection between Account 1 and the contact record. Connection newConnection1 = new Connection { Record1Id = new EntityReference(Account.EntityLogicalName, _account1Id), Record1RoleId = new EntityReference(ConnectionRole.EntityLogicalName, _connectionRoleId), Record2Id = new EntityReference(Contact.EntityLogicalName, _contactId) }; _connection1Id = _serviceProxy.Create(newConnection1); Console.WriteLine( "Created a connection between the account 1 and the contact."); // Create a new connection between the contact and Account 2 record Connection newConnection2 = new Connection { Record1Id = new EntityReference(Contact.EntityLogicalName, _contactId), Record1RoleId = new EntityReference(ConnectionRole.EntityLogicalName, _connectionRoleId), Record2Id = new EntityReference(Account.EntityLogicalName, _account2Id) }; _connection2Id = _serviceProxy.Create(newConnection2); Console.WriteLine( "Created a connection between the contact and the account 2."); return; }
[STAThread] // Added to support UX static void Main(string[] args) { CrmServiceClient service = null; try { service = SampleHelpers.Connect("Connect"); if (service.IsReady) { #region Sample Code #region Set up SetUpSample(service); #endregion Set up #region Demonstrate // Define some anonymous types to define the range // of possible connection property values. var Categories = new { Business = 1, Family = 2, Social = 3, Sales = 4, Other = 5 }; // Create a Connection Role for account and contact var newConnectionRole = new ConnectionRole { Name = "Example Connection Role", Category = new OptionSetValue(Categories.Business) }; _connectionRoleId = service.Create(newConnectionRole); Console.WriteLine("Created {0}.", newConnectionRole.Name); // Create a related Connection Role Object Type Code record for Account var newAccountConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRoleId), AssociatedObjectTypeCode = Account.EntityLogicalName }; service.Create(newAccountConnectionRoleTypeCode); Console.WriteLine( "Created a related Connection Role Object Type Code record for Account."); // Create a related Connection Role Object Type Code record for Contact var newContactConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRoleId), AssociatedObjectTypeCode = Contact.EntityLogicalName }; service.Create(newContactConnectionRoleTypeCode); Console.WriteLine( "Created a related Connection Role Object Type Code record for Contact."); #region Clean up CleanUpSample(service); #endregion Clean up #endregion Demonstrate #endregion Sample Code } else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service"; 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(); } }
/// <summary> /// Creates a new instance of the Connection class. /// </summary> /// <param name="socket">Socket which sould be used</param> /// <param name="channel">Remoting channel</param> /// <param name="keepAlive">Enables or disables TCP KeepAlive for the new connection</param> /// <param name="keepAliveTime">Time for TCP KeepAlive in Milliseconds</param> /// <param name="KeepAliveInterval">Interval for TCP KeepAlive in Milliseconds</param> /// <param name="maxRetries">Maximum number of connection retry attempts</param> /// <param name="retryDelay">Delay after connection retry in milliseconds</param> protected Connection(Socket socket, TcpExChannel channel, bool keepAlive, ulong keepAliveTime, ulong KeepAliveInterval, short maxRetries, int retryDelay) { if (socket == null) throw new ArgumentNullException("socket"); if (channel == null) throw new ArgumentNullException("channel"); _connectionRole = ConnectionRole.ActAsServer; _maxRetries = maxRetries; _retryDelay = retryDelay; _channel = channel; _socket = socket; IPEndPoint remoteEndPoint = socket.RemoteEndPoint as IPEndPoint; _socketRemoteAddress = remoteEndPoint.Address.ToString(); _socketRemotePort = remoteEndPoint.Port; CheckSocket(); if (!ReceiveChannelInfo()) throw new RemotingException(LanguageResource.RemotingException_ErrorReceivingChannelInfo); if (!SendChannelInfo()) throw new RemotingException(LanguageResource.RemotingException_ErrorSendingChannelInfo); if (_connections.ContainsKey(_remoteChannelData.ChannelID.ToString())) { socket.Close(); throw new DuplicateConnectionException(_remoteChannelData.ChannelID); } TcpKeepAliveTime = keepAliveTime; TcpKeepAliveInterval = KeepAliveInterval; TcpKeepAliveEnabled = keepAlive; AddToConnectionList(); }
/// <summary> /// Create and configure the organization service proxy. /// Create a new connectionrole instance and set the object type. /// Optionally delete any entity records that were created for this sample. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); //<snippetCreateConnectionRole1> // Define some anonymous types to define the range // of possible connection property values. var Categories = new { Business = 1, Family = 2, Social = 3, Sales = 4, Other = 5 }; // Create a Connection Role for account and contact ConnectionRole newConnectionRole = new ConnectionRole { Name = "Example Connection Role", Category = new OptionSetValue(Categories.Business) }; _connectionRoleId = _serviceProxy.Create(newConnectionRole); Console.WriteLine("Created {0}.", newConnectionRole.Name); // Create a related Connection Role Object Type Code record for Account ConnectionRoleObjectTypeCode newAccountConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRoleId), AssociatedObjectTypeCode = Account.EntityLogicalName }; _serviceProxy.Create(newAccountConnectionRoleTypeCode); Console.WriteLine( "Created a related Connection Role Object Type Code record for Account."); // Create a related Connection Role Object Type Code record for Contact ConnectionRoleObjectTypeCode newContactConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRoleId), AssociatedObjectTypeCode = Contact.EntityLogicalName }; _serviceProxy.Create(newContactConnectionRoleTypeCode); Console.WriteLine( "Created a related Connection Role Object Type Code record for Contact."); //</snippetCreateConnectionRole1> 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 void CoonectContactCheckRequiredFields_Success() { var fakedContext = new XrmFakedContext(); //input object does not contain to record id which is mandatory. string InputLoad = @" { 'fromrecordid': '369d71cf-c874-e811-a83b-000d3ab4f7af', 'fromrecordtype': 'contact', 'torecordid': 'b7293664-e46a-e811-a83c-000d3ab4f967', 'torecordtype': 'organisation', 'relations': { 'torole': 'Agent', 'fromrole': 'Agent Customer' } } "; //Inputs var inputs = new Dictionary <string, object>() { { "request", InputLoad }, }; Guid AgentId = Guid.NewGuid(); Guid AgentCustomerId = Guid.NewGuid(); ConnectionRole RoleAgent = new ConnectionRole(); RoleAgent.Id = AgentId; RoleAgent.Name = "Agent"; ConnectionRole RoleAgentcustomer = new ConnectionRole(); List <ConnectionRole> RelatedRoles = new List <ConnectionRole>(); RelatedRoles.Add(RoleAgent); RoleAgentcustomer.Referencedconnectionroleassociation_association = RelatedRoles.ToArray(); RoleAgentcustomer.Id = AgentCustomerId; RoleAgentcustomer.Name = "Agent Customer"; ConnectionRole AgentRole = new ConnectionRole(); RoleAgentcustomer.Referencedconnectionroleassociation_association = RelatedRoles.ToArray(); AgentRole.Referencedconnectionroleassociation_association = RelatedRoles.ToArray(); AgentRole.Id = AgentId; AgentRole.Name = "Agent"; fakedContext.Initialize(new List <Entity>() { new Entity() { Id = new Guid("369d71cf-c874-e811-a83b-000d3ab4f7af"), LogicalName = "contact" }, new Entity() { Id = new Guid("b7293664-e46a-e811-a83c-000d3ab4f967"), LogicalName = "account" }, AgentRole, RoleAgentcustomer }); //fakedContext.Initialize(new List<Entity>() //{ new Entity() { Id = new Guid("369d71cf-c874-e811-a83b-000d3ab4f7af"), LogicalName = "account" }, // }); //var connection = fakedContext.CreateQueryFromEntityName("connection"); var connection = fakedContext.CreateQuery <Connection>(); var result = fakedContext.ExecuteCodeActivity <CreateRelationship>(inputs); String ReturnMessage = (String)result["response"]; ContactResponse ContactResponseObject = JsonConvert.DeserializeObject <ContactResponse>(ReturnMessage); String ErrorDetails = ContactResponseObject.message; StringAssert.Contains(ErrorDetails, "Primary rolenot found."); }
/// <summary> /// Creates a new instance of the Connection class. /// </summary> /// <param name="address">Address (IP oder DNS based)</param> /// <param name="channel">Remoting channel</param> /// <param name="keepAlive">Enables or disables TCP KeepAlive for the new connection</param> /// <param name="keepAliveTime">Time for TCP KeepAlive in Milliseconds</param> /// <param name="KeepAliveInterval">Interval for TCP KeepAlive in Milliseconds</param> /// <param name="maxRetries">Maximum number of connection retry attempts</param> /// <param name="retryDelay">Delay after connection retry in milliseconds</param> protected Connection(string address, TcpExChannel channel, bool keepAlive, ulong keepAliveTime, ulong KeepAliveInterval, short maxRetries, int retryDelay) { if (string.IsNullOrEmpty(address)) throw new ArgumentException(LanguageResource.ArgumentException_AddressMustNotBeEmpty, "address"); if (channel == null) throw new ArgumentNullException("channel"); _connectionRole = ConnectionRole.ActAsClient; _maxRetries = maxRetries; _retryDelay = retryDelay; _channel = channel; Match m = _addressRegEx.Match(address); if (!m.Success) throw new FormatException(string.Format(LanguageResource.Format_Exception_InvalidAddressFormat, address)); IPAddress remoteIPAddress = Manager.GetHostByName(m.Groups["address"].Value); _socketRemoteAddress = remoteIPAddress.ToString(); _socketRemotePort = int.Parse(m.Groups["port"].Value); _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket.Connect(new IPEndPoint(remoteIPAddress, _socketRemotePort)); CheckSocket(); if (!SendChannelInfo()) throw new RemotingException(LanguageResource.RemotingException_ErrorSendingChannelInfo); if (!ReceiveChannelInfo()) throw new RemotingException(LanguageResource.RemotingException_ErrorReceivingChannelInfo); if (_connections.ContainsKey(_remoteChannelData.ChannelID.ToString())) { _socket.Close(); throw new DuplicateConnectionException(_remoteChannelData.ChannelID); } TcpKeepAliveTime = keepAliveTime; TcpKeepAliveInterval = KeepAliveInterval; TcpKeepAliveEnabled = keepAlive; AddToConnectionList(); }
public void UpdateContactCheckRequiredFields_Success() { var fakedContext = new XrmFakedContext(); //input object does not contain to record id which is mandatory. string InputLoad = @" { 'b2cobjectid': 'b2c12062018-cd20180618', 'title': 1, 'firstname': 'idm.frist.cd20180618', 'lastname': 'idm.last.cd20180618', 'email': '*****@*****.**', 'dob': '06/07/2018', 'gender': 2, 'telephone': '004412345678', 'tacsacceptedversion': '12345', 'tacsacceptedon': '10/09/2018 06:06:06', 'address': { 'type': 1, 'uprn': 20180618, 'buildingname': 'Horizon', 'buildingnumber': '3', 'street': 'deanary', 'locality': '', 'town': '', 'postcode': 'hp98tj', 'country': 'gbr', 'fromcompanieshouse': '' } } "; String ContactIdMaxLenErrorMsg = "Contact ID is invalid/exceed the max length(50);"; String FirstNameMaxLengthErrorMsg = "First Name cannot be greater than 50;"; String MiddlenameMaxLengthErrorMsg = "Middle Name cannot be greater than 50;"; String LastNameMaxLengthErrorMsg = "Last Name cannot be greater than 50"; String EmailMaxLengthErrorMsg = "Email cannot be greater than 100;"; String TelephoneMaxLengthErrorMsg = "Telephone cannot be greater than 50;"; String TermsAndConditionMaxLengthErrorMsg = "T&C Accepted Version cannot be greater than 5;"; #region Setting Input Params //Inputs var inputs = new Dictionary <string, object>() { { "PayLoad", InputLoad }, }; Guid AgentId = Guid.NewGuid(); Guid AgentCustomerId = Guid.NewGuid(); ConnectionRole RoleAgent = new ConnectionRole(); RoleAgent.Id = AgentId; RoleAgent.Name = "Agent"; ConnectionRole RoleAgentcustomer = new ConnectionRole(); RoleAgentcustomer.Id = AgentCustomerId; RoleAgentcustomer.Name = "Agent Customer"; ConnectionRole PrimaryRole = new ConnectionRole(); PrimaryRole.Id = Guid.NewGuid(); PrimaryRole.Name = "Primary User"; ConnectionRole AgentRole = new ConnectionRole(); AgentRole.Id = AgentId; AgentRole.Name = "Agent"; fakedContext.Initialize(new List <Entity>() { new Entity() { Id = new Guid("369d71cf-c874-e811-a83b-000d3ab4f7af"), LogicalName = "contact" }, new Entity() { Id = new Guid("b7293664-e46a-e811-a83c-000d3ab4f967"), LogicalName = "account" }, AgentRole, RoleAgentcustomer, PrimaryRole }); var connection = fakedContext.CreateQuery <Connection>(); var result = fakedContext.ExecuteCodeActivity <UpdateContact>(inputs); #endregion String ReturnMessage = (String)result["ReturnMessageDetails"]; ContactResponse ContactResponseObject = Newtonsoft.Json.JsonConvert.DeserializeObject <ContactResponse>(ReturnMessage); String ErrorDetails = ContactResponseObject.message; StringAssert.Contains(ReturnMessage, ContactIdMaxLenErrorMsg, "Contact ID validation failed."); StringAssert.Contains(ReturnMessage, FirstNameMaxLengthErrorMsg, "First name validation failed."); StringAssert.Contains(ReturnMessage, MiddlenameMaxLengthErrorMsg, "Middle name validation failed."); StringAssert.Contains(ReturnMessage, LastNameMaxLengthErrorMsg, "Last name validation failed."); StringAssert.Contains(ReturnMessage, EmailMaxLengthErrorMsg, "Email validation failed."); StringAssert.Contains(ReturnMessage, TelephoneMaxLengthErrorMsg, "Telephone max length validation failed."); StringAssert.Contains(ReturnMessage, TermsAndConditionMaxLengthErrorMsg, "T&C Validation failed."); }
/// <summary> /// Create and configure the organization service proxy. /// Create the connection role instances. /// Associate the connection roles. /// Optionally delete any entity records that were created for this sample. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Create the Connection Role 1 ConnectionRole newConnectionRole1 = new ConnectionRole { Name = "Example Connection Role 1", Category = new OptionSetValue((int)connectionrole_category.Business), }; _connectionRole1Id = _serviceProxy.Create(newConnectionRole1); Console.WriteLine("Created {0}.", newConnectionRole1.Name); // Create a related Connection Role Object Type Code record for Account ConnectionRoleObjectTypeCode newAccountConnectionRole1TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole1Id), AssociatedObjectTypeCode = Account.EntityLogicalName }; _serviceProxy.Create(newAccountConnectionRole1TypeCode); Console.WriteLine( "Created a related Connection Role 1 Object Type Code record for Account." ); // Create a related Connection Role Object Type Code record for Contact ConnectionRoleObjectTypeCode newContactConnectionRole1TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole1Id), AssociatedObjectTypeCode = Contact.EntityLogicalName }; _serviceProxy.Create(newContactConnectionRole1TypeCode); Console.WriteLine( "Created a related Connection Role 1 Object Type Code record for Contact." ); // Create the Connection Role 2 ConnectionRole newConnectionRole2 = new ConnectionRole { Name = "Example Connection Role 2", Category = new OptionSetValue((int)connectionrole_category.Business), }; _connectionRole2Id = _serviceProxy.Create(newConnectionRole2); Console.WriteLine("Created {0}.", newConnectionRole2.Name); // Create a related Connection Role 2 Object Type Code record for Account ConnectionRoleObjectTypeCode newAccountConnectionRole2TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole2Id), AssociatedObjectTypeCode = Account.EntityLogicalName }; _serviceProxy.Create(newAccountConnectionRole2TypeCode); Console.WriteLine( "Created a related Connection Role 2 Object Type Code record for Account." ); // Create a related Connection Role 2 Object Type Code record for Contact ConnectionRoleObjectTypeCode newContactConnectionRole2TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole2Id), AssociatedObjectTypeCode = Contact.EntityLogicalName }; _serviceProxy.Create(newContactConnectionRole2TypeCode); Console.WriteLine( "Created a related Connection Role 2 Object Type Code record for Contact." ); //<snippetAssociateReciprocalConnectionRoles> // Associate the connection roles AssociateRequest associateConnectionRoles = new AssociateRequest { Target = new EntityReference(ConnectionRole.EntityLogicalName, _connectionRole1Id), RelatedEntities = new EntityReferenceCollection() { new EntityReference(ConnectionRole.EntityLogicalName, _connectionRole2Id) }, // The name of the relationship connection role association // relationship in MS CRM Relationship = new Relationship() { PrimaryEntityRole = EntityRole.Referencing, // Referencing or Referenced based on N:1 or 1:N reflexive relationship. SchemaName = "connectionroleassociation_association" } }; _serviceProxy.Execute(associateConnectionRoles); Console.WriteLine("Associated the connection roles."); //</snippetAssociateReciprocalConnectionRoles> 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 void Invoke(IDictionary <string, string> argsDictionary) { // Setup logging if enabled string logFile; if (argsDictionary.TryGetValue(LogFileArgument, out logFile)) { EqtTrace.InitializeVerboseTrace(logFile); } #if NET451 if (EqtTrace.IsInfoEnabled) { var appConfigText = System.IO.File.ReadAllText(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); EqtTrace.Info("DefaultEngineInvoker: Using Application Configuration: '{0}'", appConfigText); } #endif // vstest.console < 15.5 won't send endpoint and role arguments. // So derive endpoint from port argument and Make connectionRole as Client. string endpoint = CommandLineArgumentsHelper.GetStringArgFromDict(argsDictionary, EndpointArgument); if (string.IsNullOrWhiteSpace(endpoint)) { var port = CommandLineArgumentsHelper.GetIntArgFromDict(argsDictionary, "--port"); endpoint = IPAddress.Loopback + ":" + port; } ConnectionRole connectionRole = ConnectionRole.Client; string role = CommandLineArgumentsHelper.GetStringArgFromDict(argsDictionary, RoleArgument); if (string.IsNullOrWhiteSpace(role) && string.Equals(role, "host", StringComparison.OrdinalIgnoreCase)) { connectionRole = ConnectionRole.Host; } // Start Processing of requests using (var requestHandler = new TestRequestHandler(new TestHostConnectionInfo { Endpoint = endpoint, Role = connectionRole, Transport = Transport.Sockets })) { // Attach to exit of parent process var parentProcessId = CommandLineArgumentsHelper.GetIntArgFromDict(argsDictionary, ParentProcessIdArgument); EqtTrace.Info("DefaultEngineInvoker: Monitoring parent process with id: '{0}'", parentProcessId); // In remote scenario we cannot monitor parent process, so we expect user to pass parentProcessId as -1 if (parentProcessId != -1) { var processHelper = new ProcessHelper(); processHelper.SetExitCallback( parentProcessId, () => { EqtTrace.Info("DefaultEngineInvoker: ParentProcess '{0}' Exited.", parentProcessId); new PlatformEnvironment().Exit(1); }); } // Initialize Communication EqtTrace.Info("DefaultEngineInvoker: Initialize communication on endpoint address: '{0}'", endpoint); requestHandler.InitializeCommunication(); // Initialize DataCollection Communication if data collection port is provided. var dcPort = CommandLineArgumentsHelper.GetIntArgFromDict(argsDictionary, DataCollectionPortArgument); if (dcPort > 0) { var dataCollectionTestCaseEventSender = DataCollectionTestCaseEventSender.Create(); dataCollectionTestCaseEventSender.InitializeCommunication(dcPort); dataCollectionTestCaseEventSender.WaitForRequestSenderConnection(ClientListenTimeOut); } // Start processing async in a different task EqtTrace.Info("DefaultEngineInvoker: Start Request Processing."); var processingTask = this.StartProcessingAsync(requestHandler, new TestHostManagerFactory()); // Wait for processing to complete. Task.WaitAny(processingTask); if (dcPort > 0) { // Close socket communication connection. DataCollectionTestCaseEventSender.Instance.Close(); } } }
/// <summary> /// Create and configure the organization service proxy. /// Create the connection role instances. /// Associate the connection roles. /// Optionally delete any entity records that were created for this sample. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Create the Connection Role 1 ConnectionRole newConnectionRole1 = new ConnectionRole { Name = "Example Connection Role 1", Category = new OptionSetValue((int)connectionrole_category.Business), }; _connectionRole1Id = _serviceProxy.Create(newConnectionRole1); Console.WriteLine("Created {0}.", newConnectionRole1.Name); // Create a related Connection Role Object Type Code record for Account ConnectionRoleObjectTypeCode newAccountConnectionRole1TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole1Id), AssociatedObjectTypeCode = Account.EntityLogicalName }; _serviceProxy.Create(newAccountConnectionRole1TypeCode); Console.WriteLine( "Created a related Connection Role 1 Object Type Code record for Account." ); // Create a related Connection Role Object Type Code record for Contact ConnectionRoleObjectTypeCode newContactConnectionRole1TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole1Id), AssociatedObjectTypeCode = Contact.EntityLogicalName }; _serviceProxy.Create(newContactConnectionRole1TypeCode); Console.WriteLine( "Created a related Connection Role 1 Object Type Code record for Contact." ); // Create the Connection Role 2 ConnectionRole newConnectionRole2 = new ConnectionRole { Name = "Example Connection Role 2", Category = new OptionSetValue((int)connectionrole_category.Business), }; _connectionRole2Id = _serviceProxy.Create(newConnectionRole2); Console.WriteLine("Created {0}.", newConnectionRole2.Name); // Create a related Connection Role 2 Object Type Code record for Account ConnectionRoleObjectTypeCode newAccountConnectionRole2TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole2Id), AssociatedObjectTypeCode = Account.EntityLogicalName }; _serviceProxy.Create(newAccountConnectionRole2TypeCode); Console.WriteLine( "Created a related Connection Role 2 Object Type Code record for Account." ); // Create a related Connection Role 2 Object Type Code record for Contact ConnectionRoleObjectTypeCode newContactConnectionRole2TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole2Id), AssociatedObjectTypeCode = Contact.EntityLogicalName }; _serviceProxy.Create(newContactConnectionRole2TypeCode); Console.WriteLine( "Created a related Connection Role 2 Object Type Code record for Contact." ); //<snippetAssociateReciprocalConnectionRoles> // Associate the connection roles AssociateRequest associateConnectionRoles = new AssociateRequest { Target = new EntityReference(ConnectionRole.EntityLogicalName, _connectionRole1Id), RelatedEntities = new EntityReferenceCollection() { new EntityReference(ConnectionRole.EntityLogicalName, _connectionRole2Id) }, // The name of the relationship connection role association // relationship in MS CRM Relationship = new Relationship() { PrimaryEntityRole = EntityRole.Referencing, // Referencing or Referenced based on N:1 or 1:N reflexive relationship. SchemaName = "connectionroleassociation_association" } }; _serviceProxy.Execute(associateConnectionRoles); Console.WriteLine("Associated the connection roles."); //</snippetAssociateReciprocalConnectionRoles> 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> /// This method creates any entity records that this sample requires. /// Create a new connectionrole instance. /// Create related Connection Role Object Type Code records /// for the account and the contact entities. /// </summary> public void CreateRequiredRecords() { // Create a Connection Role for account and contact ConnectionRole newConnectionRole = new ConnectionRole { Name = "Example Connection Role", Category = new OptionSetValue((int)connectionrole_category.Business) }; _connectionRoleId = _serviceProxy.Create(newConnectionRole); Console.WriteLine("Created {0}.", newConnectionRole.Name); // Create a related Connection Role Object Type Code record for Account ConnectionRoleObjectTypeCode newAccountConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRoleId), AssociatedObjectTypeCode = Account.EntityLogicalName }; _serviceProxy.Create(newAccountConnectionRoleTypeCode); Console.WriteLine( "Created a related Connection Role Object Type Code record for Account." ); // Create a related Connection Role Object Type Code record for Contact ConnectionRoleObjectTypeCode newContactConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRoleId), AssociatedObjectTypeCode = Contact.EntityLogicalName }; _serviceProxy.Create(newContactConnectionRoleTypeCode); Console.WriteLine( "Created a related Connection Role Object Type Code record for Contact." ); // Associate the connection role with itself. AssociateRequest associateConnectionRoles = new AssociateRequest { Target = new EntityReference(ConnectionRole.EntityLogicalName, _connectionRoleId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(ConnectionRole.EntityLogicalName, _connectionRoleId) }, // The name of the relationship connection role association // relationship in MS CRM. Relationship = new Relationship() { PrimaryEntityRole = EntityRole.Referencing, // Referencing or Referenced based on N:1 or 1:N reflexive relationship. SchemaName = "connectionroleassociation_association" } }; _serviceProxy.Execute(associateConnectionRoles); Console.WriteLine("Associated the connection role with itself."); // Create an Account Account setupAccount = new Account { Name = "Example Account" }; _accountId = _serviceProxy.Create(setupAccount); Console.WriteLine("Created {0}.", setupAccount.Name); // Create a Contact Contact setupContact = new Contact { LastName = "Example Contact" }; _contactId = _serviceProxy.Create(setupContact); Console.WriteLine("Created {0}.", setupContact.LastName); return; }
[STAThread] // Added to support UX static void Main(string[] args) { CrmServiceClient service = null; try { service = SampleHelpers.Connect("Connect"); if (service.IsReady) { #region Sample Code ////////////////////////////////////////////// #region Set up SetUpSample(service); #endregion Set up #region Demonstrate // Define some anonymous types to define the range // of possible connection property values. var Categories = new { Business = 1, Family = 2, Social = 3, Sales = 4, Other = 5 }; // Create a Connection Role. ConnectionRole setupConnectionRole = new ConnectionRole { Name = "Example Connection Role", Category = new OptionSetValue(Categories.Business), }; _connectionRoleId = service.Create(setupConnectionRole); setupConnectionRole.Id = _connectionRoleId; Console.WriteLine("Created {0}.", setupConnectionRole.Name); // Query for all Connection Roles. QueryExpression allQuery = new QueryExpression { EntityName = ConnectionRole.EntityLogicalName, ColumnSet = new ColumnSet("connectionroleid", "name"), Distinct = true, LinkEntities = { new LinkEntity { LinkToEntityName = ConnectionRoleObjectTypeCode.EntityLogicalName, LinkToAttributeName = "connectionroleid", LinkFromEntityName = ConnectionRole.EntityLogicalName, LinkFromAttributeName = "connectionroleid", LinkCriteria = new FilterExpression { FilterOperator = LogicalOperator.And, // Set a condition to only get connection roles // related to all entities (object type code = 0). Conditions = { new ConditionExpression { AttributeName = "associatedobjecttypecode", Operator = ConditionOperator.Equal, Values = { 0 } } } } } } }; EntityCollection results = service.RetrieveMultiple(allQuery); // Here you could perform operations on all of // the connectionroles found by the query. Console.WriteLine("Retrieved {0} unassociated connectionrole instance(s).", results.Entities.Count); // Query to find roles which apply only to accounts. QueryExpression accountQuery = new QueryExpression { EntityName = ConnectionRole.EntityLogicalName, ColumnSet = new ColumnSet("connectionroleid", "name"), Distinct = true, LinkEntities = { new LinkEntity { LinkToEntityName = ConnectionRoleObjectTypeCode.EntityLogicalName, LinkToAttributeName = "connectionroleid", LinkFromEntityName = ConnectionRole.EntityLogicalName, LinkFromAttributeName = "connectionroleid", LinkCriteria = new FilterExpression { FilterOperator = LogicalOperator.And, // Set a condition to only get connection roles // related to accounts (object type code = 1). Conditions = { new ConditionExpression { AttributeName = "associatedobjecttypecode", Operator = ConditionOperator.In, Values = { Account.EntityLogicalName } } } } } } }; results = service.RetrieveMultiple(accountQuery); Console.WriteLine("Retrieved {0} account-only connectionrole instance(s).", results.Entities.Count); // Create a related Connection Role Object Type Code record for // Account. ConnectionRoleObjectTypeCode setupAccountConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRoleId), AssociatedObjectTypeCode = Account.EntityLogicalName }; setupAccountConnectionRoleTypeCode.Id = service.Create(setupAccountConnectionRoleTypeCode); Console.Write("Created a related Connection Role Object Type Code"); Console.Write(" record for Account."); // Run the query to find unassociated connectionroles again. results = service.RetrieveMultiple(allQuery); Console.WriteLine(@"Retrieved {0} unassociated connectionrole instance(s).", results.Entities.Count); // Run the account-only query again. results = service.RetrieveMultiple(accountQuery); Console.WriteLine("Retrieved {0} account-only connectionrole instance(s).", results.Entities.Count); // Remove the link from account entity. service.Delete(ConnectionRoleObjectTypeCode.EntityLogicalName, setupAccountConnectionRoleTypeCode.Id); Console.WriteLine("Removed link from connectionrole to account entity."); // Run the query to find unassociated connectionroles again. results = service.RetrieveMultiple(allQuery); Console.WriteLine("Retrieved {0} unassociated connectionrole instance(s).", results.Entities.Count); // Run the account-only query again. results = service.RetrieveMultiple(accountQuery); Console.WriteLine("Retrieved {0} account-only connectionrole instance(s).", results.Entities.Count); #region Clean up CleanUpSample(service); #endregion Clean up } #endregion Demonstrate else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service"; 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; } } } #endregion Sample Code catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) { service.Dispose(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
[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 // // Create a Connection Role for account and contact ConnectionRole newConnectionRole = new ConnectionRole { Name = "Example Connection Role", Category = new OptionSetValue((int)connectionrole_category.Business) }; _connectionRoleId = _serviceProxy.Create(newConnectionRole); Console.WriteLine("Created {0}.", newConnectionRole.Name); // Create a related Connection Role Object Type Code record for Account ConnectionRoleObjectTypeCode newAccountConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRoleId), AssociatedObjectTypeCode = Account.EntityLogicalName }; _serviceProxy.Create(newAccountConnectionRoleTypeCode); Console.WriteLine( "Created a related Connection Role Object Type Code record for Account." ); // Create a related Connection Role Object Type Code record for Contact ConnectionRoleObjectTypeCode newContactConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRoleId), AssociatedObjectTypeCode = Contact.EntityLogicalName }; _serviceProxy.Create(newContactConnectionRoleTypeCode); Console.WriteLine( "Created a related Connection Role Object Type Code record for Contact." ); // Associate the connection role with itself. AssociateRequest associateConnectionRoles = new AssociateRequest { Target = new EntityReference(ConnectionRole.EntityLogicalName, _connectionRoleId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(ConnectionRole.EntityLogicalName, _connectionRoleId) }, // The name of the relationship connection role association // relationship in MS CRM. Relationship = new Relationship() { PrimaryEntityRole = EntityRole.Referencing, // Referencing or Referenced based on N:1 or 1:N reflexive relationship. SchemaName = "connectionroleassociation_association" } }; _serviceProxy.Execute(associateConnectionRoles); Console.WriteLine("Associated the connection role with itself."); // Create an Account Account setupAccount = new Account { Name = "Example Account" }; _accountId = _serviceProxy.Create(setupAccount); Console.WriteLine("Created {0}.", setupAccount.Name); // Create a Contact Contact setupContact = new Contact { LastName = "Example Contact" }; _contactId = _serviceProxy.Create(setupContact); Console.WriteLine("Created {0}.", setupContact.LastName); return; #endregion Demonstrate } else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service"; 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(); } }
/// <summary> /// Create and configure the organization service proxy. /// Create a new connectionrole instance and set the object type. /// Optionally delete any entity records that were created for this sample. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); //<snippetCreateConnectionRole1> // Define some anonymous types to define the range // of possible connection property values. var Categories = new { Business = 1, Family = 2, Social = 3, Sales = 4, Other = 5 }; // Create a Connection Role for account and contact ConnectionRole newConnectionRole = new ConnectionRole { Name = "Example Connection Role", Category = new OptionSetValue(Categories.Business) }; _connectionRoleId = _serviceProxy.Create(newConnectionRole); Console.WriteLine("Created {0}.", newConnectionRole.Name); // Create a related Connection Role Object Type Code record for Account ConnectionRoleObjectTypeCode newAccountConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRoleId), AssociatedObjectTypeCode = Account.EntityLogicalName }; _serviceProxy.Create(newAccountConnectionRoleTypeCode); Console.WriteLine( "Created a related Connection Role Object Type Code record for Account."); // Create a related Connection Role Object Type Code record for Contact ConnectionRoleObjectTypeCode newContactConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRoleId), AssociatedObjectTypeCode = Contact.EntityLogicalName }; _serviceProxy.Create(newContactConnectionRoleTypeCode); Console.WriteLine( "Created a related Connection Role Object Type Code record for Contact."); //</snippetCreateConnectionRole1> 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> /// This method creates any entity records that this sample requires. /// Create a primary connection role instance. /// Create a reciprocal connection role instance. /// Associate the connection roles. /// </summary> public void CreateRequiredRecords() { // Define some anonymous types to define the range // of possible connection property values. var Categories = new { Business = 1, Family = 2, Social = 3, Sales = 4, Other = 5 }; // Create the Connection Roles. // Create the primary connection Role instance. ConnectionRole setupPrimaryConnectionRole = new ConnectionRole { Name = "Example Primary Connection Role", Category = new OptionSetValue(Categories.Business), }; _primaryConnectionRoleId = _serviceProxy.Create(setupPrimaryConnectionRole); Console.WriteLine("Created {0}.", setupPrimaryConnectionRole.Name); // Create a related Connection Role Object Type Code record for Account // on the primary role. ConnectionRoleObjectTypeCode accountPrimaryConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _primaryConnectionRoleId), AssociatedObjectTypeCode = Account.EntityLogicalName }; _serviceProxy.Create(accountPrimaryConnectionRoleTypeCode); Console.WriteLine(@"Created a related Connection Role Object Type Code record for Account on the primary role."); // Create another Connection Role. ConnectionRole setupReciprocalConnectionRole = new ConnectionRole { Name = "Example Reciprocal Connection Role", Category = new OptionSetValue(Categories.Business), }; _reciprocalConnectionRoleId = _serviceProxy.Create(setupReciprocalConnectionRole); Console.WriteLine("Created {0}.", setupReciprocalConnectionRole.Name); // Create a related Connection Role Object Type Code record for Account // on the related role. ConnectionRoleObjectTypeCode accountReciprocalConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _reciprocalConnectionRoleId), AssociatedObjectTypeCode = Account.EntityLogicalName }; _serviceProxy.Create(accountReciprocalConnectionRoleTypeCode); Console.WriteLine(@"Created a related Connection Role Object Type Code record for Account on the related role."); // Associate the connection roles. AssociateRequest associateConnectionRoles = new AssociateRequest { Target = new EntityReference(ConnectionRole.EntityLogicalName, _primaryConnectionRoleId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(ConnectionRole.EntityLogicalName, _reciprocalConnectionRoleId) }, // The name of the relationship connection role association // relationship in MS CRM Relationship = new Relationship() { PrimaryEntityRole = EntityRole.Referencing, // Referencing or Referenced based on N:1 or 1:N reflexive relationship. SchemaName = "connectionroleassociation_association" } }; _serviceProxy.Execute(associateConnectionRoles); return; }
/// <summary> /// Create and configure the organization service proxy. /// Call the method to create any data that this sample requires. /// Update the connectionrole instance. /// Optionally delete any entity records that were created for this sample. /// </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(); //<snippetUpdateConnectionRole1> // Define some anonymous types to define the range // of possible connection property values. var Categories = new { Business = 1, Family = 2, Social = 3, Sales = 4, Other = 5 }; // Update the connectionrole instance. ConnectionRole connectionRole = new ConnectionRole { ConnectionRoleId = _connectionRoleId, Name = "Updated Connection Role", Description = "This is an updated connection role.", Category = new OptionSetValue(Categories.Other) }; _serviceProxy.Update(connectionRole); //</snippetUpdateConnectionRole1> Console.WriteLine("Updated the connectionrole instance."); 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; } }
[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 // Define some anonymous types to define the range // of possible connection property values. var Categories = new { Business = 1, Family = 2, Social = 3, Sales = 4, Other = 5 }; // Update the connectionrole instance. ConnectionRole connectionRole = new ConnectionRole { ConnectionRoleId = _connectionRoleId, Name = "Updated Connection Role", Description = "This is an updated connection role.", Category = new OptionSetValue(Categories.Other) }; service.Update(connectionRole); Console.WriteLine("Updated the connectionrole instance."); #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(); } }
public void NotifyStateConnected(ConnectionRole roleInConnection) { _roleInLastConnection = roleInConnection; if(StateConnectedEvent != null) { StateConnectedEvent.Invoke(); } }