• Andrew Fandre
  • NEWBIE
  • 30 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 2
    Likes Given
  • 5
    Questions
  • 13
    Replies
I have posted this on salesforce stack exchange (https://salesforce.stackexchange.com/questions/317374/forgot-username-lwc-controller-throws-error-outside-community) but I thought I'd post it here as well.

My forgot username Aura component works when I'm logged in, but when I'm not logged in, the Apex controller Errors out. How do I get this global component to work when not logged in?
I sure hope I can get some help, or at least another set of eyes on my problem.
My GET Request from C# works fine and retrieves data all day long
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            string oauthToken, serviceUrl;

            HttpClient authClient = new HttpClient();
            HttpContent content = GetClientContent();
            string tokenString = ConfigurationManager.AppSettings["tokenUrl"];

            HttpResponseMessage message = await authClient.PostAsync(tokenString, content);

            string responseString = await message.Content.ReadAsStringAsync();

            JObject obj = JObject.Parse(responseString);
            oauthToken = (string)obj["access_token"];
            serviceUrl = (string)obj["instance_url"];

            string service = ConfigurationManager.AppSettings.Get("RestService") + "sobjects/Case/describe/";
            string fullRequest = serviceUrl + service;


            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, fullRequest);
            request.Headers.Add("Authorization", "Bearer " + oauthToken);
            request.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            HttpClient queryClient = new HttpClient();
            HttpResponseMessage response = await queryClient.SendAsync(request);

            string result = await response.Content.ReadAsStringAsync();
But when I try a POST I get the dreaded [{\"message\":\"Session expired or invalid\",\"errorCode\":\"INVALID_SESSION_ID\"} 
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            HttpClient authClient = new HttpClient();
            HttpContent authContent = GetClientContent();
            string tokenString = ConfigurationManager.AppSettings["tokenUrl"];

            HttpResponseMessage authMessage = await authClient.PostAsync(tokenString, authContent);

            string responseString = await authMessage.Content.ReadAsStringAsync();

            JObject requestObj = JObject.Parse(responseString);
            string oauthToken = (string)requestObj["access_token"];
            string serviceUrl = (string)requestObj["instance_url"];

            string service = ConfigurationManager.AppSettings.Get("RestService") + "sobjects/Case/";
            string fullRequest = serviceUrl + service; 

            HttpRequestMessage POSTRequest = new HttpRequestMessage(HttpMethod.Post, fullRequest);

            POSTRequest.Headers.Add("Authorization", "Bearer " + oauthToken);
            POSTRequest.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            var caseJSON = JsonConvert.SerializeObject(ru);
            POSTRequest.Content = new StringContent(caseJSON, Encoding.UTF8, "application/json");

            HttpClient postClient = new HttpClient();

            HttpResponseMessage svcResp = await postClient.PostAsync(fullRequest, POSTRequest.Content);
            string caseResult = await svcResp.Content.ReadAsStringAsync();
Can someone eyeball this and give me a tip or pointer?
 
I enabled an Auth. Provider for our community to authenticate through our company OpenId server. I've got the connection working, it gets to our server, and I'm able to use it to authenticate, but when it returns to the community it just bounces back to the auth server, opening infinite new tabs.

Here's the code in the handler that I pulled from the Trailhead example that authenticates to Facebook.
global User createUser(Id portalId, Auth.UserData data){
        User u;
   
        if(!canCreateUser(data)) {
            u = null;
        } else {
            List<User> userList = [select id from User where email =: data.email];
           
            u = userList[0];
        }
        
        return u;
    }
The other method "canCreateUser" is just validating the data object values to see if they're null.

Any ideas why this is continuously requesting authorization?
 
I got a great autocomplete combobox example from here http://sfdcmonkey.com/2017/07/17/re-usable-custom-lookup/ and it works great. The autocomplete combobox composed two components one is the display, and the other is the lookup. When the lookup item is clicked it populates the display.

How do I populate the display combobox when it loads? 

I've added an init function and I get the stored value, and I can populate all the components in the init helper except I can't trigger the event or populate the lookupField with the value that's been stored. When I try to do anything on the doInit controller, nothing is defined, when I try to get to the view from the helper, nothing is defined. I'm bumping against the limits of my knowledge. 

I'll try to strip out the non-related code to keep it brief, but I'll post the full code if necessary.

Display Component
<aura:component controller="lookupController"  implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction"
                access="global">
    <aura:attribute name="selectedRecord" type="sObject" default="{}" description="Use,for store SELECTED sObject Record"/>
    <aura:attribute name="selectedLookupRecord" type="sObject" default="{}" />

    <aura:handler name="oSelectedRecordEvent" event="c:topicSelectEvent" action="{!c.handleComponentEvent}"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
Display box. This is the element I want to populate
<div aura:id="lookupField" class="slds-show">
                    <ui:inputText click="{!c.onfocus}" 
                                  updateOn="keyup" 
                                  keyup="{!c.keyPressController}" 
                                  class="slds-lookup__search-input slds-input leftPaddingClass" 
                                  value="{!v.SearchKeyWord}" 
                                  placeholder="search..."/>
                </div>
The call to the lookup component
<ul style="min-height:40px;margin-top:0px !important" 
            class="slds-listbox slds-listbox_vertical slds-dropdown slds-dropdown_fluid slds-lookup__menu slds" 
            role="listbox">
            
            <center> {!v.Message}</center>
            <aura:iteration items="{!v.listOfSearchRecords}" var="singleRec">
                <c:TopicSelect_result oRecord="{!singleRec}"/>
            </aura:iteration>
        </ul>
Display component controller
doInit : function(component, event, helper){
        helper.getTopicHelper(component,event,helper);
    }
Display component helper 
getTopicHelper : function(component,event) {
        var action = component.get("c.getDefaultTopic");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var responseValue = response.getReturnValue();
                component.set("v.selectedRecord" , responseValue);
                component.set("v.selectedLookupRecord" , responseValue);

            }           
        });
        $A.enqueueAction(action);

    },
