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.
 
  • Locked thread
Fastbreak
Jul 4, 2002
Don't worry, I had ten bucks.

The Noble Nobbler posted:

I'm not sure the exact point of the quiz, because I would write that like this:

(I made up ConnStr and CommandText because I couldn't remember what they were)

code:
 
using(SqlCommand comm = new SqlCommand())
{
  try
  {
    comm.ConnStr =  GetSetting("Constring");
    comm.CommandText = "InsertStuff";
    comm.Parameters.Add(...); 
    comm.CommandType = CommandType.StoredProcedure; 
    comm.Connection.Open(); 
    comm.ExecuteNonQuery(); 
  }
  catch (Exception ex) 
  { 
     LogError(ex); 
     return false; 
  } 
  return true;
}

... you didn't even try to close the connection. Anywhere.

Begby posted:

In your finally block, just test the state of the connection before you try to close it. It will probably be null, or the state property will show it as being not open, step it through a debugger to see.

I have already, if you try to test the state of a connection before it has properly been instatiated, you get an error.

Adbot
ADBOT LOVES YOU

csammis
Aug 26, 2003

Mental Institution

Fastbreak posted:

... you didn't even try to close the connection. Anywhere.

It gets closed in the end of the using block. And disposed. That's the point.

MSDN doesn't close it either! :monocle:


edit: hurf durf, I thought the code example was an SqlConnection, not an SqlCommand

The Noble Nobbler
Jul 14, 2003

Fastbreak posted:

... you didn't even try to close the connection. Anywhere.

SqlCommand will close the connection depending on the state on the severity level of the exception you get (but only in the case of those relating to SqlExceptions)

I'm confused, then. Are you asking for fun to see if someone guesses a way to fix this, or are you asking for a good way to write what you're doing?

MrBishop
Sep 30, 2006

I see what you did there...

Soiled Meat
^^^^^
I've used the ADO.NET connections quite a lot, but I was bored so decided to check the link. Is it just me, or does the information on that page seem a little confusing?

MSDN posted:

.NET Framework Class Library
SqlConnection Class

Represents an open connection to a SQL Server database.
Ok, so SqlConnection is an open connection. So what does it become when you close the connection? Is it automatically open when you create it?

MSDN posted:

If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose.
...
To ensure that connections are always closed, open the connection inside of a using block, as shown in the following code fragment. Doing so ensures that the connection is automatically closed when the code exits the block.

I know this is pedantic bullshit, but I can just imagine someone who's just learning ADO.NET coding their connection in a using block AND calling Dispose on it.

The Noble Nobbler
Jul 14, 2003

MrBishop posted:

^^^^^
I've used the ADO.NET connections quite a lot, but I was bored so decided to check the link. Is it just me, or does the information on that page seem a little confusing?

Ok, so SqlConnection is an open connection. So what does it become when you close the connection? Is it automatically open when you create it?

If I understand it correctly, a call to open is a request to open or a request for an already open and similar connection from the connection pool. A call to close is an explicit close or a request to release a connection back to the connection pool.

MrBishop posted:

I know this is pedantic bullshit, but I can just imagine someone who's just learning ADO.NET coding their connection in a using block AND calling Dispose on it.

Yeah, but if you use any syntactic sugar like that, you should really be aware it's just an implicit way of ... being explicit.

Fastbreak
Jul 4, 2002
Don't worry, I had ten bucks.

The Noble Nobbler posted:

SqlCommand will close the connection depending on the state on the severity level of the exception you get (but only in the case of those relating to SqlExceptions)

I'm confused, then. Are you asking for fun to see if someone guesses a way to fix this, or are you asking for a good way to write what you're doing?

This is just for fun, an obvious work around is to declare the connection object seperately from the command declaration. I can't think of a good way to do this either, thats why this is fun. It just feels like that code sample should do what is expected, but it doesn't and I was hoping to learn something if someone figures out a way.

Fastbreak fucked around with this message at 22:08 on Jun 13, 2008

The Noble Nobbler
Jul 14, 2003

Fastbreak posted:

This is just for fun, an obvious work around is to declare the connection object seperately from the command declaration. I can't think of a good way to do this either, thats why this is fun. It just feels like that code sample should do what is expected, but it doesn't and I was hoping to learn something if someone figures out a way.

Honestly, it does exactly what's expected (not trying to be a dick) because it's a pretty wonky code sample

I'd just wrap it in two usings or, if you just want to keep it like it is, have null checks before you dispose (and just call dispose, not close and dispose)

dwazegek
Feb 11, 2005

WE CAN USE THIS :byodood:
Or do:
code:
try
{
    //
}
finally
{
    //maybe change the order of these 2 statements, probably won't matter.
    comm.Dispose();
    using(comm.Connection) { }
}
No null check needed :downs:

Fastbreak
Jul 4, 2002
Don't worry, I had ten bucks.

dwazegek posted:

Or do:
code:
try
{
    //
}
finally
{
    //maybe change the order of these 2 statements, probably won't matter.
    comm.Dispose();
    using(comm.Connection) { }
}
No null check needed :downs:

This seems.... I will be honest, I don't follow at all how that would work givn the goal of the function.

Apparently others don't find it as interesting as I, I'll just let it go.

poopiehead
Oct 6, 2004

Also accessing the command after disposing it is dangerous. The connection property isn't guaranteed to be valid anymore.

You could also get both of them closed by putting both in the same using block:

code:
using(SqlConnection conn = GetSetting("Constring"), 
  SqlCommand comm = new SqlCommand("InsertStuff", conn)) 
{ 
  try 
  { 
    comm.Parameters.Add(...); 
    comm.CommandType = CommandType.StoredProcedure; 
    comm.Connection.Open(); 
    comm.ExecuteNonQuery(); 
  } 
  catch (Exception ex) 
  { 
    LogError(ex); 
    return false; 
  } 
  return true; 
}

biznatchio
Mar 31, 2001


Buglord

poopiehead posted:

You could also get both of them closed by putting both in the same using block:

When I need multiple disposable objects scoped together, I actually insert multiple using statements, such as:

code:
using (SqlConnection conn = new SqlConnection())
using (SqlCommand comm = new SqlCommand("InsertStuff", conn))
{
    // do poo poo here
}
It just looks cleaner to me, and Visual Studio just so happens to automatically indent it with the using blocks all flush against each other (as they are above) so it's clean.

Richard Noggin
Jun 6, 2005
Redneck By Default
What's the best way to handle mutually exclusive command line args in a .NET app? For example, if an application has the argument syntax myApp.exe -a -b -c, and options b and c are mutually exclusive:

myApp.exe -a -b Proceed...
myApp.exe -b -c You naughty boy you...

csammis
Aug 26, 2003

Mental Institution

Richard Noggin posted:

What's the best way to handle mutually exclusive command line args in a .NET app? For example, if an application has the argument syntax myApp.exe -a -b -c, and options b and c are mutually exclusive:

myApp.exe -a -b Proceed...
myApp.exe -b -c You naughty boy you...

That isn't really a .NET question, but anyway. You handle it however you want to handle it. Decide whether to print a message saying they screwed up, use the most recently defined option, or whatever else you can think might be valid. My choice would be the first - they're passing invalid input to the application, it shouldn't continue.

The Noble Nobbler
Jul 14, 2003
With the death of App_Code for Web Application Projects, what is a good location to place source files?

I have a legacy project that has datasets and certain .cs files inside the WAP, but they seem really out of place. Should these be migrated to a separate project?

Fastbreak
Jul 4, 2002
Don't worry, I had ten bucks.

poopiehead posted:

Good stuff

biznatchio posted:

Good stuff

Thats the kind of stuff I was talking about, thats pretty clever. Thanks.

Edit:

After messing with it, this:

code:
using(SqlConnection conn = GetSetting("Constring"), 
  SqlCommand comm = new SqlCommand("InsertStuff", conn)) 
{ 
  try 
  { 
    comm.Parameters.Add(...); 
    comm.CommandType = CommandType.StoredProcedure; 
    comm.Connection.Open(); 
    comm.ExecuteNonQuery(); 
  } 
  catch (Exception ex) 
  { 
    LogError(ex); 
    return false; 
  } 
  return true; 
}
Should actually be this:
code:
try 
  { 
     using(SqlConnection conn = GetSetting("Constring"), 
     SqlCommand comm = new SqlCommand("InsertStuff", conn)) 
     { 

        comm.Parameters.Add(...); 
        comm.CommandType = CommandType.StoredProcedure; 
        comm.Connection.Open(); 
        comm.ExecuteNonQuery(); 
        return true; 
     } 
  catch (Exception ex) 
  { 
    LogError(ex); 
    return false; 
  } 
}
If the using statement is outside of the try, it will still throw an error on the declaration of the false connection string and give the ugly error. Either way, the idea is sound. Thanks again for putting my mind at ease.

Fastbreak fucked around with this message at 18:43 on Jun 16, 2008

Richard Noggin
Jun 6, 2005
Redneck By Default

csammis posted:

That isn't really a .NET question, but anyway. You handle it however you want to handle it. Decide whether to print a message saying they screwed up, use the most recently defined option, or whatever else you can think might be valid. My choice would be the first - they're passing invalid input to the application, it shouldn't continue.

Yeah, that part I get - maybe I should have been more specific. Would you mind posting some sample code that shows how mutually exclusive arguments are handled? My programming knowledge is still in its infacy. I just can't think of a clean way to handle stuff like this.

The Noble Nobbler
Jul 14, 2003

Fastbreak posted:

If the using statement is outside of the try, it will still throw an error on the declaration of the false connection string and give the ugly error. Either way, the idea is sound. Thanks again for putting my mind at ease.

You should really be bubbling that error up to a more appropriate place to catch it because you don't want to wrap every single statement that needs a connection string in a try catch or you'll start to get some really ugly code

I would also recommend using the strongly typed configuration object to get your connection string from your app or web.config

Fastbreak
Jul 4, 2002
Don't worry, I had ten bucks.

The Noble Nobbler posted:

You should really be bubbling that error up to a more appropriate place to catch it because you don't want to wrap every single statement that needs a connection string in a try catch or you'll start to get some really ugly code

I would also recommend using the strongly typed configuration object to get your connection string from your app or web.config

Thanks. But this was just an example of an idea I whipped up. We also don't name sprocs "InsertStuff".

boo_radley
Dec 30, 2005

Politeness costs nothing

Goonamatic posted:

I just use my function


are resource files frowned on for this kind of thing? I think they cut down on this sort of cluttert immensely.

wwb
Aug 17, 2004

The Noble Nobbler posted:

With the death of App_Code for Web Application Projects, what is a good location to place source files?

I have a legacy project that has datasets and certain .cs files inside the WAP, but they seem really out of place. Should these be migrated to a separate project?

poo poo yes. App_Code was never a really appropriate place for anything in anything more complex than demo projects IMHO. Then again, I am kind of a project structure nazi.

The Noble Nobbler
Jul 14, 2003

wwb posted:

poo poo yes. App_Code was never a really appropriate place for anything in anything more complex than demo projects IMHO. Then again, I am kind of a project structure nazi.

Yeah I ended up doing this, it worked for 99% of the code, and it's pretty nice

if wishes were knishes
Mar 5, 2006

Hi I'm Buddy-dot-gif
I've been coding in php/java/c for quite some time now, and have decided to pick up on .Net

Is this something that, with past experience in other languages, has an easier learning curve?

I've perused through some random code, and I see a lot of familiar concepts. What would you suggest to read to get a somewhat-solid grasp of the language.

Small
Aug 18, 2005

Stupid question: I'm playing around with some networking stuff and the protocol I'm using requires a lot of 0xFF bytes within messages. For example, to query the server's status I need to send four 0xFF bytes plus a null-terminated ASCII string. My first instinct was to do this:
code:
string query = "\xFF\xFF\xFF\xFFTSource Engine Query\x00";
Byte[] bytesToSend = Encoding.ASCII.GetBytes(query);
but the first four bytes actually end up being 63 ('?'). I'm pretty sure this is due to Unicode issues -- \xFF becomes a non-ASCII character, which gets mapped to ASCII '?' before it's cast into a Byte.

I messed around with using Unicode/UTF8/UTF7 instead of ASCII but of course they don't give the right results either. Right now I'm just appending the above snippet with for(int i=0; i<4; i++) bytesToSend[i] = 255; but any easier way to insert the bytes inline with the string would be appreciated.

csammis
Aug 26, 2003

Mental Institution

Small posted:

any easier way to insert the bytes inline with the string would be appreciated.

Appreciated, but not possible :( This is why you really shouldn't represent binary data in string form.

Cazlab
Oct 25, 2003

Anyone have any idea how to get cascading dropdowns...
Without setting up a webservice (so that puts the AJAX control out of the question)
and have the cascading dropdowns be in a repeater?

I've scoured google many times for this, and come up empty handed. I even bought plat this morning to search CoC for a solution, but search is currently disabled :( so I apologize if it's already been asked.

wwb
Aug 17, 2004

Hmm, I think you could use jQuery to build something like that. How were you planning on feeding the data to them without using a web service?

Cazlab
Oct 25, 2003

wwb posted:

Hmm, I think you could use jQuery to build something like that. How were you planning on feeding the data to them without using a web service?

I've got a stored procedure.

It's a category -> subcategory -> subsub category kind of thing.
All of them are in the same table, and use parent->child->grandchild type relationships.

My boss is pretty adamant about not using a web service, because "it's too much hassle."
I'd already have it done if I could use a webservice.

I'll look into jQuery, but I was really hoping for more of a just .NET solution.
We don't have the jQuery library installed currently and our codebase is big enough :downs:

Dromio
Oct 16, 2002
Sleeper

Cazlab posted:

I'll look into jQuery, but I was really hoping for more of a just .NET solution.
We don't have the jQuery library installed currently and our codebase is big enough :downs:
I'm not wholly sure I follow what you want exactly. If you're not avoiding postbacks, you can just populate the second dropdown with after the first one raises it's selection changed event.

But if you want something to happen completely on the client side, you'll probably have to build up all the possibilities into a javascript object and use a client-side script to handle it all (with jQuery making it easier to write).

And yes, the easiest would probably be a webservice to feed asp.net ajax control. You might just need to spend some time convincing your boss that it's really simple. I know I thought it was a hassle until I sat down and wrote one. Then I saw it took all of 10 minutes.

wwb
Aug 17, 2004

Tell your boss to gently caress himself--the web service is basically just writing a single method and decorating it with a [WebMethod] attribute. Much easier than crafting your own cascading drop down with associated UI management and data interfaces.

Cazlab
Oct 25, 2003

If I go cowboy and just whip up a version of the page using the ajax control, which hI think is my plan at the moment, would the webservice complicate hosting of the site? We are running the same/similar code on 70 something different domains served by four different servers and it would need to work the same on all without negatively affecting load. I'm afraid the "hassle" he's referring to is in regards to that rather than development because building the webservice doesn't look like a hassle at all.

wwb
Aug 17, 2004

No complications whatsoever, presuming said sites are already running ASP.NET and no one did something really funny to the configuration.

FinkieMcGee
May 23, 2001

Look, I have to go identify our dead father's body. I'm sorry you're having a bad drug experience, but deal with it.
I have a question regarding LoadControl...

Let's say I use LoadControl to dynamically load a control onto my ASP page. Let's also say that within that control, I do some magic and register some script blocks.

Is LoadControl going to have issues with me doing this dynamically, as in will the script block be registered by the page despite the fact that I'm doing a bunch of weird crap outside the page lifecycle?

The Noble Nobbler
Jul 14, 2003

FinkieMcGee posted:

I have a question regarding LoadControl...

Let's say I use LoadControl to dynamically load a control onto my ASP page. Let's also say that within that control, I do some magic and register some script blocks.

Is LoadControl going to have issues with me doing this dynamically, as in will the script block be registered by the page despite the fact that I'm doing a bunch of weird crap outside the page lifecycle?

Controls added dynamically will play "catch-up" to fire all events up to the part in the page lifecycle in which they were added.

uXs
May 3, 2005

Mark it zero!
Linq to SQL, interfaces, ... question:

I'm getting a generic list of objects of type A from a database, with a function that first performs a Linq query and then does a queryResult.ToList() to return "List<A>".

A implements the interface IA. What I actually want to do is instead of returning a List<A>, is to return a List<IA>. (I want to use that list in other functions that should accept any List<IA>.) But then I get errors like "Cannot implicitly convert type 'A' to 'IA' at ..."

Any ideas ?

dwazegek
Feb 11, 2005

WE CAN USE THIS :byodood:

uXs posted:

Linq to SQL, interfaces, ... question:

I'm getting a generic list of objects of type A from a database, with a function that first performs a Linq query and then does a queryResult.ToList() to return "List<A>".

A implements the interface IA. What I actually want to do is instead of returning a List<A>, is to return a List<IA>. (I want to use that list in other functions that should accept any List<IA>.) But then I get errors like "Cannot implicitly convert type 'A' to 'IA' at ..."

Any ideas ?

queryResult.Cast<IA>().ToList()

Cazlab
Oct 25, 2003

Dromio posted:

I'm not wholly sure I follow what you want exactly. If you're not avoiding postbacks, you can just populate the second dropdown with after the first one raises it's selection changed event.

That's pretty much what I ended up doing:

code:
protected void OnParentIndexChange(object sender, System.EventArgs e)
        {
            
            ((DropDownList)((DropDownList)sender).Parent.FindControl("txtChildID")).DataSource = GetSublevelCategories(Convert.ToInt32(((DropDownList)((DropDownList)sender).Parent.FindControl("txtParentID")).Items[Convert.ToInt32(((DropDownList)((DropDownList)sender).Parent.FindControl("txtParentID")).SelectedIndex)].Value), null);
            ((DropDownList)((DropDownList)sender).Parent.FindControl("txtChildID")).DataTextField = "ChildCategoryDescription";
            ((DropDownList)((DropDownList)sender).Parent.FindControl("txtChildID")).DataValueField = "ChildCategoryID";
            ((DropDownList)((DropDownList)sender).Parent.FindControl("txtChildID")).DataBind();
            ((DropDownList)((DropDownList)sender).Parent.FindControl("txtChildID")).Items.Insert(0, new ListItem("None", "0"));
        }
        protected void OnChildIndexChange(object sender, System.EventArgs e)
        {
            
            ((DropDownList)((DropDownList)sender).Parent.FindControl("txtGrandchildID")).DataSource = GetSublevelCategories(Convert.ToInt32(((DropDownList)((DropDownList)sender).Parent.FindControl("txtParentID")).Items[Convert.ToInt32(((DropDownList)((DropDownList)sender).Parent.FindControl("txtParentID")).SelectedIndex)].Value), Convert.ToInt32(((DropDownList)((DropDownList)sender).Parent.FindControl("txtChildID")).Items[Convert.ToInt32(((DropDownList)((DropDownList)sender).Parent.FindControl("txtChildID")).SelectedIndex)].Value));
            ((DropDownList)((DropDownList)sender).Parent.FindControl("txtGrandchildID")).DataTextField = "GrandchildCategoryDescription";
            ((DropDownList)((DropDownList)sender).Parent.FindControl("txtGrandchildID")).DataValueField = "GrandchildCategoryID";
            ((DropDownList)((DropDownList)sender).Parent.FindControl("txtGrandchildID")).DataBind();
            ((DropDownList)((DropDownList)sender).Parent.FindControl("txtGrandchildID")).Items.Insert(0, new ListItem("None", "0"));
        }
The grandchild's assignment statement is 539 characters long.... I'm not sure how I feel about that.

Edit: Sorry for breaking tables...

The Noble Nobbler
Jul 14, 2003
Good god dude, it's not a sin to use a variable you know!

csammis
Aug 26, 2003

Mental Institution
No kidding, and all that casting is expensive as hell :gonk:

Cast once into a variable and use that instead.

The Noble Nobbler
Jul 14, 2003

Cazlab posted:

That's pretty much what I ended up doing:

First things first, txtChildID and txtParentID should both be named ddlParentList and ddlChildList.

They should both be in the same user control or at least both be able to be referenced with a strong name.

This:
code:
((DropDownList)((DropDownList)sender).Parent.FindControl("txtChildID")).DataSource = GetSublevelCategories(Convert.ToInt32(((DropDownList)((DropDownList)sender).Parent.FindControl("txtParentID")).Items[Convert.ToInt32(((DropDownList)((DropDownList)sender).Parent.FindControl("txtParentID")).SelectedIndex)].Value), null); 
Can become:

code:
int selectedParentID = Convert.ToInt32(ddlParentList.SelectedValue);
ddlChildList.DataSource = GetSublevelCategories(selectedParentID, null); /* avoid that null with an overload) */
I'm also confused about the FindControls referencing the Parent? Are these user controls? Why aren't they able to be referenced from the page? Are the child and parent controls in separate user controls? I would imagine that any coupling of lists should at least be in the same control so you can strongly type them without having to use a recursive find control

Even if I'm mistaken on the findcontrol part(the control is in a different naming container), there's definitely a better way to do what you're doing :o

The Noble Nobbler fucked around with this message at 16:40 on Jun 20, 2008

Adbot
ADBOT LOVES YOU

boo_radley
Dec 30, 2005

Politeness costs nothing
Is there a recommended tool for tracking down memory leaks?

  • Locked thread