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 -->
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…