Async-Await func return throws a System.FormatExceprion - async-await

I've been using these lines of code to get Currency from site and when I return value it throws a System.FormatExceprion (curr != null on return)
public static async Task<double> GetCurrencyVal(string url)
{
string xPath = "//*[#id=\"__next\"]/div[2]/div[2]/section/div[2]/div/main/form/div[2]/div[1]/p[2]/text()[1]";
var config = Configuration.Default.WithDefaultLoader();
var doc = await BrowsingContext.New(config).OpenAsync(url).ConfigureAwait(continueOnCapturedContext: false);
await doc.WaitForReadyAsync().ConfigureAwait(continueOnCapturedContext: false);
var curr = doc.DocumentElement.SelectSingleNode(xPath);
if (curr != null)
return double.Parse(curr.Text().Trim());
else
Console.WriteLine("Error");
return -1;
}
private void TimerOnTick(object sender = null, EventArgs eventArgs = null)
{
var now = DateTime.Now.AddSeconds(-DateTime.Now.Second);
double usd = GetCurrencyVal(someUrl).GetAwaiter().GetResult();
double eur = GetCurrencyVal(someUrl).GetAwaiter().GetResult();
}
this line throws a System.FormatException
double usd = GetCurrencyVal(someUrl).GetAwaiter().GetResult();

curr.Text().Trim() has contained "." as separator between int and fractional part, so trying to Parse it to double caused a System.FormatException

Related

gweather_location_get_city_name: assertion 'loc != NULL' failed

