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
NoDamage
Dec 2, 2000
I am porting an iOS/Mac/Android app to Windows using WPF, and need a basic sanity check on our approach to dealing with the database. We are planning to use Entity Framework and SQLite to store the client-side data, which will then be displayed at runtime in various ListViews and TreeViews. It seems like the standard way of populating those ListViews and TreeViews is to use databinding, however it's not quite clear to me how to ensure that the ListViews/TreeViews continue to update when the EF objects they are bound to are updated/inserted/deleted in the database. In particular:

1. When the EF object itself has one of its properties changed, and I want the ListView to update with the new property. Searching on StackOverflow I get the impression that I would have to manually implement INotifyPropertyChanged for each property to get the bindings to fire, as the EF objects don't include this capability by default. Is this correct?
2. When one (or more) EF objects are updated in a background thread (that is syncing with a web service), what's the proper way to ensure those changes propagate to the UI? Because DbContexts aren't thread-safe, different contexts need to be used for populating the UI vs syncing in a background thread. Is there a way to merge changes from one DbContext to another?

(On iOS/Mac, Core Data's NSManagedObjectContext supports both of these use cases, and Android's ContentProvider/CursorLoader/CursorAdapter does something similar, I am basically looking for the WPF equivalent, if there is one. Also, I'm not particularly attached to Entity Framework if there happens to be a better way to achieve this.)

Adbot
ADBOT LOVES YOU

comedyblissoption
Mar 15, 2006

Does anyone have a recommendation for a resource for learning F# for someone pretty familiar with C#?

Careful Drums
Oct 30, 2007

by FactsAreUseless

comedyblissoption posted:

Does anyone have a recommendation for a resource for learning F# for someone pretty familiar with C#?

if you have a pluralsight sub there are some good videos for both 'what the gently caress where are my curly braces' and 'okay how do i do anything useful with this'

RICHUNCLEPENNYBAGS
Dec 21, 2010

comedyblissoption posted:

Does anyone have a recommendation for a resource for learning F# for someone pretty familiar with C#?

There are a couple books with that very premise.

A Tartan Tory
Mar 26, 2010

You call that a shotgun?!
I don't suppose someone could explain to me why my results for the arrays in this code are all System.Int32[]? It's probably something obvious but I am an idiot apparently.

Done as a basic c# console program, trying to get it to print out (for two years as an example)...

1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24 Turns
1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2 Years
1,2,3,4,5,6,7,8,9,10,11,12,1,2,3,4,5,6,7,8,9,10,11,12 Months

code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestLoop1
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.Write("Enter the number of years:  ");
            string yearsasastring = Console.ReadLine();
            int Years = Convert.ToInt32(yearsasastring);

            int Months = 12;
            int Turns = Years * 12;

            int[] turnsarray = new int[Turns + 1];
            int[] yearsarray = new int[Years + 1];
            int[] monthsarray = new int[Turns + 1];

            for (int t = 0; t <= Turns; t++)
            {
                for (int y = 0; y <= Years; y++)
                {
                    for (int m = 0; m <= Months; m++)
                    {
                        turnsarray[t] = t;
                        yearsarray[y] = y;
                        monthsarray[m] = m;
                    }
                }
                
            }

            Console.WriteLine("The number of turns is:  " + turnsarray + ".");
            Console.WriteLine("The number of years is:  " + yearsarray + ".");
            Console.WriteLine("The number of months is:  " + monthsarray + ".");

            Console.ReadKey();
        }
    }
}

A Tartan Tory fucked around with this message at 05:25 on Aug 11, 2014

Mr Shiny Pants
Nov 12, 2012
I am not sure what you mean but:
code:

Console.WriteLine("The number of turns is:  " + turnsarray.Length + ".");
Console.WriteLine("The number of years is:  " + yearsarray.Length + ".");
Console.WriteLine("The number of months is:  " + monthsarray.Length + ".");


Use .Length or .Count on your arrays to print the total number?

A Tartan Tory
Mar 26, 2010

You call that a shotgun?!

Mr Shiny Pants posted:

I am not sure what you mean but:
code:

Console.WriteLine("The number of turns is:  " + turnsarray.Length + ".");
Console.WriteLine("The number of years is:  " + yearsarray.Length + ".");
onsole.WriteLine("The number of months is:  " + monthsarray.Length + ".");


Use .Length or .Count on your arrays?

This wasn't it, but it did point me to what I was actually doing wrong. Nothing wrong with the arrays themselves, just how I was displaying them. Thanks for your help (I shouldn't learn to code at 5am in the morning).

Changed to the following.

code:
Console.WriteLine(string.Join(",", turnsarray));

Mr Shiny Pants
Nov 12, 2012

A Tartan Tory posted:

This wasn't it, but it did point me to what I was actually doing wrong. Nothing wrong with the arrays themselves, just how I was displaying them. Thanks for your help (I shouldn't learn to code at 5am in the morning).

Changed to the following.

code:
Console.WriteLine(string.Join(",", turnsarray));

It wasn't clear what you were trying to do, but printing just the array will display the type: System.Int32 instead of the number of items it contains. Which is what you usually want.

A Tartan Tory
Mar 26, 2010

You call that a shotgun?!

Mr Shiny Pants posted:

It wasn't clear what you were trying to do, but printing just the array will display the type: System.Int32 instead of the number of items it contains. Which is what you usually want.

Thanks for the tips, I still find it hard to spot idiotic things that I do when coding.

Simulated
Sep 28, 2001
Lowtax giveth, and Lowtax taketh away.
College Slice

A Tartan Tory posted:

Thanks for the tips, I still find it hard to spot idiotic things that I do when coding.

To be fair to you, this is one of the vast number of pitfalls and absurdities everyone encounters when learning. Why would the default ToString() behavior of any object be to print its type name? When is that ever useful? (hint: never).

wwb
Aug 17, 2004

comedyblissoption posted:

Does anyone have a recommendation for a resource for learning F# for someone pretty familiar with C#?

I'd start with http://www.manning.com/petricek/ -- has parallel examples, and there are lots of tricks you can take back to your existing C# codebase from it.

raminasi
Jan 25, 2005

a last drink with no ice
I've developed a custom WPF control that "intelligently" determines the best way to display information that's been bound to it. I want this control to expose a facility to export the data that's currently being displayed in a way that corresponds to the current way that information is being displayed. (i.e. the export format matches the display format). However, the control shouldn't be the component that actually initiates the export - that should happen elsewhere. What's the best way to do this? I was thinking of having the control offer some kind of Action<string> (or more appropriately, a custom delegate) property that a view model could bind to using OneWayToSource binding, but I'm not sure if that's the kind of thing I should be doing, or if it is, if there's a way to enforce the one-way-reverse behavior when setting up the relevant DependencyProperty.

e: It looks like the "right" way to do this, using a ReadOnlyDependencyProperty, isn't going to work.

raminasi fucked around with this message at 18:56 on Aug 11, 2014

Sedro
Dec 31, 2008
Can't you just have a dependency property representing the stringified value?

Quebec Bagnet
Apr 28, 2009

mess with the honk
you get the bonk
Lipstick Apathy

Ender.uNF posted:

To be fair to you, this is one of the vast number of pitfalls and absurdities everyone encounters when learning. Why would the default ToString() behavior of any object be to print its type name? When is that ever useful? (hint: never).

On the contrary, it's very useful for telling me "hey moron, you need to do something with this object!"

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

Ender.uNF posted:

To be fair to you, this is one of the vast number of pitfalls and absurdities everyone encounters when learning. Why would the default ToString() behavior of any object be to print its type name? When is that ever useful? (hint: never).

Yep, this one got me too. A Tartan Tory one thing that could have helped would have been to show us both the expected and the actual output, but that's neither here nor there now that the solution has been given. Just a head's up I guess.

PhonyMcRingRing
Jun 6, 2002

Ender.uNF posted:

Why would the default ToString() behavior of any object be to print its type name? When is that ever useful? (hint: never).

What else makes sense as a default, though?

wwb
Aug 17, 2004

Fundamentally the point of .ToString() is to make sure you can call .ToString() on any object. Having the type name spit out is a reasonable behavior and gives a bit more information than having it say "Fix Me".

If you call .ToString() on an int32 it will spit out the number. If you call it on the array it will spit out the fact it is a System.Int32[]. If you want to spit out the length perhaps you should call myarray.Length.ToString().

Scuzzywuffit
Feb 5, 2012

So I'm attempting to track down a memory leak that I believe is related to an event handler, and I have a dumb question that shouldn't be that difficult to Google but apparently is (or maybe I am just bad at it). If I do the following:

code:
Foo.SomeEvent += new EventHandler(Bar.Method);
Is the resulting EventHandler's _target property pointing to Foo or Bar?

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Scuzzywuffit posted:

