Unable to add a service reference to Dynamics 365 crm in visual studio 2012 - service-reference

I am trying to add service reference to Dynamics 365 CRM using the following API https://[Organization].api.crm8.dynamics.com/api/data/v8.2/ but each time I am getting this window that asks me for credentials....
I tried using the credentials that I use to login to the crm...but they donot work...can someone tell me which credential I should use?..

Why exactly are you trying to add a reference to the CRM web services? Assuming you want to access CRM from server side code, what you need to do is:
Add references to the core CRM SDK assemblies (Microsoft.Crm.Sdk.Proxy.dll and Microsoft.Xrm.Sdk.dll). You get can them from the downloadable SDK or just add the "Microsoft.CrmSdk.CoreAssemblies" NuGet package.
After doing this you'll be able to write code "talking" with CRM. But what you are missing is the actual "connection". There are several ways of obtaining it, but the easiest one is to use the Xrm Tooling helper class, described here - https://msdn.microsoft.com/en-us/library/mt608573.aspx. You'll need to reference the required assemblies or use the "Microsoft.CrmSdk.XrmTooling.CoreAssembly" NuGet package.
After doing all this, you'll be able to successfully code against Dynamics CRM.
CrmServiceClient crmSvc = new CrmServiceClient(ConfigurationManager.ConnectionStrings["MyCRMServer"].ConnectionString);
IOrganizationService orgService = crmSvc.OrganizationServiceProxy;
// Who am I?
WhoAmIResponse whoAmIResp = orgService.Execute(new WhoAmIRequest()) as WhoAmIResponse;
Guid myUserId = whoAmIResp.UserId;
// Get all accounts starting with 'A'
QueryExpression query = new QueryExpression("account");
query.ColumnSet = new ColumnSet("accountid", "name");
query.Criteria.AddCondition("name", ConditionOperator.BeginsWith, "a");
EntityCollection ecoll = orgService.RetrieveMultiple(query);
foreach(Entity account in ecoll.Entities)
{
if(account.Attributes.Contains("name"))
{
Console.WriteLine((string)account["name"]);
}
}
// Update some account
Entity accountToUpdate = new Entity("account");
accountToUpdate["accountid"] = new Guid("_some_guid_here");
accountToUpdate["name"] = "new name";
orgService.Update(accountToUpdate);
If you want to use the type safe approach, you'll need to generate a proxy class - like described here: https://msdn.microsoft.com/en-us/library/gg327844.aspx
Afterwards you'll be able to write code like this:
DataContext data = new DataContext(orgService);
// DataContext is the name of the service context, as defined in the CrmScv tool
var myAccountData = (from a in data.AccountSet
where a.Address1_Telephone1 == "12312313"
select new
{
a.AccountId,
a.Name,
a.EMailAddress1,
a.PrimaryContactId
}).First();
Contact contactToUpdate = new Contact()
{
ContactId = myAccountData.PrimaryContactId.Id,
EMailAddress1 = myAccountData.EMailAddress1
};
orgService.Update(contactToUpdate);
... which is much nicer and less error prone.

From the looks of it you are trying to authenticate through an App outside of the context of Dynamics 365. If you want to authenticate with the Web API this way you will have to connect to Microsoft Dynamics 365 web services using OAuth and authenticate using ADAL
https://msdn.microsoft.com/en-us/library/gg327838.aspx
Here is a walkthrough on how to do it
https://msdn.microsoft.com/en-us/library/mt622431.aspx
Additional note:
If you are using CRM 2013 SDK you may need to update to 6.1.2 for Dynamics 365 Support
https://blogs.msdn.microsoft.com/crm/2017/02/01/dynamics-365-sdk-backwards-compatibility/

Related

Issue while Instantiating SharePoint 2010 method in MSCRM 2011 plug-in

