Cant write any data into my SQLite database - c#

private void comboBox9_SelectedIndexChanged(object sender, EventArgs e)
{
finish_day = Convert.ToInt32(comboBox9.Text);
}
private void comboBox10_SelectedIndexChanged(object sender, EventArgs e)
{
finish_month = Convert.ToInt32(comboBox10.Text);
}
private void comboBox11_SelectedIndexChanged(object sender, EventArgs e)
{
finfish_year = Convert.ToInt32(comboBox11.Text);
}
private void comboBox6_SelectedIndexChanged(object sender, EventArgs e)
{
begin_year = Convert.ToInt32(comboBox6.Text);
}
private void comboBox7_SelectedIndexChanged(object sender, EventArgs e)
{
begin_month = Convert.ToInt32(comboBox7.Text);
}
private void comboBox8_SelectedIndexChanged(object sender, EventArgs e)
{
begin_day = Convert.ToInt32(comboBox8.Text);
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(1000); // important
from_bs_2 += serialPort1.ReadExisting();
Thread.Sleep(1000);
this.Invoke(new EventHandler(showdata));
Thread.Sleep(1000);
}
private void showdata(object sender, EventArgs e)
{
int changdu = from_bs_2.Length;
if (changdu > 50)
{
chushihua++;
string fro;
string[] parm = new string[6];
textBox1.Text += from_bs_2;
fro = from_bs_2;
parm = fro.Split('\n');
string path = "C:\\Users\\COM\\Desktop\\data_logging.txt";
FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
for (int a = 0; a < 4; a++)
{
string[] zhongjian = new string[23];
zhongjian = parm[a].Split(';');
// textBox1.Text += zhongjian;
for (int keai = 0; keai < 23; keai++)
{
current[a, keai] = Convert.ToDouble(zhongjian[keai]);
sw.Write(current[a, keai]); sw.Write(';');
}
sw.WriteLine('/');
}
string[] zhongjian_2 = new string[23];
zhongjian_2 = parm[5].Split(';');
for (int m = 0; m < 23; m++) //
{
volatge[m] = Convert.ToDouble(zhongjian_2[m]);
sw.Write(volatge[m]); sw.Write(';');
}
sw.WriteLine('/');
DateTime dt = DateTime.Now; //strong text
int y = dt.Year; //
int yue = dt.Month; //
int d = dt.Day; //
int h = dt.Hour; //
int n = dt.Minute; //
textBox1.Text += y;
textBox1.Text += "-";
textBox1.Text += yue;
textBox1.Text += "-";
textBox1.Text += d;
textBox1.Text += "-";
textBox1.Text += h;
textBox1.Text += ":";
textBox1.Text += n;
textBox1.Text += "-";
textBox1.Text += "data logging times";
textBox1.Text += chushihua;
sw.Write(y); sw.Write("-"); sw.Write(yue); sw.Write("-"); sw.Write(d);
sw.Write("-"); sw.Write(h); sw.Write(":"); sw.Write(n); sw.WriteLine('/');
sw.Close();
fs.Close();
//////////////////time/////////////////////////////
string info = "INSERT INTO Logging_Data_2 (Time,Number,Power1,Power2,Power3,Power4,Power5,Power6,Power7,Power8,Power9,Power10,Power11,Power,Power12,Power13,Power14,Power15,Power16,Power17,Power18,Power19,Power20,Power21,Power22,Power23) values ('a',1,current[0, 0],current[0, 1],current[0, 2],current[0, 3],current[0, 4],current[0, 5],current[0, 6],current[0, 7],current[0, 8],current[0, 9],current[0, 10],current[0, 11],current[0, 12],current[0, 13],current[0, 14],current[0, 15],current[0, 16],current[0, 17],current[0, 18],current[0, 19],current[0, 20],current[0, 21],current[0, 22])";
using (System.Data.SQLite.SQLiteConnection connection = new System.Data.SQLite.SQLiteConnection("data source=logging_data.db"))
{
// connection.Open();
// using (DbTransaction transaction = connection.BeginTransaction())
// {
using (System.Data.SQLite.SQLiteCommand command = new System.Data.SQLite.SQLiteCommand(connection))
{
connection.Open();
command.CommandText = info;
//*emphasized text*command.ExecuteNonQuery();
}
// transaction.Commit();
// }
}
from_bs_2 = "";
if (textBox1.Text.Length > 1500)
{
textBox1.Text = "";
}
}
}
I am wirting a super simple file, get the data from arduino though serial ports, and than if i get data, first i log them in a txt file, and then I need to send them into a database for future calculation. therefore I installed the SQLite, and write caode in this, but when i test it, I can log data to txt fime, but nothing in my database.
I set up a database named logging_data, and the table is Logging_data_2, when I find I cant log any data to database, i just let the time be 'a', number be 1,but it still doesnt work. ask for help, thankyou!

