本文整理汇总了C#中OrganizationServiceProxy.Retrieve方法的典型用法代码示例。如果您正苦于以下问题:C# OrganizationServiceProxy.Retrieve方法的具体用法?C# OrganizationServiceProxy.Retrieve怎么用?C# OrganizationServiceProxy.Retrieve使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类OrganizationServiceProxy
的用法示例。
在下文中一共展示了OrganizationServiceProxy.Retrieve方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Run
/// <summary>
/// Create and configure the organization service proxy.
/// Initiate the method to create any data that this sample requires.
/// End 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();
//<snippetEndRecurringAppointmentSeries1>
// Retrieve a recurring appointment series
RecurringAppointmentMaster retrievedRecurringAppointmentSeries = (RecurringAppointmentMaster)_serviceProxy.Retrieve(RecurringAppointmentMaster.EntityLogicalName, _recurringAppointmentMasterId, new ColumnSet(true));
// Use the DeleteOpenInstances message to end the series to the
// last occurring past instance date w.r.t. the series end date
// (i.e., 20 days from today). Effectively, that means that the
// series will end after the third instance (day 14) as this
// instance is the last occuring past instance w.r.t the specified
// series end date (20 days from today).
// Also specify that the state of past instances (w.r.t. the series
// end date) be set to 'completed'.
DeleteOpenInstancesRequest endAppointmentSeries = new DeleteOpenInstancesRequest
{
Target = retrievedRecurringAppointmentSeries,
SeriesEndDate = DateTime.Today.AddDays(20),
StateOfPastInstances = (int)AppointmentState.Completed
};
_serviceProxy.Execute(endAppointmentSeries);
Console.WriteLine("The recurring appointment series has been ended after the third occurrence.");
//</snippetEndRecurringAppointmentSeries1>
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>
/// This method first connects to the Organization service. Afterwards, it
/// creates/retrieves a system user, and
/// updates the system user to disable/enable the user account.
/// Note: Creating a user is only supported
/// in an on-premises/active directory environment.
/// </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
{
//<snippetDisableOrEnableUser1>
// 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))
{
_serviceProxy.EnableProxyTypes();
CreateRequiredRecords();
// Retrieve a user.
SystemUser user = _serviceProxy.Retrieve(SystemUser.EntityLogicalName,
_userId, new ColumnSet(new String [] {"systemuserid", "firstname", "lastname"})).ToEntity<SystemUser>();
if (user != null)
{
Console.WriteLine("{1} {0} user account is retrieved.", user.LastName, user.FirstName);
SetStateRequest request = new SetStateRequest() {
EntityMoniker = user.ToEntityReference(),
// Sets the user to disabled.
State = new OptionSetValue(1),
// Required by request but always valued at -1 in this context.
Status = new OptionSetValue(-1)
/*
//Sets the user to enabled.
State = new OptionSetValue(0),
// Required by request but always valued at -1 in this context.
Status = new OptionSetValue(-1)
*/
};
_serviceProxy.Execute(request);
Console.WriteLine("User account is disabled.");
}
DeleteRequiredRecords(promptforDelete);
}
//</snippetDisableOrEnableUser1>
}
// 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>
/// Demonstrates how to programmatically create a Workflow from an existing
/// Process Template.
/// </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
{
//<snippetCreateProcessFromTemplate1>
// 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();
OrganizationServiceContext _orgContext = new OrganizationServiceContext(_serviceProxy);
CreateRequiredRecords();
CreateWorkflowFromTemplateRequest request = new CreateWorkflowFromTemplateRequest()
{
WorkflowName = "Workflow From Template",
WorkflowTemplateId = _processTemplateId
};
// Execute request.
CreateWorkflowFromTemplateResponse response = (CreateWorkflowFromTemplateResponse)_serviceProxy.Execute(request);
_processId = response.Id;
// Verify success.
// Retrieve the name of the workflow.
ColumnSet cols = new ColumnSet("name");
Workflow newWorkflow = (Workflow)_serviceProxy.Retrieve(Workflow.EntityLogicalName, response.Id, cols);
if (newWorkflow.Name == "Workflow From Template")
{
Console.WriteLine("Created {0}.", request.WorkflowName);
}
DeleteRequiredRecords(promptforDelete);
}
//</snippetCreateProcessFromTemplate1>
}
// 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: Run
/// <summary>
/// Convert a fax to a task.
/// <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();
// Call the method to create any data that this sample requires.
CreateRequiredRecords();
//<snippetConvertFaxToTask1>
// Retrieve the fax.
Fax retrievedFax = (Fax)_serviceProxy.Retrieve(Fax.EntityLogicalName, _faxId, new ColumnSet(true));
// Create a task.
Task task = new Task()
{
Subject = "Follow Up: " + retrievedFax.Subject,
ScheduledEnd = retrievedFax.CreatedOn.Value.AddDays(7),
};
_taskId = _serviceProxy.Create(task);
// Verify that the task has been created
if (_taskId != Guid.Empty)
{
Console.WriteLine("Created a task for the fax: '{0}'.", task.Subject);
}
//</snippetConvertFaxToTask1>
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;
}
}
示例5: Run
/// <summary>
/// Create and configure the organization service proxy.
/// Initiate the method to create any data that this sample requires.
/// Share a queue to the team.
/// Optionally delete any entity records that were created for this sample.
/// <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();
////<snippetAddPrincipalToQueue1>
ColumnSet columnSet = new ColumnSet("name");
Entity team = _serviceProxy.Retrieve(Team.EntityLogicalName, _teamId, columnSet);
AddPrincipalToQueueRequest addPrincipalToQueueRequest = new AddPrincipalToQueueRequest
{
Principal = team,
QueueId = _queueId
};
_serviceProxy.Execute(addPrincipalToQueueRequest);
//</snippetAddPrincipalToQueue1>
Console.WriteLine("The team has been added to the queue.");
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: ProgressReport
private static void ProgressReport(ServerConnection.Configuration serverConfig, object importId)
{
try
{
using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
{
var job = _serviceProxy.Retrieve("importjob", (Guid)importId, new ColumnSet("solutionname", "progress"));
decimal progress = Convert.ToDecimal(job["progress"]);
Console.WriteLine("{0:N0}%", progress);
if (progress == 100) { return; }
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Thread.Sleep(2000);
ProgressReport(serverConfig, importId);
}
示例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 method first connects to the Organization service. Afterwards,
/// an annotation is created, uploaded, then finally downloaded.
/// </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
{
//<snippetUploadAndDownloadAttachment1>
// 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();
#region Create and Upload annotation attachment
// Instantiate an Annotation object.
// See the Entity Metadata topic in the SDK documentation to determine
// which attributes must be set for each entity.
Annotation setupAnnotation = new Annotation()
{
Subject = "Example Annotation",
FileName = "ExampleAnnotationAttachment.txt",
DocumentBody = Convert.ToBase64String(
new UnicodeEncoding().GetBytes("Sample Annotation Text")),
MimeType = "text/plain"
};
// Create the Annotation object.
_annotationId = _serviceProxy.Create(setupAnnotation);
Console.Write("{0} created with an attachment", setupAnnotation.Subject);
#endregion Create and Upload annotation attachment
#region Download attachment from annotation record
// Define columns to retrieve from the annotation record.
ColumnSet cols = new ColumnSet("filename", "documentbody");
// Retrieve the annotation record.
Annotation retrievedAnnotation =
(Annotation)_serviceProxy.Retrieve("annotation", _annotationId, cols);
Console.WriteLine(", and retrieved.");
_fileName = retrievedAnnotation.FileName;
// Download the attachment in the current execution folder.
using (FileStream fileStream = new FileStream(retrievedAnnotation.FileName, FileMode.OpenOrCreate))
{
byte[] fileContent = Convert.FromBase64String(retrievedAnnotation.DocumentBody);
fileStream.Write(fileContent, 0, fileContent.Length);
}
Console.WriteLine("Attachment downloaded.");
#endregion Download attachment from annotation record
DeleteRequiredRecords(promptforDelete);
}
//</snippetUploadAndDownloadAttachment1>
}
// 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: WaitForAsyncJobCompletion
/// <summary>
/// Waits for the async job to complete.
/// </summary>
/// <param name="asyncJobId"></param>
public static void WaitForAsyncJobCompletion(OrganizationServiceProxy serviceProxy, Guid asyncJobId)
{
ColumnSet cs = new ColumnSet("statecode", "statuscode");
AsyncOperation asyncjob =
(AsyncOperation)serviceProxy.Retrieve("asyncoperation", asyncJobId, cs);
int retryCount = 100;
while (asyncjob.StateCode.Value != AsyncOperationState.Completed && retryCount > 0)
{
asyncjob = (AsyncOperation)serviceProxy.Retrieve("asyncoperation", asyncJobId, cs);
System.Threading.Thread.Sleep(2000);
retryCount--;
Console.WriteLine("Async operation state is " + asyncjob.StateCode.Value.ToString());
}
Console.WriteLine("Async job is " + asyncjob.StateCode.Value.ToString() + " with status " + ((asyncoperation_statuscode)asyncjob.StatusCode.Value).ToString());
}
示例10: 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;
}
}
示例11: Run
/// <summary>
/// This method shows how to merge two entity records with the Merge message.
/// </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))
{
// This statement is required to enable early-bound type support.
_serviceProxy.EnableProxyTypes();
//Create the Contact and Incident required for this sample.
CreateRequiredRecords();
//<snippetMerge1>
// Create the target for the request.
EntityReference target = new EntityReference();
// Id is the GUID of the account that is being merged into.
// LogicalName is the type of the entity being merged to, as a string
target.Id = _account1Id;
target.LogicalName = Account.EntityLogicalName;
// Create the request.
MergeRequest merge = new MergeRequest();
// SubordinateId is the GUID of the account merging.
merge.SubordinateId = _account2Id;
merge.Target = target;
merge.PerformParentingChecks = false;
Console.WriteLine("\nMerging account2 into account1 and adding " +
"\"test\" as Address 1 Line 1");
// Create another account to hold new data to merge into the entity.
// If you use the subordinate account object, its data will be merged.
Account updateContent = new Account();
updateContent.Address1_Line1 = "test";
// Set the content you want updated on the merged account
merge.UpdateContent = updateContent;
// Execute the request.
MergeResponse merged = (MergeResponse)_serviceProxy.Execute(merge);
//</snippetMerge1>
Account mergeeAccount =
(Account)_serviceProxy.Retrieve(Account.EntityLogicalName,
_account2Id, new ColumnSet(allColumns:true));
if(mergeeAccount.Merged == true)
{
Account mergedAccount =
(Account)_serviceProxy.Retrieve(Account.EntityLogicalName,
_account1Id, new ColumnSet(allColumns: true));
Console.WriteLine("\nAccounts merged successfully into account1");
Console.WriteLine(" Name: {0}", mergedAccount.Name);
Console.WriteLine(" Description: {0}", mergedAccount.Description);
Console.WriteLine(" Number of Employees: {0}",
mergedAccount.NumberOfEmployees);
Console.WriteLine(" Address 1 Line 1: {0}",
mergedAccount.Address1_Line1);
}
DeleteRequiredRecords(promptForDelete);
}
}
示例12: RetrieveSystemUser
/// <summary>
/// Retrieves the requested SystemUser record. If the record does not exist, a new
/// Microsoft Dynamics CRM SystemUser record is created and an associated Active
/// Directory account is created, if it doesn't currently exist.
/// </summary>
/// <param name="userName">The username field as set in Microsoft Dynamics CRM</param>
/// <param name="firstName">The first name of the system user to be retrieved</param>
/// <param name="lastName">The last name of the system user to be retrieved</param>
/// <param name="roleStr">The string representing the Microsoft Dynamics CRM security
/// role for the user</param>
/// <param name="serviceProxy">The OrganizationServiceProxy object to your Microsoft
/// Dynamics CRM environment</param>
/// <param name="ldapPath">The LDAP path for your network - you can either call
/// ConsolePromptForLDAPPath() to prompt the user or provide a value in code</param>
/// <returns></returns>
public static Guid RetrieveSystemUser(String userName, String firstName,
String lastName, String roleStr, OrganizationServiceProxy serviceProxy,
ref String ldapPath)
{
String domain;
Guid userId = Guid.Empty;
if (serviceProxy == null)
throw new ArgumentNullException("serviceProxy");
if (String.IsNullOrWhiteSpace(userName))
throw new ArgumentNullException("UserName");
if (String.IsNullOrWhiteSpace(firstName))
throw new ArgumentNullException("FirstName");
if (String.IsNullOrWhiteSpace(lastName))
throw new ArgumentNullException("LastName");
// Obtain the current user's information.
WhoAmIRequest who = new WhoAmIRequest();
WhoAmIResponse whoResp = (WhoAmIResponse)serviceProxy.Execute(who);
Guid currentUserId = whoResp.UserId;
SystemUser currentUser =
serviceProxy.Retrieve(SystemUser.EntityLogicalName, currentUserId, new ColumnSet("domainname")).ToEntity<SystemUser>();
// Extract the domain and create the LDAP object.
String[] userPath = currentUser.DomainName.Split(new char[] { '\\' });
if (userPath.Length > 1)
domain = userPath[0] + "\\";
else
domain = String.Empty;
SystemUser existingUser = GetUserIdIfExist(serviceProxy, domain, userName, firstName, lastName);
if (existingUser != null)
{
userId = existingUser.SystemUserId.Value;
if (!String.IsNullOrWhiteSpace(roleStr))
{
// Check to make sure the user is assigned the correct role.
Role role = RetrieveRoleByName(serviceProxy, roleStr);
// Associate the user with the role when needed.
if (!UserInRole(serviceProxy, userId, role.Id))
{
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);
}
}
}
else
{
// Create the system user in Microsoft Dynamics CRM if the user doesn't
// already exist.
userId = CreateSystemUser(userName, firstName, lastName, domain,
roleStr, serviceProxy, ref ldapPath);
}
return userId;
}
示例13: Run
/// <summary>
/// This method first connects to the Outlook service. Afterwards,
/// client information is retrieved and the client state is changed.
/// </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();
//<snippetRetrieveDataFilters1>
// Create and Retrieve Offline Filter
// In your Outlook client, this will appear in the System Filters tab
// under File | CRM | Synchronize | Outlook Filters.
Console.Write("Creating offline filter");
String contactName = String.Format("offlineFilteredContact {0}",
DateTime.Now.ToLongTimeString());
String fetchXml = String.Format("<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\"><entity name=\"contact\"><attribute name=\"contactid\" /><filter type=\"and\">" +
"<condition attribute=\"ownerid\" operator=\"eq-userid\" /><condition attribute=\"description\" operator=\"eq\" value=\"{0}\" />" +
"<condition attribute=\"statecode\" operator=\"eq\" value=\"0\" /></filter></entity></fetch>", contactName);
SavedQuery filter = new SavedQuery();
filter.FetchXml = fetchXml;
filter.IsQuickFindQuery = false;
filter.QueryType = SavedQueryQueryType.OfflineFilters;
filter.ReturnedTypeCode = Contact.EntityLogicalName;
filter.Name = "ReadOnlyFilter_" + contactName;
filter.Description = "Sample offline filter for Contact entity";
_offlineFilter = _serviceProxy.Create(filter);
Console.WriteLine(" and retrieving offline filter");
SavedQuery result = (SavedQuery)_serviceProxy.Retrieve(
SavedQuery.EntityLogicalName,
_offlineFilter,
new ColumnSet("name", "description"));
Console.WriteLine("Name: {0}", result.Name);
Console.WriteLine("Description: {0}", result.Description);
Console.WriteLine();
// Create and Retrieve Offline Template
// In your Outlook client, this will appear in the User Filters tab
// under File | CRM | Synchronize | Outlook Filters.
Console.Write("Creating offline template");
String accountName = String.Format("offlineFilteredAccount {0}",
DateTime.Now.ToLongTimeString());
fetchXml = String.Format("<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\"><entity name=\"account\"><attribute name=\"accountid\" /><filter type=\"and\">" +
"<condition attribute=\"ownerid\" operator=\"eq-userid\" /><condition attribute=\"name\" operator=\"eq\" value=\"{0}\" />" +
"<condition attribute=\"statecode\" operator=\"eq\" value=\"0\" /></filter></entity></fetch>", accountName);
SavedQuery template = new SavedQuery();
template.FetchXml = fetchXml;
template.IsQuickFindQuery = false;
template.QueryType = SavedQueryQueryType.OfflineTemplate;
template.ReturnedTypeCode = Account.EntityLogicalName;
template.Name = "ReadOnlyFilter_" + accountName;
template.Description = "Sample offline template for Account entity";
_offlineTemplate = _serviceProxy.Create(template);
Console.WriteLine(" and retrieving offline template");
result = (SavedQuery)_serviceProxy.Retrieve(
SavedQuery.EntityLogicalName,
_offlineTemplate,
new ColumnSet("name", "description"));
Console.WriteLine("Name: {0}", result.Name);
Console.WriteLine("Description: {0}", result.Description);
Console.WriteLine();
//</snippetRetrieveDataFilters1>
//<snippetRetrieveDataFilters2>
// Call InstantiateFiltersRequest
Console.WriteLine("Retrieving user's ID and creating the template collection");
WhoAmIRequest whoAmI = new WhoAmIRequest();
Guid id = ((WhoAmIResponse)_serviceProxy.Execute(whoAmI)).UserId;
EntityReferenceCollection templates = new EntityReferenceCollection();
templates.Add(new EntityReference(
SavedQuery.EntityLogicalName,
_offlineTemplate));
Console.WriteLine("Activating the selected offline templates for this user");
InstantiateFiltersRequest request = new InstantiateFiltersRequest
{
UserId = id,
TemplateCollection = templates
};
InstantiateFiltersResponse response =
(InstantiateFiltersResponse)_serviceProxy.Execute(request);
Console.WriteLine();
//</snippetRetrieveDataFilters2>
//<snippetRetrieveDataFilters3>
// Call ResetUserFiltersRequest
//.........这里部分代码省略.........
示例14: Run
/// <summary>
/// Create and configure the organization service proxy.
/// Initiate the method to create any data that this sample requires.
/// Convert an appointment to a recurring appointment.
/// 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();
//<snippetConvertAnAppointmenttoRecurringAppointment1>
// Specify the recurrence information that needs to be added to the
// existing appointment.
// 1. Define an anonymous type to define the possible recurrence pattern values.
var RecurrencePatternTypes = new
{
Daily = 0,
Weekly = 1,
Monthly = 2,
Yearly = 3
};
// 2. 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
};
// 3. 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
};
// 4. Finally, use a recurring appointment master object to specify
// the recurrence information. Other appointment details such as
// 'subject' and 'location' are copied from the existing appointment
// to the recurring appointment master object.
RecurringAppointmentMaster newRecurringAppointmentInfo = new RecurringAppointmentMaster
{
StartTime = DateTime.Now.AddHours(2),
EndTime = DateTime.Now.AddHours(3),
RecurrencePatternType = new OptionSetValue(RecurrencePatternTypes.Weekly),
Interval = 1,
DaysOfWeekMask = DayOfWeek.Thursday,
PatternStartDate = DateTime.Today,
PatternEndType = new OptionSetValue(RecurrenceRulePatternEndType.Occurrences),
Occurrences = 5
};
// Use the AddRecurrence message to convert the existing appointment
// object to a recurring appointment master object. The existing
// appointment object is deleted thereafter.
AddRecurrenceRequest recurringInfoRequest = new AddRecurrenceRequest
{
Target = newRecurringAppointmentInfo,
AppointmentId = _appointmentId
};
AddRecurrenceResponse recurringInfoResponse = (AddRecurrenceResponse)_serviceProxy.Execute(recurringInfoRequest);
__recurringAppointmentMasterId = recurringInfoResponse.id;
// Verify that the newly created recurring appointment master has same 'subject'
// as the existing appointment.
RecurringAppointmentMaster retrievedMasterAppointment = (RecurringAppointmentMaster)_serviceProxy.Retrieve(RecurringAppointmentMaster.EntityLogicalName, __recurringAppointmentMasterId, new ColumnSet(true));
if (retrievedMasterAppointment.Subject == "Sample Appointment")
{
Console.WriteLine("Sample Appointment is converted to a recurring appointment.");
}
//.........这里部分代码省略.........
示例15: 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;
}
}