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
epswing
Nov 4, 2003

Soiled Meat
Visual Studio 2012, with Update 4.
New Project -> ASP.NET MVC 4 Web Application -> Web API
Run the project, see standard "Welcome to ASP.NET Web API!" greeting page.
Click "API" in top right corner, taking me to auto-generated API documentation at http://localhost:12345/Help



Take a look at MvcApplication1\MvcApplication1\Areas\HelpPage\Views\Help\Index.cshtml



Apparently the Help area of a fresh WebAPI project Just Doesn't Work out of the box. I've tried a few suggestions like running Uninstall/Install-Package Microsoft.AspNet.WebApi from the package manager console, no dice. If I look at the properties of System.Web.Http in my references list, and set Copy Local to True, http://localhost:12345/Help works just fine.

What the hell is wrong with my system?

Adbot
ADBOT LOVES YOU

gariig
Dec 31, 2004
Beaten into submission by my fiance
Pillbug
Try updating your nuget packages. Microsoft pushed a new version of the MVC4 dll today that is breaking things.

StackOverflow
Microsoft bulletin

EDIT: Rereading this probably won't help. However, this might be good information for other developers

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug
Speaking of updates, VS2013 Update 4 RC is out.

http://blogs.msdn.com/b/visualstudio/archive/2014/10/16/visual-studio-2013-update-4-rc-now-available.aspx

Scaramouche
Mar 26, 2001

SPACE FACE! SPACE FACE!

Newb question:
VS2012 on a basic web project

I've got a solution (let's call it Helper) that's been running on my local workstation for the last 18 hours, on the local IISExpress worker process. As you can probably guess from my earlier questions, it's doing a bunch of image downloading and manipulation (370,000 images to be exact). I'm doing this on my local because it's a one time thing and I thought it would finish overnight. The thing is, I want to run/build Helper again, in a separate instance that won't blow up/stop my huge image download (which has at least another 14 hours to go). How can I run another another instance of the same project, build it, and not have it interfere/mess with the existing and running version of the same project? Due to the chancy nature of losing 18 hours of downloading if I'm wrong, I'm kind of scared to guess and test on this one. These are possibilities I've thought of in order of ugliness:
1. Just build it again in the same instance of VS, iis is smart enough to not shut down an existing running process.
2. Open another instance of VS, open the solution, and VS will be smart enough to keep them separate
3. Copy entire solution folder somewhere else and rename it and open as solution in VS (uggh the RCS implications)
or
4. Man up and just RDP into the development server, get latest from Git, and go from there.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

Scaramouche posted:

1. Just build it again in the same instance of VS, iis is smart enough to not shut down an existing running process.
2. Open another instance of VS, open the solution, and VS will be smart enough to keep them separate
3. Copy entire solution folder somewhere else and rename it and open as solution in VS (uggh the RCS implications)
or
4. Man up and just RDP into the development server, get latest from Git, and go from there.

Big fat No to 1 and 2. 3 should work with just copying and not renaming the solution, and 4 sounds pretty similar to 3.

The real answer, though, is to build long running processes to be able to pick up from where they left off after a catastrophic failure (or, you know, a rebuild).

Bognar fucked around with this message at 01:59 on Oct 17, 2014

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug
Silly question: Why are you downloading and manipulating images in a web application? Not that it matters in this particular instance, it's just a weird thing for a web application to do.

wwb
Aug 17, 2004

If you do anything to the one that is running it will bounce IIS because the DLLs will change which tells IIS to bounce the app pool.

The best bet if you want to work locally in it would be to check out a 2nd copy in git and develop there while it runs, being very careful of VS.

The better bet for the future is to deploy a copy locally and run long-running tasks there if you don't need interactive debugging for some reason.

Scaramouche
Mar 26, 2001

SPACE FACE! SPACE FACE!

Thanks guys, looks like I was right to be paranoid instead of diving right into 1 or 2.

It's running as a web app because this is kind of my swiss-army knife utility for functions related to a particular web site, and I like being able to instantiate events via URL (e.g. /helper.aspx?op=update-inventory). While this batch is a one-off, the idea is that it'll run iteratively in future, and only have to handle 200-300 images a day (product images for ecommerce). The way it's set up now is a manufacturer can launch new products and they'll automatically be created for the site and uploaded to 8 different marketplaces within a few hours. The downside is when a vendor decides to launch 100,000 new products all at once.

I can come back if it's interrupted; it's downloading images based on an incremental id so worse came to worst I could just look at last id processed and jump on from there. I knew it was going to be long running, but not this long running. I also might have mis-estimated the timing, based on where it's at now there's still about 18 hours to go which means it's time to go home and then bite the bullet tomorrow by using the dev server.

EDIT-For anyone curious, it just finished now.

Scaramouche fucked around with this message at 01:06 on Oct 18, 2014

Mr Shiny Pants
Nov 12, 2012
Is this F# code ok?

code:
let rec Process() =
    printfn "Listening"
    let context = listener.GetContext()
    Async.Start(ProcessRequest context)
    Process()
It is for a HttpListener that services requests. Usually it is done using a while loop, but I thought what the hell, F# is supposed to handle recursion fine.
Will this get me in trouble with stack overflows? Or will this be properly handled? Tail recursion is the word for this right?

Total F# noob here. :)

raminasi
Jan 25, 2005

a last drink with no ice
You have correctly made the recursive tail call, although by default, it will not be eliminated in Debug mode.

Knyteguy
Jul 6, 2005

YES to love
NO to shirts


Toilet Rascal


Any ideas? The key record is clearly annotated. Just trying to get EF to create my tables (code first).

Knyteguy fucked around with this message at 08:46 on Oct 19, 2014

epswing
Nov 4, 2003

Soiled Meat

Knyteguy posted:

Any ideas? The key record is clearly annotated. Just trying to get EF to create my tables (code first).

C# code:
public int Id; // this is a field
C# code:
public int Id { get; set; } // you want a property

Knyteguy
Jul 6, 2005

YES to love
NO to shirts


Toilet Rascal

epalm posted:

C# code:
public int Id; // this is a field
C# code:
public int Id { get; set; } // you want a property

Haha, thanks. I just realized about half of my model classes have fields and half have properties (some have both). Late night coding :downs:.

Mr Shiny Pants
Nov 12, 2012
Any ideas why this code gives me an AccessVilolation?

code:
let DecodeUrl (request:TogetherRequest) =
    request.Url.Segments
    |> Array.map(fun x -> x.Trim('/'))
    //|> Array.choose(fun x -> if (String.IsNullOrEmpty(x)) then None else Some(x))
    |> Array.choose(fun (x) -> match x with
                                | null -> None
                                | "" -> None
                                | x -> Some(x)) 
    |> (fun x -> {Method=request.HttpMethod;Url=x})
It should strip empty strings from an url after the split, but it errors out. In my limited knowledge it should build new arrays between the pipes so it is not trying to alter immutable arrays.
It only gives the error when stepping trough the code though, the result when running the program is fine and works as I expect it to do. :confused:

Both the commented array.choose as the other one give me this error.

raminasi
Jan 25, 2005

a last drink with no ice
Have you tried breaking up the pipeline to see exactly what the problem is?

Destroyenator
Dec 27, 2004

Don't ask me lady, I live in beer
You're right, they do create new arrays. If it's only when you're debugging it sounds like the "Locals" window or something in VS is trying to read something it shouldn't?

Side note: you can collapse your choose to a filter if you want:
Array.filter (not << System.String.IsNullOrEmpty)

Mr Shiny Pants
Nov 12, 2012

GrumpyDoctor posted:

Have you tried breaking up the pipeline to see exactly what the problem is?

Not yet, that was going to be my next step. I was scratching my head because I think it is quite reasonable code and everything I found on Stack overflow and the like said it should work.


Destroyenator posted:

You're right, they do create new arrays. If it's only when you're debugging it sounds like the "Locals" window or something in VS is trying to read something it shouldn't?

Side note: you can collapse your choose to a filter if you want:
Array.filter (not << System.String.IsNullOrEmpty)

Hmmm, I think you might be onto something. Pretty weird if it does. Access Violations during normal execution would stop my program right? I mean, I am not ignoring some exception silently?

Love your method, I am not that well versed in F# to work with it though. Not yet anyway. :)

Thanks

Edit: Thinking about your rewrite: Am I correct in assuming that the Not operator is a function that takes a value or a function? So you pipe the value coming out of the Array into the String.IsNullOrEmpty function and piping that into the Not operator? This results in a bool for the filter function? Sometimes F# code cooks my noodle.

