|
Apologies for the shouting but this is important.
When answering a question please:
- Read the question carefully
- Understand that English isn't everyone's first language so be lenient of bad spelling and grammar
- If a question is poorly phrased then either ask for clarification, ignore it, or mark it down. Insults are not welcome
- If the question is inappropriate then click the 'vote to remove message' button
Insults, slap-downs and sarcasm aren't welcome. Let's work to help developers, not make them feel stupid..
cheers,
Chris Maunder
The Code Project Co-founder
Microsoft C++ MVP
|
|
|
|
|
For those new to message boards please try to follow a few simple rules when posting your question.- Choose the correct forum for your message. Posting a VB.NET question in the C++ forum will end in tears.
- Be specific! Don't ask "can someone send me the code to create an application that does 'X'. Pinpoint exactly what it is you need help with.
- Keep the subject line brief, but descriptive. eg "File Serialization problem"
- Keep the question as brief as possible. If you have to include code, include the smallest snippet of code you can.
- Be careful when including code that you haven't made a typo. Typing mistakes can become the focal point instead of the actual question you asked.
- Do not remove or empty a message if others have replied. Keep the thread intact and available for others to search and read. If your problem was answered then edit your message and add "[Solved]" to the subject line of the original post, and cast an approval vote to the one or several answers that really helped you.
- If you are posting source code with your question, place it inside <pre></pre> tags. We advise you also check the "Encode "<" (and other HTML) characters when pasting" checkbox before pasting anything inside the PRE block, and make sure "Use HTML in this post" check box is checked.
- Be courteous and DON'T SHOUT. Everyone here helps because they enjoy helping others, not because it's their job.
- Please do not post links to your question into an unrelated forum such as the lounge. It will be deleted. Likewise, do not post the same question in more than one forum.
- Do not be abusive, offensive, inappropriate or harass anyone on the boards. Doing so will get you kicked off and banned. Play nice.
- If you have a school or university assignment, assume that your teacher or lecturer is also reading these forums.
- No advertising or soliciting.
- We reserve the right to move your posts to a more appropriate forum or to delete anything deemed inappropriate or illegal.
cheers,
Chris Maunder
The Code Project Co-founder
Microsoft C++ MVP
|
|
|
|
|
I have a project that needs the ability to modify dozens, hundreds, and potentially thousands of file modifications which are fairly intensive and affect associated resource files as well. To speed things up and maximize the ability to process multiple threads to take advantage of parallel processing I decided to use the System.Threads.Tasks.Parallel class to drive these file changes. There are a few things that I have learned and discovered along the way that I would like to better understand.
First, before I go any further, my project has a BIG need to track all changes in a log file that occur BEFORE they happen to minimize the risk of losing data when something goes wrong. That log file is then parsed for undo actions. This requires the chain of events to be tracked; and logging each change before it happens requires several sub-tasks that use .NET's await feature. A basic picture of the process used to change the files looks something like this:
public class MainFileType
{
internal async void DoSomeMajorChanges(RichTextboxBuilder builder, StreamWriter changeLog)
{
bool result;
await Task.Run(new Action(() => changeLog.LogAction(this))).ConfigureAwait(false);
await Task.Run(new Action(()=> result = coreFile.DoChanges())).ConfigureAwait(false);
builder.Control.BeginInvoke(new Action() builder.NotifyUser("Some Change Occurred", Color.Red));
foreach (ResourceFile file in this.AssociatedFiles)
{
await Task.Run(new Action(() => changeLog.LogAction(file))).ConfigureAwait(false);
await Task.Run(new Action(() => result |= file.DoChanges())).ConfigureAwait(false);
builder.Control.BeginInvoke(new Action() builder.NotifyUser("Some Change Occurred", Color.Blue));
}
return result;
}
}
This code is called by a UI that is shown any time a single or multiple files are modified. The UI regularly reports to the user:
1 public class ChangeManagerUI : Form
2 {
3 private bool processed;
4 object task;
5 StreamWriter parseableActionLog;
6
7 private void OnFormShown(object sender, EventArgs e)
8 {
9 if (!processed)
10 {
11 processed = true;
12 MainFileType file;
13 RichTextboxBuilder builder = null;
14 List<MainFileType> batch = task as List<MainFileType>;
15 Refresh();
16 if (batch != null)
17 {
18 RichTextboxBuilder.BeginConcurrentAppendProcess(this, batch.Count);
19 ReportCaption = "Conversion Progress";
20 progressBar.Visible = true;
21 progressBar.Maximum = batch.Count;
22 ConcurrentOutputManager.ConcurrentMode = true;
23
24 Task.Run(() =>
25 {
26 Parallel.For(0, batch.Count, i =>
27 {
28 file = batch[i];
29 builder = RichTextboxBuilder.BeginConcurrentAppend(i);
30
31 file.DoSomeMajorChanges(builder, parseableActionLog)
32 RichTextboxBuilder.EndConcurrentAppend(i);
33 });
34 });
35 if (builder != null)
36 {
37 builder.AppendNewLine();
38 builder.BeginColor(Color.Purple);
39 builder.AppendStyled("Batch Conversion Complete!", FontStyle.Bold);
40 builder.EndColor();
41 }
42 Finalize(false);
43 }
44 else
45 {
46 file = task as MainFileType;
47 ReportTextBuilder = new RichTextboxBuilder(this);
48 Finalize(file.DoSomeMajorChanges(mod, ReportTextBuilder).Result);
49 }
50 }
51 }
52 }
The things that I have noticed that I would like to understand are as follows:
1. If I remove the Task.Run( (line 24) that encapsulates the Parallel.For statement the program/UI locks up (stops responding) even though I am using ConfigureWait(false) in the await commands... I know that using await in the UI thread can lead to this kind of issue but as I understand, Parallel methods use separate threads.
2. Sometimes Parallel.For seems to run the action for the same item repeatedly rather than go to the next item. Do I need to explicitly code the increment? Because of this, I switched to the Parallel.Foreach method and that works more consistently.
3. I had a problem in that the code AFTER the Task.Run => Parallel.For block was run before the parallel tasks completed (which led to my discovery of 1). I fixed it by using an atomic integer that was initialized to the number of tasks and calling a method that decreased that number inside the Parallel.For each statement that would only run a block of code if the number hit zero. However, I would still like to know why this occurred and if there is another .NET mechanism for achieving the goal executing code after parallel tasks are completed built in.
|
|
|
|
|
Say for example,
I wanted to send an array of integers from my C++ exe to C# at runtime
|
|
|
|
|
Well I just said it. Now what?
|
|
|
|
|
Did you consider using sockets or (named) pipes? Or some other IPCs?
|
|
|
|
|
i tried using namedpipes it just sends and receives but, My goal is to pass the elements from C++ and get that Elements at runtime in C# and process them. Like, Get n inputs in c++ and process that n elements in C#.
Eg: I am entering 5 inputs, say 1,2,3,4,5 in C++
where c# should get that inputs and process ( eg: inputelement + 1 )
the output would be 2,3,4,5,6.
C++ file
#include <windows.h>
#include <iostream>
HANDLE fileHandle;
int main()
{
fileHandle = CreateFileW(TEXT("\\\\.\\pipe\\pipesample"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
const char* msg = "hello from c++\r\n";
WriteFile(fileHandle, msg, strlen(msg), nullptr, NULL);
}
C# File
static void Main(string[] args)
{
var namedPipeServer = new NamedPipeServerStream("pipesample", PipeDirection.InOut, 1, PipeTransmissionMode.Byte);
var streamReader = new StreamReader(namedPipeServer);
namedPipeServer.WaitForConnection();
Console.WriteLine($"read from pipe client: {streamReader.ReadLine()}");
namedPipeServer.Dispose();
}
modified 2hrs ago.
|
|
|
|
|
I use SQL CE as a database file in my project. I need to load hidden ID numbers into my datatable. What is the command for accessing ID in SQL CE?
|
|
|
|
|
There isn't a "command for accessing ID" specifically, it's just a field within your table, so you use a normal SELECT statement.
To fetch the last inserted IDENTITY value (if that is what you are using for the ID, and it probably should be that or a GUID) just issue a SELECT @@IDENTITY on the same Connection object without closing it first, as @@IDENTITY is local to the Session, and closing the Connection will clase the Session as well.
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Why would you do this? There is virtually never a good reason to do so.
Typically, this is done by noobs who think in terms of a single user using the database, never thinking of the possibility that more than one user can execute this same command at the same time and get the same answer. Now each instance of the code (and the person who wrote it) thinks they've got exclusive use of a number multiple people have.
|
|
|
|
|
Alex Dunlop wrote: What is the command for accessing ID in SQL CE? SELECT ID FROM table WHERE ...
|
|
|
|
|
I have used the following Class for saveing/reading DataGridView row and text color into/from an XML file. It works fine, but when I use column filters, all those color information got lost. Even when I remove the filters, there is no color in my texts/rows. (*** I use advanced DataGridView***)
My Class for load/save XML:
public static void WriteDataGridViewSettings(System.Windows.Forms.DataGridView dgv)
{
XmlTextWriter writer = new XmlTextWriter(Application.StartupPath + @"\MyGridColor.xml", null);
writer.WriteStartDocument();
writer.WriteStartElement(dgv.Name);
int LastRow = dgv.Rows.Count;
for (int i = 0; i < LastRow; i++)
{
writer.WriteStartElement("Row");
writer.WriteStartElement("CellColor");
writer.WriteString(dgv.Rows[i].DefaultCellStyle.BackColor.ToArgb().ToString());
writer.WriteEndElement();
writer.WriteStartElement("TextColor");
writer.WriteString(dgv.Rows[i].DefaultCellStyle.ForeColor.ToArgb().ToString());
writer.WriteEndElement();
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
}
public static void ReadDataGridViewSettings(System.Windows.Forms.DataGridView dgv)
{
XmlDocument xmldoc = new XmlDocument();
XmlNodeList xmlnode;
FileStream fs = new FileStream(Application.StartupPath + @"\MyGridColor.xml", FileMode.Open, FileAccess.Read);
xmldoc.Load(fs);
xmlnode = xmldoc.GetElementsByTagName("Row");
for (int i = 0; i <= xmlnode.Count-1; i++)
{
int cellcolor = int.Parse(xmlnode[i].ChildNodes.Item(0).InnerText.Trim());
int textcolor = int.Parse(xmlnode[i].ChildNodes.Item(1).InnerText.Trim());
if (cellcolor != 0)
{
dgv.Rows[i].DefaultCellStyle.BackColor = Color.FromArgb(Convert.ToInt32(cellcolor));
dgv.Rows[i].DefaultCellStyle.ForeColor = Color.FromArgb(Convert.ToInt32(textcolor));
}
else
{
dgv.Rows[i].DefaultCellStyle.BackColor = Color.White;
dgv.Rows[i].DefaultCellStyle.ForeColor = Color.Black;
}
}
fs.Close();
}
How can I solve this problem?
modified yesterday.
|
|
|
|
|
What you said is: it doesn't work; filter or no filter.
It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it.
― Confucian Analects: Rules of Confucius about his food
|
|
|
|
|
Filtering causes redrawing of all the rows and my color information is lost.
Of course, I need to use a hidden column for assigning an index code for each row, so I save the index color and load it. In this way, I can relocate those color information when using filtering.
|
|
|
|
|
I'm "guessing" that filtering is creating a "new" uncolored view; you might try and (re)color after applying the filter.
(It's a guess, so the troll need not get excited)
It was only in wine that he laid down no limit for himself, but he did not allow himself to be confused by it.
― Confucian Analects: Rules of Confucius about his food
|
|
|
|
|
Did you say that I'm trolling?
I just want to get help and solve my problem. It's all.
|
|
|
|
|
No, he didn't call you a troll.
He's making a comment in an attempt to head off the trolls.
|
|
|
|
|
thank you for help. the previous explanation does make sense but when about instance how yo accesss it from other class? thank you
class felhasznalo
{
adatlista adat = new adatlista();
foreach (string elem adat.lista)
{
}
}
|
|
|
|
|
Every time you "new up" adatlista , you are creating a new list, separate from any other instance.
So, if you new up two lists and add items to the one of them, you will NOT see those items in the other list.
|
|
|
|
|
thank you for help. I don't want to create new list just access the existing one from other classes possibly with foreach or for loop, recoed by record, thank you.
|
|
|
|
|
You might want to try something like this:
class felhasznalo
{
private adatlista adat = new adatlista();
public adatlista items { return adat; }
} You can now access adat from outside your class.
The simple idea behind this concept is that you are exposing a property that allows external access to members of your class, but does it in a controlled manner. This is why I wrapped this in a property. You could, just make adatlista a public field and allow classes access to the public field but that's a separate debate.
modified 2 days ago.
|
|
|
|
|
Hi
thank you for help.
In my modified instance I placed recordlist is a separate class to be able to access it from various classes but access issues occured. please help me to access the record list type thank you.
<pre>using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections.Generic;
namespace metjelentes
{
class adatok
{
public string telepules = " ";
public string ido = " ";
public string szeliranyes_erosseg = " ";
public int homerseklet = 0;
}
class adatlista
{
public List<adatok> lista = new List<adatok>();
}
class beolvasas
{
public void beolvas()
{
string olvas = @"c:\Users\Public\textfiles\tavirathu13.txt";
using (StreamReader sr =new StreamReader(olvas, Encoding.Default))
{
int db = 0;
while (!sr.EndOfStream)
{
string sor = sr.ReadLine();
string[] elemek = sor.Split(' ');
adatlista.lista.Add(new adatok());
adatlista.lista[db].telepules=elemek[0];
adatlista.lista[db].ido = elemek[1];
adatlista.lista[db].szeliranyes_erosseg = elemek[2];
adatlista.lista[db].homerseklet = Int32.Parse(elemek[3]);
db++;
}
Random rd = new Random();
int rand_num = rd.Next(1, db);
}
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
|
|
|
|
|
adatlista is not a variable, it's a class:
class adatlista
{
public List<adatok> lista = new List<adatok>();
}
So you can't access it's list like this:
adatlista.lista.Add(new adatok());
Why not?
Because you need an instance of the class to work with ...
Let's ignore computers for a moment, and talk about cars.
We both have a car: the same make, the same model, the same colour, the same engine, the same age.
I give you a ride to the shops, and while in my car, you put your mobile phone in the glove box.
When you get home again, you need you mobile so you go to your car and open the glove box. Is your phone there?
No, of course not - it's in the glove box in my car. You know that it can only be accessed my opening my car, opening that glove box and reaching in for your phone, because you know that the two vehicles are separate instances of the particular class of black Mercedes A-class cars that they made in 2006.
You know that despite being outwardly identical, they are very different vehicles and that to do anything with them, you have to use the right instance. You want to drive to the airport, you take your car, not mine!
Classes and instances also matter in computers: Car is a class, but "your car" is a Car type variable which holds a Car class instance, "my car" is another Car type variable which holds a different Car class instance.
So you access the List in your adatlista class, you need to create an use a specific instance of that class:
adatlista adat = new adatlista();
adat.lista.Add(new adatok());
There is a way to get what you wrote to work, but ... it's probably something you haven't really covered yet: static classes - so I won't go into that. It's pretty important that you understand instances anyway!
Does that make sense?
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
where view doesn't know about presenter, just raises events... presenter knows views controls (idk how to do the one where to make the presenter as if it was calling a console, for unit tests...)
1. should view contain ui logic, or all logic is in the presenter?
2. if view event is raised, should presenter call view's method or should presenter do the magic and tell view what control to change?
3. We're using a single form like sidebar with many usercontrols in the main panel, should presenters be separate from each other? even the main one?
4. When calling dispose to save resources, what happens to the presenter it's associated to? i get an error because the view is not there because deleted, check if null, create one with unity? what lifetime manager? should i dispose presenter too? how do i recreate it then if yes?
5. unity what lifetime manager is best? it's in the program.cs
thank you all in adv )
|
|
|
|
|
Hi
I try to load txt file data in record list in object but error msg stops code running. the error is below.
Severity Code Description Project File Line Suppression State
Error CS1955 Non-invocable member 'StreamReader' cannot be used like a method. metjelentes C:\Users\Dell\source\repos\metjelentes\metjelentes\Program.cs 21 Active
<pre>using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections.Generic;
namespace metjelentes
{
class adatok
{
public string telepules = " ";
public string ido = " ";
public string szeliranyes_erosseg = " ";
public int homerseklet = 0;
}
class beolvasas
{
public void beolvas()
{
string olvas = @"c:\Users\Public\textfiles\tavirathu13.txt";
using (StreamReader sr = StreamReader(olvas, Encoding.Default))
{
List<adatok> lista = new List<adatok>();
while (!sr.EndOfStream)
{
string sor = sr.ReadLine();
string[] elemek = sor.Split(' ');
lista.Add(new adatok());
}
}
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
|
|
|
|
|