Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Fanged Lawn Wormy
Jan 4, 2008

SQUEAK! SQUEAK! SQUEAK!
Well, I'm trying to create a log file for info dumps and messages that are triggered during operations. The easiest way to do this (as of yet) was to simply have messages go through a print object, which displays a message in the Max window (ie: settings saved, settings loaded, error sending email). The problem is, the Max Window isn't permanent - it can be cleared, and if the program is shut down, all record is lost.

So, I'm trying to get it to append all this data into a text file. I can think of two ways. 1) Have all message data simultaneously go to the max window and a text object which can write to an external file. 2) Have all data go to the max window, which is mirrored to the system console and exported using that.

I actually prefer the first option, but I've had some trouble getting the strings to come together properly. I may experiment with it some more, but I wanted to try this other option as well.

Adbot
ADBOT LOVES YOU

nielsm
Jun 1, 2009



Unix has a utility called 'tee', which takes standard input and writes to standard output, as well as to a file. Like this commandline:

./foo | tee foorun.txt

Will run foo and print its messages to the screen. It will also write everything printed to screen, to the file foorun.txt.

(This is not completely true. If the program also writes to standard error, those messages won't be redirected. In bash, you can add 2>&1 in before the |tee part, to redirect standard error to standard out.)

raminasi
Jan 25, 2005

a last drink with no ice

WrongWay Feldman posted:

1) Have all message data simultaneously go to the max window and a text object which can write to an external file.

This really is the best solution. Why don't you post some more details about what isn't working?

Fanged Lawn Wormy
Jan 4, 2008

SQUEAK! SQUEAK! SQUEAK!

GrumpyDoctor posted:

This really is the best solution. Why don't you post some more details about what isn't working?

Well, I'll try.

One of the main functions I need to tie in is a report of the time when events occur. I've already created the patches for that to happen. My preference is that when I output to the text file, it will read something like:

On 3/15/11 at 14:22:8 -- Event Foo Happened
--details on foo
--that may also show up

To do this, I'm attempted using the [sprintf] object, which can be used to combine symbols. For some reason though, only the time would ever appear in the printed output. At first I thought it may be due to the output of the objects info dump (like a java object I have) being a string. So I tried converting to symbol. That didn't work either. I also tried using symout to try and preserve it, since maybe it was dropping the info due to a space or something (unlikely). No luck.

I can probably figure this out eventually, but the time for me to work on it is gone, I've just got a huge dump of homework from my courses, and it'll be weeks before I get a chance to really come back to this with my whole mind to work on it.

defmacro
Sep 27, 2005
cacio e ping pong

nielsm posted:

In bash, you can add 2>&1 in before the |tee part, to redirect standard error to standard out.

Most shells support &| as a shortcut for 2>&1 |.

tripwire
Nov 19, 2004

        ghost flow

defmacro posted:

Most shells support &| as a shortcut for 2>&1 |.

Goddamn, thats a new one on me.

Jam2
Jan 15, 2008

With Energy For Mayhem
This year, I am running the officer election for my university tennis club. I want to use ballotbin.com to facilitate online voting. To do so, I need to enter email addresses for my club's 204 members. I am able to download a roster with the first and last names of all members. I also have the ability to send out mass emails to the 204 members. However, I cannot export a list of everyone's email addresses.

I could manually look up their email addresses in the online database. However, there must be a tech savvy way of accomplishing this.

What is needed to query this database

http://directory.acomp.usf.edu/?logo=1

and algorithmically write the email addresses of the 204 members to a csv or similar file so I can import them into the ballot software?

Do I need to use something like Python?

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Jam2 posted:

Do I need to use something like Python?

Yes. Don't know what a result page looks like, but unless it returns results in something crazy like a java applet, Python would probably do a fine job.

Jam2
Jan 15, 2008

With Energy For Mayhem

Thermopyle posted:

Yes. Don't know what a result page looks like, but unless it returns results in something crazy like a java applet, Python would probably do a fine job.

The site employs something that serves the result on the same page without need for a reload (like google instant). As you type, it begins to filter. Once the search has been narrowed down to 25 results, it displays them in block below the search box. I don't want to ignorantly assume it's ajax, but to the best of my understanding, ajax is what allows this. Right?

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Jam2 posted:

The site employs something that serves the result on the same page without need for a reload (like google instant). As you type, it begins to filter. Once the search has been narrowed down to 25 results, it displays them in block below the search box. I don't want to ignorantly assume it's ajax, but to the best of my understanding, ajax is what allows this. Right?

Yeah, I just looked at it again and type some random names in there and viewed the source. I didn't feel like reading over the code, but I think it will be doable with Python.

Carthag Tuek
Oct 15, 2005

Tider skal komme,
tider skal henrulle,
slægt skal følge slægters gang



Thermopyle posted:

Yeah, I just looked at it again and type some random names in there and viewed the source. I didn't feel like reading over the code, but I think it will be doable with Python.

#!/usr/bin/env python

import urllib, urllib2, cookielib
import time
import re

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
url = 'http://directory.acomp.usf.edu/?'

for name in iter(open('names.txt')):
  query = urllib.urlencode({'rsargs[]': [name.strip(), 3], 'rsrnd': int(time.time() * 1000.0), 'rs': 'liveSearch'}, doseq=True)
  resp = opener.open(url+query)
  name, email = re.search('td class=\\\\"leftcell\\\\">(.*?</td><td>.*?)</td>.*mailto:([^"]+)\\\\"', resp.read()).group(1,2)
  cleanname = re.sub('<[^>]+>', ' ', re.sub('</td><td>', ', ', name))
  print cleanname, email


Screenscraping is fun :)

Jam2
Jan 15, 2008

With Energy For Mayhem
Thanks for this. I've been thinking about how I was going to tackle this problem. I now see that I definitely would not have figured it out by the time I need it (midnight tonight when polls open). I have to get the emails in the system and send out notices before then. I still feel like I can learn a lot from simply trying to interpret your code, implement it, successfully execute it on a server, etc. So, thanks. Still need some assistance from anyone willing to help to figure out some addition questions I have:

How do I tell the program to essentially check off the student box?
How do I then tell the program to log in using my credentials?
Is time used to set a delay to allow the search engine to catch up?
Why are time and re imported on new lines? Are these libraries which are included inside of the libraries on the first line or is there a different reason? Are these called libraries?
The program prints the name and email. What if I wanted the program to present the emails on individual lines in a text file called emails.txt?
With which versions of python is this code compatible? When I started working with python over Christmas break, I noticed there were big differences between 3 and 2.6.x (e.g. print).
When I am ready to run this, should I do so from my local machine or should I execute it from a remote server? I have a Windows 2003 box if needed.

Carthag Tuek
Oct 15, 2005

Tider skal komme,
tider skal henrulle,
slægt skal følge slægters gang



Jam2 posted:

How do I tell the program to essentially check off the student box?
The number 3 after name.strip() indicates the checkboxes.

faculty = 1
staff = 2
student = 4

Add the numbers of the boxes you want checked for the query and put the result where the 3 is.

Jam2 posted:

How do I then tell the program to log in using my credentials?

That's what the cookiejar is for. If you can get your session outta your browser, you can put it into the jar. Another option is to do the login in the script. Locate the page that you log into, look at the field names in the form, and construct a query like the one in my script, then send that before the for loop. That should get you the cookie and put you in a state where you're allowed to search for students.

Jam2 posted:

Is time used to set a delay to allow the search engine to catch up?
Why are time and re imported on new lines? Are these libraries which are included inside of the libraries on the first line or is there a different reason? Are these called libraries?
There was a parameter in the query 'rsrnd' which I could see in the javascript was just filled out with a timestamp, so I figured I'd do the same thing. It's probably to avoid request spam and/or so the server can do some cache tricks and not go out to the backend if there's been a similar search just before the current one.

I like to import modules on separate lines as it's easier to update when it changes (if I don't need one anymore, I can just delete the entire line). You could also do import time, re, etc

Jam2 posted:

The program prints the name and email. What if I wanted the program to present the emails on individual lines in a text file called emails.txt?
You could change the print to not print the name, and pipe the program output into a file. Not sure how to do that on windows, but on unix it's >outfile.txt

Another option is
code:
out = open('out.txt', 'w') # before loop
out.write(email+'\n') # instead of print
out.flush() #after loop
out.close()

Jam2 posted:

With which versions of python is this code compatible? When I started working with python over Christmas break, I noticed there were big differences between 3 and 2.6.x (e.g. print).
I used python 2.7 I think

Jam2 posted:

When I am ready to run this, should I do so from my local machine or should I execute it from a remote server? I have a Windows 2003 box if needed.
It should be possible to run from any machine with python 2.x as long as it has a working connection.

Moey
Oct 22, 2010

I LIKE TO MOVE IT
I'm writing a small C# application that changes a registry value, but cannot figure out how to modify the registry using C#.

The key I want to edit is in HKLM\Software\Microsoft\WindowsNT\CurrentVersion\WinLogon\DefaultUserName

Anyone have a code snippit on how to do this? I scrapped some stuff from google, but it's crashes when ran.

code:
string username = textBox1.ToString();
Microsoft.Win32.RegistryKey key;
key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\WindowsNT\\CurrentVersion\\WinLogon");
key.SetValue("DefaultUserName",username);

nielsm
Jun 1, 2009



Moey posted:

The key I want to edit is in HKLM\Software\Microsoft\WindowsNT\CurrentVersion\WinLogon\DefaultUserName

Anyone have a code snippit on how to do this? I scrapped some stuff from google, but it's crashes when ran.

Are you sure your application has Administrator privileges? Writing to HKLM requires those.
When you get the crash, notice what exception caused it.

Orzo
Sep 3, 2004

IT! IT is confusing! Say your goddamn pronouns!

Moey posted:

I'm writing a small C# application that changes a registry value, but cannot figure out how to modify the registry using C#.

The key I want to edit is in HKLM\Software\Microsoft\WindowsNT\CurrentVersion\WinLogon\DefaultUserName

Anyone have a code snippit on how to do this? I scrapped some stuff from google, but it's crashes when ran.
You should catch the exception and see what it says whenever something 'crashes'

rolleyes
Nov 16, 2006

Sometimes you have to roll the hard... two?

Moey posted:

Registry

Is this to do with desk moves by any chance? :v:

Anyway, I'm not sure how much you know about C#/exceptions so if you're not sure what that's all about then run the program in debug mode in the IDE and it'll pop up an unhandled exception box with all the details.

Moey
Oct 22, 2010

I LIKE TO MOVE IT
I'm just trying to kill some time until I get to move more desks. :3:

I'm writing this on a Win 7 machine, but it will be running on XP, so I made that registry key manually on my box just for testing.

Looks like it craps out when executing that last line I posted.

NullReferenceException was unhandled
Object reference not set to an instance of an object.

And here are details (no idea if these are helpful).

code:
System.NullReferenceException was unhandled
  Message=Object reference not set to an instance of an object.
  Source=ResetLastLogon
  StackTrace:
       at ResetLastLogon.Form1.button1_Click(Object sender, EventArgs e) in C:\Users\moey\Desktop\ResetLastLogon\ResetLastLogon\ResetLastLogon\Form1.cs:line 24
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at ResetLastLogon.Program.Main() in C:\Users\moey\Desktop\ResetLastLogon\ResetLastLogon\ResetLastLogon\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

Moey fucked around with this message at 17:20 on Mar 25, 2011

Carthag Tuek
Oct 15, 2005

Tider skal komme,
tider skal henrulle,
slægt skal følge slægters gang



Looks like that key doesn't exist on the machine?

But why not just use a .reg file?

E: I guess it needs to be machine-/user-specific so a reg file is less than ideal unless there's a way to put variables in them.

Moey
Oct 22, 2010

I LIKE TO MOVE IT

Carthag posted:

Looks like that key doesn't exist on the machine?

But why not just use a .reg file?

E: I guess it needs to be machine-/user-specific so a reg file is less than ideal unless there's a way to put variables in them.

It seems to crash the same way on the box I'm writing it on (Win 7) and my test box (XP). The key is there on its own in XP, I manually created it myself on my Win 7 box to test also. Wonder if there is something wrong with the way I am writing the path to get to that specific key.

As for the reg file, that would be too easy :)

All I'm making is a little exe that I can have on a network share, so when I do work on someones PC, I run this, enter a user name into the text box, then click the button and it changes the last logged on user to whatever I type. This avoids confusion on their end (so they don't have to type their username next time they logon), and also I can do work and reset it so they don't know I was on their PC)

Moey fucked around with this message at 17:33 on Mar 25, 2011

odd2k
Jul 18, 2006
I DIDN'T CONTRIBUTE ANYTHING BUT A SHITTY POST SO I GOT THIS SHITTY CUSTOM TITLE!
I have a bit of a tricky algorithm question here. Say I have a class myClass, with two data members A and B. Now say I have a list of instances of class myClass. I want to iterate through the list and do the following test:

For each previous occurrence where myClass.A is equal to the one I'm currently checking, I want to check whether myClass.B is less than or equal to the B of said occurrence. If so, I want stuff to happen. I've got it kinda working, but the algorithm is factorial so the cost is O(n!). It's hardly ideal when the list contains millions of objects. Here's psuedocode of my current implementation:

code:
for(int i = 0; i<list.Count; i++)
{
	for(int i2 = 0; i2<i; i2++)
	{
		if(list[i].A == list[i2].A && list[i].B <= list[i2].B)
		{
			//make stuff happen
		}
	}
}
I'm thinking I could use a multimap, where myClass.A is the key and myClass.B the value, and then iterate through it like this:

code:
//myMultiMap is already pre-filled with contents of list
for(int i = 0; i < list.Count; i++)
{
	foreach(myClass mc in myMultiMap[list[i].A])
	{
		if(list[i].B <= mc.B)
		{
			//make stuff happen
		}
	}
}
I realize this test wouldn't work because it would find the exact same object it's checking, but that's the gist of it. Would something like this work? Is there a better way?

rolleyes
Nov 16, 2006

Sometimes you have to roll the hard... two?

Moey posted:

It seems to crash the same way on the box I'm writing it on (Win 7) and my test box (XP). The key is there on its own in XP, I manually created it myself on my Win 7 box to test also. Wonder if there is something wrong with the way I am writing the path to get to that specific key.

As for the reg file, that would be too easy :)

All I'm making is a little exe that I can have on a network share, so when I do work on someones PC, I run this, enter a user name into the text box, then click the button and it changes the last logged on user to whatever I type. This avoids confusion on their end (so they don't have to type their username next time they logon), and also I can do work and reset it so they don't know I was on their PC)

Your problem is that the line

key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey...

is returning null, so your attempt to then call one of key's methods fails because (like the exception says) it isn't set to an instance of an object.

As to why that is I'm not sure without trying it myself.

Sneftel
Jan 28, 2009

odd2k posted:

For each previous occurrence where myClass.A is equal to the one I'm currently checking, I want to check whether myClass.B is less than or equal to the B of said occurrence. If so, I want stuff to happen. I've got it kinda working, but the algorithm is factorial so the cost is O(n!). It's hardly ideal when the list contains millions of objects.
It's actually O(n^2), not O(n!). If it was factorial time, you'd never see it complete even with only fifteen instances.

quote:

I'm thinking I could use a multimap, where myClass.A is the key and myClass.B the value, and then iterate through it like this.... Would something like this work? Is there a better way?
That would work fine, but it can be simpler: Just sort all the instances by A, sorting by B in the case of ties between A's. Now all the matching As are together in a block, and sorted by B within that block; for each A-matched block, you just go through and do your thing for every pair of MyClasses in the block.

You could also do a hashmap of A's, with the value being a sorted set of B's. That's about as good as you can do, algorithmically speaking.

rolleyes
Nov 16, 2006

Sometimes you have to roll the hard... two?
Moey:

After a bit of dicking about, here's a version which will work but only if you're running the program with administrator privileges - that's required in order to write to HKLM. Failure to do so will result in a security exception and the subkey operation returning null. Also note the second parameter to the subkey function which specifies that the key should be writeable.

Caveat: I haven't actually tested this.

code:
string username = "wakkaWakkaWakka";
RegistryKey key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine,RegistryView.Default);
key = key.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon",true);
if (key == null)
{
  //Bad poo poo has happened, probably because you're not running as admin.
}
key.SetValue("DefaultUserName", username);
edit:
Also specify "using Microsoft.Win32" at the top of your class definition so you don't have to keep typing it out.

edit2:
I'm not sure if you've noticed but a big problem with your original code was that you missed the space in the "Windows NT" key. ;)

rolleyes fucked around with this message at 19:55 on Mar 25, 2011

odd2k
Jul 18, 2006
I DIDN'T CONTRIBUTE ANYTHING BUT A SHITTY POST SO I GOT THIS SHITTY CUSTOM TITLE!

Sneftel posted:

It's actually O(n^2), not O(n!). If it was factorial time, you'd never see it complete even with only fifteen instances.

Yeah, I was somehow thinking the cost was 1*2*3...*n when it's actually 1+2+3...+n. :downs:

Sneftel posted:

That would work fine, but it can be simpler: Just sort all the instances by A, sorting by B in the case of ties between A's. Now all the matching As are together in a block, and sorted by B within that block; for each A-matched block, you just go through and do your thing for every pair of MyClasses in the block.

Cool, I was thinking of sorting stuff but never gave it much thought. I'll try this method!

Sneftel posted:

You could also do a hashmap of A's, with the value being a sorted set of B's. That's about as good as you can do, algorithmically speaking.
I'm guessing a hashmap won't give any performance increase if the member objects A and B are simple value types like strings/ints?

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
You actually specifically don't want to sort on B here; the original order was important, because the magic only happens when a B value is out of descending order in the sequence of objects with like-valued As.

You could use a hash or something, but probably the best approach is to do a stable sort on A, then walk each sequence of like-valued As looking for a B that's out of sequence.

odd2k
Jul 18, 2006
I DIDN'T CONTRIBUTE ANYTHING BUT A SHITTY POST SO I GOT THIS SHITTY CUSTOM TITLE!

rjmccall posted:

You actually specifically don't want to sort on B here; the original order was important, because the magic only happens when a B value is out of descending order in the sequence of objects with like-valued As.

You could use a hash or something, but probably the best approach is to do a stable sort on A, then walk each sequence of like-valued As looking for a B that's out of sequence.

It just so happens that my class has a third member "line" that indicates its original order. The classes basically represent lines in a text file. So sorting both A and B will work out, I think.

edit: Although I might as well just sort A, and use B to identify original order. It'll require less sorting, if nothing else.

odd2k fucked around with this message at 20:18 on Mar 25, 2011

Moey
Oct 22, 2010

I LIKE TO MOVE IT

rolleyes posted:

I'm not sure if you've noticed but a big problem with your original code was that you missed the space in the "Windows NT" key. ;)

Missing details always kills me.

Thanks for the help, if you were on my side of the pond I would gladly buy you a beer.

Currently when I run the program, and input something, this is how the registry key changes.

quote:

System.Windows.Forms.TextBox, Text: WhateverUserNameITyped

Not sure why that additional text is getting dumped, will have to dick around with it more tonight to figure it out.

Carthag Tuek
Oct 15, 2005

Tider skal komme,
tider skal henrulle,
slægt skal følge slægters gang



Moey posted:

Not sure why that additional text is getting dumped, will have to dick around with it more tonight to figure it out.

