Looking for someone with decent C# experience - Page 3 - Overclock.net - An Overclocking Community
Forum Jump: 

Looking for someone with decent C# experience

Reply
 
Thread Tools
post #21 of 79 (permalink) Old 06-24-2015, 02:14 PM
Mathematician
 
Join Date: Feb 2013
Posts: 442
Rep: 20 (Unique: 15)
Quote:
Originally Posted by Awaz View Post

Thanks Algo! That helps. Code code and away!

ALGO??????!!!!!! mad.gifmad.gifmad.gifmad.gifmad.gifmad.giftongue.gif

EDIT: I'm just messing with you. You can get more help if you need it.biggrin.gif
Algorithm is offline  
Sponsored Links
Advertisement
 
post #22 of 79 (permalink) Old 06-28-2015, 11:20 AM - Thread Starter
New to Overclock.net
 
Join Date: Oct 2008
Location: Illinois
Posts: 2,085
Rep: 102 (Unique: 93)
Finally getting around to coding the Calculator application - had to take care of some personal and work related stuff. A few quick questions:

1. I do not see a 'Leave' type event (except for a MouseLeave) under the event handlers for a textbox. I do see LostFocus and GotFocus events. Should I be using LostFocus?

2. I did test out LostFocus event. It appears that when application first runs, and user does not even click on the box and moves on to another, the LostFocus event does not get fired (makes sense). So, if I put validation there, it does not get executed. For example, I have textBox1, textBox2, etc. I want to validate stuff entered on textBox1. If a user straights jumps to textBox2, the LostFocus event for textBox1 does not get fired. What do you normally do in such instances?

Registry Hack Information


Have a laugh (Click to show)Warning: Spoiler! (Click to show)


Quote:
Originally Posted by Hotcarl go_quote.gif
I keep it long and hole facing me, or does it not matter
Quote:
Originally Posted by Krunk_Kracker go_quote.gif
I have nothing of value to add to this thread, accept that I read this title as "Anus Transformer" and was prepared to infract you.



lol



Awaz is offline  
post #23 of 79 (permalink) Old 06-28-2015, 01:02 PM
Mathematician
 
Join Date: Feb 2013
Posts: 442
Rep: 20 (Unique: 15)
Quote:
Originally Posted by Awaz View Post

Finally getting around to coding the Calculator application - had to take care of some personal and work related stuff. A few quick questions:

1. I do not see a 'Leave' type event (except for a MouseLeave) under the event handlers for a textbox. I do see LostFocus and GotFocus events. Should I be using LostFocus?

2. I did test out LostFocus event. It appears that when application first runs, and user does not even click on the box and moves on to another, the LostFocus event does not get fired (makes sense). So, if I put validation there, it does not get executed. For example, I have textBox1, textBox2, etc. I want to validate stuff entered on textBox1. If a user straights jumps to textBox2, the LostFocus event for textBox1 does not get fired. What do you normally do in such instances?

I just realized you're using WPF rather than Windows Forms. I've been looking at the WPF class libraries for a few minutes, and while they seem similar to Forms, they are not identical. It looks to me like LostFocus will work though.

So what you are saying is that you want to verify that the string entered in the textboxes is correct before the user clicks Calculate? That is not possible because the textboxes are blank beforehand, so a check right in the window constructor will throw a FormatException. I would recommend setting the textbox values to 0 in the constructor, which will guarantee either that the string is parsed correctly or that the user will modify it, therefore setting off the LostFocus event, which can then verify correct parsing. Yep, long and slightly meaningless sentences. I'm very sleepy right now. biggrin.gif
Algorithm is offline  
Sponsored Links
Advertisement
 
post #24 of 79 (permalink) Old 06-28-2015, 07:10 PM - Thread Starter
New to Overclock.net
 
Join Date: Oct 2008
Location: Illinois
Posts: 2,085
Rep: 102 (Unique: 93)
lol. No problem. I am actually trying this out as a windows store app. Intent is that the look and feel should be like a real calculator. Each number and operation will be a button (button for one, two, etc. button for +, -, etc). I intend to use one event handler for all button clicks. Then based on which button was the sender, I will put some logic around performing the operation. Work in progress...with work week starting, I will be bit slower, but will keep you all posted.

