sorry for bugging you guys with such a small problem, but I cannot find a solution. I have created one class for getting attachments from exchange server and Form for adding server configuration and textbox which I attend to use for the log output. I have added backgroundWorker to create separate thread and when class gets right attachment and collect info for the output, it redirects to backgroundWorker DoWork method. The problem is that UI of the textbox is simply doesn't want to append text
Class for downloading attachment looks like:
namespace DownloadAttachmentExchange
{
class ExchangeDwnClass
{
private string path_ = "";
private string filterSender_ = "";
private string subject_ = "";
private string id_ = "";
private string username_ = "";
private string password_ = "";
private string exchange_ = "";
private string filterExcel_ = "";
private string filterCSV_ = "";
private string attachmentName_ = "";
private int emailFetch_ = 0;
private DateTime current_;
ExchangeService serv = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
public string Path
{
get { return path_; }
set { path_ = value; }
}
public string FilterSender
{
get { return filterSender_; }
set { filterSender_ = value; }
}
public string Subject
{
get { return subject_; }
set { subject_ = value; }
}
public string ID
{
get { return id_; }
set { id_ = value; }
}
public string Username
{
get { return username_; }
set { username_ = value; }
}
public string Password
{
get { return password_; }
set { password_ = value; }
}
public string Exchange
{
get { return exchange_; }
set { exchange_ = value; }
}
public string FilterExcel
{
get { return filterExcel_; }
set { filterExcel_ = value; }
}
public string FilterCsv
{
get { return filterCSV_; }
set { filterCSV_ = value; }
}
public string AttachementName
{
get { return attachmentName_; }
set { attachmentName_ = value; }
}
public int EmailFetch
{
get { return emailFetch_; }
set { emailFetch_ = value; }
}
public DateTime CurrentDate
{
get { return current_; }
set { current_ = value; }
}
public void GetAttachments()
{
try
{
serv.Credentials = new WebCredentials(Username, Password);
serv.AutodiscoverUrl(Exchange);
ItemView view = new ItemView(10);
FindItemsResults<Item> result = serv.FindItems(WellKnownFolderName.Inbox, new ItemView(EmailFetch));
if (result != null && result.Items != null && result.Items.Count > 0)
{
foreach (Item item in result.Items)
{
EmailMessage msg = EmailMessage.Bind(serv, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments, ItemSchema.HasAttachments, EmailMessageSchema.From, EmailMessageSchema.Sender));
if (msg.Sender.ToString().Contains(FilterSender) && msg.From.ToString().Contains(FilterSender))
{
foreach (Attachment att in msg.Attachments)
{
if (att is FileAttachment)
{
FileAttachment file = att as FileAttachment;
if (file.Name.Contains(FilterExcel) || file.Name.Contains(FilterCsv))
{
Form1 form = new Form1();
file.Load(Path +"\\"+ file.Name);
AttachementName = file.Name.ToString();
Subject = item.Subject.ToString();
ID = item.Id.ToString();
CurrentDate = DateTime.Now;
form.date = CurrentDate.ToString();
form.subject = Subject;
form.attachment = AttachementName;
form.backgroundWorker1.RunWorkerAsync();
Thread.Sleep(60000);
}
}
}
}
//item.Delete(DeleteMode.HardDelete);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
public void StopDownloadingAttachment()
{
}
}
}
Form looks like this:
namespace DownloadAttachmentExchange
{
public partial class Form1 : Form
{
private string path = "";
public string date = "";
public string attachment = "";
public string subject = "";
public Form1()
{
InitializeComponent();
}
ExchangeDwnClass exchange = new ExchangeDwnClass();
private void button3_Click(object sender, EventArgs e)
{
if(folderBrowserDialog1.ShowDialog(this)== DialogResult.OK)
{
path = folderBrowserDialog1.SelectedPath;
exchange.Path = path;
pathTxt.Text = path;
}
}
private void onBtn_Click(object sender, EventArgs e)
{
exchange.Username = userTxt.Text;
exchange.Password = passwdTxt.Text;
exchange.FilterSender = fromFilterTxt.Text;
exchange.EmailFetch = Convert.ToInt32(fetchUpDown.Value);
exchange.Exchange = exchangeTxt.Text;
exchange.GetAttachments();
}
private void filterExcelCheck_CheckedChanged(object sender, EventArgs e)
{
if (filterExcelCheck.CheckState == CheckState.Checked)
{
exchange.FilterExcel = ".xlsx";
}
else
{
exchange.FilterExcel = "";
}
}
private void filterCSVCheck_CheckedChanged(object sender, EventArgs e)
{
if (filterCSVCheck.CheckState == CheckState.Checked)
{
exchange.FilterCsv = ".csv";
}
else
{
exchange.FilterCsv = "";
}
}
private void exchangeTxt_MouseHover(object sender, EventArgs e)
{
tipLbl.Visible = true;
tipLbl.Text = "It is usually same as email address...";
}
private void exchangeTxt_MouseLeave(object sender, EventArgs e)
{
tipLbl.Visible = false;
}
//("\n" + CurrentDate.ToString() + " , Message id: " + ID + " , Message subject: " + Subject + " , Attachment name: " + AttachementName + "\r");
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//e.Result = "\n" + date + " , Message subject: " + subject + " , Attachment name: " + attachment + "\r";
logOutputTxt.Text = "\n" + date + " , Message subject: " + subject + " , Attachment name: " + attachment + "\r";
//backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
}
//private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
//{
// if (e.Cancelled)
// {
// logOutputTxt.Text = "Thread is somehow cancelled, please contact developer for this issue...!";
// }
// else if (e.Error != null)
// {
// logOutputTxt.Text = e.Error.Message;
// }
// else
// {
// logOutputTxt.Text += e.Result;
// }
//}
}
}
as you can see I'm calling background worker from class ExchangeDwnClass which I believe is OK, by using:
form.backgroundWorker1.RunWorkerAsync();
and when I run debugger it really jumps to background worker
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
logOutputTxt.Text = "\n" + date + " , Message subject: " + subject + " , Attachment name: " + attachment + "\r";
//backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
}
for some reason Form textbox control is not refreshing output.
p.s. I have created also on RunWorkerCompleted method but also without luck...
Any clue how can I work things out?
OK, the problem was that I have created another object in form ExchangeDowClass for Form1, instead of passing a reference object into method GetAttachments
complete code for Form1:
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;
namespace DownloadAttachmentExchange
{
public partial class Form1 : Form
{
private string path = "";
public string subject = "";
public string attachment = "";
public string date = "";
public string sender = "";
public Form1()
{
InitializeComponent();
}
ExchangeDwnClass exchange = new ExchangeDwnClass();
BackgroundWorker bgrWorker = new BackgroundWorker();
private void button3_Click(object sender, EventArgs e)
{
if(folderBrowserDialog1.ShowDialog(this)== DialogResult.OK)
{
path = folderBrowserDialog1.SelectedPath;
exchange.Path = path;
pathTxt.Text = path;
}
}
private void onBtn_Click(object sender, EventArgs e)
{
exchange.EmailFetch=Convert.ToInt32(fetchUpDown.Value);
exchange.FilterSender = fromFilterTxt.Text;
exchange.Exchange = exchangeTxt.Text;
exchange.Password = passwdTxt.Text;
exchange.Username = userTxt.Text;
backgroundWorker1.RunWorkerAsync();
}
private void filterExcelCheck_CheckedChanged(object sender, EventArgs e)
{
if (filterExcelCheck.CheckState == CheckState.Checked)
{
exchange.FilterExcel = ".xlsx";
}
else
{
exchange.FilterExcel = "";
}
}
private void filterCSVCheck_CheckedChanged(object sender, EventArgs e)
{
if (filterCSVCheck.CheckState == CheckState.Checked)
{
exchange.FilterCsv = ".csv";
}
else
{
exchange.FilterCsv = "";
}
}
private void exchangeTxt_MouseHover(object sender, EventArgs e)
{
tipLbl.Visible = true;
tipLbl.Text = "It is usually same as email address...";
}
private void exchangeTxt_MouseLeave(object sender, EventArgs e)
{
tipLbl.Visible = false;
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//logOutputTxt.Text += "\n" + date + " , Message subject: " + subject + " , Attachment name: " + attachment + "\r"
//backgroundWorker1.ReportProgress(0);
exchange.GetAttachments(this);
}
private void Form1_Load(object sender, EventArgs e)
{
this.backgroundWorker1.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorker1_ProgressChanged);
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
logOutputTxt.Text += "\n" + date + " , Sender: "+sender+" , Message subject: " + subject + " , Attachment name: " + attachment + "\r";
}
}
}
and for ExchangeDwnClass:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Exchange;
using Microsoft.Exchange.WebServices;
using Microsoft.Exchange.WebServices.Data;
using System.Threading;
namespace DownloadAttachmentExchange
{
class ExchangeDwnClass
{
private string path_ = "";
private string filterSender_ = "";
private string subject_ = "";
private string id_ = "";
private string username_ = "";
private string password_ = "";
private string exchange_ = "";
private string filterExcel_ = "";
private string filterCSV_ = "";
private string attachmentName_ = "";
private int emailFetch_ = 0;
private DateTime current_;
ExchangeService serv = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
public string Path
{
get { return path_; }
set { path_ = value; }
}
public string FilterSender
{
get { return filterSender_; }
set { filterSender_ = value; }
}
public string Subject
{
get { return subject_; }
set { subject_ = value; }
}
public string ID
{
get { return id_; }
set { id_ = value; }
}
public string Username
{
get { return username_; }
set { username_ = value; }
}
public string Password
{
get { return password_; }
set { password_ = value; }
}
public string Exchange
{
get { return exchange_; }
set { exchange_ = value; }
}
public string FilterExcel
{
get { return filterExcel_; }
set { filterExcel_ = value; }
}
public string FilterCsv
{
get { return filterCSV_; }
set { filterCSV_ = value; }
}
public string AttachementName
{
get { return attachmentName_; }
set { attachmentName_ = value; }
}
public int EmailFetch
{
get { return emailFetch_; }
set { emailFetch_ = value; }
}
public DateTime CurrentDate
{
get { return current_; }
set { current_ = value; }
}
public void GetAttachments(Form1 form)
{
try
{
serv.Credentials = new WebCredentials(Username, Password);
serv.AutodiscoverUrl("username#domain.lan");
ItemView view = new ItemView(EmailFetch);
FindItemsResults<Item> result = serv.FindItems(WellKnownFolderName.Inbox, new ItemView(EmailFetch));
if (result != null && result.Items != null && result.Items.Count > 0)
{
foreach (Item item in result.Items)
{
EmailMessage msg = EmailMessage.Bind(serv, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments, ItemSchema.HasAttachments, EmailMessageSchema.From, EmailMessageSchema.Sender));
if (msg.Sender.ToString().ToLower().Contains(FilterSender) && msg.From.ToString().ToLower().Contains(FilterSender))
{
foreach (Attachment att in msg.Attachments)
{
if (att is FileAttachment)
{
FileAttachment file = att as FileAttachment;
if (file.Name.Contains(FilterExcel) || file.Name.Contains(FilterCsv))
{
file.Load(Path +"\\"+ file.Name);
form.attachment = file.Name.ToString();
form.subject = item.Subject.ToString();
//ID = item.Id.ToString();
form.date = DateTime.Now.ToString();
form.sender = msg.Sender.ToString();
form.backgroundWorker1.ReportProgress(0);
Thread.Sleep(60000);
}
}
}
}
//item.Delete(DeleteMode.HardDelete);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
public void StopDownloadingAttachment()
{
}
}
}
Plus I had to use ProgressChanged method to refresh control...
I still have some minor bugs like double output in textbox form, but this is basically small issue.
I hope this code will be useful to others.
Cheers.
Related
I tried to write an autoupdater for a program from me.
I already got rid of a stackOverflow and such but now my Program seems to run endless when he comes to a variable. And do nothing.
I tried to get info with cw and check where it is hanging but i get nothing and can not find it.
My main
{
updater = new Updater(this);
updater.DoUpdate();
}
public string ApplicationName {
get { return "MyProgram"; }
}
public string ApplicationID {
get { return "MyProgramID"; }
}
public Assembly ApplicationAssembly {
get { return System.Reflection.Assembly.GetExecutingAssembly(); }
}
public Icon ApplicationIcon {
get { return this.Icon; }
}
public Uri UpdateXmlLocation {
get { return new Uri("UrlToXml"); }
}
public Form Context {
get { return this; }
}
in my XML class
public class UpdateXml
{
private Version version;
public Uri uri;
private string fileName;
private string md5;
private string description;
private string launchArgs;
internal Version Version {
get { return this.Version; }
}
internal Uri Uri {
get { return this.Uri; }
}
internal string FileName {
get { return this.fileName; }
}
internal string MD5 {
get { return this.md5; }
}
internal string Description {
get { return this.description; }
}
internal string LaunchArgs {
get { return this.launchArgs; }
}
after a while (code running fine it come to the part that crash)
private void DwnloadUpdate(UpdateXml update)
{
updateDownloadForm form = new updateDownloadForm(update.Uri, this.applicationInfo.ApplicationIcon);
after this code I expect that my dl windows open and the dl starts and the program get update
My Updater class
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
namespace updater
{
public class Updater
{
private Iupdater applicationInfo;
private BackgroundWorker bgWorker;
public Updater(Iupdater applicationInfo)
{
this.applicationInfo = applicationInfo;
this.bgWorker = new BackgroundWorker();
this.bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
this.bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
}
public void DoUpdate()
{
if (!this.bgWorker.IsBusy)
this.bgWorker.RunWorkerAsync(this.applicationInfo);
}
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
Iupdater application = (Iupdater)e.Argument;
if (!UpdateXml.ExistOnServer(application.UpdateXmlLocation))
{
e.Cancel = true;
}
else
{
UpdateXml ux = UpdateXml.Parse(application.UpdateXmlLocation, application.ApplicationID);
if (ux == null)
{
e.Cancel = true;
}
else
{
e.Result = ux;
}
}
}
void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if(!e.Cancelled)
{
UpdateXml update = (UpdateXml)e.Result;
if(update == null)
{
Console.WriteLine("Update NULL");
}
Console.WriteLine("test3.1");
Console.WriteLine(this.applicationInfo.ApplicationAssembly.GetName().Version);
if(this.applicationInfo.ApplicationAssembly.GetName().Version != null)
{
Console.WriteLine("YES!");
} else
{
Console.WriteLine("NO!");
}
Console.WriteLine("test3.2");
if (update != null && update.IsNewerThan(this.applicationInfo.ApplicationAssembly.GetName().Version))
{
Console.WriteLine("test4");
if (new updateInformation(applicationInfo, update).ShowDialog(this.applicationInfo.Context) == DialogResult.Yes)
this.DwnloadUpdate(update);
}
}
}
private void DwnloadUpdate(UpdateXml update)
{
Console.WriteLine(update.Uri);
if(update.Uri == null)
Console.WriteLine("null");
updateDownloadForm form = new updateDownloadForm(update.Uri, this.applicationInfo.ApplicationIcon);
Console.WriteLine("ich bin hier drinnen");
DialogResult result = form.ShowDialog(this.applicationInfo.Context);
if(result == DialogResult.OK)
{
string currentPath = this.applicationInfo.ApplicationAssembly.Location;
string newPath = Path.GetDirectoryName(currentPath) + "\\" + update.FileName;
UpdateApplication(form.TempFilePath, currentPath, newPath, update.LaunchArgs);
Application.Exit();
}
else if(result == DialogResult.Abort)
{
MessageBox.Show("The update download was cancelled. \nThis programm has not been modified.", "Update Download Cancelled", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("There was a Problem downloading the Updat. \nThis programm has not been modified.", "Update Download Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void UpdateApplication(string tempFilePath, string currentPath, string newPath, string launchArgs)
{
string argument = "/C Choice /C Y /N /D Y /T 4 & Del /F /Q \"{0}\" & Choice /C Y /N /D Y /T 2 & Move /Y \"{1}\" \"{2}\" & Start \"\" /D \"{3}\" \"{4}\"{5}";
ProcessStartInfo info = new ProcessStartInfo();
info.Arguments = string.Format(argument, currentPath, tempFilePath, newPath, Path.GetDirectoryName(newPath), Path.GetFileName(newPath), launchArgs);
info.CreateNoWindow = true;
info.FileName = "cmd.exe";
Process.Start(info);
}
}
}
my XML Updater class
using System;
using System.Net;
using System.Xml;
namespace updater
{
public class UpdateXml
{
private Version version;
public Uri uri;
private string fileName;
private string md5;
private string description;
private string launchArgs;
internal Version Version {
get { return this.Version; }
}
internal Uri Uri {
get { return this.Uri; }
}
internal string FileName {
get { return this.fileName; }
}
internal string MD5 {
get { return this.md5; }
}
internal string Description {
get { return this.description; }
}
internal string LaunchArgs {
get { return this.launchArgs; }
}
internal UpdateXml(Version version, Uri uri, string fileName, string md5, string description, string launchArgs)
{
Console.WriteLine("run in1");
this.version = version;
this.uri = uri;
this.fileName = fileName;
this.md5 = md5;
this.description = description;
this.launchArgs = launchArgs;
Console.WriteLine("run out 1");
}
internal bool IsNewerThan(Version version)
{
Console.WriteLine("run in 2");
return this.version > version;
}
internal static bool ExistOnServer(Uri location)
{
try
{
Console.WriteLine("run in 3");
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(location.AbsoluteUri);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
Console.WriteLine("run out 3");
return res.StatusCode == HttpStatusCode.OK;
}
catch { return false; }
}
internal static UpdateXml Parse(Uri location, string appID)
{
Console.WriteLine("run in 4");
Version version = null;
string url = "", fileName = "", md5 = "", description = "", launchArgs = "";
try
{
XmlDocument doc = new XmlDocument();
doc.Load(location.AbsoluteUri);
XmlNode node = doc.DocumentElement.SelectSingleNode("//update");
if(node == null)
{
return null;
}
version = Version.Parse(node["version"].InnerText);
url = node["url"].InnerText;
fileName = node["fileName"].InnerText;
md5 = node["md5"].InnerText;
description = node["description"].InnerText;
launchArgs = node["launchArgs"].InnerText;
Console.WriteLine("run out 4");
return new UpdateXml(version, new Uri(url), fileName, md5, description, launchArgs);
}
catch
{
return null;
}
}
}
}
My interfaces
using System;
using System.Reflection;
using System.Drawing;
using System.Windows.Forms;
namespace updater
{
public interface Iupdater
{
string ApplicationName { get; }
string ApplicationID { get; }
Assembly ApplicationAssembly { get; }
Icon ApplicationIcon { get; }
Uri UpdateXmlLocation { get; }
Form Context { get; }
}
}
my update start form where it seems to go into a loop
using System;
using updater;
using System.Windows.Forms;
namespace updater
{
internal partial class updateInformation : Form
{
private Iupdater applicationInfo;
private UpdateXml updateInfo;
private UpdateInoForm updateInoForm;
public updateInformation(Iupdater applicationInfo, UpdateXml updateInfo)
{
InitializeComponent();
this.applicationInfo = applicationInfo;
this.updateInfo = updateInfo;
this.Text = this.applicationInfo.ApplicationName + " - Update in Process";
if (this.applicationInfo.ApplicationIcon != null)
this.Icon = this.applicationInfo.ApplicationIcon;
//this.lblNewVersion.Text = String.Format("New Version: {0}", this.updateInfo.Version.ToString());
Timer wait = new Timer();
wait.Interval = 5000;
wait.Tick += new EventHandler(wait_Tick);
wait.Start();
}
void wait_Tick(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Yes;
}
private void Details_Click(object sender, EventArgs e)
{
if (this.updateInfo == null)
this.updateInoForm = new UpdateInoForm(this.applicationInfo, this.updateInfo);
this.updateInoForm.ShowDialog(this);
}
}
}
You need to return the field values, instead of the properties returning the property value. Do not write properties like this:
/// THIS PROPERTY TRIES TO RETURN ITSELF!!
internal Version Version {
get {
return this.Version; // you wanted to return 'this.version'
}
}
You can use auto-properties like this:
// No more private fields
public class UpdateXml
{
public Version Version { get; set; }
public string FileName { get; } // Only expose a getter, can be set in the ctor
public Uri Uri { get; set; }
// add more properties here...
public UpdateXml(string filename)
{
FileName = filename;
}
}
Or learn to use a convention seen allot in C#. Prefix the private variable names:
public class UpdateXml
{
private Version _version;
private string _fileName;
private Uri _uri;
public Version Version => _version;
public string FileName => _filename;
public Uri Uri {
get => _uri;
set => _uri = value;
}
// add more properties here...
// use the ctor to set some field values
public UpdateXml(string filename)
{
_filename = filename;
}
// fields allow setting values later on
public void SetLatestVersion(Version v)
{
if (_version == null || v > _version)
_version = v;
}
}
All in all, take care when writing code. Case does matter ;-)
I'm studying programming C# and i just got to build winform Client that can read from a text file and save it to a list, this list will then be displayed in a listbox and to be used to be sent to the server.
everything is working fine but i just have one question. What data is used here? from the server to the client. is it Byte?
Here is the code:
using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Text;
using System.Threading;
namespace Avdelningsrapport
{
public partial class Form1 : Form
{
TcpClient klient = new TcpClient();
int port = 12345;
List<Bok> bokListan = new List<Bok>(); alla sorterade böcker
List<string> itemSaver = new List<string>();
string[] vektor;
public Form1()
{
InitializeComponent();
klient.NoDelay = true;
string item = "";
List<string[]> vectors = new List<string[]>();
if (File.Exists("texter.txt"))
{
StreamReader reader = new StreamReader("texter.txt", Encoding.Default, true);
while ((item = reader.ReadLine()) != null)
{
itemSaver.Add(item);
}
foreach (string a in itemSaver)
{
vektor = a.Split(new string[] { "###" }, StringSplitOptions.None);
vectors.Add(vektor);
Bok newBok = new Bok();
bokListan.Add(newBok);
newBok.Titel = vektor[0];
newBok.Skribent = vektor[1];
newBok.Typ = vektor[2];
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
public class Bok
{
public string Titel { get; set; }
public string Skribent { get; set; }
public string Typ { get; set; }
public override string ToString()
{
return "\"" + Titel + "\" en (" + Typ + ") av " + Skribent + ".";
}
}
private void Load_Click(object sender, EventArgs e)
{
ListBox1.Items.AddRange(bokListan.ToArray());
}
private void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Skickamrk.Enabled = true;
SkickaAlla.Enabled = true;
}
private void SkickaAlla_Click(object sender, EventArgs e)
{
for (int i = 0; i < ListBox1.Items.Count; i++)
{
StartaSänding(ListBox1.Items[i].ToString());
Thread.Sleep(50);
}
}
private void SkickaMrk_Click(object sender, EventArgs e)
{
if (ListBox1.SelectedItems.Count == 1)
{
StartaSänding(ListBox1.Text.ToString());
bokListan.RemoveAt(ListBox1.SelectedIndex);
ListBox1.Items.RemoveAt(ListBox1.SelectedIndex);
}
}
private void Ansluta_Click(object sender, EventArgs e)
{
if (!klient.Connected) StartaAnslutning();
}
public async void StartaAnslutning()
{
try
{
IPAddress adress = IPAddress.Parse("127.0.0.1");
await klient.ConnectAsync(adress, port);
btnAnsluta.Enabled = false;
}
catch (Exception error) { MessageBox.Show(error.Message, Text); return; }
}
public async void StartaSänding(string message)
{
byte[] utData = Encoding.Unicode.GetBytes(message);
try
{
await klient.GetStream().WriteAsync(utData, 0, utData.Length);
}
catch (Exception error)
{
MessageBox.Show(error.Message, this.Text);
return;
}
}
}
}
The file used here is like this : Den som vandrar om natten###Marianne Fredriksson###Roman
Where 1st part before the ### is the Title of the book, 2nd aurthor, 3rd type of the book.
Thank you ;
Any idea why my visual studio doesn't send to windowsform from pi but it does send when i'm using my school's visual studio ( same version ). Do I have to download any specific thing or whatsoever to make it work? Please help.
Here's my code in case too. Would be cool if some1 can go through it and help me with it ( school's project ) Much appreciated !
string strConnectionString =
ConfigurationManager.ConnectionStrings["DataCommsDBConnection"].ConnectionString;
DataComms dataComms;
public delegate void myprocessDataDelegate(string strData);
private void saveWaterSensorDataToDB(string strTime, string strWaterValue, string strStatus)
{
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "INSERT MySensor (TimeOccurred, SensorValue, SensorStatus) +" +
"VALUES (#time, #value, #status)";
SqlCommand updateCmd = new SqlCommand(strCommandText, myConnect);
updateCmd.Parameters.AddWithValue("#time", strTime);
updateCmd.Parameters.AddWithValue("#value", strWaterValue);
updateCmd.Parameters.AddWithValue("#status", strStatus);
myConnect.Open();
int result = updateCmd.ExecuteNonQuery();
myConnect.Close();
}
private string extractStringValue(string strData, string ID)
{
string result = strData.Substring(strData.IndexOf(ID) + ID.Length);
return result;
}
private float extractFloatValue(string strData, string ID)
{
return (float.Parse(extractStringValue(strData, ID)));
}
private void handleWaterSensorData(string strData, string strTime, string ID)
{
string strWaterValue = extractStringValue(strData, ID);
txtWaterValue.Text = strWaterValue;
txtWaterLevel.Text = strWaterValue;
float fWaterValue = extractFloatValue(strData, ID);
string status = "";
if (fWaterValue <= 500)
status = "Dry";
else
status = "Wet";
txtRoomStatus.Text = status;
}
private void handleButtonData(string strData, string strTime, string ID)
{
string strbuttonValue = extractStringValue(strData, ID);
txtButtonValue.Text = strbuttonValue;
txtDoorBell.Text = strbuttonValue;
}
private void extractSensorData(string strData, string strTime)
{
if (strData.IndexOf("WaterLevel=") != -1)
handleWaterSensorData(strData, strTime, "WaterLevel=");
else if (strData.IndexOf("BUTTON=") != -1)
handleButtonData(strData, strTime, "BUTTON=");
}
public void handleSensorData(string strData)
{
string dt = DateTime.Now.ToString();
extractSensorData(strData, dt);
string strMessage = dt + ":" + strData;
lbDataComms.Items.Insert(0, strMessage);
}
public void processDataReceive(string strData)
{
myprocessDataDelegate d = new myprocessDataDelegate(handleSensorData);
lbDataComms.Invoke(d, new object[] { strData });
}
public void commsDataReceive(string dataReceived)
{
processDataReceive(dataReceived);
}
public void commsSendError(string errMsg)
{
MessageBox.Show(errMsg);
processDataReceive(errMsg);
}
private void InitComms()
{
dataComms = new DataComms();
dataComms.dataReceiveEvent += new DataComms.DataReceivedDelegate(commsDataReceive);
dataComms.dataSendErrorEvent += new DataComms.DataSendErrorDelegate(commsSendError);
}
public frmDataComms()
{
InitializeComponent();
}
private void frmDataComms_Load(object sender, EventArgs e)
{
InitComms();
}
private void btnClear_Click(object sender, EventArgs e)
{
lbDataComms.Items.Clear();
}
private void btnSendLight_Click(object sender, EventArgs e)
{
dataComms.sendData("SENDWATER");
}
private void btnSendButton_Click(object sender, EventArgs e)
{
dataComms.sendData("SENDBUTTON");
}
private void btnCmd_Click(object sender, EventArgs e)
{
dataComms.sendData(txtCmd.Text);
}
private void btnSendAll_Click(object sender, EventArgs e)
{
dataComms.sendData("SENDALL");
}
private void btnSendTemp_Click(object sender, EventArgs e)
{
dataComms.sendData("SENDTEMP");
}
}
Form ***
namespace DataCommsRpi
{
public sealed class StartupTask : IBackgroundTask
{
const int MODE_SENDWATER = 1;
const int MODE_SENDBUTTON = 2;
const int MODE_SENDALL = 3;
const int MODE_SENDTEMP = 4;
static int curMode;
Pin waterPin = Pin.AnalogPin2;
IButtonSensor button = DeviceFactory.Build.ButtonSensor(Pin.DigitalPin4);
Pin tempPin = Pin.AnalogPin0;
DataComms dataComms;
string strDataReceived = "";
private bool buttonPressed = false;
private bool prevButtonStatus = false;
int moistureAdcValue = 800;
double tempDegree = 20;
private bool moistureWet = false;
private bool moistureDry = false;
private bool tempHot = false;
private bool tempCold = false;
private void Sleep(int NoOfMs)
{
Task.Delay(NoOfMs).Wait();
}
private async void startWaterMonitoring()
{
int iPrevAdcValue = 800, iReadAdcValue, iDiff;
await Task.Delay(100);
while (true)
{
Sleep(500);
iReadAdcValue = DeviceFactory.Build.GrovePi().AnalogRead(waterPin);
if (iPrevAdcValue > iReadAdcValue)
iDiff = iPrevAdcValue - iReadAdcValue;
else
iDiff = iReadAdcValue - iPrevAdcValue;
iPrevAdcValue = iReadAdcValue;
if (iDiff < 100)
moistureAdcValue = iReadAdcValue;
}
}
private async void startTempMonitoring()
{
await Task.Delay(100);
int adcValue; double tempCalculated = 0, R;
while (true)
{
Sleep(1000);
adcValue = DeviceFactory.Build.GrovePi().AnalogRead(tempPin);
int B = 4250, R0 = 100000;
R = 100000 * (1023.0 - adcValue) / adcValue;
tempCalculated = 1 / (Math.Log(R / R0) / B + 1 / 298.15) - 273.15;
if (!Double.IsNaN(tempCalculated))
tempDegree = tempCalculated;
}
}
private async void startButtonMonitoring()
{
await Task.Delay(100);
while(true)
{
Sleep(100);
string buttonState = button.CurrentState.ToString();
if (buttonState.Equals("On"))
{
Sleep(100);
buttonState = button.CurrentState.ToString();
if(buttonState.Equals("On"))
{
buttonPressed = true;
}
}
}
}
private void commsDataReceive(string dataReceived)
{
strDataReceived = dataReceived;
Debug.WriteLine("Data Received : " + strDataReceived);
}
private void sendDataToWindows(string strDataOut)
{
try
{
dataComms.sendData(strDataOut);
Debug.WriteLine("Sending Msg : " + strDataOut);
}
catch(Exception)
{
Debug.WriteLine("ERROR. Did you forget to initComms()?");
}
}
private void initComms()
{
dataComms = new DataComms();
dataComms.dataReceiveEvent += new DataComms.DataReceivedDelegate(commsDataReceive);
}
private void handleModeSendWater()
{
if (moistureAdcValue <= 500)
moistureWet = true;
else
moistureWet = false;
if (moistureAdcValue <= 500 && moistureDry != moistureWet)
sendDataToWindows("WaterLevel=" + moistureAdcValue + " wet");
if (moistureAdcValue > 500 && moistureDry != moistureWet)
sendDataToWindows("WaterLevel=" + moistureAdcValue + " dry");
moistureDry = moistureWet;
if (strDataReceived.Equals("SENDBUTTON"))
{
curMode = MODE_SENDBUTTON;
Debug.WriteLine("===Entering MODE_SENDBUTTON===");
}
else if (strDataReceived.Equals("SENDALL"))
{
curMode = MODE_SENDALL;
Debug.WriteLine("===Entering MODE_SENDALL");
}
else if (strDataReceived.Equals("SENDTEMP"))
{
curMode = MODE_SENDTEMP;
Debug.WriteLine("===Entering MODE_SENDTEMP");
}
strDataReceived = "";
}
private void handleModeSendTemperature()
{
if (tempDegree <= 31)
tempCold = true;
else
tempCold = false;
if (tempDegree <= 31 && tempCold != tempHot)
{
Sleep(3000);
sendDataToWindows("Temperature = " + tempDegree.ToString("N2") + " : cold");
}
else if (tempDegree >= 32 && tempCold != tempHot)
{
Sleep(3000);
sendDataToWindows("Temperature = " + tempDegree.ToString("N2") + " : hot");
}
if (strDataReceived.Equals("SENDBUTTON"))
{
curMode = MODE_SENDBUTTON;
Debug.WriteLine("===Entering MODE_SENDBUTTON===");
}
else if (strDataReceived.Equals("SENDALL"))
{
curMode = MODE_SENDALL;
Debug.WriteLine("===Entering MODE_SENDALL");
}
else if (strDataReceived.Equals("SENDWATER"))
{
curMode = MODE_SENDWATER;
Debug.WriteLine("===Entering MODE_SENDWATER===");
}
}
private void handleModeSendButton()
{
if(buttonPressed != prevButtonStatus)
{
sendDataToWindows("BUTTON=" + buttonPressed);
}
prevButtonStatus = buttonPressed;
buttonPressed = false;
if(strDataReceived.Equals("SENDWATER"))
{
curMode = MODE_SENDWATER;
Debug.WriteLine("===Entering MODE_SENDWATER===");
}
else if(strDataReceived.Equals("SENDALL"))
{
curMode = MODE_SENDALL;
Debug.WriteLine("===Entering MODE_SENDALL");
}
else if (strDataReceived.Equals("SENDTEMP"))
{
curMode = MODE_SENDTEMP;
Debug.WriteLine("===Entering MODE_SENDTEMP");
}
}
private void handleModeSendAll()
{
Sleep(5000);
sendDataToWindows("Water Level=" + moistureAdcValue);
sendDataToWindows("Temperature = " + tempDegree.ToString("N2"));
if (strDataReceived.Equals("SENDWATER"))
{
curMode = MODE_SENDWATER;
Debug.WriteLine("===Entering MODE_SENDWATER");
}
else if (strDataReceived.Equals("SENDBUTTON"))
{
curMode = MODE_SENDBUTTON;
Debug.WriteLine("===Entering MODE_SENDBUTTON");
}
else if (strDataReceived.Equals("SENDTEMP"))
{
curMode = MODE_SENDTEMP;
Debug.WriteLine("===Entering MODE_SENDTEMP");
}
}
public void Run(IBackgroundTaskInstance taskInstance)
{
//
// TODO: Insert code to perform background work
//
// If you start any asynchronous methods here, prevent the task
// from closing prematurely by using BackgroundTaskDeferral as
// described in http://aka.ms/backgroundtaskdeferral
//
initComms();
startButtonMonitoring();
startWaterMonitoring();
startTempMonitoring();
curMode = MODE_SENDWATER;
Debug.WriteLine("===Entering MODE_SENDWATER===");
while (true)
{
Sleep(300);
if (curMode == MODE_SENDWATER)
handleModeSendWater();
else if (curMode == MODE_SENDBUTTON)
handleModeSendButton();
else if (curMode == MODE_SENDALL)
handleModeSendAll();
else if (curMode == MODE_SENDTEMP)
handleModeSendTemperature();
else
Debug.WriteLine("ERROR: Invalid Mode. Please check your logic");
}
}
}
}
I have three classes, and the code is provided below.
Network - Add and Remove Phone, Process Calls. Phone1 and Phone2 can call each other when added to the network.
But I am having an issue when I am connecting both the phone to the network and trying to call phone1 to phone2; it is keeping giving me "receiver busy". I have tried to do a little debugging and read the status of phone2 when calling from phone1, but it returns an empty string (which should actually return "A", when it is added to the network as I am setting its value to "A").
public partial class network : Form
{
phone1 p1 = new phone1();
phone2 p2 = new phone2();
public network()
{
InitializeComponent();
}
public Boolean numberValidator(int number)
{
Boolean exist = false;
if (comboBox2.Items.Equals(number))
{
exist = true;
}
return exist;
}
public void processCall(int rNumber)
{
if (!numberValidator(rNumber))
{
p1.TextBox1.Clear();
p1.TextBox1.Text = "Not connected";
}
else
{
p1.TextBox1.Clear();
p1.TextBox1.Text = "Call in progress";
p2.receiveCall(1);
p1.setStatus("Busy");
/*
if (p2.btnCallPressStatus())
{
p1.TextBox1.Clear();
p1.TextBox1.Text = "Call initiated";
}*/
}
}
private void button1_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == 0)
{
p1.Show();
comboBox2.Items.Add(1);
p1.setStatus("A");
}
if (comboBox1.SelectedIndex == 1)
{
p2.Show();
comboBox2.Items.Add(2);
p2.setStatus("A");
}
}
}
----------Phone1 Class---------
public partial class phone1 : Form
{
public phone1()
{
InitializeComponent();
}
string status;
public void setStatus(string Status)
{
status = Status;
}
public string returnStatus()
{
return status;
}
public void receiveCall(int callerNumber)
{
setStatus("Busy");
btnCall.Text = "Answer";
textBox1.Text = "Phone " + callerNumber + " Calling.";
}
public void makeCall(int number)
{
phone2 p2 = new phone2();
network net = new network();
MessageBox.Show(p2.returnStatus()); // this line not returing status of phone2
if (p2.returnStatus() == "A")
{
net.processCall(number);
}
else
{
textBox1.Text = "Receiver Busy";
}
}
public TextBox TextBox1
{
get
{
return textBox1;
}
}
private void btnCall_Click(object sender, EventArgs e)
{
string number = textBox1.Text;
int numberInt = Convert.ToInt16(number);
makeCall(numberInt);
}
string phoneNo = "";
private void btn2_Click(object sender, EventArgs e)
{
phoneNo = phoneNo + btn2.Text;
textBox1.Text = phoneNo;
}
}
-------------phone2 Class--------------
public partial class phone2 : phone1
{
public phone2()
{
InitializeComponent();
}
}
The routine makeCall is creating a new instance of phone2 and calling returnStatus next. The problem is that the string "status" is not Being initialized with any value when p2 is created, so, the returno value will never be "A" and you will always fail the test.
I want to add two lists to the box. It doesn't have a problem with adding items to the listbox, but a problem occurs when I try to click on one of the items and show a related form with details filled in to allow users to make amendments. Obviously the form didn't show, but instead an error occurs, no matter if I was try to open the form "delivery" or "pickup". The problem still occurs on one line
Error:
An unhandled exception of type 'System.InvalidCastException' occurred
in coursework2.exe
Additional information: Unable to cast object of type 'System.String'
to type 'coursework2.Pickup'.
namespace coursework2
{
public partial class MainForm : Form
{
private DeliveryForm deliveryform = new DeliveryForm();
private List<Visit> requests = new List<Visit>();
private Visit theVisit = new Visit();
private PickupForm pickupform = new PickupForm();
public void requestVisit(Visit newVisit)
{
requests.Add(newVisit);
}
public MainForm()
{
InitializeComponent();
}
private void btnNpickup_Click(object sender, EventArgs e)
{
pickupform.pickup = new Pickup();
pickupform.ShowDialog();
if (pickupform.pickup != null)
{
Pickup newPu = pickupform.pickup;
theVisit.addPick(newPu);
List<String> listOfPic = theVisit.listofPicks();
listboxVisits.Items.AddRange(listOfPic.ToArray());
}
updateList();
//this will upload details from pickup form to the list
}
private void groupBox2_Enter(object sender, EventArgs e)
{
}
private void MainForm_Load(object sender, EventArgs e)
{
}
private void btnNdelivery_Click(object sender, EventArgs e)
{
deliveryform.delivery = new Delivery();
deliveryform.ShowDialog();
if (deliveryform.delivery != null)
{
Delivery newDe = deliveryform.delivery;
theVisit.addDeliver(newDe);
List<String> listOfDel = theVisit.listofDeliver();
listboxVisits.Items.AddRange(listOfDel.ToArray());
}
updateList();
//this will upload detail of the delivery to the list
}
private void btnVall_Click(object sender, EventArgs e)
{
}
private void updateList()
{
listboxVisits.Items.Clear();
List<String> listofVis = theVisit.LisitVisits();
listboxVisits.Items.AddRange(listofVis.ToArray());
}
private void listboxVisits_SelectedIndexChanged(object sender, EventArgs e)
{
listboxVisits.FormattingEnabled = false;
int index = listboxVisits.SelectedIndex;
if (listboxVisits.SelectedItems.Count>0)
{
object object1 = listboxVisits.SelectedItems[0];
if (object1 is Delivery)
{
Delivery deliver = (Delivery)object1;
deliveryform.delivery = deliver;
deliveryform.ShowDialog();
}
else
{
Pickup pick = (Pickup)object1;// this is where error occur
pickupform.pickup = pick;
pickupform.ShowDialog();
}
}
this is the pickup class
public class Pickup
{
private string pickupname;
private string pickupaddress;
private Visit collects;
private Delivery sends;
private DateTime pdatetime;
private string dname;
private string daddress;
private DateTime dtime;
public string PickupName
{
get { return pickupname; }
set { pickupname = value; }
}
public string PickupAddress
{
get { return pickupaddress; }
set { pickupaddress = value; }
}
public string Dname
{
get { return dname; }
set { dname = value; }
}
public string Daddress
{
get { return daddress; }
set {daddress = value; }
}
public DateTime Pdatetime
{
get { return pdatetime; }
set { pdatetime = value; }
}
public DateTime Dtime
{
get { return dtime; }
set { dtime = value; }
}
public override string ToString()
{
return pickupname + " " + pickupaddress + " " + pdatetime.ToString()+" "+dname+" "+daddress+" "+dtime.ToString()+" Pickup ";
}
}
this is the visit class
public class Visit : Customer
{
private Customer requester;
private DateTime datetime;
private Delivery reciever;
private Pickup collect;
public DateTime DateTime
{
get { return datetime; }
set { datetime = value; }
}
private List<Pickup> picks = new List<Pickup>();
private List<Visit> visits = new List<Visit>();
private List<Delivery> deliver = new List<Delivery>();
public void addDeliver(Delivery de)
{
//adding new Delivery ToString the visit
deliver.Add(de);
}
public List<String> listofDeliver()
{
List<string> listofDeliver = new List<string>();
foreach (Delivery de in deliver)
{
String deAsString = de.ToString();
listofDeliver.Add(deAsString);
}
return listofDeliver;
}
public Delivery getDeliver(int index)
{
int count = 0;
foreach (Delivery de in deliver)
{
if (index == count)
return de;
count++;
}
return null;
}
public void addPick(Pickup pu)
{
picks.Add(pu);
}
public List<String> listofPicks()
{
List<string> listofPicks = new List<string>();
foreach (Pickup pu in picks)
{
String puAsString = pu.ToString();
listofPicks.Add(puAsString);
}
return listofPicks;
}
public Pickup getPicks(int index)
{
int count = 0;
foreach (Pickup pu in picks)
{
if (index == count)
return pu;
count++;
}
return null;
}
public List<String> LisitVisits()
{
List<String> visits = new List<string>();
visits.AddRange(listofDeliver());
visits.AddRange(listofPicks());
return visits;
}
public Visit getVisits(int index)
{
int count = 0;
foreach (Visit vis in visits)
{
if (index == count)
return vis;
count++;
}
return null;
}
public string VisitDetails()
{
return collect.PickupName + " " + collect.PickupAddress + " Pickup " + reciever.DeliveryName + " " + reciever.DeliveryAddress + " Delivery";
}
}