How to query Opportunities in Microsoft Dynamics CRM 2011 - dynamics-crm

I am trying to query Opportunity information from Microsoft Dynamincs CRM 2011.
Any idea why I keep getting a 401 Unauthorized error?
If I use the URL in the browser it seems to work.
Uri organizationUri = new Uri("/XRMServices/2011/OrganizationData.svc");
Uri homeRealmUri = null;
ClientCredentials credentials = new ClientCredentials();
credentials.Windows.ClientCredential = new System.Net.NetworkCredential("username", "password", "domain");
OrganizationServiceProxy orgProxy = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null);
// Get the IOrganizationService
IOrganizationService orgService = (IOrganizationService)orgProxy;
//Get OrganizationServiceContext -the organization service context class implements the IQueryable interface and
//a .NET Language-Integrated Query (LINQ) query provider so we can write LINQ queries against Microsoft Dynamics CRM data.
OrganizationServiceContext orgServiceContext = new OrganizationServiceContext(orgService);
// Get name,number and ownerid for all the account records
var queryAccount1 = from r in orgServiceContext.CreateQuery("opportunity")
select new
{
CustomerID = r["customerid"],
};
foreach (var account in queryAccount1)
{
txtCustomerID.Text = account.CustomerID.ToString();
}

Are you accessing you CRM on the intranet or IFD? I think the problem is the way you set up credentials.
Setting up NetworkCredential class will not work if you are accessing your CRM through IFD
var credentials = new ClientCredentials();
credentials.UserName.UserName = "username";
credentials.UserName.Password = "password";
var organizationUri = new Uri("https://externaluri");
var organizationServiceProxy = new OrganizationServiceProxy(organizationUri, null, credentials, null);
organizationServiceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());

Related

dynamics365 CRM populate form field with user login

I am new to dynamics 365 CRM. I created a form that the user will fill, it contains a lookup field that mapped to the User entity. I want to populate this field automatically depending on the user login. I have tried the business role but it didn't work. I have followed these links:
CRM Auto Populate Field From Option Set.
Auto Populate lookupfield
Dynamics CRM auto populate lookup values from custom field
the Code I am using is :
var userSetting = Xrm.Utility.getGlobalContext().userSettings;
var currentUser = new Array();
currentUser[0] = new Object();
currentUser[0].id = userSetting.userId;
currentUser[0].Name = userSetting.userName;
currentUser[0].entityType = "systemuser";
executionContext.getFormContext().getAttribute("student").setValue(currentUser);
First, retrieve logged in user settings with
var userSettings = Xrm.Utility.getGlobalContext().userSettings
Now, you should have access to the ID, Name, and Type(systemuser) of the record you want to set in your lookup field.
var currentUser = new Array();
var currentUserObject = new Object();
currentUserObject.id = userSettings.userId;
currentUserObject.name = userSettings.userName;
currentUserObject.entityType = "systemuser"
currentUser[0] = currentUserObject;
formContext.getAttribute("fieldname").setValue(currentUser);
From getGlobalContext.userSettings

Automatically map a Contact to an Account

I want to add a field to Accounts which shows the email domain for that account e.g. #BT.com. I then have a spreadsheet which lists all the Accounts and their email domains. What I want to do is when a new Contact is added to Dynamics that it checks the spreadsheet for the same email domain (obviously without the contacts name in the email) and then assigned the Contact to the Account linked to that domain. Any idea how I would do this. Thanks
Probably best chance would be to develop CRM plugin. Register your plugin to be invoked when on after contact is created or updated (so called post-event phase). And in your plugin update the parentaccountid property of the contact entity to point to account of your choice.
Code-wise it goes something like (disclaimer: not tested):
// IPluginExecutionContext context = null;
// IOrganizationService organizationService = null;
var contact = (Entity)context.InputParameters["Target"];
var email = organizationService.Retrieve("contact", contact.Id, new ColumnSet("emailaddress1")).GetAttributeValue<string>("emailaddress1");
string host;
try
{
var address = new MailAddress(email);
host = address.Host;
}
catch
{
return;
}
var query = new QueryExpression("account");
query.TopCount = 1;
// or whatever the name of email domain field on account is
query.Criteria.AddCondition("emailaddress1", ConditionOperator.Contains, "#" + host);
var entities = organizationService.RetrieveMultiple(query).Entities;
if (entities.Count != 0)
{
contact["parentaccountid"] = entities[0].ToEntityReference();
}
organizationService.Update(contact);
I took Ondrej's code and cleaned it up a bit, re-factored for pre-operation. I also updated the logic to only match active account records and moved the query inside the try/catch. I am unfamiliar with the MailAddress object, I personally would just use string mapping logic.
var target = (Entity)context.InputParameters["Target"];
try
{
string host = new MailAddress(target.emailaddress1).Host;
var query = new QueryExpression("account");
query.TopCount = 1;
// or whatever the name of email domain field on account is
query.Criteria.AddCondition("emailaddress1", ConditionOperator.Contains, "#" + host);
query.Criteria.AddCondition("statecode", ConditionOperator.Equals, 0); //Active records only
var entities = organizationService.RetrieveMultiple(query).Entities;
if (entities.Count != 0)
{
target["parentaccountid"] = entities[0].ToEntityReference();
}
}
catch
{
//Log error
}

