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
NT Plus
Nov 30, 2011

Kid just rages for a while.
Not sure if this is the right place but here we go...

Hey guys. So.... I usually do Help Desk work. But today my boss decided to throw me into VB. First he wanted me to create a button that says "Hello World." After some finagling, I found the code for this somewhere and just brute forced a series of copy/paste til I got it right. :toot:

Now he wants me to make a ListBox that shows file info for any given folder.

I don't know if this is how everybody learns Visual Basic and I'm pretty sure I can't just brute force my way through VB.NET forever.

Can anyone point me in the right direction to learn how to do this? Maybe books I should buy or links I should see? I've been plugging lines of code for like 2 hours and somehow I feel like I'm not getting the true coders' experience.

Adbot
ADBOT LOVES YOU

Inverness
Feb 4, 2009

Fully configurable personal assistant.
1. Use C# instead of VB.NET if at all possible.

2. Find a VB.NET tutorial and actually do it. Just Google for "VB.NET tutorial". Copy-pasting code without understanding it is literally the worst possible thing you could do.

3. Attempt #1 again.

epswing
Nov 4, 2003

Soiled Meat
The True Coders' Experience

:negative:

Quit while you're ahead!

Ninja Edit: I'm kidding! I'm.. 80% kidding!

RICHUNCLEPENNYBAGS
Dec 21, 2010

Inverness posted:

1. Use C# instead of VB.NET if at all possible.

The difference between them is extremely small to be honest but C# pays considerably better for whatever reason so this is probably still good advice.

Kekekela
Oct 28, 2004

RICHUNCLEPENNYBAGS posted:

The difference between them is extremely small to be honest but C# pays considerably better for whatever reason so this is probably still good advice.
e: I ended up writing a novel because as old fucks do I got all nostalgic while writing this


The reasons for the pay divide probably trace back to the origins of the languages. C# was developed from the ground up to be the flagship .NET language. VB.NET was thrown in to mollify the hoards of desktop VB6 programmers that were freaking out because the (at that time lovely as gently caress) ecosystem was changing.

C# borrowed heavily from Java which made switching to the dark side a way more attractive option for Java devs (who at that time were driving most innovations in design patterns et al for the business developer community), as you could now write a desktop app in a nice statically type language that didn't look and feel like a lovely java app This also united the guys on the MSFT side that until that point had been stuck writing C++ (which was overkill and bug-prone for a lot of business apps), with those of us that were writing VB6 apps but knew they sucked.

As a result the vast majority of new development began happening primarily in C#, while VB.NET kind of became stigmatized as what the troglodytes who didn't want to leave their comfort zone were sticking with. This wasn't helped by persistent and recurring rumors that VB.NET was either going to go away or become barely supported at any moment (when ironically it ended up getting some nice goodies along the way) for the first few years of .NET.

So the new hip libraries being ported from java were being written in C#, code samples from the luminaries of the day were appearing in C#, developers were wanting to work in C# because it was so clean (funny to think back on now), etc etc. Of course this all ends up leading to starting new projects in C# and then having to hire C# devs and the circle continues. Anyway, this concludes my thesis, thank-you for bearing with me for this walk down memory lane.

OneEightHundred
Feb 28, 2008

Soon, we will be unstoppable!
My new favorite thing in .NET is that it had an implementation bug that allowed the "no implementing interfaces that could be duplicates after type substitution" rule to be bypassed, a big corporate user got pissed when they patched it out, so they put it back in and now there are 4 pages in the standard dedicated to supporting it.

:suicide:

code:
public interface IIfc<T> { void Func(T p); }

public class Base<T> : IIfc<T> { void IIfc<T>.Func(T p) { Console.WriteLine("Base"); } }

public class Derived<A, B> : Base<A>, IIfc<B>
{
    void IIfc<B>.Func(B p) { Console.WriteLine("Derived"); }

    public void CallA(A p)
    {
        IIfc<A> ifc = this;
        ifc.Func(p);
    }
}

static void Main(string[] args)
{
    (new Derived<int, object>()).CallA(0);
    (new Derived<int, int>()).CallA(0);
}
code:
Base
Derived

mortarr
Apr 28, 2005

frozen meat at high speed

OneEightHundred posted:

My new favorite thing in .NET is that it had an implementation bug that allowed the "no implementing interfaces that could be duplicates after type substitution" rule to be bypassed, a big corporate user got pissed when they patched it out, so they put it back in and now there are 4 pages in the standard dedicated to supporting it.

:suicide:

code:
public interface IIfc<T> { void Func(T p); }

public class Base<T> : IIfc<T> { void IIfc<T>.Func(T p) { Console.WriteLine("Base"); } }

public class Derived<A, B> : Base<A>, IIfc<B>
{
    void IIfc<B>.Func(B p) { Console.WriteLine("Derived"); }

    public void CallA(A p)
    {
        IIfc<A> ifc = this;
        ifc.Func(p);
    }
}

static void Main(string[] args)
{
    (new Derived<int, object>()).CallA(0);
    (new Derived<int, int>()).CallA(0);
}
code:
Base
Derived

Looks confusing, what's the benefit / what cunning tricks can you do with this, that couldn't be done before?

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

mortarr posted:

Looks confusing, what's the benefit / what cunning tricks can you do with this, that couldn't be done before?

Write confusing code that's hard to maintain.

OneEightHundred
Feb 28, 2008

Soon, we will be unstoppable!

mortarr posted:

Looks confusing, what's the benefit / what cunning tricks can you do with this, that couldn't be done before?
If I had to guess, since the huge blow-up that involved a person spamming like 20 different sites with the Connect link complaining about it getting patched out happened circa .NET 3.5, it was probably a "clever workaround" for variance not being a language feature yet.

e: Go read II.12.2 of the standard if you want some fun, it's basically a big list of bugs-that-are-now-features, including rules for implementing duplicated methods, rules for when an interface should be matched by variance even when an exact match exists, and rules for how an inexactly matched generic virtual method should cause an interface method to dispatch different implementation methods depending on the type parameters.

OneEightHundred fucked around with this message at 16:42 on Feb 23, 2016

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

OneEightHundred posted:

If I had to guess, since the huge blow-up that involved a person spamming like 20 different sites with the Connect link complaining about it getting patched out happened circa .NET 3.5, it was probably a "clever workaround" for variance not being a language feature yet.

It's one of the reasons the open source Roslyn code is so interesting to read. There are tons of comments saying "this section implements part 3.5.1.33 of the spec, but it has to violate the spec in ways X, Y, Z in order to retain backwards compatibility"

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 an MVC5 project that I'm working on that, after receiving a file upload, has to notify a person by email that the upload has occurred. I want to hand this off to a separate process so that the user can get the HTTP response back and continue on their way without waiting for the email to send, since it's not a critical part of the process from the user's point of view and there's no reason they should wait.

I think the key lies in the asynchronous features of C# but I have literally no exposure to this and I don't really have the time to fully grok it right at this moment. What I kind of need for now is a basic introduction with maybe a clear example - does anyone know a good resource for this?

Calidus
Oct 31, 2011

Stand back I'm going to try science!

The Wizard of Poz posted:

I have an MVC5 project that I'm working on that, after receiving a file upload, has to notify a person by email that the upload has occurred. I want to hand this off to a separate process so that the user can get the HTTP response back and continue on their way without waiting for the email to send, since it's not a critical part of the process from the user's point of view and there's no reason they should wait.

I think the key lies in the asynchronous features of C# but I have literally no exposure to this and I don't really have the time to fully grok it right at this moment. What I kind of need for now is a basic introduction with maybe a clear example - does anyone know a good resource for this?

I did something similar with a console app and a SQL table that I treated like a Queue. Every time the MVC site needs to send an email to just write a row to the table. Then I the console app was setup to run every X minute(s) via the task scheduler. It is nothing fancy but works well, and the separation is nice for troubleshooting.

raminasi
Jan 25, 2005

a last drink with no ice

GrumpyDoctor posted:

The VS2015 debugger has decided to stop breaking on thrown exceptions, even though "Break when thrown" is turned on for all CLR exceptions. "Just my code" is also disabled, although it doesn't break when my code throws exceptions, either. Any ideas?

Quoting myself because I've at least figured out a workaround: not using <All Common Language Runtime Exceptions Not On This List>. I just enabled them all manually. Hooray!

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

Calidus posted:

I did something similar with a console app and a SQL table that I treated like a Queue. Every time the MVC site needs to send an email to just write a row to the table. Then I the console app was setup to run every X minute(s) via the task scheduler. It is nothing fancy but works well, and the separation is nice for troubleshooting.

Hmm okay. I was hoping there was some way I could use async/await to avoid having to wait for the email to send, but I'm not sure if maybe I've misunderstood what they're for.

Potassium Problems
Sep 28, 2001

The Wizard of Poz posted:

I have an MVC5 project that I'm working on that, after receiving a file upload, has to notify a person by email that the upload has occurred. I want to hand this off to a separate process so that the user can get the HTTP response back and continue on their way without waiting for the email to send, since it's not a critical part of the process from the user's point of view and there's no reason they should wait.

I think the key lies in the asynchronous features of C# but I have literally no exposure to this and I don't really have the time to fully grok it right at this moment. What I kind of need for now is a basic introduction with maybe a clear example - does anyone know a good resource for this?

I've been using Hangfire for stuff like this, and for scheduled tasks.

example:

code:
BackgroundJob.Enqueue<MailService>(service => service.FileUploaded("recipient@domain.com"));
It requires a database for job storage though, so it might be overkill depending on what your app is doing.

RICHUNCLEPENNYBAGS
Dec 21, 2010

The Wizard of Poz posted:

Hmm okay. I was hoping there was some way I could use async/await to avoid having to wait for the email to send, but I'm not sure if maybe I've misunderstood what they're for.

That's not really what they're for, no. I guess you could use an async method and not await it but that's not really advisable IMO.

EssOEss
Oct 23, 2006
128-bit approved
Sure you can, that's totally normal, just not the "general case" which is a fork and join in logic, like this:



But it's totally fine to actually never await, if you never need to join up the logic flows again. You can simply use Task.Factory.StartNew() to kick off some code to be run independently and forget about it.

Here is my go-to code for starting long-running (= more than a few milliseconds) tasks in the background, for cases where I do not care about awaiting:

code:
Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);

raminasi
Jan 25, 2005

a last drink with no ice
You can just use Task.Run (as long as the long-running flag isn't important to you, which it seems like it shouldn't be unless you've specifically profiled)

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug
You shouldn't do either of those in a web application since long-running threads are subject to arbitrary cancellation by the web server.

Cuntpunch
Oct 3, 2003

A monkey in a long line of kings
Speaking of async/await, outside a web context, I'm used to older .NET approaches to background tasking(Tasks directly/workers/etc) - I'm briefly curious if I'm completely missing something or whether the async/await pattern really does have to be applied to an entire callstack to fulfill its purpose?

For the sake of an example, let's say you're just trying to enumerate a highly populated directory across a network when the user clicks a button:
1. Event handler
2. Manipulation logic
3. Directory enumeration

Logically it's just that final step that's actually needing to be broken out of and returned to upon completion, but then the calling method needs async so that *it* can use await, but then if the first method which started this chain doesn't await *it*, then doesn't the stack pretty much run synchronously(which could cause UI freeze)? Which necessitates it, too, being async.

It seems like it ends up...infecting the entire codebase with async methods - is that actually the intention or am I missing some critical understanding?

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Cuntpunch posted:

It seems like it ends up...infecting the entire codebase with async methods - is that actually the intention or am I missing some critical understanding?

That is correct and that is the expectation. Behind the scenes, each "await" keyword basically turns into a step in a big state machine that the compiler generates. Your code turns into something that instead of returning concrete objects, returns a Task which indicates "I'm working on getting you the thing you asked for, come back later when I have it". So control goes back to the UI (or the thread goes back to the thread pool in a web app), and the state machine picks up where it left off when the task is done.

It's not a good idea to try to use async code synchronously -- you can call "task.Result" or "task.Wait()", but that has potential for deadlocks, especially in UI applications.

New Yorp New Yorp fucked around with this message at 14:36 on Feb 24, 2016

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

The Wizard of Poz posted:

Hmm okay. I was hoping there was some way I could use async/await to avoid having to wait for the email to send, but I'm not sure if maybe I've misunderstood what they're for.

That's not what async/await is for, and you could accomplish that task without async/await. However, I would still recommend using the database or a durable queue for email. For one, it makes it much easier to implement retry logic for when the email inevitably has a transient failure for one reason or another. Plus it gives you a nice place to store potential exceptions related to sending that email. Sure you could do all of this in-process and with log statements, but email is finicky enough that it's useful to have a single table aggregating all this information.

Also, as Ithaqua said, there's no guarantee that code will continue to execute once it is detached from a Request in ASP.NET (e.g. if the Request is closed before your email is sent - exactly what you're trying to accomplish).

chippy
Aug 16, 2006

OK I DON'T GET IT
Is there an 'out of the box' way do do a NumericUpDown type control in the MVC framework? I'm sure I've done it before, but I can't remember how.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

chippy posted:

Is there an 'out of the box' way do do a NumericUpDown type control in the MVC framework? I'm sure I've done it before, but I can't remember how.

<input type="number"/> works in good browsers, but that's not useful if you're trying to support IE.

Opulent Ceremony
Feb 22, 2012

Ithaqua posted:

You shouldn't do either of those in a web application since long-running threads are subject to arbitrary cancellation by the web server.

This is correct and the current built-in suggestion for ASP.NET with .NET 4.5.2+ is QueueBackgroundWorkItem

Drastic Actions
Apr 7, 2009

FUCK YOU!
GET PUMPED!
Nap Ghost
Cool stuff incoming, this will be awesome.

https://twitter.com/scottgu/status/702568545763225600

Malcolm XML
Aug 8, 2009

I always knew it would end like this.

took them long enough

raminasi
Jan 25, 2005

a last drink with no ice
How much trouble can I get into by doing something like this
C# code:
void Foo(int[] firstArray, int[] secondArray)
{
    Parallel.For(0, firstArray.Length, i =>
    {
        var x = CalculateSomethingFrom(firstArray[i], secondArray[i]);
        secondArray[i] = x;
    });
}
i.e. reading and writing to arrays in parallel, but with no task touching any other task's "part" of the arrays.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

GrumpyDoctor posted:

How much trouble can I get into by doing something like this
C# code:
void Foo(int[] firstArray, int[] secondArray)
{
    Parallel.For(0, firstArray.Length, i =>
    {
        var x = CalculateSomethingFrom(firstArray[i], secondArray[i]);
        secondArray[i] = x;
    });
}
i.e. reading and writing to arrays in parallel, but with no task touching any other task's "part" of the arrays.

quote:

Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

You're not enumerating the collection being modified, so you're safe from exceptions, of course. But arrays aren't thread-safe. Use a thread-safe collection just to make life easier on yourself or whoever modifies the code to do something else that suddenly makes it have a race condition.

raminasi
Jan 25, 2005

a last drink with no ice
I thought that was specifically pertaining to the use of enumerators, which I'm not doing.

e: I'm just wondering whether I can replace a for loop with a Parallel.For, #pragma OMP style. There's nothing fancier going on.

Inverness
Feb 4, 2009

Fully configurable personal assistant.

GrumpyDoctor posted:

How much trouble can I get into by doing something like this
C# code:
void Foo(int[] firstArray, int[] secondArray)
{
    Parallel.For(0, firstArray.Length, i =>
    {
        var x = CalculateSomethingFrom(firstArray[i], secondArray[i]);
        secondArray[i] = x;
    });
}
i.e. reading and writing to arrays in parallel, but with no task touching any other task's "part" of the arrays.
Should be perfectly fine since, as you say, each thread is handling a different section of memory.

EssOEss
Oct 23, 2006
128-bit approved

Ithaqua posted:

You shouldn't do either of those in a web application since long-running threads are subject to arbitrary cancellation by the web server.

I would like to learn more. Can you point to some documentation about this?

Mr Shiny Pants
Nov 12, 2012
Looks like MS just took over Xamarin.....

http://blogs.microsoft.com/blog/2016/02/24/microsoft-to-acquire-xamarin-and-empower-more-developers-to-build-apps-on-any-device/

Edit: beaten....

I hope they keep Mono as it is, dot net core can go suck a bag of dicks......

Mr Shiny Pants fucked around with this message at 09:24 on Feb 25, 2016

Gul Banana
Nov 28, 2003

Ithaqua posted:

You're not enumerating the collection being modified, so you're safe from exceptions, of course. But arrays aren't thread-safe. Use a thread-safe collection just to make life easier on yourself or whoever modifies the code to do something else that suddenly makes it have a race condition.

this is superstition, that code is correct. "thread-safe" collections don't exist in the general sense; parallel data structures have apis which encourage or require you to implement algorithms differently, in ways which are more likely or guaranteed to be threadsafe.

if your algorithm is "in parallel, for each pair of elements, update the second based on the first" then there is no better data structure than an array. System.Collections.Concurrent doesn't have a ConcurrentList or anything because there would be no point - index-accessing operations are inherently unsafe unless the algorithm guarantees, out of band, that segment accesses are disjoint.

if the Parallel.For did need to modify arbitrary element indexes, the way to achieve this would be a monitor (lock statement), not a special data structure. since it doesn't, there's no need for synchronisation at all.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

EssOEss posted:

I would like to learn more. Can you point to some documentation about this?

http://www.hanselman.com/blog/HowToRunBackgroundTasksInASPNET.aspx

metztli
Mar 19, 2006
Which lead to the obvious photoshop, making me suspect that their ad agencies or creative types must be aware of what goes on at SA

Do you have any other good references for asynchronous programming in .Net? You seem to know your poo poo and I'd love to find some good reads on the subject.

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

metztli posted:

Do you have any other good references for asynchronous programming in .Net? You seem to know your poo poo and I'd love to find some good reads on the subject.

Stephen Cleary like the whole blog is all about asynchronous programming in .NET plus his book is excellent. However, for The Wizard of Poz problem is asynchronous programming in general which usually involves queues (RabbitMQ, Azure Queue Service). Generally you are looking for publish/subscribe (pubsub) or producer/consumer models.

Ithaqua is a smart cookie

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

gariig posted:

Stephen Cleary like the whole blog is all about asynchronous programming in .NET plus his book is excellent. However, for The Wizard of Poz problem is asynchronous programming in general which usually involves queues (RabbitMQ, Azure Queue Service). Generally you are looking for publish/subscribe (pubsub) or producer/consumer models.

I grudgingly recommend Stephen Cleary, because he knows asynchrony in .NET inside and out. The grudging is only because he's an evangelical fundamentalist who proselytizes every chance he gets and it really rubs me the wrong way.

I saw him speak at a conference once and he opened up his talk with a bit about how he "knows [he's] going to heaven" which I found really distasteful. It's even in his SO profile.

metztli
Mar 19, 2006
Which lead to the obvious photoshop, making me suspect that their ad agencies or creative types must be aware of what goes on at SA
^^ Edit: Bleh, he sounds obnoxious, but as long as he knows what he's talking about with asynchrony, I'll cope.

gariig posted:

Stephen Cleary like the whole blog is all about asynchronous programming in .NET plus his book is excellent. However, for The Wizard of Poz problem is asynchronous programming in general which usually involves queues (RabbitMQ, Azure Queue Service). Generally you are looking for publish/subscribe (pubsub) or producer/consumer models.

Ithaqua is a smart cookie

Thanks!

WoP, I did something similar in the past. For things that didn't require 100% reliability, I made a library to consume segment.io + customer.io integration and could just fire and forget the segment call + payload when a given event occurred. Useful and required minimal effort.

For things that required 100% (well, 99.99%) reliability, as suggested, a console app scheduled to run regularly against a db based queue to allow for try/retry worked very well. Also wound up setting an endpoint that our email provider (sendgrid) could hit to confirm that key emails had been successfully sent as well.

Adbot
ADBOT LOVES YOU

B-Nasty
May 25, 2005

The simple Azure queue is quite nice. It doesn't involve IT like setting up and managing MSMQ/Rabbit, and it's really easy to grasp. For any regular workload, it costs less than a cup of coffee a month to use.

I'd seriously consider if a simple queue meets your need before jumping into a full service bus architecture...those tend to spiral out of control if you don't really need the pub/sub model.

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