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
Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
If I'm making significant custom changes in migrations, I like to make a new blank migration and add my custom SQL to that rather than adding it to one with all the auto-generated code. It's just an organizational thing, though.

Also, if you're doing custom migration code, it may be tempting to instantiate a DbContext to do your work. Don't do this - all your migration code should be in SQL.

Adbot
ADBOT LOVES YOU

chippy
Aug 16, 2006

OK I DON'T GET IT
I think the 'proper' way to do it is to modify the Seed() method in Configuration.cs:

http://www.asp.net/web-api/overview/data/using-web-api-with-entity-framework/part-3

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
I don't really like using the Seed method since it is run after every update-database. It's a bit easier to get things wrong than just having your SQL run once, guaranteed.

uXs
May 3, 2005

Mark it zero!
About half of you are ignoring the '7' part of my EF question, because there are no seed or populate mechanics in EF 7 yet.

I couldn't really do it in the 'up' method either, because I don't have a reference to the context and I really don't want to use plain SQL.

I ended up putting it all in a method somewhere and just call that from application startup. Maybe/probably it will have to change later but it works fine for now.

SixPabst
Oct 24, 2006

Bognar posted:

I don't really like using the Seed method since it is run after every update-database. It's a bit easier to get things wrong than just having your SQL run once, guaranteed.

Yeah agreed. I usually just make a post-deploy script (straight SQL, the horror!) that populates my database with seed data or whatever.

RICHUNCLEPENNYBAGS
Dec 21, 2010

Bognar posted:

If I'm making significant custom changes in migrations, I like to make a new blank migration and add my custom SQL to that rather than adding it to one with all the auto-generated code. It's just an organizational thing, though.

Also, if you're doing custom migration code, it may be tempting to instantiate a DbContext to do your work. Don't do this - all your migration code should be in SQL.



If you set the intializer to null it works OK.

LiterallyAnything
Jul 11, 2008

by vyelkin
I have a huge chunk of code I inherited from a company that my company bought out. I have some pretty cool plans for it, but I know very very little about C#. I'm pretty sure 95% of the code is in place, I just need it to do something more specific (for example, right now it gets details from a DB, and I want to upload Excel sheets for it to use.

I had a goon helping me back when this was just TCP socket connection request but not sure if he's interested in this or not. Either way he, and plenty others, can vouch for me when it comes to payment.

I'd love to talk to someone about this over the phone or messenger if possible to fully explain what's going on and show what all I have to determine a level of effort.

If anyone is interested PM me.


Got some interest. Thanks all.

LiterallyAnything fucked around with this message at 05:08 on Jul 2, 2015

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION
I've been thinking about unit testing a lot lately, and one of my points of confusion with the whole process is how to properly test something like an MVC controller. Since the controller itself will usually do very little, what you really want to test is whether it makes the correct calls to the correct methods in its dependant classes. For example:

code:
public class EmployeeController : Controller
{
    
    private readonly IService<Employee> employeeService;
    
    public EmployeeController(IService<Employee> employeeService)
    {
        this.employeeService = employeeService;
    }

    public ActionResult Details(int employeeId)
    {
        var employee = employeeService.GetById(employeeId);
        
        return View(employee);
    }

}
The action in this controller (Details), has only a couple of things to test:
  1. That the IService<Employee>.GetById(int id) method gets called
  2. That the correct view is requested
  3. That the view has been sent some data
I figure that the other stuff one might be tempted to test here is actually not the controller's responsibility and can be ignored. For example, testing that the correct client is sent to the view is pointless because that's really a test of the service layer, not the controller action.

So my question is - how do I test point 1? Or rather what is the correct way to test point 1? I imagine I could mock up the employee service with a fake "GetById" method that simply sets a flag saying it was called, and then the test can run an Assert on this flag. But this doesn't seem right, putting logic like that into a mock object. I can see this is probably a very common problem so I imagine there's a widely accepted solution?

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

The Wizard of Poz posted:

I've been thinking about unit testing a lot lately, and one of my points of confusion with the whole process is how to properly test something like an MVC controller. Since the controller itself will usually do very little, what you really want to test is whether it makes the correct calls to the correct methods in its dependant classes. For example:

code:

public class EmployeeController : Controller
{
    
    private readonly IService<Employee> employeeService;
    
    public EmployeeController(IService<Employee> employeeService)
    {
        this.employeeService = employeeService;
    }

    public ActionResult Details(int employeeId)
    {
        var employee = employeeService.GetById(employeeId);
        
        return View(employee);
    }

}

