I came across this code here and I would like someone to explain it to me(I would like to use something like this for my compiler).
I would like to ask directly below the question, logically, but I can't add a comment.
How does the Google Translate API work in C#? I assume you have to download some Nuget
How do you change the language?
Here is the code:
var toLanguage = "en";//English
var fromLanguage = "de";//Deutsch
var url = $"https://translate.googleapis.com/translate_a/single?client=gtx&sl={fromLanguage}&tl={toLanguage}&dt=t&q={HttpUtility.UrlEncode(word)}";
var webClient = new WebClient
{
Encoding = System.Text.Encoding.UTF8
};
var result = webClient.DownloadString(url);
try
{
result = result.Substring(4, result.IndexOf("\"", 4, StringComparison.Ordinal) - 4);
return result;
}
catch
{
return "Error";
}
Related
Can someone help me successfully send ERC20 tokens using the Nethereum package in C# .NET?
I am able to successfully get account balances, but when I try to send, it just sits there....
I am using the Infura.io project api also with the below security:
eth_accounts
eth_call
eth_getBalance
eth_getTransactionReceipt
eth_sendRawTransaction
var client = new EthClient(new RpcUrl("https://mainnet.infura.io/v3/-MyProjectID-"));
Here is the code I am using:
--The call to the transfer method
/* transfer 100 tokens */
var transactionHashTask = client.transferTokens(coinOwnerAddress, coinOwnerPrivateKey, toAddress, contractAddress, 0);
var transactionHash = transactionHashTask.Result.ToString();
lblTransHash.Text = "Transaction hash: " + transactionHash;
--Code that contains the actual method
public async Task<string> transferTokens(string senderAddress, string privateKey, string receiverAddress, string contractAddress, UInt64 tokens)
{
var transactionMessage = new TransferFunction()
{
FromAddress = senderAddress,
To = receiverAddress,
AmountToSend = tokens
};
var transferHandler = web3.Eth.GetContractTransactionHandler<TransferFunction>();
Task<string> transactionHashTask = transferHandler.SendRequestAsync(contractAddress,transactionMessage);
return await transactionHashTask;
}
You are transferring something right? So maybe you have to send extra to account for the gas fees. But i'm no expert. Let me know if you solve this please.
The transfer function doesn't have AmountToSend parameter. It has TokenAmount. So change like below
var transactionMessage = new TransferFunction()
{
To = receiverAddress,
TokenAmount= tokens
};
As per documentation, it says to use Graph API; but there is no example available online, to show the video file can be uploaded from another website to Facebook.
Issues:
The video URL shows not supported format
API for actual File upload in not able to find anywhere on Facebook documentation
What I tried:
string uriPath = "file:\\D:\\Channel_Heart_Diamond_Bow_Wedding_Set_In_14K_Yellow_Gold-FDENS3113.mp4";
string localPath = new Uri(uriPath).LocalPath;
var mediaObject = new FacebookMediaObject
{
FileName = uriPath,
ContentType = "video/3gpp"
};
mediaObject.SetValue(File.ReadAllBytes(mediaObject.FileName)); //Error here
try
{
var fb = new FacebookClient(accesstoken);
var parameters = new Dictionary<string, object>();
parameters["method"] = "video.upload";
parameters["caption"] = "video upload using rest api";
parameters["source"] = mediaObject;
parameters["title"] = "my video";
parameters["description"] = "uploading video";
var result = (IDictionary<string, object>)fb.Post(parameters);
var videoId = (string)result["vid"];
}
catch (FacebookApiException ex) { throw; }
If this wrong method, then kindly suggest the proper way to achieve it.
It will be great if you can provide us with a working example link.
I found a blog post that shows how to "shim" familiar things like HttpResponseMessage back into ASP.NET Core MVC, but I want to know what's the new native way to do the same thing as the following code in a REST Post method in a Controller:
// POST audit/values
[HttpPost]
public System.Net.Http.HttpResponseMessage Post([FromBody]string value)
{
var NewEntity = _repository.InsertFromString(value);
var msg = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Created);
msg.Headers.Location = new Uri(Request.RequestUri + NewEntity.ID.ToString());
return msg;
}
In an ASP.NET Core MVC project, I can't seem to get Request.RequestUri.
I tried inspecting Request, and I was able to make a function like this:
private string UriStr(HttpRequest Request)
{
return Request.Scheme + "://" + Request.Host + Request.Path; // Request.Path has leading /
}
So I could write UriStr(Request) instead. But I'm not sure that's right. I feel like I'm hacking my way around, and not using this correctly.
A related question for earlier non-Core ASP.NET MVC versions asks how to get the base url of the site.
Personally, I use :
new Uri(request.GetDisplayUrl())
GetDisplayUrl fully un-escaped form (except for the QueryString)
GetEncodedUrl - fully escaped form suitable for use in HTTP headers
These are extension method from the following namespace : Microsoft.AspNetCore.Http.Extensions
A cleaner way would be to use a UriBuilder:
private static Uri GetUri(HttpRequest request)
{
var builder = new UriBuilder();
builder.Scheme = request.Scheme;
builder.Host = request.Host.Value;
builder.Path = request.Path;
builder.Query = request.QueryString.ToUriComponent();
return builder.Uri;
}
(not tested, the code might require a few adjustments)
Here's a working code. This is based off #Thomas Levesque answer which didn't work well when the request is from a custom port.
public static class HttpRequestExtensions
{
public static Uri ToUri(this HttpRequest request)
{
var hostComponents = request.Host.ToUriComponent().Split(':');
var builder = new UriBuilder
{
Scheme = request.Scheme,
Host = hostComponents[0],
Path = request.Path,
Query = request.QueryString.ToUriComponent()
};
if (hostComponents.Length == 2)
{
builder.Port = Convert.ToInt32(hostComponents[1]);
}
return builder.Uri;
}
}
I am trying to use the Office API to sync contacts from a few different sources. I have been having a problem trying to make a POST request with my JSON object to create a new contact. I have been looking at the MSDN pages but I feel like I should clarify I’m relatively new to C#, this is my first time trying to use REST protocols, and async methods in C#.
I have my code below, I tried to create a class that will add a new contact with a hard coded JSON string. I have tried a few various ways of trying to complete this request. Every request I have attempted gives me a 401 or 400 Error. I left a couple lines that I felt were closest to the solution but if those are not on the right track I have no problem trying something else. There is also a function that I believe could be useful but I couldn’t really find documentation on how to use it:
await client.Me.Contacts.AddContactAsync();
Again I said I am pretty new to this so if there is a way to create an IContact item from the JSON and use the above method or to just pass the JSON directly either would be extremely useful. Even links to documentation that could be useful I would love to see. I’m a pretty stuck on this problem I’ve never posted a question before but I’m stumped on this.
Below is the documentation for the Contacts API maybe it will make more sense to you guys than me.
http://msdn.microsoft.com/en-us/library/office/dn792115(v=office.15).aspx
If anybody can figure out how to make a post request from that JSON it will be much appreciated.
using Microsoft.Office365.Exchange;
using Microsoft.Office365.OAuth;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows;
using System.Net.Http;
using System.Net.Http.Headers;
namespace ContactSynchronization
{
class OfficeAPIWrite
{
private static string odata = "#odata.type";
private static string type = "#Microsoft.Exchange.Services.OData.Model.Contact";
const string ServiceResourceId = "https://outlook.office365.com";
static readonly Uri ServiceEndpointUri = new Uri("https://outlook.office365.com/ews/odata/Me/Contacts");
static string _lastLoggedInUser;
static DiscoveryContext _discoveryContext;
public static async Task OfficeWrite()
{
try
{
var client = await EnsureClientCreated();
string json = new JavaScriptSerializer().Serialize(new
{
odata = type,
GivenName = "Mara",
Surname = "Whitley",
EmailAddress1 = "mara#fabrikam.com",
BusinessPhone1 = "425-555-1313",
Birthday = "1974-07-22T07:00:00Z"
});
try
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, ServiceEndpointUri);
request.Content = new StringContent(json);
request.Headers.Add("Accept", "application/json;odata=minimalmetadata");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
}
catch (System.Net.WebException e)
{
MessageBox.Show(e.ToString());
}
}
catch (Microsoft.Office365.OAuth.AuthenticationFailedException)
{
MessageBox.Show("Authentication Failed Exception was thrown");
}
}
public static async Task<ExchangeClient> EnsureClientCreated()
{
if (_discoveryContext == null)
{
_discoveryContext = await DiscoveryContext.CreateAsync();
}
var dcr = await _discoveryContext.DiscoverResourceAsync(ServiceResourceId);
_lastLoggedInUser = dcr.UserId;
return new ExchangeClient(ServiceEndpointUri, async () =>
{
return (await _discoveryContext.AuthenticationContext.AcquireTokenSilentAsync(ServiceResourceId, _discoveryContext.AppIdentity.ClientId, new Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier(dcr.UserId, Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifierType.UniqueId))).AccessToken;
});
}
public static async Task SignOut()
{
if (string.IsNullOrEmpty(_lastLoggedInUser))
{
return;
}
if (_discoveryContext == null)
{
_discoveryContext = await DiscoveryContext.CreateAsync();
}
await _discoveryContext.LogoutAsync(_lastLoggedInUser);
}
}
}
Well I guess I figured out a work around. This uses a ContactObject that I created and newtonsoft's JSON serializer. I was hoping to see an example of the microsoft ExchangeClient in action, the only reason I am posting this is to help others that might have similar issues posting to the office API, the below code will run successfully. I'm still looking though if anybody can show me the correct way to use the ExchangeClient functions.
// your request must include these, and a given name,
// everything else is optional
private const string odata = "#odata.type";
private const string type = "#Microsoft.Exchange.Services.OData.Model.Contact";
public static async Task CreateContact(ContactObject officeContact, string userEmail, string userPassword)
{
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, new Uri("https://outlook.office365.com/ews/odata/Me/Contacts"));
// Add the Authorization header with the basic login credentials.
var auth = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(userEmail + ":" + userPassword));
request.Headers.Add("Accept", "application/json");
request.Headers.Add("Authorization", auth);
var createResponse = new JObject();
createResponse[odata] = type; // this needs to be here for this to work
if (!String.IsNullOrEmpty(officeContact.officeDisplayName)) createResponse["DisplayName"] = officeContact.officeDisplayName;
if (!String.IsNullOrEmpty(officeContact.officeGivenName)) createResponse["GivenName"] = officeContact.officeGivenName;
if (!String.IsNullOrEmpty(officeContact.officeMiddleName)) createResponse["MiddleName"] = officeContact.officeMiddleName;
if (!String.IsNullOrEmpty(officeContact.officeNickName)) createResponse["NickName"] = officeContact.officeNickName;
if (!String.IsNullOrEmpty(officeContact.officeSurname)) createResponse["Surname"] = officeContact.officeSurname;
if (!String.IsNullOrEmpty(officeContact.officeEmailAddress1)) createResponse["EmailAddress1"] = officeContact.officeEmailAddress1;
if (!String.IsNullOrEmpty(officeContact.officeEmailAddress2)) createResponse["EmailAddress2"] = officeContact.officeEmailAddress2;
if (!String.IsNullOrEmpty(officeContact.officeEmailAddress3)) createResponse["EmailAddress3"] = officeContact.officeEmailAddress3;
if (!String.IsNullOrEmpty(officeContact.officeHomePhone1)) createResponse["HomePhone1"] = officeContact.officeHomePhone1;
if (!String.IsNullOrEmpty(officeContact.officeHomePhone2)) createResponse["HomePhone2"] = officeContact.officeHomePhone2;
if (!String.IsNullOrEmpty(officeContact.officeBusinessPhone1)) createResponse["BusinessPhone1"] = officeContact.officeBusinessPhone1;
if (!String.IsNullOrEmpty(officeContact.officeBusinessPhone2)) createResponse["BusinessPhone2"] = officeContact.officeBusinessPhone2;
if (!String.IsNullOrEmpty(officeContact.officeMobilePhone1)) createResponse["MobilePhone1"] = officeContact.officeMobilePhone1;
if (!String.IsNullOrEmpty(officeContact.officeOtherPhone)) createResponse["OtherPhone"] = officeContact.officeOtherPhone;
if (!String.IsNullOrEmpty(officeContact.officeId)) createResponse["Id"] = officeContact.officeId;
if (!String.IsNullOrEmpty(officeContact.officeCompanyName)) createResponse["CompanyName"] = officeContact.officeCompanyName;
request.Content = new StringContent(JsonConvert.SerializeObject(createResponse));
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.SendAsync(request);
try
{
response.EnsureSuccessStatusCode();
}
catch (System.Net.WebException)
{
MessageBox.Show("BAD REQUEST");
}
}
Coding Platform ASP.NET 4.0 WebForms
I have two pages that are relevant here
Login.aspx
LandingPage.aspx
On Login.aspx when I click an ImageButton, I redirect to Facebook site with the following code
protected void FacebookLoginButton_Click(object sender, ImageClickEventArgs e)
{
try
{
Response.Redirect(GetFacebookLoginURL());
}
catch (System.Threading.ThreadAbortException)
{
throw;
}
catch (Exception err)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(err);
}
}
private string GetFacebookLoginURL()
{
try
{
string baseURL = System.Configuration
.ConfigurationManager
.AppSettings["WebsiteURL"]
.ToString();
string[] extendedPermissions = new[] {
"publish_stream",
"offline_access"
};
var oauth = new FacebookOAuthClient {
ClientId = FacebookContext.Current.AppId
};
var parameters = new Dictionary<string, object>{
{ "response_type", "token" },
{ "display", "page" }
};
if (extendedPermissions != null && extendedPermissions.Length > 0)
{
var scope = new StringBuilder();
scope.Append(string.Join(",", extendedPermissions));
parameters["scope"] = scope.ToString();
}
parameters["redirect_uri"] = String.Format("{0}LandingPage.aspx", baseURL);
return oauth.GetLoginUrl(parameters).OriginalString;
}
catch (Exception err)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(err);
return "";
}
}
That part is working properly. But I am clueless on how to access the user info at the LandingPage which is my redirect_uri. Have tried this.
FacebookOAuthClient cl = new FacebookOAuthClient(FacebookContext.Current);
FacebookOAuthResult result = null;
string url = Request.Url.AbsoluteUri;
// verify that there is a code in the url
if (FacebookOAuthResult.TryParse(url, out result))
{
if (result.IsSuccess)
{
var accesstoken = result.AccessToken;
}
else
{
var errorDescription = result.ErrorDescription;
var errorReason = result.ErrorReason;
}
}
But I doubt it wont work since I dont have window.hash.location at Server Side(Its not working anyway)
var client = new FacebookClient(FacebookContext.Current);
dynamic me = client.Get("me");
string firstName = me.first_name;
string lastName = me.last_name;
string email = me.email;
Although I am not sure, getting the Access Token will solve my problem, won't it?
This is the error I am getting.
(OAuthException) An active access
token must be used to query
information about the current user.
What am I doing wrong?
here's a sample of a standalone website using webforms. Check out Default.aspx.cs and Web.config. Please note that this sample could be modified for use with the latest source code and might not work with the latest release (5.0.3 beta).
I just recently did this implementation. To access "me", you need to have an Access Token.
The implementation is pretty straighforward, however, I will say that I found the major stumbling block for me was to make sure that my redirect_uri from my "Login.aspx" url matched the redirect_uri from my landing page.
It must be simple, but I dodnt get it. So I used the lesser used Facebook C# SDK by Facebook. I pretty much did what this blog suggested. Everything is fine now.