|
parths wrote: The typecast operation assumes that the object is of type or subclasses from the target type. Actually no, it could be that the (static) type of a has an explicit conversion to string.
|
|
|
|
|
To add to (and correct) what parths said:
parths wrote: a.ToString would throw a null reference exception if a is null
No, it doesn't! It will throw a NullReferenceException, since it has no instance to call a method from.
There is also:
txtValue = a as string; Which will try to do a cast to a string, and return null if the cast cannot be performed instead of throwing an exception. This is frequently used when dealing with a variety of objects that derive from a single base class. For example:
foreach (Control c in Controls)
{
Button b = c as Button;
if ( b != null)
{
...
}
}
There is also an implicit call to ToString when you concatenate a strign with a non-string:
int i = 999;
string s = "The value is: " + i; Produces
The value is: 999 because the system does an implicit call to ToString to convert the data.
You should also note that unless a class specifically implements ToString as an override, the default Object version will be called. This returns a string which contains the fully qualified name of the instance type, which catches a lot of people out, who assume that
Image i = Image.FromFile(@"D:\Temp\MyPic.jpg");
string s = i.ToString();
string sql = "INSERT INTO MyTable (userPic) VALUES ('" + s + "')";
... will insert the image data into their database for later. What it actually inserts is the text
System.Drawing.Bitmap which confuses them when it fails to work as a picture on retrieval.
[edit]Spurious code block removed - Thanks Richard! - OriginalGriff[/edit]
The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)
modified 27-Mar-13 4:57am.
|
|
|
|
|
OriginalGriff wrote: Produces
<pre lang="text"> Oops!
Use the best guess
|
|
|
|
|
The universe is composed of electrons, neutrons, protons and......morons. (ThePhantomUpvoter)
|
|
|
|
|
n00b
“Education is not the piling on of learning, information, data, facts, skills, or abilities - that's training or instruction - but is rather making visible what is hidden as a seed” “One of the greatest problems of our time is that many are schooled but few are educated”
Sir Thomas More (1478 – 1535)
|
|
|
|
|
just to complete the information.
casting is often used in boxing/unboxing objects and is often an expensive operation.
I didn't test, but I think that
txtValue == (string)a;
is a heavier operation than
txtValue = a.ToString();
with the additional problem that you get an exception if it cannot be cast. try/catch is also heavier then if/else. (so if(a != null) { txtValue = a.ToString() } is better than using try/catch. (this is what I call defensive programming)
If you write your own class and override the ToString method, you can do some fancy stuff. eg. if you do NOT override, ToString will probably return something like "thenamespace.theclassname". If you do override it you can make a representation of your class like eg a JSON object or an XML string (or whatever format takes your fancy) with all property values in there. (serializing objects)
txtValue = Convert.ToString(a);
will convert the object to string, but in a safer way. In fact I rarely use the casting (option 1), only if I need to cast from a boxed object. I only use option 2 when I want to do fancy stuff with my class (because of the null reference exception problem.) I use option 3 in most normal cases.
hope this helps.
|
|
|
|
|
I'm trying to do a Left Join in Linq To Sql and I can't figure it out.
Here's my code with my changes undone. MaterialSizes may or may not be there in the data:
using (var dc = getDataContext())
{
ISystemDAL systemDAL = new SystemDAL();
var summaries = (from mh in dc.MaterialHeaders
join md in dc.MaterialDetails on mh.MaterialHeaderId equals md.MaterialHeaderId
join ms in dc.MaterialSizes on md.MaterialSizeId equals ms.MaterialSizeId
select new MaterialSummaryModel
{
Id = mh.MaterialHeaderId,
MaterialDetailId = md.MaterialDetailId,
ItemNumber = mh.ItemNumber,
ItemName = mh.ItemName,
Category = systemDAL.GetLookup(mh.MaterialTypeId),
Color = md.Color,
Fitting = md.FittingId.Value == null ? null : systemDAL.GetLookup(md.FittingId.Value),
Size = ms.Caption
}).ToList();
return summaries;
}
How do I turn MaterialSizes into a left join??
Thanks
If it's not broken, fix it until it is
|
|
|
|
|
have a read of this
Stackoverflow : C# Linq Left outer join syntax[^]
Lobster Thermidor aux crevettes with a Mornay sauce, served in a Provençale manner with shallots and aubergines, garnished with truffle pate, brandy and a fried egg on top and Spam - Monty Python Spam Sketch
|
|
|
|
|
I've got a service than runs on two machines and communicates back and forth through a socket connection.
To make debugging easier, I've wrapped the OnStart and OnStop stuff inside a console program. The only
difference in the two running instances is a) how the exe starts (SCM versus double-clicking the console exe) and b) the account the exe runs in (LocalSystem versus current user). Actual code of the "guts" of the program is the same.
When the following runs with two consoles communicating, everything is fine. When it runs with a console app on one machine talking to a service on the other, it fails on the indicated line, throwing a System.InvalidCastException with the message unable to cast object of type 'OverarchingServer.DerivedMessage' to type 'OverarchingServer.DerivedMessage'
A breakpoint in the debugger of the running service at the line in question shows that msg IS of the expected 'DerivedMessage' type and the fields are fully and correctly populated. The exception thrown indicates the types ARE the same. So why can't I do the type cast?
I haven't tried service to service yet - that is rather difficult to set up on my development system. Besides, I want to know why this doesn't work when run this way.
Any ideas?
Thanks,
Judy
namespace ClientMessages
{
[Serializable]
abstract public class BaseMessageClass
{
public int type;
}
}
namespace OverarchingServer
{
using ClientMessages;
public enum MessageTypeEnum : int
{
DerivedMessageType = 1,
AnotherType,
YetAnotherType
}
[Serializable]
public class DerivedMessage : BaseMessageClass
{
}
public class SendingServer
{
private Socket client;
public void DoingWork ()
{
DerivedMessage msg = new DerivedMessage ();
this.Send (msg);
}
public void Send (BaseMessageClass msg)
{
MemoryStream mem = new MemoryStream ();
BinaryFormatter bf = new BinaryFormatter ();
bf.Serialize (mem, msg);
byte[] data = mem.ToArray ();
NetworkStream stream = new NetworkStream (this.client);
BinaryWriter binWrite = new BinaryWriter (stream);
binWrite.Write ((Int32) data.Length);
binWrite.Write (data, 0, data.Length);
}
}
public class ReceivingServer
{
private Socket client;
private void LoopWithDetailsOmitted ()
{
NetworkStream stream = new NetworkStream (this.client);
BinaryReader binRead = new BinaryReader (stream);
int length;
byte[] data;
length = binRead.ReadInt32 ();
data = binRead.ReadBytes (length);
MemoryStream mem = new MemoryStream (data);
BinaryFormatter bf = new BinaryFormatter ();
BaseMessageClass msg = (BaseMessageClass) bf.Deserialize (mem);
this.HandleMessage (msg);
}
private void HandleMessage (BaseMessageClass msg)
{
MessageTypeEnum type = (MessageTypeEnum) msg.type;
switch (type)
{
case MessageTypeEnum.DerivedMessageType:
this.HandleMessage ((DerivedMessage) msg);
break;
}
}
private void HandleMessage (DerivedMessage msg) { }
}
}
Be wary of strong drink. It can make you shoot at tax collectors - and miss.
Lazarus Long, "Time Enough For Love" by Robert A. Heinlein
|
|
|
|
|
Oops forgot ... Windows XP and .NET 3.5
Be wary of strong drink. It can make you shoot at tax collectors - and miss.
Lazarus Long, "Time Enough For Love" by Robert A. Heinlein
|
|
|
|
|
Move your message classes (everything used by more than one project) to another project and reference that project from both your server service project and your console project.
|
|
|
|
|
I'll try that at work tomorrow ...
I'm guessing the point you're making is ... the same namespace in the same DLL running on both machines, versus the exact same namespace compiled into two distinct executables. My question is then, how will it deal with versioning? The messages can, and mostly likely will, change with the version of the program suite. I'll then have the same namespace in two differently versioned DLLs -- two different DLLs containing differently versioned messages on the two machines. They must still exchange messages, with the versioning controlled by the support in serialization. Am I going to have the same issue then?
Judy
Be wary of strong drink. It can make you shoot at tax collectors - and miss.
Lazarus Long, "Time Enough For Love" by Robert A. Heinlein
|
|
|
|
|
Hah another RAH fan
I would think that if your message structure changes so dramatically that it cannot inherit from the original there is a fault in the design! I would expect it to become another message type.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
I wouldn't say it would change dramatically, but for a given release one message out of the 25 or so total may add a single field. That's why I wanted to use the versioning support in serialization. I've done this lots of times before, but those were C / C++ program where I did it manually with just simple byte transfers where I would read a length, a type, a version and then deal with putting the different versions into the the message that came out of the receive function. Wasn't C# supposed to make this stuff easier? ... handling versioning (mostly) for you, and the ability to serialize and transfer something beyond an agnostic byte stream. If I can't even have the exact same code compiled into a different executable unit and have something in that namespace transfer between those units, I'll just trash the C# serialize portion of the transfer and go back to doing it manually. I must be able to have different versions running on different machines communicate with each other.
What I'm trying to do can't be that unusual. Do I need to transfer structures instead of classes? I've only been doing C# for about 2 years -- I've got the feeling I'm just missing something ...
Judy
Be wary of strong drink. It can make you shoot at tax collectors - and miss.
Lazarus Long, "Time Enough For Love" by Robert A. Heinlein
|
|
|
|
|
I think I may be missing something as, while I use WCF, I don't do any messaging as such.
I use Dave's method of externalising the models (I use Silverlight) and reference them from both client and service. I have not had any issues with differing versions, I do know a missing field in the sent object is ignored by the deserialiser and ends up with a null value.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
I haven't used binary serialization but XML will try to fill in all the data it can from the serialization data. If there's a field that isn't there in the data, it just won't get filled. If there is an extra field in the data that doesn't have a coresponding field in the object, it gets ignored.
...IIRC...
|
|
|
|
|
Moving the messages into their own namespace in their own DLL fixed the problem. I tested the versioning as well and it works fine. Looks like C# doesn't consider identically defined elements of an identically named namespace to be the same if they come out of two different executable units (i.e. my two original different EXEs); but they are the same if they come out of two different versions of the same executable unit (i.e. the new DLL).
Thanks Dave!!
Judy
Be wary of strong drink. It can make you shoot at tax collectors - and miss.
Lazarus Long, "Time Enough For Love" by Robert A. Heinlein
|
|
|
|
|
Part of the fully qualified name of the object is the assembly its defined in. Two assemblies can have the namespace names in them but still be different objects.
|
|
|
|
|
That explains it then! I'll add that tidbit to the C# file in my brain. Would have been nice if the exception message showed the fully-qualified name instead of telling me that 'x' couldn't be typecast to 'x'
Be wary of strong drink. It can make you shoot at tax collectors - and miss.
Lazarus Long, "Time Enough For Love" by Robert A. Heinlein
|
|
|
|
|
I want devexpress winforms control can somebody give me that
regards
|
|
|
|
|
Not unless you pay DevExpress some money. You might want to check into doing that here[^]
|
|
|
|
|
Nobody will give you the controls, but you can always opt to take the radical option and offer them money for their work. This money will then go towards improving the controls and adding new features. It's a radical experiment, and we hope that it catches on.
|
|
|
|
|
naseer861 wrote: I want devexpress winforms control
You can download a trial version direct from the DevExpress website.
|
|
|
|
|
If you can't afford to purchase the commercial control sets you are going to have to limit yourself to the default controls. Only use the trial versions if you can afford to purchase, otherwise it is a waste of time.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
Hi All. I have a slight problem in that my DirectoryInfo does not return the full path. Does anybody know if there is a limitation to the DirectoryInfo?
The path to the files is something like this:
C:\\Folder1\\Folder2\\Folder3\\Folder4\\Folder5
My code is as follows:
private void getAllFiles(string sExt, string sFolder)
{
DirectoryInfo di = new DirectoryInfo(sFolder);
FileInfo[] fi = di.GetFiles(sExt, SearchOption.AllDirectories);
foreach (FileInfo file in fi)
{
AddNewFile(Path.Combine(di.ToString(), file.ToString()));
counter++;
}
lblTotalFiles.Text = counter.ToString();
}
FileInfo seems to get the location of the file as it shows me the file it picked up but when the path of DirectoryIfo is passed on it excludes Folder5 thus the object I am passing it to doesn't find the file in question. Is there anyway I can fix this?
Excellence is doing ordinary things extraordinarily well.
|
|
|
|