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
Drastic Actions
Apr 7, 2009

FUCK YOU!
GET PUMPED!
Nap Ghost

gently caress them posted:

Starting to not feel the linq right now.

I kept getting "don't do this For Each because the list doesn't have any elements."

Ok! I'll throw in a drat if statement to make sure the list has a count greater than zero.

So on the line where I go "If (items.Count > 0) Then"

"ArgumentException not handled by user code
Count must have a non-negative value."

I have no clue what is going on. I'm going to just wrap it in a try catch, but honestly, what the hell is going on?

You can use "items.Any()", which returns a bool if it contains any elements.
But it seems weird that it would throw an error on an empty foreach. Unless it was null, I would think that if it was empty it would just pass over it.

Adbot
ADBOT LOVES YOU

Mr. Crow
May 22, 2008

Snap City mayor for life
[quote="gently caress them" post=""434599217"]
I have no clue what is going on. I'm going to just wrap it in a try catch, but honestly, what the hell is going on?
[/quote]

This is sage advice and generally the right thing to do when youre frustrated with a problem, you're gonna go far!

Fuck them
Jan 21, 2011

and their bullshit
:yotj:
At home for lunch, so paraphrasing.

dim return = LinqToEntities (Or LinqToSql? It's old)

if (return.Count < 0) then
return no results found
else
return the actual data
end if

at "if (return.Count < 0)" it says count must be non negative. When I look at the actual "return" it says the count is 2.

When I get back to work I'll post the whole code.

Fuck them fucked around with this message at 17:39 on Sep 8, 2014

Fuck them
Jan 21, 2011

and their bullshit
:yotj:

Mr. Crow posted:

This is sage advice and generally the right thing to do when youre frustrated with a problem, you're gonna go far!

:shobon: I'll be the best pokemon trainer ever, gotta catch them all!

Fuck them
Jan 21, 2011

and their bullshit
:yotj:

Drastic Actions posted:

You can use "items.Any()", which returns a bool if it contains any elements.
But it seems weird that it would throw an error on an empty foreach. Unless it was null, I would think that if it was empty it would just pass over it.

What's so loving frustrating is that it says the count is wrong IN AN IF STATEMENT. How is an if statement throwing an exception on list.count???

FrantzX
Jan 28, 2007

gently caress them posted:

At home for lunch, so paraphrasing.

dim return = LinqToEntities (Or LinqToSql? It's old)

if (return.Count < 0) then
return no results found
else
return the actual data
end if

at "if (return.Count < 0)" it says count must be non negative. When I look at the actual "return" it says the count is 2.

When I get back to work I'll post the whole code.

if return.Count is zero, then the if statement becomes 0 < 0, which is false. You want (return.Count == 0).

Fuck them
Jan 21, 2011

and their bullshit
:yotj:

FrantzX posted:

if return.Count is zero, then the if statement becomes 0 < 0, which is false. You want (return.Count == 0).

code:
 
    Public Function GetItems(caseNo As String, pageNo As Int16, pageSize As Int16) As List(Of CaseItem)
        Dim context As New StuffQueryDL.StuffQueryEntities()
        Dim startRow = (pageNo - 1) * pageSize
        Dim items = (From t In context.trItems Where t.ref1.Contains(caseNo) Order By t.ref1 Select t.ref1, t.ItemCode, t.ref2, t.ref3, t.location, t.ref4, t.ref6, t.ref7, t.nameout, t.updatedate).Skip(startRow).Take(pageSize)
        Dim list As New List(Of CaseItem)
        If (items.Count > 0) Then
            For Each item In items
                Dim sta = "OUT TO: " & item.nameout & " ON " & String.Format("{0:MM/dd/yyyy HH:mm}", item.updatedate)
                list.Add(New CaseItem() With {
                         .CaseNo = item.ref1, .ItemCode = item.ItemCode, .Location = item.location, .Name = item.ref3, .Volume = item.ref2, .Misc1 = item.ref4, .Misc2 = item.ref6, .Misc3 = item.ref7, .Status = sta, .UpdatedDate = item.updatedate
                })
            Next
        Else
            list.Add(New CaseItem() With
                    {.CaseNo = "", .ItemCode = "", .Volume = "", .Location = ""}) 
        End If

        Return list
    End Function
That throws the exception at the if statement. What the gently caress?

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

FrantzX posted:

if return.Count is zero, then the if statement becomes 0 < 0, which is false. You want (return.Count == 0).

Just use Any().

raminasi
Jan 25, 2005

a last drink with no ice

Bognar posted:

Can you post some code?

Are you explicitly catching SocketException, or catching any Exception? If you're just catching a SocketException and the TcpListener is on an async call, it's possible that an AggregateException is being thrown instead.

EDIT: On second thought, this is probably unlikely. Back to line 1 - got any code?

I will disclose that this is my first attempt at writing my own async code (rather than just blindly copying from someone else), so I might be thinking about this completely wrong. Here is the original, non-working code, with the relevant bits noted with comments:
code:
member public this.Start () =
    if semaphore.WaitOne(0) then
        let res = RhinoGet.GetInteger("Port", true, &port)
        if res <> Result.Success then
            semaphore.Release() |> ignore
            res
        else
            socket <- TcpListener(IPAddress.Loopback, port)
            // Important stuff starts here
            let server = async {
                let onCancel () =
                    socket.Stop()
                    socket <- Unchecked.defaultof<TcpListener>
                    semaphore.Release() |> ignore
                use! canceller = Async.OnCancel(onCancel)
                socket.Start()
                RhinoApp.WriteLine("umi CityScope: Server started on port {0}.", port)
                let client = socket.AcceptTcpClient() // This line doesn't work
                RhinoApp.WriteLine("umi CityScope: Client connected.")
                listen client // This function returns when the client closes the connection
                client.Close() }
            if cts <> Unchecked.defaultof<CancellationTokenSource> then cts.Dispose()
            cts <- new CancellationTokenSource()
            Async.Start(server, cts.Token)
            Result.Success
    else
        RhinoApp.WriteLine("umi CityScope: Server already running.")
        Result.Nothing
I was able to fix it by changing the offending line to
code:
let! client = socket.AcceptTcpClientAsync() |> Async.AwaitTask
so that no exception is thrown when the task is cancelled, but I still don't understand why I wasn't able to catch the original exception. (As an Exception, not any subtype.)

Fuck them
Jan 21, 2011

and their bullshit
:yotj:

Ithaqua posted:

Just use Any().



:psypop:

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

Wait - do solved cases count as negative?

Fuck them
Jan 21, 2011

and their bullshit
:yotj:

Newf posted:

Wait - do solved cases count as negative?

I don't understand. It's just returning rows where caseNo is found with a generated like statement, and then does some arithmetic to return paged data from the server to the jQuery/ko on the client page (this is a restful JSON thing).

I'm not sure how it can return negative rows from the database. Or what negative rows are. I can count negative things in an absolute sense anyway - and since when is count possibly anything less than zero??

I usually just roll up some sprocs and call it with ADO.NET; this is my first time using linq to whatever and it's someone else's EF project to boot. I just don't know what the hell is going on. I guess this is why some devs Just Don't Like ORMs?

Edit: Naturally if I just put my "make an empty string having object and return that thang" logic into the catch block of a try catch It Just Works!

Boy I love being a lovely programmer.

Fuck them fucked around with this message at 18:31 on Sep 8, 2014

gariig
Dec 31, 2004
Beaten into submission by my fiance
Pillbug
What is the value of the parameters passed in? I'm guessing you are getting a negative number for Take/Skip. Also, have you tried doing a ToList() on the query to force the query to be executed earlier?

gently caress them posted:

Edit: Naturally if I just put my "make an empty string having object and return that thang" logic into the catch block of a try catch It Just Works!

What?

gariig fucked around with this message at 18:33 on Sep 8, 2014

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

GrumpyDoctor posted:

I was able to fix it by changing the offending line to
code:
let! client = socket.AcceptTcpClientAsync() |> Async.AwaitTask
so that no exception is thrown when the task is cancelled, but I still don't understand why I wasn't able to catch the original exception. (As an Exception, not any subtype.)

I'm very inexperienced with F#, but my read of that code is that you are calling Async.Start which is starting the server method on the threadpool. If you're not handling exceptions within that method, the exception can not be caught because it's running on a different thread as the first method in its call stack (and therefore not wrapped in a try/catch at any level).



Is pageNo zero?

Fuck them
Jan 21, 2011

and their bullshit
:yotj:

That if else statement? I made it a Try/Catch And Now It Just Works™.

gariig posted:

What is the value of the parameters passed in? I'm guessing you are getting a negative number for Take/Skip. Also, have you tried doing a ToList() on the query to force the query to be executed earlier?

THAT makes sense.

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

gently caress them posted:

That if else statement? I made it a Try/Catch And Now It Just Works™.


THAT makes sense.

Is the Try/Catch working because you are catching the Exception and returning a good value or the Exception doesn't occur because of the try/catch? What part of it "And Now It Just Works™"?

Well what are the values? Although that makes sense is that the root cause?

Fuck them
Jan 21, 2011

and their bullshit
:yotj:

gariig posted:

Is the Try/Catch working because you are catching the Exception and returning a good value or the Exception doesn't occur because of the try/catch? What part of it "And Now It Just Works™"?

Well what are the values? Although that makes sense is that the root cause?

It Just Worked because it ate the exception and instead of crashing just did what I wanted, return json of a blank record.

Just now I added some logic to check if startRow is less than one, and if so, make it 0, so .Skip(startRow) cannot have a negative value. Go figure the old if statement works again. Why the hell would .Skip() failing (or being given a negative value - and why is that allowed?) give me such a crappy exception? "I skipped negative rows so the count is negative." doesn't make any drat sense.

raminasi
Jan 25, 2005

a last drink with no ice

Bognar posted:

I'm very inexperienced with F#, but my read of that code is that you are calling Async.Start which is starting the server method on the threadpool. If you're not handling exceptions within that method, the exception can not be caught because it's running on a different thread as the first method in its call stack (and therefore not wrapped in a try/catch at any level).

The problem is that
code:
try
    let client = socket.AcceptTcpClient()
    RhinoApp.WriteLine("umi CityScope: Client connected.")
    listen client
    client.Close()
with
    | ex -> RhinoApp.WriteLine(ex.Message)
doesn't catch it either.

SirViver
Oct 22, 2008

gently caress them posted:

It Just Worked because it ate the exception and instead of crashing just did what I wanted, return json of a blank record.

Just now I added some logic to check if startRow is less than one, and if so, make it 0, so .Skip(startRow) cannot have a negative value. Go figure the old if statement works again. Why the hell would .Skip() failing (or being given a negative value - and why is that allowed?) give me such a crappy exception? "I skipped negative rows so the count is negative." doesn't make any drat sense.
Skip() has a parameter named "count", which must not be negative - this is the exception you got. It's kind of an unfortunate coincidence that you ran into this while querying the Count property, which certainly confused things. The reason you only got it on the if (items.Count...) respectively if (items.Any()) call is because LINQ is lazily executed :)

Uziel
Jun 28, 2004

Ask me about losing 200lbs, and becoming the Viking God of W&W.
OK I have a monolithic Webforms application that uses EXT.Net for the front end. I am looking to convert it to MVC but need a replacement for EXT.Net for as much as possible.

I may need to keep certain parts of it as we use the Ext Calendar for a scheduling system (I'll cross that bridge when I come to it), but for the configuration stuff I want to leverage MVC models/routers/controllers but also avoid the pitfalls of having spaghetti jquery everywhere. Is there a recommended javascript framework or library that I should use? I'm probably just going to default to using Bootstrap for the design.

A Tartan Tory
Mar 26, 2010

You call that a shotgun?!
Just wanted to post a 'thank you so much guys' post. It's taken me about a month but I think WPF has finally clicked, I'm making small applications that actually work to their intended purposes now and TBFH it's thanks mostly in part to everyone who has helped me in this thread.

So thanks a lot guys! I'll probably be back soon with more questions, but this time I won't be a completely clueless newbie!

RICHUNCLEPENNYBAGS
Dec 21, 2010

gently caress them posted:

At home for lunch, so paraphrasing.

dim return = LinqToEntities (Or LinqToSql? It's old)
You're not sure which you're using? I'm not surprised that you're having problems.

Quebec Bagnet
Apr 28, 2009

mess with the honk
you get the bonk
Lipstick Apathy

Uziel posted:

OK I have a monolithic Webforms application that uses EXT.Net for the front end. I am looking to convert it to MVC but need a replacement for EXT.Net for as much as possible.

I may need to keep certain parts of it as we use the Ext Calendar for a scheduling system (I'll cross that bridge when I come to it), but for the configuration stuff I want to leverage MVC models/routers/controllers but also avoid the pitfalls of having spaghetti jquery everywhere. Is there a recommended javascript framework or library that I should use? I'm probably just going to default to using Bootstrap for the design.

Right now I'm in the middle of upgrading an application which uses Ext.Net 1.5 and I would advise biting the bullet and migrating to straight up Ext. ExtJS 5 has lots of fun new MVVM features which make development a lot easier and a lot of pieces and pages have been a 1 to 1 translation from markup to components, even with jumping ahead two major versions of Ext. My application was all MVC from the start though, so getting in the mindset of having a separate front end was easier. You don't need to use Sencha Cmd, it's pretty easy to structure something in MVC which works with the loader. You can PM me if you have specific questions.

Uziel
Jun 28, 2004

Ask me about losing 200lbs, and becoming the Viking God of W&W.

chmods please posted:

Right now I'm in the middle of upgrading an application which uses Ext.Net 1.5 and I would advise biting the bullet and migrating to straight up Ext. ExtJS 5 has lots of fun new MVVM features which make development a lot easier and a lot of pieces and pages have been a 1 to 1 translation from markup to components, even with jumping ahead two major versions of Ext. My application was all MVC from the start though, so getting in the mindset of having a separate front end was easier. You don't need to use Sencha Cmd, it's pretty easy to structure something in MVC which works with the loader. You can PM me if you have specific questions.
I had thought about it but I'd never get approved for the ext js license unfortunately plus we'd still likely need to use ext.net for the calendar portion.

Quebec Bagnet
Apr 28, 2009

mess with the honk
you get the bonk
Lipstick Apathy

Uziel posted:

I had thought about it but I'd never get approved for the ext js license unfortunately plus we'd still likely need to use ext.net for the calendar portion.

There's also a GPL license, if you dig deep enough on Sencha's site. Also, are you referring to the big Google Calendar style view? It's been a while but I seem to think that that's actually a third party product.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

gently caress them posted:

It Just Worked because it ate the exception and instead of crashing just did what I wanted, return json of a blank record.

Just now I added some logic to check if startRow is less than one, and if so, make it 0, so .Skip(startRow) cannot have a negative value. Go figure the old if statement works again. Why the hell would .Skip() failing (or being given a negative value - and why is that allowed?) give me such a crappy exception? "I skipped negative rows so the count is negative." doesn't make any drat sense.

GIGO

Uziel
Jun 28, 2004

Ask me about losing 200lbs, and becoming the Viking God of W&W.

chmods please posted:

There's also a GPL license, if you dig deep enough on Sencha's site. Also, are you referring to the big Google Calendar style view? It's been a while but I seem to think that that's actually a third party product.
Oh. Does my code have to be open source in order to take advantage of it? Its for an internal tool, not software that is sold.

If you are using ext for the View, how did you get around duplicate models?

Yeah, its a Google calendar style event scheduler that is from the Ext.NET team and the primary reason we went with that over ext js:
http://examples1.ext.net/#/Calendar/Overview/Basic/

Uziel fucked around with this message at 13:01 on Sep 9, 2014

Malcolm XML
Aug 8, 2009

I always knew it would end like this.

Uziel posted:

Oh. Does my code have to be open source in order to take advantage of it? Its for an internal tool, not software that is sold.

If you are using ext for the View, how did you get around duplicate models?

Yeah, its a Google calendar style event scheduler that is from the Ext.NET team and the primary reason we went with that over ext js:
http://examples1.ext.net/#/Calendar/Overview/Basic/

Talk to legal. Are you distributing it? "Distributing" software is a legally ambiguous term.

Quebec Bagnet
Apr 28, 2009

mess with the honk
you get the bonk
Lipstick Apathy

Uziel posted:

Oh. Does my code have to be open source in order to take advantage of it? Its for an internal tool, not software that is sold.

If you are using ext for the View, how did you get around duplicate models?

Yeah, its a Google calendar style event scheduler that is from the Ext.NET team and the primary reason we went with that over ext js:
http://examples1.ext.net/#/Calendar/Overview/Basic/

The GPL question depends on the type of product you're building. Internal-only tools should be clean, because it's company IP and so the only users who could request the code work there anyway, but IANAL.

Having duplicate models is unfortunately a fact of life - I have database objects, then .NET model objects which are returned and consumed by web APIs (in some situations, you might think of them like the VM part of MVVM), and then Ext representations of those models. With reflection it would be possible to generate the JS from the .NET classes and save you from maintaining two copies, I think Ext.Net does that anyway. The view models you create for Ext are specific to components though, the models are what will be sent to and received from the server.

That calendar looks like the one from http://ext.ensible.com.

Uziel
Jun 28, 2004

Ask me about losing 200lbs, and becoming the Viking God of W&W.

chmods please posted:

The GPL question depends on the type of product you're building. Internal-only tools should be clean, because it's company IP and so the only users who could request the code work there anyway, but IANAL.

Having duplicate models is unfortunately a fact of life - I have database objects, then .NET model objects which are returned and consumed by web APIs (in some situations, you might think of them like the VM part of MVVM), and then Ext representations of those models. With reflection it would be possible to generate the JS from the .NET classes and save you from maintaining two copies, I think Ext.Net does that anyway. The view models you create for Ext are specific to components though, the models are what will be sent to and received from the server.

That calendar looks like the one from http://ext.ensible.com.
Awesome thank you. I'm going through some angular tutorials and I'm going to try to evaluate which is the best fit for which parts of the application (since I already have non-MVC ext experience and MVC experience). It looks like the calendar is in extjs5 anyways!

Knyteguy
Jul 6, 2005

YES to love
NO to shirts


Toilet Rascal
So I'm on a deadline trying to learn async programming for the first time :downs:

Anyone see what I'm doing wrong here? I understand a little bit of how this works, but I'd probably go non-threaded if I could. Unfortunately I really want to use a config file and there's no way to read a file like that on Windows Phone.

C# code:
public virtual async Task<JsonObject> GetSettingsFromConfigFile(string configFilePath = @"../../Config/Settings.json")
{
    string content = String.Empty;

    var myStream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(configFilePath);
    using (StreamReader reader = new StreamReader(myStream))
    {
        content = reader.ReadToEnd();
    }

    return JsonObject.Parse(content);
}

public virtual JsonObject GetJsonValueFromServer(string outJson)
{
    Task.Factory.StartNew(async () =>
    {
        JsonObject settings;
        settings = await GetSettingsFromConfigFile();
        ServerUrl = settings["Server"].ToString();

        HttpWebRequest request =
        (HttpWebRequest)HttpWebRequest.Create(ServerUrl);

        request.BeginGetResponse(GetServerCallback, request);
    });
    return null;
}
I can't seem to run through the debugger. It won't let me "f10" over "string content = String.Empty;" (errors happen below upon doing that) and "return JsonObject.Parse(content);" never hits its breakpoint.

Ouput windows says this:
code:
A first chance exception of type 'System.ArgumentException' occurred in mscorlib.ni.dll
A first chance exception of type 'System.ArgumentException' occurred in mscorlib.ni.dll
I assume this has to do with async ignorance.

Knyteguy fucked around with this message at 19:12 on Sep 9, 2014

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

Knyteguy posted:


C# code:
public virtual async Task<JsonObject> GetSettingsFromConfigFile(string configFilePath = @"../../Config/Settings.json")
{
    string content = String.Empty;

    var myStream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(configFilePath);
    using (StreamReader reader = new StreamReader(myStream))
    {
        content = reader.ReadToEnd();
    }

    return JsonObject.Parse(content);
}

public virtual JsonObject GetJsonValueFromServer(string outJson)
{
    Task.Factory.StartNew(async () =>
    {
        JsonObject settings;
        settings = await GetSettingsFromConfigFile();
        ServerUrl = settings["Server"].ToString();

        HttpWebRequest request =
        (HttpWebRequest)HttpWebRequest.Create(ServerUrl);

        request.BeginGetResponse(GetServerCallback, request);
    });
    return null;
}

What is happening is the Task you are creating from the Task.Factory is starting to run and you are immediately returning null. You need to capture the Task<T> created from the Task.Factory and await it.

EDIT: That also means GetJsonValueFromServer should return a Task<JsonObject>. Once you go async/await it will spread through your code like a virus.

ljw1004
Jan 18, 2005

rum

Knyteguy posted:

So I'm on a deadline trying to learn async programming for the first time :downs:
Anyone see what I'm doing wrong here? I understand a little bit of how this works, but I'd probably go non-threaded if I could.

1. Async should be "async all the way down". Don't make calls to blocking APIs. If you have some CPU-bound work, put it inside "await Task.Run(...cpu-bound computationally intensive inner loop)". So the first change is
code:
content = await reader.ReadToEndAsync();
If you don't do this, then your GetSettingsFromConfigFile method will block the thread (maybe even the UI thread) waiting for the file to be read off disk.

2. Do you really truly want to use a config file? You could instead decide to save stuff like this, which is easier, works with strings, and is good for up to 8k per setting:
code:
ApplicationData.Current.LocalSettings.Values["index"] = 15;
3. Convention is to name async methods with the "Async" suffix:
code:
public async Task<JsonObject> GetSettingsFromConfigFileAsync(string configFilePath)
4. Your GetJsonValueFromServer is pretty weird in a number of ways...

You're using HttpWebRequest.BeginGetResponse with "GetServerCallback". This makes it impossible for your method to return a JsonObject (since the returned object won't be available when GetJsonValueFromServer returns; it will only be available when the OS invokes your GetServerCallback method). You observed this problem when you had to "return null" from your method. In any case, it's better to await an async API instead.

Your "ServerUrl" object is presumably a field, which makes me scared! It should most likely be a local variable, yes?

You used "Task.Factory.StartNew" which is positively dangerous when you pass in an async lambda. You should instead use Task.Run.

I don't think there's benefit in using HttpWebRequest. I'd advise to use HttpClient.

So here's how I'd rewrite the method...

code:
public virtual async Task<JsonObject> GetJsonValueFromServerAsync(string outJson)
{
    JsonObject settings;
    settings = await GetSettingsFromConfigFileAsync();
    var ServerUrl = settings["Server"].ToString();

    var http = new HttpClient();
    var response = await http.GetStringAsync(ServerUrl);
    return JsonObject.Parse(response);
}
5. Is it really worth using the Windows.Data.Json.JsonObject API? My instinct is to prefer Newtonsoft's Json.NET (by doing AddReferences > ManageNugetPackages and searching for Json.NET)


6. Is it worth making "content" a variable outside the "using" clause? Here's how I'd have written it:
code:
var myStream = await ApplicationData.Current.LocalFolder.OpenStreamForReadAsync(configFilePath);
using (StreamReader reader = new StreamReader(myStream))
{
    var content = await reader.ReadToEndAsync();
    return JsonObject.Parse(content);
}

quote:

I can't seem to run through the debugger. It won't let me "f10" over "string content = String.Empty;" (errors happen below upon doing that) and "return JsonObject.Parse(content);" never hits its breakpoint.
Ouput windows says this:
code:
A first chance exception of type 'System.ArgumentException' occurred in mscorlib.ni.dll
A first chance exception of type 'System.ArgumentException' occurred in mscorlib.ni.dll
I assume this has to do with async ignorance.

I have no idea what's going on with this. It might be worth checking whether you're on Debug or Release mode (since F10-stepping gets a bit screwed up with Release mode because it can't always tell where a given statement starts or ends).

First-chance exceptions generally aren't a problem. "First-chance" means that it was caught internally. You might be seeing the signs of some completely unrelated internal thing.

I'm curious when you say "it won't let you F10 over string content". What do you mean it won't let you? Does it pop up an error dialog? does it fail to step to the next statement?

It might also help to put a try/catch/finally around the body your first method. Then at least you could set a breakpoint in the catch and finally blocks.

ljw1004
Jan 18, 2005

rum

gariig posted:

What is happening is the Task you are creating from the Task.Factory is starting to run and you are immediately returning null. You need to capture the Task<T> created from the Task.Factory and await it.

That won't work :) Task.Factory takes a void-returning delegate argument. Therefore it will treat the lambda as an "async void". Therefore the task returned from Task.Factory will be marked as completed at the moment the lambda hits its first await.

That's why you should use Task.Run instead. Task.Run takes a Task-returning delegate argument, and so it will treat the lambda as an "async Task", and so it'll be fine.

Knyteguy
Jul 6, 2005

YES to love
NO to shirts


Toilet Rascal

ljw1004 posted:

async stuff

Thanks a lot for the well thought out response. Yea the program would just quit when I tried to stepover the string declaration. I assume that's because the main program thread returned. So it never hit anything beyond that in the method

I was using this example of a callback from http://msdn.microsoft.com/en-us/library/hh221581.aspx which uses a lot of the weird stuff like the fields. Maybe they had this code in a model though. I wish they would give more complete examples sometimes.
C# code:
void GetAvatarImageCallback(IAsyncResult result)
{
    HttpWebRequest request = result.AsyncState as HttpWebRequest;
    if (request != null)
    {
        try
        {
            WebResponse response = request.EndGetResponse(result);
            avatarImg = Texture2D.FromStream(
                graphics.GraphicsDevice,
                response.GetResponseStream());
        }
        catch (WebException e)
        {
            gamerTag = "Gamertag not found.";
            return;
        }
    }
}
Anyway thanks again for the help. I think I'll just trek through this async stuff unless I'm going to go past the deadline. Does the UI run on the main thread like WinForms on WinPhone? I definitely prefer non-UI blocking tasks; especially when it involves potentially long server calls.

Gul Banana
Nov 28, 2003

jesus christ. Grid ColumnDefinition.SharedSizeGroup takes effect at an random time after the measure and arrange passes, and *does not itself trigger a layout*

A Tartan Tory
Mar 26, 2010

You call that a shotgun?!
Small question. Is there a way to make a datagrid visible in WPF, only if a certain condition has been met?

To be more specific, I'm trying to make it so that a datagrid only appears when a checkbox bool value has been ticked to true. In the programming logic, I have the code to make it appear with an if statement, but how do I make the visual part of it appear only when that value is met? Is there even a way to do it? I'm mostly just trying to unclutter the GUI aspect of it by not having empty datagrids when they are not needed.

Gul Banana
Nov 28, 2003

<DataGrid Visibility="{Binding SomeVMProperty}"/>

if you want to bind it to a Boolean instead of a Visibility you can use the BooleanToVisibilityConverter type. if you want to bind to something in the view instead of the viewmodel, {Binding SomeProperty,ElementName=foo}

Uziel
Jun 28, 2004

Ask me about losing 200lbs, and becoming the Viking God of W&W.

Uziel posted:

Awesome thank you. I'm going through some angular tutorials and I'm going to try to evaluate which is the best fit for which parts of the application (since I already have non-MVC ext experience and MVC experience). It looks like the calendar is in extjs5 anyways!
So from what I gather, the best practice to use WebAPI and then have AngularJS consume that. I've seen examples where the ApiControllers return CLR objects, with the explanation I've found being that "ASP.NET Web API is optimized for sending and receiving arbitrary CLR object that then get serialized by the formatters in the request/response pipeline."

I've also seen examples where the controllers convert the data using JSON.Net and just return the string.

Does it matter? Which is the best practice? Just trying to wrap my head around it as I move through these tutorials and start to put something together.

Edit: Much like most problems, I found the answer on my own before being answered. That answer is that WebAPI uses JSON.NET as the default json serializer/deserializer and that its best to let WebAPI handle things as your request may have a different accept type other than JSON.

Uziel fucked around with this message at 14:37 on Sep 10, 2014

Adbot
ADBOT LOVES YOU

Ochowie
Nov 9, 2007

Can anyone point me in the right direction with the Identity framework for Web API services? I have the authentication piece set up using OAuth bearer tokens, but I need help on setting up user based authorization. I would like to make sure that a user has access to their own data and no one else's. However, when using bearer tokens the user name is never sent to the service and I Identity.Name is blank. I'm wondering how I would send along a User name and validate it against a token (or password if token's aren't the right approach) so that a user can only access their own data. I don't have much experience with security and this is for a personal project that I'm doing to learn a bit more.

Edit: I recreated the project with the individual user account authorization and now I get a username generated from the bearer token. I was creating basic authentication from scratch using a tutorial I found related to angular online but it wasn't embedding the username in the token. As a side note, does anyone find it annoying that Visual Studio won't allow a Web API project to be created without including the MVC component? You can create an empty project but then it won't allow for an authentication setting otherwise you need to create a joint Web API MVC project. I had to clean out all of the MVC stuff after the project was created which was pretty annoying.

Ochowie fucked around with this message at 17:32 on Sep 10, 2014

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