This is regarding SharePoint 2010 Integration with MSCRM 2011.
While creating a record in CRM, trying to create a Custom Document location for that record and a similar folder in sharepoint, So that when user clicks on document link in the entity record it does not prompt user to create folder in Sharpoint (Trying to avoid sharepoint noise for better user experience)
I have implemented through post create asynchronous plug-in. (I did this through console program working fine). Build the plugenter code here-in and deployed to CRM.
When creating a record it error out with a message like "An internal server 500 error - Could not load the assembly with public key token etc…blab bla bla…”
But when I am debugging the plug-in it failed at the first line of command where I am instantiating sharePoint method Create client context of sharepoint, it says [System.Security.SecurityException]={“That assembly does not allow partially trusted callers”.}
As per google, per this issue it should be having one attribute “Allow partial users” in assembly info file. As per my understanding, this should be done in because the request goes from CRM plug-in to SharePoint dll. I mean share point dlls are not allowing request from my assembly. How can we change that?
I have referenced Microsoft.SharePoint.client.dll and Microsoft.SharePoint.Client.Runtime.dll
What is the alternate to overcome this issue?
Appreciate if some one can help me ..Thanks In advance.
Here is my code for SharePoint
ClientContext clientContext = new ClientContext(siteUrl)
CredentialCache cc = new CredentialCache();
Cc.Add(new Uri(siteUrl), "NTLM", CredentialCache.DefaultNetworkCredentials);
clientContext.Credentials = cc;
clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
Web web = clientContext.Web;
SP.List list = web.Lists.GetByTitle(listName);
ListItemCreationInformation newItem = new ListItemCreationInformation();
newItem.UnderlyingObjectType = FileSystemObjectType.Folder;
newItem.FolderUrl = siteUrl + "/" + folderlogicalName;
if (!relativePath.Equals(string.Empty))
newItem.FolderUrl += "/" + relativePath;
newItem.LeafName = newfolderName;
SP.ListItem item = list.AddItem(newItem);
item.Update();
clientContext.ExecuteQuery();
Where I am passing the siteurl, folderlogicalname,relativepath and new foldername as parameters.
This works fine from my Console application. But when converted to CRM plug-in it gives the above specified issue
I've seen a similar issue before.
CRM plugins run inside a sandbox, so all assemblies and .NET libraries used must allow partial trust callers (since the CRM sandbox runs under partial trust). It works in the console because you are executing the code as a full trust user in that context.
This issue is not necessarily your code, but could be a dependency or a .NET library itself does not allow partial trust callers - in your case it sounds like the Sharepoint library is the culprit (but a stack trace of the error should reveal exactly where the cause is).
Since you don't have access to the source library causing the problem, to overcome the error you will likely have to create a wrapper. However, the problem is the wrapper cannot directly reference the problem library or you will get the same issue. So to get around this, you may have to create a web service which acts as your wrapper and then call the web service in your CRM plugin. This way the full trust code is executed by the web service (which is full trust) and then returns the result to your calling CRM plugin.
Here is more info on the error.
Thanks Jason. This works for me.
I Would like to add additional few points to the answer.
1. I have added the sharepoint dlls to the bin folder of CRM 2011 site.
2. Also deployed the same dlls in the folder whereever Async job is running to make my Async plug-in to work.
Thanks once again for the cooperation

Connect with Visual Studio 2012 and C sharp to microsoft cloud TFS server

I am building an asp.net webforms site that can connect to our tfs hosted on Microsoft (http://companyname.visualstudio.com) and get data from it. When I run the project with Cassini it runs fine as it gets the authentication from the browser. But I want to do this from code behind.
I have tried various setups like
var tfs = new TfsTeamProjectCollection(CollectionUri, new UICredentialsProvider());
[which is now deprecated as method and should not be used]
or
var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(CollectionUri);
or even with
var tfs = new TfsTeamProjectCollection(CollectionUri, new NetworkCredential("windowsliveid","password"));
I have no domain since it is a Windows Liveid
and then
tfs.EnsureAuthenticated();
Also I get the uri through
var CollectionUri = new Uri("https://companyname.visualstudio.com/DefaultCollection/");
Any ideas on how to properly authenticate. I would love to either prompt the auth window or give username and password directly.
------------------------------ SOLVED !!! ---------------------------------
Here is the solution to it after some googling following Martin Woodward's very helpful suggestion.
First alternate credentials have to be activated through the TFS account. Then the code can be changed into this which works fine :)
Just remember that you need to have the latest version of VS 2012 (at least update1) for the code to work. Else you can't reference BasicAuthCredential.
var nc = new NetworkCredential("username", "password");
var bc = new BasicAuthCredential(nc);
var tfsc = new TfsClientCredentials(bc) {AllowInteractive = false};
var tfs = new TfsTeamProjectCollection(CollectionUri, tfsc);
tfs.Authenticate();
And here are the referenced dlls.
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
Take a look at service credentials, or try enabling alternate credentials on your account which will then allow you to authenticate using http basic auth.
You probably want service credentials for what it sounds like you are doing though.

Log in to CRM from ASP.NET

