/// <summary>
        /// This method first connects to the Organization service. Afterwards,
        /// a goal is created specifying the target count. The goal is then
        /// rolled up, the actual and in-progress values are overridden and finally the
        /// goal is closed.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    // 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

                    DeleteRequiredRecords(promptforDelete);
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Пример #2
0
        [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();
            }
        }
Пример #3
0
        [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();
            }
        }
Пример #4
0
        [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();
            }
        }
        /// <summary>
        /// This method first connects to the Organization service. Afterwards, the
        /// sample creates a goal and child goals for a particular fiscal period.
        /// Stretched targets are tracked as well.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    #region Create goal metric

                    // Create the metric, setting the Metric Type to 'Count' and enabling
                    // stretch tracking.
                    Metric metric = new Metric()
                    {
                        Name             = "Sample Count Metric",
                        IsAmount         = false,
                        IsStretchTracked = true
                    };
                    _metricId = _serviceProxy.Create(metric);
                    metric.Id = _metricId;

                    Console.Write("Created count metric, ");

                    #endregion

                    #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 = metric.ToEntityReference()
                    };
                    _actualId = _serviceProxy.Create(actual);

                    Console.Write("created completed phone call 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",
                        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 closed outgoing phone calls.
                    GoalRollupQuery goalRollupQuery2 = new GoalRollupQuery()
                    {
                        Name            = "Example Goal Rollup Query",
                        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='1'/><condition attribute='statecode' operator='eq' value='1' /></filter></entity></fetch>"
                    };
                    _rollupQueryIds.Add(_serviceProxy.Create(goalRollupQuery2));
                    goalRollupQuery2.Id = _rollupQueryIds[1];

                    Console.Write("created rollup queries for phone calls.\n");
                    Console.WriteLine();

                    #endregion

                    #region Create goals

                    // Determine current fiscal period and year.
                    // Note: This sample assumes quarterly fiscal periods.
                    DateTime date          = DateTime.Now;
                    int      quarterNumber = (date.Month - 1) / 3 + 1;
                    int      yearNumber    = date.Year;

                    // Create three goals: one parent goal and two child goals.
                    Goal parentGoal = new Goal()
                    {
                        Title = "Parent Goal Example",
                        RollupOnlyFromChildGoals      = true,
                        ConsiderOnlyGoalOwnersRecords = true,
                        TargetInteger        = 8,
                        StretchTargetInteger = 10,
                        IsFiscalPeriodGoal   = true,
                        FiscalPeriod         = new OptionSetValue(quarterNumber),
                        FiscalYear           = new OptionSetValue(yearNumber),
                        MetricId             = metric.ToEntityReference(),
                        GoalOwnerId          = new EntityReference
                        {
                            Id          = _salesManagerId,
                            LogicalName = SystemUser.EntityLogicalName
                        },
                        OwnerId = new EntityReference
                        {
                            Id          = _salesManagerId,
                            LogicalName = SystemUser.EntityLogicalName
                        }
                    };
                    _parentGoalId = _serviceProxy.Create(parentGoal);
                    parentGoal.Id = _parentGoalId;

                    Console.WriteLine("Created parent goal");
                    Console.WriteLine("-------------------");
                    Console.WriteLine("Target: {0}", parentGoal.TargetInteger.Value);
                    Console.WriteLine("Stretch Target: {0}",
                                      parentGoal.StretchTargetInteger.Value);
                    Console.WriteLine("Goal owner: {0}", parentGoal.GoalOwnerId.Id);
                    Console.WriteLine("Goal Fiscal Period: {0}",
                                      parentGoal.FiscalPeriod.Value);
                    Console.WriteLine("Goal Fiscal Year: {0}",
                                      parentGoal.FiscalYear.Value);
                    Console.WriteLine("<End of Listing>");
                    Console.WriteLine();

                    Goal firstChildGoal = new Goal()
                    {
                        Title = "First Child Goal Example",
                        ConsiderOnlyGoalOwnersRecords = true,
                        TargetInteger        = 5,
                        StretchTargetInteger = 6,
                        IsFiscalPeriodGoal   = true,
                        FiscalPeriod         = new OptionSetValue(quarterNumber),
                        FiscalYear           = new OptionSetValue(yearNumber),
                        MetricId             = metric.ToEntityReference(),
                        ParentGoalId         = parentGoal.ToEntityReference(),
                        GoalOwnerId          = new EntityReference
                        {
                            Id          = _salesRepresentativeIds[0],
                            LogicalName = SystemUser.EntityLogicalName
                        },
                        OwnerId = new EntityReference
                        {
                            Id          = _salesManagerId,
                            LogicalName = SystemUser.EntityLogicalName
                        },
                        RollupQueryActualIntegerId = goalRollupQuery.ToEntityReference()
                    };
                    _firstChildGoalId = _serviceProxy.Create(firstChildGoal);

                    Console.WriteLine("First child goal");
                    Console.WriteLine("----------------");
                    Console.WriteLine("Target: {0}", firstChildGoal.TargetInteger.Value);
                    Console.WriteLine("Stretch Target: {0}",
                                      firstChildGoal.StretchTargetInteger.Value);
                    Console.WriteLine("Goal owner: {0}", firstChildGoal.GoalOwnerId.Id);
                    Console.WriteLine("Goal Fiscal Period: {0}",
                                      firstChildGoal.FiscalPeriod.Value);
                    Console.WriteLine("Goal Fiscal Year: {0}",
                                      firstChildGoal.FiscalYear.Value);
                    Console.WriteLine();

                    Goal secondChildGoal = new Goal()
                    {
                        Title = "Second Child Goal Example",
                        ConsiderOnlyGoalOwnersRecords = true,
                        TargetInteger        = 3,
                        StretchTargetInteger = 4,
                        IsFiscalPeriodGoal   = true,
                        FiscalPeriod         = new OptionSetValue(quarterNumber),
                        FiscalYear           = new OptionSetValue(yearNumber),
                        MetricId             = metric.ToEntityReference(),
                        ParentGoalId         = parentGoal.ToEntityReference(),
                        GoalOwnerId          = new EntityReference
                        {
                            Id          = _salesRepresentativeIds[1],
                            LogicalName = SystemUser.EntityLogicalName
                        },
                        OwnerId = new EntityReference
                        {
                            Id          = _salesManagerId,
                            LogicalName = SystemUser.EntityLogicalName
                        },
                        RollupQueryActualIntegerId = goalRollupQuery2.ToEntityReference()
                    };
                    _secondChildGoalId = _serviceProxy.Create(secondChildGoal);

                    Console.WriteLine("Second child goal");
                    Console.WriteLine("-----------------");
                    Console.WriteLine("Target: {0}",
                                      secondChildGoal.TargetInteger.Value);
                    Console.WriteLine("Stretch Target: {0}",
                                      secondChildGoal.StretchTargetInteger.Value);
                    Console.WriteLine("Goal owner: {0}", secondChildGoal.GoalOwnerId.Id);
                    Console.WriteLine("Goal Fiscal Period: {0}",
                                      secondChildGoal.FiscalPeriod.Value);
                    Console.WriteLine("Goal Fiscal Year: {0}",
                                      secondChildGoal.FiscalYear.Value);
                    Console.WriteLine();

                    #endregion

                    #region Calculate rollup and display result

                    // Calculate roll-up of goals.
                    RecalculateRequest recalculateRequest = new RecalculateRequest()
                    {
                        Target = new EntityReference(Goal.EntityLogicalName, _parentGoalId)
                    };
                    _serviceProxy.Execute(recalculateRequest);

                    Console.WriteLine("Calculated roll-up of goals.");

                    // Retrieve and report 3 different computed values for the goals
                    // - Percentage
                    // - ComputedTargetAsOfTodayPercentageAchieved
                    // - ComputedTargetAsOfTodayInteger
                    QueryExpression retrieveValues = new QueryExpression()
                    {
                        EntityName = Goal.EntityLogicalName,
                        ColumnSet  = new ColumnSet(
                            "title",
                            "percentage",
                            "computedtargetasoftodaypercentageachieved",
                            "computedtargetasoftodayinteger")
                    };
                    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: {0}", temp.Percentage);
                        Console.WriteLine("ComputedTargetAsOfTodayPercentageAchieved: {0}",
                                          temp.ComputedTargetAsOfTodayPercentageAchieved);
                        Console.WriteLine("ComputedTargetAsOfTodayInteger: {0}",
                                          temp.ComputedTargetAsOfTodayInteger.Value);
                        Console.WriteLine("<End of Listing>");
                    }

                    #endregion

                    DeleteRequiredRecords(promptforDelete);
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
        /// <summary>
        /// This method first connects to the Organization service. Afterwards, a
        /// rollup field and rollup query are created. The rollup query is only
        /// associated with the child goal. Then a parent goal and child goal
        /// are created. The goals are both rolled up and their results are displayed.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    // 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       = _serviceProxy.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 = _serviceProxy.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     = _serviceProxy.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 = _serviceProxy.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 = _serviceProxy.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()
                    };
                    _serviceProxy.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 = _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("ComputedTargetAsOfTodayPercentageAchieved: {0}",
                                          temp.ComputedTargetAsOfTodayPercentageAchieved);
                        Console.WriteLine("ComputedTargetAsOfTodayMoney: {0}",
                                          temp.ComputedTargetAsOfTodayMoney.Value);
                        Console.WriteLine("<End of Listing>");
                    }

                    DeleteRequiredRecords(promptforDelete);
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Пример #7
0
        [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

                    #region Create goal metric

                    // Create the metric, setting the Metric Type to 'Count' and enabling
                    // stretch tracking.
                    Metric metric = new Metric()
                    {
                        Name             = "Sample Count Metric",
                        IsAmount         = false,
                        IsStretchTracked = true
                    };
                    _metricId = service.Create(metric);
                    metric.Id = _metricId;

                    Console.Write("Created count metric, ");

                    #endregion

                    #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 = metric.ToEntityReference()
                    };
                    _actualId = service.Create(actual);

                    Console.Write("created completed phone call 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",
                        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(service.Create(goalRollupQuery));
                    goalRollupQuery.Id = _rollupQueryIds[0];

                    // The following query locates closed outgoing phone calls.
                    GoalRollupQuery goalRollupQuery2 = new GoalRollupQuery()
                    {
                        Name            = "Example Goal Rollup Query",
                        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='1'/><condition attribute='statecode' operator='eq' value='1' /></filter></entity></fetch>"
                    };
                    _rollupQueryIds.Add(service.Create(goalRollupQuery2));
                    goalRollupQuery2.Id = _rollupQueryIds[1];

                    Console.Write("created rollup queries for phone calls.\n");
                    Console.WriteLine();

                    #endregion

                    #region Create goals

                    // Determine current fiscal period and year.
                    // Note: This sample assumes quarterly fiscal periods.
                    DateTime date          = DateTime.Now;
                    int      quarterNumber = (date.Month - 1) / 3 + 1;
                    int      yearNumber    = date.Year;

                    // Create three goals: one parent goal and two child goals.
                    Goal parentGoal = new Goal()
                    {
                        Title = "Parent Goal Example",
                        RollupOnlyFromChildGoals      = true,
                        ConsiderOnlyGoalOwnersRecords = true,
                        TargetInteger        = 8,
                        StretchTargetInteger = 10,
                        IsFiscalPeriodGoal   = true,
                        FiscalPeriod         = new OptionSetValue(quarterNumber),
                        FiscalYear           = new OptionSetValue(yearNumber),
                        MetricId             = metric.ToEntityReference(),
                        GoalOwnerId          = new EntityReference
                        {
                            Id          = _salesManagerId,
                            LogicalName = SystemUser.EntityLogicalName
                        },
                        OwnerId = new EntityReference
                        {
                            Id          = _salesManagerId,
                            LogicalName = SystemUser.EntityLogicalName
                        }
                    };
                    _parentGoalId = service.Create(parentGoal);
                    parentGoal.Id = _parentGoalId;

                    Console.WriteLine("Created parent goal");
                    Console.WriteLine("-------------------");
                    Console.WriteLine("Target: {0}", parentGoal.TargetInteger.Value);
                    Console.WriteLine("Stretch Target: {0}",
                                      parentGoal.StretchTargetInteger.Value);
                    Console.WriteLine("Goal owner: {0}", parentGoal.GoalOwnerId.Id);
                    Console.WriteLine("Goal Fiscal Period: {0}",
                                      parentGoal.FiscalPeriod.Value);
                    Console.WriteLine("Goal Fiscal Year: {0}",
                                      parentGoal.FiscalYear.Value);
                    Console.WriteLine("<End of Listing>");
                    Console.WriteLine();

                    Goal firstChildGoal = new Goal()
                    {
                        Title = "First Child Goal Example",
                        ConsiderOnlyGoalOwnersRecords = true,
                        TargetInteger        = 5,
                        StretchTargetInteger = 6,
                        IsFiscalPeriodGoal   = true,
                        FiscalPeriod         = new OptionSetValue(quarterNumber),
                        FiscalYear           = new OptionSetValue(yearNumber),
                        MetricId             = metric.ToEntityReference(),
                        ParentGoalId         = parentGoal.ToEntityReference(),
                        GoalOwnerId          = new EntityReference
                        {
                            Id          = _salesRepresentativeIds[0],
                            LogicalName = SystemUser.EntityLogicalName
                        },
                        OwnerId = new EntityReference
                        {
                            Id          = _salesManagerId,
                            LogicalName = SystemUser.EntityLogicalName
                        },
                        RollupQueryActualIntegerId = goalRollupQuery.ToEntityReference()
                    };
                    _firstChildGoalId = service.Create(firstChildGoal);

                    Console.WriteLine("First child goal");
                    Console.WriteLine("----------------");
                    Console.WriteLine("Target: {0}", firstChildGoal.TargetInteger.Value);
                    Console.WriteLine("Stretch Target: {0}",
                                      firstChildGoal.StretchTargetInteger.Value);
                    Console.WriteLine("Goal owner: {0}", firstChildGoal.GoalOwnerId.Id);
                    Console.WriteLine("Goal Fiscal Period: {0}",
                                      firstChildGoal.FiscalPeriod.Value);
                    Console.WriteLine("Goal Fiscal Year: {0}",
                                      firstChildGoal.FiscalYear.Value);
                    Console.WriteLine();

                    Goal secondChildGoal = new Goal()
                    {
                        Title = "Second Child Goal Example",
                        ConsiderOnlyGoalOwnersRecords = true,
                        TargetInteger        = 3,
                        StretchTargetInteger = 4,
                        IsFiscalPeriodGoal   = true,
                        FiscalPeriod         = new OptionSetValue(quarterNumber),
                        FiscalYear           = new OptionSetValue(yearNumber),
                        MetricId             = metric.ToEntityReference(),
                        ParentGoalId         = parentGoal.ToEntityReference(),
                        GoalOwnerId          = new EntityReference
                        {
                            Id          = _salesRepresentativeIds[1],
                            LogicalName = SystemUser.EntityLogicalName
                        },
                        OwnerId = new EntityReference
                        {
                            Id          = _salesManagerId,
                            LogicalName = SystemUser.EntityLogicalName
                        },
                        RollupQueryActualIntegerId = goalRollupQuery2.ToEntityReference()
                    };
                    _secondChildGoalId = service.Create(secondChildGoal);

                    Console.WriteLine("Second child goal");
                    Console.WriteLine("-----------------");
                    Console.WriteLine("Target: {0}",
                                      secondChildGoal.TargetInteger.Value);
                    Console.WriteLine("Stretch Target: {0}",
                                      secondChildGoal.StretchTargetInteger.Value);
                    Console.WriteLine("Goal owner: {0}", secondChildGoal.GoalOwnerId.Id);
                    Console.WriteLine("Goal Fiscal Period: {0}",
                                      secondChildGoal.FiscalPeriod.Value);
                    Console.WriteLine("Goal Fiscal Year: {0}",
                                      secondChildGoal.FiscalYear.Value);
                    Console.WriteLine();

                    #endregion

                    #region Calculate rollup and display result

                    // 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
                    // - ComputedTargetAsOfTodayInteger
                    QueryExpression retrieveValues = new QueryExpression()
                    {
                        EntityName = Goal.EntityLogicalName,
                        ColumnSet  = new ColumnSet(
                            "title",
                            "percentage",
                            "computedtargetasoftodaypercentageachieved",
                            "computedtargetasoftodayinteger")
                    };
                    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("ComputedTargetAsOfTodayInteger: {0}",
                                          temp.ComputedTargetAsOfTodayInteger.Value);
                        Console.WriteLine("<End of Listing>");
                    }

                    #endregion


                    #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();
            }
        }
