Showing posts with label variable. Show all posts
Showing posts with label variable. Show all posts

Saturday, March 31, 2012

String to a Class name

Hi,

I've got some classes to access different types of databases and I have a string variable that define the type of db I want to access. What I want to do if is pssible use the value of this variable to access the class. I have the following code now.


switch (dbType)
{
case "MSSQL": return MSSQL.msSQLDataSet(sqlString);
case "ACCESS": return ACCESS.msSQLDataSet(sqlString);
case "ORACLE": return ORACLE.msSQLDataSet(sqlString);
case "MYSQL": return MYSQL.msSQLDataSet(sqlString);

default: return null;
}

I want to do something like


SomekindOfTransformation(dbType).msSQLDataSet(sqlString)

instead of using theswitch statement

Thanks,Hi Arty,

You can achieve it using Object.GetType and Type.InvokeMember. VisitObject.GetType andType.InvokeMember for complete details.

Here is a sample code:

using System;
using System.Reflection;

// This sample class has a field, constructor, method, and property.
class MyType
{
Int32 myField;
public MyType(ref Int32 x) {x *= 5;}
public override String ToString() {return myField.ToString();}
public Int32 MyProp
{
get {return myField;}
set
{
if (value < 1)
throw new ArgumentOutOfRangeException("value", value, "value must be > 0");
myField = value;
}
}
}

class MyApp
{
static void Main()
{
Type t = typeof(MyType);
// Create an instance of a type.
Object[] args = new Object[] {8};
Console.WriteLine("The value of x before the constructor is called is {0}.", args[0]);
Object obj = t.InvokeMember(null,
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.CreateInstance, null, null, args);
Console.WriteLine("Type: " + obj.GetType().ToString());
Console.WriteLine("The value of x after the constructor returns is {0}.", args[0]);

// Read and write to a field.
t.InvokeMember("myField",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetField, null, obj, new Object[] {5});
Int32 v = (Int32) t.InvokeMember("myField",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.GetField, null, obj, null);
Console.WriteLine("myField: " + v);

// Call a method.
String s = (String) t.InvokeMember("ToString",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.InvokeMethod, null, obj, null);
Console.WriteLine("ToString: " + s);

// Read and write a property. First, attempt to assign an
// invalid value; then assign a valid value; finally, get
// the value.
try
{
// Assign the value zero to MyProp. The Property Set
// throws an exception, because zero is an invalid value.
// InvokeMember catches the exception, and throws
// TargetInvocationException. To discover the real cause
// you must catch TargetInvocationException and examine
// the inner exception.
t.InvokeMember("MyProp",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] {0});
}
catch (TargetInvocationException e)
{
// If the property assignment failed for some unexpected
// reason, rethrow the TargetInvocationException.
if (e.InnerException.GetType() !=
typeof(ArgumentOutOfRangeException))
throw;
Console.WriteLine("An invalid value was assigned to MyProp.");
}
t.InvokeMember("MyProp",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetProperty, null, obj, new Object[] {2});
v = (Int32) t.InvokeMember("MyProp",
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.GetProperty, null, obj, null);
Console.WriteLine("MyProp: " + v);
}
}

Hope this helps,
Appan
Thank you Appana, that helped me a lot.

String to Enumeration

Hello,

How do I convert a string an enumeration value?

I have the following Enum:

Public Enum MyEnum
Book = 1
Movie
End Enum

Basically, I have a variable of type MyEnum and I want to define a
value to it:

Dim MyString As String = "Book"
Dim MyVar As MyEnum = MyString

I am getting an error.
I then tried:
Dim MyVar As MyEnum = CType(MyString, MyEnum)

This is still not working.
Any idea of how to solve this?

Thanks,
MiguelFor outputing the string, just use MyEnum.ToString(). And to reverse the
operation, use Enum.Parse.

string variable containing one doublequote

hallo,

how do I declare a string variable containing one doublequote?

this sentence should be in the variable: <img src="http://pics.10026.com/?src=

I was trying something ilke

Dim Path as string = "<img src="http://pics.10026.com/?src= & """ but doesn' work

any idea? thanks

reply to myself: found out the solution

chr(34) instead of """


Dim Path as string = "<img src="http://pics.10026.com/?src= & """"

'/

Dim Path as string = "<img src="http://pics.10026.com/?src=""

'/

Dim Path as string = "<img src="http://pics.10026.com/?src= & Chr(34)

