I was using Xamarin Insights until recently. I removed it from my project because it increases start up time and app size significantly. So I was left with 2 options Hockeyapp and Mobile Center from Microsoft. Problem with these 2 is that they dont have any reporting functionality for reporting caught exceptions typically what you would do inside your try catch in your xamarin forms project.
Very disappointing indeed.
xamarin insight had this and it worked fine. I would like to ask how can we report exceptions in forms project? is application insight an option. I used in other .net projects but UI is not so usable indeed.
There is even a thread on github here
https://github.com/Microsoft/ApplicationInsights-Xamarin/issues/26
Microsoft is saying that we are working on it for a year or more and never delivers anything and keeps deprecating things.
We use Mobile Center for reporting issues. Basically in each catch statement we use a static class to report issues, like so:
public static class EventTrace
{
public static void Trace(string menuName, string actionName, Dictionary<string, string> parameters = null)
{
try
{
Dictionary<string, string> tmp;
if (parameters != null)
tmp = new Dictionary<string, string>(parameters);
else
tmp = new Dictionary<string, string>();
tmp.Add("GUID", MobileCenter.InstallId.ToString());
Analytics.TrackEvent(menuName + " - " + actionName, tmp);
}
catch (Exception ex)
{
Analytics.TrackEvent("Event Trace - Error creating event", new Dictionary<string, string> { { "Exception", ex.ToString() } });
Analytics.TrackEvent(menuName + " - " + actionName, parameters);
}
}
public static void Error(string menuName, string exception)
{
var parameters = new Dictionary<string, string> { { "Exception", exception } };
var tmp = new Dictionary<string, string>(parameters);
try
{
tmp.Add("GUID", MobileCenter.InstallId.ToString());
Analytics.TrackEvent(menuName + " - Error", tmp);
}
catch (Exception ex)
{
Analytics.TrackEvent("Event Trace - Error creating event", new Dictionary<string, string> { { "Exception", ex.ToString() } });
Analytics.TrackEvent(menuName + " - Error", parameters);
}
}
}
We have events for tracing, and events for catch error. In mobile center, we can basically search for the "Error" statement in the event tab.
It works for us, hope it works for you!
Related
Hi guys I'm developing Multiplatform app with Xamarin and I'm using OneSignal platform for push notification.
Here's the code for sending push in post:
var uri = new Uri("https://onesignal.com/api/v1/notifications");
Dictionary<string, object> userData = new Dictionary<string, object>
{
{ "app_id", "MyAppID" },
{"channel_for_external_user_ids", "push" },
{ "include_external_user_ids", new string[] { $"MyID" } },
{"contents", new {en = "Are you ok?" } },
{"headings", new {en = "Ehi" } },
{"data", new {FromID = 1234} },
{"priority", 10 },
};
Notification is sent without any problem. In my Xamarin app I try to detect "data", and here's the issue.
private static void HandleNotificationOpened(OSNotificationOpenedResult result)
{
try
{
//Notification data
OSNotificationPayload payload = result.notification.payload;
Dictionary<string, object> additionalData = payload.additionalData;
int NotificationFromID = 0;
if (additionalData != null)
{
if (additionalData.ContainsKey("FromID"))
{
NotificationFromID = (int)additionalData["FromID"]);
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
I got error System.InvalidCastException: Specified cast is not valid.
I tried everything: Convert.ToInt32, I tried to pass a string... but nothing works.
If I do something like that
Debug.WriteLine(additionalData["FromID"].GetType());
I got Foundation.NSNumber (if I try to pass a string) or Foundation.NSString (if I try to pass a string). I guess NSNumber and NSString are iOS objects
How can I solve this?
I just need to pass an integer value
thanks
I have this problem on a asp.net website, but it should be general for .Net Core on windows computer.
If I try to translate an nonexistent Domain, I’ll get an exception, it’s OK, but then, all next calls with correct domain name throw an exception also "System.ObjectDisposedException: Safe handle has been closed".
I'm asking about some workaround, because name translation does ‘not work until restart of application.
This behavior can be reproduced with
Microsoft.NETCore.App 2.2.0
System.Security.Principal.Windows 4.5.1
class Program
{
static string Translate(string gName)
{
try
{
var nt = new NTAccount(gName);
if (nt.IsValidTargetType(typeof(SecurityIdentifier)))
{
var si = (SecurityIdentifier)(nt).Translate(typeof(SecurityIdentifier));
return si.ToString();
}
}
catch (Exception ex)
{
Console.Write(ex.ToString()+"\n\n");
}
return "";
}
static void Main(string[] args)
{
var si= new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
var na = si.Translate(typeof(NTAccount));
var knownName = na.ToString();
foreach (var aName in new[] { knownName,
#"DOMAIN_NOT_ESISTS\Benutzer",
knownName })
{
Console.WriteLine(aName);
Console.WriteLine(Translate(aName));
}
Console.ReadKey();
}
}
I have the following code
public void start(Stage primaryStage) {
BorderPane border_pane = new BorderPane();
TreeView tree = addTreeView(); //TreeView on the LEFT
border_pane.setLeft(tree);
/* more stuff added to the border_pane here... */
Scene scene = new Scene(border_pane, 900, 700);
scene.setFill(Color.GHOSTWHITE);
primaryStage.setTitle("PlugControl v0.1e");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
With addTreeView being a function that reads data off an SQL DB and adds around ~35 TreeItems, based on that data. The addition of TreeItems to treeItemRoot is done in a seperate thread. NOTE: treeItemRoot is declared in the main class, and is null before here.
public TreeView addTreeView() { //Our treeView is positioned on the LEFT
treeItemRoot = new PlugTreeItem<>("Active Plugs", new ImageView(new Image(getClass().getResourceAsStream("graphics/plugicon.png"))), new Plug()); //Root of the tree, contains a dummy Plug object.
selectedTreeItem = treeItemRoot;
treeItemRoot.setExpanded(true); //always expand it
selectedTreeItem.getPlugItem()
.getSIHUid().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue
) {
System.err.println("changed " + oldValue + "->" + newValue);
}
}
);
TreeView<String> treeView = new TreeView<>(treeItemRoot); //Build the tree with our root node.
final Task task;
task = new Task<Void>() {
#Override
protected Void call() throws Exception {
//=========== SQL STUFF BEGINS HERE ============================
Statement sta = null;
ResultSet result_set = null;
Connection conn = null;
try {
try {
System.err.println("Loading JDBC driver...");
Class.forName("com.mysql.jdbc.Driver");
System.err.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new RuntimeException("Cannot find JDBC driver in the classpath!", e);
}
System.err.println("Connecting to database...");
conn = DriverManager.getConnection("[DB link here]", "[username]", "[password]"); //Username is PlugControl, pw is woof
System.err.println("Connected to Database!");
sta = conn.createStatement();
String sql_query = "SELECT * FROM pwnodes INNER JOIN pwcomports ON pwnodes.NetworkID = pwcomports.NetworkID WHERE pwnodes.connection = 'on' ORDER BY pwnodes.Location";
result_set = sta.executeQuery(sql_query);
System.err.println("SQL query successfuly executed!");
int count = 0;
while (result_set.next()) {
Plug pl = null; //MARKER: We might need to do switch (result_set.getString("Server")) for SIHU1 and SIHU2.
count++;
pl = new Plug(result_set.getString("SIHUid"), result_set.getString("sensorID"), result_set.getString("Location"), result_set.getString("Appliance"), result_set.getString("Type"), result_set.getString("connection"), result_set.getString("Server"), result_set.getString("ServerIP"));
PlugTreeItem<String> pti = new PlugTreeItem(pl.getSIHUid().getValue() + " " + pl.getLocation() + " " + pl.getAppliance(), new ImageView(new Image(getClass().getResourceAsStream("graphics/smiley.png"))), pl); //icon does not work in children
treeItemRoot.getChildren().add(pti); //CONCURRENCY ERRORS HERE
}
System.err.println("ALERT SQL QUERY RESULTS: " + count);
} catch (SQLException e) //linked try clause # line 50
{
throw new RuntimeException("Cannot connect the database!", e);
} finally { // Time to wrap things up, by closing all open SQL procs.
try {
if (sta != null) {
sta.close();
}
if (result_set != null) {
result_set.close();
}
if (conn != null) {
System.err.println("Closing the connection.");
conn.close();
}
} catch (SQLException e) //We might as well ignore this, but just in case.
{
throw new RuntimeException("Error while closing up statement, result set and connection!", e);
}
}
//============== SQL STUFF ENDS HERE ===========================
System.err.println("Finished");
return null;
}
};
new Thread(task).start(); //Run the task!
treeView.getSelectionModel()
.selectedItemProperty().addListener(new ChangeListener() {
#Override
public void changed(ObservableValue observable, Object oldValue, Object newValue
) {
selectedTreeItem = (PlugTreeItem<String>) newValue;
System.err.println("DEBUG: Selection plug SIHUid: " + selectedTreeItem.getPlugItem().print()); //MARKER: REMOVE
updateTextFields(); //Update TextAreas.
if (!"DUMMY".equals(selectedTreeItem.getPlugItem().getSIHUid().getValue())) {
buttonOn.setDisable(false);
buttonOff.setDisable(false);
} else {
buttonOn.setDisable(true);
buttonOff.setDisable(true);
}
}
}
);
return treeView;
}
Once every 5-6 runs I receive a ConcurrentModificationException because I think the Thread task() doesn't manage to finish before addTreeView's returned TreeView is added to the border_pane, and maybe it begins iterating through it while it's still having items added to it?
Executing C:\Users\74\Documents\NetBeansProjects\PlugControl_v0.5\dist\run1559674105\PlugControl.jar using platform C:\Program Files\Java\jdk1.7.0_25\jre/bin/java
Loading JDBC driver...
Driver loaded!
Connecting to database...
Connected to Database!
SQL query successfuly executed!
java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:819)
at java.util.ArrayList$Itr.next(ArrayList.java:791)
at com.sun.javafx.collections.ObservableListWrapper$ObservableListIterator.next(ObservableListWrapper.java:681)
at javafx.scene.control.TreeItem.updateExpandedDescendentCount(TreeItem.java:788)
at javafx.scene.control.TreeItem.getExpandedDescendentCount(TreeItem.java:777)
at javafx.scene.control.TreeView.getExpandedDescendantCount(TreeView.java:864)
at javafx.scene.control.TreeView.updateTreeItemCount(TreeView.java:873)
at javafx.scene.control.TreeView.impl_getTreeItemCount(TreeView.java:533)
at com.sun.javafx.scene.control.skin.TreeViewSkin.getItemCount(TreeViewSkin.java:207)
at com.sun.javafx.scene.control.skin.TreeViewSkin.updateItemCount(TreeViewSkin.java:220)
at com.sun.javafx.scene.control.skin.TreeViewSkin.handleControlPropertyChanged(TreeViewSkin.java:135)
at com.sun.javafx.scene.control.skin.SkinBase$3.changed(SkinBase.java:282)
at javafx.beans.value.WeakChangeListener.changed(WeakChangeListener.java:107)
at com.sun.javafx.binding.ExpressionHelper$SingleChange.fireValueChangedEvent(ExpressionHelper.java:196)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:100)
at javafx.beans.property.IntegerPropertyBase.fireValueChangedEvent(IntegerPropertyBase.java:123)
at javafx.beans.property.IntegerPropertyBase.markInvalid(IntegerPropertyBase.java:130)
at javafx.beans.property.IntegerPropertyBase.set(IntegerPropertyBase.java:163)
at javafx.scene.control.TreeView.setTreeItemCount(TreeView.java:515)
at javafx.scene.control.TreeView.updateTreeItemCount(TreeView.java:876)
at javafx.scene.control.TreeView.impl_getTreeItemCount(TreeView.java:533)
at javafx.scene.control.TreeCell.updateItem(TreeCell.java:391)
at javafx.scene.control.TreeCell.access$000(TreeCell.java:67)
at javafx.scene.control.TreeCell$1.invalidated(TreeCell.java:95)
at com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(ExpressionHelper.java:155)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:100)
at javafx.beans.property.ReadOnlyIntegerWrapper$ReadOnlyPropertyImpl.fireValueChangedEvent(ReadOnlyIntegerWrapper.java:195)
at javafx.beans.property.ReadOnlyIntegerWrapper.fireValueChangedEvent(ReadOnlyIntegerWrapper.java:161)
at javafx.beans.property.IntegerPropertyBase.markInvalid(IntegerPropertyBase.java:130)
at javafx.beans.property.IntegerPropertyBase.set(IntegerPropertyBase.java:163)
at javafx.scene.control.IndexedCell.updateIndex(IndexedCell.java:112)
at com.sun.javafx.scene.control.skin.VirtualFlow.setCellIndex(VirtualFlow.java:1596)
at com.sun.javafx.scene.control.skin.VirtualFlow.addLeadingCells(VirtualFlow.java:1049)
at com.sun.javafx.scene.control.skin.VirtualFlow.layoutChildren(VirtualFlow.java:1005)
at com.sun.javafx.scene.control.skin.VirtualFlow.setCellCount(VirtualFlow.java:206)
at com.sun.javafx.scene.control.skin.TreeViewSkin.updateItemCount(TreeViewSkin.java:225)
at com.sun.javafx.scene.control.skin.TreeViewSkin.handleControlPropertyChanged(TreeViewSkin.java:135)
at com.sun.javafx.scene.control.skin.SkinBase$3.changed(SkinBase.java:282)
at javafx.beans.value.WeakChangeListener.changed(WeakChangeListener.java:107)
at com.sun.javafx.binding.ExpressionHelper$SingleChange.fireValueChangedEvent(ExpressionHelper.java:196)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:100)
at javafx.beans.property.IntegerPropertyBase.fireValueChangedEvent(IntegerPropertyBase.java:123)
at javafx.beans.property.IntegerPropertyBase.markInvalid(IntegerPropertyBase.java:130)
at javafx.beans.property.IntegerPropertyBase.set(IntegerPropertyBase.java:163)
at javafx.scene.control.TreeView.setTreeItemCount(TreeView.java:515)
at javafx.scene.control.TreeView.updateTreeItemCount(TreeView.java:876)
at javafx.scene.control.TreeView.impl_getTreeItemCount(TreeView.java:533)
at javafx.scene.control.TreeCell.updateItem(TreeCell.java:391)
at javafx.scene.control.TreeCell.access$000(TreeCell.java:67)
at javafx.scene.control.TreeCell$1.invalidated(TreeCell.java:95)
at com.sun.javafx.binding.ExpressionHelper$SingleInvalidation.fireValueChangedEvent(ExpressionHelper.java:155)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:100)
at javafx.beans.property.ReadOnlyIntegerWrapper$ReadOnlyPropertyImpl.fireValueChangedEvent(ReadOnlyIntegerWrapper.java:195)
at javafx.beans.property.ReadOnlyIntegerWrapper.fireValueChangedEvent(ReadOnlyIntegerWrapper.java:161)
at javafx.beans.property.IntegerPropertyBase.markInvalid(IntegerPropertyBase.java:130)
at javafx.beans.property.IntegerPropertyBase.set(IntegerPropertyBase.java:163)
at javafx.scene.control.IndexedCell.updateIndex(IndexedCell.java:112)
at com.sun.javafx.scene.control.skin.VirtualFlow.setCellIndex(VirtualFlow.java:1596)
at com.sun.javafx.scene.control.skin.VirtualFlow.getCell(VirtualFlow.java:1500)
at com.sun.javafx.scene.control.skin.VirtualFlow.getCellLength(VirtualFlow.java:1523)
at com.sun.javafx.scene.control.skin.VirtualFlow$3.call(VirtualFlow.java:478)
at com.sun.javafx.scene.control.skin.VirtualFlow$3.call(VirtualFlow.java:476)
at com.sun.javafx.scene.control.skin.PositionMapper.computeViewportOffset(PositionMapper.java:143)
at com.sun.javafx.scene.control.skin.VirtualFlow.layoutChildren(VirtualFlow.java:1001)
at javafx.scene.Parent.layout(Parent.java:1018)
at javafx.scene.Parent.layout(Parent.java:1028)
at javafx.scene.Parent.layout(Parent.java:1028)
at javafx.scene.Parent.layout(Parent.java:1028)
at javafx.scene.Scene.layoutDirtyRoots(Scene.java:516)
at javafx.scene.Scene.doLayoutPass(Scene.java:487)
at javafx.scene.Scene.access$3900(Scene.java:170)
at javafx.scene.Scene$ScenePulseListener.pulse(Scene.java:2203)
at com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:363)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:460)
at com.sun.javafx.tk.quantum.QuantumToolkit$9.run(QuantumToolkit.java:329)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:29)
at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:73)
at java.lang.Thread.run(Thread.java:724)
ALERT SQL QUERY RESULTS: 35
Closing the connection.
Finished
Any help/advice on dealing with the issue, guys? The exception doesn't point me towards a place in my code, and so far I'm working on hunches.}
EDIT: For reference, PlugTreeItem is just a TreeItem<> that also carries a Plug with it, Plug being a class of mine that holds a few String values. Nothing special.
public class PlugTreeItem<T> extends TreeItem{ \* code *\}
I would suggest you to make a List<Plug> inside your while loop rather than making individual object and adding it to the tree, because all operations on javafx controls must be done on javafx thread and not on task thread !
Create a list outside the Thread body
List<Plug> listOfPlugs = new ArrayList<Plug>();
Then, in the while loop, you can write
int count = 0;
while (result_set.next()) {
Plug pl = null;
count++;
pl = new Plug(result_set.getString("SIHUid"),
result_set.getString("sensorID"), result_set.getString("Location"),
result_set.getString("Appliance"), result_set.getString("Type"),
result_set.getString("connection"), result_set.getString("Server"),
result_set.getString("ServerIP"));
listOfPlugs.add(p1);
}
Later, after you start the thread you can make the following code
new Thread(task).start();
task.setOnSucceeded(new EventHandler<WorkerStateEvent>()
{
#Override
public void handle(WorkerStateEvent workerStateEvent) {
for(Plug p1 : listOfPlugs)
{
PlugTreeItem<String> pti = new PlugTreeItem(pl.getSIHUid().getValue()
+ " " + pl.getLocation() + " " + pl.getAppliance(),
new ImageView(new Image(
getClass().getResourceAsStream("graphics/smiley.png"))), pl);
treeItemRoot.getChildren().add(pti);
}
}
I don't see you syncing on the javafx application thread which is required when coming from another one
I have tried hundreds of times to find errors for this piece of codes.
It only works through WIFI, but When I switch off WIFI on my phone, and run the app again, this app just shut down automatically, which means it thrown an exception.
The app is simple, I used WebClint() to download HTML source and parsed it with HTML Agility Pack, then added them to a list, foreach the list to creat each news object.
I have tried catch the exception stacktrace and bind it to a texblock, It said some of ArgumentOutOfRange exception and Genericlist(int32 index)???
I have no idea about it, It was fine in wifi, but not in 3G network. Can anyone help?
public partial class MainPage : PhoneApplicationPage
{
string srcHTML;
HtmlNode UrlNode;
ObservableCollection<News> newsList = new ObservableCollection<News>();
List<HtmlNode> headlines;
HtmlDocument hd;
News n;
// Constructor
public MainPage()
{
InitializeComponent();
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
WebClient webClenet = new WebClient();
webClenet.Encoding = new HtmlAgilityPack.Gb2312Encoding();
webClenet.DownloadStringAsync(new Uri("http://www.6park.com/news/multi1.shtml", UriKind.RelativeOrAbsolute));
webClenet.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClenet_DownloadStringCompleted);
}
private void webClenet_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
srcHTML = e.Result;
GetHeadlinePage(srcHTML);
}
private void GetHeadlinePage(string srcHTML)
{
hd = new HtmlDocument();
hd.LoadHtml(srcHTML);
try
{
UrlNode = hd.DocumentNode.ChildNodes[1].ChildNodes[3].ChildNodes[8].ChildNodes["tr"].ChildNodes["td"].ChildNodes["ul"];
headlines = UrlNode.Descendants("a").ToList();
foreach (var headline in headlines)
{
if (headline.Attributes["href"].Value.Contains("6park"))
{
n = new News();
n.NewsTitle = headline.InnerText;
n.NewsUrl = headline.Attributes["href"].Value;
n.NewsDetails = headline.NextSibling.InnerText.Replace("- ", "新闻来源:") + headline.NextSibling.NextSibling.InnerText + headline.NextSibling.NextSibling.NextSibling.InnerText;
newsList.Add(n);
}
}
}
catch (Exception ex)
{
//NewsSource.Text = ex.StackTrace + "\n" + ex.Message;
}
NewslistBox.ItemsSource = newsList;
//NewsHeadlineWebBrowser.NavigateToString(ConvertExtendedASCII(headNews));
}
}
I'd debug the value passed to GetHeadlinePage().
I'd suspect that the response is different based on the network or the request is timing out or you're getting some other error.
I'd assume that the call to LoadHtml() is failing as this isn't inside any exception handling/trapping and you've not validating the value passed to it.
I'm using WebClient object in to poll some data from server.
It's working good and it's updating text block fine. Till I don't use map on same Page. When I add a map, only one request get completed and data is retrieved only once.
This is the code for getting messages:
public MessagesPage()
{
InitializeComponent();
new System.Threading.Timer(messagePolling, null, 0, 5000); // every 5 seconds
}
void messagePolling(object state)
{
getMessages(Const.GET_MESSAGES_URL + uuid);
}
private void getMessages(string uri)
{
WebClient webClient = new WebClient();
webClient.DownloadStringAsync(new Uri(uri));
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(messagesResponseCompleted);
}
void messagesResponseCompleted(object sender, DownloadStringCompletedEventArgs e)
{
lock (this)
{
try
{
string s = e.Result;
if (s.Length > 0)
{
List<Message> messagesResult = JSONHelper.Deserialize<List<Message>>(s);
foreach (Message m in messagesResult)
{
tbMessages.Text += m.message + "\n";
}
}
else
{
tbMessages.Text += "No new messages #: " + System.DateTime.Now + "\n";
}
}
catch (System.Net.WebException we)
{
MessageBox.Show(we.Message);
}
}
}
Anyone?
The WebClient response is processed on the UI thread - so you don't need the lock that you have in your event handler.
For your particular problem - is this just occurring in the emulator? I've seen quite a few timer issues with the emulator - but never anything similar on the real phone.
As an aside, I believe in general it's better to use HttpWebRequest rather than WebClient - see the explanation here of webclient using the UI thread Silverlight Background Thread using WebClient - for your particular code I don't think this will be a problem.
If using
System.Windows.Threading.DispatcherTimer myDispatcherTimer = new System.Windows.Threading.DispatcherTimer();
myDispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 5000);
myDispatcherTimer.Tick += new EventHandler(messagePolling);
myDispatcherTimer.Start();
instead of
new System.Threading.Timer(messagePolling, null, 0, 5000); // every 5 seconds
is working fine =)