So I'm attempting to track down a memory leak that I believe is related to an event handler, and I have a dumb question that shouldn't be that difficult to Google but apparently is (or maybe I am just bad at it). If I do the following:

code:
Foo.SomeEvent += new EventHandler(Bar.Method);
Is the resulting EventHandler's _target property pointing to Foo or Bar?

Have you run a profiler? Red Gate's profiler (ANTS, I believe) is excellent at hunting this kind of thing down, and there's a free trial.

Scuzzywuffit
Feb 5, 2012

Ithaqua posted:

Have you run a profiler? Red Gate's profiler (ANTS, I believe) is excellent at hunting this kind of thing down, and there's a free trial.

Yeah, I'm looking at it in dotMemory, which is how I found the handler in the first place. I have a window that's remaining in my application's window list even after I close it. dotMemory shows a reference to it from a RoutedEventHandler's _target property, which I'd been assuming was why it wasn't being removed and garbage collected.

Eggnogium
Jun 1, 2010

Never give an inch! Hnnnghhhhhh!
I have a .NET service with extremely unreliable and cumbersome end-to-end test automation so I'm trying to mock out some of the external dependencies to get things under control. One of them is a RESTful service that sends and receives data through JSON. One method is ReturnFoo and the request to the real service looks like this:

code:
POST [url]http://fooservice/lookup_foos[/url] HTTP/1.1
Content-Type: application/json

foo_names=["foo1","foo2"]
(e: sorry about the [url] tags, the reply editor is automatically sticking them in)

I have this mocked out in WCF like so:

code:
[WebInvoke(Method = "POST", UriTemplate = "lookup_foos")]
[OperationContract]
List<string> LookupFoos(List<string> foos);
But the .NET JSON deserializer shits the bed trying to parse the request content:

code:
There was an error checking start element of object of type System.Collections.Generic.List`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]. Encountered unexpected character 'f'.
Seems like it could be expecting some top-level JSON object containing the list. The contents of the request is out of my control, so what would be the best way of mapping it to a List<string> in .NET?

Faldoncow
Jun 29, 2007
Munchin' on some steak
Not sure how to solve your issue, but the reason it is occurring is probably because proper Json format for

code:
foo_names=["foo1","foo2"]
should be

code:
{
    "foo_names" : ["foo1","foo2"]
}
Check out something like http://jsonlint.com/ (No clue on this site, first response on google for Json Validator) to check that your syntax is correct. That at least is why the serializer is getting pissed off.

Not sure if it'd work, but you could try receiving the request as a string instead of a List<string> and then at least see what you have to work with.

Eggnogium
Jun 1, 2010

Never give an inch! Hnnnghhhhhh!

Faldoncow posted:

Not sure how to solve your issue, but the reason it is occurring is probably because proper Json format for

code:
foo_names=["foo1","foo2"]
should be

code:
{
    "foo_names" : ["foo1","foo2"]
}
Check out something like http://jsonlint.com/ (No clue on this site, first response on google for Json Validator) to check that your syntax is correct. That at least is why the serializer is getting pissed off.

Not sure if it'd work, but you could try receiving the request as a string instead of a List<string> and then at least see what you have to work with.

Ah thanks, I have not worked much with JSON and didn't realize it wasn't even valid. Couldn't retrieve it as a string for the same reason but was able to retrieve it as a Stream and grab the raw bytes.

Mr Shiny Pants
Nov 12, 2012

Eggnogium posted:

Ah thanks, I have not worked much with JSON and didn't realize it wasn't even valid. Couldn't retrieve it as a string for the same reason but was able to retrieve it as a Stream and grab the raw bytes.

Use something like Json.net to serialize and deserialize you object to and from Json, it will save you a lot of trouble.

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 have a problem with an MVC action I'm trying to write. I want a model to be supplied as an optional parameter to the action so that the model can be fetched from TempData instead if there is no model supplied. So I have the following:

code:
    public ActionResult Page1(TestFormViewModel model = null)
    {
        if (model == null)
        {
            model = TempData["model"] as TestFormViewModel;
        }
    
        return View("Page1", model);
    }
But every time I try this, the model is a newly instantiated copy of the TestFormViewModel class, instead of null. How can I make the parameter null when there is no model supplied?

Eggnogium
Jun 1, 2010

Never give an inch! Hnnnghhhhhh!

Mr Shiny Pants posted:

Use something like Json.net to serialize and deserialize you object to and from Json, it will save you a lot of trouble.

The serialization is in a library I don't control. All I could do was modify the config to point at my mock service. Apparently the real service can (only?) handle the invalid JSON.

Azubah
Jun 5, 2007

Is ELMAH still supported? I was thinking of using this for a MVC project at work and the last time it got any sort of love was back in 2012, the lead developers here are leery of using it because of this.

Or is there any sort of alternative to ELMAH?

Wozbo
Jul 5, 2010
Servicestack.text (3.9 branch, 4 is pay to use) is pretty good for serializing/ deserializing stuff (XML/ JSON/ etc).


I've used elmah and its fine but I mainly just use log4net. Elmah is fine as a general uncaught exception listing tool though. Just remember your permissions set for the page if this is public facing!

aBagorn
Aug 26, 2004
So I realized that I forgot to cross post from project.log over to here. Being that it's a .NET specific project, I think that you guys will be more interested than goons in general

http://forums.somethingawful.com/showthread.php?threadid=3657015

gnatalie
Jul 1, 2003

blasting women into space
I inadvertently clicked on "Enable .NET framework source stepping" in the debug/general menu and now although It's unclicked it still steps through everything :( I even exported the config file and verified that the option is set to 0, but still no dice.

Using VS 2013.3, any suggestions?

Mr Shiny Pants
Nov 12, 2012

candy for breakfast posted:

I inadvertently clicked on "Enable .NET framework source stepping" in the debug/general menu and now although It's unclicked it still steps through everything :( I even exported the config file and verified that the option is set to 0, but still no dice.

Using VS 2013.3, any suggestions?

Does this mean you get that annoying thing that says: Need source file for yadda yadda.cs?

No help, I got the same error. Now I get to remember each time make a call to an external library. Really, really annoying.

Destroyenator
Dec 27, 2004

Don't ask me lady, I live in beer
Re: ELMAH alternatives:

I've used StackExchange.Exceptional and it's pretty good. Stacks repeated exceptions so it's easy to read but will throw away some info in that case (only keeps the http context data for the first one etc.). Less configurable than ELMAH but it's easy to throw custom data into it along with the exceptions.

I haven't used it but I've heard good things about Serilog.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug
Does anyone have any ideas about getting around SignalR's inability to have async event handlers? I'm working on something where I have my application's logic totally platform-agnostic and want to fire events when the internal state changes and needs to be pushed to clients, but SignalR can't handle async void methods.

Drastic Actions
Apr 7, 2009

FUCK YOU!
GET PUMPED!
Nap Ghost

Ithaqua posted:

Does anyone have any ideas about getting around SignalR's inability to have async event handlers? I'm working on something where I have my application's logic totally platform-agnostic and want to fire events when the internal state changes and needs to be pushed to clients, but SignalR can't handle async void methods.

Does it have to be Async Void, or can it return a Task?

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Drastic Actions posted:

Does it have to be Async Void, or can it return a Task?

It's an event handler, so it can't return a Task.

Let's say I have this pseudo-pseudocode:

code:
public class MyHub : Hub 
{
    public MyHub() 
    { 
        var eventyThing = new EventyThing();
        eventyThing.SomeEvent += ThingyHandler;
    }

    public async void ThingyHandler(object sender, EventArgs args) 
    {
    }
}
ThingyHandler will never be invoked. In fact, I'm pretty sure it's failing catastrophically behind the scenes -- everything after the event invocation doesn't occur.

[edit]
Basically, I'm writing a multiplayer, multi-instance turn-based game. I want the game instances to fire events when certain actions occur internally (for example, "round timeout expired, anyone who hasn't played this round yet can get hosed") so the clients can be notified. I don't want to pass an instance of the HubContext into the game objects, because that would violate the poo poo out of separation of concerns -- the game should be responsible for maintaining its internal state, and the hub should be responsible for figuring out what data to push to connected clients based on how the game's internal state is changing.

New Yorp New Yorp fucked around with this message at 16:06 on Aug 14, 2014

Hiyoshi
Jun 27, 2003

The jig is up!

The Wizard of Poz posted:

I have a problem with an MVC action I'm trying to write. I want a model to be supplied as an optional parameter to the action so that the model can be fetched from TempData instead if there is no model supplied. So I have the following:

code:
    public ActionResult Page1(TestFormViewModel model = null)
    {
        if (model == null)
        {
            model = TempData["model"] as TestFormViewModel;
        }
    
        return View("Page1", model);
    }
But every time I try this, the model is a newly instantiated copy of the TestFormViewModel class, instead of null. How can I make the parameter null when there is no model supplied?

The MVC framework is always going to attempt to model bind the parameter. By the time that the MVC framework realizes that a complex object wasn't provided in the context, it's already instantiated the object from the its default constructor. The framework doesn't reflexively look at the object it instantiated and determine that it should call Page1() instead of Page1(model) because all of the properties on the instantiated object are defaults. If you want that functionality you'll have to write your own model binder for your TestFormViewModel class.

Assuming your TestFormViewModel class looks like this:

code:
public class TestFormViewModel
{
    public int Id { get; set; }
}
You've got a few options:
  • Pull your model from TestData if model.Id == 0 rather than if model == null.
  • Use the signature ActionResult Page1(int id = 0) and build your model in your action method if Id is not the default value; else pull it from TestData.
  • Implement a custom model binder for your TestViewModel class that returns null if Id is set to the default value.

The first option would probably be your best bet. If you want to go the model binder route, here's a custom model binder that you could use:
code:
    public class TestFormViewModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var model = base.BindModel(controllerContext, bindingContext) as TestFormViewModel;
            if (model.Id == 0)
            {
                model = null;
            }
            return model;
        }
    }

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

Ithaqua posted:

Does anyone have any ideas about getting around SignalR's inability to have async event handlers? I'm working on something where I have my application's logic totally platform-agnostic and want to fire events when the internal state changes and needs to be pushed to clients, but SignalR can't handle async void methods.

We're doing something similar to this, but are using a homegrown messaging abstraction (that we're later going to hook up to Azure pub/sub or a messaging queue). Instead of using C# events, we register for a message type with a callback.

gnatalie
Jul 1, 2003

blasting women into space

Mr Shiny Pants posted:

Does this mean you get that annoying thing that says: Need source file for yadda yadda.cs?

No help, I got the same error. Now I get to remember each time make a call to an external library. Really, really annoying.

Yes, it happens all the loving time :mad: Probably going to uninstall/reinstall tomorrow and hope for the best.

Ochowie
Nov 9, 2007

Ithaqua posted:

It's an event handler, so it can't return a Task.

Let's say I have this pseudo-pseudocode:

code:
public class MyHub : Hub 
{
    public MyHub() 
    { 
        var eventyThing = new EventyThing();
        eventyThing.SomeEvent += ThingyHandler;
    }

    public async void ThingyHandler(object sender, EventArgs args) 
    {
    }
}
ThingyHandler will never be invoked. In fact, I'm pretty sure it's failing catastrophically behind the scenes -- everything after the event invocation doesn't occur.

[edit]
Basically, I'm writing a multiplayer, multi-instance turn-based game. I want the game instances to fire events when certain actions occur internally (for example, "round timeout expired, anyone who hasn't played this round yet can get hosed") so the clients can be notified. I don't want to pass an instance of the HubContext into the game objects, because that would violate the poo poo out of separation of concerns -- the game should be responsible for maintaining its internal state, and the hub should be responsible for figuring out what data to push to connected clients based on how the game's internal state is changing.

Could you drop this out into a thread-safe helper class? That's how I've been working with hubs and I'm able to trigger async void events for timer ticks and such.

Adbot
ADBOT LOVES YOU

Mr Shiny Pants
Nov 12, 2012

Ithaqua posted:

It's an event handler, so it can't return a Task.

Let's say I have this pseudo-pseudocode:

code:
public class MyHub : Hub 
{
    public MyHub() 
    { 
        var eventyThing = new EventyThing();
        eventyThing.SomeEvent += ThingyHandler;
    }

    public async void ThingyHandler(object sender, EventArgs args) 
    {
    }
}
ThingyHandler will never be invoked. In fact, I'm pretty sure it's failing catastrophically behind the scenes -- everything after the event invocation doesn't occur.

[edit]
Basically, I'm writing a multiplayer, multi-instance turn-based game. I want the game instances to fire events when certain actions occur internally (for example, "round timeout expired, anyone who hasn't played this round yet can get hosed") so the clients can be notified. I don't want to pass an instance of the HubContext into the game objects, because that would violate the poo poo out of separation of concerns -- the game should be responsible for maintaining its internal state, and the hub should be responsible for figuring out what data to push to connected clients based on how the game's internal state is changing.

Why not logically make the game a client of the hub, the same as regular clients? Maybe a special client or something. That way logically everything is the same and the hub is only responsible for routing messages to its subscribers and you can reuse the message passing infrastructure that you already use for the clients.

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