Exception while saving data into a txt file - c#

I am trying to write the data to a file, and the data is continuously updated every 100ms. So when I click save button then
System.InvalidOperationException: Collection was modified enumeration operation may not execute.
error comes up. Upon my search there is solutions to this probelm if there is Foreach loop but in my case there is no Foreach loop.
Bellow is the code I used
File.WriteAllLines(fileDialog.FileName,
RawDataFromSerialPort.Select((v, i) => $"{i + 1} Raw data is -->, {v.ToString()}"));

I'd say your serial port is still receiving data on a background thread whilst you're trying to read from the raw data collection, I'd suggest making a copy of the collection and then writing the copy out to the file.
Try using the syncroot property on the collection while doing the copy.
https://learn.microsoft.com/en-us/dotnet/api/system.array.syncroot?view=netframework-4.7.2

Check the stacktrace as well, there you'll find the drill down of the call stack where eventually a foreach-(like)loop is used.
Click on the 'view details' link, expand the $exception node and look for the StackTrace field.

The problem was that the List name I was accessing was wrong so correcting the list name RawDataFromSerialPort made my problem solved

Related

Realtime updating textfield messages in winforms

I have a service that add items to a class and then serialize a class into a file.
Then I need to create a simple form C# with a textfield (multiline) showing realtime from the deserialized file.
I will have timer every second that will read my List of a property of the class and show it in a textfield.
My question here is:
Is there a way that instead of reading again and again the file I can just get the latest rows added and just append to the textfield?
var file = File.OpenRead("abc.txt");
file.Seek(1000, SeekOrigin.Begin);
Reading a file, use "Seek" to skip old data.
just a suggestion:
I think, you should rather use some sort of message queue for this purpose.
Again per your post, instead of directly fetching from file, it would be good if you rather store the deserialized content in a stack. That way, you can always get the content from top of the stack.

In Umbraco 6, what is the best way to save and publish a list of nodes with ContentService?

I'm writing a simple function that updates/creates nodes from an XML data-source (about 400 nodes) and I'm wondering what the best way to save and publish all the nodes is. I've noticed that you can Save a list of nodes but there's no SaveAndPublish equivalent.
Should I just iterate over the list and call SaveAndPublish for each node or is there a better way? If there is an alternative, is there any difference in terms of performance?
Any answers would be greatly appreciated!
You are correct there is no Publish or SaveAndPublish option that takes in an IEnumerable like the Save method. It could be handy as it could save some lines of code.
The most valid option currently to achieve what you want is to do the following.
var cs = ApplicationContext.Current.Services.ContentService;
foreach(var content in yourListOfContentItems)
{
cs.SaveAndPublish(content);
}
Saving your list before publishing by calling Save method isn't really going to make any differences to you as if Umbraco detects there is new content in your list it processes each individually. And from what I can tell doing that and then calling Publish after is not going to save you any cycles either because the Publish method calls the same SaveAndPublishDo method that SaveAndPublish calls. So might as well go straight for the end result.

MailItem.CreationTime is Read Only - Any Workarounds?

I recently posted a question about saving an email once it's sent - I have just about everything working, except for one small detail. Basically, I am able to catch an email right before it sends, and do whatever I want with it - in my case, save it. However, if you try to access that email's CreationTime attribute, it returns January 1st 4501 at 12AM. This is most likely because it hasn't actually been 'created' yet, in that it will be created in the Sent items folder as soon as my code finishes executing and it actually sends.
I'd like to leave this MailItem, which is about to be sent, untouched. I would like to duplicate it, change the CreationTime attribute of the duplicate to DateTime.Now, then save the duplicate, then allow Outlook to continue sending the original. However, when I attempt to modify the CreationTime, I get an error that that attribute is read-only. Is there any way to 'break into' it? Or any way to force a write or something?
A better approach is attaching to the sent items Folder.ItemAdd so you can save messages after they have been sent instead of before - that way your MailItem.CreationTime should be accurate. This may or may not be an option for you but could alleviate the issue.
Outlook.Folder sentItems = ThisAddIn.Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail) as Outlook.Folder;
sentItems.Items.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(sentItems_ItemAdd);
// ...
void sentItems_ItemAdd(object Item)
{
var msg = Item as Outlook.MailItem;
msg.SaveAs(yourPath, Outlook.OlSaveAsType.olMSG);
}
Note: You need to handle proper COM resource disposal and error handling.

Algorithm advice Unique value and Edit

I have an empty list accepting string values.
When an element will be added I need to check if a string with the same value already exist in the list, if yes an exception should occur (ROLE 1 only unique value in the array).
Now I would like a user lets edit element in the list, if the new edited value is unique fine, otherwise an exception should occur.
My problem is: let's imagine the user select the edit element but actually does not change the value when sending to the server. The system should detect that the element has not being changed and accept the value (even if is already present in the list).
PS I simplificate the problem, I'm actually using MVC and EF & linq. My problem is that I cannot check if the value inserted has been edited or not in the interface of my application.
Could you help me out to find an effective algo to solve this problem? Thanks
Let me know if the question is enough clear or you need more information
This is my solution:
Let the client check if the text was modified. If not, tell the server there was no modification. If this is not possible have the client send both the orinigial text and the modified text, and then the server will be able to check if it was modified. (if it wasn't then there is no need to touch the data you are storing). This applies for both desktop and web enviroments.
Preferibly don't use a list, use a set (may be a hashset). The set will only allow to have each item once. In case you can't I guess you can continue using the list. If I understand correctly you are using a database, so if you could interface with the database engine directly instead of syncing the list (or set) your application will have a performance boost.
Convert the edition of the list/set into a add-remove pair (instead of setting the item). Have it check if the list/set contains the new value before doing any modification. If the new value is already present then you can throw an exception or send a message to the client (or whatever is more appropiate for your enviroment).
You may want to sync the access to your list/set, keep it simple: use a lock (Monitor). I would consider a read-write lock, but that is complicating things while you are learning. [If you interface directly with the database engine, you can let it handle that instead]. Note: there is no need for this if you will only have one single client... ever (unless that single client can send multiple concurrent requests... :P).

SvnClient.GetStatus(path, args, statuses) returning 0 for versioned file?

I have written a simple C# app using SharpSVN to query the status of a file prior to attempting an add. The examples I've seen in various places for this very purpose involve calling the GetStatus method of the SvnClient, passing in the full path and an out parameter to a collection of SvnStatusEventArgs.
My understanding is that, for a file, GetStatus should return with an SvnStatusEventArgs collection having a count of exactly one, with a status among NotVersioned, Missing, Normal, and so on.
In my application, my call to GetStatus to a file under source control returns a Collection count of zero.
SvnClient foo = new SvnClient();
Collection<SvnStatusEventArgs> statuses;
foo.GetStatus("C:\\Temp\\svnu\\Program.cs", new SvnStatusArgs {Depth = SvnDepth.Empty}, out statuses);
The value of statuses.Count is zero, when I am expecting 1 with a statuses[0].LocalContentStatus value of Normal. Is this expectation incorrect? For a call to a path referencing a file not in source control, the call works with a status[0].LocalContentStatus value of NotVersioned.
The path is verified to be a working copy, and the file Program.cs is, in fact, enlisted in Subversion. I'm running SharpSVN version 1.7005.2163.13448 and VS2010.
Many thanks in advance for clearing up my obvious confusion.
EDIT Some more info: After modifying, but not committing, Program.cs, this same code snippet now returns a single status value with LocalContentStatus of "Modified." After committing the file, the original behavior (no returned status value) returned.
Apologies for the delay in getting the answer posted based on Bert Huijben's feedback. I'm posting the answer here just FYI for everyone's benefit.
Modifying the original GetStatus call to set the RetrieveAllEntries property of the SvnStatusArgs object did, in fact, solve this problem, and causes local (but uninteresting :) ) copies of files to have a return status count of 1, with a .LocalContentStatus of "Normal," as desired.
foo.GetStatus("C:\\Temp\\svnu\\Program.cs", new SvnStatusArgs {Depth = SvnDepth.Empty,
RetrieveAllEntries = true}, out statuses);
Many thanks.

Categories