:)

Monday, March 26, 2012

string.ToString (IFormatProvider) doesnt take case of the provider ?

It's seem like a bug in the framework... but I'm not sure...
It's must seems weird, but I have a string variable and I want to apply a format and get the string formatted in that format. My original string is a numeric value and I want to obtain a string formatted based on the culture of the current thread.
string numericValue = "1234.56";
string returnValue = numericValue.ToString (System.Globalization.NumberFormatInfo.CurrentInfo);
But, it doesn't work. So, I check the code in the framework and there two methods ToString on the string Object. And both, return the this even the one with the provider parameter.

publicstringToString(IFormatProvider provider){returnthis;}
I you agree with me that there is a bug in the framework ?

hello.
i think that you're seeing it the wrong way.
what you want to do is get your number (ex.: double) and use the ToString method of that struct.
Double num = ...;
num.ToString( provider );
i think that using tostring with a provider on a string doesn't make any sense...

What I am trying to do is converting the format of a string from one culture to another. Say that you have a string 1 234,56 on the french-Canada culture and want to format the string to the english-US culture. I can parse the string to double and returning back to string. But I see that the string class have a method ToString who take a FormatProvider and do nothing with the parameter.


hello.

what i was trying to say is that if you're supposed to have a number, then use a variable of the desired type to keep it and parse it to the desired culture.


My simple solution is:
private void Form1_Load(object sender, EventArgs e)
{
double i = 1234.56;
textBox1.Text = i.ToString("0,000.00");

}

Thursday, March 22, 2012

Struct Default Constructor Question

When I create a new object of type struct, I want objects to be created for each member variable in that struct. For example:

private struct Strings {
public string s1;
public string s2;
}

Strings myStrings = new Strings();

Based on what I read, the default constructor for the struct should automatically initalize s1 and s2 to string.Empty implicitly. However, doing something like int size = myStrings.s1.Length throws a NullReferenceException. I don't understand why myStrings.s1 does not exist. Aren't s1 and s2 created automatically when I create a new object called myStrings??

Hello anonim:

> Based on what I read, the default constructor for the struct should automatically initalize s1 and s2 to string.Empty implicitly.

I'm afraid this is not correct. There's no implicit initialization of objects anywhere and your strings won't be created automatically.

So here is how one commonly would write it:

private struct Strings {
public string s1;
public string s2;

public Strings() {
s1 = String.Empty;
s2 = String.Empty;
}
}

Strings myStrings = new Strings();

Feel free to ask more.

HTH. -LV


Ludovico, thanks for your reply.

Per the MSDN [link]:

"Unlike a class, a struct is not permitted to declare a parameterlessinstance constructor. Instead, every struct implicitly has aparameterless instance constructor that always returns the value thatresults from setting all value type fields to their default value andall reference type fields to null. A struct can declare instance constructors having parameters."

So based on that, you cannot create a parameterless constructor for any struct (public Strings() { ...} does not compile - try it).

The statement above says all value type fields are set to their default value, and all reference type fields are set to null. Based on the fact that the implicit constructor does not initialize the string variables in my struct, I can safely assume that these string variables are reference types, correct? So, what I must do is to create a constructor with parameters and use that to instantiate and initialize the struct member variables.

Thanks for your help.

anonim:

> Unlike a class, a struct is not permitted to declare a parameterless instance constructor.

Yes, you are right, sorry...

> The statement above says all value type fields are set to their default value, and all reference type fields are set to null. Based on the fact that the implicit constructor does not initialize the string variables in my struct, I can safely assume that these string variables are reference types, correct?

Yes: String is a class, so strings are reference types, not value types.

> So, what I must do is to create a constructor with parameters and use that to instantiate and initialize the struct member variables.

Right again!

Cheers. :) -LV


Thank you much!

Structures in Session variables

Is it possible to store structures in Session variables?

I want to store some basic user details in a Session variable (first name, last name, join date, etc) and thought it would be easier to put them into a structure rather than holding them in separate variables.

Is this possible?

How do I do it?Hi,
You can put in Session anything that inherits from System.Object. In .NET it is virtually everithing (except interfaces and delegates) including structures. Having structure str you can do it like this:


Session("MyStruct") = str

Thanks.

If I subsequently want to delete the structure from the Session, can I just set Session("MyStruct") = null ?

Will this release all the individual components of the structure in one go?
Yes