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
Mr. Crow
May 22, 2008

Snap City mayor for life
(from old thread)

zerofunk posted:

Has anyone ever had issues with different results from using the VS 2012 Test Runner and running mstest.exe from the command line? We have some Automapper Exceptions thrown due to some type mismatches (silly things like float -> double, and int? -> int). These are causing test failures if I run our tests from mstest.exe. When I run directly from VS2012, everything passes. I'm not even sure where to start in figuring out why that is happening.

Could be that VS is using one set of Test Settings and running via command line you're using a different (default/none) set of Test Settings.

Yet another reason to not use MSTest for unit testing.

edit: You can check if VS is using one in the Test -> Test Settings menu.

Adbot
ADBOT LOVES YOU

Mr. Crow
May 22, 2008

Snap City mayor for life
Going crazy trying to figure this AutoFixture issue out, any ideas would be appreciated!

http://stackoverflow.com/questions/24435874/automocking-properties-fails-on-abstract-property

Mr. Crow
May 22, 2008

Snap City mayor for life
Anyone have experience hosting external applications in WPF? In the simplest case it's pretty trivial (e.g. notepad) but if it's between two complex apps it quickly gets out of control.

Buzzwords: HwndHost, COM, OLE(?), Win32, routing message pumps

Mr. Crow
May 22, 2008

Snap City mayor for life

chmods please posted:

How much control do you have over the external process? If the answer is "none", I'd recommend building your program as a shell which draws itself around the other windows, it sounds like asking for trouble otherwise.

For all intents and purposes, 'none' is the answer.

We already do have our program as a shell... sort of. We're basically just calling SetParent on the external app and installing some hooks, but there is some (predictably) hackish stuff put in to account for weird bugs, as well as just some general quirkiness to the look and feel.

I'd be curious if you had something else in mind when you said shell, maybe it's something we can do better?

Currently exploring / prototyping using HwndHost instead, I realize in a lot of ways it's just substituting old problems for new problems, but if we can solve the new ones, the other advantages it gives would be very beneficial.

Mr. Crow
May 22, 2008

Snap City mayor for life

Ciaphas posted:

I ended up (after a lot of fuss and bother) going for Option 2, sort of. I turned off autogeneration in the datagrid, made its ItemsSource my list of DataRecords, and, in my xaml code-behind, generated, bound, and added the individual columns by selecting out the name and numeric index of each DataItem.

I don't have the code in front of me but it was something like this.
C# code:
// AllDataRecords is List<DataRecord>
var columns = myViewModel.AllDataRecords.First().Select((x,i)=>new { Name = x.Info.Name, Index = i });

foreach (var c in columns)
{
   Binding b = new Binding(string.Format("Items[{0}].DataAsString", c.Index));
   dataGrid.Columns.Add(new DataGridTextColumn() { Header = c.Name, Binding = b });
}
I don't know how robust it is, or if there was a LINQ alternative to that particular Select syntax, or how much of this is gonna change later, or even if this is remotely idiomatic or not, but it does work. Now I've got the problem that the DataGrid is very very slow to scroll (some 200mb of data, with 20 columns and 500k rows), but one step at a time I suppose.

I want to say datagrids don't use virtualizingstackpanels by default so maybe look into that for a quick fix to the performance.

There will be some other costs to using one though which you may or may not care about (no smooth scrolling for example).

Also I'd strongly recommend not building that by hand in the code behind, the XAML is made for this stuff and that's not what Ithaqa was talking about with option two.

Mr. Crow fucked around with this message at 03:56 on Jul 17, 2014

Mr. Crow
May 22, 2008

Snap City mayor for life

Ciaphas posted:

