Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics 365 | Integration, Dataverse...
Suggested answer

Today’s date > last date

(0) ShareShare
ReportReport
Posted on by 340

Hello,

I want to close an opportunity (automatically) when today’s date is greater than the last date. I think I need to write a rule that triggers this, but what formula to identify today’s date though ?

  • LeoAlt Profile Picture
    LeoAlt 16,329 on at
    RE: Today’s date > last date

    Hi partner,

    For example you want to close an existing record as win, this code will close the opportunity.

    service.Execute(winOpp);

    And under the foreach function, you could add custom filters as your rquirements.

    foreach(var c in result.Entities)

    {//add filters...  }

    The "result.Entites" contains all the opportunity records and in this foreach function, you could do actions on each record.

    Like: if (c.Attributes["field"]="Past Last Date")

    {//to do...  }

    Hope it helps.

    Best Regards,

    Leo

                    

  • Johnseito Profile Picture
    Johnseito 340 on at
    RE: Today’s date > last date

    Great, thanks for the example.

    If we create a new record just to close it, how does that close the existing records that needs to be close and can we close it base on a status of our choosing in this case as “Past Last Date”.

  • Suggested answer
    LeoAlt Profile Picture
    LeoAlt 16,329 on at
    RE: Today’s date > last date

    Hi partner,

    Consider that we could not let the coding programs keep running 24-hour in the background(beacuse D365 only allows each process to run up to 7 times per hour), I suggest that you could write a c# app to Screen out all opportunities that meet the conditions and close them at a special time everyday e.g Every day at 2 a.m. You could add this app to Windows task scheduler and let it run everyday 2.00 am automatically.

    Here is the sample code for you.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.Xrm.Tooling.Connector;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Crm.Sdk.Messages;
    using Microsoft.Xrm.Sdk.Query;
    using Microsoft.Xrm.Sdk.Client;
    namespace ConnectToDynamics365
    {
        class Program
        {
            static void Main(string[] args)
            {
                try
                {
                    string connectionString = @"AuthType=Office365;Url=">crm151356.crm.dynamics.com;Username=admin@CRM151356.onmicrosoft.com;Password=0oocek2C4G";
                    CrmServiceClient conn = new CrmServiceClient(connectionString);
                    IOrganizationService service;
                    service = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;
                    QueryExpression query = new QueryExpression("opportunity");
                    query.ColumnSet.AddColumns("datetimeField");
                    EntityCollection result = service.RetrieveMultiple(query);
                    foreach (var c in result.Entities)
                    {
                        if (Convert.ToDateTime(c.Attributes["datetimeField"]) < DateTime.Now)
                        {
                            Entity opportunity = new Entity("opportunity");
                            opportunity = service.Retrieve(opportunity.LogicalName, c.Id, new ColumnSet(true));
                            OptionSetValue status = (OptionSetValue)opportunity["statuscode"];
                            //win opportunity to close it.
                            WinOpportunityRequest winOpp = new WinOpportunityRequest();
                            winOpp.OpportunityClose = new Entity("opportunityclose");
                            winOpp.OpportunityClose["opportunityid"] = c.Id;
                            winOpp.OpportunityClose["actualvalue"] = 12345;
                            winOpp.Status = status;
                            service.Execute(winOpp);
                            //Lose opportunity to close it.
                            LoseOpportunityRequest closeOpp = new LoseOpportunityRequest();
                            Entity opportunityClose = new Entity("opportunityclose");
                            opportunityClose.Attributes.Add("opportunityid", new EntityReference(opportunity.LogicalName,c.Id));
                            opportunityClose.Attributes.Add("subject", "Lost the Opportunity!");
                            closeOpp.OpportunityClose = opportunityClose;
                            closeOpp.Status = new OptionSetValue(-1);
                            service.Execute(closeOpp);
                        }
                    }
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex.InnerException);
                }
            }
        }
    }

    Note that, in C# we could not close the opportunities by setting "statuscode", we need to create a new record of "winopportunity" or "loseopportunity" which Corresponding to "Win" and "Lose".

    And remember to add "Microsoft.CrmSdk.Xrm.Tooling.CoreAssembly" to NuGet.

    pastedimage1571814301389v1.png

    Hope it helps.

    Best Regards,

    Leo

  • Johnseito Profile Picture
    Johnseito 340 on at
    RE: Today’s date > last date

    Hi Partner,

    Thanks for your answer and advice.

    What we want to do is when today’s date is greater than last date. The opportunity is closed past last date. We want this to do automatically to all opportunity that fits this description.

    I think as you indicated is best to create a C# program in console as executable and schedule it to run which I think is great. Could you please provide some examples ?  

  • LeoAlt Profile Picture
    LeoAlt 16,329 on at
    RE: Today’s date > last date

    Hi partner,

    May I know what's the trigger conditions do you want. 24-hour real-time monitoring or some other special circumstances trigger this operation?

    If you want this rule to monitor dates in real time in the background, turn off the opportunity as soon as conditions are met, you need to create a console-app with C# to Compare 2 dates and close the opportunity and then create a windows task scheduler to let the console app runs every day.

    If you want to trigger this feature in other situations, such as when adding, upgrading, or deleting opportunities, you could create a workflow to do this.

    pastedimage1571629240507v1.png

    If my understanding is not correct, please kindly share yor complete requirement.

    Hope it helps.

    Bset Regards,

    Leo

  • Suggested answer
    Adrian Begovich Profile Picture
    Adrian Begovich 21,009 Super User 2024 Season 2 on at
    RE: Today’s date > last date

    Hi Johnseito,

    It depends on what programming language you are using to solve the problem. For example, in C# you can use the DateTime.Now Property to get a DateTime object that is set to the current date and time on your computer, expressed as the local time.

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,280 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,235 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Product updates

Dynamics 365 release plans