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
B-Nasty
May 25, 2005

New Yorp New Yorp posted:

Yeah and I'm going to be adding on another layer, with this running in an App Service where those values can be overridden at the slot level.

Unless you have some specific needs, I would keep the App Service settings overrides limited. I would, and have, generally only used the App Service settings for security-related items that I don't want checked into source. I also typically put the setting in the environment's config with a bogus value like "EncryptionKey": "This value is set by AppService settings" to keep it clear.

Adbot
ADBOT LOVES YOU

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

B-Nasty posted:

Unless you have some specific needs, I would keep the App Service settings overrides limited. I would, and have, generally only used the App Service settings for security-related items that I don't want checked into source. I also typically put the setting in the environment's config with a bogus value like "EncryptionKey": "This value is set by AppService settings" to keep it clear.

Yeah, I always push for configuration as code as much as possible. The connection string is going to be derived from whatever is provisioned during the ARM template deployment. I actually don't think there are a lot of app settings other than that.

hackbunny
Jul 22, 2007

I haven't been on SA for years but the person who gave me my previous av as a joke felt guilty for doing so and decided to get me a non-shitty av

Munkeymon posted:

My educated guess is that that property isn't backed by a managed string, one is only provided when you access it, and they probably want people to use the Secure property you mentioned but the old one is kept around to avoid a breaking API change.

Yes but, the goddamned property isn't bindable

a hot gujju bhabhi posted:

We use this at my current (soon to be previous) job and I'm not a fan. I can't describe exactly my issues with it, but it just feels clunky to use. NLog was much nicer in my opinion.

In the end I went with NLog, it was really easy to set up. Only, is the console target really as slow as it feels? I had to make it asynchronous, because it was making my app lag, but now the output window takes a very long time to catch up with some of the larger bursts of log lines, on the order of several seconds

The quick and dirty native logger I had hacked up before switching to NLog was, like, a good order of magnitude faster. I wonder if I'm doing something wrong or if I should just live with it

Night Shade
Jan 13, 2013

Old School

hackbunny posted:

is the console target really as slow as it feels?

no, but the console itself is terrible. redirect to a file and you'll see a significant performance increase out of the console logger. or shrink your console to one line tall.

amotea
Mar 23, 2008
Grimey Drawer

hackbunny posted:

The quick and dirty native logger I had hacked up before switching to NLog was, like, a good order of magnitude faster. I wonder if I'm doing something wrong or if I should just live with it

Not sure if this also applies to the console, but IIRC NLog uses some buffering/flushing mechanism to not block your program, so maybe it just flushes less often than e.g. a real-time console logger.

Night Shade
Jan 13, 2013

Old School

amotea posted:

Not sure if this also applies to the console, but IIRC NLog uses some buffering/flushing mechanism to not block your program, so maybe it just flushes less often than e.g. a real-time console logger.

Only if you wrap your targets in an async wrapper. Otherwise it's unbuffered blocking writes.

hackbunny
Jul 22, 2007

I haven't been on SA for years but the person who gave me my previous av as a joke felt guilty for doing so and decided to get me a non-shitty av

Night Shade posted:

Only if you wrap your targets in an async wrapper. Otherwise it's unbuffered blocking writes.

