本文整理汇总了C#中OrganizationServiceProxy.RetrieveMultiple方法的典型用法代码示例。如果您正苦于以下问题:C# OrganizationServiceProxy.RetrieveMultiple方法的具体用法?C# OrganizationServiceProxy.RetrieveMultiple怎么用?C# OrganizationServiceProxy.RetrieveMultiple使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类OrganizationServiceProxy
的用法示例。
在下文中一共展示了OrganizationServiceProxy.RetrieveMultiple方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Run
/// <summary>
/// This method first connects to the Organization service. Afterwards, it
/// retrieves roles.
/// </summary>
/// <param name="serverConfig">Contains server connection information.</param>
/// <param name="promptforDelete">When True, the user is prompted to delete all
/// created entities.</param>
public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
{
try
{
//<snippetRetrieveRolesForOrg1>
// Connect to the Organization service.
// The using statement assures that the service proxy is properly disposed.
using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
{
QueryExpression query = new QueryExpression
{
EntityName = Role.EntityLogicalName,
ColumnSet = new ColumnSet("name", "roleid")
};
EntityCollection entities = _serviceProxy.RetrieveMultiple(query);
// Write the name and ID of each role to the console.
foreach (Entity item in entities.Entities)
{
Role role = item.ToEntity<Role>();
Console.WriteLine("Name: {0}. Id: {1}", role.Name, role.Id);
}
}
//</snippetRetrieveRolesForOrg1>
}
// 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: ReportErrors
/// <summary>
/// Check for importlog records
/// </summary>
/// <param name="service"></param>
/// <param name="importFileId"></param>
public static void ReportErrors(OrganizationServiceProxy serviceProxy, Guid importFileId)
{
QueryByAttribute importLogQuery = new QueryByAttribute();
importLogQuery.EntityName = ImportLog.EntityLogicalName;
importLogQuery.ColumnSet = new ColumnSet(true);
importLogQuery.Attributes.Add("importfileid");
importLogQuery.Values.Add(new object[1]);
importLogQuery.Values[0] = importFileId;
EntityCollection importLogs = serviceProxy.RetrieveMultiple(importLogQuery);
if (importLogs.Entities.Count > 0)
{
Console.WriteLine("Number of Failures: " + importLogs.Entities.Count.ToString());
Console.WriteLine("Sequence Number Error Number Description Column Header Column Value Line Number");
// Display errors.
foreach (ImportLog log in importLogs.Entities)
{
Console.WriteLine(
string.Format("Sequence Number: {0}\nError Number: {1}\nDescription: {2}\nColumn Header: {3}\nColumn Value: {4}\nLine Number: {5}",
log.SequenceNumber.Value,
log.ErrorNumber.Value,
log.ErrorDescription,
log.HeaderColumn,
log.ColumnValue,
log.LineNumber.Value));
}
}
}
示例3: Run
/// <summary>
/// Create and configure the organization service proxy.
/// Retrieve the history limit of a report.
/// Optionally delete any entity records that were created for this sample.
/// </summary>
/// <param name="serverConfig">Contains server connection information.</param>
/// <param name="promptforDelete">When True, the user will be prompted to delete all
/// created entities.</param>
public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
{
try
{
// Connect to the Organization service.
// The using statement assures that the service proxy will be properly disposed.
using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
{
// This statement is required to enable early-bound type support.
_serviceProxy.EnableProxyTypes();
// Call the method to create any data that this sample requires.
CreateRequiredRecords();
//<snippetGetReportHistoryLimit1>
// Query for an an existing report: Account Overview. This is a default report in Microsoft Dynamics CRM.
QueryByAttribute reportQuery = new QueryByAttribute(Report.EntityLogicalName);
reportQuery.AddAttributeValue("name", "Account Overview");
reportQuery.ColumnSet = new ColumnSet("reportid");
// Get the report.
EntityCollection retrieveReports = _serviceProxy.RetrieveMultiple(reportQuery);
// Convert retrieved Entity to a report
Report retrievedReport = (Report)retrieveReports.Entities[0];
Console.WriteLine("Retrieved the 'Account Overview' report.");
// Use the Download Report Definition message.
GetReportHistoryLimitRequest reportHistoryRequest = new GetReportHistoryLimitRequest
{
ReportId = retrievedReport.ReportId.Value
};
GetReportHistoryLimitResponse reportHistoryResponse = (GetReportHistoryLimitResponse)_serviceProxy.Execute(reportHistoryRequest);
// Access the history limit data
int historyLimit = reportHistoryResponse.HistoryLimit;
Console.WriteLine("The report history limit is {0}.", historyLimit);
//</snippetGetReportHistoryLimit1>
}
}
// 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;
}
}
示例4: QueryForSOPSetting
private static void QueryForSOPSetting(OrganizationServiceProxy proxy, out EntityCollection organizationSettings, out bool IsSOPIntegrationEnabled)
{
QueryExpression query = new QueryExpression()
{
EntityName = "organization",
ColumnSet = new ColumnSet(true),
};
organizationSettings = proxy.RetrieveMultiple(query);
IsSOPIntegrationEnabled = organizationSettings.Entities[0].GetAttributeValue<Boolean>("issopintegrationenabled");
}
示例5: Run
/// <summary>
/// Create and configure the organization service proxy.
/// Initiate method to create any data that this sample requires.
/// Retrieve opportunity and opportunity products.
/// Optionally delete any entity records that were created for this sample.
/// </summary>
/// <param name="serverConfig">Contains server connection information.</param>
/// <param name="promptforDelete">When True, the user will be prompted to delete all
/// created entities.</param>
public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
{
try
{
// Connect to the Organization service.
// The using statement assures that the service proxy will be properly disposed.
using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
{
// This statement is required to enable early-bound type support.
_serviceProxy.EnableProxyTypes();
// Call the method to create any data that this sample requires.
CreateRequiredRecords();
//<snippetRetrieveOpportunity1>
// Retrieve Opportunity record.
Opportunity checkOpportunity = (Opportunity)_serviceProxy.Retrieve(
Opportunity.EntityLogicalName,
_opportunityId,
new ColumnSet("name"));
Console.WriteLine("Retrieved {0}", checkOpportunity.Name);
// Retrieve the related opportunity products
QueryExpression opportunityProductsQuery = new QueryExpression
{
EntityName = OpportunityProduct.EntityLogicalName,
ColumnSet = new ColumnSet("opportunityproductid", "volumediscountamount"),
Criteria = new FilterExpression
{
Conditions =
{
new ConditionExpression
{
AttributeName = "opportunityid",
Operator = ConditionOperator.Equal,
Values = { _opportunityId }
}
}
}
};
DataCollection<Entity> opportunityProducts = _serviceProxy.RetrieveMultiple(
opportunityProductsQuery).Entities;
foreach (Entity entity in opportunityProducts)
{
OpportunityProduct opportunityProduct = (OpportunityProduct)entity;
Console.WriteLine("Retrieved Opportunity Product {0}",
opportunityProduct.OpportunityProductId.Value);
}
//</snippetRetrieveOpportunity1>
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;
}
}
示例6: buttonLoadSolutionsImportJobs_Click
/// <summary>
/// Handles the Click event of the buttonLoadSolutionsImportJobs control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
private void buttonLoadSolutionsImportJobs_Click(object sender, EventArgs e)
{
try
{
List<MSCRMSolutionImportJob> Lst = new List<MSCRMSolutionImportJob>();
dataGridView1.DataSource = Lst;
if (comboBoxConnectionSource.SelectedItem == null)
{
MessageBox.Show("You must select a connection before loading the Solution Import Jobs!");
return;
}
toolStripStatusLabel1.Text = "Loading Solution Import Jobs. Please wait...";
Application.DoEvents();
MSCRMConnection connection = cm.MSCRMConnections[comboBoxConnectionSource.SelectedIndex];
_serviceProxy = cm.connect(connection);
//Get Source Default Transaction Currency
string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='importjob'>
<attribute name='completedon' />
<attribute name='createdby' />
<attribute name='data' />
<attribute name='importjobid' />
<attribute name='modifiedon' />
<attribute name='progress' />
<attribute name='solutionname' />
<attribute name='startedon' />
<order attribute='createdon' descending='true' />
</entity>
</fetch> ";
EntityCollection result = _serviceProxy.RetrieveMultiple(new FetchExpression(fetchXml));
if (result.Entities.Count < 1)
{
MessageBox.Show("There are no Solution Import Jobs!");
return;
}
List<MSCRMSolutionImportJob> ImportJobsList = new List<MSCRMSolutionImportJob>();
foreach (Entity ImportJob in result.Entities)
{
MSCRMSolutionImportJob job = new MSCRMSolutionImportJob();
if (ImportJob.Contains("completedon"))
job.completedon = (DateTime)ImportJob["completedon"];
if (ImportJob.Contains("createdby"))
job.createdby = ((EntityReference)ImportJob["createdby"]).Name;
if (ImportJob.Contains("data"))
job.data = (String)ImportJob["data"];
if (ImportJob.Contains("importjobid"))
job.importjobid = (Guid)ImportJob["importjobid"];
if (ImportJob.Contains("modifiedon"))
job.modifiedon = (DateTime)ImportJob["modifiedon"];
if (ImportJob.Contains("progress"))
job.progress = Math.Round((Double)ImportJob["progress"], 2);
if (ImportJob.Contains("solutionname"))
job.solutionname = (String)ImportJob["solutionname"];
if (ImportJob.Contains("startedon"))
job.startedon = (DateTime)ImportJob["startedon"];
if (job.importjobid != null && job.importjobid != Guid.Empty)
ImportJobsList.Add(job);
}
SortableBindingList<MSCRMSolutionImportJob> sorted = new SortableBindingList<MSCRMSolutionImportJob>(ImportJobsList);
dataGridView1.DataSource = sorted;
toolStripStatusLabel1.Text = "Loaded " + result.Entities.Count + " Import Jobs.";
}
catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
{
MessageBox.Show("Error:" + ex.Detail.Message + "\n" + ex.Detail.TraceText);
toolStripStatusLabel1.Text = "Error.";
}
catch (Exception ex)
{
if (ex.InnerException != null)
{
MessageBox.Show("Error:" + ex.Message + "\n" + ex.InnerException.Message);
toolStripStatusLabel1.Text = "Error.";
}
else
{
MessageBox.Show("Error:" + ex.Message);
toolStripStatusLabel1.Text = "Error.";
}
}
}
示例7: RetrieveRoleByName
private static Role RetrieveRoleByName(OrganizationServiceProxy serviceProxy,
String roleStr)
{
QueryExpression roleQuery = new QueryExpression
{
EntityName = Role.EntityLogicalName,
ColumnSet = new ColumnSet("roleid"),
Criteria =
{
Conditions =
{
new ConditionExpression("name", ConditionOperator.Equal, roleStr)
}
}
};
return serviceProxy.RetrieveMultiple(roleQuery).Entities[0].ToEntity<Role>();
}
示例8: Run
//.........这里部分代码省略.........
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()
示例9: CreateSystemUser
private static Guid CreateSystemUser(String userName, String firstName,
String lastName, String domain, String roleStr,
OrganizationServiceProxy serviceProxy, ref String ldapPath)
{
CreateADAccount(userName, firstName, lastName, serviceProxy, ref ldapPath);
// Retrieve the default business unit needed to create the user.
QueryExpression businessUnitQuery = new QueryExpression
{
EntityName = BusinessUnit.EntityLogicalName,
ColumnSet = new ColumnSet("businessunitid"),
Criteria =
{
Conditions =
{
new ConditionExpression("parentbusinessunitid",
ConditionOperator.Null)
}
}
};
BusinessUnit defaultBusinessUnit = serviceProxy.RetrieveMultiple(
businessUnitQuery).Entities[0].ToEntity<BusinessUnit>();
//Create a new system user.
SystemUser user = new SystemUser
{
DomainName = domain + userName,
FirstName = firstName,
LastName = lastName,
BusinessUnitId = new EntityReference
{
LogicalName = BusinessUnit.EntityLogicalName,
Name = BusinessUnit.EntityLogicalName,
Id = defaultBusinessUnit.Id
}
};
Guid userId = serviceProxy.Create(user);
if (!String.IsNullOrWhiteSpace(roleStr))
{
// Retrieve the specified security role.
Role role = RetrieveRoleByName(serviceProxy, roleStr);
// Assign the security role to the newly created Microsoft Dynamics CRM user.
AssociateRequest associate = new AssociateRequest()
{
Target = new EntityReference(SystemUser.EntityLogicalName, userId),
RelatedEntities = new EntityReferenceCollection()
{
new EntityReference(Role.EntityLogicalName, role.Id),
},
Relationship = new Relationship("systemuserroles_association")
};
serviceProxy.Execute(associate);
}
return userId;
}
示例10: Run
/// <summary>
/// Create and configure the organization service proxy.
/// Initiate the method to create any data that this sample requires.
/// Reschedule an instance of the recurring appointment series.
/// Cancel another instance of the recurring appointment series.
/// Optionally delete any entity records that were created for this sample.
/// </summary>
/// <param name="serverConfig">Contains server connection information.</param>
/// <param name="promptforDelete">When True, the user will be prompted to delete all
/// created entities.</param>
public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
{
try
{
// Connect to the Organization service.
// The using statement assures that the service proxy will be properly disposed.
using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
{
// This statement is required to enable early-bound type support.
_serviceProxy.EnableProxyTypes();
// Call the method to create any data that this sample requires.
CreateRequiredRecords();
//<snippetRescheduleandCancelRecurringAppointmentInstance1>
// Retrieve the individual appointment instance that falls on or after
// 10 days from today. Basically this will be the second instance in the
// recurring appointment series.
QueryExpression instanceQuery = new QueryExpression
{
EntityName = Appointment.EntityLogicalName,
ColumnSet = new ColumnSet
{
Columns = { "activityid", "scheduledstart", "scheduledend" }
},
Criteria = new FilterExpression
{
Conditions =
{
new ConditionExpression
{
AttributeName = "seriesid",
Operator = ConditionOperator.Equal,
Values = { _recurringAppointmentMasterId }
},
new ConditionExpression
{
AttributeName = "scheduledstart",
Operator = ConditionOperator.OnOrAfter,
Values = { DateTime.Today.AddDays(10) }
}
}
}
};
EntityCollection individualAppointments = _serviceProxy.RetrieveMultiple(instanceQuery);
//<snippetRescheduleandCancelRecurringAppointmentInstance2>
#region Reschedule an instance of recurring appointment
// Update the scheduled start and end dates of the appointment
// to reschedule it.
Appointment updateAppointment = new Appointment
{
ActivityId = individualAppointments.Entities.Select(x => (Appointment)x).First().ActivityId,
ScheduledStart = individualAppointments.Entities.Select(x => (Appointment)x).First().ScheduledStart.Value.AddHours(1),
ScheduledEnd = individualAppointments.Entities.Select(x => (Appointment)x).First().ScheduledEnd.Value.AddHours(2)
};
RescheduleRequest reschedule = new RescheduleRequest
{
Target = updateAppointment
};
RescheduleResponse rescheduled = (RescheduleResponse)_serviceProxy.Execute(reschedule);
Console.WriteLine("Rescheduled the second instance of the recurring appointment.");
#endregion Reschedule an instance of recurring appointment
//</snippetRescheduleandCancelRecurringAppointmentInstance2>
//<snippetRescheduleandCancelRecurringAppointmentInstance3>
#region Cancel an instance of recurring appointment
// Cancel the last instance of the appointment. The status of this appointment
// instance is set to 'Canceled'. You can view this appoinyment instance under
// the 'All Activities' view.
SetStateRequest appointmentRequest = new SetStateRequest
{
State = new OptionSetValue((int)AppointmentState.Canceled),
Status = new OptionSetValue(4),
EntityMoniker = new EntityReference(Appointment.EntityLogicalName,
new Guid(individualAppointments.Entities.Select(x => (Appointment)x).Last().ActivityId.ToString()))
};
_serviceProxy.Execute(appointmentRequest);
Console.WriteLine("Canceled the last instance of the recurring appointment.");
//.........这里部分代码省略.........
示例11: Run
/// <summary>
/// Create and configure the organization service proxy.
/// Retrieve organization-owned visualizations.
/// Optionally delete any entity records that were created for this sample.
/// </summary>
/// <param name="serverConfig">Contains server connection information.</param>
/// <param name="promptforDelete">When True, the user will be prompted to delete all
/// created entities.</param>
public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
{
try
{
// Connect to the Organization service.
// The using statement assures that the service proxy will be properly disposed.
using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
{
// This statement is required to enable early-bound type support.
_serviceProxy.EnableProxyTypes();
//<snippetRetrieveVisualizationsAttachedToAnEntity1>
// Create a query for retrieving all organization-owned visualizations
// that are attached to the account entity.
QueryExpression mySavedQuery = new QueryExpression
{
EntityName = SavedQueryVisualization.EntityLogicalName,
ColumnSet = new ColumnSet("name"),
Criteria = new FilterExpression
{
Conditions =
{
new ConditionExpression
{
AttributeName = "primaryentitytypecode",
Operator = ConditionOperator.Equal,
Values = {Account.EntityLogicalName}
}
}
}
};
// Retrieve a collection of organization-owned visualizations that are attached to the account entity.
DataCollection<Entity> results = _serviceProxy.RetrieveMultiple(mySavedQuery).Entities;
// Display the names of the retrieved organization-owned visualizations.
Console.WriteLine("Retrieved the following visualizations for the Account entity:");
foreach (Entity entity in results)
{
SavedQueryVisualization orgVisualization = (SavedQueryVisualization)entity;
Console.WriteLine("{0}", orgVisualization.Name);
}
//</snippetRetrieveVisualizationsAttachedToAnEntity1>
}
}
// 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;
}
}
示例12: Run
//.........这里部分代码省略.........
// Define an anonymous type to define the possible values for days
// of the week
var DayOfWeek = new
{
Sunday = 0x01,
Monday = 0x02,
Tuesday = 0x04,
Wednesday = 0x08,
Thursday = 0x10,
Friday = 0x20,
Saturday = 0x40
};
// Define an anonymous type to define the possible values
// for the recurrence rule pattern end type.
var RecurrenceRulePatternEndType = new
{
NoEndDate = 1,
Occurrences = 2,
PatternEndDate = 3
};
// Create a recurring appointment
RecurringAppointmentMaster newRecurringAppointment = new RecurringAppointmentMaster
{
Subject = "Sample Recurring Appointment",
StartTime = DateTime.Now.AddHours(1),
EndTime = DateTime.Now.AddHours(2),
RecurrencePatternType = new OptionSetValue(RecurrencePatternTypes.Weekly),
Interval = 1,
DaysOfWeekMask = DayOfWeek.Thursday,
PatternStartDate = DateTime.Today,
Occurrences = 10,
PatternEndType = new OptionSetValue(RecurrenceRulePatternEndType.Occurrences)
};
_recurringAppointmentMasterId = _serviceProxy.Create(newRecurringAppointment);
Console.WriteLine("Created {0}.", newRecurringAppointment.Subject);
// Retrieve the newly created recurring appointment
QueryExpression recurringAppointmentQuery = new QueryExpression
{
EntityName = RecurringAppointmentMaster.EntityLogicalName,
ColumnSet = new ColumnSet("subject"),
Criteria = new FilterExpression
{
Conditions =
{
new ConditionExpression
{
AttributeName = "subject",
Operator = ConditionOperator.Equal,
Values = { "Sample Recurring Appointment" }
},
new ConditionExpression
{
AttributeName = "interval",
Operator = ConditionOperator.Equal,
Values = { 1 }
}
}
},
PageInfo = new PagingInfo
{
Count = 1,
PageNumber = 1
}
};
RecurringAppointmentMaster retrievedRecurringAppointment =
_serviceProxy.RetrieveMultiple(recurringAppointmentQuery).
Entities.Select(x => (RecurringAppointmentMaster)x).FirstOrDefault();
Console.WriteLine("Retrieved the recurring appointment.");
// Update the recurring appointment.
// Update the following for the retrieved recurring appointment series:
// 1. Update the subject.
// 2. Update the number of occurences to 5.
// 3. Update the appointment interval to 2.
retrievedRecurringAppointment.Subject = "Updated Recurring Appointment";
retrievedRecurringAppointment.Occurrences = 5;
retrievedRecurringAppointment.Interval = 2;
_serviceProxy.Update(retrievedRecurringAppointment);
Console.WriteLine("Updated the subject, occurrences, and interval of the recurring appointment.");
//</snippetCRUDRecurringAppointment1>
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;
}
}
示例13: Run
/// <summary>
/// Shows how to detect dependencies that may cause a managed solution to become
/// un-deletable.
///
/// Get all solution components of a solution
/// For each solution component, list the dependencies upon that component.
/// </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();
// Call the method to create any data that this sample requires.
CreateRequiredRecords();
//<snippetGetSolutionDependencies1>
// Grab all Solution Components for a solution.
QueryByAttribute componentQuery = new QueryByAttribute
{
EntityName = SolutionComponent.EntityLogicalName,
ColumnSet = new ColumnSet("componenttype", "objectid", "solutioncomponentid", "solutionid"),
Attributes = { "solutionid" },
// In your code, this value would probably come from another query.
Values = { _primarySolutionId }
};
IEnumerable<SolutionComponent> allComponents =
_serviceProxy.RetrieveMultiple(componentQuery).Entities.Cast<SolutionComponent>();
foreach (SolutionComponent component in allComponents)
{
// For each solution component, retrieve all dependencies for the component.
RetrieveDependentComponentsRequest dependentComponentsRequest =
new RetrieveDependentComponentsRequest
{
ComponentType = component.ComponentType.Value,
ObjectId = component.ObjectId.Value
};
RetrieveDependentComponentsResponse dependentComponentsResponse =
(RetrieveDependentComponentsResponse)_serviceProxy.Execute(dependentComponentsRequest);
// If there are no dependent components, we can ignore this component.
if (dependentComponentsResponse.EntityCollection.Entities.Any() == false)
continue;
// If there are dependencies upon this solution component, and the solution
// itself is managed, then you will be unable to delete the solution.
Console.WriteLine("Found {0} dependencies for Component {1} of type {2}",
dependentComponentsResponse.EntityCollection.Entities.Count,
component.ObjectId.Value,
component.ComponentType.Value
);
//A more complete report requires more code
foreach (Dependency d in dependentComponentsResponse.EntityCollection.Entities)
{
DependencyReport(d);
}
}
//</snippetGetSolutionDependencies1>
//Find out if any dependencies on a specific global option set would prevent it from being deleted
//<snippetGetSolutionDependencies8>
// Use the RetrieveOptionSetRequest message to retrieve
// a global option set by it's name.
RetrieveOptionSetRequest retrieveOptionSetRequest =
new RetrieveOptionSetRequest
{
Name = _globalOptionSetName
};
// Execute the request.
RetrieveOptionSetResponse retrieveOptionSetResponse =
(RetrieveOptionSetResponse)_serviceProxy.Execute(
retrieveOptionSetRequest);
_globalOptionSetId = retrieveOptionSetResponse.OptionSetMetadata.MetadataId;
if (_globalOptionSetId != null)
{
//Use the global OptionSet MetadataId with the appropriate componenttype
// to call RetrieveDependenciesForDeleteRequest
RetrieveDependenciesForDeleteRequest retrieveDependenciesForDeleteRequest = new RetrieveDependenciesForDeleteRequest
{
ComponentType = (int)componenttype.OptionSet,
ObjectId = (Guid)_globalOptionSetId
};
RetrieveDependenciesForDeleteResponse retrieveDependenciesForDeleteResponse =
(RetrieveDependenciesForDeleteResponse)_serviceProxy.Execute(retrieveDependenciesForDeleteRequest);
Console.WriteLine("");
foreach (Dependency d in retrieveDependenciesForDeleteResponse.EntityCollection.Entities)
//.........这里部分代码省略.........
示例14: Run
//.........这里部分代码省略.........
};
_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;
}
}
示例15: Run
/// <summary>
/// This method first connects to the Organization service. Afterwards,
/// a Contract Template and several Contracts are created, demonstrating how to
/// create and work with the Contract entity.
/// </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
{
//<snippetWorkingWithContracts1>
// 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 Contract Template
// First, attempt to retrieve the Contract Template. Otherwise,
// create the template.
QueryExpression templateQuery = new QueryExpression()
{
EntityName = ContractTemplate.EntityLogicalName,
ColumnSet = new ColumnSet("contracttemplateid"),
Criteria =
{
Conditions =
{
new ConditionExpression("abbreviation", ConditionOperator.Equal, "SCT")
}
}
};
EntityCollection ec = _serviceProxy.RetrieveMultiple(templateQuery);
if (ec.Entities.Count > 0)
{
_contractTemplateId = ec.Entities[0].Id;
Console.Write("Template retrieved, ");
}
else
{
ContractTemplate contractTemplate = new ContractTemplate()
{
Name = "Sample Contract Template",
BillingFrequencyCode = new OptionSetValue((int)ContractTemplateBillingFrequencyCode.Monthly),
Abbreviation = "SCT",
AllotmentTypeCode = new OptionSetValue((int)ContractTemplateAllotmentTypeCode.NumberofCases),
EffectivityCalendar =
"--------+++++++++---------------+++++++++---------------+++++++++---------------+++++++++---------------+++++++++-------------------------------------------------------"
};
_contractTemplateId = _serviceProxy.Create(contractTemplate);
Console.Write("Template created, ");
}
#endregion
#region Create Contract
// Create a Contract from the Contract Template.
Contract contract = new Contract()
{
Title = "Sample Contract",
ContractTemplateId = new EntityReference
{
Id = _contractTemplateId,
LogicalName = ContractTemplate.EntityLogicalName
},
CustomerId = new EntityReference
{
Id = _accountId,
LogicalName = Account.EntityLogicalName
},
BillingCustomerId = new EntityReference
{
Id = _accountId,
LogicalName = Account.EntityLogicalName
},
ActiveOn = new DateTime(2015, 1, 1),
ExpiresOn = new DateTime(2020, 1, 1),
BillingStartOn = new DateTime(2015, 1, 1),
BillingEndOn = new DateTime(2020, 1, 1)
};
_contractId = _serviceProxy.Create(contract);
Console.Write("parent contract created, ");
// Create a contract line item.
ContractDetail contractLineItem = new ContractDetail()
{
Title = "Sample Contract Line Item",
ContractId = new EntityReference
{
Id = _contractId,
LogicalName = Contract.EntityLogicalName
//.........这里部分代码省略.........