|
Hi All,
I have what appears to be a simple problem, but cannot for the life of me work out how to do this efficiently... can someone please help.
I am building up strings programatically, which I then want to evaluate as boolean. Not my ideal way of doing it, but Im stuck with it for legacy reasons.
ie. (much simplified example - actually many lines of code)
string sToConvert = "true && true && false";
I want to evaluate this string and get the boolean value from it - in this case false.
ie. something like this
bool bConverted = Convert.ToBoolean(sToConvert); // this does not work
Can anyone think of an easy way of doing this in C# ? I have got it working with by compiling it into code with System.CodeDom.Compiler and then evaluating it, but it seems really inefficient and slow.
Any help would be appreciated.
|
|
|
|
|
I don't know if this will be helpful or not, but if the string is always made of 'true' and 'false' in the string maybe you could do something like
string sToConvert = "true && true && false";
bool bConverted = sToConvert.IndexOf("false") == -1? true : false
|
|
|
|
|
good idea, thanks. Unfortunately the string could be slightly more complicated.
ie. string sToConvert = "(true && true) || (false && true)";
|
|
|
|
|
This might be a bit overpowered but right now I can't come up with an easier way:
You could create the sourcecode for a class with an "Evaluate()" method, add the expression to the code and then use classes from the System.CodeDom namespace to compile the sourcecode.
The class stub code could look similar to this:
string clsSrc = "public class Evaluator {";
clsSrc += " public static bool Evaluate() {";
clsSrc += " return "+expressionToEval+";";
clsSrc += "} }"; with expressionToEval being a string holding your expression.
Stuff this into ICodeCompiler.CompileAssemblyFromSource() .
The new assembly can be created in memory, so that you don't have to write to disk.
Then you'd call the method either using reflection or by defining an interface that your dynamically created class implements and calling the interface method and that's it.
mav
|
|
|
|
|
Mav's idea would work, but if you have to do this a lot you'll consume a heck of a lot of memory since assemblies can't be unloaded from a domain (the domain can be unloaded, though, so long as it's a different domain).
The best way is to write (or find; we did for our flagship app) a string tokenizer. If all you're handling is booleans, this would even be easier to write. You have only two operands: 'true' and 'false'. You have only 2 operators: '&&' and '||'. Your parens act only to push and pop the values in a certain order. The rest of this is a text-book case of stack manipulation, like many college courses will use for writing simple calculators (RPN calculators).
A quick search on google (for a link to show you) resulted in a very nice page with a Java calculator implementing what's discussed in the page that even shows the evaluation stack. See http://www.math.ubc.ca/~cass/courses/m266-99a/rpn/docs/ca.html[^] for details.
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
A quick question, will all of your true false values be anded together? If this is the case, you can do something as simple as below:
string str = "true && true && false && true";
bool b = str.IndexOf("false") > 0 ? false : true;
MessageBox.Show(b.ToString());
- Nick Parker My Blog | My Articles
|
|
|
|
|
I want to cut some area from a image.How to do it?
|
|
|
|
|
There's many examples of image manipulation in .NET. I suggest you try searching for examples, like Microsoft FotoVision[^].
If you want to clip the area, create a Graphics object for the control using Control.CreateGrahpics . Or, better yet, handle the Paint event and get it from PaintEventArgs.Graphics . Then call SetClip to set the clipping region (the portions that would be drawn). Then call Graphics.DrawImage to draw the image. The clipping region will not be drawn.
If you want to copy a portion of the image into the clipboard and then delete it from the original image, that gets a bit more complicated. Not only must you implement what is above, you must also invert the clipping region (there are methods to do this) and draw that portion of the image into another image using the Graphics object for an Image , using Graphics.FromImage . This draw that clipped portion of the image into another image. You can then take tha Image and use, IIRC, Clipboard.SetDataObject(myClippedImage) , which may work. If not, adding image types to the clipboard (or for drag and drop operations, which basically amounts to the same thing) is very complicated and should be discussed in a different thread.
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
I do a user control,then I use it in my webapplication.I use the method that Image.FromFile(string strFilePath) in my user control.When I run the programm at ohter client to IE.exe, the method that Image.FromFile(string strFilePath) is fail. Because the file at local machine(WebApplication Server machine).How to do it?
|
|
|
|
|
It's really difficult to understand your question; it makes little sense.
You're saying that you're trying to create an image from the same file in two different applications using Image.FromFile ? Or are you saying that your web application is trying to access an image using Image.FromFile ? What path is it trying to access (remember that ASP.NET is only local to the server - it has no way to access the path on the client; that would be a severe security hole even if it were possible).
And if an exception is thrown, please be specific. Saying "[it] fail[s]" doesn't help. What's the exception type? What's the exception message? You must be specific when asking questions in a forum or newsgroup. We don't know your code and can't magically determine the specific problem could be with such a broad explanation of what you're doing.
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
HI~
I have written a class, say class1, which implement an interface, say interface1 in project 1.
Then I wrote another class, say class2, which implement an interface, say interface2 in project 2. The code of interface2 is 100% the same as interface1.
Then I compile project 1 and got the a dll of class1 and a dll of interface1.
Afterthat, I compile project2 and build a dll of class2. Then I copy the the dll of class2 to project 1 and use it. That means the class2 dll using the dll of interface1.
In fact, although the code of two interfaces is the same, but the version or whatever still different(i.e dll of interface1 is different from dll of interface2). However, the class2 still can use the dll of interface1 without any runtime error. It is incrediable!
Does anyone know why? I don't know it well...
Thanks
|
|
|
|
|
The DLLs are just assemblies. And of course code in one assembly can use code in another it would be fairly pointless if it couldn't - no code reuability, no third party components etc. Every application would be huge because all code would have to be compiled into each application, rather than have applications share assemblies.
Class2 can use anything in the first assembly (where interface1 is) that is declared public . Or, if it derives from anything in the first assembly, the protected items in the base class es/interface s also.
I don't know if I've explained very well as I am having difficulty working out where you are coming from with your original post. Anyway, I hope it helps
"If a man empties his purse into his head, no man can take it away from him, for an investment in knowledge pays the best interest." -- Joseph E. O'Donnell
The Second EuroCPian Event will be in Brussels on the 4th of September
Can't manage to P/Invoke that Win32 API in .NET? Why not do interop the wiki way!
|
|
|
|
|
Hello everyone, I have a problem that I have been banging my head against the wall for the past few days trying to figure out...I am writing a remote assistance service and I want to send a file(a .jpg) using tcp/ip blocking sockets. I have used MANY other peoples source code, but still the file never arrives or I get ugly unhandled exceptions...I finally found one that sort of works...It sends a snapshot of the users screen ONE time, after that the client gives me a "connection reset by software on your remote host", I have included the client and server methods that are running in a seperate continuous thread...your help is MUCH appreciated.
P.S. sorry for the bad formatting.
<---Client source snippet--->
public static void BeginSnapShotSend()
{
ScreenCapture SC = new ScreenCapture();
try
{
// get the remote IP address...
IPHostEntry IPHost = Dns.Resolve("localhost");
IPAddress[] ip = IPHost.AddressList;
int iPortNo = System.Convert.ToInt32(443);
//create the end point
IPEndPoint ipEnd = new IPEndPoint (ip[0],iPortNo);
//connect to the remote host...
PicConnect.Connect ( ipEnd );
nfs = new NetworkStream(PicConnect) ;
}
catch (SocketException SE)
{
System.Windows.Forms.MessageBox.Show(SE.ToString());
return;
}
while (true)
{
SC.CaptureScreenToFile("sc.jpg", ImageFormat.Jpeg);
Thread.Sleep(1000);
try
{
FileStream fin = new FileStream("sc.jpg",FileMode.Open , FileAccess.Read) ;
//Get the Length of the file requested
//and set various variables
long total=fin.Length;
long rdby=0;
int len=0;
byte[] buffed = new byte[4096];
//Open the file requested for download
//One way of transfer over sockets is Using a NetworkStream
//It provides some useful ways to transfer data
byte[] m_sbuf = System.Text.Encoding.UTF8.GetBytes("fsize"+" "+total.ToString());
PicConnect.Send(m_sbuf);
Thread.Sleep(1000);
//lock the Thread here
while(rdby<total&&nfs.canwrite)
{
="" read="" from="" the="" file="" (len="" contains="" number="" of="" bytes="" read)
="" len="fin.Read(buffed,0,buffed.Length)" ;
="" write="" on="" socket
="" nfs.write(buffed,="" 0,="" len);
="" increase="" counter
="" rdby="rdby+len" ;=""
="" }="" display="" a="" message="" showing="" sucessful="" transfer
="" fin.close()="" }
="" catch(exception="" ed)
="" {="" system.windows.forms.messagebox.show("a="" exception="" occured="" in="" transfer"+ed.tostring())="" ;
="" return;
="" }
<---server="" snippet---="">
public void raptwm()
{
IPAddress ipAdress = IPAddress.Any;
IPEndPoint Enp = new IPEndPoint(ipAdress, 443);
Socket ListenTehCliPic = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
ListenTehCliPic.Bind(Enp);
ListenTehCliPic.Listen(0);
Socket WorkWitTehCli = ListenTehCliPic.Accept();
NetworkStream nfs = new NetworkStream(WorkWitTehCli);
ListenTehCliPic.Close();
while (true)
{
bool done =false ;
bool check= false ;
long size=0 ;
long rby=0 ;
while(!done)
{
//declare a buffer
byte[] rce = new byte[2048];
//Recive a Sever Message
waitagain:
int i = WorkWitTehCli.Receive(rce,rce.Length,0) ;
//Convert it to string
string sm = System.Text.Encoding.ASCII.GetString(rce);
if(sm.StartsWith("fsize"))
{
string sizeoffile = sm.Remove(0,6);
//store the File Size
size=Int64.Parse(sizeoffile);
done=true ;
check=true ;
}
else
{
goto waitagain;
}
}
//The File Size has been received the continue
done=false;
//Make a File with the same name as the File that is being downloaded
//Also open a Network Stream to the Server
FileStream fout = new FileStream("sc.jpg", FileMode.OpenOrCreate , FileAccess.Write);
byte[] buffer = new byte[4096] ;
while(!done&&check)
{
try
{
long v=0 ;
//loop till the Full bytes have been read
while(rby<size)
{
="" read="" from="" the="" network="" stream
="" int="" i="nfs.Read(buffer,0,buffer.Length)" ;
="" if(i="">0)
{
//Some checking done to detremine the number of Bytes to be written
if(i>=4096&&(size-rby)>=4096)
{
v=4096 ;
}
else if(i<4096 &&(size-rby)>=4096)
{
v= i;
}
else
{
v=(size-rby) ;
}
//Write the Bytes received to the File
fout.Write(buffer,0,(int)v) ;
rby=rby+v ;
}
}
fout.Close() ;
done=true;
Thread.Sleep(100);
pictureBox1.Image = Image.FromFile("sc.jpg");
}
catch(Exception ed)
{
MessageBox.Show(MW,"A Exception occured in file transfer"+ed.ToString());
}
}
}
}
|
|
|
|
|
I have yet to figure out what everyone's infatuation with writing a VNC-like application in C# is. This is really not a good idea, mind you.
Not only are there already clients that do this installed in Windows (NetMeeting is standard in Win98 and Win2K and newer, or some form of it; Windows XP already has remote assistance that's very flexible) but you can even use some of the APIs like NetMeeting to integrate into your own application.
The true remote desktops don't use an entire screenshot, but a virtual frame buffer. Consider this: when a region is invalidated in Windows, it sends the WM_PAINT message with an HRGN that specifies what needs to be repainted (in .NET, this corresponds to the Paint event and the PaintEventArgs.ClipRectangle property). This may be an entire window or just a portion of it. But the entire screen is not drawn each time. By using a virtual frame buffer you take advantage of this (requiring much less bandwidth). Only the bits for the newly drawn portion are transferred across the wire.
It's this approach - if you're intent on reinventing the wheel (there's lots of "wheels" already, many very heavily tested) - you should look into. Unfortunately, .NET is too high level for such a task. Even if you do manage to P/Invoke all the native APIs you'll need an declare all the structs and consts, you'll incur performance penalties because of marshaling. You could, of course, write a Managed C++ assembly that alliviate most of these problems (mixing unmanaged and managed code to make such functionality accessible to other .NET assemblies written in any language).
What you're currently doing will have problems like you're seeing. Far too much bandwidth is required and will most likely require more time to transfer than your current refresh time, creating a large bottleneck that won't go away and will eventually cause timeouts (pretty quickly). The more lag on the wire, the faster timeouts will start occuring.
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
wow, ok thanks for your help. I totally forgot about using netmeeting, and I didn't truly realize how difficult such a thing could be.
|
|
|
|
|
I want to write a C# Serial communication program,but I am poor in C#,I usually did these in vc++6.0 before.
What should I do if I want to use C#?
Is there any example about these??
Thanks!!
|
|
|
|
|
I typed "RS232 C#" into google and found many results[^]. If you're looking for something specific, it's usually a good idea (and most often the fastest) to search first (whether it's this side, this forum, or on the entire indexed web).
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
Thanks!!
The google is very uesful,I have got what I want.
someone has wrote a class for .NET serial communciation,the class name is JH.CommBase.
|
|
|
|
|
Here is an issue I've run into from time to time while creating C# applications. Let's say I have a model which represents the business domain of my application. To present this model to my users, I have a GUI layer.
Let's say that there is a combo box that is a part of the GUI. The user clicks on the combo box and makes a selection. This triggers an event. In response to this event, the model is updated.
Very, very simple. But...
When updating the model from an outside source, say a file or whatever, the GUI will need to be updated to represent the model accurately. Continuing with the combo box example, if you set the SelectedIndex property to a value programmically, an event will be raised to indicate that the property has changed. So when updating the GUI, events are raised in response. And using the logic set up to respond to those events, the model will be updated unnecessarily.
In the case of the ComboBox and its SelectedIndex property, there is no distinction made between the property being modified as a result of user interaction and being modified programmically.
One obvious approach would be to disconnect from the events when you don't want to respond to them and reconnect afterwards. But with a lot of controls, that could lead to a lot of code. What this has led me to do is to use a boolean variable to indicate whether or not the model should be updated when an event is raised by the GUI controls. But this solution feels kludgish.
I was wondering if other C# programmers have run into this problem and how you dealt with it.
|
|
|
|
|
There's nothing wrong with using state variables. State variables are used throughout the entire .NET BCL (base class library) and many, many other applications. It's practically impossible to write a decently sized application without state variables.
And they result in far less instructions that attaching and detaching event handlers like you mention. To assign a state variable is (assuming an instance field) 2 IL instructions. To check that variable and branch accordingly is another 2-3 instructions (depending on if else is used immediately after the if with no else if in between). Hooking up an event handler - even in your code - takes many more instructions, and many more instructions are required by the delegate to combine the list (even if previously empty) of handlers.
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
Is is possible to pass a form control to a class?
ex. passing a listView control to a class so I can access the contents of the listView.
Thanks
Budha_man_99
Bas spellers of the world Untie!!
|
|
|
|
|
budha_man_99 wrote:
Is is possible to pass a form control to a class?
By class I am assuming you really mean an instance of a class (an object). Yes, it is possible. You can pass any object to another object and a form control is just an object.
The real question is how do you want to pass the form control to your object. Via the constructor? Through a property's setter? In a method call?
"If a man empties his purse into his head, no man can take it away from him, for an investment in knowledge pays the best interest." -- Joseph E. O'Donnell
The Second EuroCPian Event will be in Brussels on the 4th of September
Can't manage to P/Invoke that Win32 API in .NET? Why not do interop the wiki way!
|
|
|
|
|
Colin,
I am attempting to use a method call.
Thank you
budha_man_99
|
|
|
|
|
Your class can contain something like this...
public class MyClass
{
public void MyMethod(System.Windows.Forms.Control theControl)
{
}
}
From the Form (I'm assuming this is where you are coming from, you've not been very explicit about this) something like this....
public void SomeMethodInTheForm()
{
MyClass theClass = new MyClass();
theClass.MyMethod(this.theTextBox);
}
Voilá.
Does this help?
"If a man empties his purse into his head, no man can take it away from him, for an investment in knowledge pays the best interest." -- Joseph E. O'Donnell
The Second EuroCPian Event will be in Brussels on the 4th of September
Can't manage to P/Invoke that Win32 API in .NET? Why not do interop the wiki way!
|
|
|
|
|
This is exactly what I'm looking for. Thank you very much.
|
|
|
|
|