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
Dirk Pitt
Sep 14, 2007

haha yes, this feels good

Toilet Rascal

Mr. Crow posted:

Tangentially on the topic of DI/IoC, what are you guy's preferred MVVM + IoC frameworks these days (WPF/Silverlight)?

Anyone heard of and used Catel?

I am using mvvm cross for my latest winphone app and so far seems to work.

Our enterprise 'standard' used to be no framework. That was a headache...

Adbot
ADBOT LOVES YOU

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

ljw1004 posted:

Gosh, I've not used IOC/DI myself, and after that video I strongly don't want to.

(1) His code had one bug (what happens if the clock ticks over to 8pm between his two if statements) but nothing in his testing framework helped found it. The bug was only accidentally fixed in his refactoring. To be honest, most of the bugs I face are race conditions. Maybe that's just because I try to create more interactive responsive or parallelized code than usual, or maybe I'm not as good at it than others, but all of the talk's IOC/DI seemed to making it harder to spot such issues.

(2) I usually output text to the console, save this into a "baseline.txt" file that I check in. Then when I make changes to the code I compare my new "results.txt" to the original. It's simply and robust and works well. By contrast he turned his code into spaghetti to achieve THE SAME functionality within unit tests. Why? (It looked like he also had to murder his public/internal accessibility to achieve it; I just stick my code into a test exe as a linked file, so it can keep its internal accessibility).

(3) All of it was motivated by wanting to test his code against DateTime.Now. But almost no code is sensitive to that kind of thing. Instead it's sensitive to the complex set of data that goes in, e.g. the Word document that you're loading, or the set of rows in your Azure table. These things are already naturally mockable (just by loading a different document, or pointing to a test database) so I don't see that it buys anything.



There's a saying in computer science that "every problem can be solved by adding a layer of indirection". My position is: "Adding a layer of indirection always creates more problems than it solves".

In my opinion, the real benefit of unit tests and, by extension, IoC isn't what all the videos show you. All the information talks about a green field application and how to start with unit tests, which is great but doesn't show the real power. It's most useful when you pick up a project that another developer stopped working on 3 months ago to fix some obscure bug that the customer finally found. The unit tests show you what the return values should be and give you some insight into the application. You write your failing unit test for the bug, fix the bug, then run unit tests for every single other bug ever fixed to make sure you didn't break anything in the process.

Mr. Crow
May 22, 2008

Snap City mayor for life

Dirk Pitt posted:

I am using mvvm cross for my latest winphone app and so far seems to work.

Our enterprise 'standard' used to be no framework. That was a headache...

I haven't heard of this, seems really cool at first glance, watching this video.

epswing
Nov 4, 2003

Soiled Meat

Mr. Crow posted:

I haven't heard of this, seems really cool at first glance, watching this video.

Holy crap.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Mr. Crow posted:

I haven't heard of this, seems really cool at first glance, watching this video.

That's nothing new. Xamarin and Monotouch have been around for ages.

Personally, I'm still not using any MVVM frameworks when I mess around with WPF. I just haven't seen any compelling features that would convince me to use one.

Mr. Crow
May 22, 2008

Snap City mayor for life

Ithaqua posted:

That's nothing new. Xamarin and Monotouch have been around for ages.

Personally, I'm still not using any MVVM frameworks when I mess around with WPF. I just haven't seen any compelling features that would convince me to use one.

Seems ideal for larger teams, like Dirk we aren't using one and I can see plenty of benefits of migrating over to one at some point.

The only reason I use them on personal projects is to try out and learn the framework itself.

TheSleeper
Feb 20, 2003

Bognar posted:

In my opinion, the real benefit of unit tests and, by extension, IoC isn't what all the videos show you. All the information talks about a green field application and how to start with unit tests, which is great but doesn't show the real power. It's most useful when you pick up a project that another developer stopped working on 3 months ago to fix some obscure bug that the customer finally found. The unit tests show you what the return values should be and give you some insight into the application. You write your failing unit test for the bug, fix the bug, then run unit tests for every single other bug ever fixed to make sure you didn't break anything in the process.

There's that and there's also the benefit of being able to (relatively) quickly switch out anything that is being injected. For example, we've abstracted out our caching into an ICacheProvider interface and made a few implementations. When we found some limitations of the method we were using, we just added a few lines of configuration, spun up a memcached server and swapped out providers in our Autofac registry. It literally took me longer to get a memcached server downloaded, installed and working on my local for testing than it did to do all the code/configuration changes.

fankey
Aug 31, 2001

I'm having trouble figuring out an async memory leak. I have the following code
code:

    void dt_Tick(object sender, EventArgs e)
    {
      foreach (var device in Devices)
      {
#pragma warning disable 4014
        UpdateDevice(device);
#pragma warning restore 4014
      }
    }

    static WebClient wc = new WebClient();

    async public static Task<DeviceStatus> GetDeviceStatus(string ipAddress)
    {
      UriBuilder ub = new UriBuilder("http", ipAddress, 80, "cgi-bin/status_xml");
      var crap = await wc.DownloadDataTaskAsync(ub.Uri);
      return new DeviceStatus();
    }

    async Task UpdateDevice(DeviceInfo device)
    {
      if (device.IsUpdating) return;
      try
      {
        device.IsUpdating = true;
        if (device.LastGoodIp == null)
        {
          device.LastGoodIp = await Discovery.Util.GetBestIpAsync(device.Ips);
        }
        if (device.LastGoodIp != null)
        {
          // removing the await from here fixes the leak
          var x = await GetDeviceStatus(device.LastGoodIp);
        }
      }
      catch (Exception ex)
      {
        device.LastGoodIp = null;
        device.ErrorString = ex.Message;
      }
      device.IsUpdating = false;
    }
where dt_Tick is being called from a DispatchTimer. When I await the return of GetDeviceStatus memory use grows continuously. If I remove that await memory is stable. I'm using .NET 4.0 using the Async Targeting Pack.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

fankey posted:

I'm having trouble figuring out an async memory leak. I have the following code
code:

    void dt_Tick(object sender, EventArgs e)
    {
      foreach (var device in Devices)
      {
#pragma warning disable 4014
        UpdateDevice(device);
#pragma warning restore 4014
      }
    }

    static WebClient wc = new WebClient();

    async public static Task<DeviceStatus> GetDeviceStatus(string ipAddress)
    {
      UriBuilder ub = new UriBuilder("http", ipAddress, 80, "cgi-bin/status_xml");
      var crap = await wc.DownloadDataTaskAsync(ub.Uri);
      return new DeviceStatus();
    }

    async Task UpdateDevice(DeviceInfo device)
    {
      if (device.IsUpdating) return;
      try
      {
        device.IsUpdating = true;
        if (device.LastGoodIp == null)
        {
          device.LastGoodIp = await Discovery.Util.GetBestIpAsync(device.Ips);
        }
        if (device.LastGoodIp != null)
        {
          // removing the await from here fixes the leak
          var x = await GetDeviceStatus(device.LastGoodIp);
        }
      }
      catch (Exception ex)
      {
        device.LastGoodIp = null;
        device.ErrorString = ex.Message;
      }
      device.IsUpdating = false;
    }
where dt_Tick is being called from a DispatchTimer. When I await the return of GetDeviceStatus memory use grows continuously. If I remove that await memory is stable. I'm using .NET 4.0 using the Async Targeting Pack.

Did you try
code:
async void dt_Tick(object sender, EventArgs e)
    {
      foreach (var device in Devices)
      {
#pragma warning disable 4014
        await UpdateDevice(device);
#pragma warning restore 4014
      }
    }
or

code:
async void dt_Tick(object sender, EventArgs e)
    {
      await Task.WhenAll(Devices.Select(UpdateDevice));
    }

ljw1004
Jan 18, 2005

rum

fankey posted:

I'm having trouble figuring out an async memory leak. ...
When I await the return of GetDeviceStatus memory use grows continuously. If I remove that await memory is stable. I'm using .NET 4.0 using the Async Targeting Pack.

(1) Please tell me that you're using the nuget package Microsoft.Bcl.Async rather than the old flakey "compatibility pack"...

(2) You should understand that that async makes certain inherent heap allocations, but there are ways to minimize them. I recorded a short channel9 video on the subject here that you should definitely watch: http://channel9.msdn.com/Series/Three-Essential-Tips-for-Async/Async-libraries-APIs-should-be-chunky

(3) The very concept "memory leak" is unclear in .NET. Do you mean that stuff is being allocated on the heap, causing need for a subsequent garbage collection? As per the above video, that's inherent with async methods but its impact can be reduced. Or do you mean that stuff is being allocated but the GC is unable to free it because there remains a live reference to it? That's possible with poorly written code, including poorly written code in the framework or in the old flakey async compatibility pack, but it's hard to diagnose without a complete minimal self-contained repro.

(4) In the VB/C# compiler team our perf experts spend a lot of time discovering how our code is causing "GC pressure" (a nicer term than "memory leak"!). I think they primarily use PerfView and the equivalent that's built into VS. The game is always the same: run your code, use PerfView to discover which objects are taking up all the space on the heap, and figure out which bits of code exactly are allocating them.



One thing I'd start by asking: how is the memory allocation pattern different in these three examples?
code:
// OPTION 1: the synchronous version, which you said was fine
var x = GetDeviceStatus(device.LastGoodIp);

// OPTION 2: when you change it to async you suffered memory problems
var x = await GetDeviceStatusAsync(device.LastGoodIp);

// OPTION 3: is the problem caused by Await? or by GetDeviceStatusAsync?
await Task.Yield();
var x = GetDeviceStatus(device.LastGoodIp);
When you have a regular method with no awaits in it then the JIT knows that it can always GC all local variables as soon as they go out of scope. This is good. But when you have an async method which does an await, then the local variables get lifted into fields of a state machine, so they no longer get GC'd immediately by the JIT.




EDIT: You might also consider this idiom for a watcher which says repeatedly whether the thing is up and doesn't involve allocations. Or also RX.
code:
async Task WatchDeviceAsync(DeviceInfo device, IProgress<bool> progress)

ljw1004 fucked around with this message at 21:44 on Feb 14, 2014

fankey
Aug 31, 2001

Ithaqua posted:

Did you try
Both still leak.

fankey
Aug 31, 2001

ljw1004 posted:

(1) Please tell me that you're using the nuget package Microsoft.Bcl.Async rather than the old flakey "compatibility pack"...
Yes - looks like 1.0.16

ljw1004 posted:

(2) You should understand that that async makes certain inherent heap allocations, but there are ways to minimize them. I recorded a short channel9 video on the subject here that you should definitely watch: http://channel9.msdn.com/Series/Three-Essential-Tips-for-Async/Async-libraries-APIs-should-be-chunky
I'll check out the video

ljw1004 posted:

(3) The very concept "memory leak" is unclearin .NET.
I added a GC.Collect() and GC.WaitForFullGCComplete() after each timer call and memory still grew. I'm not sure if that means there an actual memory leak or not.

ljw1004 posted:

(4) In the VB/C# compiler team our perf experts spend a lot of time discovering how our code is causing "GC pressure" (a more technically precise term than "memory leak"). I think they primarily use PerfView and the equivalent that's built into VS. The game is always the same: run your code, use PerfView to discover which objects are taking up all the space on the heap, and figure out which bits of code exactly are using them.
I've been using Process Explorer. I'll check out PerfView.

ljw1004 posted:

One thing I'd start by asking: how is the memory allocation pattern different in these three examples?
code:
// OPTION 1: the synchronous version, which you said was fine
var x = GetDeviceStatus(device.LastGoodIp);

// OPTION 2: when you change it to async you suffered memory problems
var x = await GetDeviceStatusAsync(device.LastGoodIp);

// OPTION 3: is the problem caused by Await? or by GetDeviceStatusAsync?
await Task.Yield();
var x = GetDeviceStatus(device.LastGoodIp);
When you have a regular method with no awaits in it then the JIT knows that it can always GC all local variables as soon as they go out of scope. This is good. But when you have an async method, then the local variables get lifted into fields of a state machine, so they no longer get GC'd immediately by the JIT.
Option 3 acts like 1 - memory doesn't grow.

I'm going to work on a simple repro example.

Funking Giblet
Jun 28, 2004

Jiglightful!
Memory dump and windbg.

Is dt_Tick being attached to a multicast delegate without being removed later?

Secx
Mar 1, 2003


Hippopotamus retardus
I've been struggling with the ConfigurationManager class trying to get it to read a value from my App.config file. It is copied to the Debug directory when I compile and it contains the key/value pair I stored in it. I restarted a blank project with the bare minimum to isolate potential issues, but it still won't read my configuration value. I just get an empty value when I try to read it.

After much googling and searches on StackOverflow I found that you could use Properties.Settings.Default which works! But after spending so much time on what was supposed to something trivial to implement in C#, I'd like to know why my implementation below doesn't work. This is on Visual Studio 2013 and .NET 4.5.

