|
Hi all,
I'm a new programmer and I've come across a problem that I'll need some help in.
class MyObject1{...}
class MyObject2{...}
class MyObject3{...}
class MyObject4{...}
public void test(object a){
Type a = a.GetType();
//Now what?!
}
//Somewhere in main...I call test and pass it an instance of one of these objects...
test(new MyObject1());
test(new MyObject4());
test(new MyObject3());
test(new MyObject2());
What I'd like to know is how to convert variable 'a' into whatever object was passed into test();
This is probably a silly question but I'm learning....
Thanks in advance.
Humble.
|
|
|
|
|
Try to write a more useful subject line, that says something about your question. We're in the C# forum, so mentioning that in the subject is quite superflous. Almost everyone that starts a thread here need help, so that doesn't do anything at all to distinguish your thread from others.
To get a reference of a specific type, just cast the object reference:
if (a is MyObject1) {
MyObject1 a1 = (MyObject1)a;
}
or:
MyObject1 a1 = a as MyObject1;
if (a1 != null) {
}
As the reference has to be the exact type, there is no solution that handles any type. You have to write code to handle each type separately.
If the classes are supposed to work in a similar way, you might want to create a base class or an interface that defines some common methods, and make all the classes inherit the base class or interface. That way you can use a reference to the base class or the interface instead of a reference to the common base class Object .
---
single minded; short sighted; long gone;
|
|
|
|
|
Just to add - the difference between (MyObject)a and a as MyObject is that the first throws an exception and the second returns null if the cast is invalid.
Christian Graus - Microsoft MVP - C++
"I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )
|
|
|
|
|
I tried to use 'as' today and the compiler slapped me in the face (ie. it told me i was wrong)
It was just like this:
class something
{
//some private variables and whatnot
}
static void Main(string[] args)
{
object test = new something();
something newSomething = test as something;
}
and shwam, compiler throws som error.
My current favourite word is: Waffle
Cheese is still good though.
|
|
|
|
|
what was the error ?
Christian Graus - Microsoft MVP - C++
"I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )
|
|
|
|
|
I forget, i was using some microsoft visual express thingymajig, rather than my preferred SharpDevelop. I either spelled something wrong and couldn't see it, or the compiler was having a bad day.
Its working fine now (in #Develop)
My current favourite word is: Waffle
Cheese is still good though.
|
|
|
|
|
That code compiles just fine. What does the code look like that you are actually using, and what error message do you get?
---
single minded; short sighted; long gone;
|
|
|
|
|
I have the following regular expression almost working...
Regex myRegex = new Regex(
"(?<=<(?<tagName>\\S+)\\s+className=\"LiteralClassName.*?>\\s*)\\S.*?\\S(?=\\s*</\\k<tagName>>)", RegexOptions.Singleline);
Basically, I don't know the tag name, so I am using a match class to capture any tag that has an attribute "className" whose value begins with "LiteralClassName". Essentially, this regex is getting the innerXml property for all matching tags of this sort. One of the problems that I am having is that if the tag name is, say "Item", and another tag of type "Item" exists within the inner xml of what I am trying to capture, then I get f'ed. Is there some way to specify that there are an equal number of "<[^/]" and "</" between my tagName class (ie, to ensure that the number of start tags and end tags are equal)? Thanks,
Jeff
|
|
|
|
|
Although .Net's flavour of regex can deal with balanced, well, anything really (in your case "<") bending it to do what you want will be tough and unreadable, with a tomeic expression.
Do a search for balanced parenthesis in regex.
It sound like you're trying to parse an xml document and want a specific node .. for which XPath is ideally suited.
I'm largely language agnostic
After a while they all bug me
|
|
|
|
|
XPath may be able to help... if that is the way to go (vs. Regex), then does anyone know the syntax for "Get all nodes that have the property 'className' whose value begins with 'myClassName'". Basically, I have the following layout to the xml document...
...
<UnknownNodeName className="myClassName otherUnknownStuff">InnerXML</UnknownNodeName>
...
And I also don't know the path or parent to this node. All I know is that it has an attribute named className that begins with myClassName. Any insight? Thanks,
(I think it would be something like "//[@className='myClassName']", but replace '=' with a startswith operator)
Jeff
|
|
|
|
|
|
I am attempting to automate the downloading of a file from a website that requires user login. At this point i want to get clarification of the steps i need to follow to accomplish this. Currently i am doing the following (in pseudo code) without success:
--Make POST HttpWebRequest/HttpWebResponse of "Login.php" that posts login username and password;
--Get response cookie collection and put into CookieContainer variable;
--Make HttpWebRequest/HttpWebResponse of "Content.php"; assign CookieContainer variable to request;
--Get GetResponseStream of response and put HTML content into String;
--Parse HTML content for download link;
--Download link to disk;
--Process downloaded file....
With this code, the HTML retrieved from Content.php is for a webpage shown to users that have not loged on and so the download link is not shown. Below is test code for the above.
// ##################################################################
public void TEST()
{
// login
// forms authenticate
string loginUri = AppGlobal.LoginUrl;
string requestString = "username=" + AppGlobal.UserName + "&password=" + AppGlobal.Password + "&autologin=checked";
byte[] requestData = Encoding.UTF8.GetBytes(requestString);
HttpWebRequest request = null;
Stream stream = null;
HttpWebResponse response = null;
// set up request
_cookies = new CookieContainer();
request = (HttpWebRequest)WebRequest.Create(loginUri);
request.Proxy = null;
request.CookieContainer = _cookies;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = requestData.Length;
// make form post
stream = request.GetRequestStream();
stream.Write(requestData, 0, requestData.Length);
// get response
response = (HttpWebResponse)request.GetResponse();
// update cookies
foreach (Cookie returnCookie in response.Cookies)
{
// debug help
Debug.WriteLine("COOKIE: " + returnCookie.Name + " = " + returnCookie.Value);
// compare new cookie with stored cookie
// update cookie container
bool cookieFound = false;
foreach (Cookie oldCookie in _cookies.GetCookies(new Uri(AppGlobal.CookieUrl)))
{
if (returnCookie.Name == oldCookie.Name)
{
oldCookie.Value = returnCookie.Value;
cookieFound = true;
}
}
if (cookieFound == false)
{
_cookies.Add(new Uri(AppGlobal.CookieUrl), returnCookie);
}
}
// get webpage
request = (HttpWebRequest)WebRequest.Create(new Uri(AppGlobal.StartUrl));
request.Proxy = null;
request.CookieContainer = _cookies;
// get response
// check link
response = (HttpWebResponse)request.GetResponse();
string statusCode = response.StatusCode.ToString();
if (statusCode == "OK")
{
// handle cookies
foreach(Cookie returnCookie in response.Cookies)
{
bool cookieFound = false;
foreach(Cookie oldCookie in _cookies.GetCookies(new Uri(AppGlobal.CookieUrl)))
{
if (returnCookie.Name == oldCookie.Name)
{
oldCookie.Value = returnCookie.Value;
cookieFound = true;
}
}
if (cookieFound == false)
{
_cookies.Add(returnCookie);
}
}
// handle redirection
// get link html
StreamReader reader = new StreamReader(response.GetResponseStream());
string content = reader.ReadToEnd();
// check for failed log in
int position = content.IndexOf("Please log in to download");
if (position > -1)
{
Debug.WriteLine("FAILED");
}
Debug.WriteLine(content);
}
}
|
|
|
|
|
Have you already searched on Code Project? There are several articles that talk about how to do this, including this[^] one.
|
|
|
|
|
Yes, i have done search of the internet. I got code examples for downloading files using credentials. In order to download the file in my problem, user has to login to website using a POST webform, then go to webpage with link on it, then download link. One cannot go to webpage direct as webpage will not show download link without login cookie. One cannot go to download link directly as link changes name and so one must parse HTML for it first.
My problem is that after i do POST to the login page and get login cookies back, i cannot seem to use these cookies to retrieve the desired webpage. I keep getting the webpage version shown to users not logged in (which does not contain the download link). Since i am new at this, i am not sure what i am doing wrong.
|
|
|
|
|
Hi dude,
I've got the same problem here. I have figured out that the problem raises from the fact that the cookie returned to you from the first request is not persisted on the server, so you are not recognized when you request the second page. I am trying to solve this problem though. Please tell me if you've figured out the problem nearly after a year.
Thanks
|
|
|
|
|
Hi.
I am having trouble parsing a string into the format I want.
Basically, I want the string to end up being "MMdd" where MM is the month (with a leading zero if necessary) and dd is the day (with a leading zero if necessary).
This is what I have tried:
String today = DateTime.Today.Date.ToShortDateString();
String pattern = "MMdd";
DateTime dt_today = DateTime.ParseExact(today, pattern, null); // line 3
today = dt_today.ToString();
Console.WriteLine("today's date is: " + today);
The problem is that my program crashes once run. If you look at the third line, in place of null, I have tried sending: System.Globalization.CultureInfo.InvariantCulture, System.Globalization.CultureInfo.CurrentCulture
Both yielded the same result. I have also tried using "Now" instead of "Today" in the first line.
What am I doing wrong?
I'd appreciate any help.
|
|
|
|
|
I'd use an overload of the ToString method on the datetime, which allows you to specify the format. This looks like too many steps to take, to me.
Christian Graus - Microsoft MVP - C++
"I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )
|
|
|
|
|
Hi,
if you want your ParseExact to succeed, today must consist of exactly four digits.
So it all depends on your regional settings, which control the outcome of ToShortDateString().
You could try String today = DateTime.Today.Date.ToString("MMdd");
Luc Pattyn [Forum Guidelines] [My Articles]
this months tips:
- use PRE tags to preserve formatting when showing multi-line code snippets
- before you ask a question here, search CodeProject, then Google
|
|
|
|
|
What exactly are you trying to do? Do you already have a DateTime object that you are trying to display in a specific format? If so, you just need to call ToString on that object and pass the format string you want.
The code you show takes a DateTime object, converts it to a string, and then tries to parse that string and convert it back to a DateTime object, which you then call ToString on to turn it back into a string.
You can accomplish the same thing by doing this: Console.WriteLine("today's date is: " + DateTime.Today.ToString("MMdd"));
|
|
|
|
|
Thanks all for the replies!
I ended up using the overloaded ToString method.
|
|
|
|
|
I like how all the replies say the same thing
My current favourite word is: Waffle
Cheese is still good though.
|
|
|
|
|
I had a chance to learn WPF for a little while and found a useful feature which I want to create in WinForm, but not sure how to do so. I was wonder if there's a way to create an expander (just like how it work in WPF) in WinForm? Thanks...!
tant tant
|
|
|
|
|
You mean create a way for your form to expand or contract ? It won't work as smooth, but just run a timer, and inside it, set the size of your form, or your controls, or whatever.
Christian Graus - Microsoft MVP - C++
"I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )
|
|
|
|
|
Yes, In my WinForm, I want to create a function where i can expand and collapse each sections. Right now I have it by using UserControl and Panel, then each time a user hit the button it hides the Panel. However, the way I have it does not work so well because I'll then have to create a user control for each sections and one form and run to 10 sections. Please advice.
|
|
|
|
|
Is this[^] what you are looking for?
Take care,
Tom
-----------------------------------------------
Check out my blog at http://tjoe.wordpress.com
|
|
|
|