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
Dietrich
Sep 11, 2001

aBagorn posted:

Yeah that worked pretty well.

Now for the icing on the cake. Integrating it with our off the shelf ticketing software if I can.

(not completely necessary, but I'm going to try to do it anyway. Who wants to make everyone's lives easier? this guy :effort: )

Edit:

Tiny rant incoming: some smarmy as gently caress douche at the company tells me today, "I don't know why you bothered to code all that, it will be obsolete when we migrate to SharePoint"

Please tell me there's a way to import an existing ASP.NET application into SharePoint so I can shut his smug rear end up.

SharePoint is figuratively the worst software ever but for some reason managers jizz all over the marketing.

You can copy-paste your stuff into a web part template for the most part.

Adbot
ADBOT LOVES YOU

mik
Oct 16, 2003
oh
I'm experiencing a strange problem with my .NET winforms app.

The program works perfectly fine running on its own, until I RDP into the machine that is running it. When I RDP the app's UI becomes completely unresponsive - and I'm forced to kill the app. However, this only happens when the program is running on its own, rather than when I'm debugging inside VS2010 - in which case RDPing does not break the program.

I have a suspicion it has to do with a COM object it uses (since when I don't use it, it doesn't have this issue). There's a fair amount of threading going on, mostly because the COM object pushes information to me on separate threads, and then I use the data to do thousands of calcs/second sometimes using the threadpool.

I'm still new to all this, would this be a case to attach a JIT debugger to the app when it's running outside of VS2010? I'd like to have an idea where to start before picking apart the program line-by-line.

Rooster Brooster
Mar 30, 2001

Maybe it doesn't really matter anymore.
Not 100% .Net/C# specific, but I figure this is a good thread for input. I have some components used by my various data objects, view-models, etc. In a running application, they'll all use the same component instance, but I want to be able to specify the component per instance for testing purposes (stubs). Which of these is best?
  1. Optional constructor parameters with readonly variables that use a default static instance of the component if it's not specified.
  2. No constructor parameters, public get/set properties for the component, use the static instance if not specified.
  3. Required constructor parameter for a readonly variable.

I don't like (3) as it clutters the code up pretty severely when I've got, say, three components needed by a view-model. (2) seems odd because the components shouldn't be able to be changed after the objects are instantiated. So I'm leaning (1) but wanted to see if smarter people had opinions on this, or a better idea I hadn't thought of.

boo_radley
Dec 30, 2005

Politeness costs nothing

aBagorn posted:

Please tell me there's a way to import an existing ASP.NET application into SharePoint so I can shut his smug rear end up.

If you look at it from an API standpoint, SharePoint is really a complex asp.net framework and application, so yes, naturally there is.

You can create a virtual directory on your front end servers and deploy your app there, or you can integrate it into SharePoint (Retaining the flexibility of asp.net while leveraging SharePoint features). See here for a decent explanation of the underlying concepts.

However, I wouldn't recommend just dumping your app into the _layouts directory. SharePoint manages features & applications using solution package files (.wsp) to help ease migration & deployment across farms.

A lot of people go into SharePoint with a weird "Ho, ho! Take THAT, programmers!" attitude and then realize that it's Enterprise software and requires a bit more discipline than Gary in accounting who is totally awesome with Excel can provide. They wind up seeing that SharePoint's base functionality isn't sufficient for their needs, or they don't have the cross-discipline skilled resources to work with C# coding, web design, sql server administration as well as the unique aspects of SharePoint (BCS, SPD, solution design) and wind up training up staff to fill those roles or contracting out. (my rates are totally reasonable, btw, drop me a PM ;))

boo_radley fucked around with this message at 18:12 on Jan 31, 2012

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Rooster Brooster posted:

Not 100% .Net/C# specific, but I figure this is a good thread for input. I have some components used by my various data objects, view-models, etc. In a running application, they'll all use the same component instance, but I want to be able to specify the component per instance for testing purposes (stubs). Which of these is best?
  1. Optional constructor parameters with readonly variables that use a default static instance of the component if it's not specified.
  2. No constructor parameters, public get/set properties for the component, use the static instance if not specified.
  3. Required constructor parameter for a readonly variable.

I don't like (3) as it clutters the code up pretty severely when I've got, say, three components needed by a view-model. (2) seems odd because the components shouldn't be able to be changed after the objects are instantiated. So I'm leaning (1) but wanted to see if smarter people had opinions on this, or a better idea I hadn't thought of.

