本文整理汇总了C#中OrganizationServiceProxy类的典型用法代码示例。如果您正苦于以下问题:C# OrganizationServiceProxy类的具体用法?C# OrganizationServiceProxy怎么用?C# OrganizationServiceProxy使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
OrganizationServiceProxy类属于命名空间,在下文中一共展示了OrganizationServiceProxy类的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
/// <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;
}
}
示例4: Main
//Start of Main
public static void Main(string[] args)
{
Console.WriteLine("The process has started \nTrying to Export Solution");
//Create new user and gets credentials to login and capture desired solution
Session loginUser = new Session();
ClientCredentials credentials = GetCredentials(loginUser);
using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(loginUser.OrganizationUri,null, credentials, GetDeviceCredentials()))
{
string outputDir = @"C:\temp\";
//Creates the Export Request
ExportSolutionRequest exportRequest = new ExportSolutionRequest();
exportRequest.Managed = true;
exportRequest.SolutionName = loginUser.SolutionName;
ExportSolutionResponse exportResponse = (ExportSolutionResponse)serviceProxy.Execute(exportRequest);
//Handles the response
byte[] exportXml = exportResponse.ExportSolutionFile;
string filename = loginUser.SolutionName + "_" + DateToString() + ".zip";
File.WriteAllBytes(outputDir + filename, exportXml);
Console.WriteLine("Solution Successfully Exported to {0}", outputDir + filename);
}
}
示例5: CreateXrmServiceContext
protected XrmServiceContext CreateXrmServiceContext(MergeOption? mergeOption = null)
{
//string organizationUri = ConfigurationManager.AppSettings["CRM_OrganisationUri"];
string organizationUri = "https://existornest2.api.crm4.dynamics.com/XRMServices/2011/Organization.svc";
IServiceManagement<IOrganizationService> OrganizationServiceManagement = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(new Uri(organizationUri));
AuthenticationProviderType OrgAuthType = OrganizationServiceManagement.AuthenticationType;
AuthenticationCredentials authCredentials = GetCredentials(OrgAuthType);
AuthenticationCredentials tokenCredentials = OrganizationServiceManagement.Authenticate(authCredentials);
OrganizationServiceProxy organizationProxy = null;
SecurityTokenResponse responseToken = tokenCredentials.SecurityTokenResponse;
if (ConfigurationManager.AppSettings["CRM_AuthenticationType"] == "ActiveDirectory")
{
using (organizationProxy = new OrganizationServiceProxy(OrganizationServiceManagement, authCredentials.ClientCredentials))
{
organizationProxy.EnableProxyTypes();
}
}
else
{
using (organizationProxy = new OrganizationServiceProxy(OrganizationServiceManagement, responseToken))
{
organizationProxy.EnableProxyTypes();
}
}
IOrganizationService service = (IOrganizationService)organizationProxy;
var context = new XrmServiceContext(service);
if (context != null && mergeOption != null) context.MergeOption = mergeOption.Value;
return context;
}
示例6: CrmServiceFactory
public CrmServiceFactory()
{
Uri organizationUri = GetOrganizationUri();
if (string.IsNullOrWhiteSpace(CrmConnectorSection.Instance.UserName))
throw new CrmException("A value must be supplied for username in the <crmFramework> section in web.config");
if (string.IsNullOrWhiteSpace(CrmConnectorSection.Instance.Password))
throw new CrmException("A value must be supplied for password in the <crmFramework> section in web.config");
if (string.IsNullOrWhiteSpace(CrmConnectorSection.Instance.Domain))
throw new CrmException("A value must be supplied for domain in the <crmFramework> section in web.config");
IServiceManagement<IOrganizationService> serviceManagement = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(organizationUri);
ClientCredentials clientCredentials = new ClientCredentials();
clientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
clientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
clientCredentials.UserName.UserName = string.Format("{0}@{1}", CrmConnectorSection.Instance.UserName, CrmConnectorSection.Instance.Domain);
clientCredentials.UserName.Password = CrmConnectorSection.Instance.Password;
OrganizationServiceProxy organizationServiceProxy = new OrganizationServiceProxy(
serviceManagement,
clientCredentials);
organizationServiceProxy.EnableProxyTypes();
_organizationServiceProxy = organizationServiceProxy;
}
示例7: GetOrganisationService
public IOrganizationService GetOrganisationService(OrganizationDetail org, string domain, string userName, string password)
{
if (org != null)
{
Uri orgServiceUri = null;
orgServiceUri = new Uri(org.Endpoints[EndpointType.OrganizationService]);
//if (!string.IsNullOrEmpty(OrganisationServiceHostName))
//{
// UriBuilder builder = new UriBuilder(orgServiceUri);
// builder.Host = OrganisationServiceHostName;
// orgServiceUri = builder.Uri;
//}
IServiceConfiguration<IOrganizationService> orgConfigInfo = ServiceConfigurationFactory.CreateConfiguration<IOrganizationService>(orgServiceUri);
var creds = _credentialsProvider.GetCredentials(orgConfigInfo.AuthenticationType, domain, userName, password);
var orgService = new OrganizationServiceProxy(orgConfigInfo, creds);
orgService.Timeout = new TimeSpan(0, 5, 0);
var req = new WhoAmIRequest();
var response = (WhoAmIResponse)orgService.Execute(req);
Debug.WriteLine(string.Format(" Connected to {0} as Crm user id: {1}", orgConfigInfo.CurrentServiceEndpoint.Address.Uri.ToString(), response.UserId));
return orgService;
}
return null;
}
示例8: Connect
public static OrganizationServiceProxy Connect()
{
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["CRM"];
if (settings == null)
throw new ConfigurationException("No CRM Connection String was found.");
Uri uri = new Uri(settings.ConnectionString);
ClientCredentials credentials = null;
string user = ConfigurationManager.AppSettings["User"];
string password = ConfigurationManager.AppSettings["Password"];
if (!string.IsNullOrWhiteSpace(user))
{
credentials = new ClientCredentials();
credentials.UserName.UserName = "";
credentials.UserName.Password = "";
}
OrganizationServiceProxy proxy = new OrganizationServiceProxy(uri, null, credentials, null);
proxy.EnableProxyTypes(typeof(Toyota.Tsusho.CRM.API.Contact).Assembly);
return proxy;
}
示例9: GetOrgService
public static IOrganizationService GetOrgService(bool admin = false, string callerId = null, string organization = null)
{
ClientCredentials credential = new ClientCredentials();
if (Globals.OrganizationServiceUrl.Contains("https"))
{
credential.Windows.ClientCredential = admin ? new NetworkCredential(Globals.AdminUserName, Globals.AdminPassword, Globals.DomainName) : CredentialCache.DefaultNetworkCredentials;
credential.UserName.UserName = Globals.DomainName + @"\" + Globals.AdminUserName;
credential.UserName.Password = Globals.AdminPassword;
}
else
{
credential.Windows.ClientCredential = admin ? new NetworkCredential(Globals.AdminUserName, Globals.AdminPassword, Globals.DomainName) : CredentialCache.DefaultNetworkCredentials;
}
OrganizationServiceProxy orgServiceProxy = new OrganizationServiceProxy(new Uri(Globals.OrganizationServiceUrl), null, credential, null);
if (!string.IsNullOrEmpty(callerId))
{
orgServiceProxy.CallerId = new Guid(callerId);
}
return orgServiceProxy;
////credential.Windows.ClientCredential = admin ? new NetworkCredential(Globals.AdminUserName, Globals.AdminPassword, Globals.DomainName) : CredentialCache.DefaultNetworkCredentials;
////credential.UserName.UserName = Globals.DomainName + @"\" + Globals.AdminUserName;
////credential.UserName.Password = Globals.AdminPassword;
////OrganizationServiceProxy orgServiceProxy = new OrganizationServiceProxy(new Uri(Globals.OrganizationServiceUrl), null, credential, null);
////if (!string.IsNullOrEmpty(callerId))
////{
//// orgServiceProxy.CallerId = new Guid(callerId);
////}
////return orgServiceProxy;
}
示例10: 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)
{
}
}
示例11: CrmVcardUpdateService
public CrmVcardUpdateService(string userEmail)
{
if (string.IsNullOrWhiteSpace(userEmail))
{
throw new ArgumentException("userEmail must be a valid email address", "userEmail");
}
// Establish CRM connection
var crmConnection = CrmConnection.Parse(CloudConfigurationManager.GetSetting("CrmConnectionString"));
var serviceUri = new Uri(crmConnection.ServiceUri + "/XRMServices/2011/Organization.svc");
this.service = new OrganizationServiceProxy(serviceUri, null, crmConnection.ClientCredentials, null);
// This statement is required to enable early-bound type support.
this.service.EnableProxyTypes(Assembly.GetAssembly(typeof(SystemUser)));
// Create context
this.orgContext = new OrganizationServiceContext(this.service);
// Retrieve the system user ID of the user to impersonate.
this.impersonatedUser = (from user in this.orgContext.CreateQuery<SystemUser>() where user.InternalEMailAddress == userEmail select user).FirstOrDefault();
// We impersonate the user that has sent the email
if (this.impersonatedUser == null)
{
throw new Exception("User not found in CRM");
}
this.service.CallerId = this.impersonatedUser.Id;
}
示例12: connect
public bool connect(string serviceURL, string domainName, string userName, string password)
{
try
{
Uri organizationUri = new Uri(serviceURL);
Uri homeRealmUri = null;
ClientCredentials credentials = new ClientCredentials();
// set default credentials for OrganizationService
credentials.Windows.ClientCredential = new NetworkCredential(userName, password, domainName);
// credentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
OrganizationServiceProxy orgProxy = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null);
_service = (IOrganizationService)orgProxy;
//to check connection with CRM
getAttributeMax("campaign", "exchangerate");
return true;
}
catch (InvalidOperationException)
{
throw new connectionException("The URI provided cannot be resolved ( " + serviceURL + " )");
}
catch (SecurityNegotiationException)
{
throw new connectionException("The authentication failed ! Please check the credentials provided.");
}
catch (Exception ex)
{
throw new connectionException(ex.Message);
}
}
示例13: ReportErrors
/// <summary>
/// Check for importlog records
/// </summary>
/// <param name="service"></param>
/// <param name="importFileId"></param>
public static void ReportErrors(OrganizationServiceProxy serviceProxy, Guid importFileId)
{
QueryByAttribute importLogQuery = new QueryByAttribute();
importLogQuery.EntityName = ImportLog.EntityLogicalName;
importLogQuery.ColumnSet = new ColumnSet(true);
importLogQuery.Attributes.Add("importfileid");
importLogQuery.Values.Add(new object[1]);
importLogQuery.Values[0] = importFileId;
EntityCollection importLogs = serviceProxy.RetrieveMultiple(importLogQuery);
if (importLogs.Entities.Count > 0)
{
Console.WriteLine("Number of Failures: " + importLogs.Entities.Count.ToString());
Console.WriteLine("Sequence Number Error Number Description Column Header Column Value Line Number");
// Display errors.
foreach (ImportLog log in importLogs.Entities)
{
Console.WriteLine(
string.Format("Sequence Number: {0}\nError Number: {1}\nDescription: {2}\nColumn Header: {3}\nColumn Value: {4}\nLine Number: {5}",
log.SequenceNumber.Value,
log.ErrorNumber.Value,
log.ErrorDescription,
log.HeaderColumn,
log.ColumnValue,
log.LineNumber.Value));
}
}
}
示例14: 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;
}
}
示例15: 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;
}
}