The action in this controller (Details), has only a couple of things to test:
  1. That the IService<Employee>.GetById(int id) method gets called
  2. That the correct view is requested
  3. That the view has been sent some data
I figure that the other stuff one might be tempted to test here is actually not the controller's responsibility and can be ignored. For example, testing that the correct client is sent to the view is pointless because that's really a test of the service layer, not the controller action.

So my question is - how do I test point 1? Or rather what is the correct way to test point 1? I imagine I could mock up the employee service with a fake "GetById" method that simply sets a flag saying it was called, and then the test can run an Assert on this flag. But this doesn't seem right, putting logic like that into a mock object. I can see this is probably a very common problem so I imagine there's a widely accepted solution?

No, you're right. Most mocking frameworks let you assert that a mock method was called.

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION

Ithaqua posted:

No, you're right. Most mocking frameworks let you assert that a mock method was called.

Okay cool, this is what I thought - I'm currently looking at Moq - does anyone have any recommendations that they have personally used? I'm very new to unit testing so I apologise for the newbie questions.

uXs
May 3, 2005

Mark it zero!
NSubstitute!

RICHUNCLEPENNYBAGS
Dec 21, 2010
In my personal opinion there's not really much value in a test like that. I mean I guess it's an unpopular one but I think it's just crap to maintain that won't give you that much insight into anything.

Gul Banana
Nov 28, 2003

it's a brittle test. you'd only be checking that the unit *does what it does*- not verifying that this is a correct or useful implementation.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

uXs posted:

NSubstitute!

VS2012+ (I think Premium SKU) has the fakes framework, which does the same basic thing as NSubstitute and Typemock.

I agree that the test doesn't have much value though.

Dumlefudge
Feb 25, 2013

RICHUNCLEPENNYBAGS posted:

In my personal opinion there's not really much value in a test like that. I mean I guess it's an unpopular one but I think it's just crap to maintain that won't give you that much insight into anything.

Gul Banana posted:


Ithaqua posted:


This is a more general question than something specifically regarding .NET development, but... as someone who isn't well-versed in testing (aside from a bit that was done as part of my degree), can I ask how you would go about testing something like what The Wizard Of Poz posted? Any bit of insight in how to identify how to test things would be great, although I get the feeling that the response may boil down to "It depends on the specifications".

Being a recent graduate who can see that the code is obviously in need of work, but without really being able to see how to improve it, is a bit demoralizing.

RICHUNCLEPENNYBAGS
Dec 21, 2010

Dumlefudge posted:

This is a more general question than something specifically regarding .NET development, but... as someone who isn't well-versed in testing (aside from a bit that was done as part of my degree), can I ask how you would go about testing something like what The Wizard Of Poz posted? Any bit of insight in how to identify how to test things would be great, although I get the feeling that the response may boil down to "It depends on the specifications".

Being a recent graduate who can see that the code is obviously in need of work, but without really being able to see how to improve it, is a bit demoralizing.

There are different theories about testing. My personal opinion about test-driven development is it's like a religion in that devotees push it hard on people but none of them can really fully adhere to it and feel guilty about it.

What I like to test is, you know, basically that procedures have the expected results. Particularly if there's some high risk to getting it wrong (for instance, Stack Exchange does very little testing, but everything touching finances is heavily tested, according to them). Tests are also useful if you want to refactor or add capabilities to some existing code but want to verify that you haven't changed the old behavior. Or if you identify a bug and want to ensure you've fixed it.

This is totally different than the normal TDD stuff, I guess, but I also use some reflection-based tests to verify the validity of my dependency injection configurations, Entity Framework classes/contexts, and so on.

crashdome
Jun 28, 2011
When I use unit tests, I rely on them and they help me. When I force myself to write unit tests for things that are unimportant, I waste my time. TDD for me is just not feasible because it literally doubles my development time. I DON'T need to unit test controllers/services if most of the methods I'm testing are only used once somewhere. Good exception handling will pinpoint a problem quickly during integration testing or even in live production if it's just that rare of a circumstance. I DO need to unit test that recursive method, factory methods, or that class that performs fragile operations.

More often than any other bug I inadvertently create (while not having any unit tests) is because I didn't update a related class or interface properly when adding a new feature somewhere and I get the dreaded null reference exception. Nothing I hate more than to see something that worked prior suddenly just bail somewhere N-levels deep into the logic 5 seconds into hitting "Debug" and having to dig out why with a dozen different line breaks and mashing "Continue" until I find the culprit.