Related

Project cannot run anymore [Visual Studio]

I have a project that is not running anymore. I keep getting an error dialog that says "This application cannot be started. Do you want to view more information about this issue?". Also in the console, it says "The program '[10068] BinaryConverter.exe' has exited with code 0 (0x0)." Someone told me to uncheck the "Prefer 32-bit" option. When I do that, although the error dialog box is gone, the console still displays The program '[10068] BinaryConverter.exe' has exited with code 0 (0x0)." I cannot open the wpf app.
EDIT: By the way, the release folder is empty. When the app was working, my release folder had some things in it.
public MainWindow()
{
InitializeComponent();
}
public void readstuff (){
}
public static string getBetween(string strSource, string strStart, string strEnd)
{
int Start, End;
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
return strSource.Substring(Start, End - Start);
}
else
{
return "";
}
}
private void BrowseButton2(object sender, RoutedEventArgs e)
{
OpenFileDialog fd = new OpenFileDialog();
fd.InitialDirectory = "\\\\folder1\\savelocation";
fd.Filter = "Binary Files | *.bin";
fd.ShowDialog();
filePath2.Text = fd.FileName;
}
private void SavingPathButton2(object sender, RoutedEventArgs e)
{
FolderSelectDialog fs = new FolderSelectDialog();
fs.InitialDirectory = "\\\\Nx3200\\supplier\\FONEX\\LambdaGain";
fs.ShowDialog();
savingPath2.Text = fs.FileName;
}
private void StartConversion2(object sender, RoutedEventArgs e)
{
try
{
Byte [] a1 = File.ReadAllBytes(filePath2.Text);
Byte[] a2 = new Byte[2 * (a1.Length)];
int i = 0;
while(i < a1.Length) {
a2[2*i] = a1[i];
a2[(2 * i) + 1] = 0;
i++;
}
try
{
string fullPath = Path.Combine(savingPath2.Text, "new");
File.WriteAllBytes(savingPath2.Text, a2);
MessageBox.Show("Conversion Complete");
} catch (UnauthorizedAccessException ex)
{
Form3 frm3 = new Form3();
frm3.Text = "X-Formatter";
frm3.ShowDialog();
}
}
catch (FileNotFoundException ex)
{
string stackTrace = ex.ToString();
Form1 frm1 = new Form1(stackTrace);
frm1.Text = "X-Formatter";
frm1.ShowDialog();
}
}
private void BrowseButton1(object sender, RoutedEventArgs e)
{
OpenFileDialog fd = new OpenFileDialog();
fd.InitialDirectory = "\\\\folder1\\savelocation";
fd.Filter = "Binary Files | *.bin";
fd.ShowDialog();
filePath1.Text = fd.FileName;
}
private void SavingPathButton1(object sender, RoutedEventArgs e)
{
FolderSelectDialog fs = new FolderSelectDialog();
fs.InitialDirectory = "\\\\folder1\\savelocation";
fs.ShowDialog();
savingPath1.Text = fs.FileName;
}
private void StartConversion1(object sender, RoutedEventArgs e)
{
try
{
Byte[] a1 = File.ReadAllBytes(filePath1.Text);
Byte[] a2 = new Byte[(a1.Length) / 2];
a2[0] = a1[0];
int i = 2;
int j = 1;
while (i < a1.Length)
{
a2[j] = a1[i];
i = i + 2;
j += 1;
}
try
{
File.WriteAllBytes(savingPath1.Text, a2);
MessageBox.Show("Conversion Complete");
}
catch (UnauthorizedAccessException ex)
{
Form3 frm3 = new Form3();
frm3.Text = "XGIGA formatter";
frm3.ShowDialog();
}
} catch(FileNotFoundException ex)
{
string stackTrace = ex.ToString();
Form1 frm1 = new Form1(stackTrace);
frm1.Text = "XGIGA Formatter";
frm1.ShowDialog();
}
}
private void FilePath1_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
}
private void Button_Click(object sender, RoutedEventArgs e)
{
AboutBox1 ab = new AboutBox1();
ab.Text = "XGIGA Formatter";
ab.ShowDialog();
}
}

