How To Get Value/Variable From URL? - c#

So I want to write a BTC converter app, I can get the value of it for £1 at https://blockchain.info/tobtc?currency=GBP&value=1
And changing the GBP to USD in the URL changed it to USD naturally, I want to use this and parse the data into a variable and then have it used as a normal. But I want the user to be able to enter their currency and have the url change and then fetch the amounnt in say one canadian dollar. How can I use the GBP as a variable and then have it change depending on user input.
I'm thinking a dropdown box of most popular currencys but I wouldn't know how to use that at all.
Be kind, I'm a noob and trying to make my first useful application

Here is a simply example how you can get the value for the different currencies:
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace ConsoleApp5
{
public class Program
{
static void Main(string[] args)
{
Console.WriteLine(GetValueAsync("GBP").Result);
Console.WriteLine(GetValueAsync("USD").Result);
Console.WriteLine(GetValueAsync("RUB").Result);
}
public static async Task<string> GetValueAsync(string curr)
{
using (HttpClient client = new HttpClient())
{
var responseString = await client.GetStringAsync("https://blockchain.info/tobtc?currency="+curr+"&value=1");
return responseString;
}
}
}
}
Here
client.GetStringAsync("https://blockchain.info/tobtc?currency="+curr+"&value=1");
is sending asynchronous http get request by the provided URL and returning response as a string.
The site you want to use is returning just the value as a string that's why this is working.
As the request is asynchronous we must use await so that we get response in string.
If you want to do this in WinForm. Here is example. Let's assume that you have already TextBox for input value, Label for showing result and Button for Getting result. They can be added by just drop and down from Toolbox to your form.
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private async void button1_ClickAsync(object sender, EventArgs e)
{
string curr = textBox1.Text;
if (!string.IsNullOrEmpty(curr))
{
label2.Text = "waiting for response";
var res = await GetValueAsync(curr);
label2.Text = res;
}
}
public async Task<string> GetValueAsync(string curr)
{
var responseString = string.Empty;
using (HttpClient client = new HttpClient())
{
string reqString = "https://blockchain.info/tobtc?currency=" + curr + "&value=1";
responseString = await client.GetStringAsync(reqString);
}
return responseString;
}
}
}
Here is the full solution for Win Forms link
Here are useful links for you:
MSDN HttpClient GetStringAsync
WinForm with Async Methods
MSDN C# String Concatenation
MSDN WinForms Click Event
Here is a recording how to do this also:
Recording

Related

Refresh Page with new data from APi by searchHandler Xamarin C#

I have a question about the function search Handler in xamarin. I am just starting to learn xamarin, and I am trying in my project with search handler in xamarin to refresh my page with new data from the API. Currently, I am already lucky to retrieve the data, but when I do this, it creates a new page so to speak, but this is not what I want. He would kind of reload the page with new data. I have also already tried to delete previous page with "Shell.Current.Navigation.PopAsync();" But with no residual result. Anyone knows how I can achieve what I want? In addition, I would also like to remove that blur you get after the search. Thanks in advance!
using Eindproject.Models;
using Eindproject.Repository;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Eindproject.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Weather : ContentPage
{
private string icao = "EBBR";
public Weather()
{
InitializeComponent();
}
public Weather(string icao)
{
InitializeComponent();
this.icao = icao;
frontend(icao);
}
public async void frontend(string par_icao)
{
// Get weather
Models.WeatherModel weather = await DataRepository.GetWeatherAsync(par_icao);
// Set data to labels
lblLocation.Text = weather.Station.Name;
lblCode.Text = weather.Code;
lblTemp.Text = weather.Temperature.C.ToString();
lblHumidity.Text = weather.Humidity.Percent.ToString();
lblWind.Text = weather.Wind.Degrees.ToString();
lblPressure.Text = weather.Presure.Hpa.ToString();
lblDate.Text = weather.Date.ToString("G");
lblMetar.Text = weather.Metar;
lblCloud.Text = weather.Clouds[0].text;
// Get sunrise and sunset
SunTimes sunrise = await DataRepository.GetSunTimesAsync("EHBK");
// Set data to labels
lblSunrise.Text = sunrise.Sunrise.ToString("G");
lblSunset.Text = sunrise.Sunset.ToString("G");
}
private void ToolbarItem_Clicked(object sender, EventArgs e)
{
}
}
public class CustomSearchHandler : SearchHandler
{
// When user press enter and confirm get the icao code and search for the weather
protected override void OnQueryConfirmed()
{
// Get the icao code
string icao = Query;
// Call wheather object
Weather weather = new Weather();
// Call frontend
weather.frontend(icao);
}
}
}
this is creating a new instance of Weather and calling its frontend method. That won't do anything useful.
Weather weather = new Weather();
weather.frontend(icao);
Instead you need to use the existing instance that is already displayed to the user
there are many ways to do this, but this might be the simplest
// get the current page
var page = App.Current.MainPage;
// cast it to the correct type
var weather = (Weather)page;
// call its frontend method
page.frontend(icao);