Looks like it could be the C# equivalent of Java's toString() - you're setting the value of the key to the actual textbox, not hte contents of it. You'll probably want to call .getValue() or .getText() or whatever it is on the username you're setting, like

key.SetValue("DefaultUserName", username.getValue());

Moey
Oct 22, 2010

I LIKE TO MOVE IT

Carthag posted:

Looks like it could be the C# equivalent of Java's toString() - you're setting the value of the key to the actual textbox, not hte contents of it. You'll probably want to call .getValue() or .getText() or whatever it is on the username you're setting, like

key.SetValue("DefaultUserName", username.getValue());

That's the first thing I tried, changed it to username.ToString(), still write the same thing to the reg key. You figure if it accepts a string as the key, and I give it a string, all would be well. I really should keep up on my programming skills.

Carthag Tuek
Oct 15, 2005

Tider skal komme,
tider skal henrulle,
slægt skal følge slægters gang



NB: I am speaking from Objective-C/Java experience, but this seems like what is happening here.

Moey posted:

That's the first thing I tried, changed it to username.ToString(), still write the same thing to the reg key. You figure if it accepts a string as the key, and I give it a string, all would be well. I really should keep up on my programming skills.

ToString() is implicitly called on the object when the object is being accessed in a string context (such as printing or apparently setting a value in a registry key). TextBox.ToString() will return a string describing that it is a textbox, and what its value is. So you shouldn't call ToString() unless you want that. A quick google says that you can access the contents through the Text property, so:

key.SetValue("DefaultUserName", username.Text);

Assuming username is your TextBox.

Mr.Hotkeys
Dec 27, 2008

you're just thinking too much
What you want is to use username.Text instead of username.ToString()

e: Wow holy dooley thanks for loading the cached version of the page, Firefox

rolleyes
Nov 16, 2006

Sometimes you have to roll the hard... two?
Just to explain this for Moey's benefit, the reason for this behaviour comes down to objects. Let's say your text box is called "userName". UserName is the name of the instance of the TextBox class representing the text box on the form and, like any class, it has various methods and properties.

In C# every class1 has a method call ToString, because every class is derived from the System.Object object which contains that method. As Carthag has explained, because C# knows every class has a ToString method it will accept the name of an object in place of a string value and automatically call ToString instead. The default behaviour of ToString is just to give the name of the object and sometimes a few other details, which is what you're seeing when you pass your userName object to SetValue.

As has been mentioned the "text" property returns a string containing the text currently in userName text box. If, for example, you used userName.name instead then you'd get a string containing the name of the userName text box. The documentation for the TextBox class is here or you can poke around in the intellisense list in Visual Studio to find out about the provided methods and properties.



1: Not true for static classes but explaining static vs. dynamic is a whole lot of extra typing.

rolleyes fucked around with this message at 08:07 on Mar 26, 2011

Mr.Hotkeys
Dec 27, 2008

you're just thinking too much

rolleyes posted:

As Carthag has explained, because C# knows every class has a ToString method it will accept the name of an object in place of a string value and automatically call ToString instead.

Not exactly, TextBox just has an implicit cast to string method that returns the value of ToString(). Say you start a new console program, then make a class called testclass and add a ToString() override to it. If you just do this:
code:
class Program
{
    static void Main(string[] args)
    {
        testclass tc = new testclass();
        testmethod(tc);
    }

    static void testmethod(string s)
    { }
}

class testclass
{
    public override string ToString()
    {
        return "sadsad";
    }
}
There will be an error. You'd have to add this to your class (testclass in this example):
code:
public static implicit operator string(testclass tc)
{
     return tc.ToString();
}
e: rolleyes, were you maybe thinking of how the debugger automatically calls ToString() to get a string representation of variables for the watch list, etc? That hosed me over when I was doing some stuff a few months ago, took me a few hours to find what the problem was :doh:

Mr.Hotkeys fucked around with this message at 08:27 on Mar 26, 2011

rolleyes
Nov 16, 2006

