Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM (Archived)

Adding Opportunity Product / Opportunity Line Item to Opportunity via C# in Dynamics CRM

Posted on by 15

I have a scenario where I need to insert Opportunity line (Opportunity Product) to Opportunity via C#. I have gone through the Web API Entity reference and tried to insert Opportunity product via C#.

var jsonBody = new Dictionary<string, object>()
{
{ "uomid@odata.bind", "/uoms(5b71260d-3248-e611-80d1-00155ddc4299)" },
{ "productid@odata.bind", "/products(9a9b2e45-d5d3-e811-80e5-00155d02682b)"},
{ "opportunityid@odata.bind", "/opportunities(eb166885-4fde-e911-a95a-00155d026b79)"},
{ "quantity", 1.0000000000 }
};

string httpUrl = "{my URL}/api/data/v8.2/opportunityproducts";
string httpMethod = "POST";
var url = new Uri(httpUrl);
var method = new HttpMethod(httpMethod);
var request = new HttpRequestMessage(method, url);
HttpClient client = new HttpClient(new HttpClientHandler() { Credentials = new NetworkCredential("***", "***", "**") });
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite);
string jsonItem = Newtonsoft.Json.JsonConvert.SerializeObject(jsonBody, Formatting.Indented);
request.Content = new StringContent(jsonItem.ToString(), Encoding.UTF8, "application/json");

var responseaa = client.SendAsync(request).Result;
string responseContent = responseaa.Content.ReadAsStringAsync().Result;

The Above code is not working and it's not inserting any new line Item.

I am getting BadRequest with message :
"message":"Unexpected exception from plug-in (Execute): XrmMasters.CalculateOpportunityProducts: System.NullReferenceException: Object reference not set to an instance of an object."

Any idea on how to insert Opportunity Line Item with Product reference via C#. Am I missing any fields here to associate the product with Opportunity Line?

Any help is appreciated.



*This post is locked for comments

  • azerob Profile Picture
    azerob 15 on at
    RE: Adding Opportunity Product / Opportunity Line Item to Opportunity via C# in Dynamics CRM

    There is no problematic code line. I am just asking if i was wrong with attributes or something other.

    I am getting BadRequest with message and I can't see what's wrong with request.

    "message":"Unexpected exception from plug-in (Execute): XrmMasters.CalculateOpportunityProducts: System.NullReferenceException: Object reference not set to an instance of an object."

  • Joana Pinto Profile Picture
    Joana Pinto 740 on at
    RE: Adding Opportunity Product / Opportunity Line Item to Opportunity via C# in Dynamics CRM

    And when you do debugg, which is the problematic code line?

  • azerob Profile Picture
    azerob 15 on at
    RE: Adding Opportunity Product / Opportunity Line Item to Opportunity via C# in Dynamics CRM

    Hi Joana Pinto,

    Thanks for the quick answer, but

    I think it's not,

    i am using same code for all other requests like GET or POST contacts, opportunities etc, and everything goes fine, i am getting success response.

    Best regards,

  • Suggested answer
    Joana Pinto Profile Picture
    Joana Pinto 740 on at
    RE: Adding Opportunity Product / Opportunity Line Item to Opportunity via C# in Dynamics CRM

    Hi azerob,

    I am not sure but I think the problem is in this line: 

    var responseaa = client.SendAsync(request).Result;

    SendAsync is an asynchronous method. Which means that the response of that method is not immediate. So when you do .Result, probably the null reference is because .Result is accessing something null (since the response of the method is async). You need to do something like this, I think:

    var responseaa = await client.SendAsync(request); //use await to not jump to the next line of your code until this action is completed

    var result = responseaa.Result;

    Best regards

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,253 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,188 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans