How do I get the balance of a specific token on the BSC using Nethereum and Quicknodes? - binance-smart-chain

I have already purchased a node on quicknodes and have the API. I was able to retrieve my BNB balance by using this code, however, I would like to retrieve the balance of a specific token in my wallet other than BNB. Could someone point me in the right direction?
var balance = await web3.Eth.GetBalance.SendRequestAsync("ADDRESS GOES HERE");
Console.WriteLine("Balance of Ethereum Foundation's account: " + balance.Value);

var web3 = new Web3("provider address");
string abi = #"[{""inputs"":[{""internalType"":""address"",""name"":""account"",""type"":""address""}],""name"":""balanceOf"",""outputs"":[{""internalType"":""uint256"",""name"":"""",""type"":""uint256""}],""stateMutability"":""view"",""type"":""function""}]";
string contractaddress = "contractAddress";
var contract = web3.Eth.GetContract(abi, contractaddress);
var function = contract.GetFunction("balanceOf");
string address = "walletAddress";
BigInteger balance = await function.CallAsync<BigInteger>(address);

Related

Parse Server - Get Pinned Object using Labels

I am storing objects in the Local Datastore via Pinning. I can pin objects under a label (e.g. following). If I want to return all of the people that a user is following there doesn't seem to be a way to do that. I can't even find a way to return all pinned objects regardless of their label. Am I missing something?
Here is my code for storing a person object in my Local Datastore:
peer.pinWithName( 'Followed' );
I can find out if the peer is followed using:
const Followed = Parse.Object.extend( 'Peer' );
const query = new Parse.Query( Followed );
query.fromLocalDatastore();
response = await query.get( peer.id );
Querying all objects from local data store
const Followed = Parse.Object.extend('Peer');
const query = new Parse.Query(Followed);
query.fromLocalDatastore();
response = await query.find();
Reference: https://docs.parseplatform.org/js/guide/#querying-the-local-datastore
Querying an object from pin with name
const Followed = Parse.Object.extend('Peer');
const query = new Parse.Query(Followed);
query.fromPinWithName('Followed');
response = await query.get(peer.id);
Querying all objects from pin with name
const Followed = Parse.Object.extend('Peer');
const query = new Parse.Query(Followed);
query.fromPinWithName('Followed');
response = await query.find();
Reference: http://parseplatform.org/Parse-SDK-JS/api/2.7.0/Parse.Query.html#fromPinWithName

Automatically map a Contact to an Account

I want to add a field to Accounts which shows the email domain for that account e.g. #BT.com. I then have a spreadsheet which lists all the Accounts and their email domains. What I want to do is when a new Contact is added to Dynamics that it checks the spreadsheet for the same email domain (obviously without the contacts name in the email) and then assigned the Contact to the Account linked to that domain. Any idea how I would do this. Thanks
Probably best chance would be to develop CRM plugin. Register your plugin to be invoked when on after contact is created or updated (so called post-event phase). And in your plugin update the parentaccountid property of the contact entity to point to account of your choice.
Code-wise it goes something like (disclaimer: not tested):
// IPluginExecutionContext context = null;
// IOrganizationService organizationService = null;
var contact = (Entity)context.InputParameters["Target"];
var email = organizationService.Retrieve("contact", contact.Id, new ColumnSet("emailaddress1")).GetAttributeValue<string>("emailaddress1");
string host;
try
{
var address = new MailAddress(email);
host = address.Host;
}
catch
{
return;
}
var query = new QueryExpression("account");
query.TopCount = 1;
// or whatever the name of email domain field on account is
query.Criteria.AddCondition("emailaddress1", ConditionOperator.Contains, "#" + host);
var entities = organizationService.RetrieveMultiple(query).Entities;
if (entities.Count != 0)
{
contact["parentaccountid"] = entities[0].ToEntityReference();
}
organizationService.Update(contact);
I took Ondrej's code and cleaned it up a bit, re-factored for pre-operation. I also updated the logic to only match active account records and moved the query inside the try/catch. I am unfamiliar with the MailAddress object, I personally would just use string mapping logic.
var target = (Entity)context.InputParameters["Target"];
try
{
string host = new MailAddress(target.emailaddress1).Host;
var query = new QueryExpression("account");
query.TopCount = 1;
// or whatever the name of email domain field on account is
query.Criteria.AddCondition("emailaddress1", ConditionOperator.Contains, "#" + host);
query.Criteria.AddCondition("statecode", ConditionOperator.Equals, 0); //Active records only
var entities = organizationService.RetrieveMultiple(query).Entities;
if (entities.Count != 0)
{
target["parentaccountid"] = entities[0].ToEntityReference();
}
}
catch
{
//Log error
}

Visual Studio Online SDK

I am working on a project where I have a requirement to create workitem on Visual Studio Online instance. I am using personal access token. This will set CreatedBy as my name (Expected behavior). I am considering to use Oauth2; However, I am not sure if there's the way to do this Server-to-Server (Non-Interactive)? Any suggestions thoughts?
var personalAccessToken = "PAT Value fro Config";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "", personalAccessToken))));
return client;
PAT's are created in Security context of the user. I need to find a way to use Oauth without having to involved UI. So I'm looking for Server-to-Server Auth.
object[] patchDocument = new object[5];
patchDocument[0] = new { op = "add", path = "/fields/System.Title", value = bugTitle };
patchDocument[1] = new { op = "add", path = "/fields/Microsoft.VSTS.TCM.ReproSteps", value = bugReproSteps };
patchDocument[2] = new { op = "add", path = "/fields/Microsoft.VSTS.Common.Priority", value = "1" };
patchDocument[3] = new { op = "add", path = "/fields/Microsoft.VSTS.Common.Severity", value = "2 - High" };
patchDocument[4] = new { op = "add", path = "/fields/System.IterationPath", value = deserializeIteration };
//System.IterationPath
string postUrl = $"{_vsoInstanceUrl}/DefaultCollection/ProjectName/_apis/wit/workitems/$Bug?api-version=1.0";
await ExecutePatch(patchDocument.ToArray(), postUrl, "application/json-patch+json");
No there is no Server-to-Server OAuth support. If you use the .NET Client Object Model you can leverage Impersonation support.
If your account has "Act on behalf of others" permissions you can also achieve a "User X via YourAccount".

Yammer "Follow in Inbox" API support

My company has created a Yammer application that we use internally. Our app automatically subscribes people to various threads that have been created. We have found that there is a difference between "subscribing" someone to a thread and what happens when a user clicks the "follow in inbox" link on the site. When we automatically subscribe people, the only thing that we can see happening is that the thread will appear in the users "Following" section in the Home tab. Contrast this with what happens when a user clicks the "Follow in Inbox" link. From that point on any comments added to the thread will show up in the user's inbox and an email will be sent out to the user when this happens. We would really like for this to happen when we automatically subscribe someone to a thread, however, this feature seems to be missing from the REST API. Does anyone know of a way to accomplish this? The functionality provided by the subscription API endpoint is not sufficient for our purposes.
Thank you
P.S. I've sent the link to this question to several of my colleges they may respond before I get a chance to.
As a verified admin it is possible to create an impersonation token and then perform actions on behalf of the user such as join group/thread.
Note that for private groups, the group admin's are still required to approve the new member
https://developer.yammer.com/docs/impersonation
You can achieve your desired behaviour by adding users directly to the groups.
A C#.Net example I use:
// Impersonate user to join group
string ClientID = ConfigurationSettings.AppSettings["ClientID"]; // ClientID of custom app.
string userid = XMLDoc.Root.Element("response").Element("id").Value; // Yammer user id (in this case retreived from a previous API query)
string YammerGroupID = "123456"; // set group id.
string url = "https://www.yammer.com/api/v1/oauth/tokens.json?user_id=" + userid + "&consumer_key=" + ClientID; // impersonation end-point
HttpWebRequest request;
request = (HttpWebRequest)WebRequest.Create(url);
request.Headers.Add("Authorization", "Bearer " + bearer); // Bearer token of verified admin running the custom app.
request.Timeout = 90000;
request.Method = "GET";
request.ContentType = "application/json";
request.Proxy = new WebProxy() { UseDefaultCredentials = true };
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream);
string UserTokenJSON = reader.ReadToEnd(); // UserOAuth token as a JSON string.
string UserToken = UserTokenJSON.Substring(UserTokenJSON.IndexOf("token") + 8, 22); // Find 'token' in json string.
string temp = UserToken.Substring(UserToken.Length); // there is likely a much better way to parse out the token value, although this works.
temp = UserToken.Substring(UserToken.Length - 1);
temp = UserToken.Substring(UserToken.Length - 2);
if (UserToken.Substring(UserToken.Length) == "\\")
{ UserToken = UserToken.Substring(0, UserToken.Length); }
if (UserToken.Substring(UserToken.Length - 1) == "\"")
{ UserToken = UserToken.Substring(0, UserToken.Length - 1); }
if (UserToken.Substring(UserToken.Length - 2) == "\",")
{ UserToken = UserToken.Substring(0, UserToken.Length - 2); }
string url2 = "https://www.yammer.com/api/v1/group_memberships.json?group_id=" + YammerGroupID; // group membership endpoint,
HttpWebRequest request2;
request2 = (HttpWebRequest)WebRequest.Create(url2);
request2.Headers.Add("Authorization", "Bearer " + UserToken); // Impersonation Token
request2.Timeout = 90000;
request2.Method = "POST";
request2.ContentType = "application/json";
request2.Proxy = new WebProxy() { UseDefaultCredentials = true };
try
{
using (WebResponse response2 = (HttpWebResponse)request2.GetResponse())
{
confirmedstring += " New member: " + Email + "\\r\\n"; // This is used for posting summary back to a Yammer group in further code.
confirmedadditions++;
}
}
catch
{
Errorstring += "Error in adding " + Email + " to group " + YammerGroupID + "\\r\\n";
errors++;
}
}
}

