本文整理汇总了C#中Microsoft.Crm.Sdk.Samples.ServerConnection类的典型用法代码示例。如果您正苦于以下问题:C# ServerConnection类的具体用法?C# ServerConnection怎么用?C# ServerConnection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ServerConnection类属于Microsoft.Crm.Sdk.Samples命名空间,在下文中一共展示了ServerConnection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Run
/// <summary>
/// This method first connects to the Organization service. Afterwards, it
/// retrieves roles.
/// </summary>
/// <param name="serverConfig">Contains server connection information.</param>
/// <param name="promptforDelete">When True, the user is prompted to delete all
/// created entities.</param>
public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
{
try
{
//<snippetRetrieveRolesForOrg1>
// Connect to the Organization service.
// The using statement assures that the service proxy is properly disposed.
using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
{
QueryExpression query = new QueryExpression
{
EntityName = Role.EntityLogicalName,
ColumnSet = new ColumnSet("name", "roleid")
};
EntityCollection entities = _serviceProxy.RetrieveMultiple(query);
// Write the name and ID of each role to the console.
foreach (Entity item in entities.Entities)
{
Role role = item.ToEntity<Role>();
Console.WriteLine("Name: {0}. Id: {1}", role.Name, role.Id);
}
}
//</snippetRetrieveRolesForOrg1>
}
// Catch any service fault exceptions that Microsoft Dynamics CRM throws.
catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
{
// You can handle an exception here or pass it back to the calling method.
throw;
}
}
示例2: Run
/// <summary>
/// Run the sample.
/// </summary>
/// <param name="serverConfig">configuration for the server.</param>
/// <param name="promptToDelete">
/// whether or not to prompt the user to delete created records.
/// </param>
public void Run(ServerConnection.Configuration serverConfig, bool promptToDelete)
{
using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,
serverConfig.Credentials, serverConfig.DeviceCredentials))
{
using (_context = new ServiceContext(_serviceProxy))
{
// This statement is required to enable early-bound type support.
_serviceProxy.EnableProxyTypes();
// This statments checks whether Standard Email templates are present
var emailTemplateId = (
from emailTemplate in _context.TemplateSet
where emailTemplate.Title == "Contact Reconnect"
select emailTemplate.Id
).FirstOrDefault();
if (emailTemplateId != Guid.Empty)
{
CreateRequiredRecords();
// Perform the bulk delete. If you want to perform a recurring delete
// operation, then leave this as it is. Otherwise, pass in false as the
// first parameter.
PerformBulkDelete(true, promptToDelete);
}
else
{
throw new ArgumentException("Standard Email Templates are missing");
}
}
}
}
示例3: Run
public void Run(ServerConnection.Configuration serverConfig, string solutionPath)
{
try
{
using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
{
byte[] data = File.ReadAllBytes(solutionPath);
Guid importId = Guid.NewGuid();
Console.WriteLine("\n Importing solution {0} into Server {1}.", solutionPath, serverConfig.OrganizationUri);
_serviceProxy.EnableProxyTypes();
ImportSolutionRequest importSolutionRequest = new ImportSolutionRequest()
{
CustomizationFile = data,
ImportJobId = importId
};
ThreadStart starter = () =>ProgressReport(serverConfig, importId);
Thread t = new Thread(starter);
t.Start();
_serviceProxy.Execute(importSolutionRequest);
Console.Write("Solution {0} successfully imported into {1}", solutionPath, serverConfig.OrganizationUri);
}
}
catch (Exception ex)
{
}
}
示例4: Connect
private void Connect()
{
ServerConnection serverConnect = new ServerConnection();
ServerConnection.Configuration serverConfig = serverConnect.GetServerConfiguration();
this.service = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials);
}
示例5: Run
/// <summary>
/// Create and configure the organization service proxy.
/// Initiate the method to create any data that this sample requires.
/// Delete a new queue instance.
/// 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();
//<snippetDeleteQueue1>
// Delete the queue instance.
_serviceProxy.Delete(Queue.EntityLogicalName, _queueId);
//</snippetDeleteQueue1>
Console.WriteLine("Deleted a queue instance.");
}
}
// 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>
/// 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;
}
}
示例7: Run
/// <summary>
/// Create and configure the organization service proxy.
/// Call the method to create any data that this sample requires.
/// Query the connections.
/// 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();
//<snippetQueryConnections1>
// This query retrieves all connections this contact is part of.
QueryExpression query = new QueryExpression
{
EntityName = Connection.EntityLogicalName,
ColumnSet = new ColumnSet("connectionid"),
Criteria = new FilterExpression
{
FilterOperator = LogicalOperator.And,
Conditions =
{
// You can safely query against only record1id or
// record2id - CRM will find all connections this
// entity is a part of either way.
new ConditionExpression
{
AttributeName = "record1id",
Operator = ConditionOperator.Equal,
Values = { _contactId }
}
}
}
};
EntityCollection results = _serviceProxy.RetrieveMultiple(query);
// TODO: Here you could do a variety of tasks with the
// connections retrieved, such as listing the connected entities,
// finding reciprocal connections, etc.
//</snippetQueryConnections1>
Console.WriteLine("Retrieved {0} connectionrole instances.", results.Entities.Count);
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;
}
}
示例8: Run
/// <summary>
/// Create and configure the organization service proxy.
/// Create a team, a queue and a role.
/// Add read queue privileges to the role.
/// Assign the role to the team so that they can read the queue.
/// Assign the queue to the team.
/// 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();
_service = (IOrganizationService)_serviceProxy;
// Call the method to create any data that this sample requires.
CreateRequiredRecords();
//<snippetAssociateDisassociate1>
// Associate the accounts to the contact record.
// Create a collection of the entities that will be
// associated to the contact.
EntityReferenceCollection relatedEntities = new EntityReferenceCollection();
relatedEntities.Add(new EntityReference(Account.EntityLogicalName, _account1Id));
relatedEntities.Add(new EntityReference(Account.EntityLogicalName, _account2Id));
relatedEntities.Add(new EntityReference(Account.EntityLogicalName, _account3Id));
// Create an object that defines the relationship between the contact and account.
Relationship relationship = new Relationship("account_primary_contact");
//Associate the contact with the 3 accounts.
_service.Associate(Contact.EntityLogicalName, _contactId, relationship,
relatedEntities);
Console.WriteLine("The entities have been associated.");
//Disassociate the records.
_service.Disassociate(Contact.EntityLogicalName, _contactId, relationship,
relatedEntities);
//</snippetAssociateDisassociate1>
Console.WriteLine("The entities have been disassociated.");
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;
}
}
示例9: 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
{
// 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();
_service = (IOrganizationService)_serviceProxy;
CreateRequiredRecords();
//<snippetQueryByAttribute1>
// Create query using QueryByAttribute.
QueryByAttribute querybyattribute = new QueryByAttribute("account");
querybyattribute.ColumnSet = new ColumnSet("name", "address1_city", "emailaddress1");
// Attribute to query.
querybyattribute.Attributes.AddRange("address1_city");
// Value of queried attribute to return.
querybyattribute.Values.AddRange("Redmond");
// Query passed to service proxy.
EntityCollection retrieved = _service.RetrieveMultiple(querybyattribute);
System.Console.WriteLine("Query Using QueryByAttribute");
System.Console.WriteLine("===============================");
// Iterate through returned collection.
foreach (var c in retrieved.Entities)
{
System.Console.WriteLine("Name: " + c.Attributes["name"]);
if( c.Attributes.Contains("address1_city") )
System.Console.WriteLine("Address: " + c.Attributes["address1_city"]);
if( c.Attributes.Contains("emailaddress1") )
System.Console.WriteLine("E-mail: " + c.Attributes["emailaddress1"]);
}
System.Console.WriteLine("===============================");
//</snippetQueryByAttribute1>
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.
/// Initiate method to create any entity records that this sample requires.
/// Retrieves new owner's details.
/// Update the queue item record to assign it to new owner.
/// Optionally delete any entity records that were created for this sample.
/// <para name="organizationFriendlyName">The friendly name of the
/// target organization.</para>
/// <para name="discoveryServer">The name of the discovery server.</para>
/// <param name="promptForDelete">Indicates whether to prompt the user to
/// delete the records created in this sample.</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();
//<snippetAssignQueueItemWorker1>
// Retrieve the current user information.
WhoAmIRequest whoAmIRequest = new WhoAmIRequest();
WhoAmIResponse whoAmIResponse = (WhoAmIResponse)_serviceProxy.Execute(
whoAmIRequest);
ColumnSet columnSet = new ColumnSet("fullname");
SystemUser currentUser = (SystemUser)_serviceProxy.Retrieve(
SystemUser.EntityLogicalName,
whoAmIResponse.UserId, columnSet);
String currentUserName = currentUser.FullName;
_userId = currentUser.Id;
// Create an instance of an existing queueitem in order to specify
// the user that will be working on it using PickFromQueueRequest.
PickFromQueueRequest pickFromQueueRequest = new PickFromQueueRequest
{
QueueItemId = _queueItemId,
WorkerId = _userId
};
_serviceProxy.Execute(pickFromQueueRequest);
//</snippetAssignQueueItemWorker1>
Console.WriteLine("The letter queue item is queued for new owner {0}.",
currentUserName);
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
/// <summary>
/// Demonstrates how to programmatically install and uninstall the Microsoft
/// Dynamics CRM sample data records.
/// </summary>
/// <param name="serverConfig">Contains server connection information.</param>
/// <param name="promptforDelete">Not applicable for this sample.</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();
//<snippetImportOrRemoveSampleData1>
// Prompt user to install/uninstall sample data.
Console.WriteLine("Would you like to:");
Console.WriteLine("1) Install sample data for Microsoft Dynamics CRM?");
Console.WriteLine("2) Uninstall sample data for Microsoft Dynamics CRM?");
Console.Write("Press [1] to Install, [2] to Uninstall: ");
String answer = Console.ReadLine();
// Update the sample data based on the user's response.
switch (answer)
{
case "1":
Console.WriteLine("Installing sample data...");
InstallSampleDataRequest request =
new InstallSampleDataRequest();
InstallSampleDataResponse response =
(InstallSampleDataResponse)_serviceProxy.Execute(request);
Console.WriteLine("Sample data successfully installed.");
break;
case "2":
Console.WriteLine("Uninstalling sample data...");
UninstallSampleDataRequest request2 =
new UninstallSampleDataRequest();
UninstallSampleDataResponse response2 =
(UninstallSampleDataResponse)_serviceProxy.Execute(request2);
Console.WriteLine("Sample data successfully uninstalled.");
break;
default:
Console.WriteLine("Neither option was selected. No changes have been made to your records.");
break;
}
}
//</snippetImportOrRemoveSampleData1>
}
// 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 creates a new currency within the system, setting its
/// exchange rate to a pre-defined value. It then issues a
/// RetrieveExchangeRateRequest to get the exchange rate from the created
/// currency to the organization's base currency. Finally, it retrieves the
/// organization's base currency and displays the conversion rate.
/// </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
{
//<snippetTransactionCurrencyExchangeRate1>
// 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))
// using the service context makes retrieving entities easier
using (_context = new ServiceContext(_serviceProxy))
{
// This statement is required to enable early-bound type support.
_serviceProxy.EnableProxyTypes();
String currentOrganizatoinUniqueName = GetCurrentOrganizationName(serverConfig);
CreateRequiredRecords();
RetrieveExchangeRateRequest request = new RetrieveExchangeRateRequest()
{
TransactionCurrencyId = _currency.Id
};
RetrieveExchangeRateResponse response =
(RetrieveExchangeRateResponse)_serviceProxy.Execute(request);
Console.WriteLine(" Retrieved exchange rate for created currency");
// get the base currency for the current org
var baseCurrencyName =
(from currency in _context.TransactionCurrencySet
join org in _context.OrganizationSet
on currency.Id equals org.BaseCurrencyId.Id
where org.Name == currentOrganizatoinUniqueName
select currency.CurrencyName).FirstOrDefault();
Console.WriteLine(" This organization's base currency is {0}",
baseCurrencyName);
Console.WriteLine(
" The conversion from {0} -> {1} is {2}",
_currency.CurrencyName,
baseCurrencyName,
response.ExchangeRate);
DeleteRequiredRecords(promptforDelete);
}
//</snippetTransactionCurrencyExchangeRate1>
}
// 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>
/// Run the sample.
/// </summary>
/// <param name="serverConfig">configuration for the server.</param>
/// <param name="promptToDelete">
/// whether or not to prompt the user to delete created records.
/// </param>
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();
PerformBulkDeleteBackup();
DeleteRequiredRecords(promptToDelete);
}
}
示例14: Run
/// <summary>
/// Create and configure the organization service proxy.
/// Retrieve the history limit of a report.
/// Optionally delete any entity records that were created for this sample.
/// </summary>
/// <param name="serverConfig">Contains server connection information.</param>
/// <param name="promptforDelete">When True, the user will be prompted to delete all
/// created entities.</param>
public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
{
try
{
// Connect to the Organization service.
// The using statement assures that the service proxy will be properly disposed.
using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
{
// This statement is required to enable early-bound type support.
_serviceProxy.EnableProxyTypes();
// Call the method to create any data that this sample requires.
CreateRequiredRecords();
//<snippetGetReportHistoryLimit1>
// Query for an an existing report: Account Overview. This is a default report in Microsoft Dynamics CRM.
QueryByAttribute reportQuery = new QueryByAttribute(Report.EntityLogicalName);
reportQuery.AddAttributeValue("name", "Account Overview");
reportQuery.ColumnSet = new ColumnSet("reportid");
// Get the report.
EntityCollection retrieveReports = _serviceProxy.RetrieveMultiple(reportQuery);
// Convert retrieved Entity to a report
Report retrievedReport = (Report)retrieveReports.Entities[0];
Console.WriteLine("Retrieved the 'Account Overview' report.");
// Use the Download Report Definition message.
GetReportHistoryLimitRequest reportHistoryRequest = new GetReportHistoryLimitRequest
{
ReportId = retrievedReport.ReportId.Value
};
GetReportHistoryLimitResponse reportHistoryResponse = (GetReportHistoryLimitResponse)_serviceProxy.Execute(reportHistoryRequest);
// Access the history limit data
int historyLimit = reportHistoryResponse.HistoryLimit;
Console.WriteLine("The report history limit is {0}.", historyLimit);
//</snippetGetReportHistoryLimit1>
}
}
// Catch any service fault exceptions that Microsoft Dynamics CRM throws.
catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
{
// You can handle an exception here or pass it back to the calling method.
throw;
}
}
示例15: 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;
}
}