Visual Studio Online SDK

I am working on a project where I have a requirement to create workitem on Visual Studio Online instance. I am using personal access token. This will set CreatedBy as my name (Expected behavior). I am considering to use Oauth2; However, I am not sure if there's the way to do this Server-to-Server (Non-Interactive)? Any suggestions thoughts?
var personalAccessToken = "PAT Value fro Config";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "", personalAccessToken))));
return client;
PAT's are created in Security context of the user. I need to find a way to use Oauth without having to involved UI. So I'm looking for Server-to-Server Auth.
object[] patchDocument = new object[5];
patchDocument[0] = new { op = "add", path = "/fields/System.Title", value = bugTitle };
patchDocument[1] = new { op = "add", path = "/fields/Microsoft.VSTS.TCM.ReproSteps", value = bugReproSteps };
patchDocument[2] = new { op = "add", path = "/fields/Microsoft.VSTS.Common.Priority", value = "1" };
patchDocument[3] = new { op = "add", path = "/fields/Microsoft.VSTS.Common.Severity", value = "2 - High" };
patchDocument[4] = new { op = "add", path = "/fields/System.IterationPath", value = deserializeIteration };
//System.IterationPath
string postUrl = $"{_vsoInstanceUrl}/DefaultCollection/ProjectName/_apis/wit/workitems/$Bug?api-version=1.0";
await ExecutePatch(patchDocument.ToArray(), postUrl, "application/json-patch+json");
No there is no Server-to-Server OAuth support. If you use the .NET Client Object Model you can leverage Impersonation support.
If your account has "Act on behalf of others" permissions you can also achieve a "User X via YourAccount".

Export emal template from CRM4 to CRM 2016

I need to export email templates from CRM 4 directly into CRM 2016. Can't go over the complete upgrade process so my best guess would be to export using services, connect to CRM 4 and then import into CRM 2016. The problem seems to be the import into CRM 2016 which throws a faultexception. But before I would start looking into to this I tried to recreate a template that I created in CRM 2016. Using the services but this also doesn't seem so easy to do..the process creates a copy of the email template but subject and body are missing. Does this need to be casted to something esle? What could be the problem here?
This is the code I used:
ColumnSet cols = new ColumnSet(new string[] { Template.AttributeLogicalNames.Title, Template.AttributeLogicalNames.Subject,
Template.AttributeLogicalNames.TemplateTypeCode, Template.AttributeLogicalNames.IsPersonal,
Template.AttributeLogicalNames.LanguageCode, Template.AttributeLogicalNames.Body });
QueryExpression query = new QueryExpression(Template.EntityLogicalName);
query.ColumnSet = cols;
query.Criteria = new FilterExpression();
query.Criteria.AddCondition("title", ConditionOperator.Equal, "TestTemplate Candidate");
EntityCollection results = _service.RetrieveMultiple(query);
foreach (var item in results.Entities)
{
Template template = new Template() { Title = ((Template)item).Title + "-2", Subject = ((Template)item).Subject,
TemplateTypeCode = ((Template)item).TemplateTypeCode, IsPersonal = ((Template)item).IsPersonal,
LanguageCode = ((Template)item).LanguageCode,Body = ((Template)item).Body
};
Guid templateid = _service.Create(template);
Console.WriteLine("Template created with Guid: {0}", templateid);
}
It seems I was missing some fields: subjectpresentationxml, presentationxml, generatetypecode

Is Dynamics CRM 2013 sdk cache result of QueryExpresions by Default?

I wrote this simple query:
var connectionString = String.Format("Url={0}; Username={1}; Password={2}; Domain={3}", url, username, password, domain);
var myConnection = CrmConnection.Parse(connectionString);
CrmOrganizationServiceContext _service = new CrmOrganizationServiceContext(myConnection);
var whoAmI = _service.Execute(new WhoAmIRequest());
var query = new QueryExpression
{
EntityName = "phonecall",
ColumnSet = new ColumnSet(true)
};
query.PageInfo = new PagingInfo
{
Count = 20,
PageNumber = 1,
PagingCookie = null
};
query.Orders.Add(new OrderExpression
{
AttributeName = "actualstart",
OrderType = OrderType.Descending
});
query.Criteria = new FilterExpression() { FilterOperator = LogicalOperator.And };
query.Criteria.AddCondition("call_caller", ConditionOperator.In, lines);
var entities = _service.RetrieveMultiple(query).Entities;
I have a program which runs this query every minute. On the first execution the correct results are displayed but for subsequent queries the results never change as I update records in CRM.
If I restart my program the results refresh correctly again on the first load.
Why are the results not updating as records are modified in CRM?
It is the CrmOrganizationServiceContext that is doing the caching - I found the following worked a treat and the results of my RetrieveMultiple are no longer cached :)
Context = new CrmOrganizationServiceContext(CrmConnection.Parse(connectionString));
Context.TryAccessCache(cache => cache.Mode = OrganizationServiceCacheMode.Disabled);
RetrieveMultiple always brings back fresh results so there must be some other aspect of your program which is causing stale data to be displayed.

Resources