Lookup Component
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global">
		<aura:attribute name="oRecord" type="sObject" />
		<!--Register the component level event-->
		
		<aura:registerEvent name="oSelectedRecordEvent" type="c:ADF_topicSelectEvent"/>
		
		<li role="presentation" class="slds-listbox__item" onclick="{!c.selectRecord}">
			<span id="listbox-option-unique-id-01" 
				  class="slds-media slds-listbox__option slds-listbox__option_entity slds-listbox__option_has-meta" 
				  role="option">
				<span class="slds-media__body">  
					<span class="slds-listbox__option-text slds-listbox__option-text_entity">{!v.oRecord.name}</span>
				</span>
			</span>
		</li>
	</aura:component>
Lookup Controller
({
	   selectRecord : function(component, event, helper){      
		  var getSelectRecord = component.get("v.oRecord");
		  var compEvent = component.getEvent("oSelectedRecordEvent");
			 compEvent.setParams({"recordByEvent" : getSelectRecord });  
			 compEvent.fire();
		},
	})
Event component
<aura:event type="COMPONENT" description="this event will pass the selected topic into parent component" >
		<aura:attribute name="recordByEvent" type="sObject"/>
	</aura:event>
Any help would be appreciated
 
I'm new to SF development. I've got a project where I'm using an Enterprise SOAP WSDL to make several complex queries. When I get the query result, the properties of each result object isn't accessible. I'm trying to get simple properties like Product2.Name and Product2.Id, but the Visual Studio parser throws an error and won't let me access the properties.

Here's the properties on the record object after binding to a query result.User-added image


But when I try to access the properties in the loop. I can't access any of the properties of the sfObject..
User-added image


How do I access the properties of the query result in an sObject?
 
I have posted this on salesforce stack exchange (https://salesforce.stackexchange.com/questions/317374/forgot-username-lwc-controller-throws-error-outside-community) but I thought I'd post it here as well.

My forgot username Aura component works when I'm logged in, but when I'm not logged in, the Apex controller Errors out. How do I get this global component to work when not logged in?
I sure hope I can get some help, or at least another set of eyes on my problem.
My GET Request from C# works fine and retrieves data all day long
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            string oauthToken, serviceUrl;

            HttpClient authClient = new HttpClient();
            HttpContent content = GetClientContent();
            string tokenString = ConfigurationManager.AppSettings["tokenUrl"];

            HttpResponseMessage message = await authClient.PostAsync(tokenString, content);

            string responseString = await message.Content.ReadAsStringAsync();

            JObject obj = JObject.Parse(responseString);
            oauthToken = (string)obj["access_token"];
            serviceUrl = (string)obj["instance_url"];

            string service = ConfigurationManager.AppSettings.Get("RestService") + "sobjects/Case/describe/";
            string fullRequest = serviceUrl + service;


            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, fullRequest);
            request.Headers.Add("Authorization", "Bearer " + oauthToken);
            request.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            HttpClient queryClient = new HttpClient();
            HttpResponseMessage response = await queryClient.SendAsync(request);

            string result = await response.Content.ReadAsStringAsync();
But when I try a POST I get the dreaded [{\"message\":\"Session expired or invalid\",\"errorCode\":\"INVALID_SESSION_ID\"} 
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            HttpClient authClient = new HttpClient();
            HttpContent authContent = GetClientContent();
            string tokenString = ConfigurationManager.AppSettings["tokenUrl"];

            HttpResponseMessage authMessage = await authClient.PostAsync(tokenString, authContent);

            string responseString = await authMessage.Content.ReadAsStringAsync();

            JObject requestObj = JObject.Parse(responseString);
            string oauthToken = (string)requestObj["access_token"];
            string serviceUrl = (string)requestObj["instance_url"];

            string service = ConfigurationManager.AppSettings.Get("RestService") + "sobjects/Case/";
            string fullRequest = serviceUrl + service; 

            HttpRequestMessage POSTRequest = new HttpRequestMessage(HttpMethod.Post, fullRequest);

            POSTRequest.Headers.Add("Authorization", "Bearer " + oauthToken);
            POSTRequest.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            var caseJSON = JsonConvert.SerializeObject(ru);
            POSTRequest.Content = new StringContent(caseJSON, Encoding.UTF8, "application/json");

            HttpClient postClient = new HttpClient();

            HttpResponseMessage svcResp = await postClient.PostAsync(fullRequest, POSTRequest.Content);
            string caseResult = await svcResp.Content.ReadAsStringAsync();
Can someone eyeball this and give me a tip or pointer?
 
Please help.

We are a C#/.NET shop, and have been using SFDC with the WSDL api.
We want to use REST instead of the WSDL, where we would use C#/.NET code to call the SFDC-REST servers.
Can some one point us to simple, C#/.NET samples that accomplish the following tasks:

1) Create a SFDC object, using REST, given a C# string, that is in a JSON format for the object to create, and get back the
SFDC-ID after creating the SFDC object.

2) Same as (1) abiove, but create the SFDC object with a PDF, HTML-Text, and Binary File, set of attachments.

3) Update a SFDC object using REST, given a SFDC-ID.

4) Same as (3) but update the object to have new attachments, for a PDF, HTML-Text, and Binary File, set of attachments.

5) Same as (4), but in the update, remove any attachments.

6) Same as (4), but replace an existing attachment, given a file-name (or attachment name) to have something different.

7) Search for record(s) related to an SFDC object, given a SFDC-ID.

8) Search for record(s) related to an SFDC object, given key field information.

9) Same as (8), but using wild-card/partial search criteria, like search for all records where field X starts with "ABC", or
matches "A?B", or "A*B", etc.

 
I enabled an Auth. Provider for our community to authenticate through our company OpenId server. I've got the connection working, it gets to our server, and I'm able to use it to authenticate, but when it returns to the community it just bounces back to the auth server, opening infinite new tabs.

Here's the code in the handler that I pulled from the Trailhead example that authenticates to Facebook.
global User createUser(Id portalId, Auth.UserData data){
        User u;
   
        if(!canCreateUser(data)) {
            u = null;
        } else {
            List<User> userList = [select id from User where email =: data.email];
           
            u = userList[0];
        }
        
        return u;
    }
The other method "canCreateUser" is just validating the data object values to see if they're null.

Any ideas why this is continuously requesting authorization?
 
I got a great autocomplete combobox example from here http://sfdcmonkey.com/2017/07/17/re-usable-custom-lookup/ and it works great. The autocomplete combobox composed two components one is the display, and the other is the lookup. When the lookup item is clicked it populates the display.

How do I populate the display combobox when it loads? 

I've added an init function and I get the stored value, and I can populate all the components in the init helper except I can't trigger the event or populate the lookupField with the value that's been stored. When I try to do anything on the doInit controller, nothing is defined, when I try to get to the view from the helper, nothing is defined. I'm bumping against the limits of my knowledge. 

I'll try to strip out the non-related code to keep it brief, but I'll post the full code if necessary.

Display Component
<aura:component controller="lookupController"  implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction"
                access="global">
    <aura:attribute name="selectedRecord" type="sObject" default="{}" description="Use,for store SELECTED sObject Record"/>
    <aura:attribute name="selectedLookupRecord" type="sObject" default="{}" />

    <aura:handler name="oSelectedRecordEvent" event="c:topicSelectEvent" action="{!c.handleComponentEvent}"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
Display box. This is the element I want to populate
<div aura:id="lookupField" class="slds-show">
                    <ui:inputText click="{!c.onfocus}" 
                                  updateOn="keyup" 
                                  keyup="{!c.keyPressController}" 
                                  class="slds-lookup__search-input slds-input leftPaddingClass" 
                                  value="{!v.SearchKeyWord}" 
                                  placeholder="search..."/>
                </div>
The call to the lookup component
<ul style="min-height:40px;margin-top:0px !important" 
            class="slds-listbox slds-listbox_vertical slds-dropdown slds-dropdown_fluid slds-lookup__menu slds" 
            role="listbox">
            
            <center> {!v.Message}</center>
            <aura:iteration items="{!v.listOfSearchRecords}" var="singleRec">
                <c:TopicSelect_result oRecord="{!singleRec}"/>
            </aura:iteration>
        </ul>
Display component controller
doInit : function(component, event, helper){
        helper.getTopicHelper(component,event,helper);
    }
Display component helper 
getTopicHelper : function(component,event) {
        var action = component.get("c.getDefaultTopic");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var responseValue = response.getReturnValue();
                component.set("v.selectedRecord" , responseValue);
                component.set("v.selectedLookupRecord" , responseValue);

            }           
        });
        $A.enqueueAction(action);

    },
Lookup Component
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global">
		<aura:attribute name="oRecord" type="sObject" />
		<!--Register the component level event-->
		
		<aura:registerEvent name="oSelectedRecordEvent" type="c:ADF_topicSelectEvent"/>
		
		<li role="presentation" class="slds-listbox__item" onclick="{!c.selectRecord}">
			<span id="listbox-option-unique-id-01" 
				  class="slds-media slds-listbox__option slds-listbox__option_entity slds-listbox__option_has-meta" 
				  role="option">
				<span class="slds-media__body">  
					<span class="slds-listbox__option-text slds-listbox__option-text_entity">{!v.oRecord.name}</span>
				</span>
			</span>
		</li>
	</aura:component>
Lookup Controller
({
	   selectRecord : function(component, event, helper){      
		  var getSelectRecord = component.get("v.oRecord");
		  var compEvent = component.getEvent("oSelectedRecordEvent");
			 compEvent.setParams({"recordByEvent" : getSelectRecord });  
			 compEvent.fire();
		},
	})
Event component
<aura:event type="COMPONENT" description="this event will pass the selected topic into parent component" >
		<aura:attribute name="recordByEvent" type="sObject"/>
	</aura:event>
Any help would be appreciated
 
The Topic Catalog Component proves that it is possible to create a component that lists out just the nav topics. How do we replicate this?
  • April 03, 2018
  • Like
  • 0
Hi
 trying to send http request to saleforce after the upgrade to tls 1.1 .

           byte[] buffer = Encoding.UTF8.GetBytes(urldata);
            HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
            WebReq.Method = "POST";
            WebReq.ContentType = "charset=utf-8";
            WebReq.ContentLength = buffer.Length;             
            Stream PostData = WebReq.GetRequestStream();
            PostData.Write(buffer, 0, buffer.Length);
            PostData.Close();
            HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();

The status of the request is "OK" but no lead is inserted
Getting this response

