473,511 Members | 15,715 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is this possible? 'Dynamic' Code

jdn
I have a class called myConfigurationClass with 3 private members, and 3 public gets (so, 3 read-only properties). So, for instance

private members: _A, _B, _
public gets A, B,

Oh, and they are all strings. In particular, they are Connection strings for SQL Server

In my web config, I have an appSetting, let's call it "CurrentConnectionString", and its value is either "A", "B", or "C

How can you write code so that it reads the value of "CurrentConnectionString" and then executes the proper get

The typical way would be something like

Step 1) create a string to hold the value of the key

Step 2) using either case or if-else if-else, loop through and see what the value is, and do other stuff accordingl

Thus

System.Configuration.AppSettingsReader AppSettingsReader = new System.Configuration.AppSettingsReader()
string ConnectionStringType = (string)AppSettingsReader.GetValue("CurrentConnect ionString", typeof(string))
string ConnectionString = ""
if (ConnectionString == "A"

ConnectionString = myConfigurationClass.A

else if (ConnectionString == "B"

ConnectionString = myConfigurationClass.B

els

ConnectionString = myConfigurationClass.

Is there a way that I could dump the if - else stuff and write something like

string ConnectionString = myConfigurationClass.[ConnectionStringType]; //which doesn't wor

where it 'dynamically' writes the code that follows "myConfigurationClass.

TI

jdn
Nov 15 '05 #1
7 1389
Why not have one property that may return one of 3 values instead of 3
properties and needing to find out which you want?
"jdn" <ki******@earthlink.net> wrote in message
news:A5**********************************@microsof t.com...
I have a class called myConfigurationClass with 3 private members, and 3 public gets (so, 3 read-only properties). So, for instance:
private members: _A, _B, _C
public gets A, B, C

Oh, and they are all strings. In particular, they are Connection strings for SQL Server.
In my web config, I have an appSetting, let's call it "CurrentConnectionString", and its value is either "A", "B", or "C"
How can you write code so that it reads the value of "CurrentConnectionString" and then executes the proper get?
The typical way would be something like:

Step 1) create a string to hold the value of the key.

Step 2) using either case or if-else if-else, loop through and see what the value is, and do other stuff accordingly
Thus:

System.Configuration.AppSettingsReader AppSettingsReader = new System.Configuration.AppSettingsReader(); string ConnectionStringType = (string)AppSettingsReader.GetValue("CurrentConnect ionString",
typeof(string)); string ConnectionString = "";
if (ConnectionString == "A")
{
ConnectionString = myConfigurationClass.A;
}
else if (ConnectionString == "B")
{
ConnectionString = myConfigurationClass.B;
}
else
{
ConnectionString = myConfigurationClass.C
}

Is there a way that I could dump the if - else stuff and write something like:
string ConnectionString = myConfigurationClass.[ConnectionStringType]; //which doesn't work
where it 'dynamically' writes the code that follows "myConfigurationClass."
TIA

jdn

Nov 15 '05 #2
Normally, when people think they need to do this, they haven't looked for
better alternatives or designs. However, you're right that sometimes its
the best way, and it's never bad to know the options, so.... You can do what
you are asking using Reflection:
using System.Reflection;
....
Type ccType = myConfigurationInst.GetType();
string val = (string)ccType.InvokeMember( "A", BindingFlags.Public |
BindingFlags.GetProperty | BindingFlags.Instance, null, myConfigurationInst,
new object[] {/*args would go here*/});
This will do (slowly) the same thing as calling the property get like so:
string val = myConfigurationInst.A;

*please not that this was posted without a compiler handy, so you may need
to correct my enum / spelling memory before this would compile! The basic
concept here is to call Type.InvokeMember on the type of your object.


"jdn" <ki******@earthlink.net> wrote in message
news:54**********************************@microsof t.com...
Well, there are different scenarios where what I am asking about would be important (though there certainly is more than one way to skin a cat, as you
point out), so I'd like to know if it is possible.
Thanks.

----- Scott M. wrote: -----

Why not have one property that may return one of 3 values instead of 3 properties and needing to find out which you want?
"jdn" <ki******@earthlink.net> wrote in message
news:A5**********************************@microsof t.com...
> I have a class called myConfigurationClass with 3 private members, and 3
public gets (so, 3 read-only properties). So, for instance: >> private members: _A, _B, _C > public gets A, B, C
>> Oh, and they are all strings. In particular, they are Connection
strings for SQL Server. >> In my web config, I have an appSetting, let's call it "CurrentConnectionString", and its value is either "A", "B", or "C" >> How can you write code so that it reads the value of "CurrentConnectionString" and then executes the proper get? >> The typical way would be something like:
>> Step 1) create a string to hold the value of the key.
>> Step 2) using either case or if-else if-else, loop through and see
what
the value is, and do other stuff accordingly >> Thus:
>> System.Configuration.AppSettingsReader AppSettingsReader = new System.Configuration.AppSettingsReader();
> string ConnectionStringType = (string)AppSettingsReader.GetValue("CurrentConnect ionString",
typeof(string));
> string ConnectionString = "";
> if (ConnectionString == "A")
> {
> ConnectionString = myConfigurationClass.A;
> }
> else if (ConnectionString == "B")
> {
> ConnectionString = myConfigurationClass.B;
> }
> else
> {
> ConnectionString = myConfigurationClass.C
> }
>>>> Is there a way that I could dump the if - else stuff and write

something like: >> string ConnectionString =
myConfigurationClass.[ConnectionStringType];
//which doesn't work >> where it 'dynamically' writes the code that follows "myConfigurationClass." >> TIA
>> jdn


Nov 15 '05 #3
jdn


----- Philip Rieck wrote: -----

Normally, when people think they need to do this, they haven't looked for
better alternatives or designs. However, you're right that sometimes its
the best way, and it's never bad to know the options, so.... You can do what
you are asking using Reflection:
using System.Reflection;
....
Type ccType = myConfigurationInst.GetType();
string val = (string)ccType.InvokeMember( "A", BindingFlags.Public |
BindingFlags.GetProperty | BindingFlags.Instance, null, myConfigurationInst,
new object[] {/*args would go here*/});
This will do (slowly) the same thing as calling the property get like so:
string val = myConfigurationInst.A;

*please not that this was posted without a compiler handy, so you may need
to correct my enum / spelling memory before this would compile! The basic
concept here is to call Type.InvokeMember on the type of your object.
Thanks.

jdn
Nov 15 '05 #4
Solve this using the Abstract Factory design pattern. See "Design Patterns" by the "Gang of Four" -- Gamma, Helm, Johnson, Vlissides. Buy this book if you don't already have it. It was written in 1994, inspired by Christopher Alexander's 1977 "A Pattern Language: Towns/Buildings/Construction", and actual code examples are C++, but it is a timeless classic that covers the basics of OOAD. It is well organized and to the point -- you will be able to refer back to it quickly.

First, define a base class (say ConfigurationBase) with just one property, ConnectString. Then create three subclasses, AConfiguration, BConfiguration, and CConfiguration, each of which has its own straightforward logic to return its specific connect string through the ConnectString property. Note that "A", "B" and "C" can be fixed symbols (say Development, Test and Production), while the actual returned by the ConnectString property is their actual implemented value (e.g. "dsn=TheDevelServer;uid=TheDevelDb;...")

Finally, create a factory class (say ConfigurationFactory) with a method called NewConfiguration. Probably create two overloads, one that knows how o look up the appSetting itself, the other which just takes appSetting as a parameter (the value of appSetting being "A", "B" or "C", not the actual connect strings). Then NewConfiguration contains the ugly if/then/else or switch/case logic to decide which subclass to instantiate. The method returns whatever it creates as type ConfigurationBase.

