I am trying pass contact id as a parameter to one of the webservices and get value to update in account object. But i am not able to set contact records ID field as a parameter in end point URL.
List<Contact> ContactUpdate = [SELECT id FROM Contact where Rep__c like 'CRM%'];
String ContactID;
HttpRequest req = new HttpRequest();
req.setTimeout(60000);
req.setHeader('Accept','*/*');
req.setHeader('Content-Type','application/json'); // Content Type
req.setMethod('GET');
for (Contact c : ContactUpdate)
{
ContactID = c.id;
req.setEndpoint('https://xxx/xxxx/xxxxx/xxx/xxx-lookup? ContactID= {! ContactID});
Http http = new Http();
HTTPResponse res = http.send(req);
System.debug(res.getBody());
JSONParser parser = JSON.createParser(res.getBody());
String GMMID;
while (parser.nextToken() != null) {
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
(parser.getText() == 'GCGMM')) {
// Get the value.
parser.nextToken();
// Compute the grand total price for all invoices.
GMMID = parser.gettext();
}
}
//ContactUpdate.IsFutureContext__c = true;
C.Group_ID__c = GMMID;
update c;
}
Could someone please guide me in adding variable as parameter in endpoint URL.
Try using the body and removing it from your endpoint.
String body = 'ContactID=' + contactID;
req.setbody(body);
Related
On the Autoresponder I map a certain endpoint to respond to a certain URL request received.
I would like the endpoint receives the QUERY STRING and POST DATA, too.
I thought it was possible through the "REGEX:" wrapper in the rule, but it cannot capture any subexpression to pass to the mapped endpoint.
Can it be done through FiddlerScript? How to reference request and mapped endpoint?
This solution in C# allows to incercept the request to www.example-1.com and forward it to www.example-2.com, chaining possible query string and filling POSTDATA if given:
// match regex
string regex = "example-1.com/somepath/.*";
Regex rgx = new Regex(regex);
Match match = rgx.Match(oSession.fullUrl);
if (match.Success) {
// GET request -> replace the original URL with "https://www.example-2.com"
if (oSession.HTTPMethodIs("GET")) {
string qs = oSession.fullUrl.Split('?')[1];
oSession.fullUrl = oSession.fullUrl.Replace(oSession.fullUrl, "https://www.example-2.com/path?" + qs);
} else if (oSession.HTTPMethodIs("POST")) {
// Create an HTTP request to www.example-2.com and forward the request body saved above:
oSession.utilCreateResponseAndBypassServer();
var reqBody = oSession.GetRequestBodyAsString();
var data = Encoding.ASCII.GetBytes(reqBody);
var request = (HttpWebRequest)WebRequest.Create("https://plugvue.com/test/request-parser/api-write.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream()) {
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
}
It has to be put inside the OnBeforeRequest(Session oSession) handler.
I have a ldap method that returns all users that are in it (almost 1300 users) and I want to return them by page, similar to what PagingAndSortingRepository does in Springboot:
If I have this endpoint ( users/?page=0&size=1 )and I wnat to return on page 0 just 1 entry.
Is there any way to do that?
Currently I have this but it doesn´t work:
SearchRequest searchRequest = new SearchRequest(ldapConfig.getBaseDn(), SearchScope.SUB,
Filter.createEqualityFilter("objectClass", "person"));
ASN1OctetString resumeCookie = null;
while (true) {
searchRequest.setControls(new SimplePagedResultsControl(pageable.getPageSize(), resumeCookie));
SearchResult searchResult = ldapConnection.search(searchRequest);
numSearches++;
totalEntriesReturned += searchResult.getEntryCount();
for (SearchResultEntry e : searchResult.getSearchEntries()) {
String[] completeDN = UaaUtils.searchCnInDn(e.getDN());
String[] username = completeDN[0].split("=");
UserEntity u = new UserEntity(username[1]);
list.add(u);
System.out.println("TESTE");
}
SimplePagedResultsControl responseControl = SimplePagedResultsControl.get(searchResult);
if (responseControl.moreResultsToReturn()) {
// The resume cookie can be included in the simple paged results
// control included in the next search to get the next page of results.
System.out.println("Antes "+resumeCookie);
resumeCookie = responseControl.getCookie();
System.out.println("Depois "+resumeCookie);
} else {
break;
}
Page<UserEntity> newPage = new PageImpl<>(list, pageable, totalEntriesReturned);
System.out.println("content " + newPage.getContent());
System.out.println("total elements " + newPage.getTotalElements());
System.out.println(totalEntriesReturned);
}
I'm unsure if this is the proper way, but here's how I went about it:
public PaginatedLookup getAll(String page, String perPage) {
PagedResultsCookie cookie = null;
List<LdapUser> results;
try {
if ( page != null ) {
cookie = new PagedResultsCookie(Hex.decode(page));
} // end if
Integer pageSize = perPage != null ? Integer.parseInt(perPage) : PROCESSOR_PAGE_SIZE;
PagedResultsDirContextProcessor processor = new PagedResultsDirContextProcessor(pageSize, cookie);
LdapName base = LdapUtils.emptyLdapName();
SearchControls sc = new SearchControls();
sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
sc.setTimeLimit(THREE_SECONDS);
sc.setCountLimit(pageSize);
sc.setReturningAttributes(new String[]{"cn", "title"});
results = ldapTemplate.search(base, filter.encode(), sc, new PersonAttributesMapper(), processor);
cookie = processor.getCookie();
} catch ( Exception e ) {
log.error(e.getMessage());
return null;
} // end try-catch
String nextPage = null;
if ( cookie != null && cookie.getCookie() != null ) {
nextPage = new String(Hex.encode(cookie.getCookie()));
} // end if
return new PaginatedLookup(nextPage, results);
}
The main issue I kept on hitting was trying to get the cookie as something that could be sent to the client, which is where my Hex.decode and Hex.encode came in handy.
PersonAttributesMapper is a private mapper that I have to make the fields more human readable, and PaginatedLookup is a custom class I use for API responses.
I'm converting a web forms application to asp.net core mvc. In my web forms application sometimes after I set some response cookies other code needs to see if they were set, and if so, access the cookie's properties (i.e. value, Expires, Secure, http). In webforms and MVC 5 it's possible to iterate over the cookies and return any particular cookies like so (old school I know)
for(int i = 0; i < cookies.Count; i++) {
if(cookies[i].Name == cookieName) {
return cookies[i];
}
}
But the interface for accessing response cookies in asp.net core mvc looks like this:
Based on this interface I don't see a way to check to see if a response cookie exists and obtain it's properties. But there has gotta be some way to do it?
In an action method I tried setting two cookies on the response object and then immediately trying to access them. But intellisense doesn't show any methods, properties or indexers that would allow me to access them:
For a moment, I thought that perhaps I could use Response.Cookies.ToString(); and just parse the information to find my cookie info, but alas, the ToString() call returns "Microsoft.AspNet.Http.Internal.ResponseCookies" because the object doesn't override the default implementation.
Just for fun I also checked the current dev branch of GitHub to see if the interface has changed since RC1 but it has not. So given this interface, how do I check for the existence of a response cookie and get it's properties? I've thought about trying to hack in via the response headers collection but that seems pretty lame.
There is an extension method available in Microsoft.AspNetCore.Http.Extensions called GetTypedHeaders(). This can be called on HttpContext.Response to read Set-Cookie headers. For example in middleware perhaps we want to intercept a Set-Cookie response header and replace it:
public async Task Invoke(HttpContext httpContext)
{
httpContext.Response.OnStarting(state =>
{
var context = (HttpContext)state;
var setCookieHeaders = context.Response.GetTypedHeaders().SetCookie;
// We assume only one cookie is found. You could loop over multiple matches instead.
// setCookieHeaders may be null if response doesn't contain set-cookie headers
var cookie = setCookieHeaders?.FirstOrDefault(x => x.Name == "mycookiename");
if (cookie == null)
{
return Task.CompletedTask;
}
var opts = new CookieOptions
{
HttpOnly = true,
Expires = DateTimeOffset.Now.AddHours(12),
SameSite = SameSiteMode.Lax,
Secure = true
};
context.Response.Cookies.Delete(cookie.Name.Value);
context.Response.Cookies.Append(cookie.Name.Value, "mynewcookievalue", opts);
return Task.CompletedTask;
}, httpContext);
await _next(httpContext);
}
Here's how I get the value of a cookie from a Response. Something like this could be used to get the whole cookie if required:
string GetCookieValueFromResponse(HttpResponse response, string cookieName)
{
foreach (var headers in response.Headers.Values)
foreach (var header in headers)
if (header.StartsWith($"{cookieName}="))
{
var p1 = header.IndexOf('=');
var p2 = header.IndexOf(';');
return header.Substring(p1 + 1, p2 - p1 - 1);
}
return null;
}
There is an obvious problem with Shaun's answer: it will match any HTTP-header having matching value. The idea should be to match only cookies.
A minor change like this should do the trick:
string GetCookieValueFromResponse(HttpResponse response, string cookieName)
{
foreach (var headers in response.Headers)
{
if (headers.Key != "Set-Cookie")
continue;
string header = headers.Value;
if (header.StartsWith($"{cookieName}="))
{
var p1 = header.IndexOf('=');
var p2 = header.IndexOf(';');
return header.Substring(p1 + 1, p2 - p1 - 1);
}
}
return null;
}
Now the checking for a cookie name will target only actual cookie-headers.
You can use this function to get full information about the cookie set value
private SetCookieHeaderValue GetCookieValueFromResponse(HttpResponse response, string cookieName)
{
var cookieSetHeader = response.GetTypedHeaders().SetCookie;
if (cookieSetHeader != null)
{
var setCookie = cookieSetHeader.FirstOrDefault(x => x.Name == cookieName);
return setCookie;
}
return null;
}
In my case I had to get only value of auth= and don't care about other values, but you can easy rewrite code to get dict of cookie values.
I wrote this extension for HttpResponseMessage, in order to avoid work with index and substring, I separate string to array and then cast it to dictionary
internal static string GetCookieValueFromResponse(this HttpResponseMessage httpResponse, string cookieName)
{
foreach (var cookieStr in httpResponse.Headers.GetValues("Set-Cookie"))
{
if(string.IsNullOrEmpty(cookieStr))
continue;
var array = cookieStr.Split(';')
.Where(x => x.Contains('=')).Select(x => x.Trim());
var dict = array.Select(item => item.Split(new[] {'='}, 2)).ToDictionary(s => s[0], s => s[1]);
if (dict.ContainsKey(cookieName))
return dict[cookieName];
}
return null;
}
You can get the cookie string value from the response using this method. In this case, I'm using this logic in a CookieService, that is the reason you will see that I'm using the _contextAccessor. Notice that in this case, I'm returning null if the value of the cookie is empty. (This is optional)
private string GetCookieFromResponse(string cookieName)
{
var cookieSetHeader = _contextAccessor.HttpContext.Response.GetTypedHeaders().SetCookie;
var cookie = cookieSetHeader?.FirstOrDefault(x => x.Name == cookieName && !string.IsNullOrEmpty(x.Value.ToString()));
var cookieValue = cookie?.Value.ToString();
if (!string.IsNullOrEmpty(cookieValue))
{
cookieValue = Uri.UnescapeDataString(cookieValue);
}
return cookieValue;
}
If you are looking for a solution that gets the cookie from the response or the request in that order then you can use this.
private string GetCookieString(string cookieName)
{
return GetCartCookieFromResponse(cookieName) ?? GetCartCookieFromRequest(cookieName) ?? "";
}
private string GetCookieFromRequest(string cookieName)
{
return _contextAccessor.HttpContext.Request.Cookies.ContainsKey(cookieName) ? _contextAccessor.HttpContext.Request.Cookies[cookieName] : null;
}
private string GetCookieFromResponse(string cookieName)
{
var cookieSetHeader = _contextAccessor.HttpContext.Response.GetTypedHeaders().SetCookie;
var cookie = cookieSetHeader?.FirstOrDefault(x => x.Name == cookieName && !string.IsNullOrEmpty(x.Value.ToString()));
var cookieValue = cookie?.Value.ToString();
if (!string.IsNullOrEmpty(cookieValue))
{
cookieValue = Uri.UnescapeDataString(cookieValue);
}
return cookieValue;
}
The snippet seems to work for me. The result for me (derived from Shaun and Ron) looks like:
public static string GetCookieValueFromResponse(HttpResponse response, string cookieName)
{
// inspect the cookies in HttpResponse.
string match = $"{cookieName}=";
var p1 = match.Length;
foreach (var headers in response.Headers)
{
if (headers.Key != "Set-Cookie")
continue;
foreach (string header in headers.Value)
{
if (header.StartsWith(match) && header.Length > p1 && header[p1] != ';')
{
var p2 = header.IndexOf(';', p1);
return header.Substring(p1 + 1, p2 - p1 - 1);
}
}
}
return null;
}
In cases where multiple "Set-Cookie" headers exists the last one should be used:
private string GetCookieValueFromResponse(Microsoft.AspNetCore.Http.HttpResponse response, string cookieName)
{
var value = string.Empty;
foreach (var header in response.Headers["Set-Cookie"])
{
if (!header.Trim().StartsWith($"{cookieName}="))
continue;
var p1 = header.IndexOf('=');
var p2 = header.IndexOf(';');
value = header.Substring(p1 + 1, p2 - p1 - 1);
}
return value;
}
My Put method is as follows:
public void Post([FromBody]RavenUserView view)
{
if (ModelState.IsValid)
{
var request = new CreateUserRequest();
request.ID = view.ID;
request.Name = view.Name;
request.UserName = view.UserName;
request.Password = EncryptionDecryption.EncryptString(view.Password);//Encrypt The Password
request.Email = view.Email;
request.Phone = view.Phone;
request.Country = "x";
request.Note = "y";
request.IsActive = view.IsActive;
request.Creator = view.Creator;
request.CreationDate = DateTime.UtcNow;
request.ModificationDate = DateTime.UtcNow;
request.Remarks = "z";
var response = _facade.CreateUser(request);
SaveUserDetailsToCookie(response.RavenUser.ID, response.RavenUser.UserName, EncryptionDecryption.DecryptString(response.RavenUser.Password));//Cookie should be stored Decrypted Format
HttpContext.Current.Session[SessionDataKey.UserId.ToString()] = response.RavenUser.ID.ToString();
HttpContext.Current.Session[SessionDataKey.UserName.ToString()] = response.RavenUser.UserName;
}
}
But When I run my project and try to save my information then it throw me an exception "Object Reference is not set to the reference of an object"
I am using Web Api as my controller class.
After reading various documents I found that Api is stateless. Now how can I store my user information for further use.
Use:
public void Post([Bind(Include = "ID,Name,UserName,....")] CreateUserRequest request)
{
if(ModelState.IsValid)
{
var response = _facade.CreateUser(request);
SaveUserDetailsToCookie(response.RavenUser.ID, response.RavenUser.UserName, EncryptionDecryption.DecryptString(response.RavenUser.Password));//Cookie should be stored Decrypted Format
HttpContext.Current.Session[SessionDataKey.UserId.ToString()] = response.RavenUser.ID.ToString();
HttpContext.Current.Session[SessionDataKey.UserName.ToString()] = response.RavenUser.UserName;
}
}
I have an Account object, which has many Transactions related to it.
In one method, I get all transactions for a particular account.
var transactionlines = (from p in Context.account_transaction
.Include("account_transaction_line")
// .Include("Account")
.Include("account.z_account_type")
.Include("account.institution")
.Include("third_party")
.Include("third_party.z_third_party_type")
.Include("z_account_transaction_type")
.Include("account_transaction_line.transaction_sub_category")
.Include("account_transaction_line.transaction_sub_category.transaction_category")
.Include("z_account_transaction_entry_type")
.Include("account_transaction_line.cost_centre")
where p.account_id == accountId
&& p.deleted == null
select p).ToList();
This is meant to return me a list of transactions, with their related objects. I then pass each object to a Translator, which translates them into data transfer objects, which are then passed back to my main application.
public TransactionDto TranslateTransaction(account_transaction source)
{
LogUserActivity("in TranslateTransaction");
var result = new TransactionDto
{
Id = source.id,
Version = source.version,
AccountId = source.account_id,
// Account = TranslateAccount(source.account, false),
ThirdPartyId = source.third_party_id,
ThirdParty = TranslateThirdParty(source.third_party),
Amount = source.transaction_amount,
EntryTypeId = source.account_transaction_entry_type_id,
EntryType = new ReferenceItemDto
{
Id = source.account_transaction_entry_type_id,
Description = source.z_account_transaction_entry_type.description,
Deleted = source.z_account_transaction_entry_type.deleted != null
},
Notes = source.notes,
TransactionDate = source.transaction_date,
TransactionTypeId = source.account_transaction_type_id,
TransactionType = new ReferenceItemDto
{
Id = source.z_account_transaction_type.id,
Description = source.z_account_transaction_type.description,
Deleted = source.z_account_transaction_type.deleted != null
}
};
... return my object
}
The problem is:
An account has Transactions, and a Transaction therefore belongs to an Account. It seems my translators are being called way too much, and reloading a lot of data because of this.
When I load my transaction object, it's 'account' property has a'transactions' propery, which has a list of all the transactions associated to that account. Each transaction then has an account property... and those account peroprties again, have a list of all the transactions... and on and on it goes.
Is there a way I can limit the loading to one level or something?
I have this set:
Context.Configuration.LazyLoadingEnabled = false;
I was hoping my 'Includes' would be all that is loaded... Don't load 'un-included' related data?
As requested, here is my TranslateAccount method:
public AccountDto TranslateAccount(account p, bool includeCardsInterestRateDataAndBalance)
{
LogUserActivity("in TranslateAccount");
if (p == null)
return null;
var result =
new AccountDto
{
Id = p.id,
Description = p.description,
PortfolioId = p.institution.account_portfolio_id,
AccountNumber = p.account_number,
Institution = TranslateInstitution(p.institution),
AccountType = new ReferenceItemDto
{
Id = p.account_type_id,
Description = p.z_account_type.description
},
AccountTypeId = p.account_type_id,
InstitutionId = p.institution_id,
MinimumBalance = p.min_balance,
OpeningBalance = p.opening_balance,
OpeningDate = p.opening_date
};
if (includeCardsInterestRateDataAndBalance)
{
// Add the assigned cards collection
foreach (var card in p.account_card)
{
result.Cards.Add(new AccountCardDto
{
Id = card.id,
AccountId = card.account_id,
Active = card.active,
CardHolderName = card.card_holder_name,
CardNumber = card.card_number,
ExpiryDate = card.expiry
});
}
// Populate the current interest rate
result.CurrentRate = GetCurrentInterestRate(result.Id);
// Add all rates to the account
foreach (var rate in p.account_rate)
{
result.Rates.Add(
new AccountRateDto
{
Id = rate.id,
Description = rate.description,
Deleted = rate.deleted != null,
AccountId = rate.account_id,
EndDate = rate.end_date,
Rate = rate.rate,
StartDate = rate.start_date
});
}
result.CurrentBalance = CurrentBalance(result.Id);
}
LogUserActivity("out TranslateAccount");
return result;
}
The entity framework context maintains a cache of data that has been pulled out of the database. Regardless of lazy loading being enabled/disabled, you can call Transaction.Account.Transactions[0].Account.Transactions[0]... as much as you want without loading anything else from the database.
The problem is not in the cyclical nature of entity framework objects - it is somewhere in the logic of your translation objects.