Yeah, I sort of realized that wasn't quite the Option Two being presented after I posted. I'm new to the whole MVVM thing too though--in fact this is literally my first go at making GUI anything since Visual Basic 6.0 in high school--so it took me a while to realize. :(

I tried for several hours today to get binding to work in the XAML, but I kept getting blindsided mostly by the fact that the number of Items in each DataRecord, though the same across records, is completely unknown until runtime. (Their types are unknown, too, but that's what that DataAsString property is for :v:) What can I do in the XAML to set up those column definitions without that knowledge?

(The fact that my data is essentially a list of lists with some metadata leaves me confused too, but I'm sure the solution to that problem is simpler.)

You never really explained why Ithaqua's example failed you? It should have worked generally as-is; the second column wouldn't look exactly like you want, but nothing some header styles and templates can't fix.

Mr. Crow
May 22, 2008

Snap City mayor for life

gently caress them posted:

Is there any rule of thumb as far as MessageBox.show vs actually throwing up some markup and code-behind if you're doing something in WPF? I'm displaying what amounts to a list of "YO these numbers are invalid or were entered wrong" and would rather avoid mucking with markup whenever possible.

OTOH if it's now idiomatic to do something else besides a modal popup I might as well get busy.

I'm not really following you're question, but as your application evolves and becomes more complex you'll find you probably want/need to roll your own dialog window, which is pretty simple (is this your question??).

The MVVM approach to showing dialogs is to use some sort of IDialogService, MVVM-light has a good system as do the other MVVM frameworks, http://msdn.microsoft.com/en-us/magazine/jj694937.aspx.

You may also want to look at the built-in validation framework, for showing validation errors.

Otherwise... I'm an idiot and you'll need to expand on your question more.

Mr. Crow
May 22, 2008

Snap City mayor for life
Have you considered... talking with the customer and actually figuring out what they want and plan to use it?

If they get the DLNs from some spreadsheet and want to just ctrl + v a bunch at a time, having individual textboxes to put each one in would be a nightmare from a usability standpoint. On the flip-side there are benefits to the other approach that was mentioned as well. Doesn't really sound like you're sure what they want, to me.

Mr. Crow
May 22, 2008

Snap City mayor for life

Geisladisk posted:

Thanks for the suggestions. TopShelf and Puppet definitely looks interesting, I'm looking into them right now. If TopShelf is easy to integrate into the preexisting project, it looks like it'll be a huge timesaver when compared to deploying to vm via batch script.

I've also started using unit tests to test individual pieces of code, which is a huge improvement over accessing the frontend and activating the functionality from there.

I graduated this spring and got hired two months ago to dust off a 100k+ loc system (.net backend, asp and extjs frontend and two databases, interfacing with two different black-box systems, with the whole shebang running on ten virtual machines. Overwhelmed doesn't even begin to describe how I felt the first couple of weeks. :psyduck:). The system has basically been dormant for the past year, after the only guy working on it quit. They're now renewing development on it, and the first stage was hiring me.

My job for the past two months has basically been to figure out how to get this monster running, and set up development procedures and tools to lubricate the development that's starting on the system. Two weeks from now, there are two other developers starting on the project and the goal is to have the environment and procedures set up and ready to go.

Only 100k? Heh. Try 1000k+ :smugbert:

Mr. Crow
May 22, 2008

Snap City mayor for life

Knyteguy posted:

How do you guys save little reusable blurbs of code to use through various projects? A class library would work with static methods but that seems like a pain to maintain. Does VS have something like this built in?

Common libraries, and I have a common personal repo I threw up on github with my own libraries and junk I develop and want to keep track of.

If probably blog about it if I had one but :effort:

Mr. Crow
May 22, 2008

Snap City mayor for life

Mr Shiny Pants posted:

It does not do that for me, maybe only in Chrome?



I would show the dropdown and make it as wide as the widest option.

Tab completion and the possibility to select an item is what I would do.

How to build it in WPF? No clue, sorry.

ComboBox is unfortunately not very extensible, so you may end up having to re-write it (don't make that assumption yet though).

This specific example however probably isn't a big deal.

I would look at it's template, you'll have to copy it to modify what you need to modify but just quickly glancing at it you should be able to tweak it and allow the drop down to always show (IsDropDownOpen).

Something that will probably determine the pain level is and whether or not this is helpful is how the selected value in the pop-up is updated, whether it tries to resolve the selected item after the textbox loses focus or as it's changing, I don't know.

http://msdn.microsoft.com/en-us/library/ms752094(v=vs.110).aspx for the style (template is baked into it).

Mr. Crow
May 22, 2008

Snap City mayor for life
If it's not .net I don't know what Roslyn would do but I'm am idiot so...

Mr. Crow
May 22, 2008

Snap City mayor for life

Scuzzywuffit posted:

which is going to be really embarrassing if the fix is something trivial.

With me anyway, it seems like the more hair raising and obnxious the issue, the more likely it is to be something trivial I'm overlooking.

Probably worth asking a co-worker for a second set of eyes, or taking a break from it for a day (if possible).




Are you able to see if the window is actually closed when you think it is? If the window actually gets Closed() it should be enough to not worry about it, the framework will get rid of it when it's can.

Mr. Crow
May 22, 2008

Snap City mayor for life

Ciaphas posted:

Is it possible to have a WPF application, depending on certain command line options being present, not bother with the Windows part and just run in the current console (or a new one if run from a shortcut)? I have a project that a customer wants to add some scheduled processing to.

I don't see why not, just don't set the StartupUI property and launch/hook your console in a Startup event handler.

Mr. Crow
May 22, 2008

Snap City mayor for life
Are either one new? WPF has an issue where it won't compile XAML if some resource your referencing hadn't been built yet, I'm not 100% sure the specific scenario it occurs. Try commenting the data part.

Mr. Crow
May 22, 2008

Snap City mayor for life
Fourth'ing the conclusion you don't understand MVVM and are making this way more complicated than it needs to be.

Super high-level; your View-Model consumes your Model, your View consumes your View-Model, your Model knows nothing about your View-Model or View, your View-Model knows nothing about your View (there's debate on this specific point, I guess), your View knows nothing about your Model.

So exactly like a lot of what gets said about MVVM, the View-Model is the glue between your UI and your Business Logic.

A Tartan Tory posted:

The button push just tells it to get the Calculated Results? What I should be doing is telling the button to implement a command rather than to get existing results?

Your View-Model exposes/provides some sort of general ICommand property, that the View (or multiple views) consumes to perform some action. ICommands are literally just delegates with built-in if-checks (e.g. CanExecute, usually you don't even need this) in the majority case. There is nothing special about them beyond that they are heavily built into the framework to make it easy to delegate function calls, which is why a lot of Controls have a Command property.

There are also RoutedUICommands which are basically RoutedEvents + RelayCommands (linked above and re-implemented ad-nauseum across the internet), which is what is built into WPF (RoutedUICommands). Ignore these.

quote:

View passes information to viewmodel, viewmodel updates model, model updates viewmodel, viewmodel updates view? Is that supposed to be how it works?

More or less.


quote:

Ok so, this is the viewmodel, it initiates itself whenever the button is pressed (how do I represent that in the XAML in view?) and all the inputted data is bound to the name I use in the xaml in view for that textbox it just needs to be assigned to a new variable within this method (how do I access it from the binding to do that then, it can't be within the model as given in the example?).

You create your View and your ViewModel independently of each other and tell your View to consume a ViewModel by setting the Views DataContext property to whatever ViewModel.

Mr. Crow
May 22, 2008

Snap City mayor for life

A Tartan Tory posted:

Honestly, I'm on a massive downer because of this mostly because even after the better part of a week of dedicated study on it, including multiple examples from everyone here and youtube videos etc. I just straight up don't get it.

I don't get it to the extent where I don't even know where to start doing the basic program you say to try and I really don't understand why I can't either. Everything I make at the moment regarding it seems like a massive jumbled up mess that makes no sense, when it made perfect sense when I did it with the console.

I feel like a complete helpless idiot doing this stuff and I'm struggling to think of how to get over this hurdle because nothing I do actually seems to work and it is incredibly frustrating.

I find it easiest to start with the view first, as it's static and visual both of which make it easier to wrap your head around what you want and what needs to be done.

Program your view and keep it super basic, don't worry about specific bindings and gluing a view model together, think about it at that high user level. THEN you can think about what you need to expose on a view model to get your view to work. THEN you can add your business logic.

This is kind of backwards from the real world and maybe even "ideal" scenario but when I'm first getting started on a project or helps me get a coherent first step.

Also by no means is the view side of things easy, on the contrary it's a rabbit hole of complexity you'll never escape; but if you just want to throw some basic buttons and fields in a window it is fairly simple. Don't get to wrapped up in best practices and trying add more frameworks to "help" you either, get the basics down first then start worrying over having code in the code behind etc.

Mr. Crow
May 22, 2008

Snap City mayor for life

Ciaphas posted:

Since we're talking about MVVM and WPF and how the rules work, let me ask a question about breaking said rules. :v:

I don't have my code from work, as usual, but is something like the stuff bordered by slashes a total faux pas? A loose coupling from the view-model to the view? (The specific actual code involves OxyPlot being, unless I really missed something, a bit dumb about trying to automatically pan and zoom to updated data for its plots.)

C# code:
// view code-behind
    public partial class MainWindow : Window
    {
        private MainWindowViewModel MWVM;
        public MainWindow()
        {
            MWVM = new MainWindowViewModel();
            DataContext = MWVM;

            //////////////////////////////////
            MWVM.DataUpdated = OnDataUpdated;
            //////////////////////////////////

            InitializeComponent();
        }
        
        //////////////////////////////
        private void OnDataUpdated()
        {
            MessageBox.Show("fart");
        }
        //////////////////////////////
    }

// view model
    class MainWindowViewModel : ViewModelBase // ViewModelBase implements INotifyParameterChanged and IDisposable if you give a poo poo
    {
        public Action DataUpdated { get; set; }
        
        // blah blah blah

        private void UpdateData() // pretend some RelayCommand bound in the view calls this :effort:
        {
            // blah blah blah

            ///////////////////////////////////
            if (DataUpdated != null)
                DataUpdated();
            ///////////////////////////////////
        }
    }
I know the ideal is that the code-behind of views should be as empty as possible, but I feel my hand is being a bit forced by the way OxyPlot works. I really need a better charting control (cough cough :v:).

My view is developers get to zealous about that (bolded); you can't avoid the code-behind (writing controls, anything to do with dependency objects etc). The primary motivation is to make sure you're not mixing view-model concerns into your view and vica-versa I think.

That's the typical pattern for showing notifications etc; though the 'ideal' decoupled way for that specific example would be to use an event bus, which most of the MVVM frameworks have implemented in some form or another.

I personally don't view anything wrong with that if it's not all over the place or you're in a small project.

Mr. Crow
May 22, 2008

Snap City mayor for life

Factor Mystic posted:

This is ObservableCollection<T>:



Why is PropertyChanged protected, instead of public like CollectionChanged? What if I want to be notified when the Count property changes? As I currently want to, since I'm implementing ISupportIncrementalLoading. These questions are mostly rhetorical, I'm just once again irritated by OC<T>.

Of all the reasons to hate OC<T> that seems like the silliest.

Mr. Crow
May 22, 2008

Snap City mayor for life

Bognar posted:

Generally, you shouldn't JSON.stringify if you're using jQuery AJAX to GET. GET commands are (de)serialized as application/x-www-form-urlencoded because they have to be part of the query string (GET request bodies are ignored per the HTTP/1.1 spec). POST requests, on the other hand, can have anything in the body and will usually work on most servers as long as the Content-Type header is correct (e.g. application/json).

Unfortunately, the default MVC model binder is rather terrible at deserializing complex objects from a query string. A lot of things have to fall into place to make it work, and it's generally not worth figuring it out over just POSTing.

Missed opportunity to :justpost:

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!

Mr. Crow
May 22, 2008

Snap City mayor for life

Inverness posted:

Allocating delegates, from what I assume is a lambda expression, has a memory cost. Even if it's relatively small you'd still be allocating an extra object per event per instance which both wastes memory and puts pressure on the GC.

Of course in most cases the compiler will cache the allocation of lambdas that don't capture variables. Even then you're basically relying on compiler optimizations to not totally waste memory which I consider bad practice.

You could avoid that by declaring static variables for each event type to hold the no-op delegates for each, but then that seems like more effort than just doing the null check.

Finally, use a method to handle the null check, but that is only really useful for generic event delegates and prevents you from being able to only allocate EventArgs if the null check passes. For an event invoked frequently this is wasteful if there are no handlers.

TL;DR: Manual null check is more boilerplate but it avoids memory wastes or gotchas that can crop up with other approaches.

Edit: This made me realize an important question. If I do MyEvent?.Invoke(new MyArgs()), then do the args only get allocated if MyEvent is not null?

In the world of dumb micro-optimizations this is probably up there.

However the annoyance of null checking events everywhere can be circumvented (along with boilerplate event-raising logic) with a simple extension method. This also satisfies the 'performance' inclined as well, and in my opinion is just easier to use/read.
code:
public static void Raise(this EventHandler handler, object sender, EventArgs e)
{
    if (handler != null)
    {
        handler(sender, e);
    }       
}
code:
Butts.Raise(this, new ButtsArg());
I think you end up making a total of like 6 overloads for the various event handler types that don't derive from EventHandler, for example NotifyCollectionChangedEventHandler.

Mr. Crow fucked around with this message at 15:48 on Nov 17, 2014

Mr. Crow
May 22, 2008

Snap City mayor for life

Inverness posted:

Whether this is actually a problem depends on what kind of application you're writing. For most GUI apps, constructing some delegates or event args that wont be used will not have a real impact on performance.

If you're making a game or something, the last thing you want to do is allocate objects you don't need, which is why I do null checks and avoid allocating until after the check passes. That habit remains even when I write other things.

Well your first mistake was writing a game in .NET :rimshot:

Mr. Crow
May 22, 2008

Snap City mayor for life

Inverness posted:

I think that's an interesting concept but would require you to have one of those for each name. I think CallerMemberNameAttribute is more useful in a case like this anyways.

This is the pattern I use in a MVVM application:
code:
public abstract class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
    {
        if (EqualityComparer<T>.Default.Equals(field, value))
            return false;
        field = value;
        OnPropertyChanged(propertyName);
        return true;
    }

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

// And in a subclass:

public abstract class DockingItemViewModel : ViewModel
{
    private string _title;
    private string _description;
    private ImageSource _imageSource;

    public string Title
    {
        get { return _title; }

        set { SetProperty(ref _title, value); }
    }

    public string Description
    {
        get { return _description; }

        set { SetProperty(ref _description, value); }
    }

    public ImageSource ImageSource
    {
        get { return _imageSource; }

        set { SetProperty(ref _imageSource, value); }
    }
}
Why do you think they'd be in trouble?

I remember them commenting on Roslyn and saying that it's basically what they do internally anyways. They can hardly afford to abandon or rewrite all of the code centered around their own methods.

@ReSharper, agreed. At best I think they're going to finally have competition in the form of open source refactorings; which means they'll have to step up their game (which is a good thing for consumers/developers). I would expect we'll see one or a couple big open source refactoring/inspection/code-quality projects come out that utilize Roslyn and become defacto Visual Studio 'plugins' for those that don't want to pay for something of a higher quality, better integration etc.


One thing I am curious on, I would be curious on the performance of similar competing projects vs ReSharper. (I haven't payed much attention to Roslyn at all) I wonder if Roslyn-based project will outperform ReSharper on large projects.

Mr. Crow
May 22, 2008

Snap City mayor for life
Piggybacking off the GetHashCode()-chat, Nthing you really should implement it (and IEqualityComparer) they will make your life so much easier.

This is a good explanation why you need to implement GetHashCode() and the problems that can happen if you dont http://stackoverflow.com/a/371348/961464

We can debate all day best algorithms for GetHashCode but the most common-case one I've seen and personally use is the one linked above that Jon Skeet mentions. Basically, pick two primes, multiply them together and add all your public properties hashes.

If you use ReSharper, it has a very nice 'Generate Equality Members' code generation template that will automatically generate an implementation of ==, Equals, IEqualityComparer, GetHashCode etc for you.

Mr. Crow
May 22, 2008

Snap City mayor for life

bpower posted:

Any objections to using EF for the simple crud stuff, and use something else (PetaPoco maybe) for reports/graphs/import/export etc

Seems like a horror to me, but whatever you (and your coworkers) are comfortable with I guess.

Mr. Crow
May 22, 2008

Snap City mayor for life

xgalaxy posted:

Kind of a dumb bikeshedding-ish question but what is more idiomatic C#?
code:
public delegate void ScheduleCallback(int id, object state);

public interface IScheduler
{
    int Schedule(TimeSpan delay, bool repeating, ScheduleCallback callback, object state);
}
vs
code:
public interface IScheduler
{
    // let them capture their own state if they need it
    int Schedule(TimeSpan delay, bool repeating, Action<int> callback);
}
Thinking about it some more I guess they both have their uses. For instance if the Scheduler, in this case, needed to do something with the state object in the implementation. But if that were the case maybe an Action<int, object> would still be preferable? I dunno. It seemed like the trend was towards using Action and Func over bare delegates these days but I wasn't certain. Thoughts?

2nd one x1000.

I can't think of a compelling reason to use the delegate signature over Action or Func, it might as well be deprecated. Action<int,object> would be preferable to answer your first question.

Mr. Crow
May 22, 2008

Snap City mayor for life

Ithaqua posted:

Not every project lends itself to TDD, especially if you're entering unknown territory. I was just doing something where I had never used any of the frameworks or libraries period, let alone in concert. Thus, my method of development was "make something just loving work", then "make something else just loving work". I didn't have any clue about what my end goal would be, how classes would be composed (or decomposed), or anything like that. TDD would have been a terrible choice for me -- I would have been writing tests for scenarios that might not even work or be valid, and I would have had to constantly be rewriting huge swaths of tests as I figured out how to plug all of the pieces together into some sort of coherent architecture, which would have killed my enthusiasm for learning any of it.

For example, I found out late in the game that SignalR doesn't play nice with async event handlers. If I done TDD on the object model, I would have written the whole thing in isolation, with a beautiful suite of tests that proved out all of this functionality that would have had to be totally thrown out and rewritten when I went to hook it up to SignalR.

What I ended up with was, in my mind, a functional proof of concept. I figured out how to do all of the things I wanted to do and get all of the pieces to play nice together. Attempt #2 will be TDD from the ground up, including the AngularJS stuff. Angular is nice but its IOC implementation is kind of a mindfuck. I'm still trying to wrap my head around how to do IOC with AngularJS controllers and Jasmine. I think I need to start with a calculator backed by a web service or something silly like that.

I find this to be the case more often than not with me. I love writing with unit testing in mind but it seems every time I tried to do TDD it was probably just a poor choice, either because I'm not sure where I'm going end up (new frameworks/features/etc.) or because it hasn't 'clicked' for me either.

Mr. Crow
May 22, 2008

Snap City mayor for life

Sagacity posted:

Please note that unit testing also doesn't necessarily mean that you need to test ALL the details. I've seen people write tests on the level of

code:
  client.Name = "Test";
  Assert.Equals("Test", client.Name);
Not completely of course, but you get the gist. It's perfectly fine to test a big chunk of your code (a unit, if you will) in one go so that it implicity tests a lot of the details. The main thing is to avoid touching all sorts of dependencies outside of this unit and that's why you typically isolate database and filesystem access if you're testing business logic, for instance.

We literally have hundreds of those kinds of tests (exactly testing auto-props or similarly redundant tests), it drives me up a wall. I think I've generally convinced people they're a waste of time but they still sneak up every now and then, including the huge backlog of old tests.

"Does .NET work? Yes? OK, good, moving on!"

Mr. Crow
May 22, 2008

Snap City mayor for life
Probably let your unmanaged code manage the memory?

Mr. Crow
May 22, 2008

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

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

UberJumper posted:

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

Everything i see seems to have insanely long method names.

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

e.g. Butts_HasFooAndCanFoo_ReturnsBar

Mr. Crow
May 22, 2008

Snap City mayor for life
I'm getting a really bizarre log4net issue, I'm wondering if anyone has any ideas. Basically, when the (WPF) application loads up, it log4net loads its configuration context from the application config file correctly as expected; then at some point its configuration is switched to an entirely different applications configuration (Box Sync, in this case). Somehow Box Sync starts hijacking the log4net logs and my applications logging is getting dumped into a Box Sync log.

The hell?

Mr. Crow
May 22, 2008

Snap City mayor for life
Any ideas why I'm getting a 'Cannot access a closed Stream.' here?

code:
            var script = Task.Factory.StartNew(() =>
                {
                    using (var errorMemoryStream = new MemoryStream())
                    using (var outputMemoryStream = new MemoryStream())
                    using (var errorStream = new StreamWriter(errorMemoryStream, Encoding.Unicode) {AutoFlush = true})
                    using (var outputStream = new StreamWriter(outputMemoryStream, Encoding.Unicode) {AutoFlush = true})
                    {
                        // Redirect the output while the .exe is running
                        Console.SetError(errorStream);
                        Console.SetOut(outputStream);

                        try
                        {
                            // TODO: See if it's possible to run the .exe in its own appdomain and unload when done and still have debugging support etc.
                            // Run the .exe with the specified script arguments, returning the result.
                            return AppDomain.CurrentDomain.ExecuteAssembly(ExecutableDirectory + $"/{Common.ConsoleFileName}", _arguments.ToArray());
                        }
                        finally
                        {
                            // Assign the standard outputs to the stderr and stdout properties, to be verified in tests.
                            stderr = Encoding.Unicode.GetString(errorMemoryStream.ToArray(), 0, (int)errorMemoryStream.Length); // Throws here
                            stdout = Encoding.Unicode.GetString(outputMemoryStream.ToArray(), 0, (int)outputMemoryStream.Length);

                            // Set the output back to the default streams.
                            Console.SetError(StandardError);
                            Console.SetOut(StandardOut);
                        }
                    }
                }, _cts.Token);
I'm calling script.Wait() somewhere else and it's blowing up as it finishes. This code was working for the longest time, I've been fixing a bunch of static app-state related logic in the appplication and the last thing I did was remove a bunch of singletons... which should have had no impact on this specific block of code.

Edit: the actual error and output streams aren't being Disposed, just the base memory streams for some reason?

Mr. Crow fucked around with this message at 18:09 on Jan 14, 2016

Mr. Crow
May 22, 2008

Snap City mayor for life
So I guess the issue is the order in which things were getting disposed, calling the constructor with
code:
new StreamWriter(errorMemoryStream, Encoding.Unicode, 1024, true)
(the last parameter, leaveOpen, is the key) solved the issue.

I wonder if Console was doing something to dispose the StreamWriter in the other .exe or if the finally's were being fired in a weird order...

Mr. Crow
May 22, 2008

Snap City mayor for life

dougdrums posted:

What should the syntax
code:
=()=>
be called???

as in
code:
{ var x = 2; Func<int> a =()=> 10 * x; }

Nothing, it's just an assignment.

Mr. Crow
May 22, 2008

Snap City mayor for life

The Wizard of Poz posted:

It's not "just an assignment".

= is the assignment operator.
() => is the beginning of a Lambda expression.

Oh okay​, I thought you could assign expressions to variables, looks like I was mistaken, thanks for the clarification.

:cheers:

Also

uncurable mlady posted:

it's called a 'code smell'

Mr. Crow fucked around with this message at 21:54 on Mar 14, 2017

Mr. Crow
May 22, 2008

Snap City mayor for life
I find serialization is effortless until it isn't and then it's a huge pain in the rear end, so have some solace there.

Usually if you're having problems try and make it simpler and get the basic value types into a class then start building from there.

Lists and complex types are always hit and miss depending on which serialization library you're using.

Adbot
ADBOT LOVES YOU

Mr. Crow
May 22, 2008

Snap City mayor for life
What's the recommend gut check online test website for c# these days? (From a managers perspective)? Is interview mocha any good?

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