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.

Ugg boots posted:

Edit: Nevermind, figured it out! Thanks!

Please say how for the next person!

And I figured this is the best place to ask, interest check in Silverlight Megathread?

Adbot
ADBOT LOVES YOU

Factor Mystic
Mar 20, 2006

Baby's First Post-Apocalyptic Fiction

Fastbreak posted:

And I figured this is the best place to ask, interest check in Silverlight Megathread?

Well it wouldn't be any worse than the REMEMBER IF THIS HELPS PLEASE MARK AS ANSWERED AND DONT FORGET TO GO TO MY BLOG ALSO I'M A MS MVP drivel all over the official forums.

fankey
Aug 31, 2001

Not really a .Net question but what's the best practice for chaining .msi installers? I have a Visual Studio 2008 Deployment Project Installer from which I need to install Apple Bonjour. Since Apple only has a .msi avaiable I need to launch their .msi from mine. I've found something called Bootstrapper Manifest Generator that looks like it should work but I'm wondering if there's a better way to go about this.

Dr. Poz
Sep 8, 2003

Dr. Poz just diagnosed you with a serious case of being a pussy. Now get back out there and hit them till you can't remember your kid's name.

Pillbug
Edit: So I woke up this morning and I was a lot less stupid somehow. This is how I have it written now. Is there anything I could do better?

code:
(from r in Server.Responses where r.Time == (from t in Server.Responses select t.Time).Max() select r).Single<Response>();
I'm trying to pick up LINQ and am having difficulty googling up an example of what I'm trying to do. I have two tables (as shown below), one of servers, one of responses. I'm iterating through all of the servers but only need to access the most recent response. This is where I hit a wall.

I can do it by catching all of the responses in a List and sorting etc, but that would to be missing the point of the exercise. I'm still getting a hang of the different ways to select data, so different examples are welcome.

Only registered members can see post attachments!

Dr. Poz fucked around with this message at 16:51 on May 31, 2008

Intel Penguin
Sep 14, 2007
hooray
Is there a way to generate a treeview node collection from a flat list of directories?

code:
List
Characters/Lance/0.jpg
Characters/Lance/1.jpg
Characters/Brandy/0.jpg
Characters/Brandy/1.jpg
Characters/Brandy/2.jpg
Environments/Beach.jpg
Environments/Forest.jpg

to

Characters
    Lance
        0.jpg
        1.jpg
    Brandy
        0.jpg
        1.jpg
        2.jpg
Environments
    Beach.jpg
    Forest.jpg

esp
Jul 13, 2003

Intel Penguin posted:

Is there a way to generate a treeview node collection from a flat list of directories?

Not very pretty, and assumes that filename == last part of path and filename.contains(".").
code:
private void FillTreeView(TreeNode parentNode)
{
    string[] paths = new string[] {
	"Characters/Brandy/",
	"Characters/Lance/0.jpg",
	"Characters/Brandy/2.jpg",
	"Characters/Lance/1.jpg",
	"Characters/Brandy/1.jpg",
	"Characters/default.jpg",
	"Environments/Beach.jpg",
	"Characters/Brandy/1.jpg",
	"Characters/Brandy/0.jpg",
	"Characters/Brandy/1.jpg",
	"Environments/Forest.jpg",
	"test1.jpg",
	"Characters/Brandy/1.jpg",
	"Test2",
	"Test2/Test3"
    };

    foreach (string path in paths)
    {
	string[] pathBits = path.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
	TreeNode currentNode = parentNode;

	for (int i = 0; i < pathBits.Length; i++)
	{
	    if (i == pathBits.Length - 1 && pathBits[i].Contains('.') && !currentNode.Nodes.ContainsKey(pathBits[i]))
		currentNode.Nodes.Add(pathBits[i], pathBits[i]); // File
	    else
	    {
		if (!currentNode.Nodes.ContainsKey(pathBits[i]))
		{
		    currentNode = currentNode.Nodes.Add(pathBits[i], pathBits[i]); // New folder
		    currentNode.BackColor = SystemColors.Control;
		}
		else
		    currentNode = currentNode.Nodes[pathBits[i]]; // Existing folder
	    }
	}
    }
}
If the list of directories is an actual path, you could do:
code:
private void FillTreeView(DirectoryInfo info, TreeNode parentNode)
{
    DirectoryInfo[] dirs = info.GetDirectories();
    FileInfo[] files = info.GetFiles();

    foreach (DirectoryInfo dir in dirs)
    {
	TreeNode dirNode = parentNode.Nodes.Add(dir.Name);
	dirNode.BackColor = SystemColors.Control;
	FillTreeView(dir, dirNode);
    }

    foreach (FileInfo file in files)
	parentNode.Nodes.Add(file.Name);
}

gibbed
Apr 10, 2006

esp posted:

code:
first code example
Is there something wrong with Path.GetDirectoryName()?

esp
Jul 13, 2003

gibbed posted:

Is there something wrong with Path.GetDirectoryName()?

What do you mean? How would that solve the "requirement"?

gibbed
Apr 10, 2006

esp posted:

What do you mean? How would that solve the "requirement"?

Something like this,
code:
foreach (string path in paths)
{
  string name = Path.GetFileName(path);
  
  if (name == null || name == String.Empty)
  {
    continue;
  }
  
  path = Path.GetDirectoryName(path);
  string[] pathBits = path.Split(new char[] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar}, StringSplitOptions.RemoveEmptyEntries);
  TreeNode currentNode = parentNode;
  
  for (int i = 0; i < pathBits.Length; i++)
  {
    if (currentNode.Nodes.ContainsKey(pathBits[i]))
    {
      currentNode = currentNode.Nodes[pathBits[i]];
    }
    else
    {
      currentNode = currentNode.Nodes.Add(pathBits[i], pathBits[i]);
    }
  }
  	
  currentNode.Nodes.Add(name);
}

esp
Jul 13, 2003

gibbed posted:

Something like this ...

Ah, okay. That really does the same thing(but accepts duplicates and skips paths with no filename) in this case, but yes; letting the framework handle file/dir-paths is a good idea.

gibbed
Apr 10, 2006

esp posted:

Ah, okay. That really does the same thing(but accepts duplicates and skips paths with no filename) in this case, but yes; letting the framework handle file/dir-paths is a good idea.
Whoops, at allowing duplicate filenames.

thefncrow
Mar 14, 2001
OK, ASP.NET question for the folks here. I've got a GridView, which I'm using to display data, and have a footer row which allows for a quick insert of new data. It's part of a Master/Detail page, with the detail section also allowing for long-form inserts. Because of this, I have my validators in the two sections broken into two distinct Validation Groups. The long-form validators are fine, and work just as they should.

The short form validators, though, have a slight problem in working. They do run, and they do properly validate my data, which is good. However, when the validator fails, the ErrorMessage on the validator does not appear in the Validation Summary which is part of the validation group, and the validator itself is not made visible. It does cause Page.IsValid to be set properly, so my insert operation is stopped and I display a message at the top of the screen that there was an error in processing, but the validation summary isn't populated with the error messages, and the validators which were tripped are not made visible to indicate the fields that are problematic.

It's driving me nuts, because the validators are stopping the database insert when accurate, and allowing it to proceed when validation is successful, but there's no indication of which field failed validation and why.

SixPabst
Oct 24, 2006

thefncrow posted:

OK, ASP.NET question for the folks here. I've got a GridView, which I'm using to display data, and have a footer row which allows for a quick insert of new data. It's part of a Master/Detail page, with the detail section also allowing for long-form inserts. Because of this, I have my validators in the two sections broken into two distinct Validation Groups. The long-form validators are fine, and work just as they should.

Did you ensure that the "Display" (not "Visible") properties of the validators that aren't showing in the summary are set to "None"? It's required to be for the validation summary to work correctly.

Myrddin Emrys
Jul 3, 2003

Ho ho ho, Pac-man!
Okay, I am trying to make a custom server control. I get the concept and making public properties blah blah. One thing I am trying to do, though, is database access of some kind, and I don't seem able to do this from within the class library.

What is the best way to do this, or simulate this?

Specifically, I am just doing this as an excercise but I'm trying to recreate something I saw at work, which was a CMS. Obviously the add/delete/edit for content is dead simple, the tricky part comes in the display, and one technique I've seen is using a server control where you simply assign it a querystring var to watch for (or it defaults to "id") and it uses that variable to grab the right piece of content from the DB and write it out to the page.

It seemed simple in theory but I don't get how the DB access works there.

PlaneGuy
Mar 28, 2001

g e r m a n
e n g i n e e r i n g

Yam Slacker

Girl With Huge Tits posted:

Edit: So I woke up this morning and I was a lot less stupid somehow. This is how I have it written now. Is there anything I could do better?
code:
(from r in Server.Responses where r.Time == (from t in Server.Responses select t.Time).Max() select r).Single<Response>();
This page:
http://msdn.microsoft.com/en-us/library/bb386972.aspx

Has an example of using a lambda in Max to select the field out inside the query.
code:
            from prod2 in grouping
            where prod2.UnitPrice == grouping.Max(prod3 =>
                prod3.UnitPrice)
            select prod2
I suppose the sever/response version would be
code:
(from r in server.responses where where r.time == server.responses.Max(t => t.time) select r).single
I dunno if that's actually any better though. It depends on how linqtosql handles it (would it translate it into the same sql? worse because of the lambda?). Also, I'm a vb guy so check my syntax for c#.

TheReverend
Jun 21, 2005

Any libraries to suggest for voice recognition with mobile devices?

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.
Man, I'm trying to speed up one tremendously slow part of our web application and it's putting me on a hellride.

I'm using the BeginInvoke() method in order to spawn a new thread in order to take care of some database work. The problem is calls a few things from HttpContext.Current because we have a couple of small things (Like say the Username) stored in session. The problem is that the thread doesnt seem to have an instance of the HttpContext object on there, so it's stating that it's null or not an object at several points.

Is there any simple way to handle this, or am I going to have to retool a lot of these methods to take whatever we're grabbing from the HttpContext object before the thread spawns?

POKEMAN SAM
Jul 8, 2004

Fastbreak posted:

Please say how for the next person!

You just do something like:

code:

IEnumerator<int> MyRecurEnum(int i) {

    yield return i;
    foreach (int x in MyRecurEnum(i+1))
        yield return x;

}

Richard Noggin
Jun 6, 2005
Redneck By Default
Can someone explain the yield statement in terms an idjit (me) can understand?

poopiehead
Oct 6, 2004

It's as if every time it hits yield return, it adds the returned object to an enumerable and then at the end returns the whole thing.

This could be thought of as returning an enumerable that will give you 1 then 2.
[code]
yield return 1;
yield return 2;
[code]

Behind the scenes what actually happens is that each time you ask for the next element it runs the method until it hits a yield return, returns an object, and saves the state of the method. Next time you ask for the next element, it starts where it left off and eventually returns the second element.

Radnor
Dec 11, 2002

Octoparrot is watching you.
Is there a program or plugin somewhere I can use to clean up/reformat/prettify .ASPX files? I have ReSharper, and its Code Clean-Up does a nice job with my .CS files but it ignores all the front-end ASP.NET stuff.

uXs
May 3, 2005

Mark it zero!

poopiehead posted:

It's as if every time it hits yield return, it adds the returned object to an enumerable and then at the end returns the whole thing.

Except that one of the neat things about yield is that it doesn't create intermediary, temporary lists. If you call something that uses yield, and you only iterate through the X first items, only those X items will be created in the yielding function. It does not create the entire list first and then return it, it just creates the ones you need, one item at a time, when you need that item.

So, saying that it's like making an enumerable first and then returning it may look like a good way of explaining it, but unfortunately it's wrong.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I'm looking for an open source .net charting suite. Any recommendations?

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.

fletcher posted:

I'm looking for an open source .net charting suite. Any recommendations?

I think somebody asked for the same thing (and got an answer) a couple of pages ago.

poopiehead
Oct 6, 2004

uXs posted:

So, saying that it's like making an enumerable first and then returning it may look like a good way of explaining it, but unfortunately it's wrong.

That's why I wrote the second paragraph......

genki
Nov 12, 2003

FinkieMcGee posted:

Man, I'm trying to speed up one tremendously slow part of our web application and it's putting me on a hellride.

I'm using the BeginInvoke() method in order to spawn a new thread in order to take care of some database work. The problem is calls a few things from HttpContext.Current because we have a couple of small things (Like say the Username) stored in session. The problem is that the thread doesnt seem to have an instance of the HttpContext object on there, so it's stating that it's null or not an object at several points.

Is there any simple way to handle this, or am I going to have to retool a lot of these methods to take whatever we're grabbing from the HttpContext object before the thread spawns?
Retool, afaik. You can't access the httpContext object across threads, is what it sounds like. Which probably makes sense, since the term "Context" in the object name seems to imply that it gives you values based on the 'context' (thread) it's in.

This article seems to talk about exactly your issue (and links an MSDN article that might help too):
http://www.odetocode.com/Articles/112.aspx

Myrddin Emrys
Jul 3, 2003

Ho ho ho, Pac-man!

Myrddin Emrys posted:

Okay, I am trying to make a custom server control. I get the concept and making public properties blah blah. One thing I am trying to do, though, is database access of some kind, and I don't seem able to do this from within the class library.

What is the best way to do this, or simulate this?