Пример #8
0
        /// <summary>
        /// This method first connects to the Organization service. Afterwards, a 
        /// rollup field and rollup query are created. The rollup query is only
        /// associated with the child goal. Then a parent goal and child goal
        /// are created. The goals are both rolled up and their results are displayed. 
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetUsingQueriesToTrackGoals1>
                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    // 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 = _serviceProxy.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 = _serviceProxy.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 = _serviceProxy.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 = _serviceProxy.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 = _serviceProxy.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()
                    };
                    _serviceProxy.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 = _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("ComputedTargetAsOfTodayPercentageAchieved: {0}",
                            temp.ComputedTargetAsOfTodayPercentageAchieved);
                        Console.WriteLine("ComputedTargetAsOfTodayMoney: {0}",
                            temp.ComputedTargetAsOfTodayMoney.Value);
                        Console.WriteLine("<End of Listing>");
                    }

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

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Пример #9
0
        /// <summary>
        /// This method first connects to the Organization service. Afterwards,
        /// a goal is created specifying the target count. The goal is then
        /// rolled up, the actual and in-progress values are overridden and finally the 
        /// goal is closed.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetOverrideGoalTotalCount1>
                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    // 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

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

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Пример #10
0
        /// <summary>
        /// This method first connects to the Organization service. Afterwards,
        /// several actions on Goal records are executed.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetRollupAllGoalsForCustomPeriodAgainstTargetRevenue1>
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    // 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 = _serviceProxy.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 = _serviceProxy.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 = _serviceProxy.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(_serviceProxy.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(_serviceProxy.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 = _serviceProxy.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 = _serviceProxy.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 = _serviceProxy.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();

                    // <snippetRecalculate1>
                    // Calculate roll-up of goals.
                    RecalculateRequest recalculateRequest = new RecalculateRequest()
                    {
                        Target = new EntityReference(Goal.EntityLogicalName, _parentGoalId)
                    };
                    _serviceProxy.Execute(recalculateRequest);

                    //</snippetRecalculate1>
                    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 = _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: {0}", temp.Percentage);
                        Console.WriteLine("ComputedTargetAsOfTodayPercentageAchieved: {0}",
                                          temp.ComputedTargetAsOfTodayPercentageAchieved);
                        Console.WriteLine("ComputedTargetAsOfTodayMoney: {0}",
                                          temp.ComputedTargetAsOfTodayMoney.Value);
                        Console.WriteLine("<End of Listing>");
                    }

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

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
        /// <summary>
        /// This method first connects to the Organization service. Afterwards, the
        /// sample creates a goal and child goals for a particular fiscal period. 
        /// Stretched targets are tracked as well.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetRollupAllGoalsForFiscalPeriodAndStretchedTargetRevenue1>
                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    #region Create goal metric

                    // Create the metric, setting the Metric Type to 'Count' and enabling
                    // stretch tracking.
                    Metric metric = new Metric()
                    {
                        Name = "Sample Count Metric",
                        IsAmount = false,
                        IsStretchTracked = true
                    };
                    _metricId = _serviceProxy.Create(metric);
                    metric.Id = _metricId;

                    Console.Write("Created count metric, ");

                    #endregion

                    #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 = metric.ToEntityReference()
                    };
                    _actualId = _serviceProxy.Create(actual);

                    Console.Write("created completed phone call 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",
                        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 closed outgoing phone calls.
                    GoalRollupQuery goalRollupQuery2 = new GoalRollupQuery()
                    {
                        Name = "Example Goal Rollup Query",
                        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='1'/><condition attribute='statecode' operator='eq' value='1' /></filter></entity></fetch>"
                    };
                    _rollupQueryIds.Add(_serviceProxy.Create(goalRollupQuery2));
                    goalRollupQuery2.Id = _rollupQueryIds[1];

                    Console.Write("created rollup queries for phone calls.\n");
                    Console.WriteLine();

                    #endregion

                    #region Create goals

                    // Determine current fiscal period and year.
                    // Note: This sample assumes quarterly fiscal periods.
                    DateTime date = DateTime.Now;
                    int quarterNumber = (date.Month - 1) / 3 + 1;
                    int yearNumber = date.Year;

                    // Create three goals: one parent goal and two child goals.
                    Goal parentGoal = new Goal()
                    {
                        Title = "Parent Goal Example",
                        RollupOnlyFromChildGoals = true,
                        ConsiderOnlyGoalOwnersRecords = true,
                        TargetInteger = 8,
                        StretchTargetInteger = 10,
                        IsFiscalPeriodGoal = true,
                        FiscalPeriod = new OptionSetValue(quarterNumber),
                        FiscalYear = new OptionSetValue(yearNumber),
                        MetricId = metric.ToEntityReference(),
                        GoalOwnerId = new EntityReference
                        {
                            Id = _salesManagerId,
                            LogicalName = SystemUser.EntityLogicalName
                        },
                        OwnerId = new EntityReference
                        {
                            Id = _salesManagerId,
                            LogicalName = SystemUser.EntityLogicalName
                        }
                    };
                    _parentGoalId = _serviceProxy.Create(parentGoal);
                    parentGoal.Id = _parentGoalId;

                    Console.WriteLine("Created parent goal");
                    Console.WriteLine("-------------------");
                    Console.WriteLine("Target: {0}", parentGoal.TargetInteger.Value);
                    Console.WriteLine("Stretch Target: {0}", 
                        parentGoal.StretchTargetInteger.Value);
                    Console.WriteLine("Goal owner: {0}", parentGoal.GoalOwnerId.Id);
                    Console.WriteLine("Goal Fiscal Period: {0}", 
                        parentGoal.FiscalPeriod.Value);
                    Console.WriteLine("Goal Fiscal Year: {0}", 
                        parentGoal.FiscalYear.Value);
                    Console.WriteLine("<End of Listing>");
                    Console.WriteLine();

                    Goal firstChildGoal = new Goal()
                    {
                        Title = "First Child Goal Example",
                        ConsiderOnlyGoalOwnersRecords = true,
                        TargetInteger = 5,
                        StretchTargetInteger = 6,
                        IsFiscalPeriodGoal = true,
                        FiscalPeriod = new OptionSetValue(quarterNumber),
                        FiscalYear = new OptionSetValue(yearNumber),
                        MetricId = metric.ToEntityReference(),
                        ParentGoalId = parentGoal.ToEntityReference(),
                        GoalOwnerId = new EntityReference
                        {
                            Id = _salesRepresentativeIds[0],
                            LogicalName = SystemUser.EntityLogicalName
                        },
                        OwnerId = new EntityReference
                        {
                            Id = _salesManagerId,
                            LogicalName = SystemUser.EntityLogicalName
                        },
                        RollupQueryActualIntegerId = goalRollupQuery.ToEntityReference()
                    };
                    _firstChildGoalId = _serviceProxy.Create(firstChildGoal);

                    Console.WriteLine("First child goal");
                    Console.WriteLine("----------------");
                    Console.WriteLine("Target: {0}", firstChildGoal.TargetInteger.Value);
                    Console.WriteLine("Stretch Target: {0}", 
                        firstChildGoal.StretchTargetInteger.Value);
                    Console.WriteLine("Goal owner: {0}", firstChildGoal.GoalOwnerId.Id);
                    Console.WriteLine("Goal Fiscal Period: {0}", 
                        firstChildGoal.FiscalPeriod.Value);
                    Console.WriteLine("Goal Fiscal Year: {0}", 
                        firstChildGoal.FiscalYear.Value);
                    Console.WriteLine();

                    Goal secondChildGoal = new Goal()
                    {
                        Title = "Second Child Goal Example",
                        ConsiderOnlyGoalOwnersRecords = true,
                        TargetInteger = 3,
                        StretchTargetInteger = 4,
                        IsFiscalPeriodGoal = true,
                        FiscalPeriod = new OptionSetValue(quarterNumber),
                        FiscalYear = new OptionSetValue(yearNumber),                     
                        MetricId = metric.ToEntityReference(),
                        ParentGoalId = parentGoal.ToEntityReference(),
                        GoalOwnerId = new EntityReference
                        {
                            Id = _salesRepresentativeIds[1],
                            LogicalName = SystemUser.EntityLogicalName
                        },
                        OwnerId = new EntityReference
                        {
                            Id = _salesManagerId,
                            LogicalName = SystemUser.EntityLogicalName
                        },
                        RollupQueryActualIntegerId = goalRollupQuery2.ToEntityReference()
                    };
                    _secondChildGoalId = _serviceProxy.Create(secondChildGoal);

                    Console.WriteLine("Second child goal");
                    Console.WriteLine("-----------------");
                    Console.WriteLine("Target: {0}", 
                        secondChildGoal.TargetInteger.Value);
                    Console.WriteLine("Stretch Target: {0}", 
                        secondChildGoal.StretchTargetInteger.Value);
                    Console.WriteLine("Goal owner: {0}", secondChildGoal.GoalOwnerId.Id);
                    Console.WriteLine("Goal Fiscal Period: {0}", 
                        secondChildGoal.FiscalPeriod.Value);
                    Console.WriteLine("Goal Fiscal Year: {0}", 
                        secondChildGoal.FiscalYear.Value);
                    Console.WriteLine();

                    #endregion

                    #region Calculate rollup and display result

                    // Calculate roll-up of goals.
                    RecalculateRequest recalculateRequest = new RecalculateRequest()
                    {
                        Target = new EntityReference(Goal.EntityLogicalName, _parentGoalId)
                    };
                    _serviceProxy.Execute(recalculateRequest);

                    Console.WriteLine("Calculated roll-up of goals.");

                    // Retrieve and report 3 different computed values for the goals
                    // - Percentage
                    // - ComputedTargetAsOfTodayPercentageAchieved
                    // - ComputedTargetAsOfTodayInteger
                    QueryExpression retrieveValues = new QueryExpression()
                    {
                        EntityName = Goal.EntityLogicalName,
                        ColumnSet = new ColumnSet(
                            "title", 
                            "percentage", 
                            "computedtargetasoftodaypercentageachieved", 
                            "computedtargetasoftodayinteger")
                    };
                    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: {0}", temp.Percentage);
                        Console.WriteLine("ComputedTargetAsOfTodayPercentageAchieved: {0}", 
                            temp.ComputedTargetAsOfTodayPercentageAchieved);
                        Console.WriteLine("ComputedTargetAsOfTodayInteger: {0}", 
                            temp.ComputedTargetAsOfTodayInteger.Value);
                        Console.WriteLine("<End of Listing>");
                    }

                    #endregion

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

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
        /// <summary>
        /// This method first connects to the Organization service. Afterwards,
        /// several actions on Goal records are executed.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                //<snippetRollupAllGoalsForCustomPeriodAgainstTargetRevenue1>
                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    // 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 = _serviceProxy.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 = _serviceProxy.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 = _serviceProxy.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(_serviceProxy.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(_serviceProxy.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 = _serviceProxy.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 = _serviceProxy.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 = _serviceProxy.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();

                    // <snippetRecalculate1>
                    // Calculate roll-up of goals.
                    RecalculateRequest recalculateRequest = new RecalculateRequest()
                    {
                        Target = new EntityReference(Goal.EntityLogicalName, _parentGoalId)
                    };
                    _serviceProxy.Execute(recalculateRequest);

                    //</snippetRecalculate1> 
                    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 = _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: {0}", temp.Percentage);
                        Console.WriteLine("ComputedTargetAsOfTodayPercentageAchieved: {0}", 
                            temp.ComputedTargetAsOfTodayPercentageAchieved);
                        Console.WriteLine("ComputedTargetAsOfTodayMoney: {0}", 
                            temp.ComputedTargetAsOfTodayMoney.Value);
                        Console.WriteLine("<End of Listing>");
                    }

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

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }