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
uXs
May 3, 2005

Mark it zero!

RangerAce posted:

What about setting up different users for each site and have the different sites use different app pools that run as different users? Then, you should be able to set ASPNET_ENV differently for each user.

Too much magic that just floats around and can't easily be seen by looking in (text) files.

Adbot
ADBOT LOVES YOU

SixPabst
Oct 24, 2006

EssOEss posted:

Edit: Control+T is also awesome.

I've tried, I really have, to like Resharper but I end up using it for about 2 hours before I get so immensely frustrated with how it grinds VS to a halt or tries to do everything for you. I am well aware that if I sat down and turned on only a few options that really work well it would probably be fine, but then at that point I wonder why I'm even using it at all.

RangerAce
Feb 25, 2014

uXs posted:

Too much magic that just floats around and can't easily be seen by looking in (text) files.

Understandable. FWIW, if you stick to the conventions (using values "Production", "Staging", "Development") you can avoid some of that brittleness. But short of putting your sites on different servers, not sure what else MS expects us to do. It does sort of have that old Microsoft smell to it. That odor of "THIS TECHNOLOGY IS AMAZING AS LONG AS YOU RUN YOUR WHOLE STACK EXACTLY THE WAY WE EXPECT YOU TO! HAVE YOU TRIED AZURE LATELY?"

thebruce
Jul 4, 2004

Not sure if this is the correct place to post this. I've heard about wpf forever and I've started to look into it. Most of the projects I have ever done have been winform apps for controlling hardware through com ports and the like. Nearly all of the wpf tutorials I come across are for customer based data driven applications. Is wpf only really suited for certain things, or should it replace winforms in almost every instance?


Also, when looking at examples of mvvm, the model seems to only be data structures, with business logic in the viewmodel. Does this not break encapsulation? The whole point of a class is to store both the data AND the methods that act on it, but mvvm seems to go against that. Does this make it harder to use existing code libraries?

Apologies if I'm getting the wrong end of the stick.

crashdome
Jun 28, 2011
Wpf really just replaces WinForms. Will it be around forever? I have no idea.

I'm an old school .Net dev like yourself. Most of my apps are COM/Serial based and I am using Wpf on new projects as of the past year or so. MVVM is just designed to separate BL from UI. Encapsulating "Button Click does this" in your Business Logic is now known as "you're doing it wrong" and all the skinny college kids coming in will laugh at you apparently. I find it actually has made my code more flexible and I feel like it'll be more future proof. I'm pretty much a small project developer though.

edit: I hate WinForms now. I look back at old stuff now and then and I really wish I could wave a wand and make it all Wpf/MVVM at least just for the sanity of not wrestling the UI to add more features.

another edit: I now develop on a laptop with something like 643200000 x 500684358 resolution and my text size up to 150x or 200x and all my winform apps go berserk. I've noticed my Wpf apps do not. Don't know what that means exactly but, just reinforces my relief I have moved on to something else.

crashdome fucked around with this message at 00:07 on Jun 19, 2015

rarbatrol
Apr 17, 2011

Hurt//maim//kill.

Space Whale posted:

Crossposting from the SQL thread since nobody there knows MSSQL.

How do I ensure ACID transactions? Are there keywords in a stored procedure? I've only ever done CRUD type poo poo as part of being a web dev or basic scripting of poo poo, and some baby schema generation, nothing like this before. I'd rather not gently caress it up.

Every single statement by itself should be transactional unless you're doing something weird. If you need to do several things transactionally, check this out:


https://msdn.microsoft.com/en-us/library/ms174377.aspx


BEGIN TRAN[SACTION]
...
COMMIT [WORK]

error? ROLLBACK TRAN[SACTION]

Mr Shiny Pants
Nov 12, 2012

crashdome posted:

Wpf really just replaces WinForms. Will it be around forever? I have no idea.

I'm an old school .Net dev like yourself. Most of my apps are COM/Serial based and I am using Wpf on new projects as of the past year or so. MVVM is just designed to separate BL from UI. Encapsulating "Button Click does this" in your Business Logic is now known as "you're doing it wrong" and all the skinny college kids coming in will laugh at you apparently. I find it actually has made my code more flexible and I feel like it'll be more future proof. I'm pretty much a small project developer though.

edit: I hate WinForms now. I look back at old stuff now and then and I really wish I could wave a wand and make it all Wpf/MVVM at least just for the sanity of not wrestling the UI to add more features.

another edit: I now develop on a laptop with something like 643200000 x 500684358 resolution and my text size up to 150x or 200x and all my winform apps go berserk. I've noticed my Wpf apps do not. Don't know what that means exactly but, just reinforces my relief I have moved on to something else.

The learning curve is higher with WPF at first, but you are right that is pretty nice to work with if you setup your projects the right way. I had to redesign quite a lot of my UI this week and WPF makes it so much easier.

Too bad MS has to have two versions of it, WinRT and the .Net one. I really do hope they do away with WinRT and fold the good UI tablety stuff back into .Net.

I mean, do you know anyone who uses WinJS and HTML5 when you could use C#? I don't. WinRT feels like a dead-end and it looks like the Windows guys don't like the .Net guys and that is why we end up with two versions making the .Net version lag behind the RT version in Touch UI.

amotea
Mar 23, 2008
Grimey Drawer

thebruce posted:

Also, when looking at examples of mvvm, the model seems to only be data structures, with business logic in the viewmodel. Does this not break encapsulation? The whole point of a class is to store both the data AND the methods that act on it, but mvvm seems to go against that. Does this make it harder to use existing code libraries?
The thing is that you want your classes to have only one responsibility and make them re-usable when appropriate.

If you create a separate small class that represents a certain data structure/concept you can re-use that class throughout your code-base (e.g. in multiple VMs). The VM should just contain the data and operations that are needed to provide business logic used in a certain view.

One of the OOP pitfalls IMO is that it seems to advocate to put all and any operations that have anything to do with a data class in or near that class. I'm not sure if this actually is what proper OOP is about, but it's certainly taught in college and beginners books. As it turns out, a more functional approach (i.e. classes exist just to perform one or a few operations, and don't keep state) is way better to keep things decoupled.

thebruce
Jul 4, 2004

crashdome posted:

Wpf really just replaces WinForms. Will it be around forever? I have no idea.

I'm an old school .Net dev like yourself. Most of my apps are COM/Serial based and I am using Wpf on new projects as of the past year or so. MVVM is just designed to separate BL from UI. Encapsulating "Button Click does this" in your Business Logic is now known as "you're doing it wrong" and all the skinny college kids coming in will laugh at you apparently. I find it actually has made my code more flexible and I feel like it'll be more future proof. I'm pretty much a small project developer though.

edit: I hate WinForms now. I look back at old stuff now and then and I really wish I could wave a wand and make it all Wpf/MVVM at least just for the sanity of not wrestling the UI to add more features.

another edit: I now develop on a laptop with something like 643200000 x 500684358 resolution and my text size up to 150x or 200x and all my winform apps go berserk. I've noticed my Wpf apps do not. Don't know what that means exactly but, just reinforces my relief I have moved on to something else.

Thanks for the response. I thought I should move to wpf so thanks for confirming this.

The bit that doesn't click for me is the business logic bit. Should the com port (for example) be defined in the model or the viewmodel?

thebruce
Jul 4, 2004

amotea posted:

The thing is that you want your classes to have only one responsibility and make them re-usable when appropriate.

If you create a separate small class that represents a certain data structure/concept you can re-use that class throughout your code-base (e.g. in multiple VMs). The VM should just contain the data and operations that are needed to provide business logic used in a certain view.

One of the OOP pitfalls IMO is that it seems to advocate to put all and any operations that have anything to do with a data class in or near that class. I'm not sure if this actually is what proper OOP is about, but it's certainly taught in college and beginners books. As it turns out, a more functional approach (i.e. classes exist just to perform one or a few operations, and don't keep state) is way better to keep things decoupled.

If I understand correctly, I should declare as many methods to be static as is possible, passing in the data structures that should be acted upon as arguments?

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

thebruce posted:

The bit that doesn't click for me is the business logic bit. Should the com port (for example) be defined in the model or the viewmodel?

Neither. The COM port represents an external dependency of your application and should be wrapped up behind an interface, so you can later mock/stub the code that interacts with the COM port for testing purposes.

The viewmodel encapsulates the state of the UI. Models are typically just dumb classes or structs that provide a bunch of logically grouped properties. The viewmodel then calls out to another class/set of classes (typically a "business layer" or something along those lines) that do the heavy lifting for your application's core logic.

The idea is that the UI is irrelevant to the business logic, and the business logic is irrelevant to the UI.

thebruce posted:

If I understand correctly, I should declare as many methods to be static as is possible, passing in the data structures that should be acted upon as arguments?

Static methods shouldn't call out to external systems. Look up inversion of control. Statics are fine for, say, string manipulation, though.

amotea
Mar 23, 2008
Grimey Drawer
To add to that: practically speaking static classes and methods seem a good idea at first, but almost always you need some extra dependencies later on (this is where the IoC/DI comes in, DI can give you these dependencies through the constructor).

crashdome
Jun 28, 2011

thebruce posted:

The bit that doesn't click for me is the business logic bit. Should the com port (for example) be defined in the model or the viewmodel?

To expand on what Ithaqua has said, I typically define a basic Serial Port class which handles all the underlying needs of a serial port and takes a byte[] and receives back a byte[] through public methods. I also subclass a USB Serial Port which inherits everything except has a different mechanism to detect what I term "COM Port Holding" since USB does not have RTS/CTS or DTR lines physically.

I use an interface (ISerialPort) to expose the public methods of those objects so I can pass a concrete USB or standard Serial Port object wherever and never directly become tied to single concrete class.

I have a set of service classes which interact with the Serial Ports interface class. I have many of these because my applications can be anywhere from 5 to 15 devices with varying protocols and COM settings. My service class takes in a: Serial Port Settings class, a Protocol class, and a Device class. Again, this is because of the varying degree of possibilities. The service class has public methods like: SetVoltage(decimal voltage) ...which then does all the work by talking to the serial port and setting/validating values.

I then pass this service class to my View Models along with any other data models (or services) I may need. My View Model interacts with the service and doesn't care about Serial Ports, or any of that stuff. It just basically tells the service class what the user is doing (i.e. SetVoltage(120) ). My service class also therefore, does not care what the user is pushing or typing or whatever. This is the job of the View Model. It ties the two together transparently. My Protocol class inside the service is able to translate UI data to byte[] and received byte[] back to display values. My settings pass in Baud,Parity,etc.. to the ISerialPort. Finally, my Device class is used like a data model in that I usually perform many functions on a device and store them in memory so I can validate data or perhaps use some of the specific device data in the Protocol class (such as device DNP port, Modbus port, etc..).

I hope that give you a good run down of how I structure things so you have a good overview. If you want this in code form (i.e. just some abstract classes with no guts) I suppose I could type something up and PM it to you.

edit: IoC is great but, keep it simple. I use MVVM Lite which uses SimpleIoC and it works fine for me. The problem I run into with apps like above is that I often have factories instead which generate a Device, a Protocol, etc.. based on a user selection. I typically think in terms of : Register and use IoC container first or when using something akin to a singleton or if there is no dynamic creation. If dynamic, use a Factory instead.

another edit: For Devices and Protocols I also implement interfaces such as IElgar and IDNPProtocol or IMODBUSProtocol because it makes it easier to subclass those and not have to alter my service classes. For example, Elgar makes a line of models with different ASCII commands and settings. Modbus can be RTU or ASCII. The concrete classes handle the implementation. My Interfaces ensure my service classes have consistent and testable Method signatures across those subclasses. You end up with A LOT of files but, it makes testing and diagnosis much, much simper.

ok, yet more edits: I feel like I'm on a roll so sorry for the wall of text. I actually use Eltima's Virtual Serial Port product to create a stand-alone emulation program and I am emulating various devices in one app and doing integration testing on my current project without the need of having to be connected to any physical devices. I recommend it. E.g. I have a virtual serial port connecting COM port 10 to COM port 50 and my emulator mimics a device on COM 50 which sends the data to COM 10 in my current project and my app thinks it's talking to a physical device. I reused all of my Serial Port and Protocol code in the emulator. This may be too much for you but, if you are going to be doing integration testing of your application and don't want to hook up a series of cables to devices, Eltima's VSP is an awesome product if you are down for the extra work.

crashdome fucked around with this message at 18:24 on Jun 19, 2015

Boz0r
Sep 7, 2006
The Rocketship in action.
I'm trying to get a simple .NET MVC 5 project up and running, but I've run into a couple of snags.

I have a dropdown list where I select an Area, and I want to update another list with the shops in that area.

I figure I'll have to send a list of all the shops over to the client, and then filter it based on the selected shop, but I'm not really sure of the correct way of getting the data model over to the client.


Index.cshtml:
code:
@model Models.ViewModel

<table>    
    <tr>
        <td>
            <h3>Areas</h3>
            @Html.DropDownListFor(m => m.SelectedOptions, Model.Areas, new { size = 10, id = "AreaList" })
        </td>
        <td>
            <h3>Shops</h3>
            @Html.DropDownListFor(m => m.SelectedOptions, Enumerable.Empty<SelectListItem>(), new { size = 5, id = "ShopList" })
        </td>
    </tr>
</table>
Models:
code:
public class Area
{
	public string Name { get; set; }
	public List<Shop> Shops { get; set; }
}

public class Shop
{
	public string Name { get; set; }
	public District District { get; set; }
}

public class ViewModel
{
	public IEnumerable<SelectListItem> Areas;
	public IEnumerable<SelectListItem> Shops;

	public IEnumerable<string> SelectedOptions;
}
Any tips for doing this?

Uziel
Jun 28, 2004

Ask me about losing 200lbs, and becoming the Viking God of W&W.
To do cascading dropdowns, I have a controller action that results Json (that's called via javascript):
code:
[HttpGet]
        public JsonResult GetPlan(string planId)
        {
            var plan = Plan.Get(planId);
            var result = new JsonResult
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = JsonConvert.SerializeObject(plan)
            };
            return result;
        }
Then in java script:
code:
 $("#PlanId").change(function () {
        var planId = $("#PlanId").val();
        var url = "/MyAccount/GetPlan"; //url of above controller action
        var currentClients = $("#NumberOfClients").val();
        $.ajax({
            contentType: "application/html; charset=utf-8",
            dataType: "json",
            type: "GET",
            cache: true,
            url: url,
            data: { planId: planId },
            success: function (data) {
                var json = jQuery.parseJSON(data);
                
                //set value of second dropdown based on these results here
            },
            error: function (xhr, status) {
                alert(status);
            }
        });
    });

Uziel
Jun 28, 2004

Ask me about losing 200lbs, and becoming the Viking God of W&W.
Regarding C# 6.0, does anyone know if Resharper picks up the new language features and recommends using them? For example, "Hey, use the null conditional operator here instead!" or "Convert this to use auto property initializers".

Also, I can still do webforms in 2015 as well right? I'm going to try to convert most of the project to MVC as I can, but due to time constraints two particular sections will still need to be webforms!

Uziel fucked around with this message at 19:17 on Jun 20, 2015

Funking Giblet
Jun 28, 2004

Jiglightful!

Uziel posted:

Regarding C# 6.0, does anyone know if Resharper picks up the new language features and recommends using them? For example, "Hey, use the null conditional operator here instead!" or "Convert this to use auto property initializers".

Also, I can still do webforms in 2015 as well right? I'm going to try to convert most of the project to MVC as I can, but due to time constraints two particular sections will still need to be webforms!

It sure does, even in projects in the old framework...

Boz0r
Sep 7, 2006
The Rocketship in action.
Thanks, I got it working.

Boz0r
Sep 7, 2006
The Rocketship in action.
Now I've got another problem. I'm trying to get this Entity Framework to work with my database. Right now, I've added a couple of objects via code, but when I want to retrieve them, I just get an empty collection.

code:
public ViewResult Index()
{
	using (var ctx = new DatabaseContext())
	{
		ctx.Areas.Add(new Area("First"));
		ctx.Areas.Add(new Area("Second"));
		ctx.Areas.Add(new Area("Third"));
		ctx.SaveChanges();
	}

	IEnumerable<Area> areas = productRepository.Areas;

	return View();
}
code:
public class ProductRepository
{
	private DatabaseContext context = new DatabaseContext();

	public IEnumerable<Area> Areas{ get { return context.Areas; } }
}
    
public class DatabaseContext : DbContext
{
	public DatabaseContext():base("test")
	{
	}
	public DbSet<Area> Areas { get; set; }
}
What did I do wrong?

TheBlackVegetable
Oct 29, 2006

Boz0r posted:

Now I've got another problem. I'm trying to get this Entity Framework to work with my database. Right now, I've added a couple of objects via code, but when I want to retrieve them, I just get an empty collection.

code:
public ViewResult Index()
{
	using (var ctx = new DatabaseContext())
	{
		ctx.Areas.Add(new Area("First"));
		ctx.Areas.Add(new Area("Second"));
		ctx.Areas.Add(new Area("Third"));
		ctx.SaveChanges();
	}

	IEnumerable<Area> areas = productRepository.Areas;

	return View();
}
code:
public class ProductRepository
{
	private DatabaseContext context = new DatabaseContext();

	public IEnumerable<Area> Areas{ get { return context.Areas; } }
}
    
public class DatabaseContext : DbContext
{
	public DatabaseContext():base("test")
	{
	}
	public DbSet<Area> Areas { get; set; }
}
What did I do wrong?

Im pretty sure you need to get the new Area object from the ctx.Areas.Create (or some other method?), rather that newing it manually - it won't save to the database otherwise.

Boz0r
Sep 7, 2006
The Rocketship in action.
If I open the SQL manager I can see the items created, so I think it's on the fetching end the problem occurs.

Drastic Actions
Apr 7, 2009

FUCK YOU!
GET PUMPED!
Nap Ghost
I got a Raspberry Pi 2 the other day and I put Windows 10 IoT on it. I deployed my Awful app to it and it mostly worked! I say mostly because I can't seem to get HttpClient to send a cookie container with the request, so I can't log in. At first I thought my PCL Storage library was failing to serialize/deserialize my cookies, so I hardcoded it to always log me in, but it still fails. Running the request through fiddler shows no cookies being attached.

I can't replicate it in other environments, but I'm not sure if this is specific to IoT, or something wrong in my program. I might try and make a separate UAP app later to try and see if it's just how HttpClient is running, but has anyone heard of this problem before?

EDIT: Note that when I send in the login form, the response cookie container did have my authentication cookies. It's just when I tried to set one myself, it would fail.

uXs
May 3, 2005

Mark it zero!

Boz0r posted:

Now I've got another problem. I'm trying to get this Entity Framework to work with my database. Right now, I've added a couple of objects via code, but when I want to retrieve them, I just get an empty collection.

code:
public ViewResult Index()
{
	using (var ctx = new DatabaseContext())
	{
		ctx.Areas.Add(new Area("First"));
		ctx.Areas.Add(new Area("Second"));
		ctx.Areas.Add(new Area("Third"));
		ctx.SaveChanges();
	}

	IEnumerable<Area> areas = productRepository.Areas;

	return View();
}
What did I do wrong?

You're returning a view without any data.

Boz0r
Sep 7, 2006
The Rocketship in action.

uXs posted:

You're returning a view without any data.

Yeah, I'm loading the contents in JavaScript, this is just a test to see if it actually returns anything, which it doesn't :(

kingcrimbud
Mar 1, 2007
Oh, Great. Now what?

Boz0r posted:

Now I've got another problem. I'm trying to get this Entity Framework to work with my database. Right now, I've added a couple of objects via code, but when I want to retrieve them, I just get an empty collection.

code:
public ViewResult Index()
{
	using (var ctx = new DatabaseContext())
	{
		ctx.Areas.Add(new Area("First"));
		ctx.Areas.Add(new Area("Second"));
		ctx.Areas.Add(new Area("Third"));
		ctx.SaveChanges();
	}

	IEnumerable<Area> areas = productRepository.Areas;

	return View();
}
code:
public class ProductRepository
{
	private DatabaseContext context = new DatabaseContext();

	public IEnumerable<Area> Areas{ get { return context.Areas; } }
}
    
public class DatabaseContext : DbContext
{
	public DatabaseContext():base("test")
	{
	}
	public DbSet<Area> Areas { get; set; }
}
What did I do wrong?

Your Index() method is not enumerating over your locally declared areas variable and because you're not returning this variable by this method, your database won't even be hit with a select statement. Add this to your config to see what's actually happening in your database because of EF: http://blog.oneunicorn.com/2014/02/09/ef-6-1-turning-on-logging-without-recompiling/

kingcrimbud
Mar 1, 2007
Oh, Great. Now what?
Relating to the Entity Framework talk above, what are people using with Web API and Unity when they need PerRequestLifetimeManager behavior? I don't want to pull in all these MVC packages to use one class (PerRequestLifetimeManager) to manage my DbContexts. And frankly, registering this lifetime manager doesn't seem to be currently working anyway for me even when I register it. I'm still seeing singleton behavior.

Boz0r
Sep 7, 2006
The Rocketship in action.

kingcrimbud posted:

Your Index() method is not enumerating over your locally declared areas variable and because you're not returning this variable by this method, your database won't even be hit with a select statement. Add this to your config to see what's actually happening in your database because of EF: http://blog.oneunicorn.com/2014/02/09/ef-6-1-turning-on-logging-without-recompiling/

If I turn on logging, nothing gets written to the log file at all. If I try running this code, I get an exception:

code:
public ViewResult Index()
        {
            IEnumerable<Area> enumerable = productRepository.Areas;
            foreach (var area in enumerable)
            {
                Console.WriteLine(area.Name);
            }

            return View();             
        }
code:
An exception of type 'System.Reflection.TargetInvocationException' occurred in EntityFramework.SqlServer.dll but was not handled in user code

ljw1004
Jan 18, 2005

rum

Drastic Actions posted:

I got a Raspberry Pi 2 the other day and I put Windows 10 IoT on it. I deployed my Awful app to it and it mostly worked! I say mostly because I can't seem to get HttpClient to send a cookie container with the request, so I can't log in. At first I thought my PCL Storage library was failing to serialize/deserialize my cookies, so I hardcoded it to always log me in, but it still fails. Running the request through fiddler shows no cookies being attached.
I can't replicate it in other environments, but I'm not sure if this is specific to IoT, or something wrong in my program. I might try and make a separate UAP app later to try and see if it's just how HttpClient is running, but has anyone heard of this problem before?

The .NET HttpClient type has been completely rewritten from scratch for Win10 platforms. It now supports HTTP/2, amongst other features. But it is a new codebase.

The only bug I'm aware of is that in certain particular situations, HTTP POST with NTLM authentication gives a "random stream access" error, and the workaround is to follow what are best-practices anyway by pre-authenticating before you post. So not related to your problem.

And yes there are known PCL bugs in VS2015 RC on Win10 platforms with serialization/deserialization in PCLs. Specifically, if you have an "old-style PCL" (targeting .NET4.0.3 or older, or targeting SL5) then serializing types defined within it doesn't work.

So neither of these bugs relate to your situation. If you do end up making a separate minimal repro, Drastic, I'd be happy to forward it on to the right person.

kingcrimbud
Mar 1, 2007
Oh, Great. Now what?

kingcrimbud posted:

Relating to the Entity Framework talk above, what are people using with Web API and Unity when they need PerRequestLifetimeManager behavior? I don't want to pull in all these MVC packages to use one class (PerRequestLifetimeManager) to manage my DbContexts. And frankly, registering this lifetime manager doesn't seem to be currently working anyway for me even when I register it. I'm still seeing singleton behavior.

I figured this out after creating a new solution. Be careful how you register DelegatingHandlers! Their singleton behavior means dependencies will not resolve per your expectations.

Night Shade
Jan 13, 2013

Old School

kingcrimbud posted:

I figured this out after creating a new solution. Be careful how you register DelegatingHandlers! Their singleton behavior means dependencies will not resolve per your expectations.

If you want per request scoping to work right in a DelegatingHandler, you need to call request.GetDependencyScope() in SendAsync and use the resulting IDependencyScope as a service locator.

Been there, done that.

epswing
Nov 4, 2003

Soiled Meat

Night Shade posted:

If you want per request scoping to work right in a DelegatingHandler, you need to call request.GetDependencyScope() in SendAsync and use the resulting IDependencyScope as a service locator.

When I get together with friends, and we talk about work, a phrase like this is a solid conversation-ender :v:

just kidding I don't have any friends

Night Shade
Jan 13, 2013

Old School

epalm posted:

When I get together with friends, and we talk about work, a phrase like this is a solid conversation-ender :v:

just kidding I don't have any friends



But seriously, like three other people where I work have tripped over this same issue - it's fairly subtle behaviour if you start from "I need to wrap something around all my HTTP requests" and arrive at DelegatingHandler.

kingcrimbud
Mar 1, 2007
Oh, Great. Now what?

Night Shade posted:

If you want per request scoping to work right in a DelegatingHandler, you need to call request.GetDependencyScope() in SendAsync and use the resulting IDependencyScope as a service locator.

Been there, done that.

I ended up following this http://stackoverflow.com/a/26472999 and using an IUnityContainer dependency instead of a WindsorContainer.

Faldoncow
Jun 29, 2007
Munchin' on some steak
I have a question about WebAPI that I'm hoping someone here might be able to answer. It's also using Microsoft.Owin, although that may not matter. I'm playing around with loading some WebAPI controllers from an external dll at runtime so I've done the following.

Implement custom assemblies resolver:
code:
public class CustomAssembliesResolver : DefaultAssembliesResolver
{
	public override ICollection<Assembly> GetAssemblies()
	{
		string filePath = @"ExternalControllers.dll";
		string fullPath = Path.GetFullPath(filePath);

		var baseAssemblies = base.GetAssemblies();
		var externalAssembly = Assembly.LoadFrom(fullPath);
		baseAssemblies.Add(externalAssembly);
		return baseAssemblies;
	}
}
and then in my Owin Startup class:

code:
HttpConfiguration config = new HttpConfiguration();
config.Services.Replace(typeof(IAssembliesResolver), new CustomAssembliesResolver());
config.MapHttpAttributeRoutes();
app.UseWebApi(config);
This is working great, but my question is what exactly does MapHttpAttributeRoutes() do? The CustomAssembliesResolver is not called at startup, but rather when I first request an url and only once. If I comment out MapHttpAttributeRoutes(), all of my routes are 404. Does it delay actually mapping routes until the first time a client requests one?

*Edit: Of course I figure it out a few minutes after posting this. MapHttpAttributeRoutes just sets what the initializer will do.

Faldoncow fucked around with this message at 18:30 on Jun 23, 2015

raminasi
Jan 25, 2005

a last drink with no ice
Does anyone here use Code Contracts? Is the (logistical) overhead offset by productivity gains?

Sedro
Dec 31, 2008
It quadrupled my build times, so no

amotea
Mar 23, 2008
Grimey Drawer
It was hard to get it working the last time I tried it (1-2 years ago), and building the solution took about 30 minutes instead of 30 seconds.

Live code annotations worked half the time as far as I remember.

Would be great if it worked as fast as e.g. Resharper.

RangerAce
Feb 25, 2014

GrumpyDoctor posted:

Does anyone here use Code Contracts? Is the (logistical) overhead offset by productivity gains?

Seems like you could get the same benefits from some well-crafted unit tests, no?

Blasphemeral
Jul 26, 2012

Three mongrel men in exchange for a party member? I found that one in the Faustian Bargain Bin.

RangerAce posted:

Seems like you could get the same benefits from some well-crafted unit tests, no?

But that means someone has to write them. Adorning your own code with attributes or method calls is a lot easier to get people on-board with.

Adbot
ADBOT LOVES YOU

ljw1004
Jan 18, 2005

rum

RangerAce posted:

Seems like you could get the same benefits from some well-crafted unit tests, no?

I believe that the "Plex" part of code-contracts can explore EVERY POSSIBLE outcome of a program. Including every possible interleaving of concurrent stuff.


(It's not humanly possible to use unit-tests to sniff out rare concurrency bugs, as far as I can tell -- the programmer's brain naturally thinks about how concurrent stuff is meant to interleave, and subconsciously shies away from the bad cases. And honestly -- how many of you have written unit tests where you mock HttpClient and then simulate it doing a POST action which reports timeout failure but which nevertheless succeeds in modifying the back-end server?)

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