Now integration testing... that is something I really wish I could have a clone of myself to focus 100% on. Most of my bugs are now things like UI oddities or when some device in my IO stack decides to stop working correctly mid-process and my application shits itself. It's not purely my fault but, the users always want "my application" to handle everyone else's problems.

MachinTrucChose
Jun 25, 2009
Can I get some advice from more experienced Windows devs? I'd like to have a desktop app that can search a specific directory for files, using filename as well as file contents (then I do something with the result the user selects). The target directory is on a network drive, and the files are a mix of text, XML, and Office files.

So I googled for a while and discovered Windows Search, and figured out you can query the search index using C# and OLE DB. If you have Office installed, even binary formats like .doc and .xls can be searched. I figured "wonderful, I'll just index the directory, query the search index, and show the results". I figured out the search API, but then was foiled by IT/OS reasons (more like cynical MS trying to force people to buy Server licenses): Windows doesn't let you index network locations. Well, 32-bit Windows does, there's a hard-to-find optional add-in download, but there's nothing for 64-bit.

People on the MS forums bitched about it several years ago when people started moving to 64-bit OSes, and the "community MVP" drone's only answer is to configure the network drive to be available offline (ie fully copied). That's a really horrible work-around, I don't want every workstation that wants to use the tool copying the entire directory locally. What if someone drops a 50GB file there.

I just want a quick tool for co-workers to use at work and leave me alone, and don't want to spend much time on it. Is there anything I can do that doesn't involve upgrading IT infrastructure like replacing the fileserver with a Windows Server install that has the Windows Search Service role enabled? I tried finding a 3rd party .NET library that handles searching and poo poo, even a commercial one, but I can't find anything (probably because it's an IT/OS thing, not a .NET thing). There's stuff like Apache Solr, ie avoiding MS tech completely, but considering I have zero experience with it, it would take too long to set up.

I know this will only piss you guys off, and it will come off as whiny, but this is why I'm afraid of relying on MS tech. You never know when the rug is pulled from under you to increase sales for a new product (in this case, Windows Server and its Windows Search Service). It would have been trivial to allow Windows Search to index a network location. It's not some radical feature, just use the same drat filesystem APIs you use for local directories.

MachinTrucChose fucked around with this message at 22:19 on Jul 3, 2015

Calidus
Oct 31, 2011

Stand back I'm going to try science!
If your file server is a windows 7 box why just write a stupid little web app to run on IIS?

Destroyenator
Dec 27, 2004

Don't ask me lady, I live in beer
Write tests for what's going to break and for odd cases that will be forgotten so that when people fix your code they don't break the functionality.

Good tests should explain the code, but always consider [value delivered/time spent] for everything your write.

Mellow_
Sep 13, 2010

:frog:

crashdome posted:

More often than any other bug I inadvertently create (while not having any unit tests) is because I didn't update a related class or interface properly when adding a new feature somewhere and I get the dreaded null reference exception. Nothing I hate more than to see something that worked prior suddenly just bail somewhere N-levels deep into the logic 5 seconds into hitting "Debug" and having to dig out why with a dozen different line breaks and mashing "Continue" until I find the culprit.

Alternatively, set a breakpoint at the beginning of the suspect block and step through with f10 until you find the offending line. When you do, step into it with f11 and start digging.

SirViver
Oct 22, 2008

AuxPriest posted:

Alternatively, set a breakpoint at the beginning of the suspect block and step through with f10 until you find the offending line. When you do, step into it with f11 and start digging.
Alternatively, you open Debug > Exceptions and check "Thrown" for Common Language Runtime Exceptions (or, if necessary, just for the exact exception type if your code legitimately throws/handles other exceptions) and hey presto, VS will break right at the point where the exception is generated.

Che Delilas
Nov 23, 2009
FREE TIBET WEED

MachinTrucChose posted:

Can I get some advice from more experienced Windows devs? I'd like to have a desktop app that can search a specific directory for files, using filename as well as file contents (then I do something with the result the user selects). The target directory is on a network drive, and the files are a mix of text, XML, and Office files.