Mr Shiny Pants fucked around with this message at 07:16 on Oct 20, 2014

raminasi
Jan 25, 2005

a last drink with no ice

Mr Shiny Pants posted:

Hmmm, I think you might be onto something. Pretty weird if it does. Access Violations during normal execution would stop my program right? I mean, I am not ignoring some exception silently?

You might want to double-check your exceptions list (Debug > Exceptions, I think) and make sure that "Thrown" is checked for that particular exception type. Do you see the problem any time you have a debugger attached, or just when you're actually stepping through?

Mr Shiny Pants
Nov 12, 2012

GrumpyDoctor posted:

You might want to double-check your exceptions list (Debug > Exceptions, I think) and make sure that "Thrown" is checked for that particular exception type. Do you see the problem any time you have a debugger attached, or just when you're actually stepping through?

Only when actually stepping through this particular piece of code.

Destroyenator
Dec 27, 2004

Don't ask me lady, I live in beer
Yeah, sorry I could've been clearer, the << operator is function chaining, it's just a terser way of writing:
Array.filter (fun x -> not (System.String.INOE(x)))

Where "not" is just the boolean not like "!" in c#.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

Destroyenator posted:

Array.filter (not << System.String.IsNullOrEmpty)

I wish C# has this kind of composition. I love that you can do .Where(string.IsNullOrEmpty) but I hate that you have to do .Where(x => !string.IsNullOrEmpty(x)).

Jewel
May 2, 2009

Bognar posted:

I wish C# has this kind of composition. I love that you can do .Where(string.IsNullOrEmpty) but I hate that you have to do .Where(x => !string.IsNullOrEmpty(x)).

Is it possible to write a generic wrapper that lets you do something like .Where(Not(string.IsNullOrEmpty))? The closest I can get is this:

code:
Func<T, bool> Not<T>(Func<T, bool> action)
{
	return (T parameter) => !action(parameter);
}
But the only way to use it is .Where(Not<string>(string.IsNullOrEmpty))); and I don't like how it won't infer the template, but I don't know how to fix that :(

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
It would probably work better as an enumerable extension method:

code:
public static IEnumerable<T> WhereNot<T>(this IEnumerable<T> enumerable, Func<T, bool> predicate)
{
    return enumerable.Where(t => !predicate(t));
}
Though, then it's not generic to any usage of Func<T, bool>.

raminasi
Jan 25, 2005

a last drink with no ice

Mr Shiny Pants posted:

Only when actually stepping through this particular piece of code.

That's really weird. If the problem still happens with the pipeline broken up, can you post the exception message?

Mr Shiny Pants
Nov 12, 2012
Rewrote it like this:
code:
let DecodeUrl (request:TogetherRequest) =
    let list1 = Array.map(fun (x:string) -> x.Trim('/'))request.Url.Segments
    let list2 = Array.choose(fun x -> if (String.IsNullOrEmpty(x)) then None else Some(x))list1
    let request = {Method=request.HttpMethod;Url=list2}
    request
Still getting the error.

Error message:

code:
System.AccessViolationException was unhandled
Message: An unhandled exception of type 'System.AccessViolationException' occurred in FSharp.Core.dll
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
Edit:

Rewrote as pointed out:
code:
let DecodeUrl (request:TogetherRequest) =
    let list1 = Array.map(fun (x:string) -> x.Trim('/'))request.Url.Segments
    let list2 = Array.filter(not << String.IsNullOrEmpty)list1
    let request = {Method=request.HttpMethod;Url=list2}
    request
Still getting the accessviolation. Weird huh?

Mr Shiny Pants fucked around with this message at 18:43 on Oct 20, 2014

Quebec Bagnet
Apr 28, 2009

mess with the honk
you get the bonk
Lipstick Apathy
Aren't those array functions evaluated lazily? I wonder if stepping through in the debugger forces an evaluation and you wouldn't otherwise see it in normal execution for a while.

Sedro
Dec 31, 2008

Jewel posted:

Is it possible to write a generic wrapper that lets you do something like .Where(Not(string.IsNullOrEmpty))? The closest I can get is this:

