0

I am following the Build a console app that connects to CRM guide, and when I try to run it, it throws a NullReferenceException on SaveChanges(). (See bottom of the post for edits)

Here's the code:

using System;
using System.Linq;
using Xrm;
using Microsoft.Xrm.Client;

namespace CRM_Console_Application
{
    class Program
    {
        static void Main(string[] args)
        {

            var xrm = new XrmServiceContext(new Microsoft.Xrm.Client.Services.OrganizationService(new CrmConnection("Xrm")));

            var allisonBrown = new Contact
            {
                FirstName = "Allison",
                LastName = "Brown",
                Address1_Line1 = "23 Market St.",
                Address1_City = "Sammamish",
                Address1_StateOrProvince = "MT",
                Address1_PostalCode = "99999",
                Telephone1 = "12345678",
                EMailAddress1 = "allison.brown@example.com"
            };

            xrm.AddObject(allisonBrown);
            xrm.SaveChanges(); //Here is where it throws an Exception
            WriteExampleContacts(xrm);
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }

        private static void WriteExampleContacts(XrmServiceContext xrm)
        {
            var exampleContacts = xrm.ContactSet.Where(contact => contact.EMailAddress1.EndsWith("@example.com"));
            foreach (var contact in exampleContacts)
                Console.WriteLine(contact.FullName);
        }
    }
}

Also, I am using a Xrm.cs file generated by the CrmSvcUtil tool from the CRM SDK, and an App.config, as follows.

<!--App.config-->
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="microsoft.xrm.client" type="Microsoft.Xrm.Client.Configuration.CrmSection, Microsoft.Xrm.Client"/>
  </configSections>
  <connectionStrings>
    <add name="Xrm" connectionString="Server=http://[MyCompanyName].crm.dynamics.com; Username=[MyUsername]; Password=[MyPassword]"/>
  </connectionStrings>
  <microsoft.xrm.client>
    <contexts default="Xrm">
      <add name="Xrm" type="Xrm.XrmServiceContext, Xrm" connectionStringName="Xrm"/>
    </contexts>
  </microsoft.xrm.client>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
</configuration>

But I get this error and can't seem to figure out why. Also, I tried it out with Microsoft's source code and it returns the same error:

