本文整理汇总了C#中OrganizationServiceProxy.Create方法的典型用法代码示例。如果您正苦于以下问题:C# OrganizationServiceProxy.Create方法的具体用法?C# OrganizationServiceProxy.Create怎么用?C# OrganizationServiceProxy.Create使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类OrganizationServiceProxy
的用法示例。
在下文中一共展示了OrganizationServiceProxy.Create方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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;
}
}
示例2: Run
/// <summary>
/// Create and configure the organization service proxy.
/// Initiate creating all entity records that this sample requires.
/// Create a bundle record.
/// Add products to a bundle.
/// 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 = ServerConnection.GetOrganizationProxy(serverConfig))
{
// This statement is required to enable early-bound type support.
_serviceProxy.EnableProxyTypes();
// Call the method to create any data that this sample requires.
CreateRequiredRecords();
//<snippetAddProductstoBundle1>
// Add products to a bundle
ProductAssociation newAssociation1 = new ProductAssociation
{
AssociatedProduct = new EntityReference(Product.EntityLogicalName, _product1Id),
ProductId = new EntityReference(Product.EntityLogicalName, _bundleId),
Quantity = new decimal(15),
ProductIsRequired = new OptionSetValue(0), // Adding this as an optional product
UoMId = new EntityReference(UoM.EntityLogicalName, unit.Id)
};
_product1AssociationId = _serviceProxy.Create(newAssociation1);
ProductAssociation newAssociation2 = new ProductAssociation
{
AssociatedProduct = new EntityReference(Product.EntityLogicalName, _product2Id),
ProductId = new EntityReference(Product.EntityLogicalName, _bundleId),
Quantity = new decimal(20),
ProductIsRequired = new OptionSetValue(1), // Adding this as a mandatory product
UoMId = new EntityReference(UoM.EntityLogicalName, unit.Id),
};
_product2AssociationId = _serviceProxy.Create(newAssociation2);
// Verify if the product association is created
if ((_product1AssociationId != null) && (_product1AssociationId != null))
{
Console.WriteLine("\nAdded both the products to the bundle");
}
//</snippetAddProductstoBundle1>
DeleteRequiredRecords(promptForDelete);
}
}
catch
{
// You can handle an exception here or pass it back to the calling method.
throw;
}
}
示例3: Run
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();
CreateRequiredRecords();
Console.WriteLine("=== Creating and Qualifying Leads ===");
// Create two leads.
var lead1 = new Lead
{
CompanyName = "A. Datum Corporation",
FirstName = "Henriette",
LastName = "Andersen",
Subject = "Sample Lead 1"
};
_lead1Id = _serviceProxy.Create(lead1);
NotifyEntityCreated(Lead.EntityLogicalName, _lead1Id);
var lead2 = new Lead
{
CompanyName = "Adventure Works",
FirstName = "Michael",
LastName = "Sullivan",
Subject = "Sample Lead 2"
};
_lead2Id = _serviceProxy.Create(lead2);
NotifyEntityCreated(Lead.EntityLogicalName, _lead2Id);
//<snippetWorkingWithLeads1>
// Qualify the first lead, creating an account and a contact from it, but
// not creating an opportunity.
var qualifyIntoAccountContactReq = new QualifyLeadRequest
{
CreateAccount = true,
CreateContact = true,
LeadId = new EntityReference(Lead.EntityLogicalName, _lead1Id),
Status = new OptionSetValue((int)lead_statuscode.Qualified)
};
var qualifyIntoAccountContactRes =
(QualifyLeadResponse)_serviceProxy.Execute(qualifyIntoAccountContactReq);
Console.WriteLine(" The first lead was qualified.");
//</snippetWorkingWithLeads1>
foreach (var entity in qualifyIntoAccountContactRes.CreatedEntities)
{
NotifyEntityCreated(entity.LogicalName, entity.Id);
if (entity.LogicalName == Account.EntityLogicalName)
{
_leadAccountId = entity.Id;
}
else if (entity.LogicalName == Contact.EntityLogicalName)
{
_contactId = entity.Id;
}
}
// Retrieve the organization's base currency ID for setting the
// transaction currency of the opportunity.
var query = new QueryExpression("organization");
query.ColumnSet = new ColumnSet("basecurrencyid");
var result = _serviceProxy.RetrieveMultiple(query);
var currencyId = (EntityReference)result.Entities[0]["basecurrencyid"];
// Qualify the second lead, creating an opportunity from it, and not
// creating an account or a contact. We use an existing account for the
// opportunity customer instead.
var qualifyIntoOpportunityReq = new QualifyLeadRequest
{
CreateOpportunity = true,
OpportunityCurrencyId = currencyId,
OpportunityCustomerId = new EntityReference(
Account.EntityLogicalName,
_accountId),
Status = new OptionSetValue((int)lead_statuscode.Qualified),
LeadId = new EntityReference(Lead.EntityLogicalName, _lead2Id)
};
var qualifyIntoOpportunityRes =
(QualifyLeadResponse)_serviceProxy.Execute(qualifyIntoOpportunityReq);
Console.WriteLine(" The second lead was qualified.");
foreach (var entity in qualifyIntoOpportunityRes.CreatedEntities)
{
NotifyEntityCreated(entity.LogicalName, entity.Id);
if (entity.LogicalName == Opportunity.EntityLogicalName)
{
_opportunityId = entity.Id;
}
}
DeleteRecords(promptforDelete);
}
}
示例4: Run
/// <summary>
/// This method first connects to the Organization service. Afterwards,
/// it creates a system user account with a given active directory 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
{
//<snippetCreateAUser1>
// 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 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);
Console.WriteLine("Created a system user {0} for '{1}, {2}'", userId, _lastName, _firstName);
}
//</snippetCreateAUser1>
}
// 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
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))
{
String ldapPath = String.Empty;
Guid businessUnitId;
// This statement is required to enable early-bound type support.
_serviceProxy.EnableProxyTypes();
// Call this method to create any data that this sample requires.
CreateRequiredRecords();
// Retrieve the sales people that will be added to the team.
salesPersons = SystemUserProvider.RetrieveSalespersons(_serviceProxy, ref ldapPath);
// Get the ID's of the current user and business unit.
var who = new WhoAmIRequest();
var whoResponse = (WhoAmIResponse)_serviceProxy.Execute(who);
_currentUserId = whoResponse.UserId;
businessUnitId = whoResponse.BusinessUnitId;
//<snippetCreateAndShareAccessTeam1>
// Create a access team.
var team = new Team
{
AdministratorId = new EntityReference(
"systemuser", _currentUserId),
Name = "UserAccess Test Team",
BusinessUnitId = new EntityReference(
"businessunit", businessUnitId),
TeamType = new OptionSetValue((int)TeamTeamType.Access),
};
_teamId = _serviceProxy.Create(team);
Console.WriteLine("Created an access team named '{0}'.", team.Name);
// Add two sales people to the access team.
var addToTeamRequest = new AddMembersTeamRequest
{
TeamId = _teamId,
MemberIds = new[] { salesPersons[0], salesPersons[1] }
};
_serviceProxy.Execute(addToTeamRequest);
Console.WriteLine("Added two sales people to the team.");
// Grant the team read/write access to an account.
var accountReference = new EntityReference(Account.EntityLogicalName, _accountId);
var teamReference = new EntityReference(Team.EntityLogicalName, _teamId);
var grantAccessRequest = new GrantAccessRequest
{
PrincipalAccess = new PrincipalAccess
{
AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess,
Principal = teamReference
},
Target = accountReference
};
_serviceProxy.Execute(grantAccessRequest);
Console.WriteLine("Granted read/write access on the account record to the team.");
//</snippetCreateAndShareAccessTeam1>
// Retrieve and display access information for the account.
RetrieveAndDisplayEntityAccess(accountReference);
// Display the account access for the team and its members.
var currentUserReference = new EntityReference(
SystemUser.EntityLogicalName, _currentUserId);
RetrieveAndDisplayPrincipalAccess(accountReference, currentUserReference,
"Current User");
var firstSalesPersonReference = new EntityReference(
SystemUser.EntityLogicalName, salesPersons[0]);
RetrieveAndDisplayPrincipalAccess(accountReference, firstSalesPersonReference,
"Sales Person");
var secondSalesPersonReference = new EntityReference(
SystemUser.EntityLogicalName, salesPersons[1]);
RetrieveAndDisplayPrincipalAccess(accountReference, secondSalesPersonReference,
"Sales Person");
// Delete all records created by this sample.
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: 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;
}
示例7: 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
//.........这里部分代码省略.........
示例8: Run
/// <summary>
/// Create a view.
/// Retrieve Views
/// Deactivate a view
/// </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>
/// <param name="promptForReactivate">When True, the user will be prompted to reactivate
/// a view that was deactivated.</param>
public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete, bool promptForReactivate)
{
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();
// Create the view.
//<snippetWorkWithViews1>
System.String layoutXml =
@"<grid name='resultset' object='3' jump='name' select='1'
preview='1' icon='1'>
<row name='result' id='opportunityid'>
<cell name='name' width='150' />
<cell name='customerid' width='150' />
<cell name='estimatedclosedate' width='150' />
<cell name='estimatedvalue' width='150' />
<cell name='closeprobability' width='150' />
<cell name='opportunityratingcode' width='150' />
<cell name='opportunitycustomeridcontactcontactid.emailaddress1'
width='150' disableSorting='1' />
</row>
</grid>";
System.String fetchXml =
@"<fetch version='1.0' output-format='xml-platform'
mapping='logical' distinct='false'>
<entity name='opportunity'>
<order attribute='estimatedvalue' descending='false' />
<filter type='and'>
<condition attribute='statecode' operator='eq'
value='0' />
</filter>
<attribute name='name' />
<attribute name='estimatedvalue' />
<attribute name='estimatedclosedate' />
<attribute name='customerid' />
<attribute name='opportunityratingcode' />
<attribute name='closeprobability' />
<link-entity alias='opportunitycustomeridcontactcontactid'
name='contact' from='contactid' to='customerid'
link-type='outer' visible='false'>
<attribute name='emailaddress1' />
</link-entity>
<attribute name='opportunityid' />
</entity>
</fetch>";
SavedQuery sq = new SavedQuery
{
Name = "A New Custom Public View",
Description = "A Saved Query created in code",
ReturnedTypeCode = "opportunity",
FetchXml = fetchXml,
LayoutXml = layoutXml,
QueryType = 0
};
_customViewId = _serviceProxy.Create(sq);
Console.WriteLine("A new view with the name {0} was created.", sq.Name);
//</snippetWorkWithViews1>
// Retrieve Views
//<snippetWorkWithViews2>
QueryExpression mySavedQuery = new QueryExpression
{
ColumnSet = new ColumnSet("savedqueryid", "name", "querytype", "isdefault", "returnedtypecode", "isquickfindquery"),
EntityName = SavedQuery.EntityLogicalName,
Criteria = new FilterExpression
{
Conditions =
{
new ConditionExpression
{
AttributeName = "querytype",
Operator = ConditionOperator.Equal,
Values = {0}
},
new ConditionExpression
{
AttributeName = "returnedtypecode",
Operator = ConditionOperator.Equal,
Values = {Opportunity.EntityTypeCode}
}
//.........这里部分代码省略.........
示例9: Run
/// <summary>
/// Create and configure the organization service proxy.
/// Create a new queue instance.
/// 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();
//<snippetCreateQueue1>
// 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
};
var QueueViewType = new
{
Public = 0,
Private = 1
};
// Create a queue instance and set its property values.
Queue newQueue = new Queue()
{
Name = "Example Queue.",
Description = "This is an example queue.",
IncomingEmailDeliveryMethod = new OptionSetValue(
IncomingEmailDeliveryMethods.None),
IncomingEmailFilteringMethod = new OptionSetValue(
IncomingEmailFilteringMethods.AllEmailMessages),
OutgoingEmailDeliveryMethod = new OptionSetValue(
OutgoingEmailDeliveryMethods.None),
QueueViewType = new OptionSetValue(
QueueViewType.Private)
};
// Create a new queue instance.
_queueId = _serviceProxy.Create(newQueue);
//</snippetCreateQueue1>
Console.WriteLine("Created {0}", newQueue.Name);
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;
}
}
示例10: Run
/// <summary>
/// This method first connects to the Organization service. Afterwards, the
/// sample creates a goal and child goals for a particular fiscal period.
/// Stretched targets are tracked as well.
/// </summary>
/// <param name="serverConfig">Contains server connection information.</param>
/// <param name="promptforDelete">When True, the user will be prompted to delete all
/// created entities.</param>
public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
{
try
{
//<snippetRollupAllGoalsForFiscalPeriodAndStretchedTargetRevenue1>
// Connect to the Organization service.
// The using statement assures that the service proxy will be properly disposed.
using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
{
// This statement is required to enable early-bound type support.
_serviceProxy.EnableProxyTypes();
CreateRequiredRecords();
#region Create goal metric
// Create the metric, setting the Metric Type to 'Count' and enabling
// stretch tracking.
Metric metric = new Metric()
{
Name = "Sample Count Metric",
IsAmount = false,
IsStretchTracked = true
};
_metricId = _serviceProxy.Create(metric);
metric.Id = _metricId;
Console.Write("Created count metric, ");
#endregion
#region Create RollupFields
// Create RollupField which targets completed (received) phone calls.
RollupField actual = new RollupField()
{
SourceEntity = PhoneCall.EntityLogicalName,
GoalAttribute = "actualinteger",
SourceState = 1,
SourceStatus = 4,
EntityForDateAttribute = PhoneCall.EntityLogicalName,
DateAttribute = "actualend",
MetricId = metric.ToEntityReference()
};
_actualId = _serviceProxy.Create(actual);
Console.Write("created completed phone call RollupField, ");
#endregion
#region Create the goal rollup queries
// Note: Formatting the FetchXml onto multiple lines in the following
// rollup queries causes the length property to be greater than 1,000
// chars and will cause an exception.
// The following query locates closed incoming phone calls.
GoalRollupQuery goalRollupQuery = new GoalRollupQuery()
{
Name = "Example Goal Rollup Query",
QueryEntityType = PhoneCall.EntityLogicalName,
FetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='phonecall'><attribute name='subject'/><attribute name='statecode'/><attribute name='prioritycode'/><attribute name='scheduledend'/><attribute name='createdby'/><attribute name='regardingobjectid'/><attribute name='activityid'/><order attribute='subject' descending='false'/><filter type='and'><condition attribute='directioncode' operator='eq' value='0'/><condition attribute='statecode' operator='eq' value='1' /></filter></entity></fetch>"
};
_rollupQueryIds.Add(_serviceProxy.Create(goalRollupQuery));
goalRollupQuery.Id = _rollupQueryIds[0];
// The following query locates closed outgoing phone calls.
GoalRollupQuery goalRollupQuery2 = new GoalRollupQuery()
{
Name = "Example Goal Rollup Query",
QueryEntityType = PhoneCall.EntityLogicalName,
FetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='phonecall'><attribute name='subject'/><attribute name='statecode'/><attribute name='prioritycode'/><attribute name='scheduledend'/><attribute name='createdby'/><attribute name='regardingobjectid'/><attribute name='activityid'/><order attribute='subject' descending='false'/><filter type='and'><condition attribute='directioncode' operator='eq' value='1'/><condition attribute='statecode' operator='eq' value='1' /></filter></entity></fetch>"
};
_rollupQueryIds.Add(_serviceProxy.Create(goalRollupQuery2));
goalRollupQuery2.Id = _rollupQueryIds[1];
Console.Write("created rollup queries for phone calls.\n");
Console.WriteLine();
#endregion
#region Create goals
// Determine current fiscal period and year.
// Note: This sample assumes quarterly fiscal periods.
DateTime date = DateTime.Now;
int quarterNumber = (date.Month - 1) / 3 + 1;
int yearNumber = date.Year;
// Create three goals: one parent goal and two child goals.
Goal parentGoal = new Goal()
{
//.........这里部分代码省略.........
示例11: Run
/// <summary>
/// Shows how to perform the following tasks with solutions:
/// - Create a Publisher
/// - Retrieve the Default Publisher
/// - Create a Solution
/// - Retrieve a Solution
/// - Add an existing Solution Component
/// - Remove a Solution Component
/// - Export or Package a Solution
/// - Install or Upgrade a solution
/// - Delete a Solution
/// </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();
//<snippetWorkWithSolutions1>
//Define a new publisher
Publisher _crmSdkPublisher = new Publisher
{
UniqueName = "sdksamples",
FriendlyName = "Microsoft CRM SDK Samples",
SupportingWebsiteUrl = "http://msdn.microsoft.com/en-us/dynamics/crm/default.aspx",
CustomizationPrefix = "sample",
EMailAddress = "[email protected]",
Description = "This publisher was created with samples from the Microsoft Dynamics CRM SDK"
};
//Does publisher already exist?
QueryExpression querySDKSamplePublisher = new QueryExpression
{
EntityName = Publisher.EntityLogicalName,
ColumnSet = new ColumnSet("publisherid", "customizationprefix"),
Criteria = new FilterExpression()
};
querySDKSamplePublisher.Criteria.AddCondition("uniquename", ConditionOperator.Equal, _crmSdkPublisher.UniqueName);
EntityCollection querySDKSamplePublisherResults = _serviceProxy.RetrieveMultiple(querySDKSamplePublisher);
Publisher SDKSamplePublisherResults = null;
//If it already exists, use it
if (querySDKSamplePublisherResults.Entities.Count > 0)
{
SDKSamplePublisherResults = (Publisher)querySDKSamplePublisherResults.Entities[0];
_crmSdkPublisherId = (Guid)SDKSamplePublisherResults.PublisherId;
_customizationPrefix = SDKSamplePublisherResults.CustomizationPrefix;
}
//If it doesn't exist, create it
if (SDKSamplePublisherResults == null)
{
_crmSdkPublisherId = _serviceProxy.Create(_crmSdkPublisher);
Console.WriteLine(String.Format("Created publisher: {0}.", _crmSdkPublisher.FriendlyName));
_customizationPrefix = _crmSdkPublisher.CustomizationPrefix;
}
//</snippetWorkWithSolutions1>
//<snippetWorkWithSolutions2>
// Retrieve the Default Publisher
//The default publisher has a constant GUID value;
Guid DefaultPublisherId = new Guid("{d21aab71-79e7-11dd-8874-00188b01e34f}");
Publisher DefaultPublisher = (Publisher)_serviceProxy.Retrieve(Publisher.EntityLogicalName, DefaultPublisherId, new ColumnSet(new string[] {"friendlyname" }));
EntityReference DefaultPublisherReference = new EntityReference
{
Id = DefaultPublisher.Id,
LogicalName = Publisher.EntityLogicalName,
Name = DefaultPublisher.FriendlyName
};
Console.WriteLine("Retrieved the {0}.", DefaultPublisherReference.Name);
//</snippetWorkWithSolutions2>
//<snippetWorkWithSolutions3>
// Create a Solution
//Define a solution
Solution solution = new Solution
{
UniqueName = "samplesolution",
FriendlyName = "Sample Solution",
PublisherId = new EntityReference(Publisher.EntityLogicalName, _crmSdkPublisherId),
Description = "This solution was created by the WorkWithSolutions sample code in the Microsoft Dynamics CRM SDK samples.",
//.........这里部分代码省略.........
示例12: Run
/// <summary>
/// This method first connects to the Organization service. Afterwards,
/// several actions on Goal records are executed.
/// </summary>
/// <param name="serverConfig">Contains server connection information.</param>
/// <param name="promptforDelete">When True, the user will be prompted to delete all
/// created entities.</param>
public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
{
try
{
//<snippetRollupAllGoalsForCustomPeriodAgainstTargetRevenue1>
// Connect to the Organization service.
// The using statement assures that the service proxy will be properly disposed.
using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
{
// This statement is required to enable early-bound type support.
_serviceProxy.EnableProxyTypes();
CreateRequiredRecords();
// Create the revenue metric, setting the Amount Data Type to 'Money'
// and the Metric Type to 'Amount'.
Metric sampleMetric = new Metric()
{
Name = "Sample Revenue Metric",
AmountDataType = new OptionSetValue(0),
IsAmount = true,
};
_metricId = _serviceProxy.Create(sampleMetric);
Console.Write("Created revenue metric, ");
// Create first RollupField which targets the estimated values.
RollupField inProgress = new RollupField()
{
SourceEntity = Opportunity.EntityLogicalName,
SourceAttribute = "estimatedvalue",
GoalAttribute = "inprogressmoney",
SourceState = 0,
EntityForDateAttribute = Opportunity.EntityLogicalName,
DateAttribute = "estimatedclosedate",
MetricId = new EntityReference(Metric.EntityLogicalName, _metricId),
};
_inProgressId = _serviceProxy.Create(inProgress);
Console.Write("created in-progress RollupField, ");
// Create second RollupField which targets the actual values.
RollupField actual = new RollupField()
{
SourceEntity = Opportunity.EntityLogicalName,
SourceAttribute = "actualvalue",
GoalAttribute = "actualmoney",
SourceState = 1,
EntityForDateAttribute = Opportunity.EntityLogicalName,
DateAttribute = "actualclosedate",
MetricId = new EntityReference(Metric.EntityLogicalName, _metricId)
};
_actualId = _serviceProxy.Create(actual);
Console.Write("created actual revenue RollupField, ");
// Create the goal rollup queries.
// Note: Formatting the FetchXml onto multiple lines in the following
// rollup queries causes the lenth property to be greater than 1,000
// chars and will cause an exception.
// The first query locates opportunities in the first sales
// representative's area (zip code: 60661).
GoalRollupQuery goalRollupQuery = new GoalRollupQuery()
{
Name = "First Example Goal Rollup Query",
QueryEntityType = Opportunity.EntityLogicalName,
FetchXml = @"<fetch version=""1.0"" output-format=""xml-platform"" mapping=""logical"" distinct=""false""><entity name=""opportunity""><attribute name=""totalamount""/><attribute name=""name""/><attribute name=""customerid""/><attribute name=""estimatedvalue""/><attribute name=""statuscode""/><attribute name=""opportunityid""/><order attribute=""name"" descending=""false""/><link-entity name=""account"" from=""accountid"" to=""customerid"" alias=""aa""><filter type=""and""><condition attribute=""address1_postalcode"" operator=""eq"" value=""60661""/></filter></link-entity></entity></fetch>"
};
_rollupQueryIds.Add(_serviceProxy.Create(goalRollupQuery));
Console.Write("created first rollup query for zip code 60661, ");
// The second query locates opportunities in the second sales
// representative's area (zip code: 99999).
goalRollupQuery = new GoalRollupQuery()
{
Name = "Second Example Goal Rollup Query",
QueryEntityType = Opportunity.EntityLogicalName,
FetchXml = @"<fetch version=""1.0"" output-format=""xml-platform"" mapping=""logical"" distinct=""false""><entity name=""opportunity""><attribute name=""totalamount""/><attribute name=""customerid""/><attribute name=""estimatedvalue""/><attribute name=""statuscode""/><attribute name=""opportunityid""/><order attribute=""name"" descending=""false""/><link-entity name=""account"" from=""accountid"" to=""customerid"" alias=""aa""><filter type=""and""><condition attribute=""address1_postalcode"" operator=""eq"" value=""99999""/></filter></link-entity></entity></fetch>"
};
_rollupQueryIds.Add(_serviceProxy.Create(goalRollupQuery));
Console.WriteLine("created second rollup query for zip code 99999.");
Console.WriteLine();
// Create three goals: one parent goal and two child goals.
Goal parentGoal = new Goal()
{
Title = "Parent Goal Example",
RollupOnlyFromChildGoals = true,
ConsiderOnlyGoalOwnersRecords = true,
TargetMoney = new Money(300.0M),
//.........这里部分代码省略.........
示例13: Run
/// <summary>
/// Create and configure the organization service proxy.
/// Initiate method to create any data that this sample requires.
/// Create a new opportunity and few opportunity product
/// including write-in product.
/// 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();
CreateRequiredRecords();
//<snippetCreateOpportunity1>
// Create a new opportunity with user specified estimated revenue
Opportunity newOpportunity = new Opportunity
{
Name = "Example Opportunity",
CustomerId = new EntityReference(Account.EntityLogicalName,
_accountId),
PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName,
_priceListId),
IsRevenueSystemCalculated = false,
EstimatedValue = new Money(400.00m),
FreightAmount = new Money(10.00m),
DiscountAmount = new Money(0.10m),
DiscountPercentage = 0.20m
};
_opportunityId = _serviceProxy.Create(newOpportunity);
Console.WriteLine("Created {0} with user specified estimated revenue.",
newOpportunity.Name);
// Create a new opportunity product from the catalog
// Create a catalog product
OpportunityProduct catalogProduct = new OpportunityProduct
{
OpportunityId = new EntityReference(Opportunity.EntityLogicalName,
_opportunityId),
ProductId = new EntityReference(Product.EntityLogicalName,
_product1Id),
UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
Quantity = 8,
Tax = new Money(12.42m)
};
_catalogProductId = _serviceProxy.Create(catalogProduct);
Console.WriteLine("Created the catalog product.");
// Create anothter catalog product and override the list price
OpportunityProduct catalogProductPriceOverride = new OpportunityProduct
{
OpportunityId = new EntityReference(Opportunity.EntityLogicalName,
_opportunityId),
ProductId = new EntityReference(Product.EntityLogicalName,
_product2Id),
UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId),
Quantity = 3,
Tax = new Money(2.88m),
IsPriceOverridden = true,
PricePerUnit = new Money(12)
};
_catalogProductPriceOverrideId = _serviceProxy.Create(
catalogProductPriceOverride);
Console.WriteLine(@"Created another catalog product and
overriden the list price.");
// create a new write-in opportunity product with a manual discount applied
OpportunityProduct writeInProduct = new OpportunityProduct
{
OpportunityId = new EntityReference(Opportunity.EntityLogicalName,
_opportunityId),
IsProductOverridden = true,
ProductDescription = "Example Write-in Product",
PricePerUnit = new Money(20.00m),
Quantity = 5,
ManualDiscountAmount = new Money(10.50m),
Tax = new Money(7.16m)
};
_writeInProductId = _serviceProxy.Create(writeInProduct);
Console.WriteLine("Created {0}.", writeInProduct.ProductDescription);
//</snippetCreateOpportunity1>
DeleteRequiredRecords(promptForDelete);
}
//.........这里部分代码省略.........
示例14: 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;
}
}
示例15: 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;
}
}