I'm using google finance to convert a currency to another.
The code that I'm using is shown below which was working fine. However, today, I'm facing the IndexOutofrange exception and getting a result of -1 for the indexes searched below (which means that my result does not contain CONVERTED VALUE which is 100% true after logging it.
Then I went to the same web request called, fed it the same parameter, and then inspected the source code from the web browser, and I got the VALUE .
What do you think might be the issue? From a web browser I get the whole result, and from my app the result is missing the converted value field.
private static string CurrencyConvert(decimal amount, string fromCurrency, string toCurrency)
{
try
{
//Grab your values and build your Web Request to the API
string apiURL = String.Format("https://www.google.com/finance/converter?a={0}&from={1}&to={2}&meta={3}", amount, fromCurrency, toCurrency, Guid.NewGuid().ToString());
//Make your Web Request and grab the results
var request = WebRequest.Create(apiURL);
//Get the Response
StreamReader streamReader = new StreamReader(request.GetResponse().GetResponseStream(), System.Text.Encoding.ASCII);
//Grab your converted value (ie 2.45 USD)
String temp = streamReader.ReadToEnd().ToString();
int pFrom = temp.IndexOf("<span class=bld>") + ("<span class=bld>").Length;
int pTo = temp.LastIndexOf("</span>");
System.Windows.MessageBox.Show(pFrom.ToString() + " " + pTo.ToString());
String result = temp.Substring(pFrom, pTo - pFrom);
// string result = Regex.Matches(streamReader.ReadToEnd(), "<span class=\"?bld\"?>([^<]+)</span>")[0].Groups[1].Value;
//Get the Result
return result;
}
catch(Exception ex )
{
return "";
}
}
problem with URL. use this one:https://finance.google.com/finance/converter?a={0}&from={1}&to={2}&meta={3}
meta parameter unnecessary
https://finance.google.com/finance/converter?a={0}&from={1}&to={2} works fine as well
Related
I have a C# COM visible DLL that works with web services. That COM visible DLL is being referenced and used in a VB6 application. The COM visible DLL has a function that pulls data from a web service call and gets the data in Json format, and then it also de-serializes the Json document to a class object, and returns the object id field (string type) from the function. The VB6 app calls that function and tries to get the id value. But it does not retrieve the value. The same COM Dll and same function is used in a .NET app. (C#), then the id field value can be retrieved.
How to get the correct value in VB 6 ? Highly Appreciate your response.
COM Dll function Code:
public string TestGETTransactionId(string transaction_id, ref string exceptionMessage)
{
exceptionMessage = "";
string sReturnString = " - 9999";
try
{
string sDomain = HostUrl;
string sNamespace = Namespace;
string sLocationId = LocationID;
string sDeveloperId = DeveloperID;
string sUserId = UserId;
string sUserAPIKey = UserApiId;
string sUserHashKey = UserHashKey;
string sEndPoint = TransactionsRetail;
//query to see if it is Okay...
sEndPoint = "transactions";
string sUrl = sDomain + #"/" + sNamespace + #"/" + sEndPoint + "?transaction_id=" + transaction_id;
var client = new RestClient(sUrl);
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("user-id", sUserId);
request.AddHeader("user-api-key", sUserAPIKey);
request.AddHeader("developer-id", sDeveloperId);
request.AddHeader("Content-Type", "application/json");
IRestResponse response = client.Execute(request);
TransactionRetail_Rootobject transactionRetail_Rootobject = SimpleJson.DeserializeObject<TransactionRetail_Rootobject>(response.Content);
if (transactionRetail_Rootobject.transactions != null)
{
sReturnString = transactionRetail_Rootobject.transactions[0].id.ToString();
}
}
catch (Exception ex)
{
exceptionMessage = ex.Message + "\n" + ex.InnerException;
}
return sReturnString;
}
VB6 Caller:
Dim sTransaction_api_id As String
Dim sExceptionMesg As String
Dim sReturnedId As String
'
sTransaction_api_id = "SAMINC_transID001" ' change this to try
sReturnedId = MyCOMDLL.MyComDllClass(sTransaction_api_id, sExceptionMesg)
MsgBox sReturnedId 'This always return the error code -9999 and I expect to get the true ID field value
MsgBox sExceptionMesg
C# Caller:
private void btnTestGetTransaction_Click(object sender, EventArgs e)
{
string sTransaction_id = "SAMINC_transID001";
string sExceptionMesg = "";
MyCOMDLL.MyComDllClass obj = new MyCOMDLL.MyComDllClass();
string sResult = obj.TestGETTransactionId(sTransaction_id, ref sExceptionMesg);
MessageBox.Show(sResult); // this returns the ID field value fine
textBox1.Text = sResult;
}
It seems that there are some differences in the VB6 and C# code you provided.
Namely, you are calling different constructor in VB6:
sReturnedId = MyCOMDLL.MyComDllClass(sTransaction_api_id, sExceptionMesg)
compared to the C# version:
MyCOMDLL.MyComDllClass obj = new MyCOMDLL.MyComDllClass();
on which then you call the TestGETTransactionId method:
string sResult = obj.TestGETTransactionId(sTransaction_id, ref sExceptionMesg);
Try the following:
obj = MyCOMDLL.MyComDllClass()
sResult = obj.TestGETTransactionId(sTransaction_api_id, sExceptionMesg)
MessageBox sResult
Note: I haven't tested the code in an IDE.
Thanks everyone.
What happened was I had to use a different way to make web services call. I use WinHttp reference in .NET to create routines for web services calls, instead of using RestClient. WinHttp provides more transparency to communicate with VB 6. The caller from VB 6 and C# do not need to change.
I made a very simple console application which will hit MWS service and return XML document containing list of financial events. As it starts, an exception hits at line 14 'client.ListFinancialEvents(request)' and it just show null and no other information as to why its not working.
string accessKey = "AccessKey";
string secretKey = "SecretKey";
string appName = "AppName";
string appVersion = "1.0";
string serviceURL = "http://mws.amazonservices.com/Finances/2015-05-01/";
try
{
MWSFinancesServiceConfig config = new MWSFinancesServiceConfig();
config.ServiceURL = serviceURL;
MWSFinancesServiceClient client = new MWSFinancesServiceClient(accessKey, secretKey, appName, appVersion, config);
ListFinancialEventsRequest request = new ListFinancialEventsRequest();
request.SellerId = "SellerID";
request.AmazonOrderId = "111-111111111-111111111";
ListFinancialEventsResponse response = client.ListFinancialEvents(request);
Console.WriteLine("Response:");
ResponseHeaderMetadata rhmd = response.ResponseHeaderMetadata;
Console.WriteLine("RequestId: " + rhmd.RequestId);
Console.WriteLine("Timestamp: " + rhmd.Timestamp);
string responseXml = response.ToXML();
Console.WriteLine(response.ResponseHeaderMetadata);
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
Console.ReadLine();
The DLLs used as reference were downloaded from here. I have already tried MWS Scratchpad and values are working fine. What could be the possible issues due to which this exception occurred and how to solve this issue?
I am posting an answer to my own question in case someone faces similar issue in the future.
I was making a very stupid mistake and it took me a week to figure it out. In service URL, instead of "http://..." it should be "https://..." and it starts working perfectly. It return complete XML as response in 'responseXml' variable.
I want to check whether a facebook user liked my facebook page or not. I got so many solutions using javascript but I want to implement this requirement in ASP.Net.
I copied the code from the below link:
http://duanedawnrae.com/Blog/post/2012/02/29/Determine-if-a-Facebook-user-Likes-your-page-with-ASPNET.aspx
I got the below ASP.Net code which works for the same.
ASP.Net code:
public class WebService : System.Web.Services.WebService
{
[WebMethod()]
public string GetFacebookLikeStatus(string fbpageid, string fbappid, string fbtoken, string fburl)
{
string strReturn = null;
// Placeholder for the Facbook "like" API call
string strURL = null;
strURL = "https://graph.facebook.com/me/likes?access_token=" + fbtoken;
// Placeholder for the Facebook GET response
WebRequest objGETURL = null;
objGETURL = WebRequest.Create(strURL);
// Declare response stream
Stream objStream = null;
// Declare The Facebook response
string strLine = null;
// Declare a count on the search term
int intStr = 0;
try
{
// Create an instance of the StreamReader
StreamReader objReader = new StreamReader(objStream);
// Get the response from the Facebook API as a JSON string.
// If access_token is not correct for the logged
// on user Facebook returns (400) bad request error
objStream = objGETURL.GetResponse().GetResponseStream();
// If all is well
try
{
// Execute the StreamReader
strLine = objReader.ReadToEnd().ToString();
// Check if Facebook page Id exists or not
intStr = strLine.IndexOf(fbpageid); // if valid return a value
if (intStr > 0)
{
strReturn = "1";
// if not valid return a value
}
else
{
strReturn = "0";
}
objStream.Dispose();
}
catch (Exception ex)
{
// For testing comment out for production
strReturn = ex.ToString();
// Uncomment below for production
//strReturn = "Some friendly error message"
}
}
catch (Exception ex)
{
// For testing comment out for production
strReturn = ex.ToString();
// Uncomment below for production
//strReturn = "Some friendly error message"
}
return strReturn;
}
}
The above code contains a webservice which contains a single function. The function contains four input parameters and returns a single output string.
But when I run this webservice I got the error, “Value cannot be null. Parameter name: stream”. This error is coming because the “objStream” variable is set to null. Please fix the issue so that I can get my correct output as I dont know how to implement my requirement.
Like Gating is not allowed on Facebook, and neither is incentivizing users to like your Page. Users must like something only because they really want to, you can´t reward them in any way.
That being said, you would need the user_likes permission to use /me/likes, and you would need to get it approved by Facebook. Which will not happen just for checking if the user liked your Page.
Btw, that article is from 2012. A lot of stuff changed since then.
I'm new to Facebook apps. I'm trying to create an MVC 4 application with Facebook Application as my Project Template.
I'm trying to catch the page id on which the page tab is created and I've got it somehow.
My problem here is when someone visits my app, I want to know the page id through which they are viewing the page tab. I've searched a lot where I got to know that I've to use FacebookSignedRequest for this. But this class is not available to me.
Thanks in advance for any help.
If you are simply trying to parse the signed_request parameter from Facebook, you can do so using the following C# code.
This code also verifies the hash using your own app_secret param, to ensure the signed_request originated from Facebook.
public static string DecodeSignedRequest(string signed_request)
{
try
{
if (signed_request.Contains("."))
{
string[] split = signed_request.Split('.');
string signatureRaw = FixBase64String(split[0]);
string dataRaw = FixBase64String(split[1]);
// the decoded signature
byte[] signature = Convert.FromBase64String(signatureRaw);
byte[] dataBuffer = Convert.FromBase64String(dataRaw);
// JSON object
string data = Encoding.UTF8.GetString(dataBuffer);
byte[] appSecretBytes = Encoding.UTF8.GetBytes(app_secret);
System.Security.Cryptography.HMAC hmac = new System.Security.Cryptography.HMACSHA256(appSecretBytes);
byte[] expectedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(split[1]));
if (expectedHash.SequenceEqual(signature))
{
return data;
}
}
}
catch
{
// error
}
return "";
}
private static string FixBase64String(string str)
{
while (str.Length % 4 != 0)
{
str = str.PadRight(str.Length + 1, '=');
}
return str.Replace("-", "+").Replace("_", "/");
}
All I had to do was create a Facebook Client object and call the ParseSignedRequest method with the app secret.
var fb = new FacebookClient();
dynamic signedRequest = fb.ParseSignedRequest(appSecret, Request.Form["signed_request"]);
This returns a Json object which we have to parse using JObject.Parse
I am sending a message to multiple phone numbers .
Mobile numbers are stored in an array .
string phNums = "91999999999,9199999998....";.
string[] phNos = phNums.Split(',');
But message doesn't reach all of the recipients , mostly to the numbers that are present near end of array.
The message are sent via a URL provided by SMS service provider in which the phone number and the message is embedded.
for (int i = 0; i < phNos.Length; i++)
{
url = #"http://aaa.bbb.ccc.dd/HTTPMTAPI?User=abc&Password=pqr&FromAddr=xyzSMS&DestNo=" + phNos[i] + "&msg=" + message;
Uri targetUri1 = new Uri(url);
System.Net.HttpWebRequest hwb1;
hwb1 = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(targetUri1);
hwb1.GetResponse();
}
As an alternate , I also used Webclient() but still successful message delivery is not guaranteed.
for (int i = 0; i < phNos.Length; i++)
{
WebClient cli= new WebClient();
url = #"http://aaa.bbb.ccc.dd/HTTPMTAPI?User=abc&Password=pqr&FromAddr=xyzSMS&DestNo=" + phNos[i] + "&msg=" + message;
cli.DownloadString(url);
}
How to ensure that message delivery is not skipped .
Like only if successful response is received on downloading the URL , the loop should progress to next mobile number and so on.
If there is any other possible mechanism , please do suggest. Thanks
I think this is what you want to do:
for (int i = 0; i < phNos.Length; i++)
{
url = #"http://aaa.bbb.ccc.dd/HTTPMTAPI?User=abc&Password=pqr&FromAddr=xyzSMS&DestNo=" + phNos[i] + "&msg=" + message;
Uri targetUri1 = new Uri(url);
System.Net.HttpWebRequest hwb1;
hwb1 = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(targetUri1);
System.Net.HttpWebResponse response = hwb1.GetResponse();
if (response != null)
{
int status = (int)response.StatusCode; // this changes the status
// from text response to the
// number, like 404
if (status == 404//or anything else you want to test//)
{
// put your retry logic here, make sure you add a way to break
// so you dont infinitely loop if the service is down or something
}
}
}
URLs have a length constraint. Your are likely hitting this limit and your are losing the trailing phone numbers as a result. Your best bet would be to break your requests into multiple requests of a certain size.
According to the following SO, it may be good practice to limit your request so that the url does not surpass 2000 characters.
What is the maximum length of a URL in different browsers?