I'm trying to fetch my location using GeoClue and GWeather.
I want to display the name of my city in the blank space.
public class Epoch.LabelsGrid : Gtk.Grid {
public Gtk.Label face1_label;
public Gtk.Label face2_label;
public Gtk.Label face3_label;
public Gtk.Label face4_label;
public GClue.Location? geo_location {get; private set; default = null;}
public GWeather.Location location;
private GClue.Simple simple;
construct {
face1_label = new Gtk.Label ("");
face1_label.label = dgettext ("libgweather-locations", location.get_city_name ());
face1_label.halign = Gtk.Align.CENTER;
face1_label.hexpand = true;
face1_label.margin_top = 6;
face1_label.set_ellipsize (END);
face1_label.set_max_width_chars (12);
face2_label = new Gtk.Label ("Paris");
face2_label.set_markup ("<span font_desc='Inter 14'><b>Paris</b></span>");
face2_label.halign = Gtk.Align.CENTER;
face2_label.hexpand = true;
face2_label.margin_top = 6;
face2_label.set_ellipsize (END);
face2_label.set_max_width_chars (12);
face3_label = new Gtk.Label ("London");
face3_label.set_markup ("<span font_desc='Inter 14'><b>London</b></span>");
face3_label.halign = Gtk.Align.CENTER;
face3_label.hexpand = true;
face3_label.margin_top = 6;
face3_label.set_ellipsize (END);
face3_label.set_max_width_chars (12);
face4_label = new Gtk.Label ("New York");
face4_label.set_markup ("<span font_desc='Inter 14'><b>New York</b></span>");
face4_label.halign = Gtk.Align.CENTER;
face4_label.hexpand = true;
face4_label.margin_top = 6;
face4_label.set_ellipsize (END);
face4_label.set_max_width_chars (12);
}
public async void seek () {
try {
simple = yield new GClue.Simple ("com.gihhub.Suzie97.epoch", GClue.AccuracyLevel.CITY, null);
} catch (Error e) {
warning ("Failed to connect to GeoClue2 service: %s", e.message);
return;
}
simple.notify["location"].connect (() => {
on_location_updated.begin ();
});
on_location_updated.begin ();
}
public async void on_location_updated () {
geo_location = simple.get_location ();
location = location.find_nearest_city (geo_location.latitude, geo_location.longitude);
}
}
This is the code.
The code compiles but while executing the program, (com.github.Suzie97.epoch:30386): GWeather-CRITICAL **: 13:21:03.758: gweather_location_get_city_name: assertion 'loc != NULL' failed this warning is displayed.
I found this code snippet on an app by Daniel Fore called Nimbus (Link to nimbus repo)
public void on_location_updated (double latitude, double longitude) {
location = GWeather.Location.get_world ();
location = location.find_nearest_city (latitude, longitude);
if (location != null) {
weather_info.location = location;
weather_info.update ();
stack.visible_child_name = "weather";
}
}
Do I need to do something similar to this?
According to the error message, gweather_location_get_city_name () is emitting an error because the location is NULL (loc != NULL is false). Look at where you're calling get_city_name (). It's at the very top of your constructor, before location is set to anything. You need to wait until you have a location before you try to use it.
Then you should use something like the Nimbus code. It handles the case when simple.get_location () returns NULL (if it can't find your location), and also initializes the GWeather location so it can call find_nearest_city ().

android.widget.TimePicker$TimePickerDelegate.getMinute()' on a null object reference

We tried of using TimerPickerDialog with Number Picker in Xamarin android. Since we have time interval of 15mins
In Android 10 - getMinute() is returning Null
var classForid = Java.Lang.Class.ForName("com.android.internal.R$id");
var timePickerField = classForid.GetField("timePicker");
[![timePicker][1]][1] = (TimePicker)FindViewById(timePickerField.GetInt(null));
var field = classForid.GetField("minute");
NumberPicker minuteSpinner = (NumberPicker)timePicker
.FindViewById(field.GetInt(null));
minuteSpinner.MinValue = 0;
minuteSpinner.MaxValue = (60 / TimePickerInterval) - 1;
List<string> displayedValues = new List<string>();
for (int i = 0; i < 60; i += TimePickerInterval)
{
displayedValues.Add(i.ToString());
}
minuteSpinner.SetDisplayedValues(displayedValues.ToArray());
We need to get the Minute picker. Screenshot:
Try to create a custom TimePickerDialog ,here is a simple sample,you could check it:
create CustomTimePickerDialog :
public class CustomTimePickerDialog : TimePickerDialog
{
private int _interval = 1;
public CustomTimePickerDialog(Context context, EventHandler<TimeSetEventArgs> callBack, int hourOfDay, int minute, bool is24HourView, int interval)
: base(context, ThemeHoloLight, (sender, e) =>
{
callBack(sender, new TimeSetEventArgs(e.HourOfDay, e.Minute * interval));
}, hourOfDay, minute / interval, is24HourView)
{
_interval = interval;
FixSpinner(context, hourOfDay, minute, is24HourView);
}
protected CustomTimePickerDialog(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
{
}
public override void SetView(Android.Views.View view)
{
base.SetView(view);
}
void SetupMinutePicker(Android.Views.View view)
{
var numberPicker = FindMinuteNumberPicker(view as ViewGroup);
if (numberPicker != null)
{
int i = _interval;
List<string> values = new List<string>();
values.Add("00");
while (i < 60)
{
if (i < 10)
values.Add("0" + i);
else
values.Add(i.ToString());
i += _interval;
}
numberPicker.MinValue = 0;
numberPicker.MaxValue = values.Count - 1;
numberPicker.SetDisplayedValues(values.ToArray());
}
}
protected override void OnCreate(Android.OS.Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
GetButton((int)DialogButtonType.Negative).Visibility = Android.Views.ViewStates.Gone;
this.SetCanceledOnTouchOutside(false);
}
private NumberPicker FindMinuteNumberPicker(ViewGroup viewGroup)
{
for (var i = 0; i < viewGroup.ChildCount; i++)
{
var child = viewGroup.GetChildAt(i);
var numberPicker = child as NumberPicker;
if (numberPicker != null)
{
if (numberPicker.MaxValue == 59)
{
return numberPicker;
}
}
var childViewGroup = child as ViewGroup;
if (childViewGroup != null)
{
var childResult = FindMinuteNumberPicker(childViewGroup);
if (childResult != null)
return childResult;
}
}
return null;
}
private void FixSpinner(Context context, int hourOfDay, int minute, bool is24HourView)
{
try
{
// Get the theme's android:timePickerMode
int MODE_SPINNER = 1;
var styleableClass = Java.Lang.Class.ForName("com.android.internal.R$styleable");
var timePickerStyleableField = styleableClass.GetField("TimePicker");
int[] timePickerStyleable = (int[])timePickerStyleableField.Get(null);
var a = context.ObtainStyledAttributes(null, timePickerStyleable, Android.Resource.Attribute.TimePickerStyle, 0);
var timePickerModeStyleableField = styleableClass.GetField("TimePicker_timePickerMode");
int timePickerModeStyleable = timePickerModeStyleableField.GetInt(null);
int mode = a.GetInt(timePickerModeStyleable, MODE_SPINNER);
a.Recycle();
Android.Widget.TimePicker timePicker = (Android.Widget.TimePicker)findField(Java.Lang.Class.FromType(typeof(TimePickerDialog)), Java.Lang.Class.FromType(typeof(Android.Widget.TimePicker)), "mTimePicker").Get(this);
var delegateClass = Java.Lang.Class.ForName("android.widget.TimePicker$TimePickerDelegate");
var delegateField = findField(Java.Lang.Class.FromType(typeof(Android.Widget.TimePicker)), delegateClass, "mDelegate");
var delegatee = delegateField.Get(timePicker);
Java.Lang.Class spinnerDelegateClass;
if (Build.VERSION.SdkInt != BuildVersionCodes.Lollipop)
{
spinnerDelegateClass = Java.Lang.Class.ForName("android.widget.TimePickerSpinnerDelegate");
}
else
{
// TimePickerSpinnerDelegate was initially misnamed TimePickerClockDelegate in API 21!
spinnerDelegateClass = Java.Lang.Class.ForName("android.widget.TimePickerClockDelegate");
}
// In 7.0 Nougat for some reason the timePickerMode is ignored and the delegate is TimePickerClockDelegate
if (delegatee.Class != spinnerDelegateClass)
{
delegateField.Set(timePicker, null); // throw out the TimePickerClockDelegate!
timePicker.RemoveAllViews(); // remove the TimePickerClockDelegate views
var spinnerDelegateConstructor = spinnerDelegateClass.GetConstructors()[0];
spinnerDelegateConstructor.Accessible = true;
// Instantiate a TimePickerSpinnerDelegate
delegatee = spinnerDelegateConstructor.NewInstance(timePicker, context, null, Android.Resource.Attribute.TimePickerStyle, 0);
delegateField.Set(timePicker, delegatee); // set the TimePicker.mDelegate to the spinner delegate
// Set up the TimePicker again, with the TimePickerSpinnerDelegate
timePicker.SetIs24HourView(Java.Lang.Boolean.ValueOf(is24HourView));
timePicker.Hour = hourOfDay;
timePicker.Minute = minute;
timePicker.SetOnTimeChangedListener(this);
}
// set interval
SetupMinutePicker(timePicker);
}
catch (Exception e)
{
throw new Java.Lang.RuntimeException(e.ToString());
}
}
private static Java.Lang.Reflect.Field findField(Java.Lang.Class objectClass, Java.Lang.Class fieldClass, String expectedName)
{
try
{
var field = objectClass.GetDeclaredField(expectedName);
field.Accessible = true;
return field;
}
catch (Java.Lang.NoSuchFieldException e) { } // ignore
// search for it if it wasn't found under the expected ivar name
foreach (var searchField in objectClass.GetDeclaredFields())
{
if (Java.Lang.Class.FromType(searchField.GetType()) == fieldClass)
{
searchField.Accessible = true;
return searchField;
}
}
return null;
}
}
call like this:
CustomTimePickerDialog timePickerDlg = new CustomTimePickerDialog(this, new EventHandler<TimePickerDialog.TimeSetEventArgs>((o,e)=> { }),
hourOfDay, minute, true,15);// the 15 is the minute interval
timePickerDlg.Show();

Icon not highlighted when using BottomBarPage

I’m using the BottomBarPage package. I’m changing the Tab on the fly programmatically, however the icon at the bottom doesn’t get highlighted for Android when there’s a tab change. It works well on iOS on the hand.
I tried James Montemagno’s code, I couldn’t get it to work with the BottomBarPage package.
This is the link to his code
https://montemagno.com/dynamically-changing-xamarin-forms-tab-icons-when-select/
How do I get the Icon highlighted when there is a Tab Page happening programmatically for BottomBarPage?
Below is my code.
public AndroidMainPage(int indexPage)
{
InitializeComponent();
NavigationPage.SetHasNavigationBar(this, false);
CurrentPageChanged += MainPage_CurrentPageChanged;
CurrentPage = Children[indexPage];
CurrentPage.Appearing += (s, a) => Children[indexPage].Icon = new FileImageSource() { File = "quizzes_selected.png" };
CurrentPage.Disappearing += (s, a) => Children[indexPage].Icon = new FileImageSource() { File = "quizzes.png" };
_currentPage = CurrentPage;
}
private void MainPage_CurrentPageChanged(object sender, EventArgs e)
{
IIconChange currentBinding;
if (_currentPage != null)
{
currentBinding = ((NavigationPage)_currentPage).CurrentPage.BindingContext as IIconChange;
if (currentBinding != null)
currentBinding.IsSelected = false;
}
_currentPage = CurrentPage;
currentBinding = ((NavigationPage)_currentPage).CurrentPage.BindingContext as IIconChange;
if (currentBinding != null)
currentBinding.IsSelected = true;
UpdateIcons?.Invoke(this, EventArgs.Empty);
}
Android BottomBarPage Renderer:
[assembly: ExportRenderer(typeof(AndroidMainPage), typeof(MyTabbedPageRenderer))]
namespace TabPageDemo.Android.Renderers
{
public class MyTabbedPageRenderer : BottomBarPageRenderer
{
bool setup;
TabLayout layout;
public MyTabbedPageRenderer()
{
}
protected override void OnElementChanged(ElementChangedEventArgs<BottomBarPage> e)
{
if (e != null) base.OnElementChanged(e);
if (Element != null)
{
((AndroidMainPage)Element).UpdateIcons += Handle_UpdateIcons;
}
}
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (layout == null && e.PropertyName == "Renderer")
{
layout = (TabLayout)ViewGroup.GetChildAt(1);
}
}
void Handle_UpdateIcons(object sender, EventArgs e)
{
TabLayout tabs = layout;
if (tabs == null)
return;
for (var i = 0; i < Element.Children.Count; i++)
{
var child = Element.Children[i].BindingContext as IIconChange;
if (child == null) continue;
var icon = child.CurrentIcon;
if (string.IsNullOrEmpty(icon))
continue;
TabLayout.Tab tab = tabs.GetTabAt(i);
SetCurrentTabIcon(tab, icon);
}
}
void SetCurrentTabIcon(TabLayout.Tab tab, string icon)
{
tab.SetIcon(IdFromTitle(icon, ResourceManager.DrawableClass));
}
int IdFromTitle(string title, Type type)
{
string name = Path.GetFileNameWithoutExtension(title);
int id = GetId(type, name);
return id;
}
int GetId(Type type, string memberName)
{
object value = type.GetFields().FirstOrDefault(p => p.Name == memberName)?.GetValue(type)
?? type.GetProperties().FirstOrDefault(p => p.Name == memberName)?.GetValue(type);
if (value is int)
return (int)value;
return 0;
}
}
}
Using the Renderer, the tab variable is always null from this TabLayout.Tab tab = tabs.GetTabAt(i);
Any suggestion?

Add ajax behaviour to JSF renderer

I have a custom JSF component renderer that renders pagination component for datatables, but it hasn't ajax behavior . I learned that it could be done by inserting ajax to encode method or by making support of f ajax tag. Unfortunately I'm not very familiar with ajax, so could you please tell me how I should modify this code to make it ajaxable?
#FacesRenderer(componentFamily="javax.faces.Command",
rendererType="com.component.Pager")
public class PagerRenderer extends Renderer {
private static final int SHOW_PAGES = 3;
private static final String HIDDEN_FIELD_ID ="tableFormPaginatorInput";
public void encodeBegin(FacesContext context, UIComponent component)
throws IOException {
ClientBehaviorContext behaviorContext =
ClientBehaviorContext.createClientBehaviorContext(context,
component, "click", component.getClientId(context), null);
String id = component.getClientId(context);
UIComponent parent = component;
while (!(parent instanceof UIForm)) parent = parent.getParent();
String formId = parent.getClientId(context);
ResponseWriter writer = context.getResponseWriter();
writer.startElement("div", component);
writer.writeAttribute("class", "paginator-section", null);
String styleClass = (String) component.getAttributes().get("styleClass");
String selectedStyleClass
= (String) component.getAttributes().get("selectedStyleClass");
String dataTableId = (String) component.getAttributes().get("dataTableId");
// find the component with the given ID
UIData data = (UIData) component.findComponent(dataTableId);
int first = data.getFirst();
int itemcount = data.getRowCount();
int pagesize = data.getRows();
if (pagesize <= 0) pagesize = itemcount;
int pages = itemcount / pagesize;
if (itemcount % pagesize != 0) pages++;
int currentPage = first / pagesize;
if (first >= itemcount - pagesize) currentPage = pages - 1;
int startPage = 0;
int endPage = pages;
if (SHOW_PAGES > 0) {
startPage = (currentPage / SHOW_PAGES ) * SHOW_PAGES ;
endPage = Math.min(startPage + SHOW_PAGES , pages);
}
if (currentPage > 0)
writeLink(writer, component, formId, id, "<", styleClass);
if (startPage > 0)
writeLink(writer, component, formId, id, "..", styleClass);
for (int i = startPage; i < endPage; i++) {
writeLink(writer, component, formId, id, "" + (i + 1),
i == currentPage ? selectedStyleClass : styleClass);
}
if (endPage < pages)
writeLink(writer, component, formId, id, "...", styleClass);
if (first < itemcount - pagesize)
writeLink(writer, component, formId, id, ">", styleClass);
/* CommandButton commandButton = new CommandButton();
commandButton.setValue(currentPage);
commandButton.setUpdate("");
commandButton.setAjax(true);
commandButton.addActionListener(new MyActionListener());
commandButton.encodeAll(context);*/
writer.endElement("div");
// hidden field to hold result
writeHiddenField(writer, component, id);
}
private void writeLink(ResponseWriter writer, UIComponent component,
String formId, String id, String value, String styleClass)
throws IOException {
writer.writeText(" ", null);
writer.startElement("a", component);
writer.writeAttribute("href", "#", null);
writer.writeAttribute("onclick", onclickCode(formId, id, value) , null);
if (styleClass != null)
writer.writeAttribute("class", styleClass, "styleClass");
writer.writeText(value, null);
writer.endElement("a");
}
private void writeLink1(ResponseWriter writer, UIComponent component,
String formId, String id, String value, String styleClass)
throws IOException {
writer.writeText(" ", null);
writer.startElement("a", component);
writer.writeAttribute("href", "#", null);
writer.writeAttribute("data-tableFormPaginator", value, null);
if (styleClass != null)
writer.writeAttribute("class", styleClass, "styleClass");
writer.writeText(value, null);
writer.endElement("a");
}
private String onclickCode(String formId, String id, String value) {
return new StringBuilder().append("document.forms['")
.append(formId).append("']['")
.append(id).append("'].value='").append(value).append("'; document.forms['")
.append(formId).append("'].submit(); return false;").toString();
}
private String onclickCodewithout(String formId, String id, String value,UIComponent component) {
return "jsf.ajax.request('" + component.getClientId() +
"', null, {'render': '" +
component.getParent().getClientId() + "',"+id+":"+value+" })";
}
private void writeHiddenField(ResponseWriter writer, UIComponent component,
String id) throws IOException {
writer.startElement("input", component);
writer.writeAttribute("id", HIDDEN_FIELD_ID, null);
writer.writeAttribute("class", "paginator-input-value", null);
writer.writeAttribute("type", "hidden", null);
writer.writeAttribute("name", id, null);
writer.endElement("input");
}
public void decode(FacesContext context, UIComponent component) {
String id = component.getClientId(context);
Map<String, String> parameters
= context.getExternalContext().getRequestParameterMap();
String response = (String) parameters.get(id);
if (response == null || response.equals("")) return;
String dataTableId = (String) component.getAttributes().get("dataTableId");
int showpages = SHOW_PAGES ;//toInt(component.getAttributes().get("showpages"));
UIData data = (UIData) component.findComponent(dataTableId);
int first = data.getFirst();
int itemcount = data.getRowCount();
int pagesize = data.getRows();
if (pagesize <= 0) pagesize = itemcount;
if (response.equals("<")) first -= pagesize;
else if (response.equals(">")) first += pagesize;
else if (response.equals("..")) first -= pagesize * showpages;
else if (response.equals("...")) first += pagesize * showpages;
else {
int page = Integer.parseInt(response);
first = (page - 1) * pagesize;
}
if (first + pagesize > itemcount) first = itemcount - pagesize;
if (first < 0) first = 0;
data.setFirst(first);
}
private static int toInt(Object value) {
if (value == null) return 0;
if (value instanceof Number) return ((Number) value).intValue();
if (value instanceof String) return Integer.parseInt((String) value);
throw new IllegalArgumentException("Cannot convert " + value);
}
f:ajax tag can only be directly nested in an UIComponent which implements the ClientBehaviorHolder interface.
I saw that you try to implement onclick for your table, if you are using Mojarra, then it has utils method that you help you render onclick behavior that will work with f:ajax as well
renderSelectOnclick
http://grepcode.com/file/repo1.maven.org/maven2/com.sun.faces/jsf-impl/2.1.19/com/sun/faces/renderkit/RenderKitUtils.java#RenderKitUtils.renderSelectOnclick%28com.sun.faces.renderkit.FacesContext%2Cjavax.faces.component.UIComponent%2Cboolean%29
You can use it inside your encode method

Unauthorizedaccessexception{"Invalid cross-thread access."}...is occur

i want to short my url with bitly but an exception is occur when i want to set out string to my text block
private void button1_Click(object sender, RoutedEventArgs e)
{
ShortenUrl(textBox1.Text);
}
enum Format
{
XML,
JSON,
TXT
}
enum Domain
{
BITLY,
JMP
}
void ShortenUrl(string longURL)
{
Format format = Format.XML;
Domain domain = Domain.BITLY;
string _domain;
//string output;
// Build the domain string depending on the selected domain type
if (domain == Domain.BITLY)
_domain = "bit.ly";
else
_domain = "j.mp";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
string.Format(#"http://api.bit.ly/v3/shorten?login={0}&apiKey={1}&longUrl={2}&format={3}&domain={4}",
"username", "appkey", HttpUtility.UrlEncode(longURL), format.ToString().ToLower(), _domain));
request.BeginGetResponse(new AsyncCallback(GetResponse), request);
}
void GetResponse(IAsyncResult result)
{
XDocument doc;
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string responseString = reader.ReadToEnd();
doc = XDocument.Load(reader.BaseStream);
}
//// var x = from c in doc.Root.Element("data").Elements()
// where c.Name == "url"
// select c;
//XElement n = ((IEnumerable<XElement>)x).ElementAt(0);
// textBox2.Text = ((IEnumerable<String>)x).ElementAt(0);
lista = (from Born_rich in doc.Descendants("url")
select new a()
{
shrtenurl = Born_rich.Value
}).ToList();
output = lista.ElementAt(0).shrtenurl;
textBox2.Text = output;
//
//
// textBox2.Text = s;
}
List<a> lista = new List<a>();
String output;
}
public class a
{
public String shrtenurl { set; get; }
}
The calback from HttpWebRequest occurs on a non-UI thread. If you want to change soemthing in the UI you must do it on the UI thread. Fortunatley there is an easy way to do this. You simply use the dispatcher to invoke the code in question on the UI.
Dispatcher.BeginInvoke(() => textBox2.Text = output);

Resources