Specifically, I am just doing this as an exercise but I'm trying to recreate something I saw at work, which was a CMS. Obviously the add/delete/edit for content is dead simple, the tricky part comes in the display, and one technique I've seen is using a server control where you simply assign it a querystring var to watch for (or it defaults to "id") and it uses that variable to grab the right piece of content from the DB and write it out to the page.

It seemed simple in theory but I don't get how the DB access works there.
Anyone have any ideas?

uh zip zoom
May 28, 2003

Sensitive Thugs Need Hugs

I'm creating an application to automate the updating of data in a DB by uploading an Excel spreadsheet via web form. Here's my method:

code:
private void BulkCopyData(string workBook, string table, string connectionString)
    {
      //Series of commands to bulk copy data from the excel file into our SQL table
      OleDbConnection OleDbConn = new OleDbConnection(connectionString);
      OleDbCommand OleComm = new OleDbCommand(("SELECT * FROM " + workBook), OleDbConn);
      OleDbConn.Open();
      OleDbDataReader dr = OleComm.ExecuteReader();
      SqlBulkCopy BulkCopy = new SqlBulkCopy(Settings.Current.BCBSMConnectionString);

      BulkCopy.DestinationTableName = table;
      BulkCopy.WriteToServer(dr);
      OleDbConn.Close();
    }
When I run this, I get an error that the given column mapping does not match up with any column in the source or destination, which makes sense, because it doesn't. What I need is to create a SqlBulkCopyColumnMapping object to map the columns, but I don't know how to refer to the columns that are within the Excel spreadsheet. Anyone know how to do this?

poopiehead
Oct 6, 2004

Myrddin Emrys posted:

Anyone have any ideas?

Going to need more detail here. If you give a limited concrete example of what you want to do, it would be easier to help.

I'm not sure what you mean by not being able to do this from within the class library. It's definitely possible to access the database, but you need to be careful of some things, for example, if you have 5 identical or nearly identical controls, you're probably hitting the database 5 times when you could have done it once.

uh zip zoom
May 28, 2003

Sensitive Thugs Need Hugs

uh zip zoom posted:

Anyone know how to do this?

just thought I'd bump this thread to see if anyone had any ideas for me.

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.
You have to use the bulkmapping thingy to map the fields from the source to the destination. This includes an example:

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopycolumnmapping.aspx

uh zip zoom
May 28, 2003

Sensitive Thugs Need Hugs

Begby posted:

You have to use the bulkmapping thingy to map the fields from the source to the destination. This includes an example:

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopycolumnmapping.aspx

yes, I realize that. My problem is that I don't know how to refer to the columns in the Excel spreadsheet.

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.

uh zip zoom posted:

yes, I realize that. My problem is that I don't know how to refer to the columns in the Excel spreadsheet.

Did you try using an integer to refer to the column number? You can pass integer values into the SqlBulkCopyColumnMapping constructor.

EVGA Longoria
Dec 25, 2005

Let's go exploring!

I'm looking to get into C# development. I'm in an odd place of having familiarity with a lot of programming concepts and syntax but not all of them. I can't stand the idea of sitting through another tutorial that teaches me hello world and for loops. I know MSDN has a great library for syntax references, so that takes care of that.

What I'm looking for, specifically, is a good source of commented C# code in varying levels of complexity. Enough so I can glance over some code and start to get an idea of how it works and see the thought processes behind it. Does something like this exist? I don't know if it's in huge demand, but it seems to me like the best way for me to learn about a language, especially without a specific goal in mind.

ether
May 20, 2001

Currently our legacy Delphi-app uses a reporting tool called ReportBuilder which had a nice linkable designer and possibilities to hook into the diffirent parts which basically means we can integrate it fully in our app.

With the move from Delphi to C# this is one of the major components that we still don't have a competent replacement for. Are there any nice solutions out there that allow for a seamless integration of the report-designer into your app and nice extensibility.

SLOSifl
Aug 10, 2002


Visual Studio ships with Crystal Reports, and supports SQL Server Reporting Services natively as well. Either one supports Windows Forms controls that can be embedded in your application rather seamlessly. I think Reporting Services is a better platform, but Crystal is more mature. Depending on your needs, one or the other should give you what you want.

edit: Sorry, I misread your question. I'm not sure of the report *designer* embedding options those solutions provide. I vaguely recall doing that with Crystal Reports one a throwaway project back in the .NET 1.0 days, so it might be possible.