Here's my whole test program:

code:
using System;
using System.Windows.Forms;
using System.Configuration;

namespace ConfigTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {   
            InitializeComponent();
            System.Console.WriteLine(ConfigurationManager.AppSettings["pdfinputdir"]); //does not work
            System.Console.WriteLine(Properties.Settings.Default.pdfinputdir); //works
        }
    }
}
My App.config:

code:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
            <section name="ConfigTest.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
        </sectionGroup>
    </configSections>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
    </startup>
    <applicationSettings>
        <ConfigTest.Properties.Settings>
            <setting name="pdfinputdir" serializeAs="String">
                <value>pdf</value>
            </setting>
        </ConfigTest.Properties.Settings>
    </applicationSettings>
</configuration>

Secx fucked around with this message at 03:28 on Feb 18, 2014

aBagorn
Aug 26, 2004
ConfigurationManager.AppSettings["pdfinputdir"] is looking for this XML format
code:

<appSettings>
<add key="pdfinputdir" value="pdf"/>
</appSettings>

aBagorn fucked around with this message at 03:47 on Feb 18, 2014

raminasi
Jan 25, 2005

a last drink with no ice

Sedro posted:

XML code:
<StackPanel>
    <Button x:Name="FirstButton" Content="First"/>
    <Button x:Name="SecondButton" Content="Second"/>
    <Button x:Name="ThirdButton" Content="Third"/>
    <Label>
        <Label.Style>
            <Style TargetType="{x:Type Label}">
                <Setter Property="Content" Value="Nothing hovered"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsMouseOver, ElementName=FirstButton}" Value="True">
                        <Setter Property="Content" Value="First button hovered"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding IsMouseOver, ElementName=SecondButton}" Value="True">
                        <Setter Property="Content" Value="Second button hovered"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding IsMouseOver, ElementName=ThirdButton}" Value="True">
                        <Setter Property="Content" Value="Third button hovered"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Label.Style>
    </Label>
</StackPanel>

This was several pages ago, but I wanted to thank you! I just got around to using it and it works great.

Sedro
Dec 31, 2008
Great! Thanks for following up :)

RICHUNCLEPENNYBAGS
Dec 21, 2010
This is more curiosity than anything else, but do any of you have any of the C# certifications MS puts out? Is there any reason to be interested if you're already a working developer?

shrughes
Oct 11, 2008

(call/cc call/cc)

RICHUNCLEPENNYBAGS posted:

This is more curiosity than anything else, but do any of you have any of the C# certifications MS puts out? Is there any reason to be interested if you're already a working developer?

No.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

RICHUNCLEPENNYBAGS posted:

This is more curiosity than anything else, but do any of you have any of the C# certifications MS puts out? Is there any reason to be interested if you're already a working developer?

I did 70-483 (Programming in C#) on a whim, mainly because I had some downtime at work and my employer was paying for it. It was really easy. The next two in sequence for an MCSD look like they're tougher and have far more limited usefulness (Windows App Store! :toot: ), so I haven't bothered.

It's one of those things where it doesn't hurt to have the certs, but I certainly wouldn't go out of my way to get them.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
Since we were recently on the topic of memory leaks, can anyone explain why this causes an unmanaged memory leak in WPF?

C# code:
<Image Source="{Binding AbsolutePath}" />
I can load around 200 small PNG files (~100 KB) before I get an out of memory exception. Calls to GC.Collect and WaitForPendingFinalizers don't do anything. To work around the problem, I had to do some stupid poo poo like subscribing to the image's unloaded event and setting its source's URI to null.

zokie
Feb 13, 2006

Out of many, Sweden
Anyone done 70-461, sql something something? Was it hard?

Mr. Crow
May 22, 2008

Snap City mayor for life

Bognar posted:

Since we were recently on the topic of memory leaks, can anyone explain why this causes an unmanaged memory leak in WPF?

C# code:
<Image Source="{Binding AbsolutePath}" />
I can load around 200 small PNG files (~100 KB) before I get an out of memory exception. Calls to GC.Collect and WaitForPendingFinalizers don't do anything. To work around the problem, I had to do some stupid poo poo like subscribing to the image's unloaded event and setting its source's URI to null.

Try freezing your images http://msdn.microsoft.com/en-us/library/ms750509(v=vs.110).aspx

Mr. Crow fucked around with this message at 16:04 on Feb 19, 2014

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

I tried that as well with no effect. The only thing that seems to have worked at all is manually setting references to null.

wwb
Aug 17, 2004

We've got a little project that involves reading a bunch of PDFs and making them searchable. We can handle the whole "take bags of text and make it searchable" pretty easily but we are having some trouble with the reading PDFs end of the equation.

We've tried using PdfTextract which is a pretty thin wrapper on the last free version of PdfSharp before they went commercial with limited success. We have also tried Docotic.Pdf which seems to work but I really hate to pay $1k to read PDFs. Is there anything else out there that is reliable for less or better yet free*?

* money isn't really the problem, all the overhead of dealing with license components rubs me wrong and is a pain in the rear end with the CI setup we've got.

raminasi
Jan 25, 2005

a last drink with no ice
Any idea why I would get a TypeInitializationException "The type initializer for '<Module>' threw an exception" with the inner exception a CryptographicException "Padding is invalid and cannot be removed?" I'm assuming it's some kind of assembly loading problem (my application doesn't use crypto for anything) but since every object in the offending call has already been instantiated (and thus, all relevant assemblies appear to have loaded) I haven't the faintest idea what the problem could be or how to diagnose or fix it.

zokie
Feb 13, 2006

Out of many, Sweden
Google gave me this, is it a desktop application or a web-thingy?

raminasi
Jan 25, 2005

a last drink with no ice
It's desktop.

Opulent Ceremony
Feb 22, 2012

wwb posted:

Is there anything else out there that is reliable for less or better yet free*?

I've used a couple of different libraries at work and the only one I was able to find that did everything I needed was iTextSharp. It is free and has been around long enough that there are tons of StackOverflow posts on how to get stuff done. It is however not the most user-friendly API. I've never used it to capture PDF text but a cursory search looks like it is capable of that.

wwb
Aug 17, 2004

Thanks, iTextSharp was the 1st cut -- the last free version is 4.1.6 which specifically doesn't work with documents higher than v6 and seems to be barfing on a lot of the documents I've got. Checks the box but doesn't do it so well unfortunately.

Now, I have started to figure out some of iTextSharp's problem -- these PDFs had some embedded search because they are off those old "buy a book on CD" sort of things that embedded poo poo in PDFs. Rebuilding everything as pdf/a to see if that helps.

PS: how much is iText these days? Good question -- they won't even tell you, you have to tell them what you are doing and they give you a round number.

wwb fucked around with this message at 19:41 on Feb 20, 2014

mobby_6kl
Aug 9, 2009

by Fluffdaddy
Still on the subject of memory leaks, what's the general approach to tracking them down? I have what seems like a pretty easy situation - BackgroundWorker does some stuff and generates a DataTable, which is then used in another window/class. When it's closed, however, the DataTable sticks around even though it shouldn't be used by anything any longer. I can't just delete it and see what blows up so I'm kind of stuck there :(

raminasi
Jan 25, 2005

a last drink with no ice
I'm using the WPF Extended Toolkit ColorPicker, and I want to remove its text headers. This doesn't appear to be easily customizable. Is there some way I can reach into it and hide them without retemplating the whole thing? The tricky bit is that the target TextBlocks don't have names. I've got access to the default template (via this stackoverflow post). Basically I want to do this, except the target element isn't named.

Sedro
Dec 31, 2008

mobby_6kl posted:

Still on the subject of memory leaks, what's the general approach to tracking them down? I have what seems like a pretty easy situation - BackgroundWorker does some stuff and generates a DataTable, which is then used in another window/class. When it's closed, however, the DataTable sticks around even though it shouldn't be used by anything any longer. I can't just delete it and see what blows up so I'm kind of stuck there :(
Windbg. Find what's using the memory with !dumpheap, then pick an address and see what's pinning it with !gcroot. I'll show you a quick example.

Start off by listing types with lots of bytes allocated:
pre:
0:010> .loadby sos clr
0:010> !dumpheap -stat -min 10000
Statistics:
      MT    Count    TotalSize Class Name
5179cf14        1     20971532 System.Byte[]
Total 1 objects
Ok, there's a large byte array. List the individual addresses:
pre:
0:010> !dumpheap -type System.Byte[] -min 10000
 Address       MT     Size
04cf1000 5179cf14 20971532     

Statistics:
      MT    Count    TotalSize Class Name
5179cf14        1     20971532 System.Byte[]
Total 1 objects
Ok, found an address, now let's see where it's pinned:
pre:
0:010> !gcroot 04cf1000 
Thread 15a0:
    0040ef10 0f5ccc30 DomainBoundILStubClass.IL_STUB_PInvoke(System.Windows.Interop.MSG ByRef, System.Runtime.InteropServices.HandleRef, Int32, Int32)
        ebp-c: 0040ef4c
            ->  0224ad18 System.Windows.Threading.Dispatcher
            ->  022d8760 System.EventHandler
            ->  022ce724 System.Object[]
            ->  022cc948 System.EventHandler
            ->  022cc080 System.Windows.Media.MediaContext
            ->  022cc218 System.Collections.Generic.Dictionary`2[[System.Windows.Media.ICompositionTarget, PresentationCore],[System.Object, mscorlib]]
            ->  022cdcf0 System.Collections.Generic.Dictionary`2+Entry[[System.Windows.Media.ICompositionTarget, PresentationCore],[System.Object, mscorlib]][]
            ->  022cb8fc System.Windows.Interop.HwndTarget
            ->  02276ac8 MemoryLeakTest.MainWindow
            ->  04cf1000 System.Byte[]

Found 1 unique roots (run '!GCRoot -all' to see all roots).
Found it!
C# code:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    byte[] leak = new byte[20 * 1024 * 1024];
}

Mr. Crow
May 22, 2008

Snap City mayor for life

mobby_6kl posted:

Still on the subject of memory leaks, what's the general approach to tracking them down? I have what seems like a pretty easy situation - BackgroundWorker does some stuff and generates a DataTable, which is then used in another window/class. When it's closed, however, the DataTable sticks around even though it shouldn't be used by anything any longer. I can't just delete it and see what blows up so I'm kind of stuck there :(

In .Net both jetbrains and redgate have really good profilers that I typically use. Both cost, but Jetbrains has a rework of their old one in EAP and I've used it to resolve some really painfully obscure hanging event handlers keeping Windows in memory. Given its EAP it's missing some UX features but is faster than Redgates in my experience. Redgates is more mature though obviously which has its benefits (but is significantly more expensive as well).

Edit: derp this is the .Net thread.

sausage king of Chicago
Jun 13, 2001
Would someone PLEASE help me out. I'm working on a small personal project using the Yahoo Fantasy Sports API and I've been stuck for like, 2 weeks trying to figure this out and I want to cry.

All I'm trying to do is make a call to the Yahoo API. I'm able to able to authenticate using OAuth 1.0 and get an access token. The problem I'm having is when I'm actually making the request and I have to send a signature signed with HMACSHA1. I'm using OAuthBase.cs and this to help me check my signatures. However, I keep getting a 401 with oauth_problem="ST_OAUTH_SIGNATURE_INVALID_ERROR!

My method to create a request:

php:
<?
        public void CreateRequest(string token)
        {
            string baseURI = "http://query.yahooapis.com/v1/yql?";
             OAuthBase o = new OAuthBase();

            var authorizeUri = new StringBuilder();
            string query = "select * from fantasysports.players where league_key='314.l.408939'";
            string nonce = o.GenerateNonce();
            string timestamp = o.GenerateTimeStamp();
            string token_secret = (string)Session["oauth_token_secret"];

            authorizeUri.AppendFormat("callback={0}&", "");
            authorizeUri.AppendFormat("format={0}", "json");
            //authorizeUri.AppendFormat("q={0}", query);

            Uri url = new Uri(baseURI + authorizeUri.ToString());
            string normalizedURL;
            string normalizedRequestParameters;

            string sig = o.GenerateSignature(url, consumer, secret, token, token_secret,
                                                     "GET", timestamp, nonce, out normalizedURL, out normalizedRequestParameters);

            var queryUri = new StringBuilder();
            queryUri.AppendFormat("callback={0}&", "");
            queryUri.AppendFormat("format={0}", "json");
            //queryUri.AppendFormat("q={0}", HttpUtility.UrlEncode(query));
            var request = (HttpWebRequest)WebRequest.Create(baseURI + queryUri);
            request.Method = "GET";
            var header = new StringBuilder();            
            
            header.AppendFormat("OAuth realm={0},", "\"yahooapis.com\"");
            header.AppendFormat("oauth_consumer_key={0},", "\"" + o.UrlEncode(consumer) + "\"");
            header.AppendFormat("oauth_nonce={0},", "\"" + o.UrlEncode(nonce) + "\"");
            header.AppendFormat("oauth_signature_method={0},", "\"" + o.UrlEncode("HMAC-SHA1") + "\"");
            header.AppendFormat("oauth_timestamp={0},", "\"" + o.UrlEncode(timestamp) + "\"");
            header.AppendFormat("oauth_token={0},", "\"" + o.UrlEncode(token) + "\"");
            header.AppendFormat("oauth_version={0},", "\"" + o.UrlEncode("1.0") + "\"");
            header.AppendFormat("oauth_signature={0}", "\"" + o.UrlEncode(sig) + "\"");

            request.Headers["Authorization"] = header.ToString();
            request.ContentType = "Content-Type: application/x-www-form-urlencoded";                                                                                                                                                              

            try
            {                
                HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
                var result = webResponse.GetResponseStream();
               
            }
            catch (Exception ex)
            {                                
            }
        }
?>
An example of my base string(semi formatted for readability):

code:
GET&http%3A%2F%2Fquery.yahooapis.com%2Fv1%2Fyql
&callback%3D%26format%3Djson%26
oauth_consumer_key%3Ddj0yJmk9VzNvYlF5WGF2ZVRMJmQ9WVdrOWVHZDZWa2RXTm04bWNHbzlNVE13TkRjek1ESTJNZy0tJnM9Y29uc3VtZXJzZWNyZXQmeD04Mw--
%26
oauth_nonce%3D6520562%26
oauth_signature_method%3DHMAC-SHA1%26
oauth_timestamp%3D1392955530%26
oauth_token%3DA%253DqR7cnpbpnzHdZZpejD.XEfhPkujRgCi4DT3a1Zk7epEj3WZTD5BNwuhoeAEIuaAtY8cZG1TIPWg3jNw_QuOz12GzXltbTTmIHv2zObG9kGb.hG5i7Q4g
FiiJGY7QgqInhJFs7F_DHMOzhdRS6jbLSgSEg9slSwv8TUSySeOLZblJfh3irsIpmeVeU_677hN4thP9lK9Vm0oRljYZrlU8ID.nRsxop.YESnUmYgBGFSHnvMJbx0FYR8_KmgFa
07GVZ8cxow216PYxtsLkHPcaUgfqV79imy4mperJ2st6dzbtnYdm7cHHFu7GObC4rc8D4nVNBFcfIqjPVo_vr.RZxgKzuXaEUUbf3WTp05ltmzQHIXtqFB1oKxtZtxs_o_mY.vNB
gRBEw4aFNOLFgYaxQDYmmRKCHjKtLS0WVQ0MYFlN96pjbOCM.dc0daXlZwIT8.WeOVjcN_UPWMwwoaSXA9fLYckbsSftzpjv_7j9pZIj31bRfSyFN9DS.R7Bt8e79PG7B.3he9wR
QNB5g30rOzbvpLTvnaGdbUB.rMaFeq3nKFI05IY60WH3QyHn4JpVEbdfy4GZC5QZdtybODNSwmhwkp_u7_mvlJwxdncP3bPc.wpiOPQPGKXL9ens2zwFfTyJrii8w4Skm4ShHF6T
nSaDLuPyQ65X.YC9zqdyA7ClXlvgk4miB7hbybeu0cRhYMxVVhSLFu3jA2QzbXXvR_Wp5CNhOleyfiXyOSiUvrk4yYrjKvaqGejx3C3OMMhat_Udp5MLfUgEzzmJzcxPOg--
%26oauth_version%3D1.0
and my header:

code:
Authorization: OAuth realm="yahooapis.com",
oauth_consumer_key="dj0yJmk9VzNvYlF5WGF2ZVRMJmQ9WVdrOWVHZDZWa2RXTm04bWNHbzlNVE13TkRjek1ESTJNZy0tJnM9Y29uc3VtZXJzZWNyZXQmeD04Mw--",
oauth_nonce="6520562",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1392955530",
oauth_token="A%3DqR7cnpbpnzHdZZpejD.XEfhPkujRgCi4DT3a1Zk7epEj3WZTD5BNwuhoeAEIuaAtY8cZG1TIPWg3jNw_QuOz12GzXltbTTmIHv2zObG9kGb.hG5i7Q4gFii
JGY7QgqInhJFs7F_DHMOzhdRS6jbLSgSEg9slSwv8TUSySeOLZblJfh3irsIpmeVeU_677hN4thP9lK9Vm0oRljYZrlU8ID.nRsxop.YESnUmYgBGFSHnvMJbx0FYR8_KmgFa07G
VZ8cxow216PYxtsLkHPcaUgfqV79imy4mperJ2st6dzbtnYdm7cHHFu7GObC4rc8D4nVNBFcfIqjPVo_vr.RZxgKzuXaEUUbf3WTp05ltmzQHIXtqFB1oKxtZtxs_o_mY.vNBgRB
Ew4aFNOLFgYaxQDYmmRKCHjKtLS0WVQ0MYFlN96pjbOCM.dc0daXlZwIT8.WeOVjcN_UPWMwwoaSXA9fLYckbsSftzpjv_7j9pZIj31bRfSyFN9DS.R7Bt8e79PG7B.3he9wRQNB
5g30rOzbvpLTvnaGdbUB.rMaFeq3nKFI05IY60WH3QyHn4JpVEbdfy4GZC5QZdtybODNSwmhwkp_u7_mvlJwxdncP3bPc.wpiOPQPGKXL9ens2zwFfTyJrii8w4Skm4ShHF6TnSa
DLuPyQ65X.YC9zqdyA7ClXlvgk4miB7hbybeu0cRhYMxVVhSLFu3jA2QzbXXvR_Wp5CNhOleyfiXyOSiUvrk4yYrjKvaqGejx3C3OMMhat_Udp5MLfUgEzzmJzcxPOg--",
oauth_version="1.0",
oauth_signature="u8P1hb7d08uUIwtKIvlWLOLt%2BCU%3D"
Content-Type: Content-Type: application/x-www-form-urlencoded
My signature generation code doesn't appear to be wrong since I've been using that checker I linked above to verify my signatures and they appear to be fine. I've used this as a guide, but still getting the error. Also, I've been running this guy's code in PHP and am able to get it to work. I've used that as a base point to check my base string/signatures/headers against and it all seems ok so I have no loving idea what I'm doing wrong.

Sockser
Jun 28, 2007

This world only remembers the results!




Twenty minutes of googling have turned up nothing so I'm assuming I'm SOL on this one.

I'm working on automating localization testing, so the same tests will run in four different languages. The way it's currently set up, there's a french machine, a german machine, etc. I'd like to run them all on the same machine if possible, which requires switching Windows's language settings between tests. Is there a way to change the global language preference through C#? Everything I've found is about localizing one single winforms app which isn't what I need.

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

Sockser posted:

Twenty minutes of googling have turned up nothing so I'm assuming I'm SOL on this one.

I'm working on automating localization testing, so the same tests will run in four different languages. The way it's currently set up, there's a french machine, a german machine, etc. I'd like to run them all on the same machine if possible, which requires switching Windows's language settings between tests. Is there a way to change the global language preference through C#? Everything I've found is about localizing one single winforms app which isn't what I need.

Can't you change the thread's CurrentCulture? I've never messed with this but it's the first thing that popped into mind. There's also changing your application to take in a CultureInfo using Dependency Injection because really your classes are being tightly coupled with the local machine which is causing you issues with your automated unit testing.

Sockser
Jun 28, 2007

This world only remembers the results!




That's the thing, it's not enough to change my program to German or what have you, I need to set all of windows to German.

e: Not unit testing, integration testing, automation bullshit, should've been more explicit there. I'm writing a testing harness that calls other applications and runs test scripts. Hence Windows needs to be localized, not my program.

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

Sockser posted:

That's the thing, it's not enough to change my program to German or what have you, I need to set all of windows to German.

e: Not unit testing, integration testing, automation bullshit, should've been more explicit there. I'm writing a testing harness that calls other applications and runs test scripts. Hence Windows needs to be localized, not my program.

Gotcha! Tried PowerShell? You can run PowerShell from your application and use the Set-WinSystemLocale with it.

Adbot
ADBOT LOVES YOU

mobby_6kl
Aug 9, 2009

by Fluffdaddy

Sedro posted:

Windbg.


Mr. Crow posted:

In .Net both jetbrains and redgate have really good profilers that I typically use.
...

Thanks guys! Didn't have the time for this yet but seems like these two approaches should do the trick.

  • Locked thread