Close Menu
SalesforceCodex
    Facebook X (Twitter) Instagram
    Trending
    • 10 Salesforce Chrome Extensions to Boost Your Productivity
    • How to Build a Generic Modal Window in Lightning Web Component
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    • Top 10 PMD Issues Salesforce Developers Should Focus on in Apex
    Facebook X (Twitter) Instagram
    SalesforceCodex
    Subscribe
    Saturday, June 21
    • Home
    • Architecture
    • Salesforce
      • News
      • Apex
      • Integration
      • Books Testimonial
    • Questions
    • Certification
      • How to Prepare for Salesforce Integration Architect Exam
      • Certification Coupons
    • Integration Posts
    • Downloads
    • About Us
      • Privacy Policy
    SalesforceCodex
    Home»Salesforce»Publish Platform Events from ASP.NET

    Publish Platform Events from ASP.NET

    Dhanik Lal SahniBy Dhanik Lal SahniOctober 8, 2020Updated:December 25, 20242 Comments6 Mins Read
    Facebook Twitter Pinterest LinkedIn Tumblr Email
    Publish Platform Events from ASP.NET
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Platform events enable application to deliver secure, scalable, and customizable event notifications within the Salesforce platform or from external source.

    In this post we will publish platform events from ASP.NET application and subscribe using Flow, Apex trigger and Lightning component.

    Use Case:

    Let us take example, one e-commerce application is built in ASP.NET application and when order is generated by customer. That order information should be shared by various system/module like warehouse system, shipping system, vendor/partner system, billing system and CRM system. Salesforce will subscribe that event and get all order information.

    Below steps are required for this use case

    1. Platform Event Creation
    2. Connected App for ASP.NET
    3. Setup user and permission set
    4. Publish Event form ASP.NET
    5. Subscribe Event in Apex Trigger
    6. Subscribe Event in Lightning Component
    7. Subscribe Event in Visual Flow

    1. Platform Event Creation

    Platform Event is similar to salesforce object and we can create like a custom object. Platform Event are created with __e suffix. e is stands for events.


    We have to create fields like custom fields in standard or custom object. These fields are used to hold event message which will be transferred using event bus.

    To create platform event in org, go to Setup->Platform Event

    For above use case, create platform event named ‘ProductEvent’. We need following fields in Platform Event. So create these fields as mentioned in below image or based on your use case.

    2. Connected App for ASP.NET

    Create connected app for ASP.NET. A connected app is a framework that enables an external application like ASP.NET, Java etc. to integrate with Salesforce using APIs and standard protocols.

    Create connected app from Setup->App->App Manager-> New Connected App

    Create connected app with below access.

    Application Permissions:Perform requests on your behalf at any time  
     Full access  
     Provide access to your data via the Web  
     Access and manage your data
    Callback URLhttps://localhost:44378/product

    Refer Connected Apps

    3. Setup user and permission set

    Create a user, permission set and profile for external system. Provide minimum access to user. Use permission set to give permission. Profile should not have any permission.

    This user with connected app will be used by ASP.NET application.

    4. Publish Event form ASP.NET

    E-Commerce application will be created in ASP.NET. This application will fetch product information from Salesforce object product. For demo purpose, I have created only two pages. One page for showing complete product list and second page to buy that product. We are only publishing product event platform event from checkout page.

    We have to create two custom object (can use standard object also) Product and Product Order.

    Product custom object fields

    Field NameAPI NameType
    DiscountDiscount__cCurrency(2, 0)
    ImageImage__cText(255)
    Is Stock AvailableIsStockAvailable__cCheckbox
    Product DescriptionProduct_Descriptiom__cText(255)
    Product NameNameText(80)
    QuantityQuantity__cNumber(18, 0)
    Unit PriceUnitPrice__cCurrency(16, 2)
    VendorVendor__cLookup(Vendor)

    Product Order custom object fields

    Field NameAPI NameType
    Order NumberOrderNumber__cAuto Number
    Order StatusOrderStatus__cPicklist-
    New
    Review Completed
    Dispatched
    Delivered
    ProductProduct__cLookup(Products)
    ProductOrder NameNameText(80)
    QuantityQuantity__cNumber(16, 2)

    We will use above created connected app and Salesforce user in this site. Below tasks are required to publish platform event.

    • Login to Salesforce
    • Get Product Detail from Salesforce Product Object
    • Show product list on web page
    • Publish Platform Event

    a. Login to Salesforce

    Store salesforce connected app and user detail in app.config. Below code will be used to connect Salesforce org.

     public void Login()
            {
                String jsonResponse;
                using (var client = new HttpClient())
                {
                    var request = new FormUrlEncodedContent(new Dictionary<string, string>
                        {
                            {"grant_type", "password"},
                            {"client_id", ClientId},
                            {"client_secret", ClientSecret},
                            {"username", Username},
                            {"password", Password + Token}
                        }
                    );
                    request.Headers.Add("X-PrettyPrint", "1");
                    var response = client.PostAsync(LOGIN_ENDPOINT, request).Result;
                    jsonResponse = response.Content.ReadAsStringAsync().Result;
                }
                Console.WriteLine($"Response: {jsonResponse}");
                var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonResponse);
                AuthToken = values["access_token"];
                InstanceUrl = values["instance_url"];
            }

    b. Get Product Detail from Salesforce Customer Object

    Now retrieve product details with Salesforce custom object API.

    public IActionResult Index()
            {
                var client = SalesforceClient.CreateClient();
                client.Login();
                var products = client.Query("Select Id,Name,UnitPrice__c, Quantity__c,IsStockAvailable__c,Image__c from Product__c where IsStockAvailable__c=true");
                var prds = JsonConvert.DeserializeObject<Models.Product>(products);
                return View(prds);
            }

    c. Show product list on web page

    Show product list which is retrieved from above query. This is done in View page of asp.net.

    @foreach (var prd in Model.records)
    {
    
        <div style="display: inline-block">
    
            <div class="card">
                <img src=@prd.Image__c alt="Denim Jeans" style="height:180px;width:auto;margin:10px">
                <h1>@prd.Name</h1>
                <p class="price">@prd.UnitPrice__c</p>
                <p><button class="button" type="button" title="Add to Cart" value="Add to Cart" onclick="location.href='@Url.Action("Product", "Home", new { id = @prd.Id,image=prd.Image__c,quantity=@prd.Quantity__c,name=prd.Name})'" >Checkout Product</button>  </p>
            </div>
        </div>
    }

    d. Publish Platform Event

    Once product is selected, we can publish order product detail with Platform Event. This is just for demo purpose, we can put detail based on our business requirement.

    public string addMessage(string id, Int32 quantity, string name, string custId)
            {
                using (var client = new HttpClient())
                {
                    string restRequest = InstanceUrl + "/services/data/v49.0/sobjects/ProductEvent__e";
    
                    //Arrange
                    var pd = new Models.PlatformEvent();
                    pd.Quantity__c = quantity.ToString();
                    pd.ProductID__c = id;
                    pd.ProductName__c = name;
                    pd.CustomerId__c = "XXXX";
    
                    var json = JsonConvert.SerializeObject(pd);
                    //construct content to send
                    var content = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");
    
                    var request = new HttpRequestMessage(HttpMethod.Post, restRequest);
                    request.Headers.Add("Authorization", "Bearer " + AuthToken);
                    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    request.Content = content;
    
                    var response = client.SendAsync(request).Result;
                    var result = response.Content.ReadAsStringAsync().Result;
                    return result;
                }
            }

    Refer complete ASP.NET code.

    5. Subscribe Event in Apex Trigger

    As Platform Event will be published from ASP.NET application, we can subscribe that event in Salesforce Apex Trigger. This trigger is creating product order record based on event message detail. We can have different business logic when event notification is received.

    6. Subscribe Event using Lightning Component

    We can subscribe published Platform Event using lightning page. We have to create one lightning web component for this. This component will be placed on lightning app builder page. Lightning app builder page will be shown as tab.

    7. Subscribe Event using Flow

    We can subscribe event using flow to send email to customer. We can add any business functionality, for demo we are sending email.

    1. Create Email Template to send. Create one email template for Order Received.
    2. Create Workflow Email Alert to send email. Use above email template. For demo, create Product Order Alert.
    3. Create flow and use Email action to call Workflow Email Alert (Product Order Alert).
    Platform Events | SalesforceCodex

    Flow Schema:

    Reference:

    https://trailhead.salesforce.com/modules/platform_events_basics

    https://developer.salesforce.com/docs/atlas.en-us.platform_events.meta/platform_events/platform_events_subscribe_lc.htm

    https://developer.salesforce.com/docs/atlas.en-us.platform_events.meta/platform_events/platform_events_subscribe_flow.htm

    https://help.salesforce.com/apex/HTViewHelpDoc?id=platform_events.htm

    Video Explanation:

    Related Posts

    • Efficient Ways to Debug Salesforce Platform Events
    • Ultimate Guide to Monitoring Platform Events using Streaming Monitor

    Other Posts

    1. Ultimate Guide to URL Accessibility in LWC
    2. Dynamically Instantiate Components in LWC
    3. Generic Notification Component in LWC
    4. Reusable Custom Calendar LWC using FullCalendar Js Library
    5. Custom Toast with custom duration In LWC
    6. Dynamic Interaction Between Two LWCs
    7. Sending Wrapper object to Apex from LWC
    8. HeatMap Chart In LWC
    9. Generate and Create Signature in LWC
    10. Optimizing Salesforce Apex Code
    11. Optimizing Loop in Apex Code
    12. Handle Heap Size for Apex Code Optimization
    13. Enhance Apex Performance with Platform Caching
    14. Apex Trigger Code Optimization
    15. Optimize Code by Disabling Debug Mod
    16. Optimize Apex Code by Metadata Caching
    .net salesforce integration apex asp.net c# salesforce integration event based architecture event bus event message queue flow lightning lwc message oriented architecture missed event in platform event platform event replay salesforce salesforce .net integration salesforce c# integration salesforce microsoft
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleOpen Utility Bar On Lightning App Load
    Next Article Adding table row dynamically in Lightning Web Component
    Dhanik Lal Sahni
    • Website
    • Facebook
    • X (Twitter)

    With over 18 years of experience in web-based application development, I specialize in Salesforce technology and its ecosystem. My journey has equipped me with expertise in a diverse range of technologies including .NET, .NET Core, MS Dynamics CRM, Azure, Oracle, and SQL Server. I am dedicated to staying at the forefront of technological advancements and continuously researching new developments in the Salesforce realm. My focus remains on leveraging technology to create innovative solutions that drive business success.

    Related Posts

    By Dhanik Lal Sahni9 Mins Read

    10 Salesforce Chrome Extensions to Boost Your Productivity

    June 1, 2025
    By Dhanik Lal Sahni4 Mins Read

    How to Build a Generic Modal Window in Lightning Web Component

    May 26, 2025
    By Dhanik Lal Sahni6 Mins Read

    Top 10 Salesforce Flow Features of Salesforce Summer ’25

    May 11, 2025
    View 2 Comments

    2 Comments

    1. Chetan on October 19, 2020 9:21 pm

      Execellent job.Crisp and succint!

      Reply
      • Dhanik Lal Sahni on October 28, 2020 9:12 pm

        Thank You @Chetan.

        Regards
        Dhanik

        Reply
    Leave A Reply Cancel Reply

    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • 10 Salesforce Chrome Extensions to Boost Your Productivity
    • How to Build a Generic Modal Window in Lightning Web Component
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • Top 20 Salesforce Data Cloud Interview Questions & Answers for Admins June 5, 2025
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
    • How to Utilize Apex Properties in Salesforce November 3, 2024
    Archives
    Categories
    Tags
    apex (111) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code analysis (3) code optimization (8) custom metadata types (5) design principle (9) flow (15) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (65) lightning-combobox (5) lightning-datatable (10) lightning component (31) Lightning web component (63) lwc (52) named credential (8) news (4) optimize apex code (4) optimize apex trigger (3) Permission set (4) pmd (3) Queueable (9) rest api (23) S3 Server (4) salesforce (142) salesforce apex (47) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Facebook X (Twitter) Instagram Pinterest YouTube Tumblr LinkedIn Reddit Telegram
    © 2025 SalesforceCodex.com. Designed by Vagmine Cloud Solution.

    Type above and press Enter to search. Press Esc to cancel.

    Ad Blocker Enabled!
    Ad Blocker Enabled!
    Our website is made possible by displaying online advertisements to our visitors. Please support us by disabling your Ad Blocker.