When calling the Execute method on a Dynamics CRM 2011 service, passing an ImportSolutionRequest object as a parameter, the following EndpointNotFound exception is thrown:
There was no endpoint listening at http://ServerName:5555/OrganisationName/XRMServices/2011/Organization.svc that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
The InnerException is a System.Net.WebException:
{"The remote server returned an error: (404) Not Found."}
The following code is used to import a solution into a Dynamics CRM 2011 Organization:
#region Properties /// <summary> /// Gets or sets the server. /// </summary> /// <value> /// The server. /// </value> [Required] public string DiscoveryServer { get; set; } /// <summary> /// Gets or sets the port. /// </summary> /// <value> /// The port. /// </value> public string Port { get; set; } /// <summary> /// Gets or sets the scheme. /// </summary> /// <value> /// The scheme. /// </value> [Required] public string Scheme { get; set; } /// <summary> /// Gets or sets the organization. /// </summary> /// <value> /// The organization. /// </value> [Required] public string Organization { get; set; } /// <summary> /// Gets or sets the domain. /// </summary> /// <value> /// The domain. /// </value> public string Domain { get; set; } /// <summary> /// Gets or sets the name of the user. /// </summary> /// <value> /// The name of the user. /// </value> public string UserName { get; set; } /// <summary> /// Gets or sets the password. /// </summary> /// <value> /// The password. /// </value> public string Password { get; set; } /// <summary> /// Gets or sets the solution file path. /// </summary> /// <value> /// The solution file path. /// </value> [Required] public string SolutionFilePath { get; set; } #endregion #region Public Methods /// <summary> /// When overridden in a derived class, executes the task. /// </summary> /// <returns> /// true if the task successfully executed; otherwise, false. /// </returns> public override bool Execute() { try { Log.LogMessage(Properties.Resources.importSolutionStarted); CustomNameSpace.Entities.Solution solution = new CustomNameSpace.Entities.Solution(new XrmConnection(DiscoveryServer, Port, Scheme, Organization, Domain, UserName, Password).Connection); solution.ImportSolution(SolutionFilePath); Log.LogMessage(Properties.Resources.importSolutionCompleted); return true; } catch (ApplicationException exception) { Log.LogMessage(exception.Message); return false; } } #endregion
Here is the Solution Class:
/// <summary> /// Solution Class. /// </summary> public partial class Solution { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Solution"/> class. /// </summary> /// <param name="crmConnection">The CRM connection.</param> public Solution(CrmConnection crmConnection) { CrmConnection = crmConnection; ProxyUri = new Uri(String.Format(CultureInfo.CurrentCulture, "{0}/XrmServices/2011/Organization.svc", CrmConnection.ServiceUri)); } #endregion #region Properties /// <summary> /// The proxy URI. /// </summary> private Uri _proxyUri; /// <summary> /// Gets or sets the proxy URI. /// </summary> /// <value> /// The proxy URI. /// </value> public Uri ProxyUri { get { return _proxyUri; } set { _proxyUri = value; } } /// <summary> /// The Crm connection. /// </summary> private CrmConnection _crmConnection; /// <summary> /// Gets or sets the Crm connection. /// </summary> /// <value> /// The Crm connection. /// </value> public CrmConnection CrmConnection { get { return _crmConnection; } set { _crmConnection = value; } } /// <summary> /// The Crm service. /// </summary> private IOrganizationService _crmService; /// <summary> /// Gets or sets the Crm service. /// </summary> /// <value> /// The Crm service. /// </value> public IOrganizationService CrmService { get { return _crmService; } set { _crmService = value; } } /// <summary> /// The Crm proxy. /// </summary> private OrganizationServiceProxy _crmProxy; /// <summary> /// Gets or sets the Crm proxy. /// </summary> /// <value> /// The Crm proxy. /// </value> public OrganizationServiceProxy CrmProxy { get { return _crmProxy; } set { _crmProxy = value; } } #endregion #region Public Methods /// <summary> /// Method for creating a new publisher in Dynamics CRM. /// </summary> /// <param name="uniqueName">The publisher's unique name.</param> /// <param name="friendlyName">The publisher's friendly name.</param> /// <param name="supportingWebsiteUrl">The supporting web site URL.</param> /// <param name="customizationPrefix">The customisation prefix.</param> /// <param name="eMailAddress">The publisher's e-amil address.</param> /// <param name="description">The publisher's description.</param> /// <returns>A new publisher object containing the details of the new publisher.</returns> public Publisher CreatePublisher(string uniqueName, string friendlyName, Uri supportingWebsiteUrl, string customizationPrefix, string eMailAddress, string description) { try { Publisher crmSdkPublisher = new Publisher(); using (CrmProxy = new OrganizationServiceProxy(ProxyUri, CrmConnection.HomeRealmUri, CrmConnection.ClientCredentials, CrmConnection.DeviceCredentials)) { CrmProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior()); CrmProxy.Timeout = new TimeSpan(0, 10, 0); CrmService = (IOrganizationService)CrmProxy; if (supportingWebsiteUrl != null) { crmSdkPublisher = new Publisher { UniqueName = uniqueName, FriendlyName = friendlyName, SupportingWebsiteUrl = supportingWebsiteUrl.AbsoluteUri, CustomizationPrefix = customizationPrefix, EMailAddress = eMailAddress, Description = description }; QueryExpression queryPublisher = new QueryExpression { EntityName = Publisher.EntityLogicalName, ColumnSet = new ColumnSet("publisherid", "customizationprefix"), Criteria = new FilterExpression() }; queryPublisher.Criteria.AddCondition("uniquename", ConditionOperator.Equal, crmSdkPublisher.UniqueName); EntityCollection queryPublisherResults; queryPublisherResults = CrmService.RetrieveMultiple(queryPublisher); Publisher SDKPublisherResults = null; if (queryPublisherResults.Entities.Count > 0) { SDKPublisherResults = (Publisher)queryPublisherResults.Entities[0]; crmSdkPublisher.Id = (Guid)SDKPublisherResults.PublisherId; crmSdkPublisher.CustomizationPrefix = SDKPublisherResults.CustomizationPrefix; } if (SDKPublisherResults == null) { crmSdkPublisher.Id = CrmService.Create(crmSdkPublisher); } } } return crmSdkPublisher; } catch (FaultException<OrganizationServiceFault>) { throw; } } /// <summary> /// Method to retrieve the default publisher. /// </summary> /// <param name="organizationName">Name of the organization.</param> /// <returns> /// A publisher object containing the details of the new publisher. /// </returns> public Publisher RetrieveDefaultPublisher(string organizationName) { try { string DefaultPublisherPrefix = "DefaultPublisher"; Publisher DefaultPublisher = RetrievePublisherByName(DefaultPublisherPrefix, organizationName); return DefaultPublisher; } catch (FaultException<OrganizationServiceFault>) { throw; } } /// <summary> /// Retrieves the publisher by name. /// </summary> /// <param name="defaultPublisherPrefix">The default publisher prefix.</param> /// <param name="organizationName">Name of the organization.</param> /// <returns></returns> public Publisher RetrievePublisherByName(string defaultPublisherPrefix, string organizationName) { Publisher DefaultPublisher = new Publisher(); using (CrmProxy = new OrganizationServiceProxy(ProxyUri, CrmConnection.HomeRealmUri, CrmConnection.ClientCredentials, CrmConnection.DeviceCredentials)) { CrmProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior()); CrmProxy.Timeout = new TimeSpan(0, 10, 0); CrmService = (IOrganizationService)CrmProxy; QueryExpression queryDefaultPublisher = new QueryExpression { EntityName = Publisher.EntityLogicalName, ColumnSet = new ColumnSet(true), Criteria = new FilterExpression() }; queryDefaultPublisher.Criteria.AddCondition("uniquename", ConditionOperator.Equal, defaultPublisherPrefix + organizationName); Entity publisherEntity = CrmService.RetrieveMultiple(queryDefaultPublisher).Entities[0]; if (publisherEntity != null) { DefaultPublisher = publisherEntity.ToEntity<Publisher>(); } } return DefaultPublisher; } /// <summary> /// Method to create a new solution in Dynamics CRM. /// </summary> /// <param name="uniqueName">The unique name of the solution.</param> /// <param name="friendlyName">The friendly name of the solution.</param> /// <param name="publisherId">The identity of the publisher.</param> /// <param name="description">The description of the solution.</param> /// <param name="version">The version of the solution.</param> /// <returns>A new solution object containing the details of the new solution.</returns> public Solution CreateSolution(string uniqueName, string friendlyName, Guid publisherId, string description, string version) { try { using (CrmProxy = new OrganizationServiceProxy(ProxyUri, CrmConnection.HomeRealmUri, CrmConnection.ClientCredentials, CrmConnection.DeviceCredentials)) { CrmProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior()); CrmProxy.Timeout = new TimeSpan(0, 10, 0); CrmService = (IOrganizationService)CrmProxy; Solution solution = new Solution { UniqueName = uniqueName, FriendlyName = friendlyName, PublisherId = new EntityReference(Publisher.EntityLogicalName, publisherId), Description = description, Version = version }; QueryExpression querySampleSolution = new QueryExpression { EntityName = Solution.EntityLogicalName, ColumnSet = new ColumnSet(), Criteria = new FilterExpression() }; querySampleSolution.Criteria.AddCondition("uniquename", ConditionOperator.Equal, solution.UniqueName); EntityCollection querySampleSolutionResults = CrmService.RetrieveMultiple(querySampleSolution); Solution SampleSolutionResults = null; if (querySampleSolutionResults.Entities.Count > 0) { SampleSolutionResults = (Solution)querySampleSolutionResults.Entities[0]; solution.Id = (Guid)SampleSolutionResults.SolutionId; } if (SampleSolutionResults == null) { solution.Id = CrmService.Create(solution); } return solution; } } catch (FaultException<OrganizationServiceFault>) { throw; } } /// <summary> /// Method to retrieve a solution from Dynamics CRM. /// </summary> /// <param name="uniqueName">The unique name of the solution to retrieve.</param> /// <returns>A solution object containing the details of the retrieved solution.</returns> public Solution RetrieveSolution(string uniqueName) { try { Solution solution = new Solution(); using (CrmProxy = new OrganizationServiceProxy(ProxyUri, CrmConnection.HomeRealmUri, CrmConnection.ClientCredentials, CrmConnection.DeviceCredentials)) { CrmProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior()); CrmProxy.Timeout = new TimeSpan(0, 10, 0); CrmService = (IOrganizationService)CrmProxy; QueryExpression querySampleSolution = new QueryExpression { EntityName = Solution.EntityLogicalName, ColumnSet = new ColumnSet(true), Criteria = new FilterExpression() }; querySampleSolution.Criteria.AddCondition("uniquename", ConditionOperator.Equal, uniqueName); EntityCollection entityCollection = CrmService.RetrieveMultiple(querySampleSolution); if (entityCollection != null && entityCollection.Entities.Count > 0) { Entity solutionEntity = entityCollection.Entities[0]; if (solutionEntity != null) { solution = solutionEntity.ToEntity<Solution>(); } } else { querySampleSolution.Criteria = new FilterExpression(); querySampleSolution.Criteria.AddCondition("friendlyname", ConditionOperator.Equal, uniqueName); entityCollection = CrmService.RetrieveMultiple(querySampleSolution); if (entityCollection != null && entityCollection.Entities.Count > 0) { Entity solutionEntity = entityCollection.Entities[0]; if (solutionEntity != null) { solution = solutionEntity.ToEntity<Solution>(); } } } } return solution; } catch (FaultException<OrganizationServiceFault>) { throw; } } /// <summary> /// Method to delete a solution from Dynamics CRM. /// </summary> /// <param name="solution">The solution object containing the details of the solution to delete.</param> public void DeleteSolution(Entity solution) { try { using (CrmProxy = new OrganizationServiceProxy(ProxyUri, CrmConnection.HomeRealmUri, CrmConnection.ClientCredentials, CrmConnection.DeviceCredentials)) { CrmProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior()); CrmProxy.Timeout = new TimeSpan(0, 10, 0); CrmService = (IOrganizationService)CrmProxy; if (solution != null) { CrmService.Delete(Solution.EntityLogicalName, solution.Id); } } } catch (FaultException<OrganizationServiceFault>) { throw; } } /// <summary> /// Overloaded method to delete a solution from Dynamics CRM. /// </summary> /// <param name="solutionUniqueName">The unique name of the solution to delete from Dynamics CRM.</param> public void DeleteSolution(string solutionUniqueName) { try { using (CrmProxy = new OrganizationServiceProxy(ProxyUri, CrmConnection.HomeRealmUri, CrmConnection.ClientCredentials, CrmConnection.DeviceCredentials)) { CrmProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior()); CrmProxy.Timeout = new TimeSpan(0, 10, 0); CrmService = (IOrganizationService)CrmProxy; CrmService.Delete(Solution.EntityLogicalName, GetSolutionIdByUniqueName(solutionUniqueName)); } } catch (FaultException<OrganizationServiceFault>) { throw; } } /// <summary> /// Method to import a solution into Dynamics CRM. /// </summary> /// <param name="solutionFilePath">The path and file name of the file to import.</param> public void ImportSolution(string solutionFilePath) { try { byte[] fileBytes = File.ReadAllBytes(solutionFilePath); ImportSolutionRequest importSolutionRequest = new ImportSolutionRequest() { CustomizationFile = fileBytes }; using (CrmProxy = new OrganizationServiceProxy(ProxyUri, CrmConnection.HomeRealmUri, CrmConnection.ClientCredentials, CrmConnection.DeviceCredentials)) { CrmProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior()); CrmProxy.Timeout = new TimeSpan(0, 10, 0); CrmService = (IOrganizationService)CrmProxy; CrmService.Execute(importSolutionRequest); } } catch (FaultException<OrganizationServiceFault>) { throw; } } /// <summary> /// Method to export a solution from Dynamics CRM. /// </summary> /// <param name="outputDir">The path in which the exported solution file should be placed.</param> /// <param name="solutionUniqueName">The unique name of the solution to export.</param> /// <param name="managed">Should the solution being exported generate a managed or unmanaged solution file.</param> /// <returns>The file name as a string (not the path as that was an input parameter).</returns> public string ExportSolution(string outputDir, string solutionUniqueName, bool managed) { try { if (!string.IsNullOrEmpty(outputDir) && !outputDir.EndsWith(@"\", false, CultureInfo.CurrentCulture)) { outputDir += @"\"; } string ManagedStatus; if (managed) { ManagedStatus = "Managed"; } else { ManagedStatus = "UnManaged"; } ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest(); exportSolutionRequest.Managed = managed; exportSolutionRequest.SolutionName = solutionUniqueName; ExportSolutionResponse exportSolutionResponse; using (CrmProxy = new OrganizationServiceProxy(ProxyUri, CrmConnection.HomeRealmUri, CrmConnection.ClientCredentials, CrmConnection.DeviceCredentials)) { CrmProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior()); CrmProxy.Timeout = new TimeSpan(0, 10, 0); CrmService = (IOrganizationService)CrmProxy; exportSolutionResponse = (ExportSolutionResponse)CrmService.Execute(exportSolutionRequest); } byte[] exportXml = exportSolutionResponse.ExportSolutionFile; string filename = solutionUniqueName + "_" + ManagedStatus + ".zip"; File.WriteAllBytes(outputDir + filename, exportXml); return filename; } catch (FaultException<OrganizationServiceFault>) { throw; } } /// <summary> /// Method to roll back a solution. /// /// This is method is used where a backup copy of the solution is first exported as a possible restoration option before another file is imported. /// </summary> /// <param name="uniqueName">The unique name of the solution to roll back.</param> /// <param name="solutionFullPath">The path and file name of the solution file to be imported in order to restore the previous state of the solution.</param> public void RollbackSolution(string uniqueName, string solutionFullPath) { try { DeleteSolution(uniqueName); ImportSolution(solutionFullPath); using (CrmProxy = new OrganizationServiceProxy(ProxyUri, CrmConnection.HomeRealmUri, CrmConnection.ClientCredentials, CrmConnection.DeviceCredentials)) { CrmProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior()); CrmProxy.Timeout = new TimeSpan(0, 10, 0); CrmService = (IOrganizationService)CrmProxy; CrmService.Execute(new PublishAllXmlRequest()); } } catch (FaultException<OrganizationServiceFault>) { throw; } } /// <summary> /// Method to retrieve a list of Dynamics CRM Solutions. /// </summary> /// <returns>A list object containing a collection of solution objects.</returns> public Collection<Solution> RetrieveAllSolutions() { try { Collection<Solution> solutions = new Collection<Solution>(); using (CrmProxy = new OrganizationServiceProxy(ProxyUri, CrmConnection.HomeRealmUri, CrmConnection.ClientCredentials, CrmConnection.DeviceCredentials)) { CrmProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior()); CrmProxy.Timeout = new TimeSpan(0, 10, 0); CrmService = (IOrganizationService)CrmProxy; OrganizationServiceContext ServerContext = new OrganizationServiceContext(CrmService); var items = from item in ServerContext.CreateQuery<Solution>() orderby item.Version ascending where item.IsVisible == true select item; foreach (var item in items) { solutions.Add(item); } } return solutions; } catch (FaultException<OrganizationServiceFault>) { throw; } } /// <summary> /// Method to retrieve the solution identitifier by providing the solution's unique name. /// </summary> /// <param name="uniqueName">The solution's unique name.</param> /// <returns>The solution identifier.</returns> public Guid GetSolutionIdByUniqueName(string uniqueName) { try { Guid solutionQuery; using (CrmProxy = new OrganizationServiceProxy(ProxyUri, CrmConnection.HomeRealmUri, CrmConnection.ClientCredentials, CrmConnection.DeviceCredentials)) { CrmProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior()); CrmProxy.Timeout = new TimeSpan(0, 10, 0); CrmService = (IOrganizationService)CrmProxy; OrganizationServiceContext ServerContext = new OrganizationServiceContext(CrmService); solutionQuery = (from item in ServerContext.CreateQuery<Solution>() where item.UniqueName == uniqueName select item.SolutionId.Value).Single<Guid>(); } return solutionQuery; } catch (FaultException<OrganizationServiceFault>) { throw; } } /// <summary> /// Method to add a component to a solution. /// </summary> /// <param name="solutionComponentType">The component type.</param> /// <param name="componentId">The component's identifier.</param> /// <param name="solutionUniqueName">The solution's unique name.</param> /// <returns>The result of the execution.</returns> public AddSolutionComponentResponse AddComponentToSolution(componenttype solutionComponentType, Guid componentId, string solutionUniqueName) { try { AddSolutionComponentRequest addSolutionComponentRequest = new AddSolutionComponentRequest() { ComponentType = (int)solutionComponentType, ComponentId = componentId, SolutionUniqueName = solutionUniqueName }; using (CrmProxy = new OrganizationServiceProxy(ProxyUri, CrmConnection.HomeRealmUri, CrmConnection.ClientCredentials, CrmConnection.DeviceCredentials)) { CrmProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior()); CrmProxy.Timeout = new TimeSpan(0, 10, 0); CrmService = (IOrganizationService)CrmProxy; return (AddSolutionComponentResponse)CrmService.Execute(addSolutionComponentRequest); } } catch (FaultException<OrganizationServiceFault>) { throw; } } /// <summary> /// Publishes the customizations. /// </summary> public void PublishCustomizations() { try { using (CrmProxy = new OrganizationServiceProxy(ProxyUri, CrmConnection.HomeRealmUri, CrmConnection.ClientCredentials, CrmConnection.DeviceCredentials)) { CrmProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior()); CrmProxy.Timeout = new TimeSpan(0, 10, 0); CrmService = (IOrganizationService)CrmProxy; CrmService.Execute(new PublishAllXmlRequest()); } } catch (ApplicationException) { throw; } } #endregion }
The Solution class makes use of a CrmConnection class as follows:
/// <summary> /// Crm Connection Class. /// </summary> public class XrmConnection { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="XrmConnection"/> class. /// </summary> public XrmConnection() { } /// <summary> /// Initializes a new instance of the <see cref="XrmConnection"/> class. /// </summary> /// <param name="discoveryServer">The discovery server.</param> /// <param name="port">The port.</param> /// <param name="scheme">The scheme.</param> /// <param name="organization">The organization.</param> /// <param name="domain">The domain.</param> /// <param name="userName">Name of the user.</param> /// <param name="password">The password.</param> public XrmConnection(string discoveryServer, string port, string scheme, string organization, string domain, string userName, string password) { DiscoveryServer = discoveryServer; Port = port; Scheme = scheme; Domain = domain; UserName = userName; Password = password; Organization = organization; InstantiateOrganization(); InstantiateConnection(); } #endregion #region Properties /// <summary> /// Gets or sets the server. /// </summary> /// <value> /// The server. /// </value> public string DiscoveryServer { get; set; } /// <summary> /// Gets or sets the port. /// </summary> /// <value> /// The port. /// </value> public string Port { get; set; } /// <summary> /// Gets or sets the scheme. /// </summary> /// <value> /// The scheme. /// </value> public string Scheme { get; set; } /// <summary> /// Gets or sets the organization. /// </summary> /// <value> /// The organization. /// </value> public string Organization { get; set; } /// <summary> /// Gets or sets the domain. /// </summary> /// <value> /// The domain. /// </value> public string Domain { get; set; } /// <summary> /// Gets or sets the name of the user. /// </summary> /// <value> /// The name of the user. /// </value> public string UserName { get; set; } /// <summary> /// Gets or sets the password. /// </summary> /// <value> /// The password. /// </value> public string Password { get; set; } /// <summary> /// Gets or sets the connection. /// </summary> /// <value> /// The connection. /// </value> [CLSCompliant(false)] public CrmConnection Connection { get; set; } /// <summary> /// Gets or sets the discovery service URI. /// </summary> /// <value> /// The discovery service URI. /// </value> private Uri discoveryServiceUri { get; set; } /// <summary> /// Gets or sets the orgs. /// </summary> /// <value> /// The orgs. /// </value> private OrganizationDetailCollection Orgs { get; set; } /// <summary> /// Gets or sets the org. /// </summary> /// <value> /// The org. /// </value> private OrganizationDetail Org { get; set; } /// <summary> /// Gets or sets the org request. /// </summary> /// <value> /// The org request. /// </value> private RetrieveOrganizationsRequest OrgRequest { get; set; } /// <summary> /// Gets or sets the org response. /// </summary> /// <value> /// The org response. /// </value> private RetrieveOrganizationsResponse OrgResponse { get; set; } /// <summary> /// Gets or sets the org detail. /// </summary> /// <value> /// The org detail. /// </value> private OrganizationDetail orgDetail { get; set; } #endregion #region Private Methods /// <summary> /// Gets the organization. /// </summary> private void InstantiateOrganization() { ClientCredentials clientCredentials = new ClientCredentials(); if (!string.IsNullOrEmpty(Domain)) { clientCredentials.Windows.ClientCredential.Domain = Domain; } if (!string.IsNullOrEmpty(UserName)) { clientCredentials.Windows.ClientCredential.UserName = UserName; } if (!string.IsNullOrEmpty(Password)) { clientCredentials.Windows.ClientCredential.Password = Password; } if (string.IsNullOrEmpty(UserName)) { clientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials; } if (!string.IsNullOrEmpty(Port)) { discoveryServiceUri = new Uri(String.Format(CultureInfo.CurrentCulture, "{0}://{1}:{2}/XRMServices/2011/Discovery.svc", Scheme, DiscoveryServer, Port)); } else { discoveryServiceUri = new Uri(String.Format(CultureInfo.CurrentCulture, "{0}://{1}/XRMServices/2011/Discovery.svc", Scheme, DiscoveryServer)); } using (DiscoveryServiceProxy ServiceProxy = new DiscoveryServiceProxy(discoveryServiceUri, null, clientCredentials, clientCredentials)) { Orgs = DiscoverOrganizations(ServiceProxy); Org = FindOrganization(Orgs); Organization = Org.UniqueName; } } /// <summary> /// Discovers the Dynamics CRM Service URL. /// </summary> /// <param name="service">Discovery service.</param> /// <returns>Organisation detail collection.</returns> private OrganizationDetailCollection DiscoverOrganizations(IDiscoveryService service) { try { OrgRequest = new RetrieveOrganizationsRequest(); OrgResponse = (RetrieveOrganizationsResponse)service.Execute(OrgRequest); return OrgResponse.Details; } catch (FaultException<OrganizationServiceFault>) { throw; } } /// <summary> /// Finds the organisation. /// </summary> /// <param name="orgDetails">Organisation detail collection.</param> /// <returns>Organisation detail.</returns> private OrganizationDetail FindOrganization(OrganizationDetailCollection orgDetails) { try { orgDetail = null; foreach (OrganizationDetail detail in orgDetails) { if (String.Compare(detail.UniqueName, Organization, CultureInfo.CurrentCulture, CompareOptions.None) == 0) { orgDetail = detail; break; } if (String.Compare(detail.FriendlyName, Organization, CultureInfo.CurrentCulture, CompareOptions.None) == 0) { orgDetail = detail; break; } } return orgDetail; } catch (FaultException<OrganizationServiceFault>) { throw; } } /// <summary> /// Instantiates the connection. /// </summary> private void InstantiateConnection() { Connection = new CrmConnection(); string connectionString = string.Format(CultureInfo.CurrentCulture, "Url={0}://{1}/{2}", Scheme, DiscoveryServer, Organization); if (!string.IsNullOrEmpty(Port)) { connectionString = string.Format(CultureInfo.CurrentCulture, "Url={0}://{1}:{2}/{3}", Scheme, DiscoveryServer, Port, Organization); } if (!string.IsNullOrEmpty(Domain)) { connectionString = string.Format(CultureInfo.CurrentCulture, "{0}; Domain={1}", connectionString, Domain); } if (!string.IsNullOrEmpty(UserName)) { connectionString = string.Format(CultureInfo.CurrentCulture, "{0}; Username={1}", connectionString, UserName); } if (!string.IsNullOrEmpty(Password)) { connectionString = string.Format(CultureInfo.CurrentCulture, "{0}; Password={1}", connectionString, Password); } Connection = CrmConnection.Parse(connectionString); if (string.IsNullOrEmpty(UserName)) { Connection.ClientCredentials = new ClientCredentials(); Connection.ClientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials; } Connection.DeviceCredentials = Connection.ClientCredentials; } #endregion }
All the methods of the Solution class work fine when unit tested as follows:
#region Properties private string DiscoveryServer = ConfigurationManager.AppSettings["DiscoveryServer"]; private string Port = ConfigurationManager.AppSettings["Port"]; private string Scheme = ConfigurationManager.AppSettings["Scheme"]; private string Organization = ConfigurationManager.AppSettings["Organization"]; private string Domain = ConfigurationManager.AppSettings["Domain"]; private string UserName = ConfigurationManager.AppSettings["UserName"]; private string Password = ConfigurationManager.AppSettings["Password"]; private const string _entityDisplayName = "My Test Entity"; /// <summary> /// Gets the display name of the entity. /// </summary> /// <value> /// The display name of the entity. /// </value> private static string EntityDisplayName { get { return _entityDisplayName; } } private const string _entityDisplayCollectionName = "My Test Entities"; /// <summary> /// Gets the name of the entity display collection. /// </summary> /// <value> /// The name of the entity display collection. /// </value> private static string EntityDisplayCollectionName { get { return _entityDisplayCollectionName; } } private const string _entityDescription = "A test entity for me"; /// <summary> /// Gets the entity description. /// </summary> private static string EntityDescription { get { return _entityDescription; } } private const string _primaryAttributeSchemaName = "an_testattribute"; /// <summary> /// Gets the name of the primary attribute schema. /// </summary> /// <value> /// The name of the primary attribute schema. /// </value> private static string PrimaryAttributeSchemaName { get { return _primaryAttributeSchemaName; } } private const string _primaryAttributeDisplayName = "My Test Entity"; /// <summary> /// Gets the display name of the primary attribute. /// </summary> /// <value> /// The display name of the primary attribute. /// </value> private static string PrimaryAttributeDisplayName { get { return _primaryAttributeDisplayName; } } private const string _primaryAttributeDescription = "A test attribute for me"; /// <summary> /// Gets the primary attribute description. /// </summary> private static string PrimaryAttributeDescription { get { return _primaryAttributeDescription; } } private const string _uniqueName = "LbcTestSolution"; /// <summary> /// Gets the name of the unique. /// </summary> /// <value> /// The name of the unique. /// </value> private static string UniqueName { get { return _uniqueName; } } private const string _friendlyName = "My Test Solution"; /// <summary> /// Gets the name of the friendly. /// </summary> /// <value> /// The name of the friendly. /// </value> private static string FriendlyName { get { return _friendlyName; } } private const string _description = "This solution was created for me."; /// <summary> /// Gets the description. /// </summary> private static string Description { get { return _description; } } private const string _version = "1.01"; /// <summary> /// Gets the solution version. /// </summary> private static string Version { get { return _version; } } /// <summary> /// Publisher Id. /// </summary> private Guid _publisherId; /// <summary> /// Publisher Id. /// </summary> public Guid PublisherId { get { return _publisherId; } set { _publisherId = value; } } /// <summary> /// Solution. /// </summary> private Solution _solution; /// <summary> /// Solution. /// </summary> public Solution Solution { get { return _solution; } set { _solution = value; } } #endregion #region Unit Tests /// <summary> ///A test for CreatePublisher ///</summary> [TestMethod()] public void CreatePublisherTest() { try { Solution target = new Solution(new XrmConnection(DiscoveryServer, Port, Scheme, Organization, Domain, UserName, Password).Connection, Organization); string uniqueName = "LbcTestPublisher"; string friendlyName = "My Test Publisher"; string supportingWebsiteUrl = "localhost:5555"; string customizationPrefix = "gb"; string eMailAddress = "publisher@croydon-tl.local"; string description = "This publisher was created for me"; Publisher publisher = target.CreatePublisher(uniqueName, friendlyName, new Uri(supportingWebsiteUrl), customizationPrefix, eMailAddress, description); using (XrmService xrmService = new XrmService(new XrmConnection(DiscoveryServer, Port, Scheme, Organization, Domain, UserName, Password).Connection)) { xrmService.Service.Delete(Publisher.EntityLogicalName, publisher.Id); } } catch (FaultException<OrganizationServiceFault> exception) { Assert.Fail("An error occurred: " + exception.Message); } } /// <summary> ///A test for RetrieveDefaultPublisher ///</summary> [TestMethod()] public void RetrieveDefaultPublisherTest() { try { Solution target = new Solution(new XrmConnection(DiscoveryServer, Port, Scheme, Organization, Domain, UserName, Password).Connection, Organization); target.RetrieveDefaultPublisher(); } catch (FaultException<OrganizationServiceFault> exception) { Assert.Fail("An error occurred: " + exception.Message); } } /// <summary> ///A test for CreateSolution ///</summary> [TestMethod()] public void CreateSolutionTest() { try { Solution target = new Solution(new XrmConnection(DiscoveryServer, Port, Scheme, Organization, Domain, UserName, Password).Connection, Organization); Solution solution = CreateSolution(target); target.DeleteSolution(solution); } catch (FaultException<OrganizationServiceFault> exception) { Assert.Fail("An error occurred: " + exception.Message); } } /// <summary> ///A test for RetrieveSolution ///</summary> [TestMethod()] public void RetrieveSolutionTest() { try { Solution target = new Solution(new XrmConnection(DiscoveryServer, Port, Scheme, Organization, Domain, UserName, Password).Connection, Organization); Guid publisherId = target.RetrieveDefaultPublisher().PublisherId.Value; Solution solution = target.CreateSolution(UniqueName, FriendlyName, publisherId, Description, Version); solution = target.RetrieveSolution(UniqueName); using (XrmService xrmService = new XrmService(new XrmConnection(DiscoveryServer, Port, Scheme, Organization, Domain, UserName, Password).Connection)) { xrmService.Service.Delete(Solution.EntityLogicalName, solution.Id); } } catch (FaultException<OrganizationServiceFault> exception) { Assert.Fail("An error occurred: " + exception.Message); } } /// <summary> ///A test for RetrieveAllSolutions ///</summary> [TestMethod()] public void RetrieveAllSolutionsTest() { try { Solution target = new Solution(new XrmConnection(DiscoveryServer, Port, Scheme, Organization, Domain, UserName, Password).Connection, Organization); Solution solution = CreateSolution(target); Collection<Solution> solutions = target.RetrieveAllSolutions(); foreach (var item in solutions) { Debug.WriteLine("UniqueName:" + " " + item.UniqueName); Debug.WriteLine("Version:" + " " + item.Version); Debug.WriteLine("FriendlyName:" + " " + item.FriendlyName); Debug.WriteLine("IsManaged:" + " " + item.IsManaged); } target.DeleteSolution(solution); } catch (FaultException<OrganizationServiceFault> exception) { Assert.Fail("An error occurred: " + exception.Message); } } /// <summary> ///A test for GetSolutionGuidByUniqueName ///</summary> [TestMethod()] public void GetSolutionIdByUniqueNameTest() { try { Solution target = new Solution(new XrmConnection(DiscoveryServer, Port, Scheme, Organization, Domain, UserName, Password).Connection, Organization); Solution solution = CreateSolution(target); target.GetSolutionIdByUniqueName(UniqueName); target.DeleteSolution(solution); } catch (FaultException<OrganizationServiceFault> exception) { Assert.Fail("An error occurred: " + exception.Message); } } /// <summary> ///A test for ExportSolution and ImportSolution and RollBackSolution ///</summary> [TestMethod()] public void ExportImportRollbackSolutionTest() { try { Solution target = new Solution(new XrmConnection(DiscoveryServer, Port, Scheme, Organization, Domain, UserName, Password).Connection, Organization); PublisherId = target.RetrieveDefaultPublisher().PublisherId.Value; target.CreateSolution(UniqueName, FriendlyName, PublisherId, Description, Version); target.RetrieveSolution(UniqueName); string outputDir = Environment.GetEnvironmentVariable("TEMP"); DirectoryInfo directory = new DirectoryInfo(outputDir); if (!directory.Exists) { directory.Create(); } bool managed = false; string fileName = target.ExportSolution(outputDir, UniqueName, managed); string fileLocation = outputDir + @"\" + fileName; target.ImportSolution(fileLocation); target.RollbackSolution(UniqueName, fileLocation); target.DeleteSolution(UniqueName); } catch (FaultException<OrganizationServiceFault> exception) { Assert.Fail("An error occurred: " + exception.Message); } } /// <summary> ///A test for AddComponentToSolution ///</summary> [TestMethod()] public void AddComponentToSolutionTest() { try { Solution target = new Solution(new XrmConnection(DiscoveryServer, Port, Scheme, Organization, Domain, UserName, Password).Connection, Organization); XrmMetadata xrmMetadata = new XrmMetadata(new XrmConnection(DiscoveryServer, Port, Scheme, Organization, Domain, UserName, Password).Connection); string entityName = "an_testentity"; Guid componentId = xrmMetadata.CreateEntity((int)LanguageCode.EnglishUnitedStates, entityName, EntityDisplayName, EntityDisplayCollectionName, EntityDescription, PrimaryAttributeSchemaName, PrimaryAttributeDisplayName, PrimaryAttributeDescription).EntityId; CreateSolution(target); target.AddComponentToSolution(componenttype.Entity, componentId, UniqueName); xrmMetadata.DeleteEntity(entityName); target.DeleteSolution(UniqueName); } catch (FaultException<OrganizationServiceFault> exception) { Assert.Fail("An error occurred: " + exception.Message); } } #endregion #region Methods /// <summary> /// A method to create a Solution in Dynamics CRM. /// </summary> /// <param name="target">The Solution object.</param> /// <returns>A Solution object.</returns> private Solution CreateSolution(Solution target) { try { PublisherId = target.RetrieveDefaultPublisher().PublisherId.Value; Solution = target.CreateSolution(UniqueName, FriendlyName, PublisherId, Description, Version); return Solution; } catch (FaultException<OrganizationServiceFault>) { throw; } } #endregion
I am suspecting that this may be a DNS or other network issue. Can anyone help?