System.AggregateException : ComputerVisionErrorResponseException: Operation returned an invalid status code 'Forbidden'

When I upload the image for getting ocr by using the Azure Vision Cognitive services.
But it will show an exception while performing in azure vision ocr.
like this,
System.AggregateException : ComputerVisionErrorResponseException: Operation returned an invalid status code 'Forbidden'
using System;
using System.Collections.Generic;
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision;
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Threading;
using System.Linq;
namespace ComputerVisionQuickstart
{
class Program
{
// Add your Computer Vision subscription key and endpoint
static string subscriptionKey = "PASTE_YOUR_COMPUTER_VISION_SUBSCRIPTION_KEY_HERE";
static string endpoint = "PASTE_YOUR_COMPUTER_VISION_ENDPOINT_HERE";
private const string READ_TEXT_URL_IMAGE = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/ComputerVision/Images/printed_text.jpg";
static void Main(string[] args)
{
Console.WriteLine("Azure Cognitive Services Computer Vision - .NET quickstart example");
Console.WriteLine();
ComputerVisionClient client = Authenticate(endpoint, subscriptionKey);
// Extract text (OCR) from a URL image using the Read API
ReadFileUrl(client, READ_TEXT_URL_IMAGE).Wait();
}
public static ComputerVisionClient Authenticate(string endpoint, string key)
{
ComputerVisionClient client =
new ComputerVisionClient(new ApiKeyServiceClientCredentials(key))
{ Endpoint = endpoint };
return client;
}
public static async Task ReadFileUrl(ComputerVisionClient client, string urlFile)
{
Console.WriteLine("----------------------------------------------------------");
Console.WriteLine("READ FILE FROM URL");
Console.WriteLine();
// Read text from URL
var textHeaders = await client.ReadAsync(urlFile);
// After the request, get the operation location (operation ID)
string operationLocation = textHeaders.OperationLocation;
Thread.Sleep(2000);
// Retrieve the URI where the extracted text will be stored from the Operation-Location header.
// We only need the ID and not the full URL
const int numberOfCharsInOperationId = 36;
string operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId);
// Extract the text
ReadOperationResult results;
Console.WriteLine($"Extracting text from URL file {Path.GetFileName(urlFile)}...");
Console.WriteLine();
do
{
results = await client.GetReadResultAsync(Guid.Parse(operationId));
}
while ((results.Status == OperationStatusCodes.Running ||
results.Status == OperationStatusCodes.NotStarted));
// Display the found text.
Console.WriteLine();
var textUrlFileResults = results.AnalyzeResult.ReadResults;
foreach (ReadResult page in textUrlFileResults)
{
foreach (Line line in page.Lines)
{
Console.WriteLine(line.Text);
}
}
Console.WriteLine();
}
}
}
Anyone can provide solution for this issue.

My JSON API call won't refresh with new data in C#. How do I clear the cache so I get fresh data?

