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
Web API will serialize things for you if you just return the value. Use HttpResponseException for error codes.

code:
public List<Transaction> Put(int id, Transaction trans)
{
    Console.WriteLine("Id: " + id + " value: " + trans.Description);

    if (id != trans.TransactionId)
    {
        throw new HttpResponseException(HttpStatusCode.BadRequest);
    }

    // update other transactions based on the transaction description and some other stuff
    var updatedtransactions = _allocationLogicService.CarryForwardAllocationRule(trans);
    // updatedtransactions is a List<Transaction>

    try
    {
        _db.Entry(trans).State = EntityState.Modified;
        _db.SaveChanges();
    }
    catch (Exception ex)
    {
        throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex)); // use this overload to pass exception information
    }

    return updatedtransactions;
}

Adbot
ADBOT LOVES YOU

bpower
Feb 19, 2011
Thank you so much.

crashdome
Jun 28, 2011

chippy posted:

Thanks for this. When I used the List as the datasource for the ListBox directly, it didn't seem to update the display of the listbox as I added and removed items. I ended up creating a BindingSource with the list as its datasource, and then using that as the datasource for the listbox. Once I did it that way, it kept up with any items added or removed, and also took care of maintaining the selection automatically.

Yeah, BindingSource is great. A list doesn't have any INotify ....blah blah... so you'd have to call Suspend, Resume, Refresh on the listbox control manually during the update. Thanks for reminding me how much I don't miss WinForms.

bobua
Mar 23, 2003
I'd trade it all for just a little more.

If I'm trying to add a datarow to a datatable, is there a better way than this?

code:
var newrow = datatable.NewStorageAllClientsRow();
                    
newrow.ClientID = row.ClientID;
if (!row.IsDateInNull()) { newrow.DateIn = row.DateIn; }
if (!row.IsDateOutNull())  { newrow.DateOut = row.DateOut; }
if (!row.IsProjectNull()) { newrow.Project = row.Project; }
Row in this context is just a datarow from another datatable of a different type.

UberJumper
May 20, 2007
woop
Does anyone have suggestions for how to name unit testing methods? We started a new project and since are testing guy recently left i am taking over his spot temporarily.

Everything i see seems to have insanely long method names.

Che Delilas
Nov 23, 2009
FREE TIBET WEED

UberJumper posted:

Does anyone have suggestions for how to name unit testing methods? We started a new project and since are testing guy recently left i am taking over his spot temporarily.

Everything i see seems to have insanely long method names.

ShouldDoAThingUnderCondition, basically, which yeah results in long method names. The method names are basically sentences that tell you what you should expect, so that when you run a hundred of them at once and one fails, you can see more or less at a glance exactly how the method under test is failing without going into the test method. In theory, anyway.

ShouldThrowExceptionWhenGivenProductIdDoesNotExist(), for example.

You don't have to do it that way, it's just a descriptive name. It's not like you're going to be calling that function from elsewhere in your program, so it's not polluting your code.

Che Delilas fucked around with this message at 23:00 on Feb 26, 2015

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

UberJumper posted:

Does anyone have suggestions for how to name unit testing methods? We started a new project and since are testing guy recently left i am taking over his spot temporarily.

Everything i see seems to have insanely long method names.

Unit tests are generally named based on what they're testing. Unfortunately, the situations that benefit the most from automated testing are ones with complicated logic, so the tests can be fairly complicated chains of "given A and B, in C situations, when it's D day after E AM, X should happen and Y should not happen", which means complicated test names will follow suit. I don't really have a good answer for this, but I pretty commonly see long test names in our own code and a lot of open source code.


*where X is storming the beaches of Normandy and Y is the Germans winning

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

UberJumper posted:

Does anyone have suggestions for how to name unit testing methods? We started a new project and since are testing guy recently left i am taking over his spot temporarily.

Everything i see seems to have insanely long method names.

I use somewhat BDD styled naming, where my tests define the behavior of the class.

So:

code:
When_I_Foo_The_Bar 
{
    The_Bar_Should_Be_Baz() {}
    An_Exception_Should_Be_Thrown_When_Butts_Is_Null() {}
}

Inverness
Feb 4, 2009

Fully configurable personal assistant.
There is no worse way to format names.

brap
Aug 23, 2004

Grimey Drawer
I've got some legacy code with a whole lot of this

code:
private int field1;

public int Field1
{
    get
    {
        return field1;
    }
    set
    {
        field1 = value;
    }
}

// repeat like 20 times in each file
I would rather have this:
code:
public int Field1 { get; set; }
// etc...
Has anyone written a tool to go through a source file and do this?

Inverness
Feb 4, 2009

Fully configurable personal assistant.

fleshweasel posted:

Has anyone written a tool to go through a source file and do this?
ReSharper can do it.

NihilCredo
Jun 6, 2011

iram omni possibili modo preme:
plus una illa te diffamabit, quam multæ virtutes commendabunt

fleshweasel posted:

I've got some legacy code with a whole lot of this

code:
private int field1;

public int Field1
{
    get
    {
        return field1;
    }
    set
    {
        field1 = value;
    }
}

// repeat like 20 times in each file
I would rather have this:
code:
public int Field1 { get; set; }
// etc...
Has anyone written a tool to go through a source file and do this?

Yes, the find / replace tool. This is a great place to use a regular expression.

brap
Aug 23, 2004

Grimey Drawer
Maybe if each property directly followed the backing field. But I actually have a region of fields and a region of properties. It's not good.

No Safe Word
Feb 26, 2005

Use VsVim and write a vim macro to do it :getin:

crashdome
Jun 28, 2011

fleshweasel posted:

Has anyone written a tool to go through a source file and do this?


Inverness posted:

ReSharper can do it.


NihilCredo posted:

Yes, the find / replace tool. This is a great place to use a regular expression.


No Safe Word posted:

Use VsVim and write a vim macro to do it :getin:


There's got to be a "How many programmers" joke somewhere in all of this.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

Inverness posted:

ReSharper can do it.

Seconding this. ReSharper can do it as part of its "code cleanup", so it will switch to auto-properties wherever it can. If you don't like the nuclear option, you can search for all instances of that code issue and Alt+Enter each one to fix it.

rarbatrol
Apr 17, 2011

Hurt//maim//kill.
Speaking of Web API, I have a question: how would I take full advantage of async/await with one of my controllers? Returning tasks for that doesn't make sense to me, and neither does blocking until the final result is ready.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

rarbatrol posted:

Speaking of Web API, I have a question: how would I take full advantage of async/await with one of my controllers? Returning tasks for that doesn't make sense to me, and neither does blocking until the final result is ready.

Just return tasks, that's exactly what they're for. If you need to serialize a return type, make sure you're using the generic task type, e.g. Task<Order>.

rarbatrol
Apr 17, 2011

Hurt//maim//kill.

Bognar posted:

Just return tasks, that's exactly what they're for. If you need to serialize a return type, make sure you're using the generic task type, e.g. Task<Order>.

Okay, cool. Thanks. I wasn't sure how tasks crossed that boundary.

NihilCredo
Jun 6, 2011

iram omni possibili modo preme:
plus una illa te diffamabit, quam multæ virtutes commendabunt

fleshweasel posted:

Maybe if each property directly followed the backing field. But I actually have a region of fields and a region of properties. It's not good.

...but that makes things even easier? Delete the fields, then replace the {get {return (.+?) } set {\1 = value} } pattern* with {get; set;}. Done.

I mean, if you already have ReSharper / CodeRush then yeah, let them do it for you, but if you don't this isn't a huge problem or anything.


* For readability I didn't insert the newlines or escaped the curly braces, that's all you need though.

NihilCredo fucked around with this message at 07:41 on Feb 27, 2015

zokie
Feb 13, 2006

Out of many, Sweden
I'm ashamed none mentioned Roslyn yet!

brap
Aug 23, 2004

Grimey Drawer

NihilCredo posted:

...but that makes things even easier? Delete the fields, then replace the {get {return (.+?) } set {\1 = value} } pattern* with {get; set;}. Done.

I mean, if you already have ReSharper / CodeRush then yeah, let them do it for you, but if you don't this isn't a huge problem or anything.


* For readability I didn't insert the newlines or escaped the curly braces, that's all you need though.

Good call. I didn't even think of it. Might try to whip that expression up next time I'm at work.

I am tending to avoid resharper based on negative anecdotes and the assumption that if wont be that easy to turn off and on as needed. I am likely to be wrong on at least one of those points.

EssOEss
Oct 23, 2006
128-bit approved
What are the negative things you have heard about ReSharper?

zokie
Feb 13, 2006

Out of many, Sweden

EssOEss posted:

What are the negative things you have heard about ReSharper?

I must say that I'm getting more and more disappointed at ReSharper, if you install Roslyn it conflicts with IntelliSense usually putting its gray and boring pop-up over the colorful one from Roslyn. Sometimes it really doesn't understand namespaces, and resolves usings terribly. A lot of ReSharpers features are already in VS, just use CTRL + . instead

The only things I really like is the Go To Anything (CTRL + T), Find Usages, Go To Implementation being told if a method is used or not without building. Many of these things can be accomplished through different means. I guess I'll keep using ReSharper a while longer, but once VS2015 hits together with Roslyn I hope I can wave ReSharper good bye!

Inverness
Feb 4, 2009

Fully configurable personal assistant.

zokie posted:

I'm ashamed none mentioned Roslyn yet!
Because Roslyn ships with VS2015 and isn't even something released yet.

NihilCredo
Jun 6, 2011

iram omni possibili modo preme:
plus una illa te diffamabit, quam multæ virtutes commendabunt

EssOEss posted:

What are the negative things you have heard about ReSharper?

For me, it simply slowed down VS2013 far beyond what I was willing to tolerate. I was considering keeping it just for the occasional refactoring while turning off Code Analysis, but then I tried CodeRush and it provided almost the same functionality at a fraction of the speed penalty.

mastersord
Feb 15, 2001

Gold Card Putty Fan Club
Member Since 2017!
Soiled Meat

bobua posted:

If I'm trying to add a datarow to a datatable, is there a better way than this?

code:

var newrow = datatable.NewStorageAllClientsRow();
                    
newrow.ClientID = row.ClientID;
if (!row.IsDateInNull()) { newrow.DateIn = row.DateIn; }
if (!row.IsDateOutNull())  { newrow.DateOut = row.DateOut; }
if (!row.IsProjectNull()) { newrow.Project = row.Project; }

Row in this context is just a datarow from another datatable of a different type.

VB.Net programmer here. I just use row = datatable.rows.newrow to create the datarow in my table's shape and then datatable.rows.add(row) to add it to my datatable. I assume you have a separate method for committing changes to the database.

As for setting field values, i use a class with my datatables and keep track of a row cursor. I end up with
code:
datatable.rows.item(rowindex)(fieldname) = value

"Fieldname" is the column name as it appears in the table and/or database query.

I don't know if that helps.

mastersord fucked around with this message at 15:48 on Feb 27, 2015

wwb
Aug 17, 2004

EssOEss posted:

What are the negative things you have heard about ReSharper?

Breaks F# code completion.

Mr. Crow
May 22, 2008

Snap City mayor for life
Counter-argument, I have no issues with ReSharper, it's superb!

The XAML support is amazing (among other obvious benefits).

UberJumper posted:

Does anyone have suggestions for how to name unit testing methods? We started a new project and since are testing guy recently left i am taking over his spot temporarily.

Everything i see seems to have insanely long method names.

Roy Osherove recommends a METHOD_SCENARIO_BEHAVIOR pattern (or I've adopted this implementation of whatever I remember him suggesting).

e.g. Butts_HasFooAndCanFoo_ReturnsBar

EssOEss
Oct 23, 2006
128-bit approved
I use OperationUnderTest_ConditionUnderTest_ExpectedResult. So ParseHtmlDocument_WithNonClosedTag_CanStillProcessTag, with the class being named like HtmlDocumentTests. Seems to work fine so far. In fact, it helps frame tests in the right viewpoint - often I see developers on my team make lovely tests that don't test a meaningful scenario but this tends to come out and get fixed because the middle part of the name is obvious a nonsense condition or even missing (e.g. ParseHtmlDocument_WhenParsingHtmlDocument_ParsesHtmlDocument is bullshit).

chippy
Aug 16, 2006

OK I DON'T GET IT

crashdome posted:

Yeah, BindingSource is great. A list doesn't have any INotify ....blah blah... so you'd have to call Suspend, Resume, Refresh on the listbox control manually during the update. Thanks for reminding me how much I don't miss WinForms.

Yeah, it sucks balls. Really hoping to get some WPF work in my job come up so I have a chance to learn it - I don't have the time in my spare time in between doing my degree. I used to do 3 days a week on a MVC project and 2 days on the old Winforms nonsense but it's been 5 days a week on Winforms recently :(

Mr Shiny Pants
Nov 12, 2012
F# question:

I have a class that spins up a couple of mailbox processors and puts them in a List.

The class also adds and anonymous eventhandler for the mailbox processor's Error event per mailbox processor.

If an exception occurs the mailbox processor raises an event which the class responds to by disposing the mailbox processor.

Do I need to unregister the eventhandler? Or does it get Garbage Collected after the mailbox processor is disposed of?

In the same eventhandler I also spin up a new mailbox processor and register the eventhandler function again.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
Events can be fickle and it's not always completely obvious what behavior will cause a memory leak. If you're really worried about it, you can set any mailbox processor events to null during the Dispose method. This will remove all of the subscribers and, hence, remove all of the references from the processor to the subscribers.

Mr Shiny Pants
Nov 12, 2012

Bognar posted:

Events can be fickle and it's not always completely obvious what behavior will cause a memory leak. If you're really worried about it, you can set any mailbox processor events to null during the Dispose method. This will remove all of the subscribers and, hence, remove all of the references from the processor to the subscribers.

I am not really worried, I was just curious and don't want to get in the habit of doing dumb things. :) I don't quite understand:

quote:

mailbox processor events to null

How do I do this?

Btw I use the Add method instead of the AddHandler method. Don't know if it matters.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

Mr Shiny Pants posted:

How do I do this?

Btw I use the Add method instead of the AddHandler method. Don't know if it matters.

Oh, whoops, I forgot you mentioned you were using F#. I'm not exactly sure how that would be done in F#. I know you can use RemoveHandler to remove a specific handler, but I'm not sure about clearing all handlers.

EssOEss
Oct 23, 2006
128-bit approved
Events hold a reference to the object that is doing the event handling but not vice versa. So no, you do not need to unregister event handlers from mailbox processor events if the mailbox processor is going away, only the other way around - if the thing doing the event handling is going away.

That is foo.SomethingHappened += bar.EventHandler makes foo hold a reference to bar but not the other way around. If bar sets all references to foo to null, it will go away (provided that no other references exist). In case the handler is a closure, foo just gains a reference to the closure object that the compiler generates, which may in turn contain references to other objects.

EssOEss fucked around with this message at 21:12 on Feb 27, 2015

Mr Shiny Pants
Nov 12, 2012

EssOEss posted:

Events hold a reference to the object that is doing the event handling but not vice versa. So no, you do not need to unregister event handlers from mailbox processor events if the mailbox processor is going away, only the other way around - if the thing doing the event handling is going away.

That is foo.SomethingHappened += bar.EventHandler makes foo hold a reference to bar but not the other way around. If bar sets all references to foo to null, it will go away (provided that no other references exist). In case the handler is a closure, foo just gains a reference to the closure object that the compiler generates, which may in turn contain references to other objects.

Thanks, that makes sense.


Bognar posted:

Oh, whoops, I forgot you mentioned you were using F#. I'm not exactly sure how that would be done in F#. I know you can use RemoveHandler to remove a specific handler, but I'm not sure about clearing all handlers.

No worries, thanks anyway :)

mastersord
Feb 15, 2001

Gold Card Putty Fan Club
Member Since 2017!
Soiled Meat
I have an Entity Framework question. In EF6, is there a way to have 2 or more entities mapped to the same table set up in a way that VS2013 will let me compile it? I can run it in the debugger just fine but I get errors when I try to build.

My legacy projects have custom queries all over the place and converting them all to "Select *" seems like a bad idea. My eventual plan is to convert them all to functions and views in the database but I'm playing around with the "SqlQuery()" method and thinking this as a "Plan B".

These queries are used in a "read-only" capacity (reporting, populating ComboBoxes and DataGrids).

From what I have read, I found an old post from Microsoft about why they won't add this feature to EF from a few years ago, and a tutorial about how to split a table amongst multiple entities.

That doesn't work if the multiple entities share more than a foreign key in common. I am missing something. I am not at my desk so I can't post the error.

Thanx in advance.

RangerAce
Feb 25, 2014

mastersord posted:

I have an Entity Framework question. In EF6, is there a way to have 2 or more entities mapped to the same table set up in a way that VS2013 will let me compile it? I can run it in the debugger just fine but I get errors when I try to build.

My legacy projects have custom queries all over the place and converting them all to "Select *" seems like a bad idea. My eventual plan is to convert them all to functions and views in the database but I'm playing around with the "SqlQuery()" method and thinking this as a "Plan B".

These queries are used in a "read-only" capacity (reporting, populating ComboBoxes and DataGrids).

From what I have read, I found an old post from Microsoft about why they won't add this feature to EF from a few years ago, and a tutorial about how to split a table amongst multiple entities.

That doesn't work if the multiple entities share more than a foreign key in common. I am missing something. I am not at my desk so I can't post the error.

Thanx in advance.

Is it something that having an intermediary data access object could fix? You should be doing that anyway. Basically have your EF entity and have your two entities that map to the EF entity. I wouldn't use EF entities directly in your app, for example. Make that a totally separate layer. The temptation with EF is to just use EF entities all over the place, but it's usually better in the long run if you de-couple a bit, instead.

Adbot
ADBOT LOVES YOU

crashdome
Jun 28, 2011
I'll disagree with RangerAce a bit. I've taken to using EF Entities as models in my viewmodels directly because they are perfect.

I've also not had a problem using multiple entity sets to a single table. Can you post your code? or an example?

e: Are there relations to other tables? This might be the problem. I have a legacy datatable where there were multiple columns for different row types but, there are no foreign keys. Alternatively, you could also try mapping entities to unique SQL views or sprocs named differently.

crashdome fucked around with this message at 01:23 on Feb 28, 2015

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