Sometimes you have to roll the hard... two?
As much as I'd like to accept your excuse I actually just had a brainfart so yeah, listen to Mr.Hotkeys for that part of the explanation. The bit about ToString always being present is right though, so you can rely on it being there when writing code.

edit:
I also wasn't actually aware that the IDE uses ToString for watches, locals etc although it makes sense now that you mention it. Of course, I had to test it. :v:

code:
public override string ToString()
{
    return "System.Object";
}
Well look at that!

rolleyes fucked around with this message at 08:38 on Mar 26, 2011

Thel
Apr 28, 2010

(C# + crystal reports, loading up 12 different reports, running up to five selection formulars on each report, then exporting to PDF)

Augh, FML. Spent three hours trying to figure out why my reports weren't working properly. Turns out there's a big difference between Report.Refresh() and Report.RefreshReport(). :suicide:

Aaaanyway. Got nearly everything working.

The only problem is that, as far as I can tell, there's no way from the program side to see if there's any data in the report. Which is a bit of a problem, since of the ~50 reports I generate, up to half of them can be blank (and I'd really like to not export those).

What am I missing?

(The ReportDocument class has a Rows member, but it doesn't have anything useful. IDGI.)

e: Sounds like I have to connect to the database from my application, put together a DataSet and if that's not empty feed it to the report. gently caress. My. Life. Who designed this poo poo?

Thel fucked around with this message at 09:09 on Mar 26, 2011

Moey
Oct 22, 2010

I LIKE TO MOVE IT
I may be missing something here, or I didn't explain properly. (Probably missing something...)

From my program, my textbox is called textBox1, on event (button click) I call String username = textBox1.ToString()

So that is dumping whatever is in my textbox to the string username. From stuff I have done in the past, I shouldn't have to add anything when I use username as a parameter if it requires a string. Here is my current tiny chunk of code.

code:
string username = textBox1.ToString();
Microsoft.Win32.RegistryKey key;
key=Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\WindowsNT\\CurrentVersion\\WinLogon");      
key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default);
key = key.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon", true);
if (key == null)
MessageBox.Show("Are you not an admin?", "Really?", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
else
{
key.SetValue("DefaultUserName", username);
MessageBox.Show("Last logon changed!", "Hooray!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
} 

Moey fucked around with this message at 15:36 on Mar 26, 2011

nielsm
Jun 1, 2009



Moey posted:

From my program, my textbox is called textBox1, on event (button click) I call String username = textBox1.ToString()

Nonono, the contents of the text box, which is what you want, is retrieved by textBox1.Text.
You do not want to call ToString(). The ToString() method is generally mostly useful for debugging, as a way of getting some description useful for debugging out of the object. You shouldn't be using it for actual problem solving.

Moey
Oct 22, 2010

I LIKE TO MOVE IT

nielsm posted:

Nonono, the contents of the text box, which is what you want, is retrieved by textBox1.Text.
You do not want to call ToString(). The ToString() method is generally mostly useful for debugging, as a way of getting some description useful for debugging out of the object. You shouldn't be using it for actual problem solving.

Thanks, that was it.

key.SetValue("DefaultUserName", textBox1.Text);

Feeling pretty dumb about this right now. I feel like I have used .ToString() in the past to get text from text boxes. And then have used that string to dump the text into different things. My brain may just be turning into applesauce.

Thanks all.

Adbot
ADBOT LOVES YOU

rolleyes
Nov 16, 2006

Sometimes you have to roll the hard... two?
To reiterate, ToString() is a method inherited by all classes from the System.Object base class which (by default) returns a string containing a basic description of the class. The Text property of the TextBox class allows you to retrieve (and also to set) the string contained in the text box - this is the one you want.

If you're planning on doing much work with C# I'd suggest picking up a foundation book because you need to learn a bit more about some of the concepts and how the .NET library works. I've recommended this one to people before with favourable results. Plus the guy's name is Sharp! :v:

rolleyes fucked around with this message at 15:46 on Mar 26, 2011

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply