Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

c# - Connection to CRM

I need my website to connect to CRM this is my code

        var organizationUri = new Uri(ConfigurationManager.AppSettings["CRMServerUrl"]);

        //Client credentials
        var credentials = new ClientCredentials();
        credentials.UserName.UserName = @"<user>";
        credentials.UserName.Password = "<password>";
        // Use the Microsoft Dynamics CRM Online connection string from the web.config file named "CrmConnectionStr".
        using (OrganizationServiceProxy _service = new OrganizationServiceProxy(organizationUri, null, credentials, null))
        {
            Response.Write("Connected");
        }

and this is in my web.config

 <add key="CRMServerUrl" value="http://XXXXX/XRMServices/2011/Organization.svc" />
<add key="username" value="<user>" />
<add key="password" value="<password>" />

it gives me this error message:

"A critical error has occurred. Unable to connect with CRM server. The caller was not authenticated by the service."

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should use the ?Simplified Connection provided by the ?Microsoft.Xrm.Client.CrmConnection type for an easier experience.

Steps are easy:

1) in the .config file add a connection string

<connectionStrings>
  <add name="CrmConnStr" connectionString="!SEE EBELOW!"/>
</connectionStrings>

2) In code, it goes like this:

// parameter is the name of the connection string
// NOTE: These "setup" declarations are slow, reuse them as much as possibile
var connection = new CrmConnection("CrmConnStr");

var service = new OrganizationService(connection);
var context = new CrmOrganizationServiceContext(connection);

About the connection string, if On-Premise WITHOUT IFD it should be

"Url=http[s]://serverurl/organization; Domain=DOMAIN; Username=USERNAME; Password=PASSWORD"
<!-- https is always nice, but it's not mandatory in this case -->

If On-Premise WITH IFD or Online it should be

"Url=https://org.server.url; Username=USERNAME; Password=PASSWORD"
<!-- https is of course mandatory here -->
<!-- 'DOMAIN=...' part is not needed because of ADFS -->

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...