{Is-Processed: true Exception:common.exception.SalesforceGenericException
Vary: Accept-Encoding
Connection: close
Cache-Control: private
Content-Type: text/html;charset=UTF-8
Date: Sun, 22 Oct 2017 11:41:36 GMT
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Set-Cookie: BrowserId=-z9W_neATsuXA2laE8A2EA;Path=/;Domain=.salesforce.com;Expires=Thu, 21-Dec-2017 11:41:36 GMT;Max-Age=5184000


what am i doing wrong?


 
I'm new to SF development. I've got a project where I'm using an Enterprise SOAP WSDL to make several complex queries. When I get the query result, the properties of each result object isn't accessible. I'm trying to get simple properties like Product2.Name and Product2.Id, but the Visual Studio parser throws an error and won't let me access the properties.

Here's the properties on the record object after binding to a query result.User-added image


But when I try to access the properties in the loop. I can't access any of the properties of the sfObject..
User-added image


How do I access the properties of the query result in an sObject?
 
Within one of my Salesforce object, I have cascading picklists where the selection of one picklist displays values for the next level picklist. So I have three dependent picklists.

What I would like to do within my C# application using the REST API approach is to get back the dependent values based on the object field name and value I pass.

At the moment, my method to do this looks like the following:
public static async Task<List<ObjectFieldPicklistValue>> GetPicklistFieldItems(string objectApiName, string pickListFieldName)
{
    string cacheKey = "{objectApiName}|{pickListFieldName}";

    List<ObjectFieldPicklistValue> pickListValues = CacheEngine.Get<List<ObjectFieldPicklistValue>>(cacheKey);

    if (pickListValues == null)
    {
        Authentication salesforceAuth = await AuthenticationResponse.GetAccessToken();

        HttpClient queryClient = new HttpClient();

        string apiUrl = $"{SalesforceConfig.PlatformUrl}/services/data/v37.0/sobjects/{objectApiName}/describe";

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, apiUrl);
        request.Headers.Add("Authorization", $"Bearer {salesforceAuth.AccessToken}");
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = await queryClient.SendAsync(request);

        string outputJson = await response.Content.ReadAsStringAsync();

        if (!string.IsNullOrEmpty(outputJson))
        {
            // Get all the fields information from the object.
            ObjectFieldInfo objectField = JsonConvert.DeserializeObject<ObjectFieldInfo>(outputJson);

            // Filter the fields to get the required picklist.
            ObjectField pickListField = objectField.Fields.FirstOrDefault(of => of.Name == pickListFieldName && of.Type == "picklist");

            List<ObjectFieldPicklistValue> picklistItems = pickListField?.PicklistValues.ToList();

            #region Set cache

            pickListValues = picklistItems;

            // Add collection of pick list items to cache.
            CacheEngine.Add(picklistItems, cacheKey, 15);

            #endregion
        }
    }

    return pickListValues;
}
I am getting back the items of a picklist based on the object and field name. From my research online, I can see in the REST request that some of my picklist values have a "validFor" field. But don't exactly understand how to decipher this to get the dependent values.
HttpClient updateclient = new HttpClient();


            string requestMessage = "<root><name>test</name></root>";
            HttpContent updatecontent = new StringContent(requestMessage, Encoding.UTF8, "application/xml");

            //string requestMessage = "{\"Name\":\"DevForce20\"}";
            //HttpContent updatecontent = new StringContent(requestMessage, Encoding.UTF8, "application/json");

string updateurl = serviceUrl + "/services/data/v25.0/sobjects/Account/";


            //create request message associated with POST verb
            HttpRequestMessage request1 = new HttpRequestMessage(HttpMethod.Put,updateurl);

            //add token to header
            request1.Headers.Add("Authorization", "Bearer " + oauthToken);
          
            //return xml to the caller
            request1.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
            request1.Content = updatecontent;
        
            HttpResponseMessage response1 = await updateclient.PutAsync(updateurl+"001O000000MPrtsIAD",request1.Content);

            string resultipp = await response1.Content.ReadAsStringAsync();
           

            Response.Write(resultipp);

            return resultipp;
I got this error "[{\"message\":\"Session expired or invalid\",\"errorCode\":\"INVALID_SESSION_ID\"} .
If any one help me to resolve this.

I have a lightning web component that uses @wire to call to APEX. It works just fine when I place the component on a lightning page and display from a Salesforce user. However, the APEX never get's called when I place the component on a Community page.
Is there a setting that needs to be done to allow access from a community?
Thanks,
Hello, I have configured a connected app that is SAML enabled.  I am displaying the app in a Visualforce page using an iframe as part of the Case layout page.  You can see below that the src attribute of the iframe references the connected app’s startup url and then the connected app (which is an asp.net web page) is loaded.
 
<apex:page standardController="Case" >
     <apex:iframe id="CaseFrame" width="100%" height="500" scrolling="true"  src="https://domain.my.salesforce.com/idp/login?app=0sp1O000000fxTs" />
</apex:page>
 
While loading, it builds a SAML assertion which it then posts to my asp.net app’s ACS url (assertion consumer service).  This url is a configuration setting in SFDC.  Because it redirects like this and does a post, I don’t see a simple way to pass custom parameters to my app as below…(passing the case id in the src url)
 
<apex:page standardController="Case" >
          <apex:iframe id="MyIFrame" width="100%" height="220px" scrolling="false"  src="https://mydomin.paasnational.com/FM.aspx?cid={!case.ID}" />
</apex:page>
 
I see there is a way to add custom parameters to the SAML assertion by extending the Auth.ConnectedAppPlugin class.  I could write a SOQL query here and load business data that my connected app could consume, but I don’t see a way to add the case id of the Case that the current user is viewing with this approach like in the iframe above. 
 
Does anyone know of an approach I could use to pass the current case id to my saml enabled connected app?  Thanks.