[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 revenue metric, setting the Amount Data Type to 'Money' // and the Metric Type to 'Amount'. Metric sampleMetric = new Metric() { Name = "Sample Revenue Metric", AmountDataType = new OptionSetValue(0), IsAmount = true, }; _metricId = service.Create(sampleMetric); Console.Write("Created revenue metric, "); // Create first RollupField which targets the estimated values. RollupField inProgress = new RollupField() { SourceEntity = Opportunity.EntityLogicalName, SourceAttribute = "estimatedvalue", GoalAttribute = "inprogressmoney", SourceState = 0, EntityForDateAttribute = Opportunity.EntityLogicalName, DateAttribute = "estimatedclosedate", MetricId = new EntityReference(Metric.EntityLogicalName, _metricId), }; _inProgressId = service.Create(inProgress); Console.Write("created in-progress RollupField, "); // Create second RollupField which targets the actual values. RollupField actual = new RollupField() { SourceEntity = Opportunity.EntityLogicalName, SourceAttribute = "actualvalue", GoalAttribute = "actualmoney", SourceState = 1, EntityForDateAttribute = Opportunity.EntityLogicalName, DateAttribute = "actualclosedate", MetricId = new EntityReference(Metric.EntityLogicalName, _metricId) }; _actualId = service.Create(actual); Console.Write("created actual revenue RollupField, "); // Create the goal rollup queries. // Note: Formatting the FetchXml onto multiple lines in the following // rollup queries causes the lenth property to be greater than 1,000 // chars and will cause an exception. // The first query locates opportunities in the first sales // representative's area (zip code: 60661). GoalRollupQuery goalRollupQuery = new GoalRollupQuery() { Name = "First Example Goal Rollup Query", QueryEntityType = Opportunity.EntityLogicalName, FetchXml = @"<fetch version=""1.0"" output-format=""xml-platform"" mapping=""logical"" distinct=""false""><entity name=""opportunity""><attribute name=""totalamount""/><attribute name=""name""/><attribute name=""customerid""/><attribute name=""estimatedvalue""/><attribute name=""statuscode""/><attribute name=""opportunityid""/><order attribute=""name"" descending=""false""/><link-entity name=""account"" from=""accountid"" to=""customerid"" alias=""aa""><filter type=""and""><condition attribute=""address1_postalcode"" operator=""eq"" value=""60661""/></filter></link-entity></entity></fetch>" }; _rollupQueryIds.Add(service.Create(goalRollupQuery)); Console.Write("created first rollup query for zip code 60661, "); // The second query locates opportunities in the second sales // representative's area (zip code: 99999). goalRollupQuery = new GoalRollupQuery() { Name = "Second Example Goal Rollup Query", QueryEntityType = Opportunity.EntityLogicalName, FetchXml = @"<fetch version=""1.0"" output-format=""xml-platform"" mapping=""logical"" distinct=""false""><entity name=""opportunity""><attribute name=""totalamount""/><attribute name=""customerid""/><attribute name=""estimatedvalue""/><attribute name=""statuscode""/><attribute name=""opportunityid""/><order attribute=""name"" descending=""false""/><link-entity name=""account"" from=""accountid"" to=""customerid"" alias=""aa""><filter type=""and""><condition attribute=""address1_postalcode"" operator=""eq"" value=""99999""/></filter></link-entity></entity></fetch>" }; _rollupQueryIds.Add(service.Create(goalRollupQuery)); Console.WriteLine("created second rollup query for zip code 99999."); Console.WriteLine(); // Create three goals: one parent goal and two child goals. Goal parentGoal = new Goal() { Title = "Parent Goal Example", RollupOnlyFromChildGoals = true, ConsiderOnlyGoalOwnersRecords = true, TargetMoney = new Money(300.0M), IsFiscalPeriodGoal = false, MetricId = new EntityReference { Id = _metricId, LogicalName = Metric.EntityLogicalName }, GoalOwnerId = new EntityReference { Id = _salesManagerId, LogicalName = SystemUser.EntityLogicalName }, OwnerId = new EntityReference { Id = _salesManagerId, LogicalName = SystemUser.EntityLogicalName }, GoalStartDate = DateTime.Today.AddDays(-1), GoalEndDate = DateTime.Today.AddDays(30) }; _parentGoalId = service.Create(parentGoal); Console.WriteLine("Created parent goal"); Console.WriteLine("-------------------"); Console.WriteLine("Target: {0}", parentGoal.TargetMoney.Value); Console.WriteLine("Goal owner: {0}", parentGoal.GoalOwnerId.Id); Console.WriteLine("Goal Start Date: {0}", parentGoal.GoalStartDate); Console.WriteLine("Goal End Date: {0}", parentGoal.GoalEndDate); Console.WriteLine("<End of Listing>"); Console.WriteLine(); Goal firstChildGoal = new Goal() { Title = "First Child Goal Example", ConsiderOnlyGoalOwnersRecords = true, TargetMoney = new Money(100.0M), IsFiscalPeriodGoal = false, MetricId = new EntityReference { Id = _metricId, LogicalName = Metric.EntityLogicalName }, ParentGoalId = new EntityReference { Id = _parentGoalId, LogicalName = Goal.EntityLogicalName }, GoalOwnerId = new EntityReference { Id = _salesRepresentativeIds[0], LogicalName = SystemUser.EntityLogicalName }, OwnerId = new EntityReference { Id = _salesManagerId, LogicalName = SystemUser.EntityLogicalName }, RollUpQueryActualMoneyId = new EntityReference { Id = _rollupQueryIds[0], LogicalName = GoalRollupQuery.EntityLogicalName }, GoalStartDate = DateTime.Today.AddDays(-1), GoalEndDate = DateTime.Today.AddDays(30) }; _firstChildGoalId = service.Create(firstChildGoal); Console.WriteLine("First child goal"); Console.WriteLine("----------------"); Console.WriteLine("Target: {0}", firstChildGoal.TargetMoney.Value); Console.WriteLine("Goal owner: {0}", firstChildGoal.GoalOwnerId.Id); Console.WriteLine("Goal Start Date: {0}", firstChildGoal.GoalStartDate); Console.WriteLine("Goal End Date: {0}", firstChildGoal.GoalEndDate); Console.WriteLine(); Goal secondChildGoal = new Goal() { Title = "Second Child Goal Example", ConsiderOnlyGoalOwnersRecords = true, TargetMoney = new Money(200.0M), IsFiscalPeriodGoal = false, MetricId = new EntityReference { Id = _metricId, LogicalName = Metric.EntityLogicalName }, ParentGoalId = new EntityReference { Id = _parentGoalId, LogicalName = Goal.EntityLogicalName }, GoalOwnerId = new EntityReference { Id = _salesRepresentativeIds[1], LogicalName = SystemUser.EntityLogicalName }, OwnerId = new EntityReference { Id = _salesManagerId, LogicalName = SystemUser.EntityLogicalName }, RollUpQueryActualMoneyId = new EntityReference { Id = _rollupQueryIds[1], LogicalName = GoalRollupQuery.EntityLogicalName }, GoalStartDate = DateTime.Today.AddDays(-1), GoalEndDate = DateTime.Today.AddDays(30) }; _secondChildGoalId = service.Create(secondChildGoal); Console.WriteLine("Second child goal"); Console.WriteLine("-----------------"); Console.WriteLine("Target: {0}", secondChildGoal.TargetMoney.Value); Console.WriteLine("Goal owner: {0}", secondChildGoal.GoalOwnerId.Id); Console.WriteLine("Goal Start Date: {0}", secondChildGoal.GoalStartDate); Console.WriteLine("Goal End Date: {0}", secondChildGoal.GoalEndDate); Console.WriteLine(); // Calculate roll-up of goals. RecalculateRequest recalculateRequest = new RecalculateRequest() { Target = new EntityReference(Goal.EntityLogicalName, _parentGoalId) }; service.Execute(recalculateRequest); Console.WriteLine("Calculated roll-up of goals."); // Retrieve and report 3 different computed values for the goals // - Percentage // - ComputedTargetAsOfTodayPercentageAchieved // - ComputedTargetAsOfTodayMoney QueryExpression retrieveValues = new QueryExpression() { EntityName = Goal.EntityLogicalName, ColumnSet = new ColumnSet( "title", "percentage", "computedtargetasoftodaypercentageachieved", "computedtargetasoftodaymoney") }; EntityCollection ec = service.RetrieveMultiple(retrieveValues); // Compute and display the results for (int i = 0; i < ec.Entities.Count; i++) { Goal temp = (Goal)ec.Entities[i]; Console.WriteLine("Roll-up details for goal: {0}", temp.Title); Console.WriteLine("---------------"); Console.WriteLine("Percentage: {0}", temp.Percentage); Console.WriteLine("ComputedTargetAsOfTodayPercentageAchieved: {0}", temp.ComputedTargetAsOfTodayPercentageAchieved); Console.WriteLine("ComputedTargetAsOfTodayMoney: {0}", temp.ComputedTargetAsOfTodayMoney.Value); Console.WriteLine("<End of Listing>"); } #region Clean up CleanUpSample(service); #endregion Clean up } #endregion Demonstrate #endregion Sample Code else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Dynamics CRM"; 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(); } }
[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 revenue metric, setting the Amount Data Type to 'Money' // and the Metric Type to 'Amount'. Metric sampleMetric = new Metric() { Name = "Sample Revenue Metric", AmountDataType = new OptionSetValue(0), IsAmount = true, }; _metricId = service.Create(sampleMetric); sampleMetric.Id = _metricId; Console.Write("Created revenue metric, "); #region Create RollupFields // Create RollupField which targets the actual totals. RollupField actual = new RollupField() { SourceEntity = SalesOrder.EntityLogicalName, SourceAttribute = "totalamount", GoalAttribute = "actualmoney", SourceState = 1, EntityForDateAttribute = SalesOrder.EntityLogicalName, DateAttribute = "datefulfilled", MetricId = sampleMetric.ToEntityReference() }; _actualId = service.Create(actual); Console.Write("created actual revenue RollupField, "); #endregion #region Create the goal rollup query // The query locates sales orders in the first sales // representative's area (zip code: 60661) and with a value // greater than $1,000. GoalRollupQuery goalRollupQuery = new GoalRollupQuery() { Name = "First Example Goal Rollup Query", QueryEntityType = SalesOrder.EntityLogicalName, FetchXml = @"<fetch mapping=""logical"" version=""1.0""><entity name=""salesorder""><attribute name=""customerid"" /><attribute name=""name"" /><attribute name=""salesorderid"" /><attribute name=""statuscode"" /><attribute name=""totalamount"" /><order attribute=""name"" /><filter><condition attribute=""totalamount"" operator=""gt"" value=""1000"" /><condition attribute=""billto_postalcode"" operator=""eq"" value=""60661"" /></filter></entity></fetch>" }; _rollupQueryId = service.Create(goalRollupQuery); goalRollupQuery.Id = _rollupQueryId; Console.Write("created rollup query."); Console.WriteLine(); #endregion #region Create two goals: one parent and one child goal // Create the parent goal. Goal parentGoal = new Goal() { Title = "Parent Goal Example", RollupOnlyFromChildGoals = true, TargetMoney = new Money(1000.0M), IsFiscalPeriodGoal = false, MetricId = sampleMetric.ToEntityReference(), GoalOwnerId = new EntityReference { Id = _salesManagerId, LogicalName = SystemUser.EntityLogicalName }, OwnerId = new EntityReference { Id = _salesManagerId, LogicalName = SystemUser.EntityLogicalName }, GoalStartDate = DateTime.Today.AddDays(-1), GoalEndDate = DateTime.Today.AddDays(30) }; _parentGoalId = service.Create(parentGoal); parentGoal.Id = _parentGoalId; Console.WriteLine("Created parent goal"); Console.WriteLine("-------------------"); Console.WriteLine("Target: {0}", parentGoal.TargetMoney.Value); Console.WriteLine("Goal owner: {0}", parentGoal.GoalOwnerId.Id); Console.WriteLine("Goal Start Date: {0}", parentGoal.GoalStartDate); Console.WriteLine("Goal End Date: {0}", parentGoal.GoalEndDate); Console.WriteLine("<End of Listing>"); Console.WriteLine(); // Create the child goal. Goal firstChildGoal = new Goal() { Title = "First Child Goal Example", ConsiderOnlyGoalOwnersRecords = true, TargetMoney = new Money(1000.0M), IsFiscalPeriodGoal = false, MetricId = sampleMetric.ToEntityReference(), ParentGoalId = parentGoal.ToEntityReference(), GoalOwnerId = new EntityReference { Id = _salesRepresentativeId, LogicalName = SystemUser.EntityLogicalName }, OwnerId = new EntityReference { Id = _salesManagerId, LogicalName = SystemUser.EntityLogicalName }, RollUpQueryActualMoneyId = goalRollupQuery.ToEntityReference(), GoalStartDate = DateTime.Today.AddDays(-1), GoalEndDate = DateTime.Today.AddDays(30) }; _firstChildGoalId = service.Create(firstChildGoal); Console.WriteLine("First child goal"); Console.WriteLine("----------------"); Console.WriteLine("Target: {0}", firstChildGoal.TargetMoney.Value); Console.WriteLine("Goal owner: {0}", firstChildGoal.GoalOwnerId.Id); Console.WriteLine("Goal Start Date: {0}", firstChildGoal.GoalStartDate); Console.WriteLine("Goal End Date: {0}", firstChildGoal.GoalEndDate); Console.WriteLine("<End of Listing>"); Console.WriteLine(); #endregion // Calculate roll-up of goals. // Note: Recalculate can be run against any goal in the tree to cause // a rollup of the whole tree. RecalculateRequest recalculateRequest = new RecalculateRequest() { Target = parentGoal.ToEntityReference() }; service.Execute(recalculateRequest); Console.WriteLine("Calculated roll-up of goals."); Console.WriteLine(); // Retrieve and report 3 different computed values for the goals // - Percentage // - ComputedTargetAsOfTodayPercentageAchieved // - ComputedTargetAsOfTodayMoney QueryExpression retrieveValues = new QueryExpression() { EntityName = Goal.EntityLogicalName, ColumnSet = new ColumnSet( "title", "computedtargetasoftodaypercentageachieved", "computedtargetasoftodaymoney") }; EntityCollection ec = service.RetrieveMultiple(retrieveValues); // Compute and display the results for (int i = 0; i < ec.Entities.Count; i++) { Goal temp = (Goal)ec.Entities[i]; Console.WriteLine("Roll-up details for goal: {0}", temp.Title); Console.WriteLine("---------------"); Console.WriteLine("ComputedTargetAsOfTodayPercentageAchieved: {0}", temp.ComputedTargetAsOfTodayPercentageAchieved); Console.WriteLine("ComputedTargetAsOfTodayMoney: {0}", temp.ComputedTargetAsOfTodayMoney.Value); Console.WriteLine("<End of Listing>"); } #region Clean up CleanUpSample(service); #endregion Clean up } #endregion Demonstrate #endregion Sample Code else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Dynamics CRM"; 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(); } }
[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 // Get the current user's information. WhoAmIRequest userRequest = new WhoAmIRequest(); WhoAmIResponse userResponse = (WhoAmIResponse)service.Execute(userRequest); // Retrieve the working hours of the current user. QueryScheduleRequest scheduleRequest = new QueryScheduleRequest { ResourceId = userResponse.UserId, Start = DateTime.Now, End = DateTime.Today.AddDays(7), TimeCodes = new TimeCode[] { TimeCode.Available } }; QueryScheduleResponse scheduleResponse = (QueryScheduleResponse)service.Execute(scheduleRequest); // Verify if some data is returned for the availability of the current user if (scheduleResponse.TimeInfos.Length > 0) { Console.WriteLine("Successfully queried the working hours of the current user."); } } 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; } } } #endregion Demonstrate catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) { service.Dispose(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
[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 three e-mail attachments for (int i = 0; i < 3; i++) { ActivityMimeAttachment _sampleAttachment = new ActivityMimeAttachment { ObjectId = new EntityReference(Email.EntityLogicalName, emailId), ObjectTypeCode = Email.EntityLogicalName, Subject = String.Format("Sample Attachment {0}", i), Body = System.Convert.ToBase64String( new ASCIIEncoding().GetBytes("Example Attachment")), FileName = String.Format("ExampleAttachment{0}.txt", i) }; emailAttachmentId[i] = service.Create(_sampleAttachment); } Console.WriteLine("Created three e-mail attachments for the e-mail activity."); // Retrieve an attachment including its id, subject, filename and body. ActivityMimeAttachment _singleAttachment = (ActivityMimeAttachment)service.Retrieve( ActivityMimeAttachment.EntityLogicalName, emailAttachmentId[0], new ColumnSet("activitymimeattachmentid", "subject", "filename", "body")); Console.WriteLine("Retrieved an email attachment, {0}.", _singleAttachment.FileName); // Update attachment _singleAttachment.FileName = "ExampleAttachmentUpdated.txt"; service.Update(_singleAttachment); Console.WriteLine("Updated the retrieved e-mail attachment to {0}.", _singleAttachment.FileName); // Retrieve all attachments associated with the email activity. QueryExpression _attachmentQuery = new QueryExpression { EntityName = ActivityMimeAttachment.EntityLogicalName, ColumnSet = new ColumnSet("activitymimeattachmentid"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "objectid", Operator = ConditionOperator.Equal, Values = { emailId } }, new ConditionExpression { AttributeName = "objecttypecode", Operator = ConditionOperator.Equal, Values = { Email.EntityLogicalName } } } } }; EntityCollection results = service.RetrieveMultiple( _attachmentQuery); Console.WriteLine("Retrieved all the e-mail attachments."); #region Clean up CleanUpSample(service); #endregion Clean up } #endregion Demonstrate #endregion Sample Code else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Dynamics CRM"; 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(); } }
[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 // Grab all Solution Components for a solution. QueryByAttribute componentQuery = new QueryByAttribute { EntityName = SolutionComponent.EntityLogicalName, ColumnSet = new ColumnSet("componenttype", "objectid", "solutioncomponentid", "solutionid"), Attributes = { "solutionid" }, // In your code, this value would probably come from another query. Values = { _primarySolutionId } }; IEnumerable <SolutionComponent> allComponents = service.RetrieveMultiple(componentQuery).Entities.Cast <SolutionComponent>(); foreach (SolutionComponent component in allComponents) { // For each solution component, retrieve all dependencies for the component. RetrieveDependentComponentsRequest dependentComponentsRequest = new RetrieveDependentComponentsRequest { ComponentType = component.ComponentType.Value, ObjectId = component.ObjectId.Value }; RetrieveDependentComponentsResponse dependentComponentsResponse = (RetrieveDependentComponentsResponse)service.Execute(dependentComponentsRequest); // If there are no dependent components, we can ignore this component. if (dependentComponentsResponse.EntityCollection.Entities.Any() == false) { continue; } // If there are dependencies upon this solution component, and the solution // itself is managed, then you will be unable to delete the solution. Console.WriteLine("Found {0} dependencies for Component {1} of type {2}", dependentComponentsResponse.EntityCollection.Entities.Count, component.ObjectId.Value, component.ComponentType.Value ); //A more complete report requires more code foreach (Dependency d in dependentComponentsResponse.EntityCollection.Entities) { DependencyReport(service, d); } } //Find out if any dependencies on a specific global option set would prevent it from being deleted // Use the RetrieveOptionSetRequest message to retrieve // a global option set by it's name. RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest { Name = _globalOptionSetName }; // Execute the request. RetrieveOptionSetResponse retrieveOptionSetResponse = (RetrieveOptionSetResponse)service.Execute( retrieveOptionSetRequest); _globalOptionSetId = retrieveOptionSetResponse.OptionSetMetadata.MetadataId; if (_globalOptionSetId != null) { //Use the global OptionSet MetadataId with the appropriate componenttype // to call RetrieveDependenciesForDeleteRequest RetrieveDependenciesForDeleteRequest retrieveDependenciesForDeleteRequest = new RetrieveDependenciesForDeleteRequest { ComponentType = (int)componenttype.OptionSet, ObjectId = (Guid)_globalOptionSetId }; RetrieveDependenciesForDeleteResponse retrieveDependenciesForDeleteResponse = (RetrieveDependenciesForDeleteResponse)service.Execute(retrieveDependenciesForDeleteRequest); Console.WriteLine(""); foreach (Dependency d in retrieveDependenciesForDeleteResponse.EntityCollection.Entities) { if (d.DependentComponentType.Value == 2)//Just testing for Attributes { String attributeLabel = ""; RetrieveAttributeRequest retrieveAttributeRequest = new RetrieveAttributeRequest { MetadataId = (Guid)d.DependentComponentObjectId }; RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute(retrieveAttributeRequest); AttributeMetadata attmet = retrieveAttributeResponse.AttributeMetadata; attributeLabel = attmet.DisplayName.UserLocalizedLabel.Label; Console.WriteLine("An {0} named {1} will prevent deleting the {2} global option set.", (componenttype)d.DependentComponentType.Value, attributeLabel, _globalOptionSetName); } } } #region Clean up CleanUpSample(service); #endregion Clen up //DeleteRequiredRecords(promptForDelete); } #endregion Demonstrate #endregion Sample Code else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Dynamics CRM"; 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(); } }
[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 // TODO Add demonstration code here // Create the count metric, setting the Metric Type to 'Count' by // setting IsAmount to false. Metric sampleMetric = new Metric() { Name = "Sample Count Metric", IsAmount = false, }; _metricId = _serviceProxy.Create(sampleMetric); sampleMetric.Id = _metricId; Console.Write("Created phone call metric, "); #region Create RollupFields // Create RollupField which targets completed (received) phone calls. RollupField actual = new RollupField() { SourceEntity = PhoneCall.EntityLogicalName, GoalAttribute = "actualinteger", SourceState = 1, SourceStatus = 4, EntityForDateAttribute = PhoneCall.EntityLogicalName, DateAttribute = "actualend", MetricId = sampleMetric.ToEntityReference() }; _actualId = _serviceProxy.Create(actual); Console.Write("created actual revenue RollupField, "); // Create RollupField which targets open (in-progress) phone calls. RollupField inprogress = new RollupField() { SourceEntity = PhoneCall.EntityLogicalName, GoalAttribute = "inprogressinteger", SourceState = 0, EntityForDateAttribute = PhoneCall.EntityLogicalName, DateAttribute = "createdon", MetricId = sampleMetric.ToEntityReference() }; _inprogressId = _serviceProxy.Create(inprogress); Console.Write("created in-progress revenue RollupField, "); #endregion #region Create the goal rollup queries // Note: Formatting the FetchXml onto multiple lines in the following // rollup queries causes the length property to be greater than 1,000 // chars and will cause an exception. // The following query locates closed incoming phone calls. GoalRollupQuery goalRollupQuery = new GoalRollupQuery() { Name = "Example Goal Rollup Query - Actual", QueryEntityType = PhoneCall.EntityLogicalName, FetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='phonecall'><attribute name='subject'/><attribute name='statecode'/><attribute name='prioritycode'/><attribute name='scheduledend'/><attribute name='createdby'/><attribute name='regardingobjectid'/><attribute name='activityid'/><order attribute='subject' descending='false'/><filter type='and'><condition attribute='directioncode' operator='eq' value='0'/><condition attribute='statecode' operator='eq' value='1' /></filter></entity></fetch>" }; _rollupQueryIds.Add(_serviceProxy.Create(goalRollupQuery)); goalRollupQuery.Id = _rollupQueryIds[0]; // The following query locates open incoming phone calls. GoalRollupQuery inProgressGoalRollupQuery = new GoalRollupQuery() { Name = "Example Goal Rollup Query - InProgress", QueryEntityType = PhoneCall.EntityLogicalName, FetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='phonecall'><attribute name='subject'/><attribute name='statecode'/><attribute name='prioritycode'/><attribute name='scheduledend'/><attribute name='createdby'/><attribute name='regardingobjectid'/><attribute name='activityid'/><order attribute='subject' descending='false'/><filter type='and'><condition attribute='directioncode' operator='eq' value='0'/><condition attribute='statecode' operator='eq' value='0' /></filter></entity></fetch>" }; _rollupQueryIds.Add(_serviceProxy.Create(inProgressGoalRollupQuery)); inProgressGoalRollupQuery.Id = _rollupQueryIds[1]; Console.Write("created rollup queries for incoming phone calls.\n"); Console.WriteLine(); #endregion #region Create a goal to track the open incoming phone calls. // Create the goal. Goal goal = new Goal() { Title = "Sample Goal", RollupOnlyFromChildGoals = false, ConsiderOnlyGoalOwnersRecords = false, TargetInteger = 5, RollupQueryActualIntegerId = goalRollupQuery.ToEntityReference(), RollUpQueryInprogressIntegerId = inProgressGoalRollupQuery.ToEntityReference(), IsFiscalPeriodGoal = false, MetricId = sampleMetric.ToEntityReference(), GoalOwnerId = new EntityReference { Id = _salesManagerId, LogicalName = SystemUser.EntityLogicalName }, OwnerId = new EntityReference { Id = _salesManagerId, LogicalName = SystemUser.EntityLogicalName }, GoalStartDate = DateTime.Today.AddDays(-1), GoalEndDate = DateTime.Today.AddDays(30) }; _goalId = _serviceProxy.Create(goal); goal.Id = _goalId; Console.WriteLine("Created goal"); Console.WriteLine("-------------------"); Console.WriteLine("Target: {0}", goal.TargetInteger.Value); Console.WriteLine("Goal owner: {0}", goal.GoalOwnerId.Id); Console.WriteLine("Goal Start Date: {0}", goal.GoalStartDate); Console.WriteLine("Goal End Date: {0}", goal.GoalEndDate); Console.WriteLine("<End of Listing>"); Console.WriteLine(); #endregion #region Calculate rollup and display result // Calculate roll-up of the goal. RecalculateRequest recalculateRequest = new RecalculateRequest() { Target = goal.ToEntityReference() }; _serviceProxy.Execute(recalculateRequest); Console.WriteLine("Calculated roll-up of goal."); Console.WriteLine(); // Retrieve and report 3 different computed values for the goal // - Percentage // - Actual (Integer) // - In-Progress (Integer) QueryExpression retrieveValues = new QueryExpression() { EntityName = Goal.EntityLogicalName, ColumnSet = new ColumnSet( "title", "percentage", "actualinteger", "inprogressinteger") }; EntityCollection ec = _serviceProxy.RetrieveMultiple(retrieveValues); // Compute and display the results. for (int i = 0; i < ec.Entities.Count; i++) { Goal temp = (Goal)ec.Entities[i]; Console.WriteLine("Roll-up details for goal: {0}", temp.Title); Console.WriteLine("---------------"); Console.WriteLine("Percentage Achieved: {0}", temp.Percentage); Console.WriteLine("Actual (Integer): {0}", temp.ActualInteger.Value); Console.WriteLine("In-Progress (Integer): {0}", temp.InProgressInteger.Value); Console.WriteLine("<End of Listing>"); } Console.WriteLine(); #endregion #region Update goal to override the actual rollup value // Override the actual and in-progress values of the goal. // To prevent rollup values to be overwritten during next Recalculate operation, // set: goal.IsOverridden = true; goal.IsOverride = true; goal.ActualInteger = 10; goal.InProgressInteger = 5; // Update the goal. UpdateRequest update = new UpdateRequest() { Target = goal }; _serviceProxy.Execute(update); Console.WriteLine("Goal actual and in-progress values overridden."); Console.WriteLine(); #endregion #region Retrieve result of manual override // Retrieve and report 3 different computed values for the goal // - Percentage // - Actual (Integer) // - In-Progress (Integer) retrieveValues = new QueryExpression() { EntityName = Goal.EntityLogicalName, ColumnSet = new ColumnSet( "title", "percentage", "actualinteger", "inprogressinteger") }; ec = _serviceProxy.RetrieveMultiple(retrieveValues); // Compute and display the results. for (int i = 0; i < ec.Entities.Count; i++) { Goal temp = (Goal)ec.Entities[i]; Console.WriteLine("Roll-up details for goal: {0}", temp.Title); Console.WriteLine("---------------"); Console.WriteLine("Percentage Achieved: {0}", temp.Percentage); Console.WriteLine("Actual (Integer): {0}", temp.ActualInteger.Value); Console.WriteLine("In-Progress (Integer): {0}", temp.InProgressInteger.Value); Console.WriteLine("<End of Listing>"); } Console.WriteLine(); #endregion #region Close the goal // Close the goal. SetStateRequest closeGoal = new SetStateRequest() { EntityMoniker = goal.ToEntityReference(), State = new OptionSetValue(1), Status = new OptionSetValue(1) }; Console.WriteLine("Goal closed."); #endregion #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(); } }
[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 Console.WriteLine("Enabling auditing on the organization and account entities."); // Enable auditing on the organization. // First, get the organization's ID from the system user record. Guid orgId = ((WhoAmIResponse)service.Execute(new WhoAmIRequest())).OrganizationId; // Next, retrieve the organization's record. var org = service.Retrieve(Organization.EntityLogicalName, orgId, new ColumnSet(new string[] { "organizationid", "isauditenabled" })) as Organization; // Finally, enable auditing on the organization. bool organizationAuditingFlag = org.IsAuditEnabled.Value; org.IsAuditEnabled = true; service.Update(org); // Enable auditing on account entities. bool accountAuditingFlag = EnableEntityAuditing(service, Account.EntityLogicalName, true); #endregion Enable Auditing for an Account #region Retrieve the Record Change History Console.WriteLine("Retrieving the account change history.\n"); // Retrieve the audit history for the account and display it. var changeRequest = new RetrieveRecordChangeHistoryRequest(); changeRequest.Target = new EntityReference(Account.EntityLogicalName, _newAccountId); var changeResponse = (RetrieveRecordChangeHistoryResponse)service.Execute(changeRequest); AuditDetailCollection details = changeResponse.AuditDetailCollection; foreach (AttributeAuditDetail detail in details.AuditDetails) { // Display some of the detail information in each audit record. DisplayAuditDetails(service, detail); } #endregion Retrieve the Record Change History #region Retrieve the Attribute Change History // Update the Telephone1 attribute in the Account entity record. var accountToUpdate = new Account(); accountToUpdate.AccountId = _newAccountId; accountToUpdate.Telephone1 = "123-555-5555"; service.Update(accountToUpdate); Console.WriteLine("Updated the Telephone1 field in the Account entity."); // Retrieve the attribute change history. Console.WriteLine("Retrieving the attribute change history for Telephone1."); var attributeChangeHistoryRequest = new RetrieveAttributeChangeHistoryRequest { Target = new EntityReference( Account.EntityLogicalName, _newAccountId), AttributeLogicalName = "telephone1" }; var attributeChangeHistoryResponse = (RetrieveAttributeChangeHistoryResponse)service.Execute(attributeChangeHistoryRequest); // Display the attribute change history. details = attributeChangeHistoryResponse.AuditDetailCollection; foreach (var detail in details.AuditDetails) { DisplayAuditDetails(service, detail); } // Save an Audit record ID for later use. Guid auditSampleId = details.AuditDetails.First().AuditRecord.Id; #endregion Retrieve the Attribute Change History #region Retrieve the Audit Details Console.WriteLine("Retrieving audit details for an audit record."); // Retrieve the audit details and display them. var auditDetailsRequest = new RetrieveAuditDetailsRequest { AuditId = auditSampleId }; var auditDetailsResponse = (RetrieveAuditDetailsResponse)service.Execute(auditDetailsRequest); DisplayAuditDetails(service, auditDetailsResponse.AuditDetail); #endregion Retrieve the Audit Details #region Revert Auditing // Set the organization and account auditing flags back to the old values org.IsAuditEnabled = organizationAuditingFlag; service.Update(org); EnableEntityAuditing(service, Account.EntityLogicalName, accountAuditingFlag); #endregion Revert Auditing #region Clean up CleanUpSample(service); #endregion Clean up } #endregion Demonstrate else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Dynamics CRM"; 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(); } }
[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 var request = new RetrieveAllEntitiesRequest() { EntityFilters = EntityFilters.Attributes, // When RetrieveAsIfPublished property is set to false, retrieves only the currently published changes. Default setting of the property is false. // When RetrieveAsIfPublished property is set to true, retrieves the changes that are published and those changes that have not been published. RetrieveAsIfPublished = false }; // Retrieve the MetaData. RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)service.Execute(request); // Create an instance of StreamWriter to write text to a file. // The using statement also closes the StreamWriter. // To view this file, right click the file and choose open with Excel. // Excel will figure out the schema and display the information in columns. String filename = String.Concat("AllAttributeDesc.xml"); using (var sw = new StreamWriter(filename)) { // Create Xml Writer. var metadataWriter = new XmlTextWriter(sw); // Start Xml File. metadataWriter.WriteStartDocument(); // Metadata Xml Node. metadataWriter.WriteStartElement("Metadata"); foreach (EntityMetadata currentEntity in response.EntityMetadata) { //if (currentEntity.IsIntersect.Value == false) if (true) { // Start Entity Node metadataWriter.WriteStartElement("Entity"); // Write the Entity's Information. metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName); if (currentEntity.IsCustomizable.Value == true) { metadataWriter.WriteElementString("IsCustomizable", "yes"); } else { metadataWriter.WriteElementString("IsCustomizable", "no"); } if (currentEntity.IsIntersect.Value == true) { metadataWriter.WriteElementString("IsIntersect", "yes"); } else { metadataWriter.WriteElementString("IsIntersect", "no"); } #region Attributes // Write Entity's Attributes. metadataWriter.WriteStartElement("Attributes"); foreach (AttributeMetadata currentAttribute in currentEntity.Attributes) { // Only write out main attributes. if (currentAttribute.AttributeOf == null) { // Start Attribute Node metadataWriter.WriteStartElement("Attribute"); // Write Attribute's information. metadataWriter.WriteElementString("LogicalName", currentAttribute.LogicalName); // Write the Description if it is set. if (currentAttribute.Description.UserLocalizedLabel != null) { metadataWriter.WriteElementString("Description", currentAttribute.Description.UserLocalizedLabel.Label.ToString()); } metadataWriter.WriteElementString("Type", currentAttribute.AttributeType.Value.ToString()); if (currentAttribute.DisplayName.UserLocalizedLabel != null) { metadataWriter.WriteElementString("DisplayName", currentAttribute.DisplayName.UserLocalizedLabel.Label.ToString()); } if (currentAttribute.SchemaName != null) { metadataWriter.WriteElementString("SchemaName", currentAttribute.SchemaName.ToString()); } if (currentAttribute.IntroducedVersion != null) { metadataWriter.WriteElementString("IntroducedVersion", currentAttribute.IntroducedVersion.ToString()); } if (currentAttribute.DeprecatedVersion != null) { metadataWriter.WriteElementString("DeprecatedVersion", currentAttribute.DeprecatedVersion.ToString()); } if (currentAttribute.IsCustomAttribute != null) { metadataWriter.WriteElementString("IsCustomAttribute", currentAttribute.IsCustomAttribute.Value.ToString()); } if (currentAttribute.IsCustomizable != null) { metadataWriter.WriteElementString("IsCustomizable", currentAttribute.IsCustomizable.Value.ToString()); } if (currentAttribute.RequiredLevel != null) { metadataWriter.WriteElementString("RequiredLevel", currentAttribute.RequiredLevel.Value.ToString()); } if (currentAttribute.IsValidForCreate != null) { metadataWriter.WriteElementString("IsValidForCreate", currentAttribute.IsValidForCreate.Value.ToString()); } if (currentAttribute.IsValidForRead != null) { metadataWriter.WriteElementString("IsValidForRead", currentAttribute.IsValidForRead.Value.ToString()); } if (currentAttribute.IsValidForUpdate != null) { metadataWriter.WriteElementString("IsValidForUpdate", currentAttribute.IsValidForUpdate.Value.ToString()); } if (currentAttribute.CanBeSecuredForCreate != null) { metadataWriter.WriteElementString("CanBeSecuredForCreate", currentAttribute.CanBeSecuredForCreate.Value.ToString()); } if (currentAttribute.CanBeSecuredForRead != null) { metadataWriter.WriteElementString("CanBeSecuredForRead", currentAttribute.CanBeSecuredForRead.Value.ToString()); } if (currentAttribute.CanBeSecuredForUpdate != null) { metadataWriter.WriteElementString("CanBeSecuredForUpdate", currentAttribute.CanBeSecuredForUpdate.Value.ToString()); } if (currentAttribute.IsAuditEnabled != null) { metadataWriter.WriteElementString("IsAuditEnabled", currentAttribute.IsAuditEnabled.Value.ToString()); } if (currentAttribute.IsManaged != null) { metadataWriter.WriteElementString("IsManaged", currentAttribute.IsManaged.Value.ToString()); } if (currentAttribute.IsPrimaryId != null) { metadataWriter.WriteElementString("IsPrimaryId", currentAttribute.IsPrimaryId.Value.ToString()); } if (currentAttribute.IsPrimaryName != null) { metadataWriter.WriteElementString("IsPrimaryName", currentAttribute.IsPrimaryName.Value.ToString()); } if (currentAttribute.IsRenameable != null) { metadataWriter.WriteElementString("IsRenameable", currentAttribute.IsRenameable.Value.ToString()); } if (currentAttribute.IsSecured != null) { metadataWriter.WriteElementString("IsSecured", currentAttribute.IsSecured.Value.ToString()); } if (currentAttribute.IsValidForAdvancedFind != null) { metadataWriter.WriteElementString("IsValidForAdvancedFind", currentAttribute.IsValidForAdvancedFind.Value.ToString()); } // End Attribute Node metadataWriter.WriteEndElement(); } } // End Attributes Node metadataWriter.WriteEndElement(); #endregion Attributes // End Entity Node metadataWriter.WriteEndElement(); } } // End Metadata Xml Node metadataWriter.WriteEndElement(); metadataWriter.WriteEndDocument(); // Close xml writer. metadataWriter.Close(); } Console.WriteLine("Done."); #endregion Demonstrate } 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(); } }
[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 // Use the InstantiateTemplate message to create an e-mail message using a template. var instTemplateReq = new InstantiateTemplateRequest { TemplateId = _templateId, ObjectId = _accountId, ObjectType = Account.EntityLogicalName }; var instTemplateResp = (InstantiateTemplateResponse)service.Execute(instTemplateReq); // Serialize the email message to XML, and save to a file. var serializer = new XmlSerializer(typeof(InstantiateTemplateResponse)); string filename = "email-message.xml"; using (var writer = new StreamWriter(filename)) { serializer.Serialize(writer, instTemplateResp); } Console.WriteLine("Created e-mail using the template."); #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(); } }
[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 var request = new RetrieveAllEntitiesRequest() { EntityFilters = EntityFilters.Entity, RetrieveAsIfPublished = true }; // Retrieve the MetaData. var response = (RetrieveAllEntitiesResponse)service.Execute(request); // Create an instance of StreamWriter to write text to a file. // The using statement also closes the StreamWriter. // To view this file, right click the file and choose open with Excel. // Excel will figure out the schema and display the information in columns. String filename = String.Concat("EntityInfo.xml"); using (var sw = new StreamWriter(filename)) { // Create Xml Writer. var metadataWriter = new XmlTextWriter(sw); // Start Xml File. metadataWriter.WriteStartDocument(); // Metadata Xml Node. metadataWriter.WriteStartElement("Metadata"); foreach (EntityMetadata currentEntity in response.EntityMetadata) { //if (currentEntity.IsIntersect.Value == false) if (true) { // Start Entity Node metadataWriter.WriteStartElement("Entity"); // Write the Entity's Information. metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName); metadataWriter.WriteElementString("OTC", currentEntity.ObjectTypeCode.ToString()); metadataWriter.WriteElementString("OwnershipType", currentEntity.OwnershipType.Value.ToString()); if (currentEntity.DisplayName.UserLocalizedLabel != null) { metadataWriter.WriteElementString("DisplayName", currentEntity.DisplayName.UserLocalizedLabel.Label); } if (currentEntity.DisplayCollectionName.UserLocalizedLabel != null) { metadataWriter.WriteElementString("DisplayCollectionName", currentEntity.DisplayCollectionName.UserLocalizedLabel.Label); } metadataWriter.WriteElementString("IntroducedVersion", currentEntity.IntroducedVersion.ToString()); metadataWriter.WriteElementString("AutoRouteToOwnerQueue", currentEntity.AutoRouteToOwnerQueue.ToString()); metadataWriter.WriteElementString("CanBeInManyToMany", currentEntity.CanBeInManyToMany.Value.ToString()); metadataWriter.WriteElementString("CanBePrimaryEntityInRelationship", currentEntity.CanBePrimaryEntityInRelationship.Value.ToString()); metadataWriter.WriteElementString("CanBeRelatedEntityInRelationship", currentEntity.CanBeRelatedEntityInRelationship.Value.ToString()); metadataWriter.WriteElementString("CanCreateAttributes", currentEntity.CanCreateAttributes.Value.ToString()); metadataWriter.WriteElementString("CanCreateCharts", currentEntity.CanCreateCharts.Value.ToString()); metadataWriter.WriteElementString("CanCreateForms", currentEntity.CanCreateForms.Value.ToString()); metadataWriter.WriteElementString("CanCreateViews", currentEntity.CanCreateViews.Value.ToString()); metadataWriter.WriteElementString("CanModifyAdditionalSettings", currentEntity.CanModifyAdditionalSettings.Value.ToString()); metadataWriter.WriteElementString("CanTriggerWorkflow", currentEntity.CanTriggerWorkflow.Value.ToString()); metadataWriter.WriteElementString("IsActivity", currentEntity.IsActivity.Value.ToString()); //metadataWriter.WriteElementString("ActivityTypeMask", currentEntity.ActivityTypeMask.ToString()); metadataWriter.WriteElementString("IsActivityParty", currentEntity.IsActivityParty.Value.ToString()); metadataWriter.WriteElementString("IsAuditEnabled", currentEntity.IsAuditEnabled.Value.ToString()); metadataWriter.WriteElementString("IsAvailableOffline", currentEntity.IsAvailableOffline.ToString()); metadataWriter.WriteElementString("IsChildEntity", currentEntity.IsChildEntity.ToString()); metadataWriter.WriteElementString("IsConnectionsEnabled", currentEntity.IsConnectionsEnabled.ManagedPropertyLogicalName.ToString()); metadataWriter.WriteElementString("IsCustomEntity", currentEntity.IsCustomEntity.Value.ToString()); metadataWriter.WriteElementString("IsCustomizable", currentEntity.IsCustomizable.Value.ToString()); metadataWriter.WriteElementString("IsDocumentManagementEnabled", currentEntity.IsDocumentManagementEnabled.Value.ToString()); metadataWriter.WriteElementString("IsDuplicateDetectionEnabled", currentEntity.IsDuplicateDetectionEnabled.Value.ToString()); if (currentEntity.IsEnabledForCharts != null) { metadataWriter.WriteElementString("IsEnabledForCharts", currentEntity.IsEnabledForCharts.Value.ToString()); } metadataWriter.WriteElementString("IsImportable", currentEntity.IsImportable.Value.ToString()); metadataWriter.WriteElementString("IsIntersect", currentEntity.IsIntersect.Value.ToString()); metadataWriter.WriteElementString("IsMailMergeEnabled", currentEntity.IsMailMergeEnabled.Value.ToString()); metadataWriter.WriteElementString("IsManaged", currentEntity.IsManaged.Value.ToString()); metadataWriter.WriteElementString("IsMappable", currentEntity.IsMappable.Value.ToString()); metadataWriter.WriteElementString("IsReadingPaneEnabled", currentEntity.IsReadingPaneEnabled.Value.ToString()); metadataWriter.WriteElementString("IsRenameable", currentEntity.IsRenameable.Value.ToString()); metadataWriter.WriteElementString("IsValidForAdvancedFind", currentEntity.IsValidForAdvancedFind.Value.ToString()); metadataWriter.WriteElementString("IsValidForQueue", currentEntity.IsValidForQueue.Value.ToString()); metadataWriter.WriteElementString("IsVisibleInMobile", currentEntity.IsVisibleInMobile.Value.ToString()); metadataWriter.WriteElementString("PrimaryIdAttribute", currentEntity.PrimaryIdAttribute); metadataWriter.WriteElementString("PrimaryNameAttribute", currentEntity.PrimaryNameAttribute); metadataWriter.WriteElementString("ReportViewName", currentEntity.ReportViewName); metadataWriter.WriteElementString("RecurrenceBaseEntityLogicalName", currentEntity.RecurrenceBaseEntityLogicalName); if (currentEntity.Description.UserLocalizedLabel != null) { metadataWriter.WriteElementString("Description", currentEntity.Description.UserLocalizedLabel.Label); } // End Entity Node metadataWriter.WriteEndElement(); } } // End Metadata Xml Node metadataWriter.WriteEndElement(); metadataWriter.WriteEndDocument(); // Close xml writer. metadataWriter.Close(); } Console.WriteLine("Done."); #region Clean up CleanUpSample(service); #endregion Clean up } #endregion Demonstrate else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Dynamics CRM"; 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] // 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 // Obtain information about the logged on user from the web service. Guid userid = ((WhoAmIResponse)service.Execute(new WhoAmIRequest())).UserId; SystemUser systemUser = (SystemUser)service.Retrieve("systemuser", userid, new ColumnSet(new string[] { "firstname", "lastname" })); Console.WriteLine("Logged on user is {0} {1}.", systemUser.FirstName, systemUser.LastName); // Retrieve the version of Microsoft Dynamics CRM. RetrieveVersionRequest versionRequest = new RetrieveVersionRequest(); RetrieveVersionResponse versionResponse = (RetrieveVersionResponse)service.Execute(versionRequest); Console.WriteLine("Microsoft Dynamics CRM version {0}.", versionResponse.Version); // Instantiate an account object. Note the use of option set enumerations defined in OptionSets.cs. // Refer to the Entity Metadata topic in the SDK documentation to determine which attributes must // be set for each entity. Account account = new Account { Name = "Fourth Coffee" }; account.AccountCategoryCode = new OptionSetValue((int)AccountAccountCategoryCode.PreferredCustomer); account.CustomerTypeCode = new OptionSetValue((int)AccountCustomerTypeCode.Investor); // Create an account record named Fourth Coffee. _accountId = service.Create(account); Console.Write("{0} {1} created, ", account.LogicalName, account.Name); // Retrieve the several attributes from the new account. ColumnSet cols = new ColumnSet( new String[] { "name", "address1_postalcode", "lastusedincampaign" }); Account retrievedAccount = (Account)service.Retrieve("account", _accountId, cols); Console.Write("retrieved, "); // Update the postal code attribute. retrievedAccount.Address1_PostalCode = "98052"; // The address 2 postal code was set accidentally, so set it to null. retrievedAccount.Address2_PostalCode = null; // Shows use of a Money value. retrievedAccount.Revenue = new Money(5000000); // Shows use of a Boolean value. retrievedAccount.CreditOnHold = false; // Update the account record. service.Update(retrievedAccount); Console.WriteLine("and updated."); #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(); } }
[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 // Obtain information about the logged on user from the web service. Guid userid = ((WhoAmIResponse)service.Execute(new WhoAmIRequest())).UserId; SystemUser systemUser = (SystemUser)service.Retrieve("systemuser", userid, new ColumnSet(new string[] { "firstname", "lastname" })); Console.WriteLine("Logged on user is {0} {1}.", systemUser.FirstName, systemUser.LastName); // Retrieve the version of Microsoft Dynamics CRM. RetrieveVersionRequest versionRequest = new RetrieveVersionRequest(); RetrieveVersionResponse versionResponse = (RetrieveVersionResponse)service.Execute(versionRequest); Console.WriteLine("Microsoft Dynamics CRM version {0}.", versionResponse.Version); bool fetchEverything = false; if (fetchEverything) { QueryExpression queGetAllIncidents = new QueryExpression("incident"); queGetAllIncidents.ColumnSet = new ColumnSet(true); EntityCollection allIncidents = service.RetrieveMultiple(queGetAllIncidents); WriteToJson(allIncidents.Entities[0], @"entity0.json"); QueryExpression queGetAllContacts = new QueryExpression("contact"); queGetAllContacts.ColumnSet = new ColumnSet(true); EntityCollection allContacts = service.RetrieveMultiple(queGetAllContacts); WriteToJson(allContacts, @"contacts.json"); QueryExpression queGetAllAccounts = new QueryExpression("account"); queGetAllAccounts.ColumnSet = new ColumnSet(true); //queGetAllAccounts.ColumnSet = new ColumnSet(new String[]{ "AccountId", "Name" }); EntityCollection allAccounts = service.RetrieveMultiple(queGetAllAccounts); WriteToJson(allAccounts, @"accounts.json"); } //TODO - fetch by name var incident = new Incident { Title = "Testing From Roy", //PrimaryContactId = new EntityReference("contact", new Guid("{6a9334ad-bd04-ea11-a811-000d3a4a1025}")), CustomerId = new EntityReference("account", new Guid("{852179cc-e2a6-e911-a97f-000d3a2cba5f}")) }; var incidentId = service.Create(incident); ColumnSet cols = new ColumnSet( new String[] { "title", "new_tguvot_text" }); Incident retrievedIncident = (Incident)service.Retrieve("incident", incidentId, cols); Console.Write("retrieved, "); var incidentAttributes = retrievedIncident.Attributes; incidentAttributes["new_tguvot_text"] = 5; service.Update(retrievedIncident); Console.WriteLine("and updated."); } #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(); } }
[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 QueryExpression QueryExpression query = new QueryExpression() { EntityName = Opportunity.EntityLogicalName, ColumnSet = new ColumnSet("name", "accountid"), Criteria = { Filters = { new FilterExpression { FilterOperator = LogicalOperator.And, Conditions = { new ConditionExpression("name", ConditionOperator.Equal, "Opportunity 1") }, } } }, }; Console.WriteLine("Created QueryExpression."); #endregion Create QueryExpression #region Create RollupRequest // Create RollupRequest RollupRequest rollupRequest = new RollupRequest(); rollupRequest.Query = query; rollupRequest.Target = new EntityReference("account", _accountId); rollupRequest.RollupType = RollupType.Extended; Console.WriteLine("Created RollupRequest."); #endregion Create RollupRequest #region Execute RollupRequest // Execute RollupRequest RollupResponse rollupResponse = (RollupResponse)service.Execute(rollupRequest); Console.WriteLine("Executed RollupRequest."); #endregion Execute RollupRequest #region Show RollupResponse results // Show RollupResponse results Console.WriteLine("RollupResponse Results:"); Console.WriteLine("--------------------------------------------------"); Console.WriteLine("Count: " + rollupResponse.Results.Count); for (int i = 0; i < rollupResponse.Results.Count; i++) { Console.WriteLine(); Console.WriteLine("LogicalName: " + rollupResponse.EntityCollection.Entities[i].LogicalName); Console.WriteLine("Id: " + rollupResponse.EntityCollection.Entities[i].Id); } #endregion Show RollupResponse results #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; } } } catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) { service.Dispose(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
[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 // This query retrieves all connections this contact is part of. QueryExpression query = new QueryExpression { EntityName = Connection.EntityLogicalName, ColumnSet = new ColumnSet("connectionid"), Criteria = new FilterExpression { FilterOperator = LogicalOperator.And, Conditions = { // You can safely query against only record1id or // record2id - CRM will find all connections this // entity is a part of either way. new ConditionExpression { AttributeName = "record1id", Operator = ConditionOperator.Equal, Values = { _contactId } } } } }; EntityCollection results = service.RetrieveMultiple(query); // TODO: Here you could do a variety of tasks with the // connections retrieved, such as listing the connected entities, // finding reciprocal connections, etc. Console.WriteLine("Retrieved {0} connectionrole instances.", results.Entities.Count); #region Clean up CleanUpSample(service); #endregion Clean up } #endregion Demonstrate #endregion Sample Code else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Dynamics CRM"; 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(); } }
[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 Console.WriteLine("Entering:RetrieveMultipleWithRelatedEntityColumns"); //Create multiple accounts with primary contacts var contact = new Entity("contact"); contact.Attributes["firstname"] = "ContactFirstName"; contact.Attributes["lastname"] = "ContactLastName"; Guid contactId = service.Create(contact); var account = new Entity("account"); account["name"] = "Test Account1"; EntityReference primaryContactId = new EntityReference("contact", contactId); account["primarycontactid"] = primaryContactId; Guid accountId1 = service.Create(account); account["name"] = "Test Account2"; Guid accountId2 = service.Create(account); account["name"] = "Test Account3"; Guid accountId3 = service.Create(account); //Create a query expression specifying the link entity alias and the columns of the link entity that you want to return var qe = new QueryExpression(); qe.EntityName = "account"; qe.ColumnSet = new ColumnSet(); qe.ColumnSet.Columns.Add("name"); qe.LinkEntities.Add(new LinkEntity("account", "contact", "primarycontactid", "contactid", JoinOperator.Inner)); qe.LinkEntities[0].Columns.AddColumns("firstname", "lastname"); qe.LinkEntities[0].EntityAlias = "primarycontact"; EntityCollection ec = service.RetrieveMultiple(qe); Console.WriteLine("Retrieved {0} entities", ec.Entities.Count); foreach (Entity act in ec.Entities) { Console.WriteLine("account name: {0}", act["name"]); Console.WriteLine("primary contact first name: {0}", act.GetAttributeValue <AliasedValue>("primarycontact.firstname").Value); Console.WriteLine("primary contact first name: {0}", act.GetAttributeValue <AliasedValue>("primarycontact.lastname").Value); } #region Clean up CleanUpSample(service); #endregion Clean up } #endregion Demonstrate 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; } } } #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 // TODO Add demonstration code here #endregion Demonstrate // Create a query for retrieving all organization-owned visualizations // that are attached to the account entity. QueryExpression mySavedQuery = new QueryExpression { EntityName = SavedQueryVisualization.EntityLogicalName, ColumnSet = new ColumnSet("name"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "primaryentitytypecode", Operator = ConditionOperator.Equal, Values = { Account.EntityLogicalName } } } } }; // Retrieve a collection of organization-owned visualizations that are attached to the account entity. DataCollection <Entity> results = service.RetrieveMultiple(mySavedQuery).Entities; // Display the names of the retrieved organization-owned visualizations. Console.WriteLine("Retrieved the following visualizations for the Account entity:"); foreach (Entity entity in results) { SavedQueryVisualization orgVisualization = (SavedQueryVisualization)entity; Console.WriteLine("{0}", orgVisualization.Name); } } 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(); } }
[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 // Retrieve a user. SystemUser user = service.Retrieve(SystemUser.EntityLogicalName, _userId, new ColumnSet(new String[] { "systemuserid", "firstname", "lastname" })).ToEntity <SystemUser>(); if (user != null) { Console.WriteLine("{1} {0} user account is retrieved.", user.FirstName, user.LastName); // Find the role. var query = new QueryExpression { EntityName = "role", ColumnSet = new ColumnSet("roleid"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "name", Operator = ConditionOperator.Equal, Values = { _givenRole } } } } }; // Get the role. EntityCollection roles = service.RetrieveMultiple(query); // Disassociate the role. if (roles.Entities.Count > 0) { Role salesRole = service.RetrieveMultiple(query).Entities[0].ToEntity <Role>(); Console.WriteLine("Role {0} is retrieved.", _givenRole); service.Disassociate( "systemuser", user.Id, new Relationship("systemuserroles_association"), new EntityReferenceCollection() { new EntityReference("role", salesRole.Id) }); Console.WriteLine("Role {0} is disassociated from user {1} {2}.", _givenRole, user.FirstName, user.LastName); #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(); } }
[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 // Get a system user to use as the sender. var emailSenderRequest = new WhoAmIRequest(); var emailSenderResponse = service.Execute(emailSenderRequest) as WhoAmIResponse; // Set trackingId for bulk mail request. Guid trackingId = Guid.NewGuid(); var bulkMailRequest = new SendBulkMailRequest() { // Create a query expression for the bulk operation to use to retrieve // the contacts in the email list. Query = new QueryExpression() { EntityName = Contact.EntityLogicalName, ColumnSet = new ColumnSet(new String[] { "contactid" }), Criteria = new FilterExpression() { Conditions = { new ConditionExpression("contactid", ConditionOperator.In, _contactsIds) } } }, // Set the Sender. Sender = new EntityReference(SystemUser.EntityLogicalName, emailSenderResponse.UserId), // Set the RegardingId - this field is required. //RegardingId = Guid.Empty, //RegardingType = SystemUser.EntityLogicalName, // Use a built-in Microsoft Dynamics CRM email template. // NOTE: The email template's "template type" must match the type of // customers in the email list. Our list contains contacts, so our // template must be for contacts. TemplateId = new Guid("07B94C1D-C85F-492F-B120-F0A743C540E6"), RequestId = trackingId }; // Execute the async bulk email request var resp = (SendBulkMailResponse) service.Execute(bulkMailRequest); Console.WriteLine(" Sent Bulk Email."); #endregion #region Monitoring SendBulkEmail Console.WriteLine(); Console.WriteLine("Starting monitoring process.."); // Now that we've executed the bulk operation, we need to retrieve it // using our tracking Id. var bulkQuery = new QueryByAttribute() { EntityName = AsyncOperation.EntityLogicalName, ColumnSet = new ColumnSet(new string[] { "requestid" }), Attributes = { "requestid" }, Values = { trackingId } }; // Retrieve the bulk email async operation. EntityCollection aResponse = service.RetrieveMultiple(bulkQuery); Console.WriteLine(" Retrieved Bulk Email Async Operation."); // Monitor the async operation via polling. int secondsTicker = ARBITRARY_MAX_POLLING_TIME; AsyncOperation createdBulkMailOperation = null; Console.WriteLine(" Checking operation's state for " + ARBITRARY_MAX_POLLING_TIME + " seconds."); Console.WriteLine(); while (secondsTicker > 0) { // Make sure the async operation was retrieved. if (aResponse.Entities.Count > 0) { // Grab the one bulk operation that has been created. createdBulkMailOperation = (AsyncOperation)aResponse.Entities[0]; // Check the operation's state. if (createdBulkMailOperation.StateCode.Value != AsyncOperationState.Completed) { // The operation has not yet completed. // Wait a second for the status to change. System.Threading.Thread.Sleep(1000); secondsTicker--; // Retrieve a fresh version the bulk delete operation. aResponse = service.RetrieveMultiple(bulkQuery); } else { // Stop polling because the operation's state is now complete. secondsTicker = 0; } } else { // Wait a second for the async operation to activate. System.Threading.Thread.Sleep(1000); secondsTicker--; // Retrieve the entity again aResponse = service.RetrieveMultiple(bulkQuery); } } // When the bulk email operation has completed, all sent emails will // have a status of "Pending Send" and will be picked up by your email // router. Alternatively, you can then use BackgroundSendEmail to download // all the emails created with the SendBulkEmail message. // See the BackgroundSendEmail sample for an example. #endregion #region Check success // Validate async operation succeeded if (createdBulkMailOperation.StateCode.Value == AsyncOperationState.Completed) { Console.WriteLine("Operation Completed."); } else { Console.WriteLine("Operation not completed yet."); } #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(); } }
[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(); } }
[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 _productVersion = Version.Parse(((RetrieveVersionResponse)service.Execute(new RetrieveVersionRequest())).Version); #region How to create attributes // Create storage for new attributes being created addedAttributes = new List <AttributeMetadata>(); // Create a boolean attribute var boolAttribute = new BooleanAttributeMetadata { // Set base properties SchemaName = "new_Boolean", LogicalName = "new_boolean", DisplayName = new Label("Sample Boolean", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Boolean Attribute", _languageCode), // Set extended properties OptionSet = new BooleanOptionSetMetadata( new OptionMetadata(new Label("True", _languageCode), 1), new OptionMetadata(new Label("False", _languageCode), 0) ) }; // Add to list addedAttributes.Add(boolAttribute); // Create a date time attribute var dtAttribute = new DateTimeAttributeMetadata { // Set base properties SchemaName = "new_Datetime", LogicalName = "new_datetime", DisplayName = new Label("Sample DateTime", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("DateTime Attribute", _languageCode), // Set extended properties Format = DateTimeFormat.DateOnly, ImeMode = ImeMode.Disabled }; // Add to list addedAttributes.Add(dtAttribute); // Create a decimal attribute var decimalAttribute = new DecimalAttributeMetadata { // Set base properties SchemaName = "new_Decimal", LogicalName = "new_decimal", DisplayName = new Label("Sample Decimal", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Decimal Attribute", _languageCode), // Set extended properties MaxValue = 100, MinValue = 0, Precision = 1 }; // Add to list addedAttributes.Add(decimalAttribute); // Create a integer attribute var integerAttribute = new IntegerAttributeMetadata { // Set base properties SchemaName = "new_Integer", LogicalName = "new_integer", DisplayName = new Label("Sample Integer", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Integer Attribute", _languageCode), // Set extended properties Format = IntegerFormat.None, MaxValue = 100, MinValue = 0 }; // Add to list addedAttributes.Add(integerAttribute); // Create a memo attribute var memoAttribute = new MemoAttributeMetadata { // Set base properties SchemaName = "new_Memo", LogicalName = "new_memo", DisplayName = new Label("Sample Memo", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Memo Attribute", _languageCode), // Set extended properties Format = StringFormat.TextArea, ImeMode = ImeMode.Disabled, MaxLength = 500 }; // Add to list addedAttributes.Add(memoAttribute); // Create a money attribute var moneyAttribute = new MoneyAttributeMetadata { // Set base properties SchemaName = "new_Money", LogicalName = "new_money", DisplayName = new Label("Money Picklist", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Money Attribue", _languageCode), // Set extended properties MaxValue = 1000.00, MinValue = 0.00, Precision = 1, PrecisionSource = 1, ImeMode = ImeMode.Disabled }; // Add to list addedAttributes.Add(moneyAttribute); // Create a picklist attribute var pickListAttribute = new PicklistAttributeMetadata { // Set base properties SchemaName = "new_Picklist", LogicalName = "new_picklist", DisplayName = new Label("Sample Picklist", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Picklist Attribute", _languageCode), // Set extended properties // Build local picklist options OptionSet = new OptionSetMetadata { IsGlobal = false, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata( new Label("Created", _languageCode), null), new OptionMetadata( new Label("Updated", _languageCode), null), new OptionMetadata( new Label("Deleted", _languageCode), null) } } }; // Add to list addedAttributes.Add(pickListAttribute); // Create a string attribute var stringAttribute = new StringAttributeMetadata { // Set base properties SchemaName = "new_String", LogicalName = "new_string", DisplayName = new Label("Sample String", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("String Attribute", _languageCode), // Set extended properties MaxLength = 100 }; // Add to list addedAttributes.Add(stringAttribute); //Multi-select attribute requires version 9.0 or higher. if (_productVersion > new Version("9.0")) { // Create a multi-select optionset var multiSelectOptionSetAttribute = new MultiSelectPicklistAttributeMetadata() { SchemaName = "new_MultiSelectOptionSet", LogicalName = "new_multiselectoptionset", DisplayName = new Label("Multi-Select OptionSet", _languageCode), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Multi-Select OptionSet description", _languageCode), OptionSet = new OptionSetMetadata() { IsGlobal = false, OptionSetType = OptionSetType.Picklist, Options = { new OptionMetadata(new Label("First Option", _languageCode), null), new OptionMetadata(new Label("Second Option", _languageCode), null), new OptionMetadata(new Label("Third Option", _languageCode), null) } } }; // Add to list addedAttributes.Add(multiSelectOptionSetAttribute); } // NOTE: LookupAttributeMetadata cannot be created outside the context of a relationship. // Refer to the WorkWithRelationships.cs reference SDK sample for an example of this attribute type. // NOTE: StateAttributeMetadata and StatusAttributeMetadata cannot be created via the SDK. foreach (AttributeMetadata anAttribute in addedAttributes) { // Create the request. var createAttributeRequest = new CreateAttributeRequest { EntityName = Contact.EntityLogicalName, Attribute = anAttribute }; // Execute the request. service.Execute(createAttributeRequest); Console.WriteLine("Created the attribute {0}.", anAttribute.SchemaName); } #endregion How to create attributes #region How to insert status // Use InsertStatusValueRequest message to insert a new status // in an existing status attribute. // Create the request. var insertStatusValueRequest = new InsertStatusValueRequest { AttributeLogicalName = "statuscode", EntityLogicalName = Contact.EntityLogicalName, Label = new Label("Dormant", _languageCode), StateCode = 0 }; // Execute the request and store newly inserted value // for cleanup, used later part of this sample. _insertedStatusValue = ((InsertStatusValueResponse)service.Execute( insertStatusValueRequest)).NewOptionValue; Console.WriteLine("Created status named '{0}' with the value of {1}.", insertStatusValueRequest.Label.LocalizedLabels[0].Label, _insertedStatusValue); #endregion How to insert status #region How to retrieve attribute // Create the request var attributeRequest = new RetrieveAttributeRequest { EntityLogicalName = Contact.EntityLogicalName, LogicalName = "new_string", RetrieveAsIfPublished = true }; // Execute the request RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)service.Execute(attributeRequest); Console.WriteLine("Retrieved the attribute {0}.", attributeResponse.AttributeMetadata.SchemaName); #endregion How to retrieve attribute #region How to update attribute // Modify the retrieved attribute var retrievedAttributeMetadata = attributeResponse.AttributeMetadata; retrievedAttributeMetadata.DisplayName = new Label("Update String Attribute", _languageCode); // Update an attribute retrieved via RetrieveAttributeRequest var updateRequest = new UpdateAttributeRequest { Attribute = retrievedAttributeMetadata, EntityName = Contact.EntityLogicalName, MergeLabels = false }; // Execute the request service.Execute(updateRequest); Console.WriteLine("Updated the attribute {0}.", retrievedAttributeMetadata.SchemaName); #endregion How to update attribute #region How to update state value // Modify the state value label from Active to Open. // Create the request. var updateStateValue = new UpdateStateValueRequest { AttributeLogicalName = "statecode", EntityLogicalName = Contact.EntityLogicalName, Value = 1, Label = new Label("Open", _languageCode) }; // Execute the request. service.Execute(updateStateValue); Console.WriteLine( "Updated {0} state attribute of {1} entity from 'Active' to '{2}'.", updateStateValue.AttributeLogicalName, updateStateValue.EntityLogicalName, updateStateValue.Label.LocalizedLabels[0].Label ); #endregion How to update state value #region How to insert a new option item in a local option set // Create a request. var insertOptionValueRequest = new InsertOptionValueRequest { AttributeLogicalName = "new_picklist", EntityLogicalName = Contact.EntityLogicalName, Label = new Label("New Picklist Label", _languageCode) }; // Execute the request. int insertOptionValue = ((InsertOptionValueResponse)service.Execute( insertOptionValueRequest)).NewOptionValue; Console.WriteLine("Created {0} with the value of {1}.", insertOptionValueRequest.Label.LocalizedLabels[0].Label, insertOptionValue); #endregion How to insert a new option item in a local option set #region How to change the order of options of a local option set // Use the RetrieveAttributeRequest message to retrieve // a attribute by it's logical name. var retrieveAttributeRequest = new RetrieveAttributeRequest { EntityLogicalName = Contact.EntityLogicalName, LogicalName = "new_picklist", RetrieveAsIfPublished = true }; // Execute the request. RetrieveAttributeResponse retrieveAttributeResponse = (RetrieveAttributeResponse)service.Execute( retrieveAttributeRequest); // Access the retrieved attribute. var retrievedPicklistAttributeMetadata = (PicklistAttributeMetadata) retrieveAttributeResponse.AttributeMetadata; // Get the current options list for the retrieved attribute. OptionMetadata[] optionList = retrievedPicklistAttributeMetadata.OptionSet.Options.ToArray(); // Change the order of the original option's list. // Use the OrderBy (OrderByDescending) linq function to sort options in // ascending (descending) order according to label text. // For ascending order use this: var updateOptionList = optionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList(); // For descending order use this: // var updateOptionList = // optionList.OrderByDescending( // x => x.Label.LocalizedLabels[0].Label).ToList(); // Create the request. var orderOptionRequest = new OrderOptionRequest { // Set the properties for the request. AttributeLogicalName = "new_picklist", EntityLogicalName = Contact.EntityLogicalName, // Set the changed order using Select linq function // to get only values in an array from the changed option list. Values = updateOptionList.Select(x => x.Value.Value).ToArray() }; // Execute the request service.Execute(orderOptionRequest); Console.WriteLine("Option Set option order changed"); #endregion How to change the order of options of a global option set // NOTE: All customizations must be published before they can be used. service.Execute(new PublishAllXmlRequest()); Console.WriteLine("Published all customizations."); #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(); } }
[STAThread] // Added to support UX static void Main(string[] args) { CrmServiceClient service = null; try { service = SampleHelpers.Connect("Connect"); // Service implements IOrganizationService interface if (service.IsReady) { #region Sample Code ////////////////////////////////////////////// #region Set up SetUpSample(service); #endregion Set up #region Demonstrate // Processes the data in newsampleproduct.xml // to represent new products. Creates 13 records in sample_product entity. // RecordCreated property returns true to indicate the records were created. ProcessUpsert(service, ".\\newsampleproduct.xml"); // Processes the data in updatedsampleproduct.xml // to represent updates to products previously created. // Updates 6 existing records in sample_product entity. // RecordCreated property returns false to indicate the existing records were updated. ProcessUpsert(service, ".\\updatedsampleproduct.xml"); #region Clean up CleanUpSample(service); #endregion Clean up Console.WriteLine("The sample completed successfully"); return; } #endregion Demonstrate else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Dynamics CRM"; 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]// 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 // Retrieve a role from CRM. var query = new QueryExpression { EntityName = Role.EntityLogicalName, ColumnSet = new ColumnSet("roleid"), Criteria = new FilterExpression { Conditions = { // You would replace the condition below with an actual role // name, or skip this query if you had a role id. new ConditionExpression { AttributeName = "name", Operator = ConditionOperator.Equal, Values = { _roleName } } } } }; var role = service.RetrieveMultiple(query).Entities. Cast <Role>().First(); // Add the role to the team. service.Associate( Team.EntityLogicalName, _teamId, new Relationship("teamroles_association"), new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, _roleId) }); Console.WriteLine("Assigned role to team"); //</snippetAssignSecurityRoleToTeam1> #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); } }
[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 // The custom prefix would typically be passed in as an argument or // determined by the publisher of the custom solution. String prefix = "new_"; String customEntityName = prefix + "sampleentity"; // Create the custom activity entity. CreateEntityRequest request = new CreateEntityRequest { HasNotes = true, HasActivities = false, PrimaryAttribute = new StringAttributeMetadata { SchemaName = "Subject", RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), MaxLength = 100, DisplayName = new Microsoft.Xrm.Sdk.Label("Subject", 1033) }, Entity = new EntityMetadata { IsActivity = true, SchemaName = customEntityName, DisplayName = new Microsoft.Xrm.Sdk.Label("Sample Entity", 1033), DisplayCollectionName = new Microsoft.Xrm.Sdk.Label("Sample Entity", 1033), OwnershipType = OwnershipTypes.UserOwned, IsAvailableOffline = true, } }; service.Execute(request); //Entity must be published // Add few attributes to the custom activity entity. CreateAttributeRequest fontFamilyAttributeRequest = new CreateAttributeRequest { EntityName = customEntityName, Attribute = new StringAttributeMetadata { SchemaName = prefix + "fontfamily", DisplayName = new Microsoft.Xrm.Sdk.Label("Font Family", 1033), MaxLength = 100 } }; CreateAttributeResponse fontFamilyAttributeResponse = (CreateAttributeResponse)service.Execute( fontFamilyAttributeRequest); CreateAttributeRequest fontColorAttributeRequest = new CreateAttributeRequest { EntityName = customEntityName, Attribute = new StringAttributeMetadata { SchemaName = prefix + "fontcolor", DisplayName = new Microsoft.Xrm.Sdk.Label("Font Color", 1033), MaxLength = 50 } }; CreateAttributeResponse fontColorAttributeResponse = (CreateAttributeResponse)service.Execute( fontColorAttributeRequest); CreateAttributeRequest fontSizeAttributeRequest = new CreateAttributeRequest { EntityName = customEntityName, Attribute = new IntegerAttributeMetadata { SchemaName = prefix + "fontSize", DisplayName = new Microsoft.Xrm.Sdk.Label("Font Size", 1033) } }; CreateAttributeResponse fontSizeAttributeResponse = (CreateAttributeResponse)service.Execute( fontSizeAttributeRequest); Console.WriteLine("The custom activity has been created."); #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(); } }
[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 export folder for ribbon xml files if not already exist. if (!Directory.Exists(exportFolder)) { Directory.CreateDirectory(exportFolder); } //Retrieve the Application Ribbon var appribReq = new RetrieveApplicationRibbonRequest(); var appribResp = (RetrieveApplicationRibbonResponse)service.Execute(appribReq); System.String applicationRibbonPath = Path.GetFullPath(exportFolder + "\\applicationRibbon.xml"); File.WriteAllBytes(applicationRibbonPath, unzipRibbon(appribResp.CompressedApplicationRibbonXml)); //Write the path where the file has been saved. Console.WriteLine(applicationRibbonPath); //Retrieve system Entity Ribbons RetrieveEntityRibbonRequest entRibReq = new RetrieveEntityRibbonRequest() { RibbonLocationFilter = RibbonLocationFilters.All }; foreach (System.String entityName in entitiesWithRibbons) { entRibReq.EntityName = entityName; RetrieveEntityRibbonResponse entRibResp = (RetrieveEntityRibbonResponse)service.Execute(entRibReq); System.String entityRibbonPath = Path.GetFullPath(exportFolder + "\\" + entityName + "Ribbon.xml"); File.WriteAllBytes(entityRibbonPath, unzipRibbon(entRibResp.CompressedEntityXml)); //Write the path where the file has been saved. Console.WriteLine(entityRibbonPath); } //Check for custom entities var raer = new RetrieveAllEntitiesRequest() { EntityFilters = EntityFilters.Entity }; var resp = (RetrieveAllEntitiesResponse)service.Execute(raer); foreach (EntityMetadata em in resp.EntityMetadata) { if (em.IsCustomEntity == true && em.IsIntersect == false) { entRibReq.EntityName = em.LogicalName; RetrieveEntityRibbonResponse entRibResp = (RetrieveEntityRibbonResponse)service.Execute(entRibReq); System.String entityRibbonPath = Path.GetFullPath(exportFolder + "\\" + em.LogicalName + "Ribbon.xml"); File.WriteAllBytes(entityRibbonPath, unzipRibbon(entRibResp.CompressedEntityXml)); //Write the path where the file has been saved. Console.WriteLine(entityRibbonPath); } } #endregion Demonstrate #region Clean up CleanUpSample(service); #endregion Clean up } 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(); } }
[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 the column set object that indicates the fields to be retrieved. var columns = new ColumnSet( "contactid", "firstname", "lastname", "jobtitle"); // Retrieve the contact using the ID of the record that was just created. // The EntityLogicalName indicates the EntityType of the object being retrieved. var contact = (Contact)service.Retrieve( Contact.EntityLogicalName, _contactId, columns); Console.WriteLine("The contact for the sample has been retrieved."); // Serialize the contact into XML and write it to the hard drive. var earlyBoundSerializer = new DataContractSerializer(typeof(Contact)); // Create a unique file name for the XML. String earlyboundFile = "Contact_early_" + contact.ContactId.Value.ToString("B") + ".xml"; // Write the serialized object to a file. The using statement will // ensure that the FileStream is disposed of correctly. The FileMode // will ensure that the file is overwritten if it already exists. using (var file = new FileStream(earlyboundFile, FileMode.Create)) { // Write the XML to disk. earlyBoundSerializer.WriteObject(file, contact); } Console.WriteLine( "The early-bound contact instance has been serialized to a file, {0}.", earlyboundFile); // Convert the contact to a late-bound entity instance and serialize it to disk. var lateboundContact = contact.ToEntity <Entity>(); String lateboundFile = "Contact_late_" + lateboundContact.Id.ToString("B") + ".xml"; var lateBoundSerializer = new DataContractSerializer(typeof(Entity)); // Write the serialized object to a file. using (var file = new FileStream(lateboundFile, FileMode.Create)) { lateBoundSerializer.WriteObject(file, lateboundContact); } Console.WriteLine( "The late-bound contact instance has been serialized to a file, {0}.", lateboundFile); Contact deserializedContact = null; using (var file = new FileStream(earlyboundFile, FileMode.Open)) { deserializedContact = (Contact)earlyBoundSerializer.ReadObject(file); Console.WriteLine("The contact has been de-serialized: {0} {1}", deserializedContact.FirstName, deserializedContact.LastName); } // Update the contact to prove that the de-serialization worked. deserializedContact.JobTitle = "Plumber"; service.Update(deserializedContact); Console.WriteLine("The contact was updated."); #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(); } }
[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 FetchXml for marketing list's query which locates accounts // in Seattle. String fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='account'> <attribute name='name' /> <attribute name='address1_city' /> <attribute name='primarycontactid' /> <attribute name='telephone1' /> <attribute name='accountid' /> <order attribute='name' descending='false' /> <filter type='and'> <condition attribute='address1_city' operator='eq' value='seattle' /> </filter> </entity> </fetch>"; // Create dynamic list. Set the type to true to declare a dynamic // list. List dynamicList = new List() { Type = true, ListName = "Dynamic List", CreatedFromCode = new OptionSetValue((int)ListCreatedFromCode.Account), Query = fetchXml }; _dynamicListId = service.Create(dynamicList); dynamicList.Id = _dynamicListId; Console.WriteLine("Created dynamic list."); #endregion #region Associate dynamic list to campaign // Create a campaign. var campaign = new Campaign() { Name = "Sample Campaign" }; _campaignId = service.Create(campaign); campaign.Id = _campaignId; // Add the dynamic list to the campaign. var addListToCampaignRequest = new AddItemCampaignRequest() { CampaignId = _campaignId, EntityId = _dynamicListId, EntityName = List.EntityLogicalName, }; service.Execute(addListToCampaignRequest); Console.WriteLine("Added dynamic list to the campaign."); // Create a campaign activity to distribute fax to the list members. CampaignActivity campaignActivity = new CampaignActivity() { Subject = "Sample Campaign Activity", ChannelTypeCode = new OptionSetValue((int)CampaignActivityChannelTypeCode.Fax), RegardingObjectId = campaign.ToEntityReference() }; _campaignActivityId = service.Create(campaignActivity); // Add dynamic list to campaign activity. var addListToCampaignActivityRequest = new AddItemCampaignActivityRequest() { CampaignActivityId = _campaignActivityId, ItemId = _dynamicListId, EntityName = List.EntityLogicalName }; service.Execute(addListToCampaignActivityRequest); Console.WriteLine("Added dynamic list to the campaign activity."); #endregion #region Associate static list to campaign // Copy the dynamic list to a static list. var copyRequest = new CopyDynamicListToStaticRequest() { ListId = _dynamicListId }; var copyResponse = (CopyDynamicListToStaticResponse)service.Execute(copyRequest); _staticListId = copyResponse.StaticListId; Console.WriteLine("Copied dynamic list to a static list."); // Add the static list to the campaign. var addStaticListToCampaignRequest = new AddItemCampaignRequest() { CampaignId = _campaignId, EntityId = _staticListId, EntityName = List.EntityLogicalName }; service.Execute(addStaticListToCampaignRequest); Console.WriteLine("Added static list to the campaign."); // Add the static list to the campaign activity. var addStaticListToCampaignActivityRequest = new AddItemCampaignActivityRequest() { CampaignActivityId = _campaignActivityId, ItemId = _staticListId, EntityName = List.EntityLogicalName }; service.Execute(addStaticListToCampaignActivityRequest); Console.WriteLine("Added static list to the campaign's activity."); #endregion #region Create fax for campaign's activity // Create a fax. var fax = new Fax() { Subject = "Example Fax" }; Console.WriteLine("Created fax for campaign's activity."); #endregion Create fax for campaign's activity #region Distribute fax to the marketing list // Distribute the campaign activity to the marketing lists. var distributeRequest = new DistributeCampaignActivityRequest() { CampaignActivityId = _campaignActivityId, Activity = fax, Owner = new EntityReference("systemuser", _salesManagerId), Propagate = true, SendEmail = false, PostWorkflowEvent = true }; service.Execute(distributeRequest); Console.WriteLine("Distributed fax to the marketing lists."); #endregion Distribute fax to the marketing list #region Retrieve collection of entities from marketing list // Retrieve a collection of entities that correspond // to all of the members in a marketing list // This approach of retrieving list members allows you to dynamically // retrieve the members of a list programmatically without requiring // knowledge of the member entity type. OrganizationServiceContext orgContext = new OrganizationServiceContext(service); var member = (from mb in orgContext.CreateQuery <List>() where mb.Id == _dynamicListId select mb).FirstOrDefault(); string fetchQuery = member.Query; var memberRequest = new RetrieveMultipleRequest(); FetchExpression fetch = new FetchExpression(fetchQuery); memberRequest.Query = fetch; var memberResponse = (RetrieveMultipleResponse)service.Execute(memberRequest); Console.WriteLine("Retrieved collection of entities from a marketing list."); #endregion Demonstrate #region Clean up CleanUpSample(service); #endregion Clean up } 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(); } }
[STAThread] // Added to support UX static void Main(string[] args) { CrmServiceClient service = null; try { service = SampleHelpers.Connect("Connect"); if (service != null) { // Service implements IOrganizationService interface if (service.IsReady) { #region Sample Code ////////////////////////////////////////////// #region Demonstrate // Instantiate an account object. Entity newAccount = new Entity("account"); // Set the required attributes. For account, only the name is required. newAccount["name"] = "Fourth Coffee"; //Set any other attribute values. newAccount["address2_postalcode"] = "98074"; // Create an account record named Fourth Coffee. Guid accountid = service.Create(newAccount); Console.WriteLine("Created {0} entity named {1}.", newAccount.LogicalName, newAccount["name"]); // Create a column set to define which attributes should be retrieved. ColumnSet attributes = new ColumnSet("name", "ownerid"); // Retrieve the account and its name and ownerid attributes. newAccount = service.Retrieve(newAccount.LogicalName, accountid, attributes); Console.WriteLine("Retrieved Entity"); /* * IMPORTANT: * Do not update an entity using a retrieved entity instance. * Always instantiate a new Entity and * set the primary key value to match the entity you want to update. * Only set the attribute values you are changing. */ Entity accountToUpdate = new Entity("account"); accountToUpdate["accountid"] = newAccount.Id; // Update the address 1 postal code attribute. accountToUpdate["address1_postalcode"] = "98052"; // The address 2 postal code was set accidentally, so set it to null. accountToUpdate["address2_postalcode"] = null; // Shows use of Money. accountToUpdate["revenue"] = new Money(5000000); // Shows use of boolean. accountToUpdate["creditonhold"] = false; // Perform the update. service.Update(accountToUpdate); Console.WriteLine("Updated Entity"); //Delete the entity service.Delete("account", accountid); Console.WriteLine("Deleted Entity"); #endregion Demonstrate ////////////////////////////////////////////// #endregion Sample Code Console.WriteLine("The sample completed successfully"); return; } 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(); } }
[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 //Grab the default public view for opportunities. QueryExpression mySavedQuery = new QueryExpression { ColumnSet = new ColumnSet("savedqueryid"), EntityName = SavedQuery.EntityLogicalName, Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "isdefault", Operator = ConditionOperator.Equal, Values = { true } }, new ConditionExpression { AttributeName = "querytype", Operator = ConditionOperator.Equal, Values = { 0 } }, new ConditionExpression { AttributeName = "returnedtypecode", Operator = ConditionOperator.Equal, Values = { Opportunity.EntityTypeCode } } } } }; //This query should return one and only one result. SavedQuery defaultOpportunityQuery = service.RetrieveMultiple(mySavedQuery) .Entities.Select(x => (SavedQuery)x).FirstOrDefault(); // Retrieve visualizations out of the system. // This sample assumes that you have the "Top Opportunities" // visualization that is installed with Microsoft Dynamics CRM. QueryByAttribute visualizationQuery = new QueryByAttribute { EntityName = SavedQueryVisualization.EntityLogicalName, ColumnSet = new ColumnSet("savedqueryvisualizationid"), Attributes = { "name" }, //If you do not have this visualization, you will need to change //this line. Values = { "Top Opportunities" } }; SavedQueryVisualization visualization = service.RetrieveMultiple(visualizationQuery). Entities.Select(x => (SavedQueryVisualization)x).FirstOrDefault(); //This is the language code for U.S. English. If you are running this code //in a different locale, you will need to modify this value. int languageCode = 1033; //We set up our dashboard and specify the FormXml. Refer to the //FormXml schema in the Microsoft Dynamics CRM SDK for more information. SystemForm dashboard = new SystemForm { Name = "Sample Dashboard", Description = "Sample organization-owned dashboard.", FormXml = String.Format(@"<form> <tabs> <tab name='Test Dashboard' verticallayout='true'> <labels> <label description='Sample Dashboard' languagecode='{0}' /> </labels> <columns> <column width='100%'> <sections> <section name='Information Section' showlabel='false' showbar='false' columns='111'> <labels> <label description='Information Section' languagecode='{0}' /> </labels> <rows> <row> <cell colspan='1' rowspan='10' showlabel='false'> <labels> <label description='Top Opportunitiess - 1' languagecode='{0}' /> </labels> <control id='TopOpportunities' classid='{{E7A81278-8635-4d9e-8D4D-59480B391C5B}}'> <parameters> <ViewId>{1}</ViewId> <IsUserView>false</IsUserView> <RelationshipName /> <TargetEntityType>opportunity</TargetEntityType> <AutoExpand>Fixed</AutoExpand> <EnableQuickFind>false</EnableQuickFind> <EnableViewPicker>false</EnableViewPicker> <EnableJumpBar>false</EnableJumpBar> <ChartGridMode>Chart</ChartGridMode> <VisualizationId>{2}</VisualizationId> <EnableChartPicker>false</EnableChartPicker> <RecordsPerPage>10</RecordsPerPage> </parameters> </control> </cell> <cell colspan='1' rowspan='10' showlabel='false'> <labels> <label description='Top Opportunities - 2' languagecode='{0}' /> </labels> <control id='TopOpportunities2' classid='{{E7A81278-8635-4d9e-8D4D-59480B391C5B}}'> <parameters> <ViewId>{1}</ViewId> <IsUserView>false</IsUserView> <RelationshipName /> <TargetEntityType>opportunity</TargetEntityType> <AutoExpand>Fixed</AutoExpand> <EnableQuickFind>false</EnableQuickFind> <EnableViewPicker>false</EnableViewPicker> <EnableJumpBar>false</EnableJumpBar> <ChartGridMode>Grid</ChartGridMode> <VisualizationId>{2}</VisualizationId> <EnableChartPicker>false</EnableChartPicker> <RecordsPerPage>10</RecordsPerPage> </parameters> </control> </cell> </row> <row /> <row /> <row /> <row /> <row /> <row /> <row /> <row /> <row /> </rows> </section> </sections> </column> </columns> </tab> </tabs> </form>", languageCode, defaultOpportunityQuery.SavedQueryId.Value.ToString("B"), visualization.SavedQueryVisualizationId.Value.ToString("B")), IsDefault = false }; _dashboardId = service.Create(dashboard); Console.WriteLine("Created {0}.", dashboard.Name); //Now we will retrieve the dashboard. SystemForm retrievedDashboard = (SystemForm)service.Retrieve(SystemForm.EntityLogicalName, _dashboardId, new ColumnSet(true)); Console.WriteLine("Retrieved the dashboard."); // Update the retrieved dashboard. Enable the chart picker on the chart. var xDocument = XDocument.Parse(retrievedDashboard.FormXml); var chartPicker = (from control in xDocument.Descendants("control") where control.Attribute("id").Value == "TopOpportunities" select control.Descendants("EnableChartPicker").First() ).First(); chartPicker.Value = "true"; //Now we place the updated Xml back into the dashboard, and update it. retrievedDashboard.FormXml = xDocument.ToString(); service.Update(retrievedDashboard); // Publish the dashboard changes to the solution. // This is only required for organization-owned dashboards. var updateRequest = new PublishXmlRequest { ParameterXml = @"<dashboard>_dashboardId</dashboard>" }; service.Execute(updateRequest); Console.WriteLine("Updated the dashboard."); #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(); } }
[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 var query = new QueryExpression { EntityName = Role.EntityLogicalName, ColumnSet = new ColumnSet("name", "roleid") }; EntityCollection entities = service.RetrieveMultiple(query); // Write the name and ID of each role to the console. foreach (Entity item in entities.Entities) { Role role = item.ToEntity <Role>(); Console.WriteLine("Name: {0}. Id: {1}", role.Name, role.Id); } #endregion Demonstrate #region Clean up //CleanUpSample(service); #endregion Clean up } 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(); } }
[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 and Retrieve Offline Filter // In your Outlook client, this will appear in the System Filters tab // under File | CRM | Synchronize | Outlook Filters. Console.Write("Creating offline filter"); String contactName = String.Format("offlineFilteredContact {0}", DateTime.Now.ToLongTimeString()); String fetchXml = String.Format("<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\"><entity name=\"contact\"><attribute name=\"contactid\" /><filter type=\"and\">" + "<condition attribute=\"ownerid\" operator=\"eq-userid\" /><condition attribute=\"description\" operator=\"eq\" value=\"{0}\" />" + "<condition attribute=\"statecode\" operator=\"eq\" value=\"0\" /></filter></entity></fetch>", contactName); SavedQuery filter = new SavedQuery(); filter.FetchXml = fetchXml; filter.IsQuickFindQuery = false; filter.QueryType = SavedQueryQueryType.OfflineFilters; filter.ReturnedTypeCode = Contact.EntityLogicalName; filter.Name = "ReadOnlyFilter_" + contactName; filter.Description = "Sample offline filter for Contact entity"; _offlineFilter = service.Create(filter); Console.WriteLine(" and retrieving offline filter"); var result = (SavedQuery)service.Retrieve( SavedQuery.EntityLogicalName, _offlineFilter, new ColumnSet("name", "description")); Console.WriteLine("Name: {0}", result.Name); Console.WriteLine("Description: {0}", result.Description); Console.WriteLine(); // Create and Retrieve Offline Template // In your Outlook client, this will appear in the User Filters tab // under File | CRM | Synchronize | Outlook Filters. Console.Write("Creating offline template"); String accountName = String.Format("offlineFilteredAccount {0}", DateTime.Now.ToLongTimeString()); fetchXml = String.Format("<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\"><entity name=\"account\"><attribute name=\"accountid\" /><filter type=\"and\">" + "<condition attribute=\"ownerid\" operator=\"eq-userid\" /><condition attribute=\"name\" operator=\"eq\" value=\"{0}\" />" + "<condition attribute=\"statecode\" operator=\"eq\" value=\"0\" /></filter></entity></fetch>", accountName); var template = new SavedQuery(); template.FetchXml = fetchXml; template.IsQuickFindQuery = false; template.QueryType = SavedQueryQueryType.OfflineTemplate; template.ReturnedTypeCode = Account.EntityLogicalName; template.Name = "ReadOnlyFilter_" + accountName; template.Description = "Sample offline template for Account entity"; _offlineTemplate = service.Create(template); Console.WriteLine(" and retrieving offline template"); result = (SavedQuery)service.Retrieve( SavedQuery.EntityLogicalName, _offlineTemplate, new ColumnSet("name", "description")); Console.WriteLine("Name: {0}", result.Name); Console.WriteLine("Description: {0}", result.Description); Console.WriteLine(); // Call InstantiateFiltersRequest Console.WriteLine("Retrieving user's ID and creating the template collection"); var whoAmI = new WhoAmIRequest(); Guid id = ((WhoAmIResponse)service.Execute(whoAmI)).UserId; EntityReferenceCollection templates = new EntityReferenceCollection(); templates.Add(new EntityReference( SavedQuery.EntityLogicalName, _offlineTemplate)); Console.WriteLine("Activating the selected offline templates for this user"); var request = new InstantiateFiltersRequest { UserId = id, TemplateCollection = templates }; var response = (InstantiateFiltersResponse)service.Execute(request); Console.WriteLine(); // Call ResetUserFiltersRequest Console.WriteLine("Resetting the user's offline templates to the defaults"); var resetRequest = new ResetUserFiltersRequest { QueryType = SavedQueryQueryType.OfflineFilters }; var resetResponse = (ResetUserFiltersResponse)service.Execute(resetRequest); Console.WriteLine(); #endregion Demonstrate #region Clean up CleanUpSample(service); #endregion Clean up } 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(); } }