An error occured while processing this request. System.NullReferenceException: Object reference not set to an instance of an object. at Microsoft.Xrm.Sdk.Client.ProxyTypesBehavior.System.ServiceModel.Description.IEndpointBehavior.ApplyClientBehavior(ServiceEndpoint serviceEndpoint, ClientRuntime behavior) at Microsoft.Xrm.Client.Services.OrganizationService.CreateServiceConfiguration(CrmConnection connection) at Microsoft.Xrm.Client.Services.OrganizationService.GetServiceConfiguration(CrmConnection connection) at Microsoft.Xrm.Client.Services.OrganizationService.ToOrganizationServiceProxy(CrmConnection connection) at Microsoft.Xrm.Client.Services.OrganizationService.ToOrganizationService(CrmConnection connection) at Microsoft.Xrm.Client.Services.OrganizationService.<>c__DisplayClass2.<.ctor>b__0() at System.Lazy1.CreateValue() at System.Lazy1.LazyInitValue() at System.Lazy1.get_Value() at Microsoft.Xrm.Client.Services.OrganizationService.InnerOrganizationService.UsingService[TResult](Func2 action) at Microsoft.Xrm.Client.Services.OrganizationService.Execute(OrganizationRequest request) at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.Execute(OrganizationRequest request) at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.SaveChange(OrganizationRequest request, IList`1 results)

What am I missing? Is there something I'm doing wrong?

Thanks in advance.

EDIT: No, the "Duplicate" link does not help, since I cannot debug what XrmServiceContext.SaveChanges() does in order to get to the missing/null object.

EDIT2:

I modified my console app (for connnection testing) and now it returns that the credentials must be populated, but the login info is already there. Same happens if I go

IServiceManagement<IOrganizationService> orgServiceManagement = ServiceConfigurationFactory.CreateManagement<IOrganizationSe‌​rvice>(new Uri(url)); 
Sdk.Client.AuthenticationCredentials credentials = new Sdk.Client.AuthenticationCredentials(); 
credentials.ClientCredentials.UserName.UserName = "MyUsername"; 
credentials.ClientCredentials.UserName.Password = "MyPassword"; 
orgServiceManagement.Authenticate(credentials);
Mayer M
  • 243
  • 1
  • 6
  • 17
  • Try if you can connect to CRM using constructor that is not making use of connection string (for example OrganizationServiceProxy(IServiceConfiguration serviceConfiguration, ClientCredentials clientCredentials)), if yes then for 99% it's bad connection string – pen2 Mar 07 '17 at 08:24
  • @pen2 Thank you for your reply. I used what you said, but when I do `var serviceConfiguration = ServiceConfigurationFactory.CreateConfiguration(new Uri (http://serverurl.crm.dynamics/Organization.svc));` it throws >Metadata Contains a Reference That Cannot be resolved – Mayer M Mar 07 '17 at 14:40
  • If I do that, the innerException says `CData elements not valid at top level of an XML document. Line 1, position 3`. – Mayer M Mar 07 '17 at 14:52
  • If I try the following code to test the connection: `WebRequest.DefaultWebProxy = WebRequest.GetSystemWebProxy(); WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials; var connection = XrmClient.CrmConnection.Parse(http://serverurl.crm.dynamics/Organization.svc); var orgService = new XrmClient.Services.OrganizationService(connection); var userId = ((WhoAmIResponse)orgService.Execute(new WhoAmIRequest())).UserId;` The exception is the same, but the innerException returns a 404. – Mayer M Mar 07 '17 at 14:52
  • Can you connect to your CRM using for example plugin registration tool from SDK or is also it throwing an exception? – pen2 Mar 08 '17 at 08:16
  • Yes. I can connect using the [plugin registration tool from SDK.](https://msdn.microsoft.com/en-us/library/gg309580.aspx) – Mayer M Mar 08 '17 at 17:06
  • I also used the AuthenticationWithNoHelp solution from Microsoft to log in with success. But I used the Discovery service instead of the Organization one, and can't figure how to connect using the Organization service. – Mayer M Mar 08 '17 at 17:13
  • I modified my console app and now it returns that the credentials must be populated, but the login info is already there. Same happens if I go `IServiceManagement orgServiceManagement = ServiceConfigurationFactory.CreateManagement(new Uri(url));` `Sdk.Client.AuthenticationCredentials credentials = new Sdk.Client.AuthenticationCredentials();` `credentials.ClientCredentials.UserName.UserName = "MyUsername";` `credentials.ClientCredentials.UserName.Password = "MyPassword";` `orgServiceManagement.Authenticate(credentials);` – Mayer M Mar 08 '17 at 17:27
  • What account type are you using to connect to CRM? If it is AD account then try adding domain in your connection string - I don't see it there. – pen2 Mar 09 '17 at 08:47
  • Also in one of your comment you are using address `http://serverurl.crm.dynamics/‌​Organization.svc`. Don't know how it should look in online but in on-premise it should be `http://serverurl.crm.dynamics/‌​XRMServices/2011/Organization.svc` - could you try to use similar? – pen2 Mar 09 '17 at 08:50
  • @pen2 I'm using an Office 365 online account. It uses OnlineFederation instead of ActiveDirectory – Mayer M Mar 09 '17 at 15:08
  • @pen2 yes, it should look like you said, but when using `OrganizationService` it adds the /XRMServices part. However, I tried using how it was supposed to go (with and without the .api.dynamics part according to my CRM site), but it returns the `clientCredentials.UserName.UserName or clientCredentials.Windows.ClientCredential.UserName MUST be populated!` error, evennthough I'm passing the Username and Password in the connectionString. It also throws `An unsecured or incorrectly secured fault was received from the other party.` if I use "MyUsername@myCRM365Site.onmicrosoft.com" as Username – Mayer M Mar 09 '17 at 15:25

0 Answers0