473,585 Members | 2,496 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Is this poor C# programming?

JM
Hi

I have a Windows Form that I have 3 textboxes and some buttons. Below is
the code that I have implemented it reads a pile of files from a folder and
then reads each of the files. If the McAfee Dat file version is old (older
than 15 revisions) then it will output the machine name, Scan Engine, and dat
file version (all of this is each of the text files that I load)

Is the way that I coded it poor C# OOP? I mean I have a registry class that
I have borrowed and implemented "using" so that I have access to the class.
Is it a bad practice to have so much code after a button like I do in my Run
button??

BTW I am using C# Express 2005 Beta 1....

#region Using directives

using System;
using System.Collecti ons.Generic;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Windows. Forms;
using Utility.ModifyR egistry; // Class borrowed from the Internet
using System.IO;

#endregion

namespace McAfeeVersionCh eck
{
partial class MainForm : Form
{

// Create an instance of the the registry class. Needs to be here
// because of the Save button (which saves the stuff to Registry)
(SCOPE)
ModifyRegistry myRegistry = new ModifyRegistry( );

public MainForm()
{
InitializeCompo nent();
}

private void buttonExit_Clic k(object sender, EventArgs e)
{
Application.Exi t(); // Close Program
}

private void MainForm_Load(o bject sender, EventArgs e)
{
// Create an instance of the class.
//ModifyRegistry myRegistry = new ModifyRegistry( );

// Creates strings and stores a value for each
// Registry reads from HKLM\SOFTWARE\< ProgramName>
string strMcAfeeVersio n = myRegistry.Read ("McAfeeVersion ");
string strScanEngine = myRegistry.Read ("ScanEngine ");
string strDatFile = myRegistry.Read ("DatFile");

if ((strMcAfeeVers ion != null && strScanEngine != null &&
strDatFile != null) && (strMcAfeeVersi on != "" || strScanEngine != "" ||
strDatFile != ""))
{
// Place the values on the form from the registry
textBoxMcAfeeVe rsion.Text = strMcAfeeVersio n;
textBoxScanEngi ne.Text = strScanEngine;
textBoxDatVersi on.Text = strDatFile;
buttonRun.Enabl ed = true;
}
else //null or empty
{
MessageBox.Show ("This must be the first time that you have
used this program. Please set the values in the text boxes and click the
Save Button");
}
}

private void buttonSave_Clic k(object sender, EventArgs e)
{

if ((textBoxMcAfee Version.Text == null || textBoxScanEngi ne.Text
== null || textBoxDatVersi on.Text == null) || (textBoxMcAfeeV ersion.Text ==
"" || textBoxScanEngi ne.Text == "" || textBoxDatVersi on.Text == ""))
{
MessageBox.Show ("Please fill out all of the text boxes
before trying to Save");
}
else
{
myRegistry.Writ e("McAfeeVersio n", textBoxMcAfeeVe rsion.Text);
myRegistry.Writ e("ScanEngine ", textBoxScanEngi ne.Text);
myRegistry.Writ e("DatFile", textBoxDatVersi on.Text);
}
}

private void buttonRun_Click (object sender, EventArgs e)
{
if ((textBoxMcAfee Version.Text == null ||
textBoxScanEngi ne.Text == null || textBoxDatVersi on.Text == null) ||
(textBoxMcAfeeV ersion.Text == "" || textBoxScanEngi ne.Text == "" ||
textBoxDatVersi on.Text == ""))
{
MessageBox.Show ("Please fill out all of the text boxes
before trying to Run");
}
else
{
DirectoryInfo Dir = new DirectoryInfo(@ "c:\SVirus_ver" );
FileInfo[] txtFiles = Dir.GetFiles();

// Print out the names of the files in the current directory.
foreach (FileInfo filesTemp in txtFiles)
//MessageBox.Show (filesTemp.Name );
{
try
{
// Create an instance of StreamReader to read from
a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new
StreamReader(Pa th.Combine(@"c: \SVirus_ver",fi lesTemp.Name)))
{
String line;
// Read and display lines from the file until
the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{

// Remove spaces
string RemovedSpacesLi ne = line.Replace(",
",",");

// Split the line into an string array
string[] LineFields =
RemovedSpacesLi ne.Split(',');

// Dat File, some are 8, some are 4. Trim
the long ones.
if (LineFields[9].Length > 4)
LineFields[9] =
LineFields[9].Substring(4, (LineFields[9].Length - 4));

// Convert the Array Member to an int
int DatVersion =
Convert.ToInt32 (LineFields[9]);

// Create the limit for the dat files.
int DatFileLowLimit =
(Convert.ToInt3 2(textBoxDatVer sion.Text) - 15);

if (DatVersion < DatFileLowLimit )
{
// Computer Name
MessageBox.Show (LineFields[3]);

// Software Version
MessageBox.Show (LineFields[8]);

// Scan Engine
MessageBox.Show (LineFields[11]);

// Dat File
MessageBox.Show (LineFields[9]);
}

}
} // End of Using

} // End of Try
catch (Exception except)
{
// Let the user know what went wrong.
//MessageBox.Show ("The file could not be read:");
//MessageBox.Show (except.Message );
}
} // End of ForEach
} // End of If Else
} // End of Button Click
} // End of Class
} // End NameSpace
Nov 16 '05 #1
4 2227
Hi, JM,

To me, the deep nesting indicates too much complexity in one function.
That kind of complexity makes it hard to debug and hard to reuse code
elements. So I would refactor it. Step one might look like this:

private void ShowStuff(strin g[] LineFields)
{
// Computer Name
MessageBox.Show (LineFields[3]);
// Software Version
MessageBox.Show (LineFields[8]);
// Scan Engine
MessageBox.Show (LineFields[11]);
// Dat File
MessageBox.Show (LineFields[9]);
}

which doesn't help very much on its own, but it's a start. You might
go even deeper:

private string ComputerName(st ring[] LineFields)
{
return LineFields[3];
}
private string SoftwareVersion (string[] LineFields)
{
return LineFields[8];
}
private string ScanEngine(stri ng[] LineFields)
{
return LineFields[11];
}
private string DatFile(string[] LineFields)
{
return LineFields[9];
}
private void ShowStuff(strin g[] LineFields)
{
MessageBox.Show (ComputerName(L ineFields));
MessageBox.Show (SoftwareVersio n(LineFields));
MessageBox.Show (ScanEngine(Lin eFields));
MessageBox.Show (DatFile(LineFi elds));
}

eliminating the need for some comments while preserving clarity.

This starts to suggest a class is waiting to be born, something that
would hold LineFields and be able to report from it, for example, the
ComputerName and SoftwareVersion ; you could feed the "line" variable
into it in its constructor, and let it prune out the spaces and split
along the commas. You might find you have a use for that class
somewhere else; it wouldn't be so tightly tied to this particular Form.

Another approach to this might be to declare the indexes into the
LineFields arrays as constants:
const int ComputerName = 3;
const int SoftwareVersion = 8;
etc.

This would still work quite well with the separate class.

HTH,
--Carl

Nov 16 '05 #2
SP
"JM" <JM@discussions .microsoft.com> wrote in message
news:B4******** *************** ***********@mic rosoft.com...
Hi

I have a Windows Form that I have 3 textboxes and some buttons. Below is
the code that I have implemented it reads a pile of files from a folder
and
then reads each of the files. If the McAfee Dat file version is old
(older
than 15 revisions) then it will output the machine name, Scan Engine, and
dat
file version (all of this is each of the text files that I load)

Is the way that I coded it poor C# OOP? I mean I have a registry class
that
I have borrowed and implemented "using" so that I have access to the
class.
Is it a bad practice to have so much code after a button like I do in my
Run
button??

BTW I am using C# Express 2005 Beta 1....

#region Using directives

using System;
using System.Collecti ons.Generic;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Windows. Forms;
using Utility.ModifyR egistry; // Class borrowed from the Internet
using System.IO;

#endregion

namespace McAfeeVersionCh eck
{
partial class MainForm : Form
{

// Create an instance of the the registry class. Needs to be here
// because of the Save button (which saves the stuff to Registry)
(SCOPE)
ModifyRegistry myRegistry = new ModifyRegistry( );

public MainForm()
{
InitializeCompo nent();
}

private void buttonExit_Clic k(object sender, EventArgs e)
{
Application.Exi t(); // Close Program
}

private void MainForm_Load(o bject sender, EventArgs e)
{
// Create an instance of the class.
//ModifyRegistry myRegistry = new ModifyRegistry( );

// Creates strings and stores a value for each
// Registry reads from HKLM\SOFTWARE\< ProgramName>
string strMcAfeeVersio n = myRegistry.Read ("McAfeeVersion ");
string strScanEngine = myRegistry.Read ("ScanEngine ");
string strDatFile = myRegistry.Read ("DatFile");

if ((strMcAfeeVers ion != null && strScanEngine != null &&
strDatFile != null) && (strMcAfeeVersi on != "" || strScanEngine != "" ||
strDatFile != ""))
Why not have this testing as part of the class, e.g.

if(! myRegistry.hasN ullOrEmptyValue s)

This would also eliminate the temporary variables...
{
// Place the values on the form from the registry
textBoxMcAfeeVe rsion.Text = strMcAfeeVersio n;
with...
textBoxMcAfeeVe rsion.Text =
myRegistry.Read ("McAfeeVersion ");
textBoxScanEngi ne.Text = strScanEngine;
textBoxDatVersi on.Text = strDatFile;
buttonRun.Enabl ed = true;
}
else //null or empty
{
MessageBox.Show ("This must be the first time that you have
used this program. Please set the values in the text boxes and click the
Save Button");
}
}

private void buttonSave_Clic k(object sender, EventArgs e)
{

If you have an observer on the button then there would be no need to test
when they click because it would
be disabled until they have filled in the textboxes. I also think that
Text.Length != 0 should cover what you need in the observer.
if ((textBoxMcAfee Version.Text == null ||
textBoxScanEngi ne.Text
== null || textBoxDatVersi on.Text == null) || (textBoxMcAfeeV ersion.Text
==
"" || textBoxScanEngi ne.Text == "" || textBoxDatVersi on.Text == ""))
{
MessageBox.Show ("Please fill out all of the text boxes
before trying to Save");
}
else
{
myRegistry.Writ e("McAfeeVersio n",
textBoxMcAfeeVe rsion.Text);
myRegistry.Writ e("ScanEngine ", textBoxScanEngi ne.Text);
myRegistry.Writ e("DatFile", textBoxDatVersi on.Text);
}
}

private void buttonRun_Click (object sender, EventArgs e)
{
same here with the observer
if ((textBoxMcAfee Version.Text == null ||
textBoxScanEngi ne.Text == null || textBoxDatVersi on.Text == null) ||
(textBoxMcAfeeV ersion.Text == "" || textBoxScanEngi ne.Text == "" ||
textBoxDatVersi on.Text == ""))
{
MessageBox.Show ("Please fill out all of the text boxes
before trying to Run");
}
else
{
DirectoryInfo Dir = new DirectoryInfo(@ "c:\SVirus_ver" );
FileInfo[] txtFiles = Dir.GetFiles();

// Print out the names of the files in the current
directory.
foreach (FileInfo filesTemp in txtFiles)
//MessageBox.Show (filesTemp.Name );
{
try
{
// Create an instance of StreamReader to read from
a file.
// The using statement also closes the
StreamReader.
using (StreamReader sr = new
StreamReader(Pa th.Combine(@"c: \SVirus_ver",fi lesTemp.Name)))
{
String line;
// Read and display lines from the file until
the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{

// Remove spaces
string RemovedSpacesLi ne = line.Replace(",
",",");

// Split the line into an string array
string[] LineFields =
RemovedSpacesLi ne.Split(',');

// Dat File, some are 8, some are 4. Trim
the long ones.
if (LineFields[9].Length > 4)
LineFields[9] =
LineFields[9].Substring(4, (LineFields[9].Length - 4));

// Convert the Array Member to an int
int DatVersion =
Convert.ToInt32 (LineFields[9]);

// Create the limit for the dat files.
int DatFileLowLimit =
(Convert.ToInt3 2(textBoxDatVer sion.Text) - 15);

if (DatVersion < DatFileLowLimit )
{
// Computer Name
MessageBox.Show (LineFields[3]);

// Software Version
MessageBox.Show (LineFields[8]);

// Scan Engine
MessageBox.Show (LineFields[11]);

// Dat File
MessageBox.Show (LineFields[9]);
}

}
} // End of Using

} // End of Try
catch (Exception except)
{
// Let the user know what went wrong.
//MessageBox.Show ("The file could not be read:");
//MessageBox.Show (except.Message );
}
} // End of ForEach
} // End of If Else
} // End of Button Click
} // End of Class
} // End NameSpace


Final comment - far too many comments!!! A comment is often a sign to
extract a method and a whole bunch of comments is probably asking for a
class.

SP
Nov 16 '05 #3
>
Final comment - far too many comments!!! A comment is often a sign to
extract a method and a whole bunch of comments is probably asking for a
class.

SP


To SP: I disagree. A comment that illustrates a complicated snafu in the
code may be a sign that the code should be refactored. OTOH, a list of
comments that appear derived from psuedocode may simply be a sign of an
organized mind.

To JM: Typically, comments are most useful when they explain "why" the code
is what it is, or "what purpose" a section of code has. Comments on every
line is probably not an efficient use of your time. That said, there is
NOTHING WRONG with it.

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--
Nov 16 '05 #4
Nick Malik [Microsoft] <ni*******@hotm ail.nospam.com> wrote:

<snip>
To JM: Typically, comments are most useful when they explain "why" the code
is what it is, or "what purpose" a section of code has. Comments on every
line is probably not an efficient use of your time. That said, there is
NOTHING WRONG with it.


I disagree - when comments are there when they don't need to be, they
make the really *useful* comments less easily visible, and they
distract from the code.

The rules I use are:

1) Comment every member, except private fields which have direct
property equivalents - and then make doubly sure you comment the
properties.

2) Add comments within the code if it's not immediately clear what that
code is doing, especially if it would otherwise look like it could be
changed or removed to simplify things.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

30
2221
by: Michael B Allen | last post by:
I have a general purpose library that has a lot of checks for bad input parameters like: void * linkedlist_get(struct linkedlist *l, unsigned int idx) { if (l == NULL) { errno = EINVAL; return NULL; }
4
1764
by: Bill Thorne | last post by:
We have a COM object that has been wrappered for use in .NET and which can make calls which can take a while to execute. These are mainframe integration calls that might perform a lot of data entry and gathering, returning the results to the ASP.NET caller. I have tried an AsyncPage class (implements IHttpAsyncHandler and uses custom...
20
2098
by: John Mark Howell | last post by:
I had a customer call about some C# code they had put together that was handling some large arrays. The performance was rather poor. The C# code runs in about 22 seconds and the equivalent C++.Net code runs in 0.3 seconds. Can someone help me understand why the C# code performance is so poor? I rewote the C# code to use a single...
11
2342
by: John Fly | last post by:
I'm working on a large project(from scratch). The program is essentially a data file processor, the overall view is this: A data file is read in, validated and stored in a memory structure similar to a database or XML representation. Rules to modify the stored data will be executed, then the data will be transformed into an output format....
4
2676
by: Jim Devenish | last post by:
I have converted an Access back-end to SQL Server back-end but am having some problems. The Access to Access application has been running well for some years. I have successfully copied all the data to SQL Server and linked the tables to the front end .mdb (I am not using .adp). Some queries were performing poorly so I have converted...
49
2753
by: utab | last post by:
Why is for(int i=0; i < 100; ++i) poor?
40
1974
by: JeffP | last post by:
Is this a holiday week? There are way too many unanswered posts! I dont' care if the person asked a dumb or un-comprehensible question, they deserve a response even if it is to clarify or re-state their question and offer a suggestion. Hang in there posters, hopefully our questions will be asnwered.
12
10225
by: pittendrigh | last post by:
Let's say we're trying to keep blog and forum spammers out of our site--we're not trying to protect fort knox. 1) Step one is a one-time-only step. We create six different css files that define the same six color names differently, but each such css file assigns red to one and only one of those same six color names, and then store the...
4
2388
by: joa2212 | last post by:
Hello everybody, I'm posting this message because I'm quiet frustrated. We just bought a software from a small software vendor. In the beginning he hosted our application on a small server at his office. I think it was a Fujitsu-Siemens x86 running debian Linux. The performance of the DSL-Line was very poor, so we decided to buy an own...
0
7908
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7836
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8336
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
8212
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5710
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3835
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3863
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1447
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1175
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.