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);
Related
So after following some tutorials and using https://openweathermap.org/current, I got some code going and now I've been spending hours trying to figure out why it won't work. I started by making a Windows Forms app and made this interface. At first it was going to be able to find the weather of any city you typed in, but I can't find such an option on openweathermap so I only restricted it to Seoul, Korea. However I don't understand why nothing happens when I click the button, I thought it should bring back the forecast in the text boxes.. If anyone could help it would be really appreciated.
This is my full code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Net;
namespace WindowsFormsApp3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string city;
city = txtcity.Text;
string uri = string.Format("http://api.openweathermap.org/data/2.5/weather?q=Seoul&mode=xml&appid=78dff84492be32f8b4f77692904607a1", city);
XDocument doc = XDocument.Load(uri);
string iconUri = (string)doc.Descendants("icon").FirstOrDefault();
WebClient client = new WebClient();
string maxtemp = (string)doc.Descendants("temperature.max").FirstOrDefault();
string mintemp = (string)doc.Descendants("temperature.min").FirstOrDefault();
string maxwindm = (string)doc.Descendants("maxwind_mph").FirstOrDefault();
string maxwindk = (string)doc.Descendants("maxwind_kph").FirstOrDefault();
string humidity = (string)doc.Descendants("avghumidity").FirstOrDefault();
string country = (string)doc.Descendants("country").FirstOrDefault();
string cloud = (string)doc.Descendants("text").FirstOrDefault();
txtmaxtemp.Text = maxtemp;
txtmintemp.Text = mintemp;
txtwindm.Text = maxwindm;
txtwindk.Text = maxwindk;
txthumidity.Text = humidity;
label7.Text = cloud;
txtcountry.Text = country;
}
private void button1_Click(object sender, EventArgs e)
{
}
}
}
You have burned this info in your link that you are asking for a certain city (Seul):
"http://api.openweathermap.org/data/2.5/weather?q***=Seoul***&mode=xml&appid=78dff84492be32f8b4f77692904607a1"
There is no info in your code that you changed it in this link. Please try this:
String.Format("http://api.openweathermap.org/data/2.5/weather?q={0}&mode=xml&appid=78dff84492be32f8b4f77692904607a1",city);
Hope will fine :)
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(...)
I have already create some customization in screen Payment and Application of Acumatica ERP. I have created new Extension of ARPaymentEntryExtension.cs
The following is the source code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using PX.Data;
using PX.Objects.AR;
using PX.Objects.GL;
namespace SGLCustomizeProject
{
public class ARPaymentEntryExtension: PXGraphExtension<ARPaymentEntry>
{
#region Override Button Menu
public override void Initialize()
{
Base.report.AddMenuAction(ReceiptVoucher);
}
#endregion
#region Button Receipt Vocher
public PXAction<ARPayment> ReceiptVoucher;
[PXButton]
[PXUIField(DisplayName = "Receipt Voucher")]
public IEnumerable receiptVoucher(PXAdapter adapter)
{
var result = adapter.Get<ARPayment>();
foreach (ARPayment doc in result)
{
object FinPeriodID;
if (Base.Caches[typeof(ARPayment)].GetStatus(doc) == PXEntryStatus.Notchanged)
{
Base.Caches[typeof(ARPayment)].SetStatus(doc, PXEntryStatus.Updated);
}
Base.Save.Press();
var docPeriod = (FinPeriodID = Base.Caches[typeof(ARPayment)].GetValueExt<ARRegister.finPeriodID>(doc)) is PXFieldState ? (string)((PXFieldState)FinPeriodID).Value : (string)FinPeriodID;
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters["ReferenceNbr"] = doc.RefNbr;
throw new PXReportRequiredException(parameters, "AR909095", "Report");
}
return result;
}
#endregion
}
}
I used extensoin above to preview report from current screen and it works.
When user need to create new document and then add some detail document and then click on save button, it will work.
But, when user need to add another detail document and then click on save button, system will show the error message.
Please refer to the following screenshot.
Actually the error message appear after Acumatica was upgraded into version 2017 R2 - Build 17.207.0029.
In previous version (Version 5.3 - Build 5.30.4209) it work fine.
Does anyone know how to solve this issue ?
I have solve this problem by remove the following If Condition of the code:
if (Base.Caches[typeof(ARPayment)].GetStatus(doc) == PXEntryStatus.Notchanged)
{
Base.Caches[typeof(ARPayment)].SetStatus(doc, PXEntryStatus.Updated);
}
After remove code above, the customization is work and no error.
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
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;