Dromio
Oct 16, 2002
Sleeper
I must be doing something stupid here-- using SQL Compact. I insert a row into a table and it says it's ok (even though I can't see it using the Server Explorer), but then if I try to get a value back it fails.
code:
using (SqlCeConnection DBConnect = Utility.GetDBConnection())
{
    string SQL = "INSERT INTO tbl_Class " + 
                 "(Class, Owner, Path, Locale) " + 
                 "VALUES (@Class, @Owner, @Path, @Locale);";
    using (SqlCeCommand DBCommand = new SqlCeCommand(SQL, DBConnect))
    {
        DBCommand.CommandType = CommandType.Text;
        SqlCeParameter Param1 = new SqlCeParameter("@Class", _Name);
        SqlCeParameter Param2 = new SqlCeParameter("@Owner", _Owner);
        SqlCeParameter Param3 = new SqlCeParameter("@Path", _Path);
        SqlCeParameter Param4 = new SqlCeParameter("@Locale", CurrentCulture);

        DBCommand.Parameters.Add(Param1);
        DBCommand.Parameters.Add(Param2);
        DBCommand.Parameters.Add(Param3);
        DBCommand.Parameters.Add(Param4);
        DBConnect.Open();
        int iReturn = DBCommand.ExecuteNonQuery();  //THIS RETURNS "1"
    }
    SQL = "SELECT ID From tbl_Class WHERE Class=@Class AND Locale=@Locale";
    using (SqlCeCommand DBCommand = new SqlCeCommand(SQL, DBConnect))
    {
        SqlCeParameter Param1 = new SqlCeParameter("@Class", _Name);
        SqlCeParameter Param2 = new SqlCeParameter("@Locale", CurrentCulture);

        DBCommand.Parameters.Add(Param1);
        DBCommand.Parameters.Add(Param2);
        _ID = Convert.ToInt32(DBCommand.ExecuteScalar()); //FAILS WITH A DBNULL
        DBConnect.Close();
    }
}
Anyone see my mistake?

Edit: Another stupid mistake. the ID actually WAS null.

Dromio fucked around with this message at 16:25 on Jun 12, 2008

Fastbreak
Jul 4, 2002
Don't worry, I had ten bucks.
This is more of a quiz than a real question, but its interesting nonetheless.

Lets say that you are inserting a row in the DB, but the DB connection is declared in the instantiation of the SqlCommand, not as its own variable.

Lets say a freak accident happens, and the webconfig or whatever is messed up and the GetSetting function below returns null instead of a real string for the connection.

It will go to the catch block naturally and return false so the parent function knows the insert failed and we should return a nice friendly error message to the user. But you see, since we never opened a connection, the finally block where we close the connection will fail and throw an ugly server errror message. We also never created a valid connection object associated with the command I think, so checking to see if its open will fail too.

So what should you put in the finally block in this case ONLY changing the finally block? Well I guess small changes elsewhere would be okay to, like changing a property, but no new variables.

code:
function....
{
 SqlCommand comm = new SqlCommand();
        try
        {
            comm = new SqlCommand("InsertStuff", GetSetting("Constring"));
            comm.Parameters.Add(...);

            comm.CommandType = CommandType.StoredProcedure;
            comm.Connection.Open();
            comm.ExecuteNonQuery();
            return true;
        }
        catch (Exception ex)
        {
            LogError();
            return false;
        }
        finally
        {
            comm.Connection.Close();
            comm.Connection.Dispose();
            comm.Dispose();
        }
    }

The Noble Nobbler
Jul 14, 2003
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;
}

Adbot
ADBOT LOVES YOU

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.

Fastbreak posted:

This is more of a quiz than a real question, but its interesting nonetheless.

Lets say that you are inserting a row in the DB, but the DB connection is declared in the instantiation of the SqlCommand, not as its own variable.

Lets say a freak accident happens, and the webconfig or whatever is messed up and the GetSetting function below returns null instead of a real string for the connection.

It will go to the catch block naturally and return false so the parent function knows the insert failed and we should return a nice friendly error message to the user. But you see, since we never opened a connection, the finally block where we close the connection will fail and throw an ugly server errror message. We also never created a valid connection object associated with the command I think, so checking to see if its open will fail too.

So what should you put in the finally block in this case ONLY changing the finally block? Well I guess small changes elsewhere would be okay to, like changing a property, but no new variables.

code:
function....
{
 SqlCommand comm = new SqlCommand();
        try
        {
            comm = new SqlCommand("InsertStuff", GetSetting("Constring"));
            comm.Parameters.Add(...);

            comm.CommandType = CommandType.StoredProcedure;
            comm.Connection.Open();
            comm.ExecuteNonQuery();
            return true;
        }
        catch (Exception ex)
        {
            LogError();
            return false;
        }
        finally
        {
            comm.Connection.Close();
            comm.Connection.Dispose();
            comm.Dispose();
        }
    }

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.

  • Locked thread