You can do poor man's IoC pretty easily with constructor chaining, so I'd say option #3 is easy enough.

Ex:
code:
public class Foo 
{
    private readonly IBar bar;
    public Foo(IBar bar) 
    {
        this.bar=bar;
        //other constructory goodness
    }
    
    public Foo() : this(new RealBar()) { } 
}
Past that, look into a real IoC framework like Ninject, it makes gluing all of your dependencies together a lot easier once you have a lot of dependencies to glue.

akadajet
Sep 14, 2003

Rooster Brooster posted:

Not 100% .Net/C# specific, but I figure this is a good thread for input. I have some components used by my various data objects, view-models, etc. In a running application, they'll all use the same component instance, but I want to be able to specify the component per instance for testing purposes (stubs). Which of these is best?
  1. Optional constructor parameters with readonly variables that use a default static instance of the component if it's not specified.
  2. No constructor parameters, public get/set properties for the component, use the static instance if not specified.
  3. Required constructor parameter for a readonly variable.

I don't like (3) as it clutters the code up pretty severely when I've got, say, three components needed by a view-model. (2) seems odd because the components shouldn't be able to be changed after the objects are instantiated. So I'm leaning (1) but wanted to see if smarter people had opinions on this, or a better idea I hadn't thought of.

Go with option 3, and use Unity to deal with resolving all your dependencies at runtime. Testing is going to be a little bit of work to maintain, but once you've got that IOC container goodness going you'll find that it's worth it. I personally use Moq to deal with creating my "stubs" and it works beautifully.

Dietrich
Sep 11, 2001

Curious. How does Unity compare to Castle.Windsor and/or Ninject?

wwb
Aug 17, 2004

Also voting option #3 and get a real DI framework if you need it.

Personally I'm partial to structuremap, but I would also want to know how it compares to Unity or whatever else since everyone seems to be using something else these days.

Rooster Brooster
Mar 30, 2001

Maybe it doesn't really matter anymore.
Thanks guys. I guess it's time to really learn IoC/DI. I'll check out Unity and Ninject and see what's what.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

wwb posted:

Also voting option #3 and get a real DI framework if you need it.

Personally I'm partial to structuremap, but I would also want to know how it compares to Unity or whatever else since everyone seems to be using something else these days.

Yeah, there are a million IoC frameworks and mocking frameworks these days. There's no clear "best" one, which is both good and bad.

Dietrich
Sep 11, 2001

Ninject is a good starter on account of how simple it is. Castle.Windsor just integrates and is used by a lot of big things like NHibernate, so I kinda went with that.

akadajet
Sep 14, 2003

The only reasons I use Unity is because it's provided by Microsoft and it was included with Prism, which I use frequently at work. I've used Spring.Net's container in the past and really, the only major difference I ran into was the configuration file.

Ed: Huh... looks like Ninject doesn't use configuration files. That actually sounds nicer. Who really needs to change a dependency configuration after compilation?

akadajet fucked around with this message at 22:26 on Jan 31, 2012

havelock
Jan 20, 2004

IGNORE ME
Soiled Meat

Dietrich posted:

Curious. How does Unity compare to Castle.Windsor and/or Ninject?

Unity is semantically wrong and should be avoided where possible. Here are the 2 major semantic problems with it:

1. If you try to Resolve a concrete type that you haven't registered with the container, Unity won't fail - instead it will new up an instance and hand it back.

2. Unity doesn't know how to Release. Suppose you have dependencies that need to be disposed. If you are using Unity, the only way to make this work is to force all of your interfaces to extend IDisposable on the off chance that their implementations need it and then implement IDisposable yourself and Dispose all your dependencies.

With Windsor (and others I'm sure), you just call Release and the container knows if the dependencies of the instance need to be cleaned up and does it.

Windsor also has a really nice facility for WCF integration (auto proxy creation / recreation on fault using the ChannelFactory for clients plus a servicefactory for services so you can inject dependencies there, too).

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed

akadajet posted:

Who really needs to change a dependency configuration after compilation?
I've had to because of arbitrary restrictions from management that did not allow rebuilding the code, but did allow changes to the config file that resulted in completely different behavior, because it's "not code".

boo_radley
Dec 30, 2005

Politeness costs nothing

Plorkyeran posted:

I've had to because of arbitrary restrictions from management that did not allow rebuilding the code, but did allow changes to the config file that resulted in completely different behavior, because it's "not code".

Ah, the paradigm of semantics oriented programming.

adaz
Mar 7, 2009

havelock posted:


With Windsor (and others I'm sure), you just call Release and the container knows if the dependencies of the instance need to be cleaned up and does it.

Windsor also has a really nice facility for WCF integration (auto proxy creation / recreation on fault using the ChannelFactory for clients plus a servicefactory for services so you can inject dependencies there, too).

This brings up a question I just had today at work. I've recently been writing a lot of MVC pages using repositories with interfaces and dependency injection - but not using stuff like Ninject as these are pretty small webpages and I didn't feel the need. At any rate, when you are done with your repository are you supposed to explicitly dispose of it? These particular repositories are using entity framework + LINQ, should I make sure it's disposed of when done? I only ask because the VS 2010 compiler was saying I should implement IDisposable on it when I ran a code analysis.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

adaz posted:

This brings up a question I just had today at work. I've recently been writing a lot of MVC pages using repositories with interfaces and dependency injection - but not using stuff like Ninject as these are pretty small webpages and I didn't feel the need. At any rate, when you are done with your repository are you supposed to explicitly dispose of it? These particular repositories are using entity framework + LINQ, should I make sure it's disposed of when done? I only ask because the VS 2010 compiler was saying I should implement IDisposable on it when I ran a code analysis.

Yes, you should implement IDisposable in any class that uses disposable objects. Although if you're just newing up a disposable object in a method and then using it in the scope of that method, just wrap it in a using block and you're good to go.

Here's the proper way to implement IDisposable, right off of MSDN:

code:
public class Resource : IDisposable 
{
    private IntPtr nativeResource = Marhsal.AllocHGlobal(100);
    private AnotherResource managedResource = new AnotherResource();

// Dispose() calls Dispose(true)
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    // NOTE: Leave out the finalizer altogether if this class doesn't 
    // own unmanaged resources itself, but leave the other methods
    // exactly as they are. 
    ~Resource() 
    {
        // Finalizer calls Dispose(false)
        Dispose(false);
    }
    // The bulk of the clean-up code is implemented in Dispose(bool)
    protected virtual void Dispose(bool disposing)
    {
        if (disposing) 
        {
            // free managed resources
            if (managedResource != null)
            {
                managedResource.Dispose();
                managedResource = null;
            }
        }
        // free native resources if there are any.
        if (nativeResource != IntPtr.Zero) 
        {
            Marshal.FreeHGlobal(nativeResource);
            nativeResource = IntPtr.Zero;
        }
    }
}

New Yorp New Yorp fucked around with this message at 04:45 on Feb 1, 2012

wwb
Aug 17, 2004

I'd definitely want to clean up any EF data contexts I'd have floating around. Two ways to get there:

a) If instantiation is easy and sane enough, just dispose of it in whatever the appropriate cleanup spot is. EG, Controller.OnActionExecuted or in your ActionFilter or on Request_End if you are using HttpContext.Items

b) Just take it as a sign from god you should get a proper IoC container that does stuff like scope things per HTTP request and clean up after you.

I should really check out Windsor for the WCF wire-up. We've got some rather ghetto means of doing that I don't like . . .

boo_radley
Dec 30, 2005

Politeness costs nothing

Ithaqua posted:

Yes, you should implement IDisposable in any class that uses disposable objects. Although if you're just newing up a disposable object in a method and then using it in the scope of that method, just wrap it in a using block and you're good to go.

Here's the proper way to implement IDisposable, right off of MSDN:

code:
public class Resource : IDisposable 
{
... Marhsal.AllocHGlobal(100); ...


How does stuff like this make it into code samples? It's an obvious thing to correct in VS, but still...

adaz
Mar 7, 2009

Ithaqua posted:

Yes, you should implement IDisposable in any class that uses disposable objects. Although if you're just newing up a disposable object in a method and then using it in the scope of that method, just wrap it in a using block and you're good to go.

Here's the proper way to implement IDisposable, right off of MSDN:


Thanks for this. Actually I'm thinking I might have inadvertently saved myself the pain of needing to do this based on how I tend to write MVC pages. This is probably a bit of a beginners question so sorry --

Assume my controller wants a List(of Person) where person is an object with a first name and last name. What I usually do is call the repository interface from the controller for a list of person. The repository does the LINQ query, creates a list and sets the properties on each object, and returns it to the controller.

Since the scope is just in the repository and everything based back to the controller isn't directly touching the entity framework I should be ok without explicitly implementing iDisposable right although I probably should as general practice for future things.

Or have I done something terrible.

adaz fucked around with this message at 05:08 on Feb 1, 2012

boo_radley
Dec 30, 2005

Politeness costs nothing

adaz posted:



Since the scope is just in the repository and everything based back to the controller isn't directly touching the entity framework I should be ok without explicitly implementing iDisposable right although I probably should as general practice for future things.


If you have a class that inherits from IDisposable or contains an IDisposable implementing property, you need to make sure you're disposing correctly. If you don't, you won't be releasing memory in a timely fashion and your app may start to hang or crash.

If you are working with an IDisposable in any way, it needs to get disposed. You can put it in a using block for simplicity's sake, but you have to dispose of them.

If the compiler is giving you a warning that you need to implement iDisposable, you should implement iDisposable or have a really awesome and technically valid reason for not implementing it (and I can't think of one).

adaz
Mar 7, 2009

Basically stop being lazy. Check

Dromio
Oct 16, 2002
Sleeper
I have to build a hierarchal data structure from a fairly large (5000+ rows) dataset. I've got something that works, but it's taking ~30 seconds to do so and I have to wonder if I can do something to make it better. Here's the general idea:

code:
public class DataReport
{
  public DataNode GetReport(int topNodeID)
  {
    var rows = (from info in repository.datasource
                      where info.isvalue // Several where clauses to filter the data up front.
                      select info)
                      .ToList() //Go ahead and execute against the db so I get it all in mem
                      .AsQueryable();
     var topNode = new DataNode(rows.First(r=>r.ID == topNodeID));
     AddChildren(topNode, rows);
     return topNode;
  }

  private void AddChildren(DataNode node, IQueryable<DatabaseRow> rows)
  {
    var children = (from row in rows
                            where row.ParentID == node.ID
                            && row.ParentID != row.ID  //The top in the db points to himself
                            select row);
    if(!children.Any()) {return;}
    foreach(var childNode in children.Select(row => new DataNode(row, node)))
    {
      node.Children.Add(childNode);
      AddChildren(childNode, rows); //Recurse down this line
    }
  }
}

public class DataNode
{
  public DataNode(DatabaseRow row, DataNode parent)
  {
      Name = row.Name; //We set some other simple properties
      Parent = parent;
  }

  public string Name {get; private set;}
  private List<DataNode> _children = new List<DataNode>();
  public List<DataNode> Children 
  {
    get { return _children; } 
    set{ _children = value; } 
  }

  public DataNode Parent {get; private set;}

}
The initial fetch of the rows from the db is plenty fast. It's the recursive buildup of the nodes that's taking way too long. Can anyone see something I'm doing obviously wrong that would be slowing me down?

Dromio fucked around with this message at 15:25 on Feb 1, 2012

Nurbs
Aug 31, 2001

Three fries short of a happy meal...Whacko!
Would joining info on itself where ID = ParentID be faster because you only select nodes which have children?

Zhentar
Sep 28, 2003

Brilliant Master Genius
I wouldn't really expect it to be that slow for such a small data set, but you're repeatedly searching over the entire data set. It would be a lot faster to do a first pass to pull them out into a dictionary or similar by parent ID.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug
I posted a question on Stack Overflow yesterday regarding WPF and screenreaders. It's not getting much love over there, so I'm crossposting here to see if you fine gents have any ideas. I'm terrible at WPF still.

http://stackoverflow.com/questions/9086158/overriding-a-controls-name-for-screen-reader-purposes

Dromio
Oct 16, 2002
Sleeper

Zhentar posted:

I wouldn't really expect it to be that slow for such a small data set, but you're repeatedly searching over the entire data set. It would be a lot faster to do a first pass to pull them out into a dictionary or similar by parent ID.

This seemed to help a lot. I'm still not ecstatic about the speed of building the hierarchy, but it's better. I fetched the rows from the db first. Then I built a Dictionary<int, List<DatabaseRow>>() where the key was the parentID and the list was of each child data row. Then I recurse down and build the hierarchy. It cut the average run-time from 30 seconds to 8. 2 of those seconds were spent fetching the data and building the dictionary.

Dromio
Oct 16, 2002
Sleeper
Now I've pointed the routine at our production data set (20000 rows) and it's still way too slow:

code:
[Debug] '' 2/1/2012 10:12:18 AM Start
[Debug] '' 2/1/2012 10:12:21 AM Fetched 19550 items for tree
[Debug] '' 2/1/2012 10:12:21 AM Building dictionary
[Debug] '' 2/1/2012 10:17:58 AM Done building dictionary
...
[Debug] '' 2/1/2012 10:28:38 AM Done building hierarchy
The hierarchy I'm trying to build is much "wider" in production data than on my development data, so the dictionary would end up with many more entries.

Here's how I'm building that Dictionary. Maybe there's a better way:

code:
private Dictionary<int, List<DatabaseRecord>> data;
...
foreach (var row in rows)
{
  var parentID = row.ParentID;
  if(!data.ContainsKey(parentID))
  {
    data.Add(parentID, new List<DatabaseRecord>(){row});
  }
  else 
  {
    data[parentID].Add(row);
  }
} 

wwb
Aug 17, 2004

adaz posted:

Thanks for this. Actually I'm thinking I might have inadvertently saved myself the pain of needing to do this based on how I tend to write MVC pages. This is probably a bit of a beginners question so sorry --

Assume my controller wants a List(of Person) where person is an object with a first name and last name. What I usually do is call the repository interface from the controller for a list of person. The repository does the LINQ query, creates a list and sets the properties on each object, and returns it to the controller.

Since the scope is just in the repository and everything based back to the controller isn't directly touching the entity framework I should be ok without explicitly implementing iDisposable right although I probably should as general practice for future things.

Or have I done something terrible.

Probably the more terrible thing is that it seems you are returning IQueryables to the view which can get really nasty really fast. Always materialize things by calling .ToArray() or .ToList(). Or map out to another object.

Is the repo newing up the EF DbContext? If so, it should be responsible for cleaning it up, probably by implementing IDisposable. I'd generally prefer passing the DbContext into the repository as a dependency, but then the infrastructure would need to deal with disposing the context.

Sedro
Dec 31, 2008

Ithaqua posted:

I posted a question on Stack Overflow yesterday regarding WPF and screenreaders. It's not getting much love over there, so I'm crossposting here to see if you fine gents have any ideas. I'm terrible at WPF still.

http://stackoverflow.com/questions/9086158/overriding-a-controls-name-for-screen-reader-purposes
Not answering your question, but you should be aware that there is a bug causing horrible performance of WPF when a screen reader is running. You can see if it affects you by opening a Popup (ie. tooltip) and immediately trying to resize the window. source with links to hotfix

Zhentar
Sep 28, 2003

Brilliant Master Genius

Dromio posted:

Now I've pointed the routine at our production data set (20000 rows) and it's still way too slow:

code:
[Debug] '' 2/1/2012 10:12:18 AM Start
[Debug] '' 2/1/2012 10:12:21 AM Fetched 19550 items for tree
[Debug] '' 2/1/2012 10:12:21 AM Building dictionary
[Debug] '' 2/1/2012 10:17:58 AM Done building dictionary
...
[Debug] '' 2/1/2012 10:28:38 AM Done building hierarchy

What the hell are you running on, a 286? For a mere 20,000 rows, I'd expect that dictionary code to be running in a fraction of a second... your best option is to profile, if you can. I don't think the real problem is contained in the code you've posted.

boo_radley
Dec 30, 2005

Politeness costs nothing

Dromio posted:

Now I've pointed the routine at our production data set (20000 rows) and it's still way too slow:

code:
[Debug] '' 2/1/2012 10:12:18 AM Start
[Debug] '' 2/1/2012 10:12:21 AM Fetched 19550 items for tree
[Debug] '' 2/1/2012 10:12:21 AM Building dictionary
[Debug] '' 2/1/2012 10:17:58 AM Done building dictionary
...
[Debug] '' 2/1/2012 10:28:38 AM Done building hierarchy
The hierarchy I'm trying to build is much "wider" in production data than on my development data, so the dictionary would end up with many more entries.

Here's how I'm building that Dictionary. Maybe there's a better way:

code:
private Dictionary<int, List<DatabaseRecord>> data;
...
foreach (var row in rows)
{
  var parentID = row.ParentID;
  if(!data.ContainsKey(parentID))
  {
    data.Add(parentID, new List<DatabaseRecord>(){row});
  }
  else 
  {
    data[parentID].Add(row);
  }
} 

Five minutes (really?) to build a dictionary out of 19,550 rows is kind of weird, though. Have you obscured part of what you're doing for privacy/ security reasons? Is a web service your data source?

edit: Zhentar! :arghfist:

edit edit: if all else fails, I think TryGetValue might be faster than if(ContainsKey(...)) else

boo_radley fucked around with this message at 18:32 on Feb 1, 2012

Dietrich
Sep 11, 2001

Dromio posted:

Now I've pointed the routine at our production data set (20000 rows) and it's still way too slow:

code:
[Debug] '' 2/1/2012 10:12:18 AM Start
[Debug] '' 2/1/2012 10:12:21 AM Fetched 19550 items for tree
[Debug] '' 2/1/2012 10:12:21 AM Building dictionary
[Debug] '' 2/1/2012 10:17:58 AM Done building dictionary
...
[Debug] '' 2/1/2012 10:28:38 AM Done building hierarchy

Are you absolutely sure there are no lazy loading features causing an N+1 select problem?

Dromio
Oct 16, 2002
Sleeper

Zhentar posted:

What the hell are you running on, a 286? For a mere 20,000 rows, I'd expect that dictionary code to be running in a fraction of a second... your best option is to profile, if you can. I don't think the real problem is contained in the code you've posted.

I've not posted the full code because it has a lot of extraneous details, but I'm trying to remain true to what it's really doing. Especially the dictionary building portion.

I think I'm avoiding the lazy-loading by forcing the .ToList() on the initial fetch from the database, so I don't think that's the issue. That DOES force linq2sql to do the pull right then, right?

I did try out TryGetValue() and it didn't make a discernable difference.

Aha, there is one detail I left out... maybe that's the issue. The parentID coming from the db is nullable, even though my query ensures they are not null:

code:
foreach (var row in rows)
{
  var parentID = (int)row.ParentID; // I forgot this part in my original posted code
  if(!data.ContainsKey(parentID))
  {
    data.Add(parentID, new List<DatabaseRecord>(){row});
  }
  else 
  {
    data[parentID].Add(row);
  }
} 
I'm doing this in an nunit test. I guess I'll have to figure out how to run it in a profiler of some sort.

Sab669
Sep 24, 2009

So, I'm pretty new to the whole "security", thing. I don't take my first official software security class until next quarter, but I'm always down for learning sooner.

I'm working on an online shopping cart sort of application in a .net class I'm taking this quarter, and I have it so people need to sign up before they can purchase stuff. But I'm curious, what's considered the 'proper' way of encrypting passwords in .Net?

I recently "learned how" in PHP (or rather, someone briefly showed me the phpass class), but I wouldn't know how to properly encrypt it when I first add a user to a database, and then when they actually log in compare that to what's in the DB.

Any pointers, goons?

aBagorn
Aug 26, 2004

Sab669 posted:

So, I'm pretty new to the whole "security", thing. I don't take my first official software security class until next quarter, but I'm always down for learning sooner.

I'm working on an online shopping cart sort of application in a .net class I'm taking this quarter, and I have it so people need to sign up before they can purchase stuff. But I'm curious, what's considered the 'proper' way of encrypting passwords in .Net?

I recently "learned how" in PHP (or rather, someone briefly showed me the phpass class), but I wouldn't know how to properly encrypt it when I first add a user to a database, and then when they actually log in compare that to what's in the DB.

Any pointers, goons?

I was just about to ask something like this, but what I want to do is scrape our AD for the information without having the user have to log in (what it should do is keep out all the users except those that are in our HelpDesk and Desktop Support OU, as well as domain admins)

I tried just doing this in the webconfig, doing an

allow roles "domain\ou"
deny users "*"

but that poo poo out errors about my SQL connection string.

Dietrich
Sep 11, 2001

Sab669 posted:

So, I'm pretty new to the whole "security", thing. I don't take my first official software security class until next quarter, but I'm always down for learning sooner.

I'm working on an online shopping cart sort of application in a .net class I'm taking this quarter, and I have it so people need to sign up before they can purchase stuff. But I'm curious, what's considered the 'proper' way of encrypting passwords in .Net?

I recently "learned how" in PHP (or rather, someone briefly showed me the phpass class), but I wouldn't know how to properly encrypt it when I first add a user to a database, and then when they actually log in compare that to what's in the DB.

Any pointers, goons?

Maybe this is what you meant by "Encrypting the password", but you don't really want to Encrypt the password.

You shouldn't know what your user's password is. It's irrelevant. You should know what your user's password hashes to when combined with a reproducible salt of some sort. When the user sets their password, you should calculate this hash and store it in your database, then promptly forget the actual password. When a user tries to log in, you should repeat this process and compare the result to the stored hash, then promptly forget the actual password. Your salt should be either a fixed, static value in your code, or should be based on a field on the user table that will be immutable after the password is set. Either one is alright, although salting all your passwords with the same salt is a little less secure than having a different salt for each user. You should not calculate a distinct salt for your user and store it on the table in a field named 'salt'.

The whole idea behind this is that you can't take a hash and re-create the data that it represents. The only way to calculate a password via a hash is a hash-table, which is created by taking a dictionary and hashing every word in it, and also hashing the dictionary with common character substitutions and mundane numeric and punctuation additions. This gives you a list information such as 06HX29KAFGH2 = 'P@ssw0rd13', and if they've got the hashes for your users, they can then figure out that 'GoKuSS69-420', who's password hash is '06HX29KAFGH2' uses 'P@ssw0rd13' to log in. By salting the password prior to hashing, that makes hash-tables pretty useless, because the string you are hashing isn't even the user's password.

Well, let me elaborate on that a bit... depending on the hashing mechanism and salt, there may be another distinct password that gives you the same hash. If they can figure out your salt and hash mechanism, and manage to get a hold of your users table, they could figure out a password that will validate with your password check function and they can use that to log in as that user to your site.

But here's the important part of being a good web developer: your first duty is to your users, and your users are most likely using the same password for your site that they've used for other sites, like Amazon, or Gmail, or Ebay. If your site gets hacked, and the hackers can use your users table to figure out what all your users passwords are, they can use that information to get at their other accounts, and mostly that's what they're interested in.

tl;dr: Don't store your user's password. Don't store an encrypted copy of your user's password. Don't even store a simple hash of your user's password. Doing so makes you a bad person.

Dietrich fucked around with this message at 19:51 on Feb 1, 2012

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Dietrich posted:


tl;dr: Don't store your user's password. Don't store an encrypted copy of your user's password. Don't even store a simple hash of your user's password. Doing so makes you a bad person.

Also, when working with user passwords, for the love of god use a SecureString. You don't want your user's password to get interned.

gariig
Dec 31, 2004
Beaten into submission by my fiance
Pillbug

Dromio posted:

Now I've pointed the routine at our production data set (20000 rows) and it's still way too slow:

code:
[Debug] '' 2/1/2012 10:12:18 AM Start
[Debug] '' 2/1/2012 10:12:21 AM Fetched 19550 items for tree
[Debug] '' 2/1/2012 10:12:21 AM Building dictionary
[Debug] '' 2/1/2012 10:17:58 AM Done building dictionary
...
[Debug] '' 2/1/2012 10:28:38 AM Done building hierarchy

I think Dietrich is right and you have a N+1 situation. I think even if you call ToList() it will only load the main query but if you have data that is only pulled via additional queries it will still fire off the subqueries because they are still IQueryable. Can you add
code:
<your DB context>.Log = Console.Out
to see if you have an N+1 situation. A quick explanation to the N+1 Problem because the name isn't intuitive (to me).

Adbot
ADBOT LOVES YOU

wwb
Aug 17, 2004

Also, just use freaking membership if you need to ask what is the proper way of encrypting passwords. It is pretty drat well implemented anyhow. Better than you can do it in most cases.

quote:

I think Dietrich is right and you have a N+1 situation. I think even if you call ToList() it will only load the main query but if you have data that is only pulled via additional queries it will still fire off the subqueries because they are still IQueryable. Can you add

I wouldn't want to start logging 20k records worth of SQL, that will probably cause it's own performance issue. I'd suggest using SQL trace to watch what is happening on the database server. That said, you could be hitting that 5 minute delay just hydrating a 20k line long object graph there. That is at least quite a bit of data coming over the wire. And it is a bit beyond L2S' skill set. I would strongly consider going back to a trusty old SqlDataReader here for ingest as that has loads less overhead.

  • Locked thread