Salesforce Integration using REST API

Working Sample Code for Salesforce Integration using REST API from Salesforce.

First register your app and select appropriate access to API with all relevant details.
Then register your callback url in CORS.

For more detail please refer to below Salesfore links:-

https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_query.htm
https://developer.salesforce.com/forums/?id=906F000000099zpIAA
https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/quickstart_oauth.htm

HTML and JQuery Script below:-

<h3>REST API With Javascript</h3>
<button id=”connect”>Connect to the REST API</button>
<h4>Create Account Record</h4>
<label for=”name”>Account Name</label>
<input type=”text” name=”Name” id=”name”>
<br><br>
<button id=”button”>Submit</button>
<button id=”getButton”>Get Account</button>

$(document).ready(function () {
$(‘#connect’).click(function () {

//The clientId and consumerSecret are the ones from the Connected App
var clientId = “****************”;
var consumerSecret = “*************”;
//Authorization endpoint
var authEndPoint = “https://login.salesforce.com/services/oauth2/authorize&#8221;;
//response_type must be set to token
var responseType = “token”;
//This is the callback URL from the connected app
var redirectURI = “https://&#8221;;
//Construct the URL with the required parameters
var requestURL = authEndPoint + ‘?client_id=’ + clientId + ‘&response_type=’ + responseType + ‘&redirect_uri=’ + redirectURI;
//redirect the user to the endpoint
window.location = requestURL;
});

//Create Account Record button click
$(‘#button’).click(function () {

var accountName = $(‘#name’).val();
var accessToken = decodeURI(GetURLParameter(‘access_token’));
console.log(accessToken);
if (accountName != ”) {
//replace the below url with your domain name or yourInstance.salesforce.com
var requestUrl = ‘https://eu11.salesforce.com/services/data/v20.0/sobjects/Account/&#8217;;
//create a javascript object with the account field values
var accountInfo = {
“Name”: accountName
}
//convert the object to a JSON string
var accountInfoJson = JSON.stringify(accountInfo);
//send POST with ajax
$.ajax({
type: ‘POST’,
url: requestUrl,
//add the authorization header including the access_token
headers: {
‘Authorization’: ‘Bearer ‘ + accessToken,
‘Content-Type’: ‘application/json’
},
data: accountInfoJson,
success: function (response) {
displayAccountInfo(response);
},
error: function (response) {
displayError(response);
}
});

} else {
alert(‘Please specify name’);
}

});

$(‘#getButton’).click(function () {

var accessToken = decodeURI(GetURLParameter(‘access_token’));
console.log(accessToken);
if (1 != 2) {
//replace the below url with your domain name or yourInstance.salesforce.com
var requestUrl = ‘https://.salesforce.com/services/data/v20.0/query/?q=SELECT name from Account’;

$.ajax({
type: ‘GET’,
url: requestUrl,
//add the authorization header including the access_token
headers: {
‘Authorization’: ‘Bearer ‘ + accessToken,
‘Content-Type’: ‘application/json’
},
// data: accountInfoJson,
success: function (response) {
displayAccountData(response);
},
error: function (response) {
displayError(response);
}
});

} else {
alert(‘Please specify name’);
}

});

});
function displayAccountData(responseObject) {
var statusMessage = ‘

Account Detail

‘;
$(‘#status’).append(JSON.stringify(responseObject));
$(‘‘, {//replace this with your salesforce instance url
text: ‘
https://eu5.salesforce.com/&#8217; + responseObject.id,
href: ‘https://eu5.salesforce.com/&#8217; + responseObject.id,
target: ‘_blank’
}).appendTo($(‘#status’));
}
function displayAccountInfo(responseObject) {
var statusMessage = ‘

Success! Your account has been created, click on the link below.

‘;
$(‘#status’).append(statusMessage);
$(‘‘, {//replace this with your salesforce instance url
text: ‘
https://eu5.salesforce.com/&#8217; + responseObject.id,
href: ‘https://eu5.salesforce.com/&#8217; + responseObject.id,
target: ‘_blank’
}).appendTo($(‘#status’));
}
//Use this function to get the access token from the URL
function GetURLParameter(sParam) {
var mainURL = document.location + ”;
var pageUrls = mainURL.split(‘#’);
var sURLVariables = pageUrls[1].split(‘&’);
for (var i = 0; i A problem has occurred, please contact your administrator

‘;
$(‘#status’).append(statusMessage);
$(‘

‘, {
text: responseJson[0].errorCode + “: ” + responseJson[0].message
}).appendTo($(‘#status’));

}

 

 

Advertisements

Host ASP.Net Core With IIS

Things to know ASP.Net Core run as separate unlike classic ASP.Net which run in process of the IIS Worker Process.

ASP.Net Core run in it’s own web server using highly optimised Kestrel component .

ASP.NET Core applications are standalone Console applications invoked through the dotnet runtime command. It uses AspNetCoreModule to execute the external console.
The AspNetCoreModule loades when the first request comes and then routed to your ASP.NET Core application.

Incoming request int the kernel mode http.sys which routes into IIS.
The request is then forwarded to your ASP.NET Core application on the HTTP port,
Kestrel pushes the request into the ASP.NET Core middleware pipeline which then handles your request and HTTP output is then passed back to the IIS.

Web.Config

<?xml version=”1.0″ encoding=”utf-8″?>
<configuration>
<system.webServer>
<handlers>
<add name=”aspNetCore” path=”*” verb=”*” modules=”AspNetCoreModule” resourceType=”Unspecified” />
</handlers>
<aspNetCore processPath=”dotnet” arguments=”.\WAppCore.dll” stdoutLogEnabled=”false” stdoutLogFile=”.\logs\stdout” />
</system.webServer>
</configuration>

Note: Check AspNetCoreModule is installed in IIS.
This can be installed using ASP.Net Core SDK

 

 

 

Configure Hyper V Virtual Machine With Internet Connection via Laptop WIFI

In order to connect your Hyper-V machine with the internet will require virtual network adaptor and sharing internet via wifi network in your laptop.

  1. Create Virtual adaptor
    1. Go to Hyper V manager
    2. Do not select any Hyper-V machine instance
    3. Select machine name on left pane
    4. From Action menu select Virtual Switch manager
    5. Select Internal Only
    6. From right pane Select Internal
    7. Press the Create Virtual Switch button
    8. Enter name of your Virtual Switch
    9. Check the VLAN ID checkbox
    10. Click OK to save
  2. Select the Instance of Hyper-V machine
  3. Click on settings using right click or from right pane
  4. Select your Network adaptor from the left pane
  5. From Right pane
  6. Select your virtual adaptor from the drop down option created in step -1.8
  7. Check the VLAN ID check box
  8. Click OK
  9. Go to “Control Panel –> Network and Internet –> Network and Sharing Centre”
  10. Click “Change adaptor settings”
  11. Go to properties of WIFI adaptor
  12. Click on Sharing Tab
  13. Check the allow network users to connect through this computer’s internet connection.
  14. Click OK.
  15. Select the virtual LAN created in step-1 from the drop down option
  16. Select your Virtual Adaptor as created in step-1.8
  17. Go to Properties
  18. Double click Internet Protocol Version 4 (TCP/IPv4)
  19. IP address will default to 192.168.137.1
  20. under DNS add 8.8.8.8 and 8.8.4.4

For network connection problem click here

ASP.Net Core SPA Application Command Line

ASP.NET Core is initialized from the Startup class in the application

wwwroot folder contains static files (like js, css and image files for our web application).

project.json file. JavaScript object notation to store configuration information and it is this file that is really the heart of a .NET application.

 
<environment names=”Development”>
<link rel=”stylesheet” href=”~/view-resources/Areas/AppAreaName/Views/Users/Index.css” asp-append-version=”true” />
</environment>

<environment names=”Staging,Production”>
<link rel=”stylesheet” href=”~/view-resources/Areas/AppAreaName/Views/Users/Index.min.css” asp-append-version=”true” />
</environment>

Below are the commands to setup SPA in ASP.Net Core

COMMANDS:-

dotnet new –install Microsoft.AspNetCore.SpaTemplates::*

dotnet new angular

dotnet restore

npm install

start

  • npm i -g webpack
  • npm i webpack-compiler

How to change environment in ASP.Net Core application?

If are getting error after deploying your ASP.Net Core application in Azure PaaS environment and want to see quick error stack then you need to make change in web.config file

1. Web.config file settings:-

<aspNetCore …>
<environmentVariables>
<environmentVariable name=”ASPNETCORE_ENVIRONMENT” value=”Development” />
</environmentVariables>
</aspNetCore>

Also check your appsetting.json file.

SharePoint Check User Permission

This is code snippet to check if user has role permission

/// Find the particular role definition to check agaionst the user has permisson
SPRoleDefinition roleDefinition = web.RoleDefinitions.GetByType(SPRoleType.Administrator);
SPUser siteUser = web.SiteUsers[“SP\\mukesh”];

///Get all permission for the selected user
SPPermissionInfo userPermissions = web.GetUserEffectivePermissionInfo(siteUser.LoginName);

///Check role is is assigned to the user
var memberof = userPermissions.RoleAssignments.Where(role => role.RoleDefinitionBindings.Contains(roleDefinition)).Select(roleMember => roleMember.Member).ToList();