I did, because the blocking writes were making my app unusable (many log lines come from realtime threads doing audio - I know it sounds crazy but it's never been an issue on iPhone or Android builds of the same code). But is there any buffering other than the async wrapper's queue?

Night Shade
Jan 13, 2013

Old School

hackbunny posted:

I did, because the blocking writes were making my app unusable (many log lines come from realtime threads doing audio - I know it sounds crazy but it's never been an issue on iPhone or Android builds of the same code). But is there any buffering other than the async wrapper's queue?

Unless it got added while I wasn't watching, no. Without an async wrapper you should be able to follow the call stack all the way from the call to Logger to Console.WriteLine.

LongSack
Jan 17, 2003

Are there any tools which will diagram the relationships between classes, interfaces, etc in a WPF project / solution? For example, all of my POCO objects derive from NotifyBase (which itself implements INotifyPropertyChanged) and implement IEquatable<T>. And as another example, in one project the Firewall object contains collections of nats, identity nats, version 9 nats, interfaces, rules, named objects, routes, rules, object groups, etc. I’d love to see a graphic representation of all the interdependencies.

downout
Jul 6, 2009

LongSack posted:

Are there any tools which will diagram the relationships between classes, interfaces, etc in a WPF project / solution? For example, all of my POCO objects derive from NotifyBase (which itself implements INotifyPropertyChanged) and implement IEquatable<T>. And as another example, in one project the Firewall object contains collections of nats, identity nats, version 9 nats, interfaces, rules, named objects, routes, rules, object groups, etc. I’d love to see a graphic representation of all the interdependencies.

Isn't this built into VS?

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

downout posted:

Isn't this built into VS?

VS Enterprise, yeah. There's architecture diagram tools -- I think it's called "Code Map". NDepend also does it.

LongSack
Jan 17, 2003

New Yorp New Yorp posted:

VS Enterprise, yeah. There's architecture diagram tools -- I think it's called "Code Map". NDepend also does it.

Sadly, neither of these things are free :ohdear:

downout
Jul 6, 2009

LongSack posted:

Sadly, neither of these things are free :ohdear:

google free c# class diagram tool - it looks like there are a few options that might work

LongSack
Jan 17, 2003

downout posted:

google free c# class diagram tool - it looks like there are a few options that might work

Thanks! Am still thinking of rolling my own as an exercise, but will definitely take a look.

dougdrums
Feb 25, 2005
CLIENT REQUESTED ELECTRONIC FUNDING RECEIPT (FUNDS NOW)
The name of HashSet<T>.ExceptWith borders on "Until" levels of confusion for me, because I think it is union at first.

mst4k
Apr 18, 2003

budlitemolaram

Just hopping in to say JB Rider (on a mac) is loving awesome but it doesn't respect your launchSettings.json port, so you have to make a profile for each service if your are doing microservice bs. Other than that, it's freaking great.

megalodong
Mar 11, 2008

I've been completely unable to find the answer to this: does await work with foreach?

e.g.

C# code:
foreach(var foo in non_async_bar)
{
  var baz = await some_IO_bound_op_on_foo(foo);
  do_something();
  baz.frob = 1;
}
The code compiles and runs without complaint, but I have no idea if the foreach has to wait for each await to complete before starting its next iteration or not.

Or would I need to make a list of Tasks and add to it in the foreach, and then await Task.WhenAll() after the foreach is done?

All I can find is people trying to make linq's .ForEach() method work, or people wanting parallel foreachs...

EssOEss
Oct 23, 2006
128-bit approved
Yes, await works perfectly normally in a foreach.

No, a foreach does not run in parallel unless you make it run in parallel.

Yes, to execute multiple Tasks in parallel, you can collect them into a list and WhenAll() them later.

Sab669
Sep 24, 2009

Edit, never mind

Sab669 fucked around with this message at 18:55 on Mar 30, 2018

LongSack
Jan 17, 2003

Is there a way to change the font family for menu items in a context menu? The MenuItem class has a FontFamily property (inherited from Control) but appears to ignore it.

I'm using a context menu to allow the user to select a different font / font size if they are having trouble reading with the defaults. The context menu offers a couple standard options (Arial, Times New Roman, Calibri, Comic Sans for a chuckle) and a final option which will allow them to choose from a dialog box. The idea is to have the menuitem font match the font being selected, but it's not working.

I've tried setting the FontFamily directly on the MenuItem itself, and also using a TextBlock in an ItemTemplate like:
code:
<MenuItem Header="Times New Roman" FontFamily="Times New Roman" Command="{Binding SetFontFamilyCommand}" CommandParameter="Times New Roman">
  <MenuItem.Icon>
    <TextBlock FontSize="18" FontFamily="Times New Roman" Text="A"/>
  </MenuItem.Icon>
  <MenuItem.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="Times New Roman" FontFamily="Times New Roman" FontSize="18"/>
    </DataTemplate>
  </MenuItem.ItemTemplate>
</MenuItem>
<MenuItem Header="Calibri" FontFamily="Calibri" Command="{Binding SetFontFamilyCommand}" CommandParameter="Calibri">
  <MenuItem.Icon>
    <TextBlock FontSize="18" FontFamily="Calibri" Text="A"/>
  </MenuItem.Icon>
</MenuItem>
neither method works (Note that the TextBlock in the Icon property does get the correct font):



Any ideas?

EssOEss
Oct 23, 2006
128-bit approved
I vaguely remember font settings being special somehow but I forget how. Try looking up the visual tree in XAML Spy or whatever the modern variant of that tool is and fiddling with the properties until the hidden relation shows up.

This is a memory from Silverlight/WPF days, though, so if you are doing UWP perhaps it no longer applies.

LongSack
Jan 17, 2003

EssOEss posted:

I vaguely remember font settings being special somehow but I forget how. Try looking up the visual tree in XAML Spy or whatever the modern variant of that tool is and fiddling with the properties until the hidden relation shows up.

This is a memory from Silverlight/WPF days, though, so if you are doing UWP perhaps it no longer applies.

Nope, just using WPF on windows. The MS docs just say that the MenuItem FontFamily property is inherited from Control, but don’t indicate that it’s ignored. I’ve tried straight up binding, ItemTemplates and even ItemContainerStyle (or whatever it’s called) without success. Probably going to give up on it, not worth wasting a ton of time on, but wondered if anyone else had come across it.

I think my next feature will be a whiteboard with the ability to drop characters, locations, incidents, etc on the board and draw arrows connecting them with annotations. I’ve got some example code that is not MVVM, so it will be interesting to try to change the paradigm as well as giving me the change to try out some more extensive styling. Not sure if you can bind the Children of a Canvas, so it should be a challenge.

fankey
Aug 31, 2001

LongSack posted:



Any ideas?

Try just settting FontFamily on the MenuItem itself. This works for me
code:
            <MenuItem Header="Times New Roman" FontFamily="Times New Roman">
              <MenuItem.Icon>
                <TextBlock FontSize="18" FontFamily="Times New Roman" Text="A"/>
              </MenuItem.Icon>
            </MenuItem>

Careful Drums
Oct 30, 2007

by FactsAreUseless
How long do y'all think MVC/Web API Controller Action methods should be? I try to keep mine down to like 10 lines tops, at leas when I'm creating new stuff. But one that I'm maintaining is 260 lines long. The method does quite a few different things underlying the surface of 'edit this busiess entity', including sending the entity to two different third party services and gobs of validation code. Is that 'fine', 'bad', or 'ludicrous' ?

beuges
Jul 4, 2005
fluffy bunny butterfly broomstick

Careful Drums posted:

How long do y'all think MVC/Web API Controller Action methods should be? I try to keep mine down to like 10 lines tops, at leas when I'm creating new stuff. But one that I'm maintaining is 260 lines long. The method does quite a few different things underlying the surface of 'edit this busiess entity', including sending the entity to two different third party services and gobs of validation code. Is that 'fine', 'bad', or 'ludicrous' ?

I tend to always keep the Action methods very tiny, and defer actual logic to a separate business logic layer (web api, dll or even just another class). The only time I cram everything into the Action method is if I'm writing something I know is going to be once-off. Aside from the obvious maintainability etc, it also makes it a lot easier to create a separate app for the product if the web UI is just presentation and all actual processing happens elsewhere.

LongSack
Jan 17, 2003

fankey posted:

Try just settting FontFamily on the MenuItem itself. This works for me
code:
            <MenuItem Header="Times New Roman" FontFamily="Times New Roman">
              <MenuItem.Icon>
                <TextBlock FontSize="18" FontFamily="Times New Roman" Text="A"/>
              </MenuItem.Icon>
            </MenuItem>

That’s the first thing I tried. In the code I posted above, the menuitem for Calibri does just that. Doesn’t seem to work.

EssOEss
Oct 23, 2006
128-bit approved
The only thing my controller action methods do is just translate input/output from the controller's API contract to my internal business logic objects. If those 260 lines are data transformation, it is fine. But it sounds like you actually have the business logic in there, which I would not look kindly upon.

NihilCredo
Jun 6, 2011

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

Same, my controller methods are pretty much only for producing the correct HTTP return codes and messages. Example (F#):

code:
    [<HttpPost "login">] 
    [<SwaggerResponse(Http.BadRequest, typeof<string>)>]
    [<SwaggerResponse(Http.OK, typeof<LoginSuccess>)>]
    [<SwaggerResponse(Http.Ambiguousus, typeof<Dictionary<int, string>>)>]
    [<SwaggerResponse(Http.Forbidden, typeof<obj>)>]
    member this.Login([<FromBody>] credentials) = 

      // Boilerplate validation line. Will become unnecessary with .NET Core 2.1 and the [<ApiController>] attribute
      if not this.ModelState.IsValid then reply Http.BadRequest this.ModelState.Root.Errors else

      // Call an active pattern on the credentials and context, then translate the result to HTTP-friendly responses
      match (ctx, credentials) with
      // Credentials only match one account, return auth token
      | Unique (location, token) -> reply Http.OK { JWT = token; Location = location.Name }
      // Credentials are valid for multiple locations, provide list and ask user to pick one
      | Multiples (_, locations) -> reply Http.Ambiguous (dict [ for location in locations -> location.LocationId, location.Name ])      
      // Credentials are not valid
      | None -> reply Http.Forbidden ()

Careful Drums
Oct 30, 2007

by FactsAreUseless
thanks everyone, glad to hear i'm not crazy. on to the challenge of refactoring it without breaking anything :sludgepal:

Careful Drums
Oct 30, 2007

by FactsAreUseless
Hey I have another question, in the form of "fine, bad, or terrible"

A method has a try/catch embedded inside another try/catch. Is that "fine", "bad", or "terrible"? It seems pretty terrible to me.

Ciaphas
Nov 20, 2005

> BEWARE, COWARD :ovr:


Feels terrible offhand, why not just have a second catch clause on the outer try?

I guess technically try/catch within a try/catch is exactly what's happening all the time anyway, just usually there's a method call in between :v:

zokie
Feb 13, 2006

Out of many, Sweden
Depends, you might want to handle some errors differently. I've used it to make a budget TryFoo variant when one is missing. I'd say code smell not horror...

Ciaphas
Nov 20, 2005

> BEWARE, COWARD :ovr:


I guess the only thing I can think of is something like this:

C# code:
DoTotallySafeStuff();
try
{
    UnsafeStuff(); // can throw FooBarException but not WowYouFuckedUpException (at least it's not, er, expected to???)
    try
    {
        ReallyUnsafeStuff(); // can throw FooBarException or WowYouFuckedUpException
    }
    catch (WowYouFuckedUpException e) { }
}
catch (FooBarException e) { }
Looks kinda gross, but I'd need more context :shrug:

EssOEss
Oct 23, 2006
128-bit approved
It is perfectly fine if the inner catch needs to operate over a smaller scope of code. If the only thing inside the outer try is the inner try-catch then it is a bit more fishy, though. Might still simplify some inconvenient patterns.

All in all, post code for exact judgement!

Potassium Problems
Sep 28, 2001

Ciaphas posted:

I guess the only thing I can think of is something like this:

C# code:
DoTotallySafeStuff();
try
{
    UnsafeStuff(); // can throw FooBarException but not WowYouFuckedUpException (at least it's not, er, expected to???)
    try
    {
        ReallyUnsafeStuff(); // can throw FooBarException or WowYouFuckedUpException
    }
    catch (WowYouFuckedUpException e) { }
}
catch (FooBarException e) { }
Looks kinda gross, but I'd need more context :shrug:

Wouldn't something like this work to avoid a nested try/catch?
C# code:
DoTotallySafeStuff();
try
{
    UnsafeStuff(); // can throw FooBarException but not WowYouFuckedUpException (at least it's not, er, expected to???)
    ReallyUnsafeStuff(); // can throw FooBarException or WowYouFuckedUpException
}
catch (FooBarException fbe) 
{ 
}
catch (WowYouFuckedUpException wyfue)
{
}

Ciaphas
Nov 20, 2005

> BEWARE, COWARD :ovr:


Potassium Problems posted:

Wouldn't something like this work to avoid a nested try/catch?
C# code:
DoTotallySafeStuff();
try
{
    UnsafeStuff(); // can throw FooBarException but not WowYouFuckedUpException (at least it's not, er, expected to???)
    ReallyUnsafeStuff(); // can throw FooBarException or WowYouFuckedUpException
}
catch (FooBarException fbe) 
{ 
}
catch (WowYouFuckedUpException wyfue)
{
}

the difference is that your example sort of implies (without reading comments because who reads those) that UnsafeStuff could throw a WowYouFuckedUpException which you might not want to handle right there (though I suppose you could rethrow in the corresponding catch block in that case)

EssOEss
Oct 23, 2006
128-bit approved
Sometimes you want to convert an exception into a different type.

code:
try
{
    var options = ParseOptions();
    options.Validate(); // Throws OptionException if things be off

    try
    {
          LogFile.Set(File.Create(options["logfile.name"]));
    }
    catch (IOException ex)
    {
          throw new OptionException("You cannot make this log file: " + ex.Message);
    }
}
catch (OptionException ex)
{
    Console.Error.WriteLine("You messed up your command line options: " + ex.Message);
    return -1;
}
Granted, in this case it is a bit simpleminded since why do you even need to convert it here but imagine there is a lot more code to work with OptionExceptions when you screw up your command line options, omitted here.

Careful Drums
Oct 30, 2007

by FactsAreUseless

EssOEss posted:

It is perfectly fine if the inner catch needs to operate over a smaller scope of code. If the only thing inside the outer try is the inner try-catch then it is a bit more fishy, though. Might still simplify some inconvenient patterns.

All in all, post code for exact judgement!

Thanks for opinions. Its work code so to post it I'd have to anonymize it a bit but it's in an interesting grey area. It does fit the form of "doing unsafe stuff" inside an otherwise safe-ish method.

LongSack
Jan 17, 2003

Wondering if there is a better way to handle this. One program I’m working on has an Account object. It had an AccountType, a Number, Due Date Type (monthly, quarterly, annually, etc), month and day. The account number is stored encrypted and converted to base64, and is displayed using the account type and the last 4 digits of the number - a VISA card would be displayed as “Credit Card 0000”.

The account number and due date fields on the screen are bound to the account object, with value converters. Problem: if the account is edited to change the due date, the change is not reflected on the screen because the Account object has not changed.

I should note that the Account object has an Id field which is an identity key in the database, and the equality methods check only the Id fields - two Accounts are equal if their Id fields are equal.

I’ve worked around it by changing the bindings for the account number and due date to MultiBindings bound to each of the individual fields with a multiconverter to match, and it works fine, but I wonder if there is a more elegant way to handle it. I thought about changing my equality methods to actually compare all the fields rather than just the Id, but that would have side effects that I’d rather not deal with.

Adbot
ADBOT LOVES YOU

Supersonic
Mar 28, 2008

You have used 43 of 300 characters allowed.
Tortured By Flan
So I've been working on a simple text RPG to help me learn C#, and I'm just wondering if this code looks okay. So far everything in the menus works (the options to fight a monster only appear once a character has been created save for the boss fight which I haven't fully implemented yet). My main issue is being confused as to whether or not I'm doing OOP right.

Is it a good idea to have the player class be static like I have? My rationale is that there's only one player (although I imagine this could change if you wanted to create a new character). Moreover, I'm a bit confused about inheritance. I imagine that the boss class should inherit the enemy class (bosses are enemies and have both HP and a name), but then the boss class should override the enemy HP variable and be set to a different (higher) value.

Finally, is the general logic right? I'm wondering if I should be having more functions return a result rather than things like Console.Writeline (to decouple methods from formatting)m, but if thats the case, where would the methods be returning to?

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