Home Salesforce Publish Platform Events from ASP.NET

Publish Platform Events from ASP.NET

by Dhanik Lal Sahni
Publish-Platfrom-Event-From-ASP.NET SalesforceCodex

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).

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:

You may also like

2 comments

Chetan October 19, 2020 - 9:21 pm

Execellent job.Crisp and succint!

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

Thank You @Chetan.

Regards
Dhanik

Reply

Leave a Comment