As many others here, I’m new to C# and Xamarin, but not programming in general.
I’m working on a proof of model concept where I can reach out and query stock/crypto price data and update elements in Xamarin with that data.
I have an API method called LoadData() which works right when the application launches. It updates a few Xamarin Label items with the data in their Text property.
I have a Xamarin Button object which has a Click event that triggers the same LoadData() method in the attempt that it will load in new JSON data and subsequently update the Labels with the new data.
Any subsequent LoadData() call will NOT work once it is called the first time. What I think is happening is that the original data it called gets cached, and the call doesn’t return brand NEW, fresh data.
I have spent two days looking up caching in C# trying to find the right code syntax to either clear out the JSON data before each LoadData() call, or to prevent it from caching. I have found quite a few conversations and code examples, but when I try them they either don’t work, or they appear with red underlines in Visual Studio and generate errors.
I’m going to be making a lot of these API calls and so I’m looking for the right syntax to use to solve this problem. Any help with clear code examples is greatly appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Xamarin.Forms;
namespace DataBindingTest2
{
[System.ComponentModel.DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
static string IEXTrading_API_PATH = "https://cloud.iexapis.com/v1/crypto/btcusdt/quote/1?token=TOKEN_GOES_HERE";
static List<string> FinalPriceQuote = new List<string>(); // The LIST object to hold the final JSON data
public string vLatestPrice = "";
public string vCompanyName = "";
public string vLatestVolume = "";
public MainPage()
{
InitializeComponent();
LoadData();
}
void Handle_Clicked(object sender, System.EventArgs e)
{
LoadData();
}
public async void LoadData()
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Cache-Control", "no-cache"); // <-- doesn't seem to have any effect
using (HttpResponseMessage response = await client.GetAsync(IEXTrading_API_PATH))
using (HttpContent content = response.Content)
{
string data = await content.ReadAsStringAsync();
if (data != null)
{
RootObject priceData = JsonConvert.DeserializeObject<RootObject>(data);
FinalPriceQuote.Add(priceData.symbol.ToString());
FinalPriceQuote.Add(priceData.latestPrice.ToString());
FinalPriceQuote.Add(priceData.latestVolume.ToString());
vCompanyName = FinalPriceQuote[0];
vLatestPrice = FinalPriceQuote[1];
vLatestVolume = FinalPriceQuote[2];
CompanyName.Text = vCompanyName; // <-- updates Label text in XAML
PriceLabel.Text = vLatestPrice; // <-- updates Label text in XAML
LatestVolume.Text = vLatestVolume; // <-- updates Label text in XAML
}
}
}
}
}
It looks like you're always appending to FinalPriceQuote and reading the first 3 values., but never clearing it. Try adding FinalPriceQuote.Clear() before your FinalPriceQuote.Add(...)

Routing JSON data to Event Hubs in Azure

