So I've been stuck on this for a while. (Forms application)
I want this to run in the "Background".
I normally call it with the "search button".
So far I've read you can't access UI stuff in another thread? So how would I approach this and make the UI accessible while it loads the results and converts them into buttons?
Is there any easy way to do this for someone who just started out with C#?
Code below :
private void Search_Video_Youtube(string page)
{
YouTubeService youtube = new YouTubeService(new BaseClientService.Initializer()
{
ApplicationName = this.GetType().ToString(),
ApiKey = "*MyApiKeyGoesHere*",
});
var listRequest = youtube.Search.List("snippet");
listRequest.Q = Youtube_SearchVideo_Box.Text;
listRequest.MaxResults = 50;
listRequest.Type = "video";
listRequest.PageToken = nextPageToken;
video_results_vids = video_results_vids + 50;
var resp = listRequest.Execute();
List<string> videos = new List<string>();
foreach (SearchResult result in resp.Items)
{
switch (result.Id.Kind)
{
case "youtube#video":
PictureBox picturebox = new PictureBox();
picturebox.Height = 100;
picturebox.Width = 100;
picturebox.BorderStyle = BorderStyle.None;
picturebox.SizeMode = PictureBoxSizeMode.StretchImage;
string template2 = "http://i3.ytimg.com/vi/{0}{1}";
string data2 = result.Id.VideoId.ToString();
string quality2 = "/default.jpg";
string messageB = string.Format(template2, data2, quality2);
var request = WebRequest.Create(messageB);
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
picturebox.Image = Bitmap.FromStream(stream);
}
flowLayoutPanel1.Controls.Add(picturebox);
listnumber += 1;
Button button = new Button();
button.Text = listnumber.ToString() + " " + result.Snippet.Title.ToString();
button.Tag = result.Id.VideoId;
button.TextImageRelation = TextImageRelation.ImageBeforeText;
button.FlatStyle = FlatStyle.Flat;
button.ForeColor = Color.LightSteelBlue;
button.BackColor = Color.SteelBlue;
button.Width = (flowLayoutPanel1.Width - 150);
button.TextAlign = ContentAlignment.MiddleLeft;
button.Height = 100;
button.Font = new Font(button.Font.FontFamily, 10);
button.Click += (s, e) => {
Youtube_video_Player_hider.Visible = false;
var a = result.Id.VideoId;
string template = "https://www.youtube.com/v/{0}{1}";
string data = a.ToString();
string quality = Video_Quality;
string messagea = string.Format(template, data, quality);
axShockwaveFlash1.Movie = messagea;
axShockwaveFlash1.Play();
};
flowLayoutPanel1.Controls.Add(button);
break;
}
}
nextPageToken = resp.NextPageToken;
toolStripStatusLabel1.Text = "Status : Idle";
toolStripStatusLabel2.Text = "Results : " + video_results_vids;
}
Any help is welcome but please explain it in detail as I am very new to C# but I do have a basic programming knowledge.
(Also if you see anything I could do better feel free to point it out, am here to learn :) )
EDIT : Thanks to Jeroen van langen (Answer below) I figured it out.
The current code is now :
// At using Stuff
using ExtensionMethods;
private void Search_Video_Youtube(string page)
{
ThreadPool.QueueUserWorkItem(new WaitCallback((state) =>
{
YouTubeService youtube = new YouTubeService(new BaseClientService.Initializer()
{
ApplicationName = this.GetType().ToString(),
ApiKey = "ThisIsTheApiKeyYouTubeWantsForAnyoneWondering",
});
var listRequest = youtube.Search.List("snippet");
listRequest.Q = Youtube_SearchVideo_Box.Text;
listRequest.MaxResults = 50;
listRequest.Type = "video";
listRequest.PageToken = nextPageToken;
video_results_vids = video_results_vids + 50;
var resp = listRequest.Execute();
List<string> videos = new List<string>();
Parallel.ForEach(resp.Items, (SearchResult result) =>
{
switch (result.Id.Kind)
{
case "youtube#video":
string template2 = "http://i3.ytimg.com/vi/{0}{1}";
string data2 = result.Id.VideoId.ToString();
string quality2 = "/default.jpg";
string messageB = string.Format(template2, data2, quality2);
Image image;
var request = WebRequest.Create(messageB);
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
image = Bitmap.FromStream(stream);
}
listnumber += 1;
this.Invoke(() =>
{
PictureBox picturebox = new PictureBox();
picturebox.Height = 100;
picturebox.Width = 100;
picturebox.Image = image;
picturebox.BorderStyle = BorderStyle.None;
picturebox.SizeMode = PictureBoxSizeMode.StretchImage;
flowLayoutPanel1.Controls.Add(picturebox);
Button button = new Button();
button.Text = listnumber.ToString() + " " + result.Snippet.Title.ToString();
button.Tag = result.Id.VideoId;
button.TextImageRelation = TextImageRelation.ImageBeforeText;
button.FlatStyle = FlatStyle.Flat;
button.ForeColor = Color.LightSteelBlue;
button.BackColor = Color.SteelBlue;
button.Width = (flowLayoutPanel1.Width - 150);
button.TextAlign = ContentAlignment.MiddleLeft;
button.Height = 100;
button.Font = new Font(button.Font.FontFamily, 10);
button.Click += (s, e) =>
{
Youtube_video_Player_hider.Visible = false;
var a = result.Id.VideoId;
string template = "https://www.youtube.com/v/{0}{1}";
string data = a.ToString();
string quality = Video_Quality;
string messagea = string.Format(template, data, quality);
axShockwaveFlash1.Movie = messagea;
axShockwaveFlash1.Play();
};
flowLayoutPanel1.Controls.Add(button);
});
break;
}
nextPageToken = resp.NextPageToken;
this.Invoke(() =>
{
toolStripStatusLabel1.Text = "Status : Idle";
toolStripStatusLabel2.Text = "Results : " + video_results_vids;
});
});
}));
}
Class Contents :
using System;
using System.Windows.Forms;
namespace ExtensionMethods
{
public static class MyExtensions
{
public static void Invoke(this Control control, Action action)
{
control.Invoke((Delegate)action);
}
}
}
You should execute the 'whole' method on a thread. Try to move all creation of controls to one section and invoke that part on the GUI thread. The most consuming time will be the WebRequests
PSEUDO: something like:
private void Search_Video_Youtube(string page)
{
ThreadPool.QueueUserWorkItem(new WaitCallback((state) =>
{
YouTubeService youtube = new YouTubeService(new BaseClientService.Initializer()
{
ApplicationName = this.GetType().ToString(),
ApiKey = "*MyApiKeyGoesHere*",
});
var listRequest = youtube.Search.List("snippet");
listRequest.Q = Youtube_SearchVideo_Box.Text;
listRequest.MaxResults = 50;
listRequest.Type = "video";
listRequest.PageToken = nextPageToken;
video_results_vids = video_results_vids + 50;
var resp = listRequest.Execute().OfType<SearchResult>();
List<string> videos = new List<string>();
Parallel.Foreach(resp.Items, (result) =>
{
switch (result.Id.Kind)
{
case "youtube#video":
string template2 = "http://i3.ytimg.com/vi/{0}{1}";
string data2 = result.Id.VideoId.ToString();
string quality2 = "/default.jpg";
string messageB = string.Format(template2, data2, quality2);
Bitmap image;
var request = WebRequest.Create(messageB);
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
image = Bitmap.FromStream(stream);
}
listnumber += 1;
this.Invoke(() =>
{
PictureBox picturebox = new PictureBox();
picturebox.Height = 100;
picturebox.Width = 100;
picturebox.Image = image;
picturebox.BorderStyle = BorderStyle.None;
picturebox.SizeMode = PictureBoxSizeMode.StretchImage;
flowLayoutPanel1.Controls.Add(picturebox);
Button button = new Button();
button.Text = listnumber.ToString() + " " + result.Snippet.Title.ToString();
button.Tag = result.Id.VideoId;
button.TextImageRelation = TextImageRelation.ImageBeforeText;
button.FlatStyle = FlatStyle.Flat;
button.ForeColor = Color.LightSteelBlue;
button.BackColor = Color.SteelBlue;
button.Width = (flowLayoutPanel1.Width - 150);
button.TextAlign = ContentAlignment.MiddleLeft;
button.Height = 100;
button.Font = new Font(button.Font.FontFamily, 10);
button.Click += (s, e) => {
Youtube_video_Player_hider.Visible = false;
var a = result.Id.VideoId;
string template = "https://www.youtube.com/v/{0}{1}";
string data = a.ToString();
string quality = Video_Quality;
string messagea = string.Format(template, data, quality);
axShockwaveFlash1.Movie = messagea;
axShockwaveFlash1.Play();
};
flowLayoutPanel1.Controls.Add(button);
});
break;
}
nextPageToken = resp.NextPageToken;
this.Invoke(() =>
{
toolStripStatusLabel1.Text = "Status : Idle";
toolStripStatusLabel2.Text = "Results : " + video_results_vids;
});
}, null);
}
Create a delegate that takes argument of type of resp
public delegate void ListDispatcher(var resp)
remember, var needs to be replaced with the exact type of the resp.
Now create a ListDispatcher reference member in the main class.
public ListDispatcher dispatcher;
and add a new method to its invocation list.
dispatcher += MyNewMethod;
Define the new method as
public void MyNewMethod(var resp){
//Move all your controls creation code here
}
Remove the code after the call
var resp = listRequest.Execute();
and simply put there
dispatcher(resp);
Now you can safely call the Search_Video_Youtube(string page) in a separate thread.
Related
I'm using Infragistics UltraChart controls for displaying graphs. (Version 19.1)
My line chart graph is as below
Here Y-axis is noting but milliseconds(turn around time of Int64 type), I want to display it like "days:hh:mm:ss" format. Is it possible to display Y- axis lables in this format? while X axis is showing list of sample names (Which is of string type) The Ultra line chart data binding code is as below
ultraChartTAT.Data.DataSource = dsTAT.Tables["dtTAT"];
ultraChartTAT.Data.DataBind();
Here ultraChartTAT is an UltraChart infragistic control and dsTAT is a DataSet. The dsTAT.Tables["dtTAT"] design structure is as below
DataTable dtTAT = new DataTable("dtTAT");
dtTAT.Columns.Add("TAT", typeof(string));
dtTAT.Columns.Add("Sample1", typeof(Int64));
dtTAT.Columns.Add("Sample2", typeof(Int64));
dtTAT.Columns.Add("Sample3", typeof(Int64));
dtTAT.Columns.Add("Sample4", typeof(Int64));
dtTAT.Columns.Add("Sample5", typeof(Int64));
dtTAT.Columns.Add("Sample6", typeof(Int64));
dtTAT.Columns.Add("Sample7", typeof(Int64));
dtTAT.Columns.Add("Sample8", typeof(Int64));
For more reference take a look on this link https://stackoverflow.com/a/36329469/4524485
In case if any other information is required then add it in comment I'll update my question accordingly.
To format data for the X/Y axis labels the IRenderLabel interface can be used.
In example below the DateTimeRenderer class is using the IRenderLabel interface implementation to display Y-axis labels in the DateTime format:
For additional information see the Infragistics documentation:
http://help.infragistics.com/Help/Doc/WinForms/2011.1/CLR2.0/html/Chart_Customize_Labels_Using_the_IRenderLabel_Interface.html
DateTimeRenderer.cs
using Infragistics.UltraChart.Resources;
using System;
using System.Collections;
using System.Data;
namespace UltraGrid
{
public class DateTimeRenderer : IRenderLabel
{
readonly DataTable source;
public DateTimeRenderer(DataTable dt)
{
source = dt;
}
public string ToString(Hashtable context)
{
double dataValue = (double)context["DATA_VALUE"];
var dt = new DateTime((long)dataValue);
return dt.ToString("MM/dd/yyyy HH:mm:ss");
}
}
}
Form1.cs
using System;
using System.Collections;
using System.Data;
using System.Windows.Forms;
namespace UltraGrid
{
public partial class Form1 : Form
{
DataTable table = new DataTable("Statistics");
public Form1()
{
InitializeComponent();
// Create columns to hold sample data.
var column1 = new DataColumn("Sample", typeof(string));
var column2 = new DataColumn("Line1", typeof(Int64));
var column3 = new DataColumn("Line2", typeof(Int64));
var column4 = new DataColumn("Line3", typeof(Int64));
table.Columns.AddRange(new DataColumn[] { column1, column2, column3, column4 });
var now = DateTime.Now.Ticks;
var rnd = new Random();
for (int i = 1; i < 20; i++)
{
table.Rows.Add(new object[] { "Sample" + i.ToString(), now + rnd.Next(999, 3600000)*1000, now + rnd.Next(999, 3600000)*1000, now + rnd.Next(999, 3600000)*1000 });
}
}
private void LineChartStyles_Load(object sender, System.EventArgs e)
{
this.ultraChart1.Data.DataSource = table;
ultraChart1.Axis.Y.Labels.ItemFormatString = "<MY_VALUE>";
ultraChart1.Tooltips.FormatString = "<MY_VALUE>";
var MyLabelHashTable = new Hashtable { { "MY_VALUE", new DateTimeRenderer(table) } };
this.ultraChart1.LabelHash = MyLabelHashTable;
this.ultraChart1.Data.DataBind();
}
}
}
Form1.Designer.cs
namespace UltraGrid
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
Infragistics.UltraChart.Resources.Appearance.PaintElement paintElement1 = new Infragistics.UltraChart.Resources.Appearance.PaintElement();
Infragistics.UltraChart.Resources.Appearance.PaintElement paintElement2 = new Infragistics.UltraChart.Resources.Appearance.PaintElement();
Infragistics.UltraChart.Resources.Appearance.PaintElement paintElement3 = new Infragistics.UltraChart.Resources.Appearance.PaintElement();
Infragistics.UltraChart.Resources.Appearance.PaintElement paintElement4 = new Infragistics.UltraChart.Resources.Appearance.PaintElement();
Infragistics.UltraChart.Resources.Appearance.PaintElement paintElement5 = new Infragistics.UltraChart.Resources.Appearance.PaintElement();
Infragistics.UltraChart.Resources.Appearance.PaintElement paintElement6 = new Infragistics.UltraChart.Resources.Appearance.PaintElement();
Infragistics.UltraChart.Resources.Appearance.LineChartAppearance lineChartAppearance1 = new Infragistics.UltraChart.Resources.Appearance.LineChartAppearance();
Infragistics.UltraChart.Resources.Appearance.LineAppearance lineAppearance1 = new Infragistics.UltraChart.Resources.Appearance.LineAppearance() { Thickness = 3 };
Infragistics.UltraChart.Resources.Appearance.PaintElement paintElement7 = new Infragistics.UltraChart.Resources.Appearance.PaintElement();
Infragistics.UltraChart.Resources.Appearance.LineAppearance lineAppearance2 = new Infragistics.UltraChart.Resources.Appearance.LineAppearance() { Thickness = 3 };
Infragistics.UltraChart.Resources.Appearance.PaintElement paintElement8 = new Infragistics.UltraChart.Resources.Appearance.PaintElement();
Infragistics.UltraChart.Resources.Appearance.LineAppearance lineAppearance3 = new Infragistics.UltraChart.Resources.Appearance.LineAppearance() { Thickness = 3 };
Infragistics.UltraChart.Resources.Appearance.PaintElement paintElement9 = new Infragistics.UltraChart.Resources.Appearance.PaintElement();
this.ultraChart1 = new Infragistics.Win.UltraWinChart.UltraChart();
((System.ComponentModel.ISupportInitialize)(this.ultraChart1)).BeginInit();
this.SuspendLayout();
this.ultraChart1.ChartType = Infragistics.UltraChart.Shared.Styles.ChartType.LineChart;
//
// ultraChart1
//
resources.ApplyResources(this.ultraChart1, "ultraChart1");
this.ultraChart1.Axis.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(248)))), ((int)(((byte)(220)))));
paintElement1.ElementType = Infragistics.UltraChart.Shared.Styles.PaintElementType.None;
paintElement1.Fill = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(248)))), ((int)(((byte)(220)))));
this.ultraChart1.Axis.PE = paintElement1;
this.ultraChart1.Axis.X.Labels.Font = new System.Drawing.Font("Verdana", 7F);
this.ultraChart1.Axis.X.Labels.HorizontalAlign = System.Drawing.StringAlignment.Near;
this.ultraChart1.Axis.X.Labels.ItemFormatString = "<ITEM_LABEL>";
this.ultraChart1.Axis.X.Labels.Orientation = Infragistics.UltraChart.Shared.Styles.TextOrientation.VerticalLeftFacing;
this.ultraChart1.Axis.X.Labels.SeriesLabels.Font = new System.Drawing.Font("Verdana", 7F);
this.ultraChart1.Axis.X.Labels.SeriesLabels.FormatString = "";
this.ultraChart1.Axis.X.Labels.SeriesLabels.HorizontalAlign = System.Drawing.StringAlignment.Near;
this.ultraChart1.Axis.X.Labels.SeriesLabels.Orientation = Infragistics.UltraChart.Shared.Styles.TextOrientation.VerticalLeftFacing;
this.ultraChart1.Axis.X.Labels.SeriesLabels.VerticalAlign = System.Drawing.StringAlignment.Center;
this.ultraChart1.Axis.X.Labels.SeriesLabels.Visible = true;
this.ultraChart1.Axis.X.Labels.VerticalAlign = System.Drawing.StringAlignment.Center;
this.ultraChart1.Axis.X.Labels.Visible = true;
this.ultraChart1.Axis.X.LineThickness = 1;
this.ultraChart1.Axis.X.MajorGridLines.AlphaLevel = ((byte)(255));
this.ultraChart1.Axis.X.MajorGridLines.Color = System.Drawing.Color.Gainsboro;
this.ultraChart1.Axis.X.MajorGridLines.DrawStyle = Infragistics.UltraChart.Shared.Styles.LineDrawStyle.Dot;
this.ultraChart1.Axis.X.MajorGridLines.Visible = true;
this.ultraChart1.Axis.X.MinorGridLines.AlphaLevel = ((byte)(255));
this.ultraChart1.Axis.X.MinorGridLines.Color = System.Drawing.Color.LightGray;
this.ultraChart1.Axis.X.MinorGridLines.DrawStyle = Infragistics.UltraChart.Shared.Styles.LineDrawStyle.Dot;
this.ultraChart1.Axis.X.MinorGridLines.Visible = false;
this.ultraChart1.Axis.X.Visible = true;
this.ultraChart1.Axis.X2.Labels.Font = new System.Drawing.Font("Verdana", 7F);
this.ultraChart1.Axis.X2.Labels.HorizontalAlign = System.Drawing.StringAlignment.Far;
this.ultraChart1.Axis.X2.Labels.ItemFormatString = "<ITEM_LABEL>";
this.ultraChart1.Axis.X2.Labels.Orientation = Infragistics.UltraChart.Shared.Styles.TextOrientation.VerticalLeftFacing;
this.ultraChart1.Axis.X2.Labels.SeriesLabels.FormatString = "";
this.ultraChart1.Axis.X2.Labels.SeriesLabels.HorizontalAlign = System.Drawing.StringAlignment.Far;
this.ultraChart1.Axis.X2.Labels.SeriesLabels.Orientation = Infragistics.UltraChart.Shared.Styles.TextOrientation.VerticalLeftFacing;
this.ultraChart1.Axis.X2.Labels.SeriesLabels.VerticalAlign = System.Drawing.StringAlignment.Center;
this.ultraChart1.Axis.X2.Labels.SeriesLabels.Visible = true;
this.ultraChart1.Axis.X2.Labels.VerticalAlign = System.Drawing.StringAlignment.Center;
this.ultraChart1.Axis.X2.Labels.Visible = false;
this.ultraChart1.Axis.X2.MajorGridLines.AlphaLevel = ((byte)(255));
this.ultraChart1.Axis.X2.MajorGridLines.Color = System.Drawing.Color.Gainsboro;
this.ultraChart1.Axis.X2.MajorGridLines.DrawStyle = Infragistics.UltraChart.Shared.Styles.LineDrawStyle.Dot;
this.ultraChart1.Axis.X2.MajorGridLines.Visible = true;
this.ultraChart1.Axis.X2.MinorGridLines.AlphaLevel = ((byte)(255));
this.ultraChart1.Axis.X2.MinorGridLines.Color = System.Drawing.Color.LightGray;
this.ultraChart1.Axis.X2.MinorGridLines.DrawStyle = Infragistics.UltraChart.Shared.Styles.LineDrawStyle.Dot;
this.ultraChart1.Axis.X2.MinorGridLines.Visible = false;
this.ultraChart1.Axis.X2.Visible = false;
this.ultraChart1.Axis.Y.Extent = 110;
this.ultraChart1.Axis.Y.Labels.Font = new System.Drawing.Font("Verdana", 7F);
this.ultraChart1.Axis.Y.Labels.HorizontalAlign = System.Drawing.StringAlignment.Far;
this.ultraChart1.Axis.Y.Labels.ItemFormatString = "<DATA_VALUE:00.##>";
this.ultraChart1.Axis.Y.Labels.Orientation = Infragistics.UltraChart.Shared.Styles.TextOrientation.Horizontal;
this.ultraChart1.Axis.Y.Labels.SeriesLabels.FormatString = "";
this.ultraChart1.Axis.Y.Labels.SeriesLabels.HorizontalAlign = System.Drawing.StringAlignment.Far;
this.ultraChart1.Axis.Y.Labels.SeriesLabels.Orientation = Infragistics.UltraChart.Shared.Styles.TextOrientation.Horizontal;
this.ultraChart1.Axis.Y.Labels.SeriesLabels.VerticalAlign = System.Drawing.StringAlignment.Center;
this.ultraChart1.Axis.Y.Labels.SeriesLabels.Visible = true;
this.ultraChart1.Axis.Y.Labels.VerticalAlign = System.Drawing.StringAlignment.Center;
this.ultraChart1.Axis.Y.Labels.Visible = true;
this.ultraChart1.Axis.Y.LineThickness = 1;
this.ultraChart1.Axis.Y.MajorGridLines.AlphaLevel = ((byte)(255));
this.ultraChart1.Axis.Y.MajorGridLines.Color = System.Drawing.Color.Gainsboro;
this.ultraChart1.Axis.Y.MajorGridLines.DrawStyle = Infragistics.UltraChart.Shared.Styles.LineDrawStyle.Dot;
this.ultraChart1.Axis.Y.MajorGridLines.Visible = true;
this.ultraChart1.Axis.Y.MinorGridLines.AlphaLevel = ((byte)(255));
this.ultraChart1.Axis.Y.MinorGridLines.Color = System.Drawing.Color.LightGray;
this.ultraChart1.Axis.Y.MinorGridLines.DrawStyle = Infragistics.UltraChart.Shared.Styles.LineDrawStyle.Dot;
this.ultraChart1.Axis.Y.MinorGridLines.Visible = false;
this.ultraChart1.Axis.Y.TickmarkInterval = 50D;
this.ultraChart1.Axis.Y.TickmarkStyle = Infragistics.UltraChart.Shared.Styles.AxisTickStyle.Smart;
this.ultraChart1.Axis.Y.Visible = true;
this.ultraChart1.Axis.Y2.Labels.Font = new System.Drawing.Font("Verdana", 7F);
this.ultraChart1.Axis.Y2.Labels.HorizontalAlign = System.Drawing.StringAlignment.Near;
this.ultraChart1.Axis.Y2.Labels.ItemFormatString = "<DATA_VALUE:00.##>";
this.ultraChart1.Axis.Y2.Labels.Orientation = Infragistics.UltraChart.Shared.Styles.TextOrientation.Horizontal;
this.ultraChart1.Axis.Y2.Labels.SeriesLabels.FormatString = "";
this.ultraChart1.Axis.Y2.Labels.SeriesLabels.HorizontalAlign = System.Drawing.StringAlignment.Near;
this.ultraChart1.Axis.Y2.Labels.SeriesLabels.Orientation = Infragistics.UltraChart.Shared.Styles.TextOrientation.Horizontal;
this.ultraChart1.Axis.Y2.Labels.SeriesLabels.VerticalAlign = System.Drawing.StringAlignment.Center;
this.ultraChart1.Axis.Y2.Labels.SeriesLabels.Visible = true;
this.ultraChart1.Axis.Y2.Labels.VerticalAlign = System.Drawing.StringAlignment.Center;
this.ultraChart1.Axis.Y2.Labels.Visible = false;
this.ultraChart1.Axis.Y2.MajorGridLines.AlphaLevel = ((byte)(255));
this.ultraChart1.Axis.Y2.MajorGridLines.Color = System.Drawing.Color.Gainsboro;
this.ultraChart1.Axis.Y2.MajorGridLines.DrawStyle = Infragistics.UltraChart.Shared.Styles.LineDrawStyle.Dot;
this.ultraChart1.Axis.Y2.MajorGridLines.Visible = true;
this.ultraChart1.Axis.Y2.MinorGridLines.AlphaLevel = ((byte)(255));
this.ultraChart1.Axis.Y2.MinorGridLines.Color = System.Drawing.Color.LightGray;
this.ultraChart1.Axis.Y2.MinorGridLines.DrawStyle = Infragistics.UltraChart.Shared.Styles.LineDrawStyle.Dot;
this.ultraChart1.Axis.Y2.MinorGridLines.Visible = false;
this.ultraChart1.Axis.Y2.Visible = false;
this.ultraChart1.Axis.Z.Labels.Font = new System.Drawing.Font("Verdana", 7F);
this.ultraChart1.Axis.Z.Labels.HorizontalAlign = System.Drawing.StringAlignment.Near;
this.ultraChart1.Axis.Z.Labels.ItemFormatString = "";
this.ultraChart1.Axis.Z.Labels.Orientation = Infragistics.UltraChart.Shared.Styles.TextOrientation.Horizontal;
this.ultraChart1.Axis.Z.Labels.SeriesLabels.HorizontalAlign = System.Drawing.StringAlignment.Near;
this.ultraChart1.Axis.Z.Labels.SeriesLabels.Orientation = Infragistics.UltraChart.Shared.Styles.TextOrientation.Horizontal;
this.ultraChart1.Axis.Z.Labels.SeriesLabels.VerticalAlign = System.Drawing.StringAlignment.Center;
this.ultraChart1.Axis.Z.Labels.SeriesLabels.Visible = true;
this.ultraChart1.Axis.Z.Labels.VerticalAlign = System.Drawing.StringAlignment.Center;
this.ultraChart1.Axis.Z.Labels.Visible = true;
this.ultraChart1.Axis.Z.MajorGridLines.AlphaLevel = ((byte)(255));
this.ultraChart1.Axis.Z.MajorGridLines.Color = System.Drawing.Color.Gainsboro;
this.ultraChart1.Axis.Z.MajorGridLines.DrawStyle = Infragistics.UltraChart.Shared.Styles.LineDrawStyle.Dot;
this.ultraChart1.Axis.Z.MajorGridLines.Visible = true;
this.ultraChart1.Axis.Z.MinorGridLines.AlphaLevel = ((byte)(255));
this.ultraChart1.Axis.Z.MinorGridLines.Color = System.Drawing.Color.LightGray;
this.ultraChart1.Axis.Z.MinorGridLines.DrawStyle = Infragistics.UltraChart.Shared.Styles.LineDrawStyle.Dot;
this.ultraChart1.Axis.Z.MinorGridLines.Visible = false;
this.ultraChart1.Axis.Z.Visible = false;
this.ultraChart1.Axis.Z2.Labels.Font = new System.Drawing.Font("Verdana", 7F);
this.ultraChart1.Axis.Z2.Labels.HorizontalAlign = System.Drawing.StringAlignment.Near;
this.ultraChart1.Axis.Z2.Labels.ItemFormatString = "";
this.ultraChart1.Axis.Z2.Labels.Orientation = Infragistics.UltraChart.Shared.Styles.TextOrientation.Horizontal;
this.ultraChart1.Axis.Z2.Labels.SeriesLabels.HorizontalAlign = System.Drawing.StringAlignment.Near;
this.ultraChart1.Axis.Z2.Labels.SeriesLabels.Orientation = Infragistics.UltraChart.Shared.Styles.TextOrientation.Horizontal;
this.ultraChart1.Axis.Z2.Labels.SeriesLabels.VerticalAlign = System.Drawing.StringAlignment.Center;
this.ultraChart1.Axis.Z2.Labels.SeriesLabels.Visible = true;
this.ultraChart1.Axis.Z2.Labels.VerticalAlign = System.Drawing.StringAlignment.Center;
this.ultraChart1.Axis.Z2.Labels.Visible = false;
this.ultraChart1.Axis.Z2.MajorGridLines.AlphaLevel = ((byte)(255));
this.ultraChart1.Axis.Z2.MajorGridLines.Color = System.Drawing.Color.Gainsboro;
this.ultraChart1.Axis.Z2.MajorGridLines.DrawStyle = Infragistics.UltraChart.Shared.Styles.LineDrawStyle.Dot;
this.ultraChart1.Axis.Z2.MajorGridLines.Visible = true;
this.ultraChart1.Axis.Z2.MinorGridLines.AlphaLevel = ((byte)(255));
this.ultraChart1.Axis.Z2.MinorGridLines.Color = System.Drawing.Color.LightGray;
this.ultraChart1.Axis.Z2.MinorGridLines.DrawStyle = Infragistics.UltraChart.Shared.Styles.LineDrawStyle.Dot;
this.ultraChart1.Axis.Z2.MinorGridLines.Visible = false;
this.ultraChart1.Axis.Z2.Visible = false;
this.ultraChart1.Border.CornerRadius = 5;
this.ultraChart1.ColorModel.AlphaLevel = ((byte)(150));
this.ultraChart1.ColorModel.ModelStyle = Infragistics.UltraChart.Shared.Styles.ColorModels.CustomLinear;
paintElement2.ElementType = Infragistics.UltraChart.Shared.Styles.PaintElementType.Gradient;
paintElement2.Fill = System.Drawing.Color.FromArgb(((int)(((byte)(108)))), ((int)(((byte)(162)))), ((int)(((byte)(36)))));
paintElement2.FillGradientStyle = Infragistics.UltraChart.Shared.Styles.GradientStyle.Horizontal;
paintElement2.FillStopColor = System.Drawing.Color.FromArgb(((int)(((byte)(148)))), ((int)(((byte)(244)))), ((int)(((byte)(17)))));
paintElement2.Stroke = System.Drawing.Color.Transparent;
paintElement3.ElementType = Infragistics.UltraChart.Shared.Styles.PaintElementType.Gradient;
paintElement3.Fill = System.Drawing.Color.FromArgb(((int)(((byte)(7)))), ((int)(((byte)(108)))), ((int)(((byte)(176)))));
paintElement3.FillGradientStyle = Infragistics.UltraChart.Shared.Styles.GradientStyle.Horizontal;
paintElement3.FillStopColor = System.Drawing.Color.FromArgb(((int)(((byte)(53)))), ((int)(((byte)(200)))), ((int)(((byte)(255)))));
paintElement3.Stroke = System.Drawing.Color.Transparent;
paintElement4.ElementType = Infragistics.UltraChart.Shared.Styles.PaintElementType.Gradient;
paintElement4.Fill = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(0)))), ((int)(((byte)(5)))));
paintElement4.FillGradientStyle = Infragistics.UltraChart.Shared.Styles.GradientStyle.Horizontal;
paintElement4.FillStopColor = System.Drawing.Color.FromArgb(((int)(((byte)(254)))), ((int)(((byte)(117)))), ((int)(((byte)(16)))));
paintElement4.Stroke = System.Drawing.Color.Transparent;
paintElement5.ElementType = Infragistics.UltraChart.Shared.Styles.PaintElementType.Gradient;
paintElement5.Fill = System.Drawing.Color.FromArgb(((int)(((byte)(230)))), ((int)(((byte)(190)))), ((int)(((byte)(2)))));
paintElement5.FillGradientStyle = Infragistics.UltraChart.Shared.Styles.GradientStyle.Horizontal;
paintElement5.FillStopColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(81)))));
paintElement5.Stroke = System.Drawing.Color.Transparent;
paintElement6.ElementType = Infragistics.UltraChart.Shared.Styles.PaintElementType.Gradient;
paintElement6.Fill = System.Drawing.Color.FromArgb(((int)(((byte)(252)))), ((int)(((byte)(122)))), ((int)(((byte)(10)))));
paintElement6.FillGradientStyle = Infragistics.UltraChart.Shared.Styles.GradientStyle.Horizontal;
paintElement6.FillStopColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(208)))), ((int)(((byte)(66)))));
paintElement6.Stroke = System.Drawing.Color.Transparent;
this.ultraChart1.ColorModel.Skin.PEs.AddRange(new Infragistics.UltraChart.Resources.Appearance.PaintElement[] {
paintElement2,
paintElement3,
paintElement4,
paintElement5,
paintElement6});
this.ultraChart1.Data.EmptyStyle.LineStyle.DrawStyle = Infragistics.UltraChart.Shared.Styles.LineDrawStyle.Dash;
this.ultraChart1.Data.SwapRowsAndColumns = true;
this.ultraChart1.ForeColor = System.Drawing.SystemColors.ControlText;
this.ultraChart1.Legend.Font = new System.Drawing.Font("Verdana", 7F);
this.ultraChart1.Legend.Location = Infragistics.UltraChart.Shared.Styles.LegendLocation.Top;
this.ultraChart1.Legend.Visible = true;
lineAppearance1.IconAppearance.CharacterFont = new System.Drawing.Font("Microsoft Sans Serif", 12F);
paintElement7.ElementType = Infragistics.UltraChart.Shared.Styles.PaintElementType.None;
lineAppearance1.IconAppearance.PE = paintElement7;
lineAppearance1.Key = "Monday";
paintElement8.ElementType = Infragistics.UltraChart.Shared.Styles.PaintElementType.None;
lineAppearance2.IconAppearance.PE = paintElement8;
lineAppearance2.Key = "Tuesday";
lineAppearance2.LineStyle.DrawStyle = Infragistics.UltraChart.Shared.Styles.LineDrawStyle.Dash;
paintElement9.ElementType = Infragistics.UltraChart.Shared.Styles.PaintElementType.None;
lineAppearance3.IconAppearance.PE = paintElement9;
lineAppearance3.Key = "Wednesday";
lineAppearance3.LineStyle.DrawStyle = Infragistics.UltraChart.Shared.Styles.LineDrawStyle.Dot;
lineChartAppearance1.LineAppearances.Add(lineAppearance1);
lineChartAppearance1.LineAppearances.Add(lineAppearance2);
lineChartAppearance1.LineAppearances.Add(lineAppearance3);
this.ultraChart1.LineChart = lineChartAppearance1;
this.ultraChart1.Name = "ultraChart1";
this.ultraChart1.Tooltips.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F);
this.ultraChart1.Tooltips.HighlightFillColor = System.Drawing.Color.DimGray;
this.ultraChart1.Tooltips.HighlightOutlineColor = System.Drawing.Color.DarkGray;
//
// Form1
//
this.BackColor = System.Drawing.Color.White;
resources.ApplyResources(this, "$this");
this.Controls.Add(this.ultraChart1);
this.Name = "Form1";
this.Load += new System.EventHandler(this.LineChartStyles_Load);
((System.ComponentModel.ISupportInitialize)(this.ultraChart1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private Infragistics.Win.UltraWinChart.UltraChart ultraChart1;
}
}
I'm trying to make weather application. And when I input new city in my combobox,my labels and pictureboxes don't refresh. I have already tried Refresh() Update() and Invalidate() and none of them worked. Tell me please ,what I'm suppose to do. Thank you in advance!
private async void SetWeatherForecastDataToWeatherApp(string city)
{
try
{
var jsonData = string.Empty;
var url = string.Format("http://api.openweathermap.org/data/2.5/forecast?q={0}&APPID=a54961a05f7a1fc0cf9bd2bf1465dea5", city);
var uri = new Uri(url);
var request = WebRequest.Create(uri);
var response = await request.GetResponseAsync();
using (var stream = response.GetResponseStream())
{
using (var streamReader = new StreamReader(stream))
{
jsonData = await streamReader.ReadToEndAsync();
}
}
response.Close();
_jsonFutureWeatherForecastData = jsonData;
_weatherForecast = JsonConvert.DeserializeObject<WeatherForecast>(_jsonFutureWeatherForecastData);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Input Error", MessageBoxButtons.OK);
}
var dayNameLabelList = new List<Label>();
var weatherDescriptionLablList = new List<Label>();
var gradesLabel = new List<Label>();
var pictureBoxList = new List<PictureBox>();
int yLocation = 50;
int xLocation = Width / 2;
int cnt = 0;
string currDayOfWeek = string.Empty;
string CurrentDate = string.Empty;
for (int i = 0; i < 9; i++)
{
currDayOfWeek = _dateConverter.ConvertMilisecondsToCurrentTime(_weatherForecast.WeatherList[i].CurrentDate).DayOfWeek.ToString();
CurrentDate = _dateConverter.ConvertMilisecondsToCurrentTime(_weatherForecast.WeatherList[i].CurrentDate).Day.ToString();
cnt++;
pictureBoxList.Add(new PictureBox());
pictureBoxList[i].Name = "WeatherForecastImage" + cnt.ToString();
pictureBoxList[i].Location = new Point(xLocation, yLocation);
pictureBoxList[i].Load($"Icons/{_weatherForecast.WeatherList[i].Weather[0].Icon}.png");
Controls.Add(pictureBoxList[i]);
pictureBoxList[i].Invalidate();
dayNameLabelList.Add(new Label());
dayNameLabelList[i].Text = currDayOfWeek + " " + CurrentDate;
dayNameLabelList[i].Location = new Point(xLocation + 100, yLocation);
dayNameLabelList[i].Size = new Size(100, 15);
dayNameLabelList[i].Font = new Font("Lucida Sans", 10, FontStyle.Regular);
Controls.Add(dayNameLabelList[i]);
weatherDescriptionLablList.Add(new Label());
weatherDescriptionLablList[i].Text = _weatherForecast.WeatherList[i].Weather[0].Description;
weatherDescriptionLablList[i].Location = new Point(xLocation + 100, yLocation + 15);
weatherDescriptionLablList[i].Font = new Font("Lucida Sans", 8, FontStyle.Regular);
Controls.Add(weatherDescriptionLablList[i]);
gradesLabel.Add(new Label());
gradesLabel[i].Text = _weatherForecast.WeatherList[i].Main.Temperature.ToString("0") + " C°";
gradesLabel[i].Location = new Point(xLocation + 200, yLocation);
gradesLabel[i].Font = new Font("Lucida Sans", 10, FontStyle.Regular);
Controls.Add(gradesLabel[i]);
yLocation += 100;
}
for (int i = 0; i < dayNameLabelList.Count; i++)
{
dayNameLabelList[i].ForeColor = Color.White;
weatherDescriptionLablList[i].ForeColor = Color.White;
gradesLabel[i].ForeColor = Color.White;
}
}
You need to add event handlers to the combo for either SelectedIndexChangedEvent (if it's a non-editable combo), or TextUpdateEvent if it is (likely both in that latter case). Those event handlers then change the other controls as needed.
I'm building an android app with Xamarin which communicates with an ASP.net server's API. I'm trying to upload a file to the server using the following lines of code:
public async Task<HttpResponseMessage> UploadFile(byte[] file)
{
var progress = new System.Net.Http.Handlers.ProgressMessageHandler();
//progress.HttpSendProgress += progress_HttpSendProgress;
using (var client = HttpClientFactory.Create(progress))
{
client.BaseAddress = new Uri(GlobalVariables.host);
// Set the Accept header for BSON.
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/bson"));
var request = new uploadFileModel { data = file, dateCreated = DateTime.Now, fileName = "myvideooo.mp4", username = "psyoptica" };
// POST using the BSON formatter.
MediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
var m = client.MaxResponseContentBufferSize;
var result = await client.PostAsync("api/media/upload", request, bsonFormatter);
return result.EnsureSuccessStatusCode();
}
}
The app crashes before the server receives the request. The file I'm trying to upload could be a video or an audio file. The server receives the request after the app has crashed. This works fine on the local server but the crash happens with the live server. My server side code looks like this:
[HttpPost]
[Route("upload")]
public async Task<HttpResponseMessage> Upload(uploadFileModel model)
{
var result = new HttpResponseMessage(HttpStatusCode.OK);
if (ModelState.IsValid)
{
string thumbname = "";
string resizedthumbname = Guid.NewGuid() + "_yt.jpg";
string FfmpegPath = Encoding_Settings.FFMPEGPATH;
string tempFilePath = Path.Combine(HttpContext.Current.Server.MapPath("~/tempuploads"), model.fileName);
string pathToFiles = HttpContext.Current.Server.MapPath("~/tempuploads");
string pathToThumbs = HttpContext.Current.Server.MapPath("~/contents/member/" + model.username + "/thumbs");
string finalPath = HttpContext.Current.Server.MapPath("~/contents/member/" + model.username + "/flv");
string resizedthumb = Path.Combine(pathToThumbs, resizedthumbname);
var outputPathVid = new MediaFile { Filename = Path.Combine(finalPath, model.fileName) };
var inputPathVid = new MediaFile { Filename = Path.Combine(pathToFiles, model.fileName) };
int maxWidth = 380;
int maxHeight = 360;
var namewithoutext = Path.GetFileNameWithoutExtension(Path.Combine(pathToFiles, model.fileName));
thumbname = model.VideoThumbName;
string oldthumbpath = Path.Combine(pathToThumbs, thumbname);
var fileName = model.fileName;
File.WriteAllBytes(tempFilePath, model.data);
if (model.fileName.Contains("audio"))
{
File.WriteAllBytes(Path.Combine(finalPath, model.fileName), model.data);
string audio_thumb = "mic_thumb.jpg";
string destination = Path.Combine(pathToThumbs, audio_thumb);
string source = Path.Combine(pathToFiles, audio_thumb);
if (!System.IO.File.Exists(destination))
{
System.IO.File.Copy(source, destination, true);
}
Video_Struct vd = new Video_Struct();
vd.CategoryID = 0; // store categoryname or term instead of category id
vd.Categories = "";
vd.UserName = model.username;
vd.Title = "";
vd.Description = "";
vd.Tags = "";
vd.OriginalVideoFileName = model.fileName;
vd.VideoFileName = model.fileName;
vd.ThumbFileName = "mic_thumb.jpg";
vd.isPrivate = 0;
vd.AuthKey = "";
vd.isEnabled = 1;
vd.Response_VideoID = 0; // video responses
vd.isResponse = 0;
vd.isPublished = 1;
vd.isReviewed = 1;
vd.Thumb_Url = "none";
//vd.FLV_Url = flv_url;
vd.Embed_Script = "";
vd.isExternal = 0; // website own video, 1: embed video
vd.Type = 0;
vd.YoutubeID = "";
vd.isTagsreViewed = 1;
vd.Mode = 0; // filter videos based on website sections
long videoid = VideoBLL.Process_Info(vd, false);
}
else
{
using (var engine = new Engine())
{
engine.GetMetadata(inputPathVid);
// Saves the frame located on the 15th second of the video.
var outputPathThumb = new MediaFile { Filename = Path.Combine(pathToThumbs, thumbname+".jpg") };
var options = new ConversionOptions { Seek = TimeSpan.FromSeconds(0), CustomHeight = 360, CustomWidth = 380 };
engine.GetThumbnail(inputPathVid, outputPathThumb, options);
}
Image image = Image.FromFile(Path.Combine(pathToThumbs, thumbname+".jpg"));
//var ratioX = (double)maxWidth / image.Width;
//var ratioY = (double)maxHeight / image.Height;
//var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(maxWidth);
var newHeight = (int)(maxHeight);
var newImage = new Bitmap(newWidth, newHeight);
Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
Bitmap bmp = new Bitmap(newImage);
bmp.Save(Path.Combine(pathToThumbs, thumbname+"_resized.jpg"));
//File.Delete(Path.Combine(pathToThumbs, thumbname));
using (var engine = new Engine())
{
var conversionOptions = new ConversionOptions
{
VideoSize = VideoSize.Hd720,
AudioSampleRate = AudioSampleRate.Hz44100,
VideoAspectRatio = VideoAspectRatio.Default
};
engine.GetMetadata(inputPathVid);
engine.Convert(inputPathVid, outputPathVid, conversionOptions);
}
File.Delete(tempFilePath);
Video_Struct vd = new Video_Struct();
vd.CategoryID = 0; // store categoryname or term instead of category id
vd.Categories = "";
vd.UserName = model.username;
vd.Title = "";
vd.Description = "";
vd.Tags = "";
vd.Duration = inputPathVid.Metadata.Duration.ToString();
vd.Duration_Sec = Convert.ToInt32(inputPathVid.Metadata.Duration.Seconds.ToString());
vd.OriginalVideoFileName = model.fileName;
vd.VideoFileName = model.fileName;
vd.ThumbFileName = thumbname+"_resized.jpg";
vd.isPrivate = 0;
vd.AuthKey = "";
vd.isEnabled = 1;
vd.Response_VideoID = 0; // video responses
vd.isResponse = 0;
vd.isPublished = 1;
vd.isReviewed = 1;
vd.Thumb_Url = "none";
//vd.FLV_Url = flv_url;
vd.Embed_Script = "";
vd.isExternal = 0; // website own video, 1: embed video
vd.Type = 0;
vd.YoutubeID = "";
vd.isTagsreViewed = 1;
vd.Mode = 0; // filter videos based on website sections
//vd.ContentLength = f_contentlength;
vd.GalleryID = 0;
long videoid = VideoBLL.Process_Info(vd, false);
}
return result;
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
}
}`
What am I doing wrong here that's making the app crash. Is there a better way to do this?
Any help is appreciated.
In my mobile app (iOS) I have FormatException in this code:
public partial class DetailTovarProsmotr : UIViewController
{
public JsonValue myjsondetail;
int count_product;
float price_defoult;
public string Code1;
public DetailTovarProsmotr (IntPtr handle) : base (handle)
{
}
public async Task<UIImage> LoadImage (string imageUrl)
{
var httpClient = new HttpClient();
Task<byte[]> contentsTask = httpClient.GetByteArrayAsync (imageUrl);
// await! control returns to the caller and the task continues to run on another thread
var contents = await contentsTask;
// load from bytes
return UIImage.LoadFromData (NSData.FromArray (contents));
}
public async override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Console.Out.WriteLine (detailtitle+" ViewDidLoad metod is run" + myjsondetail["ID"].ToString());
Code1 = myjsondetail ["sku"];
titleproduct001.Text = myjsondetail["post_title"];
postSingleProduct.Text = myjsondetail["post_excerpt"];
Weight001.Text = myjsondetail["weight"]+" г";
price001.Text = myjsondetail["price"]+" грн";
postImage.Image =await this.LoadImage (myjsondetail["img_url"]);
count_product = 1;
countproduct.Text = "1";
//float price_defoult = float.Parse(price001.Text, CultureInfo.InvariantCulture) ;
price_defoult = float.Parse( ((string)myjsondetail["price"]).Replace(".00", ".0") );
plus.TouchUpInside += (o,s) => {
//Console.Out.WriteLine("Нажали плюс!!!!");
countproduct.Text = string.Format("{0}", ++count_product);
price001.Text = string.Format("{0}", count_product*price_defoult + "грн");
};
mines.TouchUpInside += (o,s) => {
// Console.Out.WriteLine("Нажали минусссс!!!!");
countproduct.Text = string.Format("{0}", count_product > 1 ? --count_product : 1);
price001.Text = string.Format("{0}", count_product * price_defoult + "грн");
};
addToCart.TouchUpInside += (o,s) => {
var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
var filePath = Path.Combine (documents, "myFile.xml");
Console.Out.WriteLine("Добавить в корзину!!!!!");
Console.Out.WriteLine(countproduct.Text);
//MessageBarStyleSheet styles = new MessageBarStyleSheet ();
//UIColor colorb = UIColor.Black;
//styles.BackgroundColorForMessageType(MessageType.Info).GetWhite;
// style.BackgroundColorForMessageType = UIColor.Black;
MessageBarManager.SharedInstance.ShowMessage ("Товар добавлен ", "в корзину", MessageType.Info);
//Posrednic singleprod = new Posrednic(myjsondetail);
CartProduct cart = new CartProduct();
int productQty = int.Parse(countproduct.Text);
for (int i = 0; i< productQty; i++) {
cart.Add(myjsondetail.ToString());
}
CartProduct.PrintProducts(cart);
//singleprod.myjsondetail =myjsondetail;
XDocument doc = XDocument.Load(filePath);
var product = new XElement("Product", new XAttribute("Code", Code1), new XAttribute("Qty", countproduct.Text));
var products = doc.Descendants("Products").First(); // Get the first Products node. Throw an exception if not found.
products.Add(product);
File.WriteAllText(filePath, doc.ToString());
doc.Save (filePath);
Console.WriteLine("Smotri tut");
Console.WriteLine (doc.ToString());
};
}
}
I think my problem in this line
price_defoult = float.Parse( ((string)myjsondetail["price"]).Replace(".00", ".0") );
but I don't now where my problem. In simulator my code is working, but in iphone 5s I have:
FormatException Input string was not in a correct format. (mscorlib)
SIGABRT Crash in System_Runtime_CompilerServices_AsyncMethodBuilderCore__ThrowAsyncm__0_object
SIGABRT Crash in System_Xml_XmlTextReaderImpl_Read
I'm solved my problem:
delete line 6 float price_defoult;
in line price001.Text = myjsondetail["price"]+" грн"; deleting +" грн"
use this line float price_defoult = float.Parse(price001.Text, CultureInfo.InvariantCulture) for bringing type.
I have a default geocoordinate. Another geocoorinate which the user will provide. I want to change the change the map view such such that the source and destination can be clearly seen on the phone window with max zoom possible. Please help on how to approach this problem. I tried using setview() but i coudn't find an overload which could do the task.
public async void ShowMyLocationOnTheMap(string mapvariable)
{
JObject o = JObject.Parse(mapvariable);
string successcallback = o["successCallback"].ToString();
string failutecallback = o["failureCallback"].ToString();
var markerifo = o["markerInfo"];
int count = markerifo.Count();
try
{
for (int i = 0; i < count; i++)
{
drawmap(markerifo[i],"red");
}
Geolocator myGeolocator = new Geolocator();
Geoposition myGeoposition = await myGeolocator.GetGeopositionAsync();
JObject current = new JObject();
current["locationLatitude"] = myGeoposition.Coordinate.Latitude.ToString();
current["locationLongitude"] = myGeoposition.Coordinate.Longitude.ToString();
current["locationDescription"] = "Your Current Location";
current["locationName"] = "";
drawmap(current,"blue");
GeoCoordinate myGeoCoordinate = new GeoCoordinate(myGeoposition.Coordinate.Latitude, myGeoposition.Coordinate.Longitude);
MapAppzillon.SetView(myGeoCoordinate1,6);
gobject.ContentPanel.Children.Add(MapAppzillon);
var jsonstring = "{\"successMessage\":\" Map Displayed \"}";
string[] param = { successcallback, jsonstring };
gobject.invokeScript("StringToJsonObject", param);
}
catch (Exception ex)
{
var jsonstring = "{\"errorCode\":\"APZ-CNT-107\"}";
string[] param = { failutecallback, jsonstring };
gobject.invokeScript("StringToJsonObject", param);
}
}
public void drawmap(JToken markerifo,string color)
{
double latitude = Convert.ToDouble(markerifo["locationLatitude"].ToString());
double longitude = Convert.ToDouble(markerifo["locationLongitude"].ToString());
myGeoCoordinate1 = new GeoCoordinate(latitude, longitude);
Ellipse myCircle = new Ellipse();
if (color == "red")
{
myCircle.Fill = new SolidColorBrush(Colors.Red);
}
else
myCircle.Fill = new SolidColorBrush(Colors.Blue);
myCircle.Height = 20;
myCircle.Width = 20;
myCircle.Opacity = 50;
myCircle.Tap += (sender, e) => myCircle_Tap(sender, markerifo["locationDescription"].ToString(), markerifo["locationName"].ToString());
// myCircle.Tap += myCircle_Tap;
MapOverlay myLocationOverlay = new MapOverlay();
myLocationOverlay.Content = myCircle;
myLocationOverlay.PositionOrigin = new System.Windows.Point(0.5, 0.5);
myLocationOverlay.GeoCoordinate = myGeoCoordinate1;
MapLayer myLocationLayer = new MapLayer();
myLocationLayer.Add(myLocationOverlay);
MapAppzillon.Layers.Add(myLocationLayer);
}
Edit: I tried using dispatcher.Invoke and it finally worked. but now its loading only once . when i press the back button and specify another geocoordinate setview dosent work. Is there any solution to this.
List<GeoCoordinate> the2Points = new List<GeoCoordinate>();
the2Points.Add(myGeoCoordinate1);
the2Points.Add(myGeoCoordinate);
rect = LocationRectangle.CreateBoundingRectangle(the2Points);
gobject.ContentPanel.Children.Add(MapAppzillon);
MapAppzillon.Dispatcher.BeginInvoke(() =>
{
MapAppzillon.SetView(rect);
});
await Task.Delay(150);
You do need to use the SetView method on the Map control. But it needs a BoundingRectangle to work!
So a quick code snippet:
List<GeoCoordinate> the2Points = new List<GeoCoordinate>();
the2Points.Add(point1);
the2Points.Add(point2);
LocationRectangle rect = LocationRectangle.CreateBoundingRectangle(the2Points);
TheMapControl.SetView(rect);