本文整理汇总了C#中OrganizationServiceProxy.Update方法的典型用法代码示例。如果您正苦于以下问题:C# OrganizationServiceProxy.Update方法的具体用法?C# OrganizationServiceProxy.Update怎么用?C# OrganizationServiceProxy.Update使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类OrganizationServiceProxy
的用法示例。
在下文中一共展示了OrganizationServiceProxy.Update方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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;
}
}
示例2: Run
/// <summary>
/// Create and configure the organization service proxy.
/// Call the method to create any data that this sample requires.
/// Update the connectionrole instance.
/// Optionally delete any entity records that were created for this sample.
/// </summary>
public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
{
try
{
// Connect to the Organization service.
// The using statement assures that the service proxy will be properly disposed.
using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
{
// This statement is required to enable early-bound type support.
_serviceProxy.EnableProxyTypes();
CreateRequiredRecords();
//<snippetUpdateConnectionRole1>
// Define some anonymous types to define the range
// of possible connection property values.
var Categories = new
{
Business = 1,
Family = 2,
Social = 3,
Sales = 4,
Other = 5
};
// Update the connectionrole instance.
ConnectionRole connectionRole = new ConnectionRole
{
ConnectionRoleId = _connectionRoleId,
Name = "Updated Connection Role",
Description = "This is an updated connection role.",
Category = new OptionSetValue(Categories.Other)
};
_serviceProxy.Update(connectionRole);
//</snippetUpdateConnectionRole1>
Console.WriteLine("Updated the connectionrole instance.");
DeleteRequiredRecords(promptForDelete);
}
}
// Catch any service fault exceptions that Microsoft Dynamics CRM throws.
catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
{
// You can handle an exception here or pass it back to the calling method.
throw;
}
}
示例3: Run
/// <summary>
/// This method first connects to the organization service. Next, auditing
/// is enabled on the organization and an account entity. The account record
/// is updated and the audit history printed out.
/// </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)
{
using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
{
// Enable early-bound type support.
_serviceProxy.EnableProxyTypes();
// You can access the service through the proxy, but this sample uses the interface instead.
_service = _serviceProxy;
#region Enable Auditing for an Account
//<snippetAuditing1>
Console.WriteLine("Enabling auditing on the organization and account entities.");
// Enable auditing on the organization.
// First, get the organization's ID from the system user record.
Guid orgId = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).OrganizationId;
// Next, retrieve the organization's record.
Organization org = _service.Retrieve(Organization.EntityLogicalName, orgId,
new ColumnSet(new string[] { "organizationid", "isauditenabled" })) as Organization;
// Finally, enable auditing on the organization.
bool organizationAuditingFlag = org.IsAuditEnabled.Value;
org.IsAuditEnabled = true;
_service.Update(org);
// Enable auditing on account entities.
bool accountAuditingFlag = EnableEntityAuditing(Account.EntityLogicalName, true);
//</snippetAuditing1>
#endregion Enable Auditing for an Account
CreateRequiredRecords();
#region Retrieve the Record Change History
Console.WriteLine("Retrieving the account change history.\n");
//<snippetAuditing5>
// Retrieve the audit history for the account and display it.
RetrieveRecordChangeHistoryRequest changeRequest = new RetrieveRecordChangeHistoryRequest();
changeRequest.Target = new EntityReference(Account.EntityLogicalName, _newAccountId);
RetrieveRecordChangeHistoryResponse changeResponse =
(RetrieveRecordChangeHistoryResponse)_service.Execute(changeRequest);
AuditDetailCollection details = changeResponse.AuditDetailCollection;
//</snippetAuditing5>
foreach (AttributeAuditDetail detail in details.AuditDetails)
{
// Display some of the detail information in each audit record.
DisplayAuditDetails(detail);
}
#endregion Retrieve the Record Change History
#region Retrieve the Attribute Change History
//<snippetAuditing7>
// Update the Telephone1 attribute in the Account entity record.
Account accountToUpdate = new Account();
accountToUpdate.AccountId = _newAccountId;
accountToUpdate.Telephone1 = "123-555-5555";
_serviceProxy.Update(accountToUpdate);
Console.WriteLine("Updated the Telephone1 field in the Account entity.");
// Retrieve the attribute change history.
Console.WriteLine("Retrieving the attribute change history for Telephone1.");
var attributeChangeHistoryRequest = new RetrieveAttributeChangeHistoryRequest
{
Target = new EntityReference(
Account.EntityLogicalName, _newAccountId),
AttributeLogicalName = "telephone1"
};
var attributeChangeHistoryResponse =
(RetrieveAttributeChangeHistoryResponse)_service.Execute(attributeChangeHistoryRequest);
// Display the attribute change history.
details = attributeChangeHistoryResponse.AuditDetailCollection;
//</snippetAuditing7>
foreach (var detail in details.AuditDetails)
{
DisplayAuditDetails(detail);
}
// Save an Audit record ID for later use.
Guid auditSampleId = details.AuditDetails.First().AuditRecord.Id;
#endregion Retrieve the Attribute Change History
#region Retrieve the Audit Details
//<snippetAuditing8>
//.........这里部分代码省略.........
示例4: Run
/// <summary>
/// This method first connects to the Organization service. Afterwards,
/// basic create, retrieve, update, and delete entity operations are performed.
/// </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
{
//<snippetCRUDOperations1>
// 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();
// Instantiate an account object.
// See the Entity Metadata topic in the SDK documentation to determine
// which attributes must be set for each entity.
Account account = new Account { Name = "Fourth Coffee" };
// Create an account record named Fourth Coffee.
_accountId = _serviceProxy.Create(account);
Console.Write("{0} {1} created, ", account.LogicalName, account.Name);
// Retrieve the account containing several of its attributes.
ColumnSet cols = new ColumnSet(
new String[] { "name", "address1_postalcode", "lastusedincampaign", "versionnumber" });
Account retrievedAccount = (Account)_serviceProxy.Retrieve("account", _accountId, cols);
Console.Write("retrieved ");
// Retrieve version number of the account. Shows BigInt attribute usage.
long? versionNumber = retrievedAccount.VersionNumber;
if (versionNumber != null)
Console.WriteLine("version # {0}, ", versionNumber);
// Update the postal code attribute.
retrievedAccount.Address1_PostalCode = "98052";
// The address 2 postal code was set accidentally, so set it to null.
retrievedAccount.Address2_PostalCode = null;
// Shows usage of option set (picklist) enumerations defined in OptionSets.cs.
retrievedAccount.Address1_AddressTypeCode = new OptionSetValue((int)AccountAddress1_AddressTypeCode.Primary);
retrievedAccount.Address1_ShippingMethodCode = new OptionSetValue((int)AccountAddress1_ShippingMethodCode.DHL);
retrievedAccount.IndustryCode = new OptionSetValue((int)AccountIndustryCode.AgricultureandNonpetrolNaturalResourceExtraction);
// Shows use of a Money value.
retrievedAccount.Revenue = new Money(5000000);
// Shows use of a Boolean value.
retrievedAccount.CreditOnHold = false;
// Shows use of EntityReference.
retrievedAccount.ParentAccountId = new EntityReference(Account.EntityLogicalName, _parentAccountId);
// Shows use of Memo attribute.
retrievedAccount.Description = "Account for Fourth Coffee.";
// Update the account record.
_serviceProxy.Update(retrievedAccount);
Console.WriteLine("and updated.");
DeleteRequiredRecords(promptforDelete);
}
//</snippetCRUDOperations1>
}
// 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;
}
}
示例5: Run
/// <summary>
/// Create and configure the organization service proxy.
/// Set the report to be available and then unavailable for the organization.
/// 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
{
//<snippetMakeReportAvailableOrUnavailableToOrganization1>
// 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();
// Retrieve existing personal report.
Report existingPersonalReport =
(Report)_serviceProxy.Retrieve(Report.EntityLogicalName,
_reportId,
new ColumnSet("ispersonal"));
// Set IsPersonal property to false.
existingPersonalReport.IsPersonal = false;
// Make the report available to the organization.
_serviceProxy.Update(existingPersonalReport);
// Retrieve the report and verify that the report is available to the organization
ColumnSet Cols1 = new ColumnSet("ispersonal");
Report retrieveAvailableReport =
(Report)_serviceProxy.Retrieve(Report.EntityLogicalName,
_reportId, Cols1);
if (retrieveAvailableReport.IsPersonal.Value == false)
{
Console.WriteLine("Report is available to the organization.");
}
// Now make the retrieved report unavailable to the organization
retrieveAvailableReport.IsPersonal = true;
_serviceProxy.Update(retrieveAvailableReport);
// Retrieve the report, and verify that the report is unavailable to the organization
ColumnSet Cols2 = new ColumnSet("ispersonal");
Report retrieveUnavailableReport =
(Report)_serviceProxy.Retrieve(Report.EntityLogicalName,
_reportId, Cols2);
if (retrieveUnavailableReport.IsPersonal.Value == true)
{
Console.WriteLine("Report is unavailable to the organization.");
}
DeleteRequiredRecords(promptforDelete);
}
//</snippetMakeReportAvailableOrUnavailableToOrganization1>
}
// 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: Run
/// <summary>
/// Create and configure the organization service proxy.
/// Configure an existing queue's email property values.
/// 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();
//<snippetConfigureQueueEmail1>
// Define some anonymous types to define the range
// of possible queue property values.
var IncomingEmailDeliveryMethods = new
{
None = 0,
EmailRouter = 2,
ForwardMailbox = 3
};
var IncomingEmailFilteringMethods = new
{
AllEmailMessages = 0,
EmailMessagesInResponseToCrmEmail = 1,
EmailMessagesFromCrmLeadsContactsAndAccounts = 2
};
var OutgoingEmailDeliveryMethods = new
{
None = 0,
EmailRouter = 2
};
// Update a queue instance and set its email property values.
Queue configureQueue = new Queue()
{
QueueId = _queueId,
IncomingEmailDeliveryMethod = new OptionSetValue(
IncomingEmailDeliveryMethods.EmailRouter),
IncomingEmailFilteringMethod = new OptionSetValue(
IncomingEmailFilteringMethods.EmailMessagesInResponseToCrmEmail),
OutgoingEmailDeliveryMethod = new OptionSetValue(
OutgoingEmailDeliveryMethods.None),
// TODO: Update with appropriate address
// for accessing the e-mail router.
EMailAddress = "[email protected]",
};
_serviceProxy.Update(configureQueue);
//</snippetConfigureQueueEmail1>
Console.WriteLine("Configured the queue's email property values.");
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: Run
/// <summary>
/// Run this sample, which shows both how to serialize late-bound and
/// early-bound entity instances to XML and how to de-serialize them back from
/// XML into entity instances.
/// </summary>
/// <param name="serverConfig"> Contains server connection information.</param>
/// <param name="promptToDelete"> When True, the user will be prompted to delete all
/// created entities.
public void Run(ServerConnection.Configuration serverConfig, bool promptToDelete)
{
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 Retrieve the contact from Microsoft CRM
// Create the column set object that indicates the fields to be retrieved.
var columns = new ColumnSet(
"contactid",
"firstname",
"lastname",
"jobtitle");
// Retrieve the contact from Microsoft CRM using the ID of the record that was just created.
// The EntityLogicalName indicates the EntityType of the object being retrieved.
var contact = (Contact)_serviceProxy.Retrieve(
Contact.EntityLogicalName, _contactId, columns);
Console.WriteLine("The contact for the sample has been retrieved.");
#endregion
#region Serialize the contact into XML and save it
// Serialize the contact into XML and write it to the hard drive.
var earlyBoundSerializer = new DataContractSerializer(typeof(Contact));
// Create a unique file name for the XML.
String earlyboundFile = "Contact_early_" + contact.ContactId.Value.ToString("B") + ".xml";
// Write the serialized object to a file. The using statement will
// ensure that the FileStream is disposed of correctly. The FileMode
// will ensure that the file is overwritten if it already exists.
using (var file = new FileStream(earlyboundFile, FileMode.Create))
{
// Write the XML to disk.
earlyBoundSerializer.WriteObject(file, contact);
}
Console.WriteLine(
"The early-bound contact instance has been serialized to a file, {0}.",
earlyboundFile);
// Convert the contact to a late-bound entity instance and serialize it to disk.
var lateboundContact = contact.ToEntity<Entity>();
String lateboundFile = "Contact_late_" + lateboundContact.Id.ToString("B") + ".xml";
var lateBoundSerializer = new DataContractSerializer(typeof(Entity));
// Write the serialized object to a file.
using (var file = new FileStream(lateboundFile, FileMode.Create))
{
lateBoundSerializer.WriteObject(file, lateboundContact);
}
Console.WriteLine(
"The late-bound contact instance has been serialized to a file, {0}.",
lateboundFile);
#endregion
#region De-serialize the Microsoft CRM contact from XML
Contact deserializedContact = null;
using (var file = new FileStream(earlyboundFile, FileMode.Open))
{
deserializedContact = (Contact)earlyBoundSerializer.ReadObject(file);
Console.WriteLine("The contact has been de-serialized: {0} {1}",
deserializedContact.FirstName, deserializedContact.LastName);
}
#endregion
#region Update contact in Microsoft CRM
// Update the contact in Microsoft CRM to prove that the de-serialization worked.
deserializedContact.JobTitle = "Plumber";
_serviceProxy.Update(deserializedContact);
Console.WriteLine("The contact was updated in Microsoft CRM.");
#endregion
DeleteRequiredRecords(promptToDelete);
}
}
示例8: Run
/// <summary>
/// This sample demonstrates how to audit user access to Microsoft Dynamics CRM.
/// The sample first enables user access auditing on an organization. Next, it
/// creates and modifies an entity. Finally, the sample displays a report of the
/// audited information.
/// </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)
{
_sampleStartTime = DateTime.Now;
using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
{
// This statement is required to enable early-bound type support.
_serviceProxy.EnableProxyTypes();
#region Enable Auditing
// Enable auditing on the organization and for user access by editing the
// organization's settings.
// First, get the organization's ID from the system user record.
var whoAmIReq = new WhoAmIRequest();
var whoAmIRes = (WhoAmIResponse)_serviceProxy.Execute(whoAmIReq);
Guid orgId = whoAmIRes.OrganizationId;
_systemUserId = whoAmIRes.UserId;
// Next, retrieve the organization's record.
var org = (Organization)_serviceProxy.Retrieve(
Organization.EntityLogicalName, orgId,
new ColumnSet("organizationid", "isauditenabled", "isuseraccessauditenabled", "useraccessauditinginterval"));
// Finally, enable auditing on the organization, including auditing for
// user access.
bool organizationAuditingFlag = org.IsAuditEnabled.Value;
bool userAccessAuditingFlag = org.IsUserAccessAuditEnabled.Value;
if (!organizationAuditingFlag || !userAccessAuditingFlag)
{
org.IsAuditEnabled = true;
org.IsUserAccessAuditEnabled = true;
_serviceProxy.Update(org);
Console.WriteLine("Enabled auditing for the organization and for user access.");
Console.WriteLine("Auditing interval is set to {0} hours.", org.UserAccessAuditingInterval);
}
else
{
Console.WriteLine("Auditing was enabled before the sample began, so no auditing settings were changed.");
}
// Enable auditing on the account entity, since no audits will be created
// when we create/update an account entity, otherwise.
var oldAccountAuditing = EnableEntityAuditing(Account.EntityLogicalName, true);
#endregion Enable Auditing
#region Make Audited Service Calls
CreateRequiredRecords();
// Make an update request to the Account entity to be tracked by auditing.
var newAccount = new Account();
newAccount.AccountId = _newAccountId;
newAccount.AccountNumber = "1-A";
newAccount.AccountCategoryCode = new OptionSetValue(
(int)AccountAccountCategoryCode.PreferredCustomer);
newAccount.Telephone1 = "555-555-5555";
_serviceProxy.Update(newAccount);
Console.WriteLine("Created an account and made updates which should be captured by auditing.");
#endregion Make Audited Service Calls
#region Revert auditing
// Set the organization and account auditing flags back to the old values
if (!organizationAuditingFlag || !userAccessAuditingFlag)
{
// Only revert them if they were actually changed to begin with.
org.IsAuditEnabled = organizationAuditingFlag;
org.IsUserAccessAuditEnabled = userAccessAuditingFlag;
_serviceProxy.Update(org);
Console.WriteLine("Reverted organization and user access auditing to their previous values.");
}
else
{
Console.WriteLine("Auditing was enabled before the sample began, so no auditing settings were reverted.");
}
// Revert the account entity auditing.
EnableEntityAuditing(Account.EntityLogicalName, oldAccountAuditing);
#endregion Revert auditing
#region Show Audited Records
// Select all columns for convenience.
var query = new QueryExpression(Audit.EntityLogicalName)
{
ColumnSet = new ColumnSet(true),
//.........这里部分代码省略.........
示例9: Run
/// <summary>
/// This method connects to the Organization service using an impersonated user
/// credential. Afterwards, basic create, retrieve, update, and delete entity
/// operations are performed as the impersonated user.
/// </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
{
//<snippetImpersonateWithOnBehalfOfPrivilege1>
//<snippetImpersonateWithOnBehalfOfPrivilege2>
// Connect to the Organization service.
// The using statement ensures 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();
// Retrieve the system user ID of the user to impersonate.
OrganizationServiceContext orgContext = new OrganizationServiceContext(_serviceProxy);
_userId = (from user in orgContext.CreateQuery<SystemUser>()
where user.FullName == "Kevin Cook"
select user.SystemUserId.Value).FirstOrDefault();
// To impersonate another user, set the OrganizationServiceProxy.CallerId
// property to the ID of the other user.
_serviceProxy.CallerId = _userId;
// Instantiate an account object.
// See the Entity Metadata topic in the SDK documentation to determine
// which attributes must be set for each entity.
Account account = new Account { Name = "Fourth Coffee" };
// Create an account record named Fourth Coffee.
_accountId = _serviceProxy.Create(account);
Console.Write("{0} {1} created, ", account.LogicalName, account.Name);
//</snippetImpersonateWithOnBehalfOfPrivilege2>
// Retrieve the account containing several of its attributes.
// CreatedBy should reference the impersonated SystemUser.
// CreatedOnBehalfBy should reference the running SystemUser.
ColumnSet cols = new ColumnSet(
"name",
"createdby",
"createdonbehalfby",
"address1_postalcode",
"lastusedincampaign");
Account retrievedAccount =
(Account)_serviceProxy.Retrieve(Account.EntityLogicalName,
_accountId, cols);
Console.Write("retrieved, ");
// Update the postal code attribute.
retrievedAccount.Address1_PostalCode = "98052";
// The address 2 postal code was set accidentally, so set it to null.
retrievedAccount.Address2_PostalCode = null;
// Shows use of a Money value.
retrievedAccount.Revenue = new Money(5000000);
// Shows use of a boolean value.
retrievedAccount.CreditOnHold = false;
// Update the account record.
_serviceProxy.Update(retrievedAccount);
Console.Write("updated, ");
// Delete the account record.
_serviceProxy.Delete(Account.EntityLogicalName, _accountId);
Console.WriteLine("and deleted.");
DeleteRequiredRecords(promptforDelete);
}
//</snippetImpersonateWithOnBehalfOfPrivilege1>
}
// 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: Run
/// <summary>
/// Create, Retrieve, Update and Delete an e-mail attachment.
/// <param name="serverConfig">Contains server connection information.</param>
/// <param name="promptforDelete">When True, the user will be prompted to delete all
/// created entities.</param>
/// </summary>
public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
{
try
{
// Connect to the Organization service.
// The using statement assures that the service proxy will be properly disposed.
using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
{
// This statement is required to enable early-bound type support.
_serviceProxy.EnableProxyTypes();
CreateRequiredRecords();
//<snippetCRUDEmailAttachments1>
// Create three e-mail attachments
for (int i = 0; i < 3; i++)
{
ActivityMimeAttachment _sampleAttachment = new ActivityMimeAttachment
{
ObjectId = new EntityReference(Email.EntityLogicalName, _emailId),
ObjectTypeCode = Email.EntityLogicalName,
Subject = String.Format("Sample Attachment {0}", i),
Body = System.Convert.ToBase64String(
new ASCIIEncoding().GetBytes("Example Attachment")),
FileName = String.Format("ExampleAttachment{0}.txt", i)
};
_emailAttachmentId[i] = _serviceProxy.Create(_sampleAttachment);
}
Console.WriteLine("Created three e-mail attachments for the e-mail activity.");
// Retrieve an attachment including its id, subject, filename and body.
ActivityMimeAttachment _singleAttachment =
(ActivityMimeAttachment)_serviceProxy.Retrieve(
ActivityMimeAttachment.EntityLogicalName,
_emailAttachmentId[0],
new ColumnSet("activitymimeattachmentid",
"subject",
"filename",
"body"));
Console.WriteLine("Retrieved an email attachment, {0}.", _singleAttachment.FileName);
// Update attachment
_singleAttachment.FileName = "ExampleAttachmentUpdated.txt";
_serviceProxy.Update(_singleAttachment);
Console.WriteLine("Updated the retrieved e-mail attachment to {0}.", _singleAttachment.FileName);
// Retrieve all attachments associated with the email activity.
QueryExpression _attachmentQuery = new QueryExpression
{
EntityName = ActivityMimeAttachment.EntityLogicalName,
ColumnSet = new ColumnSet("activitymimeattachmentid"),
Criteria = new FilterExpression
{
Conditions =
{
new ConditionExpression
{
AttributeName = "objectid",
Operator = ConditionOperator.Equal,
Values = {_emailId}
},
new ConditionExpression
{
AttributeName = "objecttypecode",
Operator = ConditionOperator.Equal,
Values = {Email.EntityLogicalName}
}
}
}
};
EntityCollection results = _serviceProxy.RetrieveMultiple(
_attachmentQuery);
Console.WriteLine("Retrieved all the e-mail attachments.");
//</snippetCRUDEmailAttachments1>
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;
}
}
示例11: Run
//.........这里部分代码省略.........
</Chart>
";
// Set the data XML string.
string dataXml = @"
<datadefinition>
<fetchcollection>
<fetch mapping='logical' count='10'
aggregate='true'>
<entity name='opportunity'>
<attribute name='actualvalue_base'
aggregate='sum'
alias='sum_actualvalue_base' />
<attribute name='stepname' groupby='true'
alias='stepname' />
<order alias='stepname' descending='false'/>
</entity>
</fetch>
</fetchcollection>
<categorycollection>
<category>
<measurecollection>
<measure alias='sum_actualvalue_base'/>
</measurecollection>
</category>
</categorycollection>
</datadefinition>
";
//<snippetCRUDVisualization2>
// Create the visualization entity instance.
SavedQueryVisualization newOrgOwnedVisualization = new SavedQueryVisualization
{
Name = "Sample Visualization",
Description = "Sample organization-owned visualization.",
PresentationDescription = presentationXml,
DataDescription = dataXml,
PrimaryEntityTypeCode = Opportunity.EntityLogicalName,
IsDefault = false
};
_orgOwnedVisualizationId = _serviceProxy.Create(newOrgOwnedVisualization);
//</snippetCRUDVisualization2>
Console.WriteLine("Created {0}.", newOrgOwnedVisualization.Name);
//</snippetCRUDVisualization1>
// Retrieve the visualization
SavedQueryVisualization retrievedOrgOwnedVisualization = (SavedQueryVisualization)_serviceProxy.Retrieve(SavedQueryVisualization.EntityLogicalName, _orgOwnedVisualizationId, new ColumnSet(true));
Console.WriteLine("Retrieved the visualization.");
// Update the retrieved visualization
// 1. Update the name.
// 2. Update the data description string.
string newDataXml = @"<datadefinition>
<fetchcollection>
<fetch mapping='logical' count='10'
aggregate='true'>
<entity name='opportunity'>
<attribute name='estimatedvalue_base'
aggregate='sum'
alias='sum_estimatedvalue_base' />
<attribute name='name'
groupby='true'
alias='name' />
<order alias='name'
descending='false'/>
</entity>
</fetch>
</fetchcollection>
<categorycollection>
<category>
<measurecollection>
<measure alias='sum_estimatedvalue_base'/>
</measurecollection>
</category>
</categorycollection>
</datadefinition>";
retrievedOrgOwnedVisualization.Name = "Updated Sample Visualization";
retrievedOrgOwnedVisualization.DataDescription = newDataXml;
_serviceProxy.Update(retrievedOrgOwnedVisualization);
// Publish the changes to the solution. This step is only required
// for organization-owned visualizations.
PublishAllXmlRequest updateRequest = new PublishAllXmlRequest();
_serviceProxy.Execute(updateRequest);
Console.WriteLine("Updated the visualization.");
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;
}
}
示例12: Run
/// <summary>
/// This method first connects to the Organization service. Afterwards,
/// create, retrieve, update, and delete operations are performed on the
/// SharePoint location records.
/// </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
{
//<snippetCRUDSharePointLocationRecords1>
// 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();
//<snippetCRUDSharePointLocationRecords2>
// Instantiate a SharePoint site object.
// See the Entity Metadata topic in the SDK documentation to determine
// which attributes must be set for each entity.
SharePointSite spSite = new SharePointSite
{
Name = "Sample SharePoint Site",
Description = "Sample SharePoint Site Location record",
// TODO: Change this URL to a valid SharePoint URL.
AbsoluteURL = "http://www.example.com",
};
// Create a SharePoint site record named Sample SharePoint Site.
_spSiteId = _serviceProxy.Create(spSite);
//</snippetCRUDSharePointLocationRecords2>
Console.WriteLine("{0} created.", spSite.Name);
//<snippetCRUDSharePointLocationRecords3>
// Instantiate a SharePoint document location object.
// See the Entity Metadata topic in the SDK documentation to determine
// which attributes must be set for each entity.
SharePointDocumentLocation spDocLoc = new SharePointDocumentLocation
{
Name = "Sample SharePoint Document Location",
Description = "Sample SharePoint Document Location record",
// Set the Sample SharePoint Site created earlier as the parent site.
ParentSiteOrLocation = new EntityReference(SharePointSite.EntityLogicalName, _spSiteId),
RelativeUrl = "spdocloc",
// Associate this document location instance with the Fourth Coffee
// sample account record.
RegardingObjectId = new EntityReference(Account.EntityLogicalName, _account1Id)
};
// Create a SharePoint document location record named Sample SharePoint Document Location.
_spDocLocId = _serviceProxy.Create(spDocLoc);
//</snippetCRUDSharePointLocationRecords3>
Console.WriteLine("{0} created.", spDocLoc.Name);
// Retrieve the SharePoint site and SharePoint document location containing several of its attributes.
ColumnSet colsSpSite = new ColumnSet("name", "absoluteurl");
SharePointSite retrievedSpSite = (SharePointSite)_serviceProxy.Retrieve(SharePointSite.EntityLogicalName, _spSiteId, colsSpSite);
ColumnSet colsSpDocLoc = new ColumnSet("name", "regardingobjectid");
SharePointDocumentLocation retrievedSpDocLoc = (SharePointDocumentLocation)_serviceProxy.Retrieve(SharePointDocumentLocation.EntityLogicalName, _spDocLocId, colsSpDocLoc);
Console.Write("Retrieved,");
// Update the URL of the SharePoint site.
// TODO: Change this URL to a valid SharePoint URL.
retrievedSpSite.AbsoluteURL = "http://www.example.net";
_serviceProxy.Update(retrievedSpSite);
// Update the SharePoint document location to associate it with the
// Northwind Traders sample account.
retrievedSpDocLoc.RegardingObjectId = new EntityReference(Account.EntityLogicalName,_account2Id);
_serviceProxy.Update(retrievedSpDocLoc);
Console.WriteLine(" and updated the records.");
DeleteRequiredRecords(promptforDelete);
}
//</snippetCRUDSharePointLocationRecords1>
}
// 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>
/// This method first connects to the Organization service. Afterwards,
/// create, retrieve, update, and delete operations are performed on a
/// dialog process.
/// </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
{
//<snippetCRUDDialog1>
// 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();
// Define an anonymous type to define the possible values for
// workflow category
var WorkflowCategory = new
{
Workflow = 0,
Dialog = 1
};
// Instantiate a Workflow object.
// See the Entity Metadata topic in the SDK documentation to determine
// which attributes must be set for each entity.
Workflow sampleDialog = new Workflow
{
Category = new OptionSetValue((int)WorkflowCategory.Dialog),
Name = "Sample Dialog: Call Categorization",
PrimaryEntity = PhoneCall.EntityLogicalName,
//Language code for U.S. English
LanguageCode = 1033,
Xaml = File.ReadAllText(pathToXAML)
};
// Create a dialog record.
_dialogId = _serviceProxy.Create(sampleDialog);
Console.Write("{0} created,", sampleDialog.Name);
// Activate the dialog.
SetStateRequest activateRequest = new SetStateRequest
{
EntityMoniker = new EntityReference(Workflow.EntityLogicalName, _dialogId),
State = new OptionSetValue((int)WorkflowState.Activated),
Status = new OptionSetValue(2)
};
_serviceProxy.Execute(activateRequest);
Console.WriteLine(" and activated.");
// Retrieve the dialog containing several of its attributes.
ColumnSet cols = new ColumnSet("name", "statecode", "statuscode");
Workflow retrievedDialog = (Workflow)_serviceProxy.Retrieve(Workflow.EntityLogicalName, _dialogId, cols);
Console.Write("Retrieved,");
// Update the dialog.
// Deactivate the dialog before you can update it.
SetStateRequest deactivateRequest = new SetStateRequest
{
EntityMoniker = new EntityReference(Workflow.EntityLogicalName, _dialogId),
State = new OptionSetValue((int)WorkflowState.Draft),
Status = new OptionSetValue(1)
};
_serviceProxy.Execute(deactivateRequest);
// Retrieve the dialog record again to get the unpublished
// instance in order to update.
Workflow retrievedDialogDeactivated = (Workflow)_serviceProxy.Retrieve(Workflow.EntityLogicalName, _dialogId, cols);
// Update the dialog.
retrievedDialogDeactivated.Name = "Updated Dialog: Call Categorization";
_serviceProxy.Update(retrievedDialogDeactivated);
Console.Write(" updated,");
// Activate the dialog.
SetStateRequest updateActivateRequest = new SetStateRequest
{
EntityMoniker = new EntityReference(Workflow.EntityLogicalName, _dialogId),
State = new OptionSetValue((int)WorkflowState.Activated),
Status = new OptionSetValue(2)
};
_serviceProxy.Execute(updateActivateRequest);
Console.WriteLine(" and activated again.");
DeleteRequiredRecords(promptforDelete);
}
//</snippetCRUDDialog1>
}
//.........这里部分代码省略.........
示例14: Run
//.........这里部分代码省略.........
ServiceContext svcContext = new ServiceContext(_service);
var accounts = from a in svcContext.AccountSet
select new Account
{
Name = a.Name,
Address1_County = a.Address1_County
};
System.Console.WriteLine("List all accounts in CRM");
System.Console.WriteLine("========================");
foreach (var a in accounts)
{
System.Console.WriteLine(a.Name + " " + a.Address1_County);
}
//</snippetCreateALinqQuery1>
System.Console.WriteLine();
System.Console.WriteLine("<End of Listing>");
System.Console.WriteLine();
var queryContacts = from c in svcContext.ContactSet
select new Contact
{
FirstName = c.FirstName,
LastName = c.LastName,
Address1_City = c.Address1_City
};
System.Console.WriteLine("List all contacts in CRM");
System.Console.WriteLine("=====================================");
foreach (var c in queryContacts)
{
System.Console.WriteLine(c.FirstName + " " +
c.LastName + " " + c.Address1_City);
}
System.Console.WriteLine();
System.Console.WriteLine("<End of Listing>");
System.Console.WriteLine();
// Display information about the logged on user.
Guid userid = ((WhoAmIResponse)_serviceProxy.Execute(new WhoAmIRequest())).UserId;
SystemUser systemUser = (SystemUser)_serviceProxy.Retrieve("systemuser", userid,
new ColumnSet(new string[] {"firstname", "lastname"}));
Console.WriteLine("Logged on user is {0} {1}.", systemUser.FirstName, systemUser.LastName);
// Retrieve the version of Microsoft Dynamics CRM.
RetrieveVersionRequest versionRequest = new RetrieveVersionRequest();
RetrieveVersionResponse versionResponse =
(RetrieveVersionResponse)_serviceProxy.Execute(versionRequest);
Console.WriteLine("Microsoft Dynamics CRM version {0}.", versionResponse.Version);
//<snippetCRUDOperations2>
// Instantiate an account object. Note the use of the option set enumerations defined in OptionSets.cs.
// See the Entity Metadata topic in the SDK documentation to determine
// which attributes must be set for each entity.
Account account = new Account { Name = "Fourth Coffee" };
account.AccountCategoryCode = new OptionSetValue((int)AccountAccountCategoryCode.PreferredCustomer);
account.CustomerTypeCode = new OptionSetValue((int)AccountCustomerTypeCode.Investor);
// Create an account record named Fourth Coffee.
_accountId = _serviceProxy.Create(account);
//</snippetCRUDOperations2>
Console.Write("{0} {1} created, ", account.LogicalName, account.Name);
// Retrieve the account containing several of its attributes.
ColumnSet cols = new ColumnSet(
new String[] { "name", "address1_postalcode", "lastusedincampaign" });
Account retrievedAccount = (Account)_serviceProxy.Retrieve("account", _accountId, cols);
Console.Write("retrieved, ");
// Update the postal code attribute.
retrievedAccount.Address1_PostalCode = "98052";
// The address 2 postal code was set accidentally, so set it to null.
retrievedAccount.Address2_PostalCode = null;
// Shows use of a Money value.
retrievedAccount.Revenue = new Money(5000000);
// Shows use of a Boolean value.
retrievedAccount.CreditOnHold = false;
// Update the account record.
_serviceProxy.Update(retrievedAccount);
Console.WriteLine("and updated.");
DeleteRequiredRecords(promptforDelete);
}
//</snippetCRUDOperations1>
}
// 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
//.........这里部分代码省略.........
<EnableJumpBar>false</EnableJumpBar>
<ChartGridMode>Chart</ChartGridMode>
<VisualizationId>{2}</VisualizationId>
<EnableChartPicker>false</EnableChartPicker>
<RecordsPerPage>10</RecordsPerPage>
</parameters>
</control>
</cell>
<cell colspan='1' rowspan='10'
showlabel='false'>
<labels>
<label description='Top Opportunities - 2'
languagecode='{0}' />
</labels>
<control id='TopOpportunities2'
classid='{{E7A81278-8635-4d9e-8D4D-59480B391C5B}}'>
<parameters>
<ViewId>{1}</ViewId>
<IsUserView>false</IsUserView>
<RelationshipName />
<TargetEntityType>opportunity</TargetEntityType>
<AutoExpand>Fixed</AutoExpand>
<EnableQuickFind>false</EnableQuickFind>
<EnableViewPicker>false</EnableViewPicker>
<EnableJumpBar>false</EnableJumpBar>
<ChartGridMode>Grid</ChartGridMode>
<VisualizationId>{2}</VisualizationId>
<EnableChartPicker>false</EnableChartPicker>
<RecordsPerPage>10</RecordsPerPage>
</parameters>
</control>
</cell>
</row>
<row />
<row />
<row />
<row />
<row />
<row />
<row />
<row />
<row />
</rows>
</section>
</sections>
</column>
</columns>
</tab>
</tabs>
</form>",
languageCode,
defaultOpportunityQuery.SavedQueryId.Value.ToString("B"),
visualization.SavedQueryVisualizationId.Value.ToString("B")),
IsDefault = false
};
_dashboardId = _serviceProxy.Create(dashboard);
//</snippetCRUDDashboards2>
Console.WriteLine("Created {0}.", dashboard.Name);
//Now we will retrieve the dashboard.
SystemForm retrievedDashboard = (SystemForm)_serviceProxy.Retrieve(SystemForm.EntityLogicalName, _dashboardId, new ColumnSet(true));
Console.WriteLine("Retrieved the dashboard.");
// Update the retrieved dashboard. Enable the chart picker on the chart.
XDocument xDocument = XDocument.Parse(retrievedDashboard.FormXml);
var chartPicker = (from control in xDocument.Descendants("control")
where control.Attribute("id").Value == "TopOpportunities"
select control.Descendants("EnableChartPicker").First()
).First();
chartPicker.Value = "true";
//Now we place the updated Xml back into the dashboard, and update it.
retrievedDashboard.FormXml = xDocument.ToString();
_serviceProxy.Update(retrievedDashboard);
// Publish the dashboard changes to the solution.
// This is only required for organization-owned dashboards.
PublishXmlRequest updateRequest = new PublishXmlRequest
{
ParameterXml = @"<dashboard>_dashboardId</dashboard>"
};
_serviceProxy.Execute(updateRequest);
Console.WriteLine("Updated the dashboard.");
DeleteRequiredRecords(promptForDelete);
//</snippetCRUDDashboards1>
}
}
// 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;
}
}