I'm writing an application in which I have to log on to a CRM 2011 server from ASP.NET code. I quickly found this article:
http://msdn.microsoft.com/en-us/library/cc156363.aspx
The problem I'm having is in this bit of code from that article:
//Create the Service
CrmService service = new CrmService();
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
service.CrmAuthenticationTokenValue = token;
service.Url = crmurl;
Visual Studio can't resolve CrmService. So I tried to add a web reference to this project and point the web reference at the CRM service I'm using. The URL I'm getting from Settings->Customizations in CRM, and I'm using the Organization Service endpoint. However, after I add that reference CrmService is still unresolvable. What am I doing wrong?
First off, you have linked a CRM 4 MSDN article, some things have changed so you might want try this one instead: Authenticate Users with Microsoft Dynamics CRM Web Services.
Then as an alternative you may want to try the CrmConnection class, its a helper library in Microsoft.Xrm.Client. It means you can use a connection string approach to authenticate with CRM (and let the class takes care of all the hard work).
var connection = CrmConnection.Parse("Url=http://crm.contoso.com/xrmContoso; Domain=CONTOSO; Username=jsmith; Password=passcode;");
var service = new OrganizationService(connection);
var context = new CrmOrganizationServiceContext(connection);
You can also keep the connection strings in config files makes life significantly easier.
Related articles:
Simplified Connection to Microsoft Dynamics CRM.
Sample: Simplified Connection Quick Start using Microsoft Dynamics CRM.
If you're using standard AD authentication with a local environment this answer should work fine: How to Authenticate to CRM 2011?
Actually, the login procedure is heavily dependent on the authentication provider you're targeting. I'm currently in the process of structuring that info in a pedagogic way on my blog so you're welcome to check it out and nag if it's too techy.
There are at the moment four such ways.
Active directory
Live id
Federation
Online federation
Which is applicable in your case, you should know already. If not, there's code for that too uploaded just a few days ago.
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
...
public AuthenticationProviderType GetAuthenticationProviderType(Uri address)
{
IServiceManagement<IOrganizationService> organizationServiceManagement
= ServiceConfigurationFactory.CreateManagement
<IOrganizationService>(address);
return organizationServiceManagement.AuthenticationType;
}
Assuming that you're aiming for AD, you're in luck. It's the easiest.
Uri organizationUrl = new Uri("http ... Organization.svc");
OrganizationServiceProxy organizationService = new OrganizationServiceProxy(
organizationUrl, null, null, null);
If you're aiming for Live Id - that's stingy. I'm still trying to set up a graspable example. The ones at MSDN are just too heavy and confusing. At least when one's dense and lazy like me. More info at mentioned but undisclosed location.

Get the SharePoint URL for a Team Project programmatically

I want to find out by coding if a given Team Project has an associated SharePoint. If yes I also want to get the URL for the SharePoint in order to create a specific link to it.
I do not mean the web access of the TFS but the associated SharePoint. Is there a way to find this out without knowing the URL of the SharePoint server that is different from the TFS server?
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
private static string RetrieveProjectPortalBaseAddress(TfsTeamProjectCollection tfs, string teamProject)
{
IRegistration registration = (IRegistration)tfs.GetService(typeof(IRegistration));
RegistrationEntry[] entries = registration.GetRegistrationEntries("TeamProjects");
ServiceInterface endpoint = entries[0].ServiceInterfaces.FirstOrDefault(si => si.Name == teamProject + ":Portal");
return endpoint.Url;
}

Sharepoint 2010 Client Object Module getting a site url list

I’m trying to learn SharePoint Client Object Model, specifically how to get a list of all SharePoint site URLs using a remote connection. This is possible using webservices…but I want to do it using the client object model.
I’ve figured how to get the title lists of a specific sharepoint site using the following code:
client object module):
ClientContext ctx = new ClientContext( server );
ctx.AuthenticationMode = ClientAuthenticationMode.Default;
ctx.Credentials = WindowsAuthenticationCredentials(username, password);
Web w = ctx.Web;
var lists = ctx.LoadQuery(w.Lists);
ctx.ExecuteQuery();
//Enumerate the results.
foreach (List theList in lists)
{
}
Output:
Announcements, Master Collection Pages… etc…
How can I do the same to get a site url list?
In web services you can call the following to achieve that, but as I said just trying to figure out how to do the same using client object module. If you can provide c# code that would greatly be appreciated.
WSPSitedata.SiteData sitedata = new SiteData();
sitedata.Url = #SharePointBaseURL + #"_vti_bin/sitedata.asmx";
sitedata.Credentials = our_credentials
_sSiteMetadata metaData = new _sSiteMetadata();
_sWebWithTime[] webWithTime
sitedata.GetSite(out metaData, out webWithTime, out users, out groups, out vgroups);
The SharePoint Client Object Model CSOM is designed to remotly interact with your SiteCollection. Sure, it is possible to connect to various SiteCollections, but it's not possible to look over all SiteCollections sitting within a SPWebApplications.
In 2010 you could still use the ASMX WebServices which are available in earlier versions of SharePoint.
To get a better understanding of the CSOM you should have a look at the MSDN site http://msdn.microsoft.com/en-us/library/ee537247.aspx
Did you really mean a list containing all SiteCollection URLs or was that a misunderstanding?
Thorsten

Resources