web
You’re offline. This is a read only version of the page.
close
Skip to main content
Community site session details

Community site session details

Session Id :
Customer experience | Sales, Customer Insights,...
Answered

Close Opportunity as Won through Plugin

(0) ShareShare
ReportReport
Posted on by 165

Hello,

I am running the following plugin as a console app and I get the following error:

Exception caught - An unexpected error occured. Exception thrown: 'System.ServiceModel.FaultException`1' in Microsoft.Xrm.Sdk.dll

Here is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Crm.Sdk.Messages;
using System.Net;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk.Query;

namespace Qualco_AddBPWStages
{
    class Program
    {
        static void Main(string[] args)
        {
            IOrganizationService organizationService = null;

            try
            {
                ClientCredentials clientCredentials = new ClientCredentials();
                clientCredentials.UserName.UserName = "###";
                clientCredentials.UserName.Password = "###";

                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                organizationService = (IOrganizationService)new OrganizationServiceProxy(new Uri("https://..."),
 null, clientCredentials, null);
                if (organizationService != null)
                {
                    Guid userid = ((WhoAmIResponse)organizationService.Execute(new WhoAmIRequest())).UserId;

                    if (userid != Guid.Empty)
                    {
                        Console.WriteLine("Connected succesfully");

                        QueryExpression queryOpp = new QueryExpression("opportunity");
                        queryOpp.ColumnSet = new ColumnSet(new string[] { "name", "opportunityid", "actualclosedate", "actualvalue" });
                        //queryOpp.Criteria.AddCondition("statuscode", ConditionOperator.Equal, 100000005);
                        //queryOpp.Criteria.AddCondition("actualvalue", ConditionOperator.ContainValues);
                        //queryOpp.Criteria.AddCondition("actualclosedate", ConditionOperator.ContainValues);
                        queryOpp.Criteria.AddCondition("zst_opportunitynumber", ConditionOperator.Equal, "OP-0000841");
                        EntityCollection collectionOpportunities = organizationService.RetrieveMultiple(queryOpp);
                        
                        foreach(Entity opport in collectionOpportunities.Entities)
                        {

                            Entity oppClose = new Entity("opportunityclose");
                            oppClose["opportunityid"] = opport.Id;
                            oppClose["actualend"] = opport.GetAttributeValue("actualclosedate");
                            oppClose["actualrevenue"] = opport.GetAttributeValue("actualvalue");

                            WinOpportunityRequest woReq = new WinOpportunityRequest();
                            woReq.OpportunityClose = oppClose;
                            woReq.RequestName = "WinOpportunity";

                            OptionSetValue oStatus = new OptionSetValue();
                            oStatus.Value = 3;
                            woReq.Status = oStatus;

                            organizationService.Execute(woReq);
                            string name = opport.GetAttributeValue("name");
                            Console.WriteLine("Opportunity"   name   "is closed as Won");
                        }

                        Console.WriteLine("Plugin completed succesfully");
                    }
                }
                else
                {
                    Console.WriteLine("Failed to Established Connection!!!");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception caught - "   ex.Message);
            }
            Console.ReadKey();
        }
    }
}

Any help would be greately appreciated

I have the same question (0)
  • irenegr Profile Picture
    165 on at
    RE: Close Opportunity as Won through Plugin

    Thank you!

  • Suggested answer
    Pawar Pravin  Profile Picture
    5,237 on at
    RE: Close Opportunity as Won through Plugin

    Please refer code mentioned in below doc:

    docs.microsoft.com/.../microsoft.crm.sdk.messages.winopportunityrequest

  • Verified answer
    Wahaj Rashid Profile Picture
    11,321 on at
    RE: Close Opportunity as Won through Plugin

    Hi,

    Thank you for your query.

    "opportunityid" is an Entity Reference, but you are passing a Guid.

    Replace following line in your code:

    //oppClose["opportunityid"] = opport.Id; Replace with following:
    
    oppClose["opportunityid"] = new EntityReference("opportunity", opport.Id);

    Furthermore, you can look into INNER EXCEPTION to get exact details of the error.

    If you get following error, make sure all associated Quotes are Closed:

    'The opportunity can not be closed.'

    Let me know if you need further clarification.

    Best,

    Wahaj

    (if it helps, please mark it as verified)

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

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Abhilash Warrier – Community Spotlight

We are honored to recognize Abhilash Warrier as our Community Spotlight honoree for…

Leaderboard > Customer experience | Sales, Customer Insights, CRM

#1
Rishabh Kanaskar Profile Picture

Rishabh Kanaskar 258

#2
Daniyal Khaleel Profile Picture

Daniyal Khaleel 180

#3
Tom_Gioielli Profile Picture

Tom_Gioielli 92 Super User 2025 Season 2

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans