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
RICHUNCLEPENNYBAGS
Dec 21, 2010

kingcrimbud posted:

Unit tests don't necessarily show that software is 'correct'. They simply allow you to show it does something, so that when you make changes to your software you can quickly see how that something changed. The better your testing, the more accurate you can measure the potential delta.

So we are in agreement.

Adbot
ADBOT LOVES YOU

Azubah
Jun 5, 2007

mortarr posted:

Yeah, same here... I not at work so no code to hand, but the object model you're working with is pretty opaque - the best I could do was get the SSRS report to render to pdf in memory and then I sent that down to the client as a filecontentresult.

In fact, I remember I got so cross with the whole thing I put the report up on the sql server and just called that from my mvc proj, it was too hard to get meaningful error messages when hosting the whole shebang inside my web app. I'm sure there were permissions errors where kerberos/delegation wasn't working but damned if I could find what aspect of the thing was bailing.

The reports are on the server already, I just need to meaningfully navigate to them and get the user to the report. I tried setting adding a service reference to the project but it didn't like the credentials, I'm at a roadblock until I hear back from the database guy about this.

If presentation and logging in wasn't such an issue, I'd just use the iframe method and call it a day.

Gildiss
Aug 24, 2010

Grimey Drawer
Hoping someone knows what is going wrong.

The software that we make at our place makes a data warehouse and populates it from a source DB and sets it up to do all sorts of ETL and reports poo poo.
I have yet to have a successful installation on my desktop because it will always timeout on the enable CDC portion of the install.
This should not happen because the DW owner is set to sa, the passwords are all correct. Everything else goes fine.
This is loving me up because the install also creates the SSISFramework DB etc that set up everything for testing and actually using the BIDS thing to develop on that specific machine that it is installed.
But it can never get to that point.

So TLDR. What could be causing enable CDC to timeout on a DW with an sa owner?

chippy
Aug 16, 2006

OK I DON'T GET IT

mortarr posted:

In fact, I remember I got so cross with the whole thing I put the report up on the sql server and just called that from my mvc proj.

This is what we do too.

Knyteguy
Jul 6, 2005

YES to love
NO to shirts


Toilet Rascal

Ithaqua posted:

Don't worry, Microsoft's entire strategy around software deployment is kind of schizophrenic right now. It's going to get better, but probably not in the next 3-6 months.

Hm yea it's a pain. I think there's too much QC for a desktop application. Not sure what was wrong with the old .msi or install wizard approach there. And for mobile apps if they don't want to allow appx packages to be installed from the web, at least have the InTune company portal accept universal apps easily without having to put a sensitive enterprise program on the store. Unfortunately our mobile launch date will be before any likely fixes, but it looks like we'll be able to use the current system, but just have it as a private store entry. It's no wonder the Windows Phone market isn't doing that great. The new 8.1 devices are actually pretty sweet all things considered.

Also boo at hosted TFS being down right now. Stuff like this seems to happen every time I work remotely and absolutely have to pull the current source. MICROSOFT! :arghfist:

brap
Aug 23, 2004

Grimey Drawer

RICHUNCLEPENNYBAGS posted:

So we are in agreement.

Tests are only going to be perfect for simple and obvious functions, and it's funny when people act like code without automated tests is a time bomb. It's not that black and white. But the nice thing about tests is you get to be specific and literal about what the expected behavior of your code is. That's really handy when evaluating how well your program fulfills requirements and it's very useful for the poor sap maintaining your code in the future who needs to figure out what the gently caress it does.

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.

EssOEss posted:

You can unload assemblies by unloading the AppDomain that they belong to, though managing AppDomains can be a bit of a hassle. Is it really worth the convenience of swapping bits out at runtime? Possibly it is easier to just stop the service, update it and start it again. This, of course, assumes that the service code has been built with proper stopping logic in mind - not always the case.

Ok, I didn't know it was this complicated. It would be nice if I could toggle a new version flag in the db where the service would then reload the new dll and flip the flag bit, but I don't want to rock the boat. I mean it gets the job done like it is and the service does have proper stopping logic in there.

RICHUNCLEPENNYBAGS
Dec 21, 2010

fleshweasel posted:

Tests are only going to be perfect for simple and obvious functions, and it's funny when people act like code without automated tests is a time bomb. It's not that black and white. But the nice thing about tests is you get to be specific and literal about what the expected behavior of your code is. That's really handy when evaluating how well your program fulfills requirements and it's very useful for the poor sap maintaining your code in the future who needs to figure out what the gently caress it does.

Well, again, sure. But tests are code that has to be maintained and can have bugs too and TDD's obsession with "code coverage" leads, I'm contending, to lower software quality.

bobua
Mar 23, 2003
I'd trade it all for just a little more.

VS wouldn't autogenerate a .update() command for a tableadapter(i think because it doesn't have a primary key). Is there any way to force it to or at least get close? Typing these things out sounds tedious as hell.

Edit: Nevermind, I didn't see the 'new' drop down under properties that would eventually get me to the query builder.

bobua fucked around with this message at 03:06 on Dec 19, 2014

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

RICHUNCLEPENNYBAGS posted:

So we are in agreement.

Yes and no. I personally think TDD makes sense on paper. With what I said before, unit tests can guarantee a minimum state of the classes in your system. Once a class changes, tests can go red or they can stay green.

If you've truly designed your system well (good luck doing that) where you're open for extension and closed for modification, then your tests from TDD will already cover your previous code and you'll never go red. Two problems with this though is that we'll never design it perfectly the first time and requirements will always shift.

Until we get perfect requirements with which we can perfectly design, TDD will not be perfect.

turn it up TURN ME ON
Mar 19, 2012

In the Grim Darkness of the Future, there is only war.

...and delicious ice cream.
I'm trying to grab the size of a specific folder within my code, and in looking around the Internet I'm seeing a lot of references to Scripting.FileSystemObject, which looks like it's a VB 6 artifact. Is there a more up to date .NET object I should be using to get attributes of file system objects?

Mr Shiny Pants
Nov 12, 2012

SquadronROE posted:

I'm trying to grab the size of a specific folder within my code, and in looking around the Internet I'm seeing a lot of references to Scripting.FileSystemObject, which looks like it's a VB 6 artifact. Is there a more up to date .NET object I should be using to get attributes of file system objects?

System.IO.Directory.EnumerateFiles() and you can iterate over the file entries. Per entry get a System.IO.FileInfo from the path and this FileInfo object has a length property.

turn it up TURN ME ON
Mar 19, 2012

In the Grim Darkness of the Future, there is only war.

...and delicious ice cream.

Mr Shiny Pants posted:

System.IO.Directory.EnumerateFiles() and you can iterate over the file entries. Per entry get a System.IO.FileInfo from the path and this FileInfo object has a length property.

System.IO looks to have all the stuff I need. Thanks.

bobua
Mar 23, 2003
I'd trade it all for just a little more.

code:
            if (frame.PixelFormat == VmbPixelFormatType.VmbPixelFormatMono8)
            {
                Image<Gray, byte> img = new Image<Gray, byte>((int)frame.Width, (int)frame.Height);
            }
            else if (frame.PixelFormat == VmbPixelFormatType.VmbPixelFormatBayerRG8)
            {
                Image<Rgb, byte> img = new Image<Rgb, byte>((int)frame.Width, (int)frame.Height);
            }
            else
            {
                System.Diagnostics.Debug.WriteLine(frame.PixelFormat.ToString() + " not supported.  Defaulting to Mono8.");
                Image<Gray, byte> img = new Image<Gray, byte>((int)frame.Width, (int)frame.Height);
            }
            Buffer.BlockCopy(frame.Buffer, 0, img.Data, 0, (int)frame.BufferSize);
            App.Current.Dispatcher.BeginInvoke((Action)delegate() { m_FrameReceivedHandler(img, null); });
This doesn't compile because img is considerred undefined, so I changed it to this

code:
	    if (frame.PixelFormat == VmbPixelFormatType.VmbPixelFormatMono8)
            {
                Image<Gray, byte> img = new Image<Gray, byte>((int)frame.Width, (int)frame.Height);
                Buffer.BlockCopy(frame.Buffer, 0, img.Data, 0, (int)frame.BufferSize);
                App.Current.Dispatcher.BeginInvoke((Action)delegate() { m_FrameReceivedHandler(img, null); });
            }
            else if (frame.PixelFormat == VmbPixelFormatType.VmbPixelFormatBayerRG8)
            {
                Image<Rgb, byte> img = new Image<Rgb, byte>((int)frame.Width, (int)frame.Height);
                Buffer.BlockCopy(frame.Buffer, 0, img.Data, 0, (int)frame.BufferSize);
                App.Current.Dispatcher.BeginInvoke((Action)delegate() { m_FrameReceivedHandler(img, null); });
            }
            else
            {
                System.Diagnostics.Debug.WriteLine(frame.PixelFormat.ToString() + " not supported.  Defaulting to Mono8.");
                Image<Gray, byte> img = new Image<Gray, byte>((int)frame.Width, (int)frame.Height);
                Buffer.BlockCopy(frame.Buffer, 0, img.Data, 0, (int)frame.BufferSize);
                App.Current.Dispatcher.BeginInvoke((Action)delegate() { m_FrameReceivedHandler(img, null); });
            }
But it just seems like there should be a better way. Is there?

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

bobua posted:



This doesn't compile because img is considerred undefined, so I changed it to this


But it just seems like there should be a better way. Is there?

Make a generic method that takes whatever class Grey and Rgb derive from as a constraint, move all of the logic into that method.

code:
public void Foo() 
{
	    if (frame.PixelFormat == VmbPixelFormatType.VmbPixelFormatMono8)
            {
                 DoWhateverWithImages<Grey>(parameters);
            }
            else if (frame.PixelFormat == VmbPixelFormatType.VmbPixelFormatBayerRG8)
            {
                 DoWhateverWithImages<Rgb>(parameters);
            }
            else
            {
                System.Diagnostics.Debug.WriteLine(frame.PixelFormat.ToString() + " not supported.  Defaulting to Mono8.");
                DoWhateverWithImages<Grey>(parameters);
            }
}

public void DoWhateverWithImages<T>(whatever parameters you need to pass) where T: WhateverBaseClass
{
    var img = new Image<T, byte>((int)frame.Width, (int)frame.Height);
    Buffer.BlockCopy(frame.Buffer, 0, img.Data, 0, (int)frame.BufferSize);
    App.Current.Dispatcher.BeginInvoke((Action)delegate() { m_FrameReceivedHandler(img, null); });
}

bobua
Mar 23, 2003
I'd trade it all for just a little more.

Ithaqua posted:

Make a generic method that takes whatever class Grey and Rgb derive from as a constraint, move all of the logic into that method.



Sweet. Never messed with this sorta thing. Thanks!

chippy
Aug 16, 2006

OK I DON'T GET IT
Can I use a List of Strings as a the key for a dictionary?

Or, can anyone think of a neat solution to this? I've got a collection of Foos, each of which has a collection of Strings. I need to find each unique list of Strings, along with the Foos that share it.

p.s. VB, not C#, if it makes any difference.
p.p.s. I am aware that this is a somewhat remedial level question, but I am ill and sleep deprived and it is the end of the day.

chippy fucked around with this message at 18:24 on Dec 22, 2014

Sedro
Dec 31, 2008

chippy posted:

Can I use a List of Strings as a the key for a dictionary?

Or, can anyone think of a neat solution to this? I've got a collection of Foos, each of which has a collection of Strings. I need to find each unique list of Strings, along with the Foos that share it.

p.s. VB, not C#, if it makes any difference.
p.p.s. I am aware that this is a somewhat remedial level question, but I am ill and sleep deprived and it is the end of the day.
You can, but the List in .NET doesn't implement equality/hash in terms of its items. So you should use a custom EqualityComparer when you construct the dictionary.

chippy
Aug 16, 2006

OK I DON'T GET IT

Sedro posted:

You can, but the List in .NET doesn't implement equality/hash in terms of its items. So you should use a custom EqualityComparer when you construct the dictionary.

Thanks, yeah I just tried it out in LINQPad and found that the standard equality operator won't work. I'll look into that.

NihilCredo
Jun 6, 2011

iram omni possibili modo preme:
plus una illa te diffamabit, quam multæ virtutes commendabunt

chippy posted:

Can I use a List of Strings as a the key for a dictionary?

Or, can anyone think of a neat solution to this? I've got a collection of Foos, each of which has a collection of Strings. I need to find each unique list of Strings, along with the Foos that share it.

p.s. VB, not C#, if it makes any difference.
p.p.s. I am aware that this is a somewhat remedial level question, but I am ill and sleep deprived and it is the end of the day.

From the way you describe the problem, it sounds like you want to start with the Foos as the keys, and the lists of strings as the values, and then turn that "inside-out" into the dictionary you actually want.

GroupBy would fit exactly what you want to do, but as Sedro says it would also require you to define an EqualityComparer (using SequenceEqual). If you would have no further use for the comparer I'd just go with the lo-tech approach of a For Each loop: https://dotnetfiddle.net/fBRDaW

Forgall
Oct 16, 2012

by Azathoth
I'm trying to save and load images using PngBitmapEncoder and PngBitmapDecoder. After I save png it opens fine in gimp and colors look right. But after loading with FromPNG method I get red and blue channels switched up. Format property on bitmapSource in the second method says format is Bgr24 for some reason, and I'm not sure where it gets this idea, or how to force correct format.
code:
using System;
using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;

public class ImageConverter {
    int width, height;
    const int bitsPerPixel = 24;

    public ImageConverter(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public byte[] ToPNG(IntPtr pixelsPointer) {
        int stride = 4 * ((width * bitsPerPixel + 31) / 32);
        var bufferSize = height * stride;
        BitmapSource image = BitmapSource.Create(
            width,
            height,
            96,
            96,
            PixelFormats.Rgb24,
            null,
            pixelsPointer,
            bufferSize,
            stride);
        using (var stream = new MemoryStream()) {
            PngBitmapEncoder encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(image));
            encoder.Save(stream);
            return stream.ToArray();
        }
    }

    public WriteableBitmap FromPNG(byte[] bytes) {
        using (var stream = new MemoryStream(bytes)) {
            PngBitmapDecoder decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            BitmapSource bitmapSource = decoder.Frames[0];
            return new WriteableBitmap(bitmapSource);
        }
    }
}

raminasi
Jan 25, 2005

a last drink with no ice

chippy posted:

Can I use a List of Strings as a the key for a dictionary?

Or, can anyone think of a neat solution to this? I've got a collection of Foos, each of which has a collection of Strings. I need to find each unique list of Strings, along with the Foos that share it.

p.s. VB, not C#, if it makes any difference.
p.p.s. I am aware that this is a somewhat remedial level question, but I am ill and sleep deprived and it is the end of the day.

Using mutable objects as dictionary keys is a Real Bad Idea. It can "work" as long as you make sure you don't actually mutate the objects once they become keys, but it's a smelly thing to do, at best.

Funking Giblet
Jun 28, 2004

Jiglightful!

chippy posted:

Can I use a List of Strings as a the key for a dictionary?

Or, can anyone think of a neat solution to this? I've got a collection of Foos, each of which has a collection of Strings. I need to find each unique list of Strings, along with the Foos that share it.

p.s. VB, not C#, if it makes any difference.
p.p.s. I am aware that this is a somewhat remedial level question, but I am ill and sleep deprived and it is the end of the day.

You could extend the list and override GetHashCode to order the strings, join them and call string.GetHashCode, or use an int as the key. It really depends on how important the hash is. If it's only used in memory, then you should be fine. Storing the hash would mean you should use a consistent hash instead of GetHashCode for string.

chippy
Aug 16, 2006

OK I DON'T GET IT
Thanks everyone. I ended up writing a custom IEqualityComparer and using GroupBy().

Canine Blues Arooo
Jan 7, 2008

when you think about it...i'm the first girl you ever spent the night with



Grimey Drawer
gently caress, do I struggle with Form controls.

I have a form which has a PictureBox in it. When the form loads initially, that picture box is a gray dot. When I hit a button, it needs to turn to a green dot. I can not for the life of me get this son of a bitch to change it's picture. Just to test it, I'm trying to get it to flip a color on startup, and it won't even do that and I'm way too stupid at Windows Formsprogramming to understand what's happening. 'main' is the form name. My code looks like this:

code:
public partial class main : Form
{
...
        public void changeNtpStatus(int status)
        {
                switch (status)
                {
                    case 0:
                        ntpBox.Image = sysinfo.Properties.Resources.gray;
                        ntpBox.Refresh();
                        break;
                    case 1:
                        ntpBox.Image = sysinfo.Properties.Resources.green;
                        ntpBox.Refresh();
                        break;
                    case 2:
                        ntpBox.Image = sysinfo.Properties.Resources.yellow;
                        ntpBox.Refresh();
                        break;
                    case 3:
                        ntpBox.Image = sysinfo.Properties.Resources.red;
                        ntpBox.Refresh();
                        break;
            	}
        }
}

code:
internal class Reporting
  {
    private main form = new main();
...

    public void createWindow()
    { 
        Application.Run(form);
        form.changeNtpStatus(1);
    }
}
code:
  internal static class Program
  {
    [STAThread]
    private static void Main()
    {
      
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);

      Reporting report = new Reporting();
      report.createWindow();     
    }
  }
}
Now, if I flip the lines in Reporting.createWindow() to be

code:
    public void createWindow()
    { 
        form.changeNtpStatus(1);
        Application.Run(form);
    }
Than it will load as a green dot, as it should. But anything that happens after Run() is called is no bueno. I just want to change the picture in a picture box on a button click! This has got to be really simple. What the gently caress do I do!?!?

Che Delilas
Nov 23, 2009
FREE TIBET WEED

Canine Blues Arooo posted:

Than it will load as a green dot, as it should. But anything that happens after Run() is called is no bueno. I just want to change the picture in a picture box on a button click! This has got to be really simple. What the gently caress do I do!?!?

I'm assuming this is in WinForms? You need to make an event handler to process your button's Click event.

If you're in the design view, the quickest way to do this is just double-click on the button in question, and Visual Studio will automagically create the function stub for you. It'll look something like this:

C# code:
private void button1_Click(object sender, EventArgs e)
{

}
The "button1" part comes from the name of the button. You'll want to call whatever color-changing function you have from within this event handler function, like so:

C# code:
private void button1_Click(object sender, EventArgs e)
{
    changeNtpStatus(1);
}
That's all you should have to do to get it to function the way you want. To actually understand what's going on under the hood (and you should endeavor to), you'll need to go a little deeper, specifically the topics of Events and Event Handlers.

http://msdn.microsoft.com/en-us/library/dd492171.aspx Is a set of basic WinForms tutorials that looks pretty good. #1 has you write button click event handlers the way I told you about, and #2 goes a little deeper into events and shows you where they're attached to the controls that generate said events.

----

Also on a more personal note, stop getting down on yourself for not getting this right away. Windows GUI programming has a lot of extra baggage and complexity attached to it which does a fantastic job of muddying the waters when you're just trying to learn basic programming concepts. It can be difficult to teach yourself because dozens of little things have to be correct, and if you don't know several of them at once, it's hard to know where you're going wrong or what you're missing. Just keep asking questions when you don't understand something (and frankly, get comfortable with not understanding things - the more you learn about programming, the more you realize just how much there is that you don't know.)

Forgall
Oct 16, 2012

by Azathoth

Canine Blues Arooo posted:

Than it will load as a green dot, as it should. But anything that happens after Run() is called is no bueno. I just want to change the picture in a picture box on a button click! This has got to be really simple. What the gently caress do I do!?!?
Lines after Application.Run() are only executed after you close your application. I don't see your button click event handler in code you posted, do you have one?

Canine Blues Arooo
Jan 7, 2008

when you think about it...i'm the first girl you ever spent the night with



Grimey Drawer

Forgall posted:

I don't see your button click event handler in code you posted, do you have one?

Oh yeah. I removed pretty much all the functionality in the name of isolating where the problem is here. Complete code for main is:

code:
namespace sysinfo
{
    public partial class main : Form
    {
        public main()
        {
            InitializeComponent();
        }

        private void createReport_MouseClick(object sender, MouseEventArgs e)
        {
            Reporting report = new Reporting();

            report.run();
        }
        public void changeNtpStatus(int status)
        {
                switch (status)
                {
                    case 0:
                        ntpBox.Image = sysinfo.Properties.Resources.gray;
                        ntpBox.Refresh();
                        break;
                    case 1:
                        ntpBox.Image = sysinfo.Properties.Resources.green;
                        ntpBox.Refresh();
                        break;
                    case 2:
                        ntpBox.Image = sysinfo.Properties.Resources.yellow;
                        ntpBox.Refresh();
                        break;
                    case 3:
                        ntpBox.Image = sysinfo.Properties.Resources.red;
                        ntpBox.Refresh();
                        break;
            }
        }
    }
}
The context under which it'd be used looks something like this

code:
public string createHash(sysinfo.main form)
        {
            try
            {
                string[] strArray = Enumerable.ToArray<string>(Enumerable.Select<char, string>((IEnumerable<char>) string.Format("{0:ddMMyyhhmmssffff}", 
			(object) SimpleNTP.GetNetworkTime()), (Func<char, string>) (c => c.ToString())));
                string[] input = new string[8];

                form.changeNtpStatus(2);
                //System.Threading.Thread.Sleep(1000);
                //updateStatus(2);

                for (int index = 0; index < 8; ++index)
                {
                    string str = strArray[index] + strArray[15 - index];
                    input[index] = str;
                }

                this.finalhash = this.createHash(input);
            }
            catch (Exception ex)
            {
                Console.WriteLine(((object) ex).ToString());
                form.changeNtpStatus(3);
                //updateStatus(3);
            }

        form.changeNtpStatus(1);
        //updateStatus(1);
        return this.finalhash;
        }
The image just won't update. If I can get it to update in the context which I presented it in the post above, I can probably get it to update in it's actual context, so that's all I really need.

Forgall
Oct 16, 2012

by Azathoth
Ok, this is a little convoluted, especially your createHash function... But that aside, best thing would probably be to put a debugger breakpoint in changeNtpStatus and make sure that it is being called when you click a button, that it is called with correct parameter, and that it is being called only once. I have a feeling that changeNtpStatus is either not called at all or called multiple times, with latter call overwriting ntpBox.Image with wrong icon.

Edit: And this is unrelated to your present problem, but function called createHash should not be changing state of UI, and it really shouldn't be making calls to the network.

Forgall fucked around with this message at 15:07 on Dec 23, 2014

Che Delilas
Nov 23, 2009
FREE TIBET WEED
Yeah, you're passing in the form to your createHash function, which reeeealy shouldn't be necessary. Can you show us where you're calling createHash?

NickFendon
May 4, 2009
Speaking of WinForms, I've been looking for ways to make some of the apps that I maintain a bit cleaner / more modular / more maintainable. Reading this article has me pretty keen on trying out an event aggregation approach, but I don't really have any idea how things would fit together in a larger app. Has anyone done something similar before, or know of any open source examples of a similarly architected app? I've got a little Rx event aggregator that I wrote a while back, but my biggest pain points at the moment are wiring up the subscriptions and putting things together - particular with non-UI classes that process events, etc.

Canine Blues Arooo
Jan 7, 2008

when you think about it...i'm the first girl you ever spent the night with



Grimey Drawer

Che Delilas posted:

Yeah, you're passing in the form to your createHash function, which reeeealy shouldn't be necessary. Can you show us where you're calling createHash?

Sure -- Just a quick note: I've made a mess of this code trying to fix this. I've restored it to where I left off before I said 'gently caress it'.

First, the form class. This is the only form on the application, so that makes things a little easier:

code:
    public partial class main : Form
    {
        public main()
        {
            InitializeComponent();
        }

        private void createReport_MouseClick(object sender, MouseEventArgs e)
        {
            Reporting report = new Reporting();

            report.run();
        }
        public void changeNtpStatus(int status)
        {
                switch (status)
                {
                    case 0:
                        ntpBox.Image = sysinfo.Properties.Resources.gray;
                        ntpBox.Refresh();
                        break;
                    case 1:
                        ntpBox.Image = sysinfo.Properties.Resources.green;
                        ntpBox.Refresh();
                        break;
                    case 2:
                        ntpBox.Image = sysinfo.Properties.Resources.yellow;
                        ntpBox.Refresh();
                        break;
                    case 3:
                        ntpBox.Image = sysinfo.Properties.Resources.red;
                        ntpBox.Refresh();
                        break;
            }
        }
    }
}
The one button there talks to the Reporting class. The relevant bits look like so:

code:
  internal class Reporting
  {
    private main form = new main();
    private Hash hash = new Hash();
    private OperatingSystem os = new OperatingSystem();
    private CPU cpu = new CPU();
    private GFX gfx = new GFX();
    private HardDrive hardDrive = new HardDrive();
    private InstalledPrograms programs = new InstalledPrograms();
    private Motherboard mb = new Motherboard();
    private Minidump minidump = new Minidump();
    private PageFile pageFile = new PageFile();
    private ProcessList processes = new ProcessList();
    private RAM memory = new RAM();
    private ServiceList services = new ServiceList();
    private StartupItems startupItems = new StartupItems();
    private HardDrive hd = new HardDrive();
    private string report = "";
    public string reportID = "";
    private string reporturl = "";
    private string version = "SysInfo - Version 0.3.1 - 6/23/2014";
    
    private string GenerateReport()
    {
      reportID += hash.createHash(form);

      //report += createHeader();
      //report += os.getOS();
      //report += memory.getMemory();
      //report += cpu.getCPU();
      //report += gfx.getGFXUnit();
      //report += pageFile.getPageFile();
      //report += hd.buildData();
      //report += minidump.getCrashes(reportID);
      //report += processes.getProcessList();
      //report += services.getServiceList();
      //report += startupItems.getStartupItems();

      return report;
    }
The commented out stuff is all functional, but I'm trying to just the one picturebox to work instead of all 15 or whatever it ends up being, so I only call the one method. The method we are working with is in the Hash class:

code:
  internal class Hash
  {
    private string[] hashTable = new string[100]
    {
...
    };
    private string finalhash;

        public string createHash()
        {
            main form = new main();
            try
            {
                string[] strArray = Enumerable.ToArray<string>(Enumerable.Select<char, string>((IEnumerable<char>) string.Format("{0:ddMMyyhhmmssffff}",
			(object) SimpleNTP.GetNetworkTime()), (Func<char, string>) (c => c.ToString())));
                string[] input = new string[8];

                form.changeNtpStatus(2);

                for (int index = 0; index < 8; ++index)
                {
                    string str = strArray[index] + strArray[15 - index];
                    input[index] = str;
                }

                this.finalhash = this.createHash(input);
            }
            catch (Exception ex)
            {
                Console.WriteLine(((object) ex).ToString());
                form.changeNtpStatus(3);
            }

        form.changeNtpStatus(1);
        return this.finalhash;
        }

        private string createHash(string[] input)
        {
            string str1 = "";

            foreach (string str2 in input)
            {
                int index = Convert.ToInt32(str2);
                str1 = str1 + this.hashTable[index];
            }
                return str1;
        }
    }
}
I realize I cannot actually create a new form object here and expect it to change the existing form's state, but I think this at least clearly illustrates what I want to accomplish.

Canine Blues Arooo fucked around with this message at 15:55 on Dec 23, 2014

Che Delilas
Nov 23, 2009
FREE TIBET WEED

Canine Blues Arooo posted:

I realize I cannot actually create a new form object here (in the Hash class) and expect it to change the existing form's state, but I think this at least clearly illustrates what I want to accomplish.

Added stuff in bold. This is correct, you can't do that. But you are also doing it in your Reporting class:
code:
internal class Reporting
{
    private main form = new main();
    //Snip
    reportID += hash.createHash(form);
}
Like you said, you can't create that second form and expect it to change anything on the calling form.

----

Beyond that, as forgall mentioned you really, really shouldn't be changing the state of your UI outside of your form. WinForms is bad about letting you separate display logic from other logic, but at the very least, your form class should be manipulating the color of the picture box based on the results of the other classes, not letting those classes do it.

Something like this:

C# code:
public partial class main : Form
{
  //Snip
  private void createReport_MouseClick(object sender, MouseEventArgs e)
        {
            Reporting report = new Reporting();
            
            //Indicate reporting has begun
            changeNtpStatus(YELLOW);
            
            try 
            {
               report.run();
            }
            catch (Exception ex)  //Failure
            {
                 //Log ex.Message or whatever

                changeNtpStatus(RED); //Indicate Failure
                return;
            }
            
            //Indicate Success
            changeNtpStatus(GREEN);
        }
//Snip
}
Then remove everything having to do with changing controls or otherwise manipulating the UI from your Reporting and Hash classes. It does not belong there.

Probably a good idea to explicitly try/catch/rethrow the exception within your Reporting.GenerateReport() method too, but it should bubble up either way.

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!
I have a collections data structures question about ArrayList. I am in a situation where I wanted to use one, but the data I'm inserting into it is be placed in reverse-order. So I'm adding to the beginning every time. Is there any reason this is suboptimal for that container? I was wondering if, say, its default array started with i=0 and I immediately wreck it. I wonder then if it compensates in the second internal array it makes, or what.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Rocko Bonaparte posted:

I have a collections data structures question about ArrayList. I am in a situation where I wanted to use one, but the data I'm inserting into it is be placed in reverse-order. So I'm adding to the beginning every time. Is there any reason this is suboptimal for that container? I was wondering if, say, its default array started with i=0 and I immediately wreck it. I wonder then if it compensates in the second internal array it makes, or what.

You don't want to use an ArrayList for anything, ever. It's a legacy holdover from .NET 1.1, which didn't have generics. Use a List<T> and the Insert method. Internally, it's just copying and resizing the backing array, which shouldn't matter to you -- it's not going to be a performance issue unless you have a huge list, and if you have a huge list, you probably have a design issue.

You could also use a SortedSet<T>, which will maintain the sort order automatically.

New Yorp New Yorp fucked around with this message at 17:59 on Dec 24, 2014

Rocko Bonaparte
Mar 12, 2002

Every day is Friday!
Ahh that is right. I keep relearning not to use ArrayLists. I should figure out an IDE extension to yell at me when I type it.

Forgall
Oct 16, 2012

by Azathoth
Also, if you are inserting into beginning of List, it's going to move every element already in there every time you do that. You could just reverse it once you are done adding elements, or not reverse it at all and access it using a[a.Count - 1 - n] instead of a[n]. Or use a stack.

Canine Blues Arooo
Jan 7, 2008

when you think about it...i'm the first girl you ever spent the night with



Grimey Drawer

Che Delilas posted:

Added stuff in bold. This is correct, you can't do that. But you are also doing it in your Reporting class:
code:
internal class Reporting
{
    private main form = new main();
    //Snip
    reportID += hash.createHash(form);
}
Like you said, you can't create that second form and expect it to change anything on the calling form.

----

Beyond that, as forgall mentioned you really, really shouldn't be changing the state of your UI outside of your form. WinForms is bad about letting you separate display logic from other logic, but at the very least, your form class should be manipulating the color of the picture box based on the results of the other classes, not letting those classes do it.

Something like like:

This is what I ended up doing and it works just fine. It seems so obvious but it never even crossed my mind until you mentioned it. Thanks!

xgalaxy
Jan 27, 2004
i write code

Ithaqua posted:

You don't want to use an ArrayList for anything, ever.

I don't really agree with this in practice. On mobile ArrayList performs better than generic List. In fact on mobile avoiding generics as much as possible helps performance a ton. This is using the Xamarin mono runtime not official runtime. So this may not be relevant for Windows Phone stuff.

Adbot
ADBOT LOVES YOU

ljw1004
Jan 18, 2005

rum

xgalaxy posted:

I've got a question / concern about HttpWebRequest.
Keep in mind I'm working in Unity3d so I only have access to .Net 3.5 features, so no async/await or HttpClient.
I want to use HttpWebRequest BeginGetResponse but there is a note on it saying that this call can block for various reasons and that I shouldn't call it from a UI thread. May I ask what is the loving point of this call then?

From memory, HttpWebRequest.BeginGetResponse does some initial part of the connection (resolving URL? opening up the TCP port?) synchronously. My vague memory is that when I had a misconfigured network connection I could observe BeginGetResponse hanging rather than returning immediately.

I agree with "what's the point?". I think the underlying problem is I've *NEVER* met a developer who really pays pedantic attention to the low-level nuts and bolts of what exactly each operation will do and whether it might fail.

As you said, doing it on a background thread sounds like a fine approach. You'll have the problem that the background thread might hang indefinitely and it's rude to terminate a thread...

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