Lucene.Net (that's a library, not a website URL) is probably your best bet if you want to do custom things (solr is built upon the original Java version of this). Haven't used it myself though, so I can't tell you how arcane it is.

crashdome
Jun 28, 2011

AuxPriest posted:

Alternatively, set a breakpoint at the beginning of the suspect block and step through with f10 until you find the offending line. When you do, step into it with f11 and start digging.


SirViver posted:

Alternatively, you open Debug > Exceptions and check "Thrown" for Common Language Runtime Exceptions (or, if necessary, just for the exact exception type if your code legitimately throws/handles other exceptions) and hey presto, VS will break right at the point where the exception is generated.

Oh, yes, I have it checked. I was just lamenting my most recent update a few weeks ago to a WinForms app in which the exception was thrown a few levels deep because I didn't override one of a few virtual methods on a base class. Sometimes when you know of the few places it can happen, the quickest thing to do is just plow through a few breaks. I could have even used conditional breaks but the time for me to type those out would take just as long as just breaking and hovering over a parameter or two and moving on.

I think that is a prime example of a good use for a simple unit test to save time: Adding a new subclass? Unit test each overridden method to make sure it's not defaulting to a base class.

Next round I have to update that application I think I will take my own advice.

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION
I think I gave the wrong impression with my example - I didn't want to write out pages of code for the sake of an SA post so I just quickly wrote a stupid-simple controller action to demonstrate my problem. I'm not actually planning on unit testing anything like that, really my point was that I needed to test if a method had been called.

RICHUNCLEPENNYBAGS
Dec 21, 2010
What do people use to enforce indentation and code style and the rest of that kind of stuff? We're using a shared ReSharper file but it's kinda so-so (some of the settings do not seem to be getting shared consistently; don't know why) so I wonder if there's a better way to do it. (Ideally you could just point it at files and say "make them conform to the style").

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

RICHUNCLEPENNYBAGS posted:

What do people use to enforce indentation and code style and the rest of that kind of stuff? We're using a shared ReSharper file but it's kinda so-so (some of the settings do not seem to be getting shared consistently; don't know why) so I wonder if there's a better way to do it. (Ideally you could just point it at files and say "make them conform to the style").

Code reviews, FxCop/StyleCop analysis rules as part of CI. Basically, make it a pain in the rear end for the developer not conforming to rules.

Drastic Actions
Apr 7, 2009

FUCK YOU!
GET PUMPED!
Nap Ghost

Ithaqua posted:

Code reviews, FxCop/StyleCop analysis rules as part of CI. Basically, make it a pain in the rear end for the developer not conforming to rules.

My last job had this, and it worked out really well. It was a royal pain in the rear end, but the end result was worth it. Especially after getting resharper and matching its rules to our FxCop/Stylecop set.

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION

Drastic Actions posted:

My last job had this, and it worked out really well. It was a royal pain in the rear end, but the end result was worth it. Especially after getting resharper and matching its rules to our FxCop/Stylecop set.

Could definitely use something like this where I work now...

Boz0r
Sep 7, 2006
The Rocketship in action.
Is there ever any reason to do custom setters like this, when not calling any external listeners or anything(programming in Unity:

code:
public string Name
{
    get { return this.name; }
    set
    {
        if (value != name)
        {
            name = value;
        }
    }
}

Dumlefudge
Feb 25, 2013

RICHUNCLEPENNYBAGS posted:

There are different theories about testing. My personal opinion about test-driven development is it's like a religion in that devotees push it hard on people but none of them can really fully adhere to it and feel guilty about it.

What I like to test is, you know, basically that procedures have the expected results. Particularly if there's some high risk to getting it wrong (for instance, Stack Exchange does very little testing, but everything touching finances is heavily tested, according to them). Tests are also useful if you want to refactor or add capabilities to some existing code but want to verify that you haven't changed the old behavior. Or if you identify a bug and want to ensure you've fixed it.

This is totally different than the normal TDD stuff, I guess, but I also use some reflection-based tests to verify the validity of my dependency injection configurations, Entity Framework classes/contexts, and so on.

crashdome posted:

When I use unit tests, I rely on them and they help me. When I force myself to write unit tests for things that are unimportant, I waste my time. TDD for me is just not feasible because it literally doubles my development time. I DON'T need to unit test controllers/services if most of the methods I'm testing are only used once somewhere. Good exception handling will pinpoint a problem quickly during integration testing or even in live production if it's just that rare of a circumstance. I DO need to unit test that recursive method, factory methods, or that class that performs fragile operations.

More often than any other bug I inadvertently create (while not having any unit tests) is because I didn't update a related class or interface properly when adding a new feature somewhere and I get the dreaded null reference exception. Nothing I hate more than to see something that worked prior suddenly just bail somewhere N-levels deep into the logic 5 seconds into hitting "Debug" and having to dig out why with a dozen different line breaks and mashing "Continue" until I find the culprit.

Now integration testing... that is something I really wish I could have a clone of myself to focus 100% on. Most of my bugs are now things like UI oddities or when some device in my IO stack decides to stop working correctly mid-process and my application shits itself. It's not purely my fault but, the users always want "my application" to handle everyone else's problems.

Being the newbie, I reckon that there's a high risk of "getting it wrong" everywhere.

Thanks for your thoughts. It looks like have to start hunting down code that merits testing (once I've turned the obviously sketchy code into something less sketchy), although it is really confusing coming from my lecturer's preaching of SOLID principles, testing in isolation, etc to developing a plugin (which is loaded by black magic and blood rituals) whose sole purpose is to interact with an awkward API wrapper and trying to figure out how to apply what I was thought.

RICHUNCLEPENNYBAGS
Dec 21, 2010

Dumlefudge posted:

Being the newbie, I reckon that there's a high risk of "getting it wrong" everywhere.


What I mean is more that the consequences of getting something wrong are severe. If the consequence of a bug somewher would be that it exposes a bunch of sensitive information or double-charges someone's credit card that deserves more care than something where the consequence of a bug would be misaligned table elements in the UI.

ether
May 20, 2001

Ithaqua posted:

Code reviews, FxCop/StyleCop analysis rules as part of CI. Basically, make it a pain in the rear end for the developer not conforming to rules.

I'll be THAT guy and say stylecop in itself is a dumb tool that serves no purpose but make peoples lives harder for no real reason. Codereviews are the prime moment to explain WHY you have certain coding guidelines. Still bitter because codereviews where tagged as a waste of time and we got stylecop instead "because it serves the same purpose", loving asshats, and it made most of our legacycode even more obtuse.

Aside from the personal bitterness there are some dumbass rules in stylecop that kill overarching code-structure (encase public/privates/events/etc in regions, alphabetize functions), make code less clear (disallowing a _-prefix for locals, thus making it less clear that you have scoping issues) and mess with 'code' that doesn't get compiled (all the fuckery with HOW you must comment things)

zerofunk
Apr 24, 2004
I like having it. It probably depends on your team, but I know that we would have people checking in poorly formatted code if StyleCop wasn't throwing up warnings that they knew had to be fixed. It sucks, but that's just how it is. They'll do it on another project where we're using old tools that have little in the way of support for enforcing things like that.

There are some things that are stupid, but you can change them. I definitely wouldn't want StyleCop to replace code reviews or vice versa though.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

Boz0r posted:

Is there ever any reason to do custom setters like this, when not calling any external listeners or anything(programming in Unity:

code:
public string Name
{
    get { return this.name; }
    set
    {
        if (value != name)
        {
            name = value;
        }
    }
}

No, just use auto-properties.

LOOK I AM A TURTLE
May 22, 2003

"I'm actually a tortoise."
Grimey Drawer

Boz0r posted:

Is there ever any reason to do custom setters like this, when not calling any external listeners or anything(programming in Unity:

code:
public string Name
{
    get { return this.name; }
    set
    {
        if (value != name)
        {
            name = value;
        }
    }
}

If it's intended as an optimization it will actually have the opposite effect, since comparing two strings is far slower than assigning a string value that's already there to a property. In fact, assigning the same string value to a property could conceivably end up being optimized away entirely through some combination of string interning and the JIT compiler. (It probably won't, but don't sweat it.)

If it's intended as something else than an optimization it's merely pointless, unless something else is also happening inside the if-block.

Boz0r
Sep 7, 2006
The Rocketship in action.
Yeah, it's something I've stumbled upon a couple of times where I work. It's a project in Unity3D, but I don't think that has anything weird like listening on all field changes.

raminasi
Jan 25, 2005

a last drink with no ice
That's the kind of thing you might also see as vestigial remains of more complicated logic.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

LOOK I AM A TURTLE posted:

If it's intended as an optimization it will actually have the opposite effect, since comparing two strings is far slower than assigning a string value that's already there to a property. In fact, assigning the same string value to a property could conceivably end up being optimized away entirely through some combination of string interning and the JIT compiler. (It probably won't, but don't sweat it.)

If it's intended as something else than an optimization it's merely pointless, unless something else is also happening inside the if-block.

It could be slower even with int values where comparison is simple. What was a simple memory write now becomes a branch and memory write, which could be significantly slower if the branch prediction fails.

Adbot
ADBOT LOVES YOU

Mellow_
Sep 13, 2010

:frog:
E: nevermind, misunderstood the post I was replying to.

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