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.
 
  • Locked thread
RICHUNCLEPENNYBAGS
Dec 21, 2010
Right, but why should the lifespan be so different if it's getting disposed after every request? I'm not talking about a static connection or anything.

e: This is a genuine question; I hope I'm not giving you the impression I'm challenging you because you obviously have more experience with MVC than I do.

RICHUNCLEPENNYBAGS fucked around with this message at 05:12 on Jan 3, 2014

Adbot
ADBOT LOVES YOU

epswing
Nov 4, 2003

Soiled Meat
Using Entity Framework, I have a one-to-many relationship, and on the many side is a table-per-hierarchy.

http://stackoverflow.com/questions/20892673

The SO example uses Garage for the one side, and Car/Motorcycle : Vehicle for the many side. Can one of you EF experts also tell me that what I'm after isn't supported?

ManoliIsFat
Oct 4, 2002

epalm posted:

Using Entity Framework, I have a one-to-many relationship, and on the many side is a table-per-hierarchy.

http://stackoverflow.com/questions/20892673

The SO example uses Garage for the one side, and Car/Motorcycle : Vehicle for the many side. Can one of you EF experts also tell me that what I'm after isn't supported?

Can you explain a little more how your setup is different than the SO? This microsoft example spells it out a little more http://www.asp.net/mvc/tutorials/ge...mvc-application

epswing
Nov 4, 2003

Soiled Meat
My setup is exactly like the SO post.

It's my SO post!

sadus
Apr 5, 2004

I'm trying to setup a global message handler in a Web API project to do the following:
1) check the request for a couple mandatory headers (i.e. a simple DeviceId and API Key)
2) validate those headers (ultimately against MSSQL/Entity Framework)
3) save the DeviceId (that was set via headers) somewhere so my controllers can access it, so all the methods in the API don't have to have a DeviceId passed in as a parameter

Re: #3, I've mostly wrapped my head around dependency injection and am close to having that fully working for injecting "services"/repositories into the ApiControllers, which then in turn get a DBContext injected into them... I found for Action Filters you can save data in the ActionContext.Request.Properties (although I'm not quite sure how to read that back out inside of the ApiController as well), but that doesn't seem to be an option in a Message Handler.

I thought maybe the controllers should have a DeviceId injected into their constructors as well, but not sure how I could get a Message Handler to do the injecting - I'm guessing that's not even possible? I guess I'm basically looking for some sort of ViewBag equivalent for Web API that the message handler can write to, and the API Controllers can read from.

Re: #2, Besides keeping track of the DeviceId itself, I'm also at a bit of a loss as to how the message handler can be written to call the "service"/repository to check if the DeviceID and API Key is valid, in a DI-friendly/testable fashion (i.e. not putting raw Entity Framework code right in there)? Can you actually inject objects into Message Handlers as well? I'm trying out Autofac for now but it's still making my head hurt a bit despite understanding constructor injection in theory.

Che Delilas
Nov 23, 2009
FREE TIBET WEED

RICHUNCLEPENNYBAGS posted:

Right, but why should the lifespan be so different if it's getting disposed after every request? I'm not talking about a static connection or anything.

e: This is a genuine question; I hope I'm not giving you the impression I'm challenging you because you obviously have more experience with MVC than I do.

It's not necessarily bad on a technical level (that I know of), though I'm sure there are some corner cases where it won't get disposed the way you expect. It's more a design issue. Spraying data access logic at your Controller classes severely breaks separation of concerns, which is the point of MVC to begin with. Data access is such an orthogonal issue to an MVC app that it really should be handled in its own place; at minimum in its own class (some projects have it in its own project entirely). And really, moving each linq query out to its own method in a data access class somewhere doesn't really add a lot of complexity at all, if you don't bother with doing full dependency injection.

It's a shame that every beginners guide and tutorial does it precisely the wrong way (dbcontext instantiated directly in the controller), in their haste to explain Actions and passing data through to strongly typed Views. I get why they do it, it just does damage to new developers and it's something you have to unlearn when you start doing big projects.

Funking Giblet
Jun 28, 2004

Jiglightful!
If you are doing the following

code:
using (var context = new ProductContext())
{
}
In every action, you are probably doing it wrong. IOC should handle the instantiation and diposal of the context. You could also use an actionfilter to manage this too, although that is per action, not per request, so something like transaction management would be better suited there.

RICHUNCLEPENNYBAGS
Dec 21, 2010

Che Delilas posted:

It's not necessarily bad on a technical level (that I know of), though I'm sure there are some corner cases where it won't get disposed the way you expect. It's more a design issue. Spraying data access logic at your Controller classes severely breaks separation of concerns, which is the point of MVC to begin with. Data access is such an orthogonal issue to an MVC app that it really should be handled in its own place; at minimum in its own class (some projects have it in its own project entirely). And really, moving each linq query out to its own method in a data access class somewhere doesn't really add a lot of complexity at all, if you don't bother with doing full dependency injection.

It's a shame that every beginners guide and tutorial does it precisely the wrong way (dbcontext instantiated directly in the controller), in their haste to explain Actions and passing data through to strongly typed Views. I get why they do it, it just does damage to new developers and it's something you have to unlearn when you start doing big projects.

I understand that, but what if you have a separate class that, say, has methods like GetMyObject() or SaveApplicationObject() or whatever, rather than directly making DbContext calls, and that class is itself disposable? Then you can dispose it in the controller's dispose method and if you're using an interface you could go back and mock it later (yeah it should probably happen at the same time but I'm working on a really tight deadline to have a first release).

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

RICHUNCLEPENNYBAGS posted:

I understand that, but what if you have a separate class that, say, has methods like GetMyObject() or SaveApplicationObject() or whatever, rather than directly making DbContext calls, and that class is itself disposable? Then you can dispose it in the controller's dispose method and if you're using an interface you could go back and mock it later (yeah it should probably happen at the same time but I'm working on a really tight deadline to have a first release).

You're defeating the point of doing MVC. Data access belongs in the model classes, not the controller. The controller just tells the application where to go next, it should not have data access logic.

Che Delilas
Nov 23, 2009
FREE TIBET WEED

RICHUNCLEPENNYBAGS posted:

I understand that, but what if you have a separate class that, say, has methods like GetMyObject() or SaveApplicationObject() or whatever, rather than directly making DbContext calls, and that class is itself disposable? Then you can dispose it in the controller's dispose method and if you're using an interface you could go back and mock it later (yeah it should probably happen at the same time but I'm working on a really tight deadline to have a first release).

That sounds to me like basically what we've been advocating. Make a separate class that manages your data access, with methods that represent what kind of data access operations you're doing. If that involves EF and DbContexts, then great. If it involves ADO SqlClient, that's fine too. Whatever. The point is, the Controller doesn't care how the data access is being accomplished, just THAT it is being accomplished.

That said, you have a deadline. Here's what you have to consider: Some of the things we've talked about (notably IOC containers) add some initial complexity to a project, which is going to cost you time, especially if you're just learning about the more modern OOP concepts and tools (again, like IoC and IoC containers). Some projects are not worth adding that much complexity to. For example, little one-off utilities or internal web sites that are only going to be used by like 2 guys in a single department. It would be NICE to have a beautiful design where everything is loosely coupled and unit-testable and infinitely maintainable and extendable, but it's not always necessary.

Beyond that, sometimes you just have to get poo poo done. If you're on a tight deadline, you have to make a judgement call about how far you need to go in that respect. If you're up against a wall, go with what's easiest to do, for you, right now. Get that poo poo out the door, because nobody will care how beautiful and extendable and maintainable the project is in the future if it isn't ready when they need it in the first place. Some people in here may disagree with me on this point, but that's been my (albiet limited) experience.

Just realize that these choices you have to make will affect how difficult it is to extend and maintain the project in the future. The bigger the project is, the more good design will save your rear end. Make a judgement call.

ManoliIsFat
Oct 4, 2002

RICHUNCLEPENNYBAGS posted:

I understand that, but what if you have a separate class that, say, has methods like GetMyObject() or SaveApplicationObject() or whatever, rather than directly making DbContext calls, and that class is itself disposable? Then you can dispose it in the controller's dispose method and if you're using an interface you could go back and mock it later (yeah it should probably happen at the same time but I'm working on a really tight deadline to have a first release).

That's what's Ithaqua means by using repo classes, and it really is the proper way to abstract your data access. I suppose it doesn't REALLY matter if you have using{}s in each function or just make the dbContext in the constructor, destroy it in the dispose. But I like having that clean, predictable unit of work in the function, knowing that nothing else has potentially messed with this dbContext before I try to insert/update/delete on it, or making sure there's nothing I'm accidentally lazily loading (unless that's what you want to do, then of course you gotta keep the context around).

Macichne Leainig
Jul 26, 2012

by VG
Got this problem that's driving me nuts at work. We use the WPF extended toolkit's busy indicator so our BA's don't freak out when the app appears to be doing nothing. It mostly works, but the person who originally wrote this app has like several dozen nested tasks (i.e. Task.Factory.StartNew()) to get stuff done. As you can imagine, the boolean property that the indicator binds to often gets set to false before the chain of tasks finishes executing, so the app will appear to be complete with its task before it actually is.

Question is - what's the way to properly wait for all the tasks to complete before setting the Busy flag? It happens pretty much exclusively with certain methods, but the methods that these methods call are not exclusive to the original methods, so I can't go in and just delete the "internal" property change.

Is there a way to basically check if all tasks fired off from the task factory/original task chain are complete? That'd be ideal, but with my admittedly limited knowledge in how the factory works and my Googling, it doesn't seem like it exists.

Dirk Pitt
Sep 14, 2007

haha yes, this feels good

Toilet Rascal
I am pretty sure you can do something like this:
code:

this.IsBusy=true;
await Task.WhenAll(task1, task2,task3);
This.IsBusy = false;

That is what I have done when I need to fire off some tasks and wait for them all to complete.

If it is not async, there is a task.WaitAll as well that locks the thread until everything finishes.

Dirk Pitt fucked around with this message at 18:58 on Jan 6, 2014

Night Shade
Jan 13, 2013

Old School

Tha Chodesweller posted:

Is there a way to basically check if all tasks fired off from the task factory/original task chain are complete? That'd be ideal, but with my admittedly limited knowledge in how the factory works and my Googling, it doesn't seem like it exists.

Specifying TaskCreationOptions.AttachedToParent in the nested Task.Factory.CreateNew() call will link the task contexts together, causing the parent to wait for the child to complete before completing itself. It also has the neat effect of propagating exceptions up through the parent task.

code:
[Test]
public void TestDetachedTask() {
  int complete = 0;
  var outer = Task.Factory.StartNew( () => {
    var inner = Task.Factory.StartNew( () => {
      Thread.Sleep(1000);
      Interlocked.Exchange(ref complete, 1);
    });
  }
  outer.Wait(); // does not wait for inner to complete
  Assert.That(complete, Is.EqualTo(1)); //fails
}

[Test]
public void TestAttachedTask() {
  int complete = 0;
  var outer = Task.Factory.StartNew( () => {
    var inner = Task.Factory.StartNew( () => {
      Thread.Sleep(1000);
      Interlocked.Exchange(ref complete, 1);
    }, TaskCreationOptions.AttachedToParent);
  }
  outer.Wait(); // waits for inner to complete
  Assert.That(complete, Is.EqualTo(1)); //passes
}
disclaimer: typed directly into edit box, may not compile

mortarr
Apr 28, 2005

frozen meat at high speed
Can someone critique the way I configure Automapper and Autofac in an MVC/WebAPI project?

What I'm trying to do is firstly have autofac identify a series of modules across all projects that the MVC project depends on in the solution and register them, one of which does roughly the same for automapper.

I thought it might be a good idea to have all the autofac and automapper config for the project lie in the relevant project itself, so I don't end up with boatloads of config stuff in the MVC project, but I can't work out how to autoscan all dependant assemblies in AutomapperModule.Load() - I've tried AppDomain.CurrentDomain.GetAssemblies() but it doesn't seem to work.

Is this even a sensible thing to do, or should I just throw all my config stuff back in the MVC project?

code:
  // In project 'Orm' (a class library holding repositories and DTO's etc)
  // This project makes heavy use of Automapper, and this method controls the config for the 'Orm' project.
  public class OrmProfile : Profile
  {
    protected override void Configure()
    {
      Mapper.CreateMap<Project, Item>();
      // Lots of mapping code removed...
    }
  }
code:
  // In project 'WebUI' (an MVC project), which has a reference to 'Orm'
  public class AutofacConfig
  {
    // This is called from globabl.asax and scans for all Autofac modules in 
    // the current assembly and loads them, I'd like to make this work for all 
    // dependant assemblies but don't need to right now.
    public static void Register(HttpConfiguration config)
    {
      var builder = new ContainerBuilder();
      builder.RegisterAssemblyModules(Assembly.GetExecutingAssembly());
      var container = builder.Build();

      DependencyResolver.SetResolver(new AutofacDependencyResolver(container));      
      GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);      
    }
  }

  // Also in project 'WebUI' 
  public class AutomapperModule : Module
  {
    protected override void Load(ContainerBuilder builder)
    {
      // I want to merge this and the below call, but 
      // builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies()).AssignableTo<Profile>().As<Profile>(); 
      // doesn't seem to do what I thought it would.
      builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
             .AssignableTo<Profile>()
             .As<Profile>();

      builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(OrmProfile)))
             .AssignableTo<Profile>()
             .As<Profile>();

      builder.Register(GetMappingEngine).As<IMappingEngine>().SingleInstance();
    }

    private static IMappingEngine GetMappingEngine(IComponentContext context)
    {
      Mapper.Configuration.ConstructServicesUsing(DependencyResolver.Current.GetService);

      foreach (var p in context.Resolve<IEnumerable<Profile>>())
      {
        Mapper.AddProfile(p);
      }

      Mapper.AssertConfigurationIsValid();
      return Mapper.Engine;
    }
  }

Sedro
Dec 31, 2008
AppDomain.CurrentDomain.GetAssemblies will only return assemblies which are loaded at the time, and they are often lazy loaded as part of the IoC container's job.

Try BuildManager.GetReferencedAssemblies.

Macichne Leainig
Jul 26, 2012

by VG

Night Shade posted:

Specifying TaskCreationOptions.AttachedToParent in the nested Task.Factory.CreateNew() call will link the task contexts together, causing the parent to wait for the child to complete before completing itself. It also has the neat effect of propagating exceptions up through the parent task.

Eh, it's not quite the intended result of the original tasks, but I will give it a shot.

Also, ran into a weird bug today. Two methods, in the same class, with the same properties from the same model, both use Task spooling. They both set Busy to true and false identically. Only one actually sets up the busy indicator and meanwhile the UI thread continues to operate. We're using the WPF Extended Toolkit busy indicator (with some custom XAML if that's relevant, but it just changes the bar to a spinner) and a base class contains the bound Busy property. Any ideas what this is? (I'm willing to bet our half-assed IoC implementation, but the fact that it works in one method...)

Chuu
Sep 11, 2004

Grimey Drawer
I've been working in C# for about 2 years writing very high performance libraries involving messaging; similar to the problems TPL solves. I want to learn ASP.NET. I know very little about how web stacks work. I can barely write HTML.

Where's the best place to start for an experienced programmer? I also tend to learn best by sitting down with documentation and consuming it before I start to tinker; is there a definitive book or guide for ASP.NET?

uXs
May 3, 2005

Mark it zero!
How can this

code:
var boomItemLink = this.IndicatorLinks.SingleOrDefault(i => i.IdBudgetronde == idBudgetronde); 
give me an Exception that there are multiple items found, when there's a unique index on that table that prohibits multiple items?

Funking Giblet
Jun 28, 2004

Jiglightful!
Duplicates on a join maybe? It can happen using lots of Includes in EF or JoinQueryOver in NHibernate. Paste the SQL here, and also, check the list for duplicates by hand if it's a small enough list.

TheReverend
Jun 21, 2005

So I'm probably making a "programming 101" error here.

I'm doing simple algebraic operations like finding where two lines intersect, etc.

My function works fine with smaller numbers, but when I get to coordinates like:

Point 1 2107808.042 , 10448210.764
Point 2 2114928.023 , 10448045.309
[these make up a line]

Point 3 2111929.673 , 10447168.359
[this is a point on a line that's perpendicular to the first line]

I get an answer (for where the two lines intersect) that's close.

Its off by about ~.202 on the X and ~.58 on the Y.

I'm using the decimal data type for all data types.

The most mathematically complicated thing I'm doing is division. I guess that's where this is loving up somehow?

Any input would be greatly appreciated.

epswing
Nov 4, 2003

Soiled Meat
Let's see your function! :toot:

TheReverend
Jun 21, 2005

Ok.
I apologize for naming things lovely. I tried to clean it up a little bit.
I mostly just wanted to test my math before I "integrate it" into the other software I'm working on.

code:
            decimal x1 = 0, x2 = 0, y1 = 0, y2 = 0, x3 = 0, y3 = 0;


           //There are three sets of TextBox Controls where you type the input
           //points 1 and 2 are on the line. Point 3 is on an intersecting line. We want to find where the lines intersect. 
          
            x1 = Convert.ToDecimal(X1.Text);
            y1 = Convert.ToDecimal(Y1.Text);
            x2 = Convert.ToDecimal(X2.Text);
            y2 = Convert.ToDecimal(Y2.Text);
            x3 = Convert.ToDecimal(X3.Text);
            y3 = Convert.ToDecimal(Y3.Text);

            decimal slope = (y2 - y1) / (x2 - x1);
            //this is the slope of the line
            

            decimal islope = (1 / slope) * -1;
            //This is the slope of the intersecting line

            //finding B
            //y-y1=slope(x-x1);

            decimal B = (slope * x1 * -1) + y1;
            //Finding the y-intercept  

            decimal B2 = (islope * x3 * -1) + y3;
            //Finding the y-intercept of the intersecting line

            //THE GREAT EQUALIZER. I GOT SOMETHING FOR GUYS LIKE YOU 
            //(inverse the second slope. take sum of both. )
            //inverse the first b. take sum of both
            //This is a "worked out version" of taking two matching linear equations and finding the X-intercept  

            decimal slopes = slope + (-1 * islope);
                         

            decimal Bs = B2 + (B * -1);
       
            //so simplified you'd have something like 3X=9; Find X.
            decimal Xintercept = Bs / slopes;

              
            //now use the X value and  the equation of the intersecting line to get the Y 
            decimal Yintercept = Xintercept * islope + B2;
         
            textBoxYFinal.Text = Yintercept .ToString();
            textBoxXFinal.Text = Xintercept .ToString();

I'm 99% sure my math is ok.

silentpenguins
May 9, 2013

Abysswalking
Working with Sitefinity (and .Net, basically) for the first time and having some trouble. Modifying an importer, I can get the settings fields to show up but I can't seem to save them properly. This is my code to display them:

code:
<sfFields:TextField ID="braftonPublicKey" runat="server" Title="Video Public Key (Video Only)"
        DisplayMode="Write" Expanded="true" DataFieldName="BraftonPublicKey" WrapperTag="div"
        ExpandText="Change" CssClass="sfFormCtrl">
        <validatordefinition required="false" messagecssclass="sfError" requiredviolationmessage="" />
    </sfFields:TextField>

    <sfFields:TextField ID="braftonPrivateKey" runat="server" Title="Video Private Key (Video Only)"
        DisplayMode="Write" Expanded="true" DataFieldName="BraftonPrivateKey" WrapperTag="div"
        ExpandText="Change" CssClass="sfFormCtrl">
        <validatordefinition required="false" messagecssclass="sfError" requiredviolationmessage="" />
</sfFields:TextField>
There's a js file and a cs file of the same name I think are being involved in the saving, I have posted those in addition to the file the code is in. If anything else is needed let me know.

https://www.dropbox.com/s/6dwro49a55cla2l/code.zip

As I said I don't have an abundance of experience with .Net or Sitefinity and the time frame I was given to accomplish this in isn't helping either of those. I don't want someone to write code, but what/where the code that does the saving and how it works would be great, as I can't seem to find it.

If this is something simple and I can learn it quickly with a few tutorials, please let me know.

uXs
May 3, 2005

Mark it zero!
EF question:

I have some views in my edmx, and EF is now giving me this warning:

"Error 6002: The table/view 'blablabla' does not have a primary key defined. The key has been inferred and the definition was created as a read-only table/view. C:\...\xyz.edmx 1 1"

This is perfectly fine, the correct columns are chosen as the primary key, and all is great.

Except that I really, really, really detest any and all warnings in my solutions, and I can't seem to get rid of these. Someone tell me how to remove those warnings because I'm ready to shoot someone. And then throw my PC through the window.

Edit: this guy saved the life of some of my coworkers: http://thecurlybrace.blogspot.be/2012/02/suppress-ef-compiler-warnings-error.html

uXs fucked around with this message at 13:32 on Jan 8, 2014

zerofunk
Apr 24, 2004
Can you not just add a PK to the table? You should probably have one anyway.

epswing
Nov 4, 2003

Soiled Meat

I don't know for sure, but it sounds like settings Validate On Build to false might suppress ALL warnings. In the future you might miss something obvious, no?

ljw1004
Jan 18, 2005

rum

TheReverend posted:

I'm doing simple algebraic operations like finding where two lines intersect, etc. My function works fine with smaller numbers, but when I get to coordinates like: [snip] I get an answer (for where the two lines intersect) that's close. Its off by about ~.202 on the X and ~.58 on the Y.

Q. How do you know it's off?

I tried your code with decimal as you wrote, then with double, then with BigRational. They were all in agreement to within 0.0000001.

I wonder if your code is indeed correctly implementing the formula you want, and doing so with acceptable accuracy. I wonder if either you've got the wrong formula, or if your idea about what the correct answer should be is itself wrong?

TheReverend
Jun 21, 2005

I guess it's possible.
The other possibility is that maybe the "answer" I was provided was wrong.

I guess I'll keep digging.

Combat Pretzel
Jun 23, 2004

No, seriously... what kurds?!
I've been bit by the optimizer in the JIT for the first time. First time I'm aware of, anyway.

Any particular reason why this ugly code would break? When I remove the MethodImpl and let the JIT do it's thing, it stops executing properly, without throwing any errors. Note that I'm counting executions at the bottom, the number rose as expected. However none of the calls to the sub-methods went through. Took me tons of lovely hacks and time to narrow it down to this. Options is an enum and the .HasFlag() static method belongs to the enum. It's quasi a system class, yet it seems to break.
code:
// No optimization, because it breaks this method for whatever reason.
[MethodImpl(MethodImplOptions.NoOptimization)]
protected override void Render(int[] buffer, int width, int height, float[] audiobuffer)
{
	substeps = Options.HasFlag(RenderOptions.DoubleSpeed) ? 16 : 8;

	// Move buffer
	Array.Copy(rollingBuffer, samplingSize, rollingBuffer, 0, samplingSize);
	Array.Copy(audiobuffer, 0, rollingBuffer, samplingSize, samplingSize);

	// Shift pixelbuffer for new FFT data.
#if __ARM
	Array.Copy(buffer, substeps, buffer, 0, buffer.Length - substeps);
#else
	fastCopy.Copy(buffer, substeps, buffer, 0, buffer.Length - substeps);
#endif

	if (Options.HasFlag(RenderOptions.Stereo))
	{
		int hh = height / 2;
		if (Options.HasFlag(RenderOptions.Logarithmic))
		{
			RenderLog(buffer, width, hh, 0, rollingBuffer, 0, 2048);
			RenderLog(buffer, width, hh, hh, rollingBuffer, 1, 2048);
		}
		else
		{
			if (Options.HasFlag(RenderOptions.Zoom2X))
			{
				RenderZoom(buffer, width, hh, 0, rollingBuffer, 0, 2048, 2);
				RenderZoom(buffer, width, hh, hh, rollingBuffer, 1, 2048, 2);
			}
			else if (Options.HasFlag(RenderOptions.Zoom3X))
			{
				RenderZoom(buffer, width, hh, 0, rollingBuffer, 0, 2048, 3);
				RenderZoom(buffer, width, hh, hh, rollingBuffer, 1, 2048, 3);
			}
			else
			{
				Render(buffer, width, hh, 0, rollingBuffer, 0, 2048);
				Render(buffer, width, hh, hh, rollingBuffer, 1, 2048);
			}
		}
	}
	else
	{
		if (Options.HasFlag(RenderOptions.Logarithmic))
		{
			RenderLog(buffer, width, height, 0, rollingBuffer, 0, 2048);
		}
		else
		{
			if (Options.HasFlag(RenderOptions.Zoom2X))
			{
				RenderZoom(buffer, width, height, 0, rollingBuffer, 0, 2048, 2);
			}
			else if (Options.HasFlag(RenderOptions.Zoom3X))
			{
				RenderZoom(buffer, width, height, 0, rollingBuffer, 0, 2048, 3);
			}
			else
			{
				Render(buffer, width, height, 0, rollingBuffer, 0, 2048);
			}
		}
	}
	DebugStats.FourierCount++;
}

ljw1004
Jan 18, 2005

rum

Combat Pretzel posted:

I've been bit by the optimizer in the JIT for the first time. First time I'm aware of, anyway.
Any particular reason why this ugly code would break?

If you're able to make a small self-contained repro, I'll pass it on to the CLR codegen team. They're pretty passionate about this kind of thing. Say whether it's Release or Debug, and whether it's on ARM or Intel, and whether it's x86 or x64.

Combat Pretzel
Jun 23, 2004

No, seriously... what kurds?!
In my project, it happens in Release mode, as long you don't launch it within VS with the debugger attached. That's what made it perplexing to find. I'll try to figure a way out to reproduce it later this week.

uXs
May 3, 2005

Mark it zero!

epalm posted:

I don't know for sure, but it sounds like settings Validate On Build to false might suppress ALL warnings. In the future you might miss something obvious, no?

Yeah, but it's just on build. I'll still get warnings when I'm changing something in the designer.

mortarr
Apr 28, 2005

frozen meat at high speed

Sedro posted:

AppDomain.CurrentDomain.GetAssemblies will only return assemblies which are loaded at the time, and they are often lazy loaded as part of the IoC container's job.

Try BuildManager.GetReferencedAssemblies.

Thanks, that did the business.

raminasi
Jan 25, 2005

a last drink with no ice
I have a dataset that needs to be presented visually in a variety of different ways, depending on a user's whim. As a toy example, the dataset is just x-y pairs, and I want to be able to show both a scatterplot of all the points and a histogram of the y-values. I've got the WPF Toolkit installed, so the actual charts themselves are (presumably) taken care of, and getting the varied format capability set up doesn't seem hard, except that I'd like to make this functionality easily reusable. Ideally, it seems like I want to build a single WPF control that just presents differently depending on how its properties are set, but I'm not sure how to do that or whether it's the best option.

sadus
Apr 5, 2004

Sanity check: working on a Windows service to hit a WebApi2 API (.NET 4.5 of course). Unfortunately I need to support Windows 2003 clients, so limited to .NET 4.0, which is incompatible with the WebApi2 client. :suicide:

I'm thinking of just using the last free ServiceStack 3.x client until Windows 2003 is dead and gone, or does anyone know of a better RESTful API client that doesn't require .NET 4.5? I'm not even using any task/async stuff in the api yet, if I do need to I suppose I could always have a Win2003 version of the service with ServiceStack.net and another version for non-ancient-servers, but that doesn't like much fun to maintain.

ManoliIsFat
Oct 4, 2002

sadus posted:

I'm thinking of just using the last free ServiceStack 3.x client until Windows 2003 is dead and gone, or does anyone know of a better RESTful API client that doesn't require .NET 4.5? I'm not even using any task/async stuff in the api yet, if I do need to I suppose I could always have a Win2003 version of the service with ServiceStack.net and another version for non-ancient-servers, but that doesn't like much fun to maintain.
http://restsharp.org/ is really straightforward and what I usually go for when I need to bang out some quick communication with a REST service. It's really dead simple. Uses 3.5+

Literal Hamster
Mar 11, 2012

YOSPOS
I'm trying to get a WPF TextBox to display the contents of an exception object's message string but my inexperience with .Net is killing me.

How do I databind my TextBox to my string ErrorMessage variable? For reference, here's the class:

code:
namespace ENB_Manager
{
	/// <summary>
	/// Interaction logic for ErrorWindow.xaml
	/// </summary>
	public partial class ErrorWindow : Window, INotifyPropertyChanged
	{
		public ErrorWindow() { InitializeComponent(); }
		public string ErrorMessage;
	}
}

epswing
Nov 4, 2003

Soiled Meat

ErrorMessage is a field, and what you want is to bind to a property:

C# code:
	public partial class ErrorWindow : Window, INotifyPropertyChanged
	{
		public ErrorWindow() { InitializeComponent(); }
		public string ErrorMessage { get; set; }
	}
}
Edit: c# will magically turn my code above into a property with a backing field which looks roughly like this:

C# code:
	public partial class ErrorWindow : Window, INotifyPropertyChanged
	{
		public ErrorWindow() { InitializeComponent(); }
		public string errorMessage;
		public string ErrorMessage
		{
			get { return errorMessage; }
			set { errorMessage = value; }
		}
	}
}

epswing fucked around with this message at 23:46 on Jan 8, 2014

Adbot
ADBOT LOVES YOU

ManoliIsFat
Oct 4, 2002

Don't forget you've also gotta notify if ErrorMessage is ever gonna change.

  • Locked thread