Adding domain user to Organisation Unit using Google Apps script

I'm trying to add a user (newly created) to a specific org unit in my Google Apps domain, but I can't seem to find any documentation or examples on this. Is this even possible? Perhaps through the use of plain REST calls?
My code so far to create a user:
var user = UserManager.createUser(userName, firstName, lastName, "welcome").setChangePasswordAtNextLogin(true);
Now I want to attach the user to a specific org unit, and make it a member of certain groups (but that's another question I'm diving into).
Any help will greatly be appreciated!
Regards,
Kees.
The UserManager service doesn't support org units, but you can build the request manually.
The following Apps Script code adds an user to an OU. The parameters are the customerId, the email address of the user to add to the org unit and the org unit path:
function addUserToOU(customerId, email, ou) {
var oauthConfig = UrlFetchApp.addOAuthService("google");
var scope = "https://apps-apis.google.com/a/feeds/policies/";
oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oauthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oauthConfig.setConsumerKey("anonymous");
oauthConfig.setConsumerSecret("anonymous");
var body = "<?xml version=\"1.0\" encoding=\"utf-8\"?><atom:entry xmlns:atom=\"http://www.w3.org/2005/Atom\" xmlns:apps=\"http://schemas.google.com/apps/2006\"><apps:property name=\"orgUnitPath\" value=\"" + ou + "\" /></atom:entry>";
var requestData = {
"method": "put",
"contentType": "application/atom+xml",
"oAuthServiceName": "google",
"oAuthUseToken": "always",
"payload": body
};
var url = "https://apps-apis.google.com/a/feeds/orguser/2.0/" + customerId + "/" + email;
var result = UrlFetchApp.fetch(url, requestData);
Logger.log(result.getContentText());
}
I think that this task is quite easy nowadays:
This sinple code should work:
var emailAddress = 'myuser#mydomain.com';
var user = AdminDirectory.Users.get(emailAddress);
var orgunittomove='myorgunit' //you can set the whole path;
user.orgUnitPath = orgunittomove;
AdminDirectory.Users.update(user, emailAddress);
In the same way that the last answer, you can add the organization unit on the user object when you create the user. In the user object you have to set the orgUnitPath property.
var user = {
primaryEmail: "aperetz#austriajohn.edu",
orgUnitPath:"/Students",
name: {
givenName: "Albert",
familyName: "Peretz"
},
password: "XWYlkf"
};
userGsuite = AdminDirectory.Users.insert(user);

Resources