locked
Dynamics CRM 2011 EndpointNotFoundException RRS feed

  • Question

  • 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?
    • Edited by Johan Küstner Monday, July 8, 2013 10:22 AM Missed a word.
    Monday, July 8, 2013 9:32 AM

All replies

  • The first thing I'd do is check if you can access the URL specified in the errir message from a browser on the same machine that you run the code on.

    If you still get a 404 error, it is instructive to know how quickly the error is returned. If it's very quick, then either the server is accessible but the path is wrong, or you've got a cached DNS lookup failure. If it's slow (10+ seconds), then you may have a firewall blocking the communication, or the server may be down.

    For DNS issues, try running ipconfig /displaydns from a command prompt to see if the name has been resolved. You can use ipconfig /flushdns to clear the local cache


    Microsoft CRM MVP - http://mscrmuk.blogspot.com/ http://www.excitation.co.uk

    Monday, July 8, 2013 10:23 AM
    Moderator
  • I can access the URL. Also, when running ipconfig /displaydns the DNS resolves. Any other ideas?
    Monday, July 8, 2013 10:29 AM
  • Go through SDk then connect and test your url.

    if connection establish then debug your code.


    Hope this helps. ----------------------------------------------------------------------- Santosh Bhagat If this post answers your question, please click "Mark As Answer" on the post and "Vote as Helpful"

    Monday, July 8, 2013 11:10 AM
  • I've done that.
    Monday, July 8, 2013 12:31 PM
  • Any other ideas?
    Monday, July 8, 2013 1:54 PM
  • What authentication is used - AD or Claims ? If it's claims then there will be a call to the ADFS server which may be the cause of the error. A tool like Fiddler may provide more useful information

    Is the error specific to the ImportSolutionRequest, or does it happen or all requests ?


    Microsoft CRM MVP - http://mscrmuk.blogspot.com/ http://www.excitation.co.uk

    Monday, July 8, 2013 3:20 PM
    Moderator
  • I've had a look at Fiddler and there are 3 calls to the same service (probably for organization service discovery) followed by the fourth call, which produces the 404 error. The error is specific to ImportSolutionRequest. The ExportSolutionRequest works fine.
    Monday, July 8, 2013 3:45 PM
  • Sorry - AD authentication.
    Monday, July 8, 2013 3:45 PM
  • Some further information: file size of the solution is 88851kB.
    Tuesday, July 9, 2013 7:38 AM
  • Some further information: file size of the managed solution is 88851kB.

    I tried this with a different managed solution of size 3kB that just has the Account Entity customisation and it worked. So it's definitely the file size that's causing the problem.

    Tuesday, July 9, 2013 7:50 AM
  • I think there's a limit of 64 MB on web service calls. I remember this limit from pre-WCF days, and it may be that there are WCF properties (probably server-side as well as client-side) that would allow you to extend it

    Microsoft CRM MVP - http://mscrmuk.blogspot.com/ http://www.excitation.co.uk

    Tuesday, July 9, 2013 8:26 AM
    Moderator
  • Do you know which settings to change to allow for a larger file?
    Tuesday, July 9, 2013 9:28 AM
  • I just had the same Issue in CRM2015.

    My solution was 26MB, I saw with feedler that the content sent was close to 46MB (because it is envolved in SOAP request, Base64, etc).

    I changed CRM webconfig in httpRuntime the attribute maxRequestLength to be 100000000 (100MB because my solution is still growing) and also maxAllowedContentLength in request filtering in IIS at CRM's website

    That's all

    • Proposed as answer by Charan Raju C R Wednesday, January 18, 2017 4:38 AM
    Wednesday, October 19, 2016 9:43 AM