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
Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
I really like what async/await gives you, but I do agree that there are some nasty hidden gotchas. My main complaint is that you're not able to easily call an async method synchronously. Doing that is basically a recipe for deadlocks, but what option do I have if I'm not running in an async ready context (e.g. console app)? This forces most libraries to expose both synchronous and asynchronous method calls which just pollutes their APIs. If calling asynchronous methods synchronously was easy then we could get rid of this silly *Async duplicate method convention and just expose async methods.

Adbot
ADBOT LOVES YOU

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

Newf posted:

Here's a real easy ASP.NET question for everyone. I'm trying to display a list of strings in a ListView, but the examples I'm working from all work from all bind to properties of the bound objects rather than the objects themselves. EG, the //what goes here line is expressed using something like <% #Eval("PropertyX") %>. How do I display the bound object itself (they're just strings!).

Should just be able to use <%# Container.DataItem %>

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
Don't use a for-loop and don't use Response.Write in your ASPX page. Use another repeater bound to States, instead.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

Newf posted:

To follow up on this... The context here is that I'm making a web front-end that interfaces with a windows service which exposes a bunch of controls exposed via [ServiceContract] class and [OperationContract] methods. I'm using svcutil.exe to generate the client class for the webapp.

I understand that webforms are maybe on the way out, but they do seem like the simplest tool that's adequate for the job. Nothing super fancy will be going on - mostly CRUD interaction and configuring the windows service. Am I wrong about this? Are there reasons that I'd be better off going for an MVC2 app? (VS2010)

Web Forms is terrible and will almost never end up being the simplest tool for the job. As you already saw, something as simple as adding an <li> element for every item in a list isn't intuitive. The "event" structure of Web Forms is a misguided attempt to make the web like the desktop which ends up making everything inefficient. If there's nothing forcing you to use Web Forms, use MVC.

And if you can help it, don't use MVC2. Get the latest VS you can get your hands on and use the latest version of MVC.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

Ciaphas posted:

I have data I need to process with record times at nanosecond resolution (specifically, measured in nanoseconds since the start of the year the data was recorded in, stored as uint64). For now I just need to turn it into a human-readable date and time, like 2012 May 28 11:35:58.000045921 (edit: adjustments will need to happen later, but that's not an immediate requirement). I figured at first (being a .NET and C# newbie) that DateTime would be able to do it with some finagling, but I guess from google that it only can store down to the microsecond, chopping off the 921 nanos at the end there. (Apparently they're important. :shrug:) (edit: or is it 0.1 microsecond? Anyway still two digits short in that case)

Do I have any options short of, say, making the DateTime with the microsecond precision out of the uint64 nanos, ToString()ing it, and just tacking nanos % 1000 to the end of the string? Strikes me as maddeningly clunky, even if it'd work for now.

DateTime precision only goes down to the 100 nanoseconds. If you just want to use the built-in formatting DateTime formatting options, then I would say to make a class that wraps DateTime (e.g. PreciseDateTime) to delegate .ToString() calls and use whatever level of precision you need.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
SignalR groups might be able to do what you need, but I imagine you would want to handle choosing which client to send updates to yourself. Groups don't scale as well as users do, and I imagine you would have to set up a group for each ticker which users would join if they want subscriptions. With stocks, that means you'd have a ton of groups.

You should be able to use the PersistentConnection API to send messages to individual clients. You'll have to manually keep track of who should be receiving updates depending on the data, but this should work better than having the client subscribe to a large number of groups.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

Betjeman posted:

You'll need to override Equals I think

This is correct. HashSet first checks the hash, then checks for equality using the specified equality comparer (which will most likely be EqualityComparer<T>.Default which uses .Equals()).

But yeah, you should probably be using a Dictionary.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

Newf posted:

It's really not a complicated issue, and either implementation works, I think. I've left it as it because the Equals override was only a couple of lines and I'd rather not have to wrap my Adds in Try/Catch blocks.

The initial problem is to keep a list of objects (they're boats, incidentally) who have requested a service. Each boat, after requesting service, will receive a default service until the service is configured (server side) for them by an administrator. I just want to keep a list of boats who have requested service but remain unconfigured. I also want the dates at which they first requested service. So the bean is just a unique identifier for the boat (the key in my problem), the boat's "common name", and the date of the service request. It's possible for a boat to make several service requests before the administrator configures them, but I don't want double/triple/ ect records of that.

Personally, I'd use a Dictionary and check .ContainsKey before insertion, but I don't think there's a functional difference. It just seems more appropriate to me to use a Dictionary when you're working with keys and values.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
It doesn't help that there's no definitive library method for combining hash codes. Tuple<T1, T2> uses this:

C# code:
internal static int CombineHashCodes(int h1, int h2) { 
    return (((h1 << 5) + h1) ^ h2);
} 

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

GrumpyDoctor posted:

If I'm inheriting from an abstract class, is there really no way to make one of the overridden properties more accessible without essentially duplicating it?

Use the new keyword and make a call to base.SomeMethod? It's still essentially duplication, but you get to keep the same name.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
Ah, if you're implementing an abstract method/property then no you can't change access rights.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

Geisladisk posted:

Does anyone have any tips for streamlining Windows Service development?

I started working on a large, mature system two months ago, which runs on a fairly baffling ecosystem of virtual machines. Most of these VMs are running windows services, which I need to develop.

I've got batch scripts that, whenever I recompile a particular service, automatically uninstalls it, copies the new files to the VM, reinstalls the service, and then starts it. I then attach the debugger to the process running on the VM if I need to debug. This is all fairly nice, but the process still feels very unweildy, and compiling and running the code takes up to a minute, which is frustrating me more than it should.

Are there any ways to streamline this process that I haven't noticed? I'm running visual studio 2012 pro, but I can get a upgrade to 2013 pro if needed.

Take all of your interesting code and put it in a separate project, then debug through a console app? This will work if you can test on your dev machine and not have to deploy to a VM.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
I've used predicate builder for a few things and it worked quite nicely, never the full LINQKit though.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

Newf posted:

I'd like to know what gets spit out by Path.GetInvalidFileNameChars(). Is there a more reasonable thing for me to do than boot up a new console app and print them to screen? I feel like Visual Studio should have some sort of console that I can type commands like this into.

Unfortunately there's not an easily accessible C# REPL yet. You could use the F# interactive console in Visual Studio:

code:
> open System.IO;;
> Path.GetInvalidFileNameChars();;
val it : char [] =
  [|'"'; '<'; '>'; '|'; '\000'; '\001'; '\002'; '\003'; '\004'; '\005'; '\006';
    '\007'; '\b'; '\009'; '\010'; '\011'; '\012'; '\013'; '\014'; '\015';
    '\016'; '\017'; '\018'; '\019'; '\020'; '\021'; '\022'; '\023'; '\024';
    '\025'; '\026'; '\027'; '\028'; '\029'; '\030'; '\031'; ':'; '*'; '?';
    '\\'; '/'|]

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
Congratulations, you now know functional programming!

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
Chiming in here about the awesomeness of React. It's a breath of fresh air in the poo poo-filled world of frontend JS frameworks. The .NET shop I work at has picked it up for a few things and is absolutely loving it. My biggest gripe, however, is the complete lack of syntax support (even through plugins) in Visual Studio for JSX.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

Volte posted:

I'm using it for exactly that and it's basically the best thing ever, as long as you can afford the price tag (or can get the student discount). Definitely look at MvvmCross, and avoid Xamarin.Forms since it is still basically alpha-quality software despite the production status.

I'm using Xamarin + MvvmCross on a sizable education-related project right now and I've been really impressed at how well it all works together. If you want to learn MvvmCross, definitely take a look at the N+1 series of videos by the creator/maintainer of the project.

Regarding the demo version, I don't really know how capable it is since we just dove in and bought a subscription. So far, though, it's been completely worth it.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

Dietrich posted:

You ever finish something really complex and want to throw up your hands and cackle "It's alive!!" the first time it runs?

I usually just get worried about which obvious thing I might have screwed up this time.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

quote:

The initializer directly initializes the underlying field – it doesn’t go through the setter. For that reason, it is now meaningful to allow getter-only auto-properties:

public int Y { get; } = y;

For getter-only auto-properties, we would generated the backing field as readonly.

This seems like a halfway solution to what I really want, which is true readonly (as in the access modifier) properties that are settable through the constructor, e.g.:

C# code:
public class A
{
    public int Y { get; readonly set; }
    // OR
    public readonly int Y { get; }

    public A(int y)
    {
        Y = y;
    }
}
It seems that with their suggestion, to do this you'd still have to use a readonly backing field and getter-only manual property.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

Mr Shiny Pants posted:

The new Identity stuff in MVC 5 is complex.

We attempted to use it for a recent project, but ultimately we threw it out and rolled our own like we have done for years. I wish MS would get away from trying to provide the "one identity solution to rule them all" and instead just provide sane defaults for password hashing, password requirements, and default functionality for email validation, password resets, and the like.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
Before I go off writing my own C# bindings for Cairo, does anyone know of a half-decent way of generating EPS files in .NET?

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

mortarr posted:

Does anyone have or know of a .net wrapper for ghostscript, or some other free pdf library?

I'm trying to render single pages to png using imageresizers' pdf renderer, but I've got some kind of wierd pdf that is causing it to fail, and I want to get to grips with what's causing my failure without going through the imageresizer pipeline.

GhostScript.NET: https://github.com/jhabjan/Ghostscript.NET

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
Note that if you're dealing with multiple web servers, caching and cache invalidation becomes a harder problem. However, with just one web server you can either use something as simple as static variables (with thread-safe access), or possibly use the built-in ASP.NET caching.

See:
http://msdn.microsoft.com/en-us/library/vstudio/ms178597%28v=vs.100%29.aspx
http://msdn.microsoft.com/en-us/library/vstudio/18c1wd61%28v=vs.100%29.aspx

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

Dr. Poz posted:

Mvc Question

My action method takes an int but if a jerk types in a string they get send to a runtime error page. I'd much rather send them to an error page of my design. What's the best way to handle parameter validation of this fashion for action methods?

Use int? and check for nulls.

Optionally, if you just want to send them to a custom error page without any special message, use the <customErrors> tag with a redirect in the web.config.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
Sounds very similar to Event Sourcing to me. Changes to the model are described as events, and those events are applied in order. Events can be written to a database or queue extremely quickly and then processed separately. The end result is high scalability at the expense of immediate updates.

You probably won't find too many libraries for this since the events are highly specific to your domain model. Also, for the vast majority of the time you can get away with simple CRUD anyway.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

gariig posted:

InitClass will be called at startup because the runtime wants to create the variable initialized. It sounds like you want Lazy<T>. Without a better sample it's hard to say if this is good or bad. I'd lean toward not doing it because it's hard to mock out or hide static anything during a unit test.

Jon Skeet has a useful post on static variables and initialization:

http://csharpindepth.com/Articles/General/Beforefieldinit.aspx

Long story short, if you really want to continue using statics to do a lazy check, add a static constructor and initialize your variable there. In general, though, it's better to not try to rely on edge case scenarios of the CLR for lazy loading and just implement it yourself. Use Lazy<T> or maybe something like:

C# code:
class Foo
{
    private static bool? _initialized;
    private static bool Initialized
    {
        { get { return _initialized ?? (_initialized = InitClass()).Value; } }
    }

    private bool InitClass() { return true; }
    // ...
}

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

ljw1004 posted:

Wait, what? That's not what the link says. It says:

In practice, the JIT compiles a method only at the first time the method is invoked. At that moment it first chases down every type that's touched by the method, and ensures they're all loaded. The type-load process will invoke all static constructors (hence, will initialize all static variables).

I don't know when static constructors are invoked in ProjectN (native compilation of C#)

I don't think that's completely true. See this other Jon Skeet link about what happens without an explicit static constructor:

http://codeblog.jonskeet.uk/2010/01/26/type-initialization-changes-in-net-4-0/

EDIT: Though you are correct that it won't necessarily be called at startup.

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.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
I've never really liked switching on/off timers if it wasn't necessary. It always seemed kind of janky to me. I would probably just leave the timer running and then perform some check in the callback to see if it should early return. That way you have control over any locking you might need to perform for the check, etc. instead of just depending on the timer's Enabled property.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

NoDamage posted:

Have not found a good solution for (2) yet, but I am starting to get the impression that people just Refresh() their data when changes occur out-of-band from the UI. Is there no better way?

I'd say do this until you have a good reason not to (e.g. performance) since it makes the code a lot simpler. In most applications, you're just not going to run into that performance wall. Computers are faster than you think.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

Mr. Crow posted:

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.

I once spent an hour combing through VS bug reports trying to figure out why my loving tests in one single file wouldn't run. My co-worker pointed out that my class wasn't public. :doh:

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

IdentityMatrix posted:

Not sure where that event handler is hooked up, but are you unhooking the event handler when shutting everything down? And have you tried pw.Show() instead of pw.ShowDialog() or would that impact the execution path?

ShowDialog() vs Show() shouldn't make a difference in WPF. However, I bet there is still a dangling event handler somewhere around there.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

Ithaqua posted:

It feels wrong, but I can't express what's so wrong about it.

I hate the ever-living poo poo out of it, but I also have an imbalanced dislike of dynamic in general. As Destroyenator said, you have a public interface with a lack of compile time type/typo checking. You could use Tuple to gain those benefits, but the code is still ugly with .Item1, .Item2. I feel like there's a happy medium that should exist in the language that's best described as "public anonymous types" or maybe "structural types" in the loosest sense of the term. Though this is all rehashing old discussions.

In your case, I would probably just define a public class nested in the class that is spawning the event. If it's only used in that specific case, then there's no need to clutter your namespace with the event definition. This goes directly against being a lazy jerk, though.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

Drastic Actions posted:

EDIT: Oh yeah, this might be a good place for this.

VLC needs more people for the VLC WinRT port. Right now there is really only one person working full time on it. The codebase, while not as bad as it was a few months ago when I first saw it, still needs to be refactored quite a bit.

I've been working on it off and on for a few months now. They are getting ready to release an updated 8.1 app, and it actually works pretty well (considering how poor the first version was, that's not saying much, but still :v:). If any of you are up for a challenge, and have worked on Windows Phone/Windows 8 apps before, it's a good way to get involved in a huge open source project.

I looked through the recent commits and read some of the code, but I was trying to find some low hanging fruit to go after that would actually be warranted. Is there a list of goals or bugs specifically for the WinRT version? I briefly browsed their bug tracker but the different milestones didn't seem terribly relevant.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
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.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

Mr. Crow posted:

Missed opportunity to :justpost:

:smith: I am ashamed.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

GrumpyDoctor posted:

edit: There had better be a better way to do this, as I am apparently unable to actually catch this exception. No matter where I put try/catch blocks, the exception slips through and brings my app down.

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?

Bognar fucked around with this message at 14:38 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?

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

darthbob88 posted:

That might do it, but I don't understand async that well. I don't suppose I can get a demonstration, just a toy program?

ETA: I think I might get it. You're suggesting three StreamWriters to write to three files, with asyncs and awaits to keep them vaguely in sync. That'd work, but what I really wanted was something that'd let me do
code:
using (var comicsLog = File.CreateText(file1, file2, file3)) {comicsLog.Write(things)}

C# code:
public class MultiFileWriter
{
    public Task WriteFilesAsync(byte[] data, params string[] files)
    {
        var tasks = files.Select(f => WriteAsync(data, f));
        await Task.WhenAll(tasks);
    }

    private Task WriteAsync(byte[] data, string path)
    {
        using (var fs = new FileStream(path, FileMode.Create))
        {
            await fs.WriteAsync(data, 0, data.Length);
        }
    }
}
Bugs + typos may exist, code from the internet warnings still apply.

Adbot
ADBOT LOVES YOU

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

mortarr posted:

If you're after optional conditions in the where clause, there's always predicate builder.

I highly recommend this library. I've used it in a few places when dynamically building expression trees and it's always worked as expected.

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