This approach keeps all the branching crap out of your non-factory classes. Branching is kept to a minimum in the factory class, too -- just in one method. Each class has a specific responsibility, and doesn't try to be a jack-of-all-trades where each method and property is filled with senseless schizophrenia. Using the base class (or interface) type when referring to them outside of the factory frees you from caring which subtype even got instantiated. The code in each subclass will be much more straightforward.
Nov 15 '05 #5

Hi jdn,

Is your problem resolved?

For a quick start of .Net Reflection, please refer to:
http://msdn.microsoft.com/library/de...us/cpqstart/ht
ml/cpsmpnetsamples-howtoreflection.asp

It gives you a good and simple documentation and sample of Reflection.

If you have any further concern, please feel free to tell me, I will wor
with you.

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #6
jdn
I don't know yet for sure. I think that Philip's response that one should look at other alternatives is a valid one. Without further research and development, I can't say for certain.

But in the interim, I would say that the response I got was helpful in showing code that would do what I wanted, as well as suggesting other possibilities that might be better for the particular code situation I am looking at.

If I find anything that changes the 'interim response', I will post accordingly.

Thanks to all.

jdn

----- \"Jeffrey Tan[MSFT]\" wrote: -----
Hi jdn,

Is your problem resolved?

For a quick start of .Net Reflection, please refer to:
http://msdn.microsoft.com/library/de...us/cpqstart/ht
ml/cpsmpnetsamples-howtoreflection.asp

It gives you a good and simple documentation and sample of Reflection.

If you have any further concern, please feel free to tell me, I will wor
with you.

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
Nov 15 '05 #7

Hi jdn,

Thanks for your feedback.

No problem, please feel free to post, we will not ignore your post, :-)

I will help you at my best. (Do register your email address)

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Nov 15 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2931
by: CAD Fiend | last post by:
Hello, Well, after an initial review of my database by my client, they have completely changed their minds about how they want their form. As a result, I'm having to re-think the whole process....
7
8428
by: Carolyn Vo | last post by:
Hi, How can I call Java classes from C# code? I've seen the call in ASP ("NewJavaObject"), so I'm sure that I can do something similar in C# code. Please please please help, thanks!!!
6
1225
by: dw | last post by:
Hello, all. We're building a Web app where we can have any number of questions, which can contain any type of form element -- check boxes, text fields, radio buttons, dropdowns, etc. We'd like to...
4
2187
by: Zark3 | last post by:
Hi all, I was wondering if anybody could enlighten me on the possibility of dynamic casting. Or, well, whether or not I'm actually trying to do this the right way. What I have is a base class...
0
1095
by: bne | last post by:
Hi All, I have a shopping cart app that (I think) has broken due to an upgrade to .NET 2.0. Some products display fine: <http://ukweddinggroup.com/default.aspx?prd=11> Others display okay...
13
17110
by: salad | last post by:
Operating in A97. I didn't receive much of a response conserning Pivot tables in Access. Pivot tables are nice, but a CrossTab will work for me too. Using a Pivot table, one is actually...
25
3757
by: jwrweatherley | last post by:
I'm pretty new to python, but am very happy with it. As well as using it at work I've been using it to solve various puzzles on the Project Euler site - http://projecteuler.net. So far it has not...
71
3227
by: Jack | last post by:
I understand that the standard Python distribution is considered the C-Python. Howerver, the current C-Python is really a combination of C and Python implementation. There are about 2000 Python...
18
2269
by: Angus | last post by:
Hello We have a lot of C++ code. And we need to now create a library which can be used from C and C++. Given that we have a lot of C++ code using classes how can we 'hide' the fact that it is...
13
1174
by: DL | last post by:
For instance, function addNew(i) { var 'element'&i ... } If possible, how to? Thanks.
0
7251
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7148
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7367
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
7089
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7517
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
5072
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4743
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3217
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
451
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.