|
Lookup reflection - thats the way to dynamically instantiate .NET classes without the need to reference them.
|
|
|
|
|
Could you provide a code example please?
|
|
|
|
|
I know .NET doesn't like Generics or serialization based on anything but XML but I would like an explanation of the following behavior given the code pasted at the bottom.
When SelectNotClassified is set to null the code executes fine with no errors. The GetValue method returns null. In fact, changing info.GetValue to typeof(object) still returns null which is expected.
When SelectNotClassified is not null the code throws an InvalidCastException. info.GetValue(..., typeof(bool)) would work fine and returns a Boolean results but interestingly info.GetValue(..., typeof(object)) returns a string value of "true" (see my post in the Lounge about things that really p*** me off about .NET). This means that (bool?)info.GetValue(..., typeof(object)) is not a valid solution since a string cannot be cast as a Boolean, only converted.
There are many workarounds to the issue but I am interested in the why and how to write this code as it should be written. Double casting, ternary operators, and parsing from what should be a binary stream all seem ridiculous to me. Am I missing the obvious info.GetValue statement that should be working?
GetObjectData(SerializationInfo info, StreamingContext context){
...
info.AddValue("selectNotClassified", (bool?)SelectNotClassified);
...
}
public Foo(SerializationInfo info, StreamingContext context){
...
SelectNotClassified = (bool?)info.GetValue("selectNotClassified", typeof(bool?));
...
}
Need software developed? Offering C# development all over the United States, ERL GLOBAL, Inc is the only call you will have to make.
If you don't ask questions the answers won't stand in your way.
Most of this sig is for Google, not ego.
|
|
|
|
|
Just checking the obvious, but you do realise that bool? is shorthand for the struct System.Nullable< bool> yeah?
The complier is probably selecting the AddValue(string, bool) overload, and putting a bool in the ourput stream.
I would suggest that info.GetValue(..., typeof(object)) is actually returning a boxed bool, which in the watch window looks a lot like a string (as .ToString() is called). You can't cast directly from a boxed boolean to a bool? - you will have to go with new bool?(GetValue(bool)).
If you really need a bool? in your serialized object, then use the AddValue(string, object, Type) overload, and specify typeof(bool?).
|
|
|
|
|
Yes, I do and I also realize that .NET serialization does not support generics requiring custom serialization and it just really irks me that something as simple as a Nullable type requires custom code.
Mark Churchill wrote: Just checking the obvious, but you do realise that bool? is shorthand for the struct System.Nullable< bool> yeah?
I don't think so because null comes back just fine.
Mark Churchill wrote: The complier is probably selecting the AddValue(string, bool) overload, and putting a bool in the ourput stream.
Check the code as I did. GetValue is returning null when AddValue has added a null and typeof(object) is actually returning a string not a boxed type. I attempted info.GetValue(..., typeof(object)).GetType() to locate.
Mark Churchill wrote: I would suggest that info.GetValue(..., typeof(object)) is actually returning a boxed bool, which in the watch window looks a lot like a string (as .ToString() is called). You can't cast directly from a boxed boolean to a bool? - you will have to go with new bool?(GetValue(bool)).
This thing is really just messed up beyond recognition. I can write code to account for it without difficultly but I shouldn't have to. My post is with the hopes of finding some expert in serialization that can go aha, Ennis, you missed this hidden special feature in .NET that does it like we all expected it to work.
Need software developed? Offering C# development all over the United States, ERL GLOBAL, Inc is the only call you will have to make.
If you don't ask questions the answers won't stand in your way.
Most of this sig is for Google, not ego.
|
|
|
|
|
Also, along with the joys of boxing, the statement object foo = new bool?(false); will unwrap the nullable object and give you a plain boxed boolean in foo.
Other that that it sounds like you are probably using the XML/SOAP formatter and everything is getting munged. Any reason you need it serialized as XML?
|
|
|
|
|
When using the Serialization constructor and GetData interface One would assume no knowledge of the particular serialization method in use. And, this particular project is using Binary Serialization over .NET remoting.
Again, back to my original post, wtf. None of this should be an issue. GetValue should return the value assigned from SetValue without any other consideration.
Need software developed? Offering C# development all over the United States, ERL GLOBAL, Inc is the only call you will have to make.
If you don't ask questions the answers won't stand in your way.
Most of this sig is for Google, not ego.
|
|
|
|
|
Hrmm, this works with the BinaryFormatter (but not the SoapFormatter) - so I'd suggest the problem exists in your code somewhere.
It would be nice if the SoapFormatter could be made to work completely transparantly. Unfortunately this isn't possible because of the impedance mismatch between the SOAP standards and .Net model (a simple example is SOAP will round off your timestamps). This is just something a user will have to understand when using the API.
When I've had to use XML serialization seriously I've generally worked from and xsd, and used the xsd tool.
[TestFixture]
public class RandomTests
{
[Serializable]
public class Foo : ISerializable
{
public bool? bn = true;
public bool? bt = null;
public bool? bf = null;
public Foo()
{
bn = null;
bt = true;
bf = false;
}
protected Foo(SerializationInfo info, StreamingContext context)
{
bn = (bool?)info.GetValue("bn", typeof(bool?));
bt = (bool?)info.GetValue("bt", typeof(bool?));
bf = (bool?)info.GetValue("bf", typeof(bool?));
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("bn", bn);
info.AddValue("bt", bt);
info.AddValue("bf", bf);
}
}
private SerializationInfo _info;
private Foo foo;
[TestFixtureSetUp]
public void Setup()
{
var stream = new MemoryStream();
var formatter = new BinaryFormatter();
formatter.Serialize(stream, new Foo());
stream.Seek(0, SeekOrigin.Begin);
foo = (Foo) formatter.Deserialize(stream);
}
[Test]
public void BoolFalse()
{
Assert.IsFalse(foo.bf.Value);
}
[Test]
public void BoolTrue()
{
Assert.IsTrue(foo.bt.Value);
}
[Test]
public void BoolNull()
{
Assert.IsNull(foo.bn);
}
}
|
|
|
|
|
I am allegedly using the BinaryFormatter as well
<channels>
<channel ref="tcp" />
<serverProviders>
<formatter href="binary" />
</serverProviders>
</channels>
Need software developed? Offering C# development all over the United States, ERL GLOBAL, Inc is the only call you will have to make.
If you don't ask questions the answers won't stand in your way.
Most of this sig is for Google, not ego.
|
|
|
|
|
Hi Folks,
Just using a DataGridBoolColumn; allowing Nullvalue as DBNull.Value.
All three states are shown als it schould be (explained by msdn). true=checked,false=unchecked and DBNull= grey and checked. For my app. it is necessary to have the DBNull-State shown as greyd and unchecked.
How to?
Version: Studio 2003 and Framework 1.1
Thanks for advance
|
|
|
|
|
I'm creating a function that should return the max value of a field within the database..
1. Any idea why I'm getting the following compilation errors?
2. I need to return a value of type System.Data.Sqltypes.SqlInt64, whilst the return value is a string, any idea how to do the conversion? An explicit cast does not work i.e.
if (rawValue != DBNull.Value) {
return {System.SqlTypes.SqlInt64.rawValue.ToString();
Errors:
1. Warning 1 Unreachable code detected C:\Inetpub\wwwroot\TaskEntry\TaskEntry.aspx.cs 163 13 C:\...\TaskEntry\
2. Error 2 'TaskEntry.nextTaskRef()': not all code paths return a value C:\Inetpub\wwwroot\TaskEntry\TaskEntry.aspx.cs 149 43 C:\...\TaskEntry\
private System.Data.SqlTypes.SqlInt64 nextTaskRef() {
try
{
string getTaskRef = @"SELECT MAX([taskID_PK]) FROM [teamwiki].[dbo].[task];";
SqlCommand getTaskRefSQL = new SqlCommand(getTaskRef, conAppDB);
object rawValue = getTaskRefSQL.ExecuteScalar();
if (rawValue != DBNull.Value) {
return (System.Data.SqlTypes.SqlInt64) rawValue;
}
}
catch (Exception ex) {
throw ex;
return 0;
}
finally {
conAppDB.Close();
}
}
Environment notes
Visual Studio 2005 Team edition / .NET 2.0
ASP.NET
SQL Server 2005
Win XP SP3
Jon
modified on Wednesday, January 28, 2009 10:00 AM
|
|
|
|
|
Yep,
you are only returning a value if the rawValue is not null.
Put a return null statement at the end of the method if you like.
Regards
Sebastian
|
|
|
|
|
Hi,
private System.Data.SqlTypes.SqlInt64 nextTaskRef()
{
try
{
string getTaskRef = @"SELECT MAX([taskID_PK]) FROM [teamwiki].[dbo].[task];";
SqlCommand getTaskRefSQL = new SqlCommand(getTaskRef, conAppDB);
object rawValue = getTaskRefSQL.ExecuteScalar();
if (rawValue != DBNull.Value) {
return (System.Data.SqlTypes.SqlInt64) rawValue;
}
}
catch (Exception ex) {
throw ex;
return 0;
}
finally {
conAppDB.Close();
}
return 0;
}
This code can be best written as follows
private System.Data.SqlTypes.SqlInt64 nextTaskRef()
{
object rawValue;
try
{
string getTaskRef = @"SELECT MAX([taskID_PK]) FROM [teamwiki].[dbo].[task];";
SqlCommand getTaskRefSQL = new SqlCommand(getTaskRef, conAppDB);
rawValue = getTaskRefSQL.ExecuteScalar();
}
catch (Exception ex) {
throw ex;
}
finally {
conAppDB.Close();
}
if (rawValue != DBNull.Value) {
return (System.Data.SqlTypes.SqlInt64) rawValue;
}
return 0;
}
Happy Coding,
Karmendra
|
|
|
|
|
Thanks, I was having issues with explicit casting the value to SqlInt64:
return (System.Data.SqlTypes.SqlInt64) rawValue;
Jon
|
|
|
|
|
To give a little bit different approach.
Now you're using a meaningful value as a primary key. Could you consider using surrogate key[^] instead.
In order to do that you would define your primary key column as IDENTITY . After that SQL Server takes care of the numbering so one less thing to worry about. Especially if you use foreign keys between tables, I really encourage you to consider this option.
|
|
|
|
|
The finally block will always be executed so your comment against the if statement is wrong. The purpose of the finally block is to ensure that code is run no matter how the try block is exited even if an exception is thrown.
Your comment in the catch block is spot on - the return is unreachable and completely redundant.
However your solution is good.
An alternative would be to add an else statement that returns 0 after the if.
I.e do this
if (rawValue != DBNull.Value) {
return (System.Data.SqlTypes.SqlInt64) rawValue;
}
else {
return 0;
}
Regards
David
|
|
|
|
|
Hi all,
I have to validate a textbox for giving ratio to a value, i.e. i 've two boxes in which i enter ratio. i have to validate these box that values shud be integer & between range 0-100 only
can any body have the code or any help
|
|
|
|
|
Use Int32.TryParse[^] and if both return true, check the fields that the out parameter assigns to against your logic.
DaveBTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)
|
|
|
|
|
Didn't get it correctly..
I am very new to coding.. on which event do i have to check . can i get a sample code for the same
|
|
|
|
|
It depends on how you want to handle it.
The code below uses the Validating[^] event, but that may not be appropriate for your situation. I prefer to stop invalid characters getting into the textbox in the first place. Check out my article - Simple Numeric TextBox[^].
Assumes textBox1, textBox2 and label1 already exist on the form.
private static readonly int MinValue = 0;
private static readonly int MaxValue = 100;
int textBox1Value;
int textBox2Value;
bool textBox1Valid;
bool textBox2Valid;
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (!ValidateTextBoxes() && !textBox1Valid)
{
e.Cancel = true;
textBox1.SelectAll();
}
}
private void textBox2_Validating(object sender, CancelEventArgs e)
{
if (!ValidateTextBoxes() && !textBox2Valid)
{
e.Cancel = true;
textBox2.SelectAll();
}
}
private bool ValidateTextBoxes()
{
textBox1Valid = int.TryParse(textBox1.Text, out textBox1Value);
textBox2Valid = int.TryParse(textBox2.Text, out textBox2Value);
if (textBox1Valid)
textBox1Valid = textBox1Value >= MinValue && textBox1Value <= MaxValue;
if (textBox2Valid)
textBox2Valid = textBox2Value >= MinValue && textBox2Value <= MaxValue;
SetResultLabel(textBox1Valid && textBox2Valid);
return textBox1Valid && textBox2Valid;
}
private void SetResultLabel(bool validated)
{
if (validated)
label1.Text = string.Format("{0}:{1}", textBox1Value, textBox2Value);
else
label1.Text = string.Empty;
}
DaveBTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)
|
|
|
|
|
Hi
My application (Gaming AntiCheat Application) takes screenshots and uploads it to a server. But the image size is too big. I want to lower the image size by reducing the quality of the picture. But I don't know how to do it. I have searched CodeProject and Google but I couldn't see a satisfacting answer.
If you need the screenshot code that I am using, here it is:
int screenWidth = Screen.GetBounds(new Point(0, 0)).Width;
int screenHeight = Screen.GetBounds(new Point(0, 0)).Height;
Rectangle bounds = Screen.GetBounds(Point.Empty);
using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
}
Graphics graphicImage = Graphics.FromImage(bitmap);
graphicImage.SmoothingMode = SmoothingMode.AntiAlias;
Rectangle r = new Rectangle(150, 10, 130, 35);
graphicImage.DrawRectangle(new Pen(Color.White, 100), r);
string datetime = DateTime.Now.ToString().Replace(':', '.');
string datetime2 = datetime.Replace(' ', '.');
string cozunurluk= screenWidth + " x " + screenHeight;
graphicImage.DrawString(depo.username, new Font("Arial", 12, FontStyle.Bold), SystemBrushes.WindowText, new Point(110, 10));
graphicImage.DrawString(DateTime.Now.ToString(), new Font("Arial", 12, FontStyle.Bold), SystemBrushes.WindowText, new Point(110, 35));
graphicImage.DrawString(cozunurluk, new Font("Arial", 12, FontStyle.Bold), SystemBrushes.WindowText, new Point(110, 60));
Bitmap baskilogo = kaynaklar.baskilogo;
graphicImage.DrawImage(baskilogo, 321, 0, 236, 96);
string localresimadi = (depo.userid + "." + datetime2 + ".hl2" + ".bac");
bitmap.Save(localresimadi, ImageFormat.Jpeg);
depo.resimlist = depo.resimlist + ";" + localresimadi;
depo.ekrangoruntusuadedi++;
txtSSnr.Text = depo.ekrangoruntusuadedi.ToString();
graphicImage.Dispose();
bitmap.Dispose();
try
{
StreamReader oku = new StreamReader("upl.bac");
depo.uplbacsatir = rot13.use( oku.ReadLine() );
oku.Close();
oku.Dispose();
}
catch (FileNotFoundException)
{
depo.uplbacsatir = null;
}
StreamWriter yaz = new StreamWriter("upl.bac");
yaz.Write( rot13.use(depo.uplbacsatir) + rot13.use(localresimadi + ";"));
yaz.Close();
yaz.Dispose();
}
Thanks.
|
|
|
|
|
|
"You obviously didn't search hard enough, here's what I came up with using Google for two minutes:
http://msdn.microsoft.com/en-US/library/system.drawing.imaging.encoderparameter.aspx[^]"
I have seen that, but I didn't understand what to do exactly.
|
|
|
|
|
Theoretically, if you knew information about what was supposed to be on the screen at specific times you could probably pass time, location, and image hash instead of the entire image to identify cheating.
Need software developed? Offering C# development all over the United States, ERL GLOBAL, Inc is the only call you will have to make.
If you don't ask questions the answers won't stand in your way.
Most of this sig is for Google, not ego.
|
|
|
|
|
I couldn't exactly understand what you are trying to mean. Are you trying to say that I am making a keylogger-like application. This is just a anti-cheating application like X-ray Anti-Cheat. You can access the pictures it takes from http://www.xraygaming.com/
Or maybe I understood your message wrong
|
|
|
|
|