I have a situation where I need to send JSON data (a JSON file, not convert to JSON) to Time Series Insights via Event Hubs. But I am not able to send the data due to my lack of experience in C#.
I am able to send other sample messages but not JSON. How can I do that?
Any help or insight would be appreciated.
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
using System.IO;
using Microsoft.ServiceBus.Messaging;
namespace ConsoleApp5
{
class Program
{
static string _connectionString = "Endpoint..;
static async Task MainAsync(string[] args)
{
var client = EventHubClient.CreateFromConnectionString(_connectionString, "eventhub");
var json = File.ReadAllText(#"C:\Users\Shyam\Downloads\personal.json");
var eventData = new EventData(Encoding.UTF8.GetBytes(json));
await EventHubClient.SendAsync(eventData);
}
}
}
It throws an error in the async method though.
Severity Code Description Project File Line Suppression State
Error CS0120 An object reference is required for the non-static field, method, or property 'EventHubClient.SendAsync(EventData)' ConsoleApp5 C:\Users\Shyam\source\repos\ConsoleApp5\ConsoleApp5\Program.cs 21 Active
UPDATE:
namespace jsonData
{
using System;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Azure.EventHubs;
public class Program
{
private static EventHubClient eventHubClient;
private const string EhConnectionString = "Endpoint=sb://";
private const string EhEntityPath = "hub";
public static void Main(string[] args)
{
MainAsync(args).GetAwaiter().GetResult();
}
private static async Task MainAsync(string[] args)
{
// Creates an EventHubsConnectionStringBuilder object from the connection string, and sets the EntityPath.
// Typically, the connection string should have the entity path in it, but this simple scenario
// uses the connection string from the namespace.
var connectionStringBuilder = new EventHubsConnectionStringBuilder(EhConnectionString)
{
EntityPath = EhEntityPath
};
eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString());
var json = File.ReadAllText(#"D:\Sample.json");
var eventData = new EventData(Encoding.UTF8.GetBytes(json));
await eventHubClient.SendAsync(eventData);
await eventHubClient.CloseAsync();
Console.WriteLine("Press ENTER to exit.");
Console.ReadLine();
}
}
}
Wrap your events into a JSON array:
using (var ms = new MemoryStream())
using (var sw = new StreamWriter(ms))
{
// Wrap events into JSON array:
sw.Write("[");
for (int i = 0; i < events.Count; ++i)
{
if (i > 0)
{
sw.Write(',');
}
sw.Write(events[i]);
}
sw.Write("]");
sw.Flush();
ms.Position = 0;
// Send JSON to event hub.
EventData eventData = new EventData(ms);
eventHubClient.Send(eventData);
}
Reference: learn.microsoft.com/time-series-insights-send-events
I'm sure you have figured this out by now but you're problem is not with JSON, it's with how you're using the event hub client.
Instead of this line:
await EventHubClient.SendAsync(eventData);
it should be this:
await client.SendAsync(eventData);
JSON is just a string for Event Hubs, so as simple as
var json = File.ReadAllText("myfile.json");
var eventData = new EventData(Encoding.UTF8.GetBytes(json));
await eventHubClient.SendAsync(eventData);

Twitter and Winform C# app is making me go bald

Ok twitter might be great for social media but for a small app that I am trying to create just for fun has turned into a nightmare. I have searched everywhere and can't find a good explanation on how to use the api.
I am using the TweetSharp api and all I want to do is for user to allow my app and be able to post from the app to their twitter.
My problem comes when the app gives out a pin code for the user to type in...where would the user type it in at? Ok so this is what I have so far..if anyone can help i would be most greatful so I can stop pulling my hair..
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TweetSharp;
using System.Configuration;
using Hammock.Authentication.OAuth;
using System.Diagnostics;
namespace testtweet
{
public partial class Form1 : Form
{
//I already have these values not showing here for obvious reasons.
TwitterService service = new TwitterService("ConsumerKey", "ConsumerSecret");
public Form1()
{
InitializeComponent();
// Pass your credentials to the service
// Step 1 - Retrieve an OAuth Request Token
OAuthRequestToken requestToken = service.GetRequestToken();
// Step 2 - Redirect to the OAuth Authorization URL
Uri uri = service.GetAuthorizationUri(requestToken);
Form2 frm = new Form2(uri.ToString());
frm.Show();
OAuthRequestToken requestToken = service.GetRequestToken();
// Step 3 - Exchange the Request Token for an Access Token
string verifier = "123456"; // <-- This is input into your application by your user
OAuthAccessToken access = service.GetAccessToken(requestToken, verifier);
// Step 4 - User authenticates using the Access Token
service.AuthenticateWith(access.Token, access.TokenSecret);
IEnumerable<TwitterStatus> mentions = service.ListTweetsMentioningMe();
}
}
}
on my Form2
public Form2(string url)
{
InitializeComponent();
webBrowser1.Navigate(url);
}
Here is where I am lost. As you see Step 3 is wating for the pin code..How would I set it in there? I had an idea to write directly in the app.config but
how do I know when it has been generated? Should I make a 3rd form to have the user input the pin code there?
so this is what I've got (add a webbrowser named webBrowser1 in the designer)
public partial class TwitterBrowser : Form
{
public TwitterBrowser()
{
InitializeComponent();
webBrowser1.Navigated += OnNavigate;
}
private void OnNavigate(object sender, WebBrowserNavigatedEventArgs e)
{
if (e.Url.ToString() != #"https://api.twitter.com/oauth/authorize")
return;
if (webBrowser1.Document != null)
{
var regex = new Regex("<code>([0-9]*)</code>", RegexOptions.Multiline);
VerificationCode = regex.Match(webBrowser1.DocumentText).Groups[1].Value;
Close();
}
}
public string VerificationCode { get; private set; }
#region Implementation of ITwitterUserInteraction
public void NavigateTo(Uri uri)
{
webBrowser1.Navigate(uri);
}
#endregion
}
Then use it like this:
var browser = new TwitterBrowser();
browser.NavigateTo(uri);
browser.ShowDialog();
result = browser.VerificationCode;

Categories

Resources