Skip to main content

Notifications

Announcements

No record found.

Dynamics 365 general forum

Access to Microsoft CRM Dynamics 365 from .Net

(0) ShareShare
ReportReport
Posted on by Microsoft Employee

Hello All,

I need access to CRM Dynamics 365 i use below code to access its worked fine with "ADFS (IFD) Authentication", but with CRM Online "Dynamics 365 https://OrgName.api.crm4.dynamics.com/XRMServices/2011/Organization.svc | Microsoft Dynamics 365

getting this Error:

An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail.

Server stack trace: 
   at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.ProcessReply(Message reply, SecurityProtocolCorrelationState correlationState, TimeSpan timeout)
   at System.ServiceModel.Channels.SecurityChannelFactory`1.SecurityRequestChannel.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]: 
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at System.ServiceModel.Security.IWSTrustContract.Issue(Message message)
   at System.ServiceModel.Security.WSTrustChannel.Issue(RequestSecurityToken rst, RequestSecurityTokenResponse& rstr)
   at Microsoft.Xrm.Sdk.Client.ServiceConfiguration`1.Issue(AuthenticationCredentials authenticationCredentials)
   at Microsoft.Xrm.Sdk.Client.ServiceConfiguration`1.AuthenticateInternal(AuthenticationCredentials authenticationCredentials)
   at Microsoft.Xrm.Sdk.Client.ServiceConfiguration`1.AuthenticateWithOrgIdForACS(AuthenticationCredentials authenticationCredentials, Uri identifier)
   at Microsoft.Xrm.Sdk.Client.ServiceConfiguration`1.AuthenticateOnlineFederationInternal(AuthenticationCredentials authenticationCredentials)
   at Microsoft.Xrm.Sdk.Client.ServiceConfiguration`1.Authenticate(AuthenticationCredentials authenticationCredentials)
   at Microsoft.Xrm.Sdk.Client.OrganizationServiceConfiguration.Authenticate(AuthenticationCredentials authenticationCredentials)


This my code:

public static IOrganizationService GetService()
{

    try
    {
        OrganizationServiceProxy _serviceProxy;

        string userName = "";
        string password = "";
        string domain = "";
        Uri serviceUri;


        serviceUri = new Uri(ConfigurationManager.AppSettings["URL"]);
        userName = ConfigurationManager.AppSettings["UserName"];
        password = ConfigurationManager.AppSettings["Password"];
        domain = ConfigurationManager.AppSettings["domain"];


        IServiceManagement<IOrganizationService> orgServiceManagement = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(serviceUri);

        if (orgServiceManagement.AuthenticationType == AuthenticationProviderType.Federation)
        {
            // ADFS (IFD) Authentication
            ClientCredentials clientCred = new ClientCredentials();
            clientCred.UserName.UserName = userName;
            clientCred.UserName.Password = password;
            _serviceProxy = new OrganizationServiceProxy(orgServiceManagement, clientCred);
        }
        else if (orgServiceManagement.AuthenticationType == AuthenticationProviderType.OnlineFederation)
        {
            // Online authentication
            AuthenticationCredentials authCredentials = new AuthenticationCredentials();

            authCredentials.ClientCredentials.UserName.UserName = userName;
            authCredentials.ClientCredentials.UserName.Password = password;

            // Error getting here
            AuthenticationCredentials tokenCredentials = orgServiceManagement.Authenticate(authCredentials); 


            _serviceProxy = new OrganizationServiceProxy(orgServiceManagement, tokenCredentials.SecurityTokenResponse);
        }
        else
        {
            // On-Premise, non-IFD authentication
            ClientCredentials credentials = new ClientCredentials();
            credentials.Windows.ClientCredential = new NetworkCredential(userName, password, domain);
            _serviceProxy = new OrganizationServiceProxy(serviceUri, null, credentials, null);
        }

        _serviceProxy.EnableProxyTypes();


    }
    catch (Exception e)
    {

    }

    return (IOrganizationService)_serviceProxy;
}


Help me on this!

Thanks!

Categories:
  • Mahmoud Fahmy Profile Picture
    Mahmoud Fahmy 25 on at
    RE: Access to Microsoft CRM Dynamics 365 from .Net

    Duplicate question

    [View:https://community.dynamics.com/crm/f/microsoft-dynamics-crm-forum/221058/access-to-microsoft-crm-dynamics-365-from-net:750:50]

  • Suggested answer
    Michel van den Brink Profile Picture
    Michel van den Brink 4,697 on at
    RE: Access to Microsoft CRM Dynamics 365 from .Net

    Hello sekar098,

    It looks like you're using a quite old version of the SDK libraries.
    Did you already update to the latest SDK version 9? Even if your Dynamics org isn't yet on version 9, updating your libraries will be a good way to get ready, they are backwards compatible.

    ---

    Also, I recommend that you use the CrmServiceClient from XrmTooling, as it is the latest and greatest from the Dynamics 365 (CRM) team.
    Docs: https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/xrm-tooling/use-crmserviceclient-constructors-connect#connect-to-includepndynamicscrmonlineincludespn-dynamics-crm-onlinemd-office-365 

    Going from your code example, this would be the most appropriate constructor. There's no need to provide a domain, as it is already included in your username, when working with Office 365.

    var crmSvc = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient("{UserName}", CrmServiceClient.MakeSecureString("{Password}"), "{CrmRegion}", "{OrgName}", useUniqueInstance: true, useSsl: true, isOffice365: true);

    The CrmServiceClient is available as a part of this NuGet package:
    https://www.nuget.org/packages/Microsoft.CrmSdk.XrmTooling.CoreAssembly/, which will also auto install all latest dependencies 

    Valid values for the {CrmRegion} parameter are: NorthAmerica, EMEA, APAC, SouthAmerica, Oceania, JPN, CAN, IND, and NorthAmerica2.  For the {OrgName} parameter, you can specify either the unique or friendly name.

    ---

    Lastly, to make sure, Dynamics 365 requires the use of TLS 1.2 for all incoming connections, which is the default for any project built in .NET Framework 4.6.1 or higher. If you are building your project in .NET Framework 4.5 or below, you should update your target framework to continue connecting to Dynamics 365 successfully. 

    ---

    I hope this helps you get connected. If you have any additional questions, please let me know.
    And if you found my answer helpful, please mark it as such/verified :-)

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

November Spotlight Star - Khushbu Rajvi

Congratulations to a top community star!

Forum Structure Changes Coming on 11/8!

In our never-ending quest to help the Dynamics 365 Community members get answers faster …

Dynamics 365 Community Platform update – Oct 28

Welcome to the next edition of the Community Platform Update. This is a status …

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,711 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,458 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans