|
Hi all,
One of my windows application I want to read a text file and add the result into a list view.
What I've done is read the text file in a background thread. It's fine. But from the thread I cannot add data into the UI thread, basically to the list view. What can I do.
When I try to work on with the UI controls I got the following exception.
Cross-thread operation not valid: Control 'listView1' accessed from a thread other than the thread it was created on.
Can someone give me a comment on this.
If I don't use a background thread, while the text file read the UI is completely stuck and not responding.
I appreciate your help all the time...
CodingLover
|
|
|
|
|
You need to use BeginInvoke[^]/Invoke for cross thread changes.
|
|
|
|
|
Thanks for the comment.
I've solved it using the avoiding the illegal thread calls of the form, with the background thread.
I appreciate your help all the time...
CodingLover
|
|
|
|
|
Hi all,
I have written an XML handler class for a project I am currently writing and all the read and write methods do what I expect of them.
It then occurred to me that the main code in this class should be able to do something along the lines of:
section("firstlevel")
{
section("secondlevel")
{
WriteValue("value1", 1);
WriteValue("value2", 2);
}
}
where "section" is a keyword of my XML class and the open and close curly brace calls XmlWriter.WriteStartElement() and XmlWriter.WriteEndElement() respectively creating section tags "firstlevel" and "secondlevel" as they do.
Google searches tend to turn up statements such as "use the keyword new" etc..
Just wondering on where to start on creating a keyword and if there is a suitable example I can follow to get started. Or if I can even do something like this at all.
Regards,
David Bailey.
|
|
|
|
|
You can't create a keyword, but of course you can create classes and methods. I'm wondering whether or not you are describing a recursive method to write out an XML document.
My preferred method of writing XML is by using an XmlDocument and calling its WriteTo method.
More detail would be required to help further.
|
|
|
|
|
Hi PIEBALDconsult,
Thanks for your reply.
No, I was not describing a recursive method. I was aiming for something that was easy to read and configure as well as being specific to a particular class.
What I was trying for was to override the curly braces, but apparently this is not allowed either. The curly braces would then have acted upon the new class keyword "section" to open and then close that section. The WriteValue("value1", 1) method would then place a value into the section.
using the above sample code, I would then get the output along the lines (minus the headers etc):
<firstlevel>
<secondlevel>
<value1>1</value1>
<value2>2</value2>
</secondlevel>
</firstlevel>
The "section" could be a method, granted, but then how do I complement it with curly braces such that
section("firstlevel")
{
}
could replace
openSection("firstlevel");
.
.
closeSection();
where openSection/closeSection are defined something like (just rough pseudo code)
XmlWriterSettings settings = new XmlWriterSettings();
XmlWriter writer = XmlWriter.Create(SettingsFile, settings);
private void openSection(string sect)
{
writer.WriteStartElement(sect);
}
private void closeSection()
{
writer.WriteEndElement();
}
I hope this makes sense. There is no great loss if I cannot achieve what I am aiming for. But it would be really good if it could be achieved.
Thanks again,
David.
|
|
|
|
|
Sounds like you need a DSL, Domain Specific Language. The purpose of a DSL is to provide a language that models your business needs better than a general language like C#, if such a thing is needed. You can find more here:
Domain Specific Language @ Wikipedia
DSL in Visual Studio
|
|
|
|
|
Thanks for everyone's input. I might put this into the "Too hard basket" for the moment.
-David.
|
|
|
|
|
Hello everyone,
I am looking for a sample, which could let me deserialize an XML stream encoded in UTF-8 into a field of a class. More specifically, I have a class like,
class Foo
{
string abc;
byte[] bcd;
}
and abc maps to XML element "Abc" and bcd maps to XML element "Bcd", and I want to get the stream for bcd and retrieve bytes (from XML stream for related element "Bcd" directly) to manipulate manually/in a customized way.
I am looking for a sample, but failed, could anyone help to point me to a related sample or wrote some pseudo code?
thanks in advance,
George
|
|
|
|
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;
[Serializable]
class Customer {
public string name;
public long id;
}
class Test{
static void Main(string[] args) {
ArrayList list = new ArrayList();
Customer cust = new Customer();
cust.name = "Charles Darwin";
cust.id = 10;
list.Add(cust);
cust = new Customer();
cust.name = "Isaac Newton";
cust.id = 20;
list.Add(cust);
foreach(Customer x in list){
Console.WriteLine("{0} : {1}", x.name.ToString(), x.id.ToString());
}
Console.WriteLine("Saving Customer list");
FileStream s = new FileStream("cust.txt", FileMode.Create);
SoapFormatter f = new SoapFormatter();
f.Serialize(s, list);
s.Close();
Console.WriteLine("Restoring to New List");
s = new FileStream("cust.txt", FileMode.Open);
ArrayList list2 = (ArrayList)f.Deserialize(s);
s.Close();
foreach(Customer y in list2){
Console.WriteLine(y.name + ":" + y.id);
}
}
}
//You have to reference in using System.Runtime.Serialization.Formatters.Soap;
//just right click on the reference folder and click add. Its under the web tab.
//Let me know if this helps
|
|
|
|
|
Thanks Zap-Man!
I do not think your reply is directly related to my question. Here is a little more response.
The XML is SOAP reaponse from server, in the response there is one response XML element (element Bcd in my sample) which is encoded by UTF-8 from server side, but since Http Web Services will use base64 at client side, so each time I receive such "bytes" at client side and the automatically generated web services proxy will throw exception says invalid XML element in base64 encoding. So, I am thinking about how to overwrite the default using base64 encoding to decode the bytes, and this is why I ask this question. If there could be a way to accept stream or something similar represents the on-wire bytes of the related response elements (Bcd in my sample) and let me manipulate, it will be so great!
regards,
George
|
|
|
|
|
Another question for today lol,
Is it possible to make the enter(return) key call the Validated event of a textbox? In other words, I have stuff happening when a user presses the tab key with text entered in the textbox, and i want the same stuff to happen if he presses the enter key. I searched msdn and coudn't find anything...any ideas? Thanks =)
Yup, I'm a NEWB
|
|
|
|
|
Try something like this:
public partial class Form1 : Form
{
List<button> buttons = new List<button>();
int counter = 0;
int maxButtons = 10;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if (counter < maxButtons)
{
Point loc = new Point();
buttons.Add(new Button());
loc.X = ClientRectangle.X + (counter * 50);
loc.Y = ClientRectangle.Y + (counter * 50);
buttons[counter].Location = loc;
buttons[counter].Name = "Input name with some variable?";
buttons[counter].Click += new EventHandler(ButtonClickEvent1);
this.Controls.Add(buttons[counter]);
counter++;
}
else
{
throw(new Exception("Too many buttons"));
}
}
catch (Exception ex)
{
MessageBox.Show("A system error ocurred:\n" + ex.Message, "System Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
void ButtonClickEvent1(object sender, EventArgs e)
{
}
void ButtonClickEvent2(object sender, EventArgs e)
{
}
}</button></button>
|
|
|
|
|
Hi “High Octane”
YES YOU CAN! Been there and done it!
I am also a NEWB, I am also new to pasting replies on the code-project.
If (matter.resolved==false)
{
Read on!
}
I am assuming you are want to use the return/enter key to move from one textbox to another but validating the data that has been entered.
A group of textboxes for example? with the "Type in data then press enter" option?
I am not sure how you are validating your data but assume that you use the “Causes validation” property of the textbox. Personally I have a separate validation method fired by the leave event of the textbox.
I also use a keydown event for the same textbox.
In that event I call the "SelectNextControl" method once the return key was pressed.
The "SelectNextControl" method does what it says on the tin, but There are five parameters to it.
These are:-
Ctl
The Control at which to start the search.
forward
true to move forward in the tab order; false to move backward in the tab order.
tabStopOnly
true to ignore the controls with the TabStop property set to false; otherwise, false.
nested
true to include nested (children of child controls) child controls; otherwise, false.
wrap
true to continue searching from the first control in the tab order after the last control has been reached; otherwise, false.
Return Value
true if a control was activated; otherwise, false.
If you using a few textboxes then generate two event handlers one for keydown and one for leave and connect each textbox to the SAME EVENT HANDLER and use “case statements” switched from the name of the textbox. I can show you how to do this if necessary(just post a reply) I have about a dozen textboxes on one form and use ONE “Leave event” handler to handle EVERY ONE OF THEM and the return key can move between them.
I use the leave event to validate and enter the data into the program.
I use the keydown event is to detect if a key is down (crazy that eh!)
I have several textboxes and the use exactly the same leave and keydown event handlers, in the case below "tbxUpper"
private void tbxUpper_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Return)
{
TextBox tbx = (TextBox)sender;
SelectNextControl(tbx, true, true, true, true);
}
}
the above event actually fires every time a key is presses in a text box but the "if statement" looks for the return key. when the return key is pressed a textbox called tbx is generated and copied from sender then the next control is selected.
I don't know if this actually helps you.
If you need furthur help post a reply "and then hit Enter"!!
|
|
|
|
|
Could someone help out. I'm bulding a windows application that uses a skin instead of the form border that windows provides. Everything is going well except for my bosses specs. I am suppose to map the area on the skin that needs to be an onclick event. Kind of like an html and javaScript where your able to map a certain section of an image and make it a clickable link.
|
|
|
|
|
A transparent panel?
hmmm pie
|
|
|
|
|
Yep tried that. And I would think that it would work but it puts a black box over my image. I even tried to set the transparencyKey and that just cut a hole through my app. But in idea a transparent panel should work. Any thoughts?
|
|
|
|
|
I tried with a background image and the following worked fine:
this.panel1.BackColor = System.Drawing.Color.Transparent;
this.panel1.Click += new System.EventHandler(this.panel1_Click);
So panel with a background image instead of a pisture box would work fine.
hmmm pie
|
|
|
|
|
ok well my app is a little different. here a small sample of the app.
//this is my overloaded constructor
//gets loaded when the form is first Initialized
public HighCapacity(Skins sk) {
// I put the panel before the InitializeComponent() to get it to load.
// everything will need to be loaded dynamically
InitializeComponent();
//sets the border syle to none to I can add my own
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
//menuOff is a PictureBox that displays as the form
this.menuOff.Image = new Bitmap(sk.DayMenuSkin);
this.menuOff.SizeMode = PictureBoxSizeMode.CenterImage;
this.menuOff.SizeMode = PictureBoxSizeMode.StretchImage;
this.ClientSize = new Size(800, 600);
//set the background of menuOff
if (sk.BackgroundSkinType == "COLOR") {
//this.BackColor = Color.FromArgb();
} else if (sk.BackgroundSkinType == "IMAGE") {
this.menuOff.BackgroundImage = new Bitmap(sk.BackgroundImage);
} else {
this.BackColor = Color.Black; ;
}
this.menuOff.SizeMode = PictureBoxSizeMode.AutoSize;
this.Controls.Add(this.menuOff);
}
|
|
|
|
|
this.menuOff.Controls.Add(this.panel1);
Visual studio is a bit silly when it comes to moving the transparent panel over the image as it resets the above to add it to the form instead which is why it gives a black box.
hmmm pie
modified on Monday, February 23, 2009 6:22 AM
|
|
|
|
|
That did it lol. Thanks allot dude!!!!!
|
|
|
|
|
Hey.
I'm trying to create a client which responds to specific packets. The idea is, i'm going to have a large array of struct "packet" which stores information such as, the type of packet, the length of the sent packet, and a corresponding function it should call.
I know in C++ you can parse functions as parameters quite easily, or with some coding. However, in C# you need to use either delegate functions, or use the Reflection.MethodInfo methods.
The delegate functions may work, but the code to setup each row for my array would be extremely long and rather messy. I tried using the MethodInfo method instead, but the functions i'll be calling are marked with unsafe , and so my byte* parameter can't be passed through as an object in the object[] params :\
Is there any other method I could use to automate this system? Here's a snippet of what I mean:
_packetDB[++i] = new Packet() { type = 0x73, len = 11, func = "authok" };
Where "authok" is a function in a class foo . (When the packet is received, it will search for packet 0x73, and send the byte* data, the length into the function func )
Any help would be greatly appreciated.
Thanks
|
|
|
|
|
You should be using delegates. In general, its best to avoid the use of unsafe code or PInvoke, whenever possible. For your scenario, you should only need to do the following:
unsafe delegate void PacketHandler(byte* data, int length);
struct Packet
{
int type;
int len;
PacketHandler func;
}
void CreatePacket()
{
Packet packet = new Packet
{
type = 0x73,
len = 11,
func = AuthOK
};
}
unsafe void PacketProcessor(Packet packet)
{
byte* data = GetPacketData(packet.type);
packet.func(data, packet.len);
}
unsafe void AuthOK(byte* data, int len)
{
}
|
|
|
|
|
Oh! I always thought you had to define delegation functions as new DelegateFunction(FunctionToCall);
Thanks a lot, you're a life-saver. This should make the system work much, much better
|
|
|
|
|
Glad to be of service.
|
|
|
|