Why when trying to download the files again when clicking the start button I'm getting exception on the progressBar? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Xml.Linq;
using System.Diagnostics;
using System.Management;
using System.Runtime.InteropServices;
namespace DownloadFiles
{
public partial class Form1 : Form
{
Stopwatch sw = new Stopwatch();
Stopwatch stopwatch = new Stopwatch();
string filesdirectory = "Downloaded_Files";
string mainurl = "http://www.usgodae.org/ftp/outgoing/fnmoc/models/navgem_0.5/latest_data/";
List<string> parsedlinks = new List<string>();
string path_exe = Path.GetDirectoryName(Application.LocalUserAppDataPath);
List<string> results = new List<string>();
List<string> urls = new List<string>();
string radarImageWebAddressP1;
string radarImageWebAddressP2;
public Form1()
{
InitializeComponent();
label3.Text = "";
label4.Text = "";
label5.Text = "";
label7.Text = "";
button2.Enabled = false;
button3.Enabled = false;
filesdirectory = Path.Combine(path_exe, filesdirectory);
if (!Directory.Exists(filesdirectory))
{
Directory.CreateDirectory(filesdirectory);
}
else
{
if (IsDirectoryEmpty(filesdirectory) == false)
{
button3.Enabled = true;
}
}
radarImageWebAddressP1 = "http://www.ims.gov.il/Ims/Pages/RadarImage.aspx?Row=";
radarImageWebAddressP2 = "&TotalImages=10&LangID=1&Location=";
for (int i = 0; i < 9; i++)
{
urls.Add(radarImageWebAddressP1 + i + radarImageWebAddressP2);
}
}
public bool IsDirectoryEmpty(string path)
{
return !Directory.EnumerateFileSystemEntries(path).Any();
}
private string downloadhtml(string url)
{
backgroundWorker1.ReportProgress(0, "Downloading Main Url");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Proxy = null;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
string html = sr.ReadToEnd();
sr.Close();
response.Close();
StreamWriter w = new StreamWriter(path_exe + "\\page.html");
w.Write(html);
w.Close();
return html;
}
int Counter = 0;
int percentage = 0;
int total = 0;
int countfiletodownload = 0;
bool processStatus = false;
private void Parseanddownloadfiles()
{
//downloadhtml(mainurl);
if (bgw.CancellationPending == false)
{
/*backgroundWorker1.ReportProgress(0, "Parsing Links");
HtmlAgilityPack.HtmlWeb hw = new HtmlAgilityPack.HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc = hw.Load(path_exe + "\\page.html");
foreach (HtmlAgilityPack.HtmlNode link in doc.DocumentNode.SelectNodes("//a[#href]"))
{
string hrefValue = link.GetAttributeValue("href", string.Empty);
if (hrefValue.Contains("US"))
{
string url = "http://www.usgodae.org/ftp/outgoing/fnmoc/models/navgem_0.5/latest_data/" + hrefValue;
parsedlinks.Add(url);
if (bgw.CancellationPending == true)
return;
}
}*/
parsedlinks = urls;
countfiletodownload = parsedlinks.Count;
total = parsedlinks.Count;
backgroundWorker1.ReportProgress(0, "Downloading Files");
processStatus = true;
for (int i = 0; i < parsedlinks.Count && bgw.CancellationPending == false; i++)
{
try
{
using (WebClient client = new WebClient())
{
sw.Start();
Uri uri = new Uri(parsedlinks[i]);
string filename = "RadarImage" + i.ToString() + ".gif";//parsedlinks[i].Substring(71);
client.DownloadFileAsync(uri, filesdirectory + "\\" + filename);
Counter += 1;
percentage = Counter * 100 / total;
string filenametoreport = filename.Substring(1);
countfiletodownload--;
backgroundWorker1.ReportProgress(percentage, filenametoreport);//countfiletodownload, filenametoreport);
}
}
catch (Exception err)
{
string error = err.ToString();
}
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
BackgroundWorker bgw;
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
bgw = (BackgroundWorker)sender;
if (bgw.CancellationPending == true)
{
return;
}
else
{
Parseanddownloadfiles();
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.UserState.ToString() == "Downloading Main Url")
{
label3.Text = e.UserState.ToString();
}
if (e.UserState.ToString() == "Parsing Links")
{
label3.Text = e.UserState.ToString();
}
if (e.UserState.ToString() == "Downloading Files")
{
label7.Text = countfiletodownload.ToString();//parsedlinks.Count.ToString();
label3.Text = e.UserState.ToString();
}
if (processStatus == true)
{
if (e.UserState.ToString() != "Downloading Files")
{
label4.Text = e.UserState.ToString();
label7.Text = countfiletodownload.ToString();
progressBar1.Value = e.ProgressPercentage;
/*using (var bitmap = new Bitmap(this.Width, this.Height))
{
this.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
bitmap.Save(#"e:\screens\ss.gif" + countscreenshots, System.Drawing.Imaging.ImageFormat.Gif);
countscreenshots += 1;
}*/
}
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
}
else
{
label3.Text = "Download Completed";
stopwatch.Reset();
stopwatch.Stop();
timer1.Stop();
}
if(e.Cancelled)
label3.Text = "Operation Cancelled";
button1.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
label3.Text = "Cancelling Operation";
backgroundWorker1.CancelAsync();
button2.Enabled = false;
timer1.Stop();
stopwatch.Stop();
stopwatch.Reset();
}
private void button1_Click(object sender, EventArgs e)
{
label3.Text = "";
label4.Text = "";
label7.Text = "";
backgroundWorker1.RunWorkerAsync();
timer1.Start();
stopwatch.Start();
button1.Enabled = false;
button2.Enabled = true;
}
private void button3_Click(object sender, EventArgs e)
{
Process.Start(filesdirectory);
}
private void timer1_Tick(object sender, EventArgs e)
{
label5.Text = string.Format("{0:hh\\:mm\\:ss}", stopwatch.Elapsed);
}
}
}
First time it's downloading fine but next time when clicking again the start button(button1) it's showing exception: System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.'
I tried to reset the progressBar value to 0 in the start button(button1) click event but it didn't solve the problem.
ArgumentOutOfRangeException: Value of '111' is not valid for 'Value'. 'Value' should be between 'minimum' and 'maximum'.
Parameter name: Value
The ArgumentOutOfRange exception is because you never reset Counter:
You define Counter as class level variable and initialize to 0:
int Counter = 0;
Then in your loop you call:
Counter += 1;
percentage = Counter * 100 / total;
When you click the button to restart the download, Counter still holds the final value of the previous run.
In button1_Click, prior to calling RunWorkerAsync
You need to reset it:
Counter = 0;

TweetInvi Listview can't get TweetID

I'm trying to get Tweet ID via TweetInvi API but always get null point exception. I'm out of options and can't understand what i did wrong. Here is my code. Problem occurs when i select desired Item from view and press retweet.
namespace MIF_TwitterApplication
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Auth.SetUserCredentials("KEY", "KEY", "KEY",
"KEY");
}
private void Form1_Load(object sender, EventArgs e)
{
var user = User.GetAuthenticatedUser();
//PROFILE
profileImage.ImageLocation = user.ProfileImageUrlFullSize;
nameLabel.Text = user.Name;
usernameLabel.Text = "#" + user.ScreenName;
followersLabel.Text = "Followers: " + user.FollowersCount;
}
//Tweeting with PICS
private void tweetBtn_Click(object sender, EventArgs e)
{
if (tweetBox.Text != "")
{
if (imgUploadPath.Text != "")
{
byte[] file = File.ReadAllBytes(imgPreview.ImageLocation);
Tweet.PublishTweetWithImage(tweetBox.Text, file);
imgPreview.ImageLocation = "";
imgUploadPath.Text = "";
tweetBox.Clear();
MessageBox.Show("Tweet posted!");
}
else
{
Tweet.PublishTweet(tweetBox.Text);
MessageBox.Show("Tweet posted!");
tweetBox.Clear();
}
}
else
{
MessageBox.Show("Please enter text!");
tweetBox.Clear();
}
}
private void addImg_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
imgPreview.ImageLocation = ofd.FileName;
imgUploadPath.Text = ofd.FileName;
}
private void dropImg_Click(object sender, EventArgs e)
{
imgPreview.ImageLocation = "";
imgUploadPath.Text = "";
}
private void timelineBtn_Click(object sender, EventArgs e)
{
var user = User.GetAuthenticatedUser();
var getTweets = Timeline.GetHomeTimeline(40);
listView1.Clear();
listView1.View = View.Details;
listView1.GridLines = true;
listView1.FullRowSelect = true;
listView1.Columns.Add("Tweet", 570);
listView1.Columns.Add("Created By", 130);
listView1.Columns.Add("Create Time", 130);
listView1.Columns.Add("Likes", 60);
listView1.Columns.Add("Retweets", 70);
int x = 0;
foreach (var t in getTweets)
{
ListViewItem listItem = new ListViewItem(t.Text);
listItem.SubItems.Add(t.CreatedBy.ScreenName.ToString());
listItem.SubItems.Add(t.CreatedAt.ToString());
listItem.SubItems.Add(t.FavoriteCount.ToString());
listItem.SubItems.Add(t.RetweetCount.ToString());
listView1.Items.Add(listItem);
listView1.Items[x].Tag = t.Id;
}
}
private void postsBtn_Click(object sender, EventArgs e)
{
var user = User.GetAuthenticatedUser();
var getTweets = Timeline.GetUserTimeline(user, 40);
listView1.Clear();
listView1.View = View.Details;
listView1.GridLines = true;
listView1.FullRowSelect = true;
listView1.Columns.Add("Tweet", 570);
listView1.Columns.Add("Created By", 130);
listView1.Columns.Add("Create Time", 130);
listView1.Columns.Add("Likes", 60);
listView1.Columns.Add("Retweets", 70);
int x = 0;
foreach (var t in getTweets)
{
ListViewItem listItem = new ListViewItem(t.Text);
listItem.SubItems.Add(t.CreatedBy.ScreenName.ToString());
listItem.SubItems.Add(t.CreatedAt.ToString());
listItem.SubItems.Add(t.FavoriteCount.ToString());
listItem.SubItems.Add(t.RetweetCount.ToString());
listView1.Items.Add(listItem);
listView1.Items[x].Tag = t.Id;
}
}
private void retweetBtn_Click(object sender, EventArgs e)
{
var checkedItems = listView1.SelectedItems;
long a = (long)listView1.SelectedItems[0].Tag;
var user = User.GetAuthenticatedUser();
var retweet = Tweet.PublishRetweet(a);
MessageBox.Show("Retweet was successfull");
listView1.Items.Clear();
}
}
}
Breakes on long a, I can't figure out how to get that Long Tweet ID
Here is the full code
Problem was that my X was not incrementing correctly as it was out of for loop.
int x = 0;
foreach (var t in getTweets)
{
ListViewItem listItem = new ListViewItem(t.Text);
listItem.SubItems.Add(t.CreatedBy.ScreenName.ToString());
listItem.SubItems.Add(t.CreatedAt.ToString());
listItem.SubItems.Add(t.FavoriteCount.ToString());
listItem.SubItems.Add(t.RetweetCount.ToString());
listView1.Items.Add(listItem);
listView1.Items[x].Tag = t.Id;
x = x +1;
}

How to plot graphs with data from a SerialPort with multiple sensors

I need to plot data from sensors of pH, Temperature and Humidity, the data is sent as a matrix from arduino to PC through the serial port.
I can show the data in a TextBox, but when I try to plot the data, it doesn't work (I don't know how to do it).
I just can plot the data when is not a matrix and it's data from just one sensor.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading.Tasks;
using System.IO.Ports;
using System.Windows.Forms.DataVisualization.Charting;
namespace grafik1
{
public partial class Form1 : Form
{
private SerialPort sensport;
private DateTime datetime;
private string data;
private string data2;
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.DataSource = SerialPort.GetPortNames();
timer1.Start();
}
double rt = 0;
Boolean i = false;
private void timer1_Tick(object sender, EventArgs e)
{
rt = rt + 0.1;
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
sensport.Close();
}
private void button1_Click(object sender, EventArgs e)
{
if (comboBox2.Text == "")
{
MessageBox.Show("Error");
}
else
{
sensport = new SerialPort();
sensport.BaudRate = int.Parse(comboBox2.Text);
sensport.PortName = comboBox1.Text;
sensport.Parity = Parity.None;
sensport.DataBits = 8;
sensport.StopBits = StopBits.One;
sensport.Handshake = Handshake.None;
sensport.DataReceived += sensport_DataReceived;
try
{
sensport.Open();
textBox1.Text = "";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
}
void sensport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (i == false)
{
rt = 0;
i = true;
}
data = sensport.ReadLine();
this.chart1.Series["Data1"].Points.AddXY(rt, data);
this.Invoke(new EventHandler(displaydata_event));
}
private void displaydata_event(object sender, EventArgs e)
{
datetime = DateTime.Now;
string time = datetime.Day + "/" + datetime.Month + "/" + datetime.Year + "\t" + datetime.Hour + ":" + datetime.Minute + ":" + datetime.Second;
txtData.AppendText(time + "\t" + data + "\n");
}
private void button2_Click(object sender, EventArgs e)
{
string directorio = textBox1.Text;
if (directorio == "")
{
MessageBox.Show("Error");
}
else {
try
{
string kayıtyeri = #"" + directorio + "";
this.chart1.SaveImage(("+kayityeri+"), ChartImageFormat.Png);
MessageBox.Show("Grafica guardada en " + kayıtyeri);
}
catch (Exception ex3)
{
MessageBox.Show(ex3.Message, "Error");
}
}
}
private void label4_Click(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
sensport.Close();
}
private void button4_Click(object sender, EventArgs e)
{
try
{
string pathfile = #"C:\Users\MARIO GONZALEZ\Google Drive\VisualStudio\Arduino0_1\DATA";
string filename = "arduinoRTPv1.xls";
System.IO.File.WriteAllText(pathfile + filename, txtData.Text);
MessageBox.Show("Data saved");
}
catch (Exception ex3)
{
MessageBox.Show(ex3.Message, "Error");
}
}
private void button5_Click(object sender, EventArgs e)
{
}
private void chart1_Click(object sender, EventArgs e)
{
}
}
}
Let's assume you have prepared your chart, maybe like this:
chart1.Series.Clear();
chart1.Series.Add("ph");
chart1.Series.Add("Temp");
chart1.Series.Add("Hum");
chart1.Series["ph"].ChartType = SeriesChartType.Line;
chart1.Series["Temp"].ChartType = SeriesChartType.Line;
chart1.Series["Hum"].ChartType = SeriesChartType.Line;
chart1.ChartAreas[0].AxisY2.Enabled = AxisEnabled.True;
chart1.ChartAreas[0].AxisY2.Title = "Temp";
chart1.ChartAreas[0].AxisY2.Maximum = 100;
Now you can add a string that contains some data blocks as shown in the comments..
string data = "7.5 23.8 67 \n8.5 23.1 72 \n7.0 25.8 66 \n";
..like this:
var dataBlocks = data.Split('\n');
foreach (var block in dataBlocks)
{
var numbers = block.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries);
// rt += someTime; (*)
for (int i = 0; i < numbers.Length; i++)
{
double n = double.NaN;
bool ok = double.TryParse(numbers[i], out n);
if (ok) chart1.Series[i].Points.AddXY(rt, n);
else
{
int p = chart1.Series[i].Points.AddXY(rt, 0);
chart1.Series[i].Points[p].IsEmpty = true;
Console.WriteLine("some error message..");
}
}
}
I have modified the data a little to show the changes a little better..
Note that I left out the counting up of your timer rt, which is why the chart shows the points with indexed x-values. For a real realtime plot do include it maybe here (*) !
If you keep adding data your chart will soon get rather crowded.
You will then either have to remove older data from the beginning or at least set a minimum and maximum x-values to restrict the display to a reasonably number of data points and or turn on zooming!
See here here and here for some examples and discussions of these things!

For some reason it does not perform the timer2_tick function

The program is supposed to call start timer1 when a button is clicked, timer1 is 17secs long. Then in timer1 it is supposed to start timer2, which is 8secs long. For some reason it does not perform the timer2_tick function.
private void timer1_Tick(object sender, EventArgs e)
{
string[] ProxList = File.ReadAllLines("C:\\Prox.txt");
string[] s = new string[4];
WinInetInterop.SetConnectionProxy(ProxList[p]);
if (p > 3273)
p = 0;
s[0] = textBox1.Text;
s[1] = textBox2.Text;
s[2] = textBox3.Text;
s[3] = textBox4.Text;
try
{
webBrowser1.Navigate(s[txtBxNum]);
timer2.Start();
label1.Text = "Current Link: " + s[txtBxNum].ToString();
label2.Text = "Current IP: " + ProxList[p].ToString();
txtBxNum++;
if (txtBxNum > 3)
txtBxNum = 0;
}
catch { }
p++;
}
private void timer2_Tick(object sender, EventArgs e)
{
webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
try
{
webBrowser1.Document.GetElementById("skip_ad_button").InvokeMember("click");
}
catch { }
}

Categories