I've just started using your ImapX library to retrieve and read mails from gmail.
Now, everything is working fine and it's a great library.
However, when i'm trying to mark a mail read using the Message.Process() option, it returns the IndexOutOfRangeException.
private void Start()
{
int amountRead = 0;
failedMessages.Clear();
foreach(string origin Properties.Settings.Default.MailOrigins)
{
IMailOriginAdapter adapter = MailOriginFactory.CreateMailOriginContainer(origin);
foreach (ImapX.Message message in adapter.Messages())
{
if (SendWebRequest(url))
{
message.Process();
amountRead++;
Dispatcher.BeginInvoke(new MethodInvoker(delegate
{
this.btnStart.Content = "Read [" + amountRead + "/" + GmailUser.Instance.Messages.Count + "]";
}));
}
else
{
failedMessages.Add(message);
}
}
System.Windows.MessageBox.Show(adapter.GmailFromEmail() + " reading completed.");
}
}
Hopefully someone's capable of helping me with this problem which i've had now for over then a month..
Thanks in advance.
Yours Sincerely,
Larssy1
Related
I am creating a C# .NET Mono application to read logs in from a text file and display them in a listview. The logs are stored in JSON format so they can be parsed easily and be displayed as subitems in the listview.
Picture of the working ListView run on Windows
My application is working correctly when I run the application on windows, however when I run it on the raspbian OS using mono none of the items in the listview are shown. I know that the logs are being read correctly from the text file on both Windows & Linux, as I have logged them to the console for debugging purposes. I have also confirmed that the logs have been copied into the ListViewItem "eachRow" correctly by logging it to the console as well.
I am hoping to find the problem that is causing the ListView Items to not be displayed when run on Raspbian. Due to the fact that I have the data stored correctly all the way up until it is added to the listview, I believe my problem is with the redrawing of the screen/listview.
This is the code I am using to Add each JSON item to the listview.
private void AddLogsToScreen()
{
//Create a copy of the current logList Stack
LogMutex.WaitOne();
Stack<string[]> logListCopy = new Stack<string[]>(new Stack<string[]>(LogList));
Console.WriteLine("LLC: " + string.Join(" , ", logListCopy.Peek()));
LogMutex.ReleaseMutex();
if (HUBsLogsListView.InvokeRequired)
{
HUBsLogsListView.Invoke(new MethodInvoker(delegate
{
MessageBox.Show("Invoke Begin Update");
HUBsLogsListView.BeginUpdate();
}));
}
else
{
MessageBox.Show("Begin Update");
HUBsLogsListView.BeginUpdate();
}
var allItemsToAdd = new List<ListViewItem>();
int totalLogs = logListCopy.Count;
for (int logNum = 0; logNum < totalLogs; logNum++)
{
string[] log = logListCopy.Pop();
string[] deepLogCopy = new string[8];
// Copy to avoid messing up original
log.CopyTo(deepLogCopy, 0);
deepLogCopy[2] = DateTime.Parse(log[2]).ToString("dd-MM-yyyy, hh:mm:ss tt");
ListViewItem eachRow = new ListViewItem(deepLogCopy);
Console.WriteLine("ListViewItem eachRow: " + eachRow.SubItems[0] + " , " + eachRow.SubItems[1] + " , " + eachRow.SubItems[2] + " , " + eachRow.SubItems[3] + " , " + eachRow.SubItems[4] + " , " + eachRow.SubItems[5] + " , " + eachRow.SubItems[6] + " , " + eachRow.SubItems[7]);
if (deepLogCopy[4] == "3") //Warning
{
eachRow.BackColor = Color.Yellow;
}
else if (deepLogCopy[4] == "4") //Error
{
eachRow.BackColor = Color.Red;
}
allItemsToAdd.Add(eachRow);
}
if (HUBsLogsListView.InvokeRequired)
{
HUBsLogsListView.Invoke(new MethodInvoker(delegate
{
ListView.ListViewItemCollection lvic = new ListView.ListViewItemCollection(HUBsLogsListView);
lvic.AddRange(allItemsToAdd.ToArray());
HUBsLogsListView.EndUpdate();
}));
}
else
{
ListView.ListViewItemCollection lvic = new ListView.ListViewItemCollection(HUBsLogsListView);
lvic.AddRange(allItemsToAdd.ToArray());
HUBsLogsListView.EndUpdate();
}
}
I can't come up with a reason why this function is acting differently, with the same files, on Windows compared to running on Linux using mono. I am not as experienced writing .NET programs using mono, so any and all help is appreciated.
Does anyone have any idea what could be the problem? Thanks!
I am trying to write some string to a file, and here is the code:
private static void WriteSelfDefinedFile(string msg)
{
ArrayList logTypes = SelfDefinedLogRule(msg);
// New some StreamWriter here
StreamWriter[] sws = new StreamWriter[selfDefinedLogFileName.Length];
for(int i = 0;i<selfDefinedLogFileName.Length;i++)
{
sws[i] = new StreamWriter(selfDefinedLogDir + selfDefinedLogFileName[i], true);
Debug.Log("111");
}
// It is writting here, not important for this question,I think.
foreach(SelfDefinedLogType temp in logTypes)
{
int index = (int)temp;
foreach (SelfDefinedLogType n in Enum.GetValues(typeof(SelfDefinedLogType)))
{
if(temp == n && sws[index]!=null)
{
sws[index].WriteLine(System.DateTime.Now.ToString() + ":\t"+ msg);
break;
}
else if(sws[index] == null)
{
LogError("File " + selfDefinedLogFileName[index] + " open fail");
}
}
}
// Close the StreamWrite[] here
for(int i=0;i<selfDefinedLogFileName.Length;i++)
{
sws[i].Close();
Debug.Log("222");
}
}
When the client is sending msg to server or server replying some msg to client, this funtion will be called to write some message to some files.
And unity throws the IOException:Sharing violation on path D:\SelfDefinedLogs\SentAndReceiveMsg.txt, sometimes. I mean, it doesn't happened everytime I write.
I have closed all the opened streamWriter at the end of the funtion, but the problem still come up.I am really confused.I will be grateful if anybody gives some solutions to this problem.
For a couple of days, I have puzzled about how to do this in the best way possible. I created a form application like so:
I gave the name "WiFi Hacker" for giggles. But my question is, why does Visual Studio give me this error after a couple minutes using the program?
Additional information: Type 'NativeWifi.Wlan+WlanReasonCode' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed.
I am using NativeWifi for my program, and the code for logging networks is as follows:
WlanClient client = new WlanClient();
private void wifilister()
{
foreach (WlanClient.WlanInterface wI in client.Interfaces)
{
foreach (Wlan.WlanAvailableNetwork network in wI.GetAvailableNetworkList(0))
{
Wlan.Dot11Ssid ssid = network.dot11Ssid;
string networkName = Encoding.ASCII.GetString(ssid.SSID, 0, (int)ssid.SSIDLength);
if (wifis.Contains(networkName) == false)
{
//Name
ListViewItem item = new ListViewItem(networkName);
wifis.Add(networkName);
listBox1.Items.Add(networkName);
//Encryption Type
item.SubItems.Add(network.dot11DefaultCipherAlgorithm.ToString());
wifis.Add(network.dot11DefaultCipherAlgorithm.ToString());
//Signal
item.SubItems.Add(network.wlanSignalQuality + "%");
wifis.Add(network.wlanSignalQuality + "%");
//Logged Time
item.SubItems.Add(DateTime.Now.ToString("T"));
wifis.Add(DateTime.Now.ToString("T"));
listView1.Items.Add(item);
label2.Text = "Networks: " + (wifis.Count / 4).ToString();
}
if (checkBox2.Checked)
{
label1.Text = track;
if (Encoding.ASCII.GetString(ssid.SSID, 0, (int)ssid.SSIDLength) == track)
{
label1.Text += " " + network.wlanSignalQuality + "%";
}
}
}
}
I got most of this off a tutorial from YouTube, but after it logs more than about 40 different networks in the List, it seems to give that weird error about
'NativeWifi.Wlan+WlanReasonCode'.
This annoyed me, is there a way around it?
I have simple code to parse HTML with HtmlAgilityPack and upload results to SQL data server. The thing is when I am using foreach loop it is working properly. I wanted to try the Parell for each loop. I saw, that the scraping is going faster, but I am getting (not everytime) stack overflow exception. Can you look on the code and tell me why?
//for each link object
Parallel.ForEach(link, _link =>
{
pageNumber=0;
position=1;
//try to load every single page number
while (true)
{
//load page's html
siteHtml = web.Load(_link.LinkUrl + "?page=" + pageNumber);
try
{
doc.LoadHtml(siteHtml.DocumentNode.SelectNodes("//section[#class='answers']")[0].InnerHtml);
comments = doc.DocumentNode.SelectNodes("//singleAnswer");
foreach (HtmlNode _comments in comments)
{
HtmlAgilityPack.HtmlDocument HtmlPage2 = new HtmlAgilityPack.HtmlDocument();
HtmlPage2.LoadHtml(_comments.InnerHtml)
commentId = Convert.ToInt32(_comments.GetAttributeValue("id", ""));
commentValue = (HtmlPage2.DocumentNode.SelectNodes("//p[#class='content']")[0].InnerText);
if (commentValue.Contains(_link.Keyword))
{
sql.updateComment(_link.LinkId, commentValue);
_link.Position = position;
_link.MyCommentId = commentId;
goto NextLink;
}
position++;
}
}
catch
{
}
if (!siteHtml.DocumentNode.InnerHtml.Contains(#"class=""pagingx"" rel=""nextPage"">"))
{
break;
}
pageNumber++;
}
NextLink:;
groupBox1.Invoke(new Action(delegate ()
{
groupBox1.Text = "Link's statistics (" + finished + "/" + linksUrlElements + ")";
}));
});
I also saw that CPU usage is much higher with Parallel for each instead of for each
Alright, The following code I've had in production for over a year with no changes. It has been working quite well. Within the past month more then a handful machines report that the xml documents are completely empty. They do not even contain a xml header . I cannot duplicate the files suddenly being empty, nor can i suggest a way for it to happen. I am hoping someone has had a similar issue that they solved.
Most of the machine that have been using this code have been using it for about a year, if not more. The empty files used to have data and lists in them.The files do not serialize at the same time. The save / serialize one after the other before the program exits.
My questions:
is it possible for the code below to create an empty file?
What else would cause them to be suddenly empty?
Has anyone else had issues with XML-serializer in the past month? (This problem has only happened in the past month on builds that have been stable for 3+ months.)
If you have questions or i missing something ask please. There also is a wide variety of types that i serialize... so if you can imagine it I probably have something similar that gets serialized.
public class BackEnd<T> {
public string FileSaveLocation = "this gets set on startup";
public bool DisabledSerial;
public virtual void BeforeDeserialize() { }
public virtual void BeforeSerialize() { }
public virtual void OnSuccessfulSerialize() { }
protected virtual void OnSuccessfulDeserialize(ListBackEnd<T> tmpList) { }
protected virtual void OnDeserialize(ListBackEnd<T> tmpList) { }
public virtual void serialize()
{
if (DisabledSerial)
return;
try
{
BeforeSerialize();
using (TextWriter textWrite = new StreamWriter(FileSaveLocation))
{
(new XmlSerializer(this.GetType())).Serialize(textWrite, this);
Debug.WriteLine(" [S]");
textWrite.Close();
}
OnSuccessfulSerialize();
}
catch (Exception e)
{
Static.Backup.XmlFile(FileSaveLocation);
Log.ErrorCatch(e,
"xml",
"serialize - " + typeof(T) + " - " + (new FileInfo(FileSaveLocation)).Name);
}
}
public virtual object deserialize(TextReader reader)
{
if (this.DisabledSerial)
return false;
ListBackEnd<T> tmp = null;
this.BeforeDeserialize();
if (reader == null && !File.Exists(this.FileSaveLocation))
{
Log.Write(Family.Error,
"xml",
"deserialize - " + this.GetType() + " - file not found. " + (new FileInfo(FileSaveLocation)).Name);
}
else
{
try
{
using (TextReader textRead = ((reader == null) ? new StreamReader(this.FileSaveLocation) : reader))
{
tmp = (ListBackEnd<T>)this.get_serializer().Deserialize(textRead);
Debug.WriteLine(" [D]");
textRead.Close();
}
OnSuccessfulDeserialize(tmp);
if (tmp != null)
{
this._Items = tmp._Items;
this.AutoIncrementSeed = tmp.AutoIncrementSeed;
if (this._Items.Count > this.AutoIncrementSeed && this._Items[0] is ItemStorage)
this.AutoIncrementSeed = this._Items.Max(item => (item as ItemStorage).Key);
}
}
catch (Exception e)
{
// this only copies the file
Static.Backup.XmlFile(FileSaveLocation);
// this only logs the exception
Log.ErrorCatch(e,
"xml",
"deserialize - " + typeof(T) + " - " + (new FileInfo(FileSaveLocation)).Name);
}
}
//{ Log.ErrorCatch(e, "xml", "deserialize" + this.GetType() + " - " + this.FileSaveLocation); }
OnDeserialize(tmp);
tmp = null;
return (_Items.Count > 0);
}
}
We've encountered this problem several times at $WORK, with the symptom being an empty file of the correct size but filled with zero bytes.
The solution we found was to set the WriteThrough value on the FileStream:
using (Stream file = new FileStream(settingTemp, FileMode.Create,
FileAccess.Write, FileShare.None,
0x1000, FileOptions.WriteThrough))
{
using (StreamWriter sw = new StreamWriter(file))
{
...
}
}
The only reason I can think that this would happen is that this line:
(new XmlSerializer(this.GetType())).Serialize(textWrite, this);
throws an exception and the textwriter is created and disposed without ever having anything written to it. I'd look at your log for errors.
What does
Static.Backup.XmlFile(FileSaveLocation);
do?