code:
Func<T, bool> Not<T>(Func<T, bool> action)
{
	return (T parameter) => !action(parameter);
}
But the only way to use it is .Where(Not<string>(string.IsNullOrEmpty))); and I don't like how it won't infer the template, but I don't know how to fix that :(
It's not possible in C# because string.IsNullOrEmpty is typeless. In the case of Enumerable.Where<T>, the type parameter T is inferred from the IEnumerable<T> rather than the Func<T, bool>.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
I don't like the word typeless for describing a method group, but I can't really express why. It's an internal type used by the compiler, but yeah it can't map directly to C# types.

The important thing to note is that a method group is a group since it can describe multiple methods (e.g. multiple overloads). If you do something like cast to a typed Func, then you are explicitly specifying which overload you are using (and you will get a compilation error if the overload doesn't exist).

C# code:
var test = new List<string>();
Func<string, bool> inoe = string.IsNullOrEmpty;
var noEmpties = test.Where(Not(inoe));
You would think, though, that the compiler could infer that the expected type is Func<string, bool>, and that therefore T in Func<T, bool> Not<T> is a string.

Bognar fucked around with this message at 19:36 on Oct 20, 2014

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
Actually, I take that back, the compiler probably can't figure it out due to generic type covariance/contravariance. Func<T1, T2> has an contravariant T1 (parameter type) and covariant T2 (output type), e.g.:

C# code:
  public delegate TResult Func<in T, out TResult>(T arg);
That means you can do things like this:

C# code:
Func<T, bool> Not<T>(Func<T, bool> action)
{
    return t => !action(t);
}

bool IsNull(object obj)
{
    return obj == null;
}

class Base { }
class Derived : Base { }

void Test()
{
    var deriveds = new List<Derived>();
    Func<Base, bool> baseIsNull = IsNull;
    deriveds.Where(Not(baseIsNull));
}
Note that IsNull takes an object, but is castable to Func<Base, bool>. Also, deriveds can use a Func<Base, bool> as a Where clause. I don't think you could make a compiler wrestle the ambiguities out of that when coupled with overloaded methods in a method group.

Bognar fucked around with this message at 19:55 on Oct 20, 2014

aBagorn
Aug 26, 2004
Unit Testing and Web API 2 questions ahoy!!!

I have a basic framework laid out for how I want to start writing my tests (which is good, I'm learning TDD on the fly), but I'm kind of stumped with testing the put functionality.

As taken from here:
http://www.asp.net/web-api/overview/testing-and-debugging/mocking-entity-framework-when-unit-testing-aspnet-web-api-2#tests

The most basic PUT unit test should be something like:

C# code:
        public void PutProduct_ShouldReturnStatusCode()
        {
            var controller = new ProductController(new TestStoreAppContext());

            var item = GetDemoProduct();

            var result = controller.PutProduct(item.Id, item) as StatusCodeResult;
            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(StatusCodeResult));
            Assert.AreEqual(HttpStatusCode.NoContent, result.StatusCode);
        }
which seems simple enough and does what it's supposed to, but what if I want/need to get deeper into testing to make sure the modified properties are correctly being modified, or am I going into the realm of validation instead of unit testing?

For example, we have a tenant object and a building object, and then there is a history mapping table that maps the start date and end date of a tenant's assignment to a building.

I want to check against that table (or mock it) when a tenant is edited to make sure that the new start date is greater than the previous start and end date (and so on and so forth).

Is this testing or validation is basically my big question...

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug
If you're thinking that far ahead, you're not doing TDD. In TDD, you should be thinking about the next tiny, logical step that moves you closer to your end goal.

Mr Shiny Pants
Nov 12, 2012
Anyone have clue how to get SQLite working in F# using the Nuget drivers?

I downloaded the SQLite core drivers and referenced them, but no luck. During compilation it craps out and in the interactive window I am getting a cannot load DLL error SQLite.Interop.DLL.

Pretty frustrating, any pointers would be appreciated.

Edit: Found it. Don't know what is wrong with the Nuget package but the one from the site works great:

http://system.data.sqlite.org/downloads/1.0.94.0/sqlite-netFx451-setup-bundle-x64-2013-1.0.94.0.exe

It even works in the FSI and no mucking about with the interop DLL.

Edit 2: Wow, the X64 DLL does not work with the TypeProvider because Visual Studio is a 32Bit application that can't load X64 binaries.

So the X86 binary is still required for VS to work. Bummer.

Mr Shiny Pants fucked around with this message at 21:13 on Oct 20, 2014

aBagorn
Aug 26, 2004

Ithaqua posted:

If you're thinking that far ahead, you're not doing TDD. In TDD, you should be thinking about the next tiny, logical step that moves you closer to your end goal.

Right. That makes sense. I guess I'm mixing up my "project manager" and "lead developer" hats that I'm wearing for this particular project.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

aBagorn posted:

Right. That makes sense. I guess I'm mixing up my "project manager" and "lead developer" hats that I'm wearing for this particular project.

You also threw the word "table" in there, which makes it sound like you're thinking in terms of SQL. Unless you're testing your persistence layer, your code shouldn't know or care how the data is persisted. It could be a SQL database, a NoSQL database, a flat file, a paper tape, or engraved in stone tablets. If the "history table" is something represented in your code and you're doing TDD, you'll end up writing tests for it. That's how TDD works: You don't write code that isn't backed by a test.

There's still value in testing your SQL, especially when dealing with ORMs. This is where integration tests come into play, or if you're just using straight up stored procedures, SQL server data tools lets you do "database unit tests". I'm not a huge fan of it, but it's not terrible.

Dirk Pitt
Sep 14, 2007

haha yes, this feels good

Toilet Rascal
I thought I had a grip on async / await and then I got a bit confused.

Is this:

code:
public override void LoadView ()
    {
	Task.Run(async () => await StageTheView());
    }
Preferable to this:

code:
public async override void LoadView()
{
    await StageTheView();
}
Is it ok to use "Task.Run(async () => await asyncMethod());" if I need to run an asyncronous method, in a constructor or override method?

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Dirk Pitt posted:

I thought I had a grip on async / await and then I got a bit confused.

Is this:

code:
public override void LoadView ()
    {
	Task.Run(async () => await StageTheView());
    }
Preferable to this:

code:
public async override void LoadView()
{
    await StageTheView();
}
Is it ok to use "Task.Run(async () => await asyncMethod());" if I need to run an asyncronous method, in a constructor or override method?

No, in fact they are very different.

Task.Run returns a task, which you're not awaiting. That means that you synchronously call LoadView, and it starts a task and immediately returns, without waiting for that task to complete. This is probably not what you want.

Also, you should never use async void methods except for event handlers. There are a bunch of good reasons why: you can't await them, and exceptions can cause unexpected behavior, like outright crashing your application.

If you need to synchronously wait for an asynchronous thing to finish, use Task.Wait. Or more ideally, make the application async "all the way down". Async keywords will spread throughout your code, which is okay!

New Yorp New Yorp fucked around with this message at 02:54 on Oct 21, 2014

Dirk Pitt
Sep 14, 2007

haha yes, this feels good

Toilet Rascal
Ahhh, I was using task.run to avoid having to make an async void.

What am I supposed to do if I need to await an asyncronous method in an override void or constructor? I typically make everything async all the way down. This is an issue I am curious about in a framework I have little control over (xamarin).

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Dirk Pitt posted:

Ahhh, I was using task.run to avoid having to make an async void.

What am I supposed to do if I need to await an asyncronous method in an override void or constructor? I typically make everything async all the way down. This is an issue I am curious about in a framework I have little control over (xamarin).

Task.Wait, although IIRC this can cause deadlocks.

Dirk Pitt
Sep 14, 2007

haha yes, this feels good

Toilet Rascal
Hmm, ok, thanks a ton. I will look at that. I really usually do have a good grasp on async / await, this is the edge case that gives me loving fits. Especially when I tell someone on stack overflow that there are other options (even if they are correcting my code), and they get all huffy puffy.

Dirk Pitt fucked around with this message at 03:04 on Oct 21, 2014

Adbot
ADBOT LOVES YOU

Destroyenator
Dec 27, 2004

Don't ask me lady, I live in beer

chmods please posted:

Aren't those array functions evaluated lazily? I wonder if stepping through in the debugger forces an evaluation and you wouldn't otherwise see it in normal execution for a while.
No, the array ones are eager. You can always poke around in the internals here: https://github.com/fsharp/fsharp/blob/master/src/fsharp/FSharp.Core/array.fs#L144 if you need to check. The Seq ones are lazy IEnumerables though.

Bognar posted:

I wish C# has this kind of composition. I love that you can do .Where(string.IsNullOrEmpty) but I hate that you have to do .Where(x => !string.IsNullOrEmpty(x)).
Yeah, and I find myself wanting to do it with single arg constructors more often than you'd expect.

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