Registry Hack Information


Have a laugh (Click to show)Warning: Spoiler! (Click to show)


Quote:
Originally Posted by Hotcarl go_quote.gif
I keep it long and hole facing me, or does it not matter
Quote:
Originally Posted by Krunk_Kracker go_quote.gif
I have nothing of value to add to this thread, accept that I read this title as "Anus Transformer" and was prepared to infract you.



lol



Awaz is offline  
post #25 of 79 (permalink) Old 06-29-2015, 01:22 PM
Mathematician
 
Join Date: Feb 2013
Posts: 442
Rep: 20 (Unique: 15)
Quote:
Originally Posted by Awaz View Post

lol. No problem. I am actually trying this out as a windows store app. Intent is that the look and feel should be like a real calculator. Each number and operation will be a button (button for one, two, etc. button for +, -, etc). I intend to use one event handler for all button clicks. Then based on which button was the sender, I will put some logic around performing the operation. Work in progress...with work week starting, I will be bit slower, but will keep you all posted.

That's not the way programmers normally write event handlers for buttons, but it's certainly a creative one. Reminds me of the days when I still didn't get how references worked, and thought that modifying the control referred to by "sender" wouldn't modify the actual control. Just a memory from my C++ days, when classes behaved like a C# struct, and you had to create a pointer to an object to make it work like a C# class. I should really get back into C++ sometime.
Algorithm is offline  
post #26 of 79 (permalink) Old 07-01-2015, 06:28 AM
Software Developer
 
RagingCain's Avatar
 
Join Date: Oct 2010
Location: Jacksonville, FL
Posts: 7,212
Rep: 727 (Unique: 510)
Quote:
Originally Posted by Awaz View Post

lol. No problem. I am actually trying this out as a windows store app. Intent is that the look and feel should be like a real calculator. Each number and operation will be a button (button for one, two, etc. button for +, -, etc). I intend to use one event handler for all button clicks. Then based on which button was the sender, I will put some logic around performing the operation. Work in progress...with work week starting, I will be bit slower, but will keep you all posted.

This is how I generally handle generic event triggers such as button clicks. Rather than having 30 or 40 button click event handlers I usually have just one or two.

I have specific event handlers for specific tasks though. It's just a judgement call I generally make.
Code:
private void ButtonClickEventHandler(object sender, EventArgs e)
{
    if (sender.Equals(btnOne))
    { }
    else if (sender.Equals(btnTwo))
    { }
    else if (sender.Equals(btnThree))
    { }
}

There is not much else to it. To prevent calling functions of buttons or to use "specific" methods to the Button class, i.e. change the text of all buttons that are clicked, you do a "Sender As".
Code:
private void ButtonClickEventHandler(object sender, EventArgs e)
{
    //Treat object like a button.
    Button AbstractingSender = sender as Button;
    
    //Use button's properties like Text field.
    AbstractingSender.Text = "Button clicked!";
}

As you have discovered there are good programming practices, good and accepted ways of doing things, and then there are programmers' preference.

I handle the preference part with the following mentality: "If I am going to do things my way, i.e. a little against the grain/norm, I will always write the code cleanly so any programmer worth his, or her, stuff will be able to follow it."

My Site: HouseofCat
My Repos: GitHub Repository
RagingCain is offline  
post #27 of 79 (permalink) Old 07-01-2015, 09:35 AM
Mathematician
 
Join Date: Feb 2013
Posts: 442
Rep: 20 (Unique: 15)
Quote:
Originally Posted by RagingCain View Post

I handle the preference part with the following mentality: "If I am going to do things my way, i.e. a little against the grain/norm, I will always write the code cleanly so any programmer worth his, or her, stuff will be able to follow it."

What's your approach to comments? Verbose, or do you just put comments where there's a complicated formula or something that's not obvious? Just wondering.

Awaz, here's a program I have been working on for a few weeks. Don't worry about what the program actually does (I'm only going to include my Form1 class), just look at the event handlers and see what I did.
Warning: Spoiler! (Click to show)
Code:
        private void btnRADec_Click(object sender, EventArgs e)
        {
            if (!CheckCartesianValues())
            {
                MessageBox.Show("One or more values is not entered correctly. "
                + "Please check the Coordinate fields for correctness.");
                return;
            }

            PolarCoordinates p = new PolarCoordinates(new Point3D(x.value, y.value, z.value));

            raradians.value = p.RA.Radians;
            decradians.value = p.Dec.Radians;
            distance.value = p.Distance;

            txtRARadians.Text = raradians.ToString();
            txtDecRadians.Text = decradians.ToString();
            txtDistance.Text = distance.ToString();

            Black(txtRAHour, ref raradians); //make the textboxes' text black and correct
            Black(txtRAMin, ref raradians);
            Black(txtRASec, ref raradians);
            Black(txtDecDegrees, ref decradians);
            Black(txtDecMin, ref decradians);
            Black(txtDecSec, ref decradians);
            Black(txtDistance, ref distance);

            PrintRATriplet(); //get the hours, minutes, seconds components and print them
            PrintDecTriplet(); //same
        }

        private void btnCartCoord_Click(object sender, EventArgs e)
        {
            if (!CheckAngleValues())
            {
                MessageBox.Show("One or more values is not entered correctly. "
                + "Please check the RA, Dec, and Distance fields for correctness.");
                return;
            }

            Angle RA = new Angle(raradians.value);
            Angle Dec = new Angle(decradians.value);
            Point3D p = new Point3D(new PolarCoordinates(RA, Dec, distance.value));

            x.value = p.X;
            y.value = p.Y;
            z.value = p.Z;

            txtCartX.Text = x.ToString();
            txtCartY.Text = y.ToString();
            txtCartZ.Text = z.ToString();

            Black(txtCartX, ref x); //make the textboxes' text black and correct
            Black(txtCartY, ref y);
            Black(txtCartZ, ref z);
        }

        private void LeaveRATextbox(object sender, EventArgs e) //when an RA textbox loses focus
        {
            try
            {
                int hours = CheckIntValues(txtRAHour, ref raradians);
                int minutes = CheckIntValues(txtRAMin, ref raradians);
                int seconds = CheckIntValues(txtRASec, ref raradians);
                raradians.value = (3600 * hours + 60 * minutes + seconds) / 86400.0 * 2 * Math.PI; //find what fraction of a circle it is and multiply by 2 pi for the radians
                txtRARadians.Text = raradians.ToString();
            }
            catch (FormatException)
            {
                txtRARadians.Text = "Error";
            }
        }

        private void LeaveDecTextbox(object sender, EventArgs e) //when a Dec textbox loses focus
        {
            try
            {
                int degrees = CheckIntValues(txtDecDegrees, ref decradians);
                int minutes = CheckIntValues(txtDecMin, ref decradians);
                int seconds = CheckIntValues(txtDecSec, ref decradians);
                decradians.value = (3600 * degrees + 60 * minutes + seconds) / 1296000.0 * 2 * Math.PI; //find what fraction of a circle it is and multiply by 2 pi for the radians
                txtDecRadians.Text = decradians.ToString();
            }
            catch (FormatException)
            {
                txtDecRadians.Text = "Error";
            }
        }

        private void LeaveDoubleTextbox(object sender, EventArgs e) //when any other textbox loses focus
        {
            if(object.ReferenceEquals(sender, txtDistance))
            {
                try
                {
                    distance.value = CheckDoubleValues(txtDistance, ref distance); //just check string for correctness
                }
                catch(FormatException)
                {

                }
            }
            else if(object.ReferenceEquals(sender, txtCartX))
            {
                try
                {
                    x.value = CheckDoubleValues(txtCartX, ref x);
                }
                catch(FormatException)
                {

                }
            }
            else if(object.ReferenceEquals(sender, txtCartY))
            {
                try
                {
                    y.value = CheckDoubleValues(txtCartY, ref y);
                }
                catch(FormatException)
                {

                }
            }
            else if (object.ReferenceEquals(sender, txtCartZ))
            {
                try
                {
                    z.value = CheckDoubleValues(txtCartZ, ref z);
                }
                catch (FormatException)
                {

                }
            }
        }

Sorry it's so long. I already eliminated the non-event handler methods. You can see two different styles used. My form has two buttons, each with its own event handler. It also has a lot of textboxes, which are in three groups. I want to parse a textbox after the user clicks away from it and turn the text red if there is a parsing error. But each group requires a different parsing algorithm, so I assign each textbox in a particular group to a handler that figures out which textbox it is by using object.ReferenceEquals() or just checks all the textboxes in the group.
Algorithm is offline  
post #28 of 79 (permalink) Old 07-01-2015, 10:38 AM
Software Developer
 
RagingCain's Avatar
 
Join Date: Oct 2010
Location: Jacksonville, FL
Posts: 7,212
Rep: 727 (Unique: 510)
Quote:
Originally Posted by Algorithm View Post

Quote:
Originally Posted by RagingCain View Post

I handle the preference part with the following mentality: "If I am going to do things my way, i.e. a little against the grain/norm, I will always write the code cleanly so any programmer worth his, or her, stuff will be able to follow it."

What's your approach to comments? Verbose, or do you just put comments where there's a complicated formula or something that's not obvious? Just wondering.

I generally comment where optimizations take place and the code doesn't adhere to common sense. For example in my CPU Benchmark program, I have quite a few optimizations take place that run faster then what occurs in the standard loop.

If I found code online that does something similar to what I need, or references a control in a unique manner, I comment what I try to do and the original source of the code for later reference.

Above complex Eventhandlers (for the above reason).

Combine this with data-type + Camel Case variables, non-generic function names, and utilization of #regions + comments, my code, I feel just naturally becomes readable.
Code:
intNumberOfDeadPeople = 0;

lngNumberOfLivingPeople = 0;

dblSpaceGhostMultiplier = 0.0;

/* Section that has multiple functions that handle displaying of information to the user. */
#region PrintScreens
#endregion


//Populates the NIC TreeView.
private void funcLoadNICs()
{
    funcLOG("All network interface information has been gathered.");

    int j = 1;

    foreach (NIC nic in comp.listNIC)
    {
        if (nic.IsPhysical)
        {
            treeNICS.Nodes.Add("Network Adapter #: " + j.ToString() + " - " + nic.getName());

            if (j == 1)
            {
                physNicName = nic.getName();
                physNicMac = nic.getMAC();
                physNicGuid = nic.getGUID();
            }

            for (int i = 0; i < nic.intNICLength; i++)
            {
                treeNICS.Nodes[(j - 1)].Nodes.Add(nic.NICInfo.ElementAt(i));
            }

            funcLOG("NIC" + j + ": " + nic.getName() + " has loaded.");
            j++;
        }
    }

    funcLOG("All Physical NICs have finished loading in tree view.");
}

And of course, humor:
Code:
//Purpose: For dealing with stupid Folder Redirection.
//Source: http://stackoverflow.com/questions/14023051/bcdedit-not-recognized-when-running-via-c-sharp, user2126375
string cmdFullFileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows),
                            ((Environment.Is64BitOperatingSystem) && (!(Environment.Is64BitProcess)))
                                ? @"Sysnative\cmd.exe" : @"System32\cmd.exe");

The above case deals with the fact that an x86 program, running on Windows 8.x (x64) is unable to use certain keywords to launch applications, in this case: CMD.EXE

So on Windows 7, this works in all cases:
Code:
ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd.exe");

In Windows 8.x+:
Code:
System.Diagnostics.Process p = new System.Diagnostics.Process();
ProcessStartInfo ps = new ProcessStartInfo();

string cmdFullFileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows),
                            Environment.Is64BitOperatingSystem && !Environment.Is64BitProcess
                                ? @"Sysnative\cmd.exe"
                                : @"System32\cmd.exe");

ps.FileName = cmdFullFileName;

ps.UseShellExecute = false;
ps.CreateNoWindow = true;
ps.RedirectStandardOutput = true;
ps.RedirectStandardError = true;

p.StartInfo = ps;
p.Start();

Then I found, the above is not ALWAYS true, and the truly best method is to turn off 64-bit folder redirection temporarily.
Code:
//Microsoft is officially ********.
#region UnmanagedCode
class NativeMethods
{
    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern bool Wow64DisableWow64FsRedirection(ref IntPtr ptr);

    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern bool Wow64RevertWow64FsRedirection(ref IntPtr ptr);
}
#endregion

public static void funcEnableHPET()
{
    if ((System.Environment.Is64BitOperatingSystem) && (!(System.Environment.Is64BitProcess)))
    {
        IntPtr ptr = new IntPtr();
        NativeMethods.Wow64DisableWow64FsRedirection(ref ptr);
        ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd.exe");

        procStartInfo.UseShellExecute = true;
        procStartInfo.CreateNoWindow = false;
        procStartInfo.WorkingDirectory = @"C:\Windows\system32";
        procStartInfo.Arguments = @"/k bcdedit /set useplatformclock true";

        Process proc = new Process();
        proc.StartInfo = procStartInfo;
        proc.Start();

        NativeMethods.Wow64RevertWow64FsRedirection(ref ptr);
    }
    else
    {
        ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd.exe");

        procStartInfo.UseShellExecute = true;
        procStartInfo.CreateNoWindow = false;
        procStartInfo.WorkingDirectory = @"C:\Windows\system32";
        procStartInfo.Arguments = @"/k bcdedit /set useplatformclock true";

        Process proc = new Process();
        proc.StartInfo = procStartInfo;
        proc.Start();
    }
}

So I document that kind of stuff... usually if I have to ask the question Why? It needs a comment.

My Site: HouseofCat
My Repos: GitHub Repository
RagingCain is offline  
post #29 of 79 (permalink) Old 07-01-2015, 11:13 AM
Mathematician
 
Join Date: Feb 2013
Posts: 442
Rep: 20 (Unique: 15)
Quote:
Originally Posted by RagingCain View Post

I generally comment where optimizations take place and the code doesn't adhere to common sense. For example in my CPU Benchmark program, I have quite a few optimizations take place that run faster then what occurs in the standard loop.

...

So I document that kind of stuff... usually if I have to ask the question Why? It needs a comment.

Yeah, pretty much the same here. I always comment nastily when I have to write a bunch of lines to compensate for some .NET annoyance.
Algorithm is offline  
post #30 of 79 (permalink) Old 07-01-2015, 11:27 AM
Software Developer
 
RagingCain's Avatar
 
Join Date: Oct 2010
Location: Jacksonville, FL
Posts: 7,212
Rep: 727 (Unique: 510)
Quote:
Originally Posted by Algorithm View Post

Quote:
Originally Posted by RagingCain View Post

I generally comment where optimizations take place and the code doesn't adhere to common sense. For example in my CPU Benchmark program, I have quite a few optimizations take place that run faster then what occurs in the standard loop.

...

So I document that kind of stuff... usually if I have to ask the question Why? It needs a comment.

Yeah, pretty much the same here. I always comment nastily when I have to write a bunch of lines to compensate for some .NET annoyance.

We are spoiled programmers ^.^

My Site: HouseofCat
My Repos: GitHub Repository
RagingCain is offline  
Reply

Quick Reply
Message:
Options

Register Now

In order to be able to post messages on the Overclock.net - An Overclocking Community forums, you must first register.
Please enter your desired user name, your email address and other required details in the form below.
User Name:
If you do not want to register, fill this field only and the name will be used as user name for your post.
Password
Please enter a password for your user account. Note that passwords are case-sensitive.
Password:
Confirm Password:
Email Address
Please enter a valid email address for yourself.
Email Address:

Log-in



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Show Printable Version Show Printable Version
Email this Page Email this Page


Forum Jump: 

Posting Rules  
You may post new threads
You may post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off