6 Replies - 624 Views - Last Post: 03 September 2011 - 11:44 AM Rate Topic: -----

#1 adn258  Icon User is offline

  • D.I.C Addict

Reputation: 11
  • View blog
  • Posts: 761
  • Joined: 31-August 11

Delete Program Uses Too Many GOTO Statements?

Posted 02 September 2011 - 06:01 PM

So some other programmers and I were asking to see the code for this delete program. It's not done yet but I am having a really hard time as to how I could possibly get this to work without goto.

In any case Any help is appreciated. Essentially this program is designed so it will DELETE all Java cache and web history automatically upon the user exiting all of his/her browsers. I have tested this code and it works fine. It currently only works for Chrome because I haven't created enough delete constructs using the function and class ( but I will).

The real question is how else could this be done without goto since it has to take into account when the browser is opened and while it's open when it will be closed again (all browsers) to delete the web history.




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Diagnostics;
using System.Windows.Forms;

namespace DeleteNotLogin
{

    public class DeleteMethod
    {


        public string a;

        public void delete()
        {
            string[] filePaths = Directory.GetFiles(a);     // Delete  files 
            foreach (string file in filePaths)
                File.Delete(file);

        }
    }



 class DeletionNotLogin
    {


     

       static void Main(string[] args)
        {



            string MainUserPath = System.Environment.GetEnvironmentVariable("USERPROFILE");  // Main User directory which is where Internet Data Is Stored
            string RootBrowserPathChrome = @"\AppData\Local\Google\Chrome\User Data\Default";  //One Of The Main Chrome Directories For Web History
            string RootBrowserPathChromeCache = @"\AppData\Local\Google\Chrome\User Data\Default\Cache";
            string JavaCachePath = @"\AppData\LocalLow\Sun\Java\Deployment\cache";  //Java Cache
     




        Start:
            Thread.Sleep(500);    //check every half second

            Process[] pNameChrome = Process.GetProcessesByName("chrome");
            Process[] pNameInternetExplorer = Process.GetProcessesByName("iexplore");
            Process[] pNameFirefox = Process.GetProcessesByName("firefox");
            if (pNameChrome.Length != 0 || pNameInternetExplorer.Length != 0 || pNameFirefox.Length != 0)
            {
                goto WaitClose; //if any browser doesn't equal zero i.e. it's open and running as a process so we goto to the part of the program where we 
            }                       //wait for the user to close the Browers that are open.
            else
            {

                goto Start;  //Don't do anything until the browser starts, once it does wait for the user to close the browser.

            }



            //when the user exits, Delte all the web content and java cache that user has.
           //check every half second
            WaitClose:                   
            Thread.Sleep(500);
            Process[] pNameChromeTwo = Process.GetProcessesByName("chrome");
            Process[] pNameInternetExplorerTwo = Process.GetProcessesByName("iexplore");
            Process[] pNameFirefoxTwo = Process.GetProcessesByName("firefox");
            if (pNameChromeTwo.Length == 0 && pNameInternetExplorerTwo.Length == 0 && pNameFirefoxTwo.Length == 0) // when all browsers are closed
            {



                DeleteMethod ChromeDirec = new DeleteMethod();
                ChromeDirec.a = MainUserPath + RootBrowserPathChrome;   //delete files from main chrome Directory ALL OF THEM!!
                ChromeDirec.delete();


                DeleteMethod ChromeCache = new DeleteMethod();
                ChromeCache.a = MainUserPath + RootBrowserPathChromeCache;
                ChromeCache.delete();

                DeleteMethod IExplorerCache = new DeleteMethod();

                



                DirectoryInfo dir = new DirectoryInfo(MainUserPath + JavaCachePath); //deleteing the java cache

                foreach (FileInfo files in dir.GetFiles())
                {
                    files.Delete();
                }

                foreach (DirectoryInfo dirs in dir.GetDirectories())
                {
                    dirs.Delete(true);
                }



          
              goto Start;    //start at the beginning of the program again checking if the browser is ever opened


              }

            else
            {
                goto WaitClose;   //keep checking for the browser to be closed - As Soon as it's closed cache and web history is deleted
            }








        }

    }
}












Is This A Good Question/Topic? 0
  • +

Replies To: Delete Program Uses Too Many GOTO Statements?

#2 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4437
  • View blog
  • Posts: 7,712
  • Joined: 08-June 10

Re: Delete Program Uses Too Many GOTO Statements?

Posted 02 September 2011 - 06:38 PM

This is definitely a case where you can remove the gotos with a combination of functions and an infinite loop. I'm not at a computer where I can easily provide an example, so hopefully someone else will soon or I will try to tomorrow.
Was This Post Helpful? 0
  • +
  • -

#3 adn258  Icon User is offline

  • D.I.C Addict

Reputation: 11
  • View blog
  • Posts: 761
  • Joined: 31-August 11

Re: Delete Program Uses Too Many GOTO Statements?

Posted 02 September 2011 - 09:05 PM

View PostCurtis Rutland, on 02 September 2011 - 06:38 PM, said:

This is definitely a case where you can remove the gotos with a combination of functions and an infinite loop. I'm not at a computer where I can easily provide an example, so hopefully someone else will soon or I will try to tomorrow.



Ok thank you, I really appreciate your support.
Was This Post Helpful? 0
  • +
  • -

#4 CodingSup3rnatur@l-360  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 991
  • View blog
  • Posts: 971
  • Joined: 30-September 10

Re: Delete Program Uses Too Many GOTO Statements?

Posted 03 September 2011 - 02:59 AM

Hi,

I've done a quick conversion of your code. I think it should work the same still. All I've done is replace the code labels with methods, and replaced the goto statements with method calls:

IGNORE THIS CODE! It's...obscene.
Spoiler


The only real time that I can think of where goto like statements should be seen anywhere near a C# program is when they are generated by the C# compiler (in certain state machine implementations (like iterators blocks (yield return etc), and the new asynchronous methods CTP), for example)!

Some people argue that on very very rare occasions, goto statements can make code simpler, but I think it best to avoid them entirely in your code, and favour method calls and conditionals :)

EDIT: Oh wow... Ignore the stack overflow waiting to happen above. Don't ask what I was thinking there :no: I'm off for some fresh air...

EDIT2: I'm back... You want something more like this:

class DeletionNotLogin {
        static string MainUserPath = System.Environment.GetEnvironmentVariable("USERPROFILE");  // Main User directory which is where Internet Data Is Stored
        static string RootBrowserPathChrome = @"\AppData\Local\Google\Chrome\User Data\Default";  //One Of The Main Chrome Directories For Web History
        static string RootBrowserPathChromeCache = @"\AppData\Local\Google\Chrome\User Data\Default\Cache";
        static string JavaCachePath = @"\AppData\LocalLow\Sun\Java\Deployment\cache";  //Java Cache

        static void Main(string[] args) {
            while (true) {
                Start();
            }
        }

        private static void Start() {
            Thread.Sleep(500);    //check every half second

            Process[] pNameChrome = Process.GetProcessesByName("chrome");
            Process[] pNameInternetExplorer = Process.GetProcessesByName("iexplore");
            Process[] pNameFirefox = Process.GetProcessesByName("firefox");
            if (pNameChrome.Length != 0 || pNameInternetExplorer.Length != 0 || pNameFirefox.Length != 0) {
                WaitClose(); //if any browser doesn't equal zero i.e. it's open and running as a process so we goto to the part of the program where we 
            }                       //wait for the user to close the Browers that are open.
        }

        private static void WaitClose() {
            while (true) {
                Thread.Sleep(500);
                Process[] pNameChromeTwo = Process.GetProcessesByName("chrome");
                Process[] pNameInternetExplorerTwo = Process.GetProcessesByName("iexplore");
                Process[] pNameFirefoxTwo = Process.GetProcessesByName("firefox");
                if (pNameChromeTwo.Length == 0 && pNameInternetExplorerTwo.Length == 0 && pNameFirefoxTwo.Length == 0) // when all browsers are closed
                {
                    DeleteMethod ChromeDirec = new DeleteMethod();
                    ChromeDirec.a = MainUserPath + RootBrowserPathChrome;   //delete files from main chrome Directory ALL OF THEM!!
                    ChromeDirec.delete();

                    DeleteMethod ChromeCache = new DeleteMethod();
                    ChromeCache.a = MainUserPath + RootBrowserPathChromeCache;
                    ChromeCache.delete();

                    DeleteMethod IExplorerCache = new DeleteMethod();

                    DirectoryInfo dir = new DirectoryInfo(MainUserPath + JavaCachePath); //deleteing the java cache

                    foreach (FileInfo files in dir.GetFiles()) {
                        files.Delete();
                    }

                    foreach (DirectoryInfo dirs in dir.GetDirectories()) {
                        dirs.Delete(true);
                    }
                    return;
                } 
            }
        }
    }



Here are some examples of using goto in different scenarios in C#. As noted in that article though, you can produce solutions for the different scenarios without goto, and that is what I would strongly argue you should do :)

This post has been edited by CodingSup3rnatur@l-360: 03 September 2011 - 05:15 AM

Was This Post Helpful? 0
  • +
  • -

#5 Momerath  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1010
  • View blog
  • Posts: 2,444
  • Joined: 04-October 09

Re: Delete Program Uses Too Many GOTO Statements?

Posted 03 September 2011 - 04:01 AM

It's not a good idea to be calling Start() at the end of every method. You'll eventually overflow the stack as none of the methods ever ends. Remove them all and make the Main method read
static void Main(string[] args) {
    while (true) {
        Start();
    }
}


As for GOTO there are some uses for it. Donald Knuth wrote a paper describing when to use it, and both Linus Torvalds (of Linux fame) and Steve McConnell (author of Code Complete, a book every developer should read) believe it has its place.

This post has been edited by Momerath: 03 September 2011 - 04:12 AM

Was This Post Helpful? 1
  • +
  • -

#6 baavgai  Icon User is online

  • Dreaming Coder
  • member icon

Reputation: 5780
  • View blog
  • Posts: 12,595
  • Joined: 16-October 07

Re: Delete Program Uses Too Many GOTO Statements?

Posted 03 September 2011 - 05:09 AM

I knew you could use a goto in C#. I've never seem anyone actually do it...

I have a long standing challenge in the C forums. I can guarantee you that life can be lived without goto; almost always more happily. I have yet to see an example that demands it. Most of the examples that feel it's better are wrong.

First, some comments:
public class DeleteMethod {
	public string a; // a?  WTF kind of name is a?  Why is it public?
	// Where's your construtor?  What is the point of this class?
	public void delete() {
		string[] filePaths = Directory.GetFiles(a);     // Delete  files 
		foreach (string file in filePaths) {
			File.Delete(file);
		}
	}
}

class DeletionNotLogin {
	// everything is in main?  you already know something's wrong
	static void Main(string[] args) {
		string MainUserPath = System.Environment.GetEnvironmentVariable("USERPROFILE");  // Main User directory which is where Internet Data Is Stored
		string RootBrowserPathChrome = @"\AppData\Local\Google\Chrome\User Data\Default";  //One Of The Main Chrome Directories For Web History
		string RootBrowserPathChromeCache = @"\AppData\Local\Google\Chrome\User Data\Default\Cache";
		string JavaCachePath = @"\AppData\LocalLow\Sun\Java\Deployment\cache";  //Java Cache

		// and the evil begins
		Start:
			Thread.Sleep(500);    //check every half second
		
			// three different arrays... why
			Process[] pNameChrome = Process.GetProcessesByName("chrome");
			Process[] pNameInternetExplorer = Process.GetProcessesByName("iexplore");
			Process[] pNameFirefox = Process.GetProcessesByName("firefox");
			if (pNameChrome.Length != 0 || pNameInternetExplorer.Length != 0 || pNameFirefox.Length != 0) {
				goto WaitClose;
			} else {
				goto Start;
			}
		WaitClose:
			// cut and paste code from above?  Seriously?
			Thread.Sleep(500);
			Process[] pNameChromeTwo = Process.GetProcessesByName("chrome");
			Process[] pNameInternetExplorerTwo = Process.GetProcessesByName("iexplore");
			Process[] pNameFirefoxTwo = Process.GetProcessesByName("firefox");
			if (pNameChromeTwo.Length == 0 && pNameInternetExplorerTwo.Length == 0 && pNameFirefoxTwo.Length == 0) {
				// this is a horrible mess
				// you don NOT need an object instance here
				DeleteMethod ChromeDirec = new DeleteMethod();
				ChromeDirec.a = MainUserPath + RootBrowserPathChrome;
				ChromeDirec.delete();

				// you already have an instance, why another one?
				DeleteMethod ChromeCache = new DeleteMethod();
				ChromeCache.a = MainUserPath + RootBrowserPathChromeCache;
				ChromeCache.delete();

				DeleteMethod IExplorerCache = new DeleteMethod();
				DirectoryInfo dir = new DirectoryInfo(MainUserPath + JavaCachePath);
				foreach (FileInfo files in dir.GetFiles()) {
					files.Delete();
				}

				foreach (DirectoryInfo dirs in dir.GetDirectories()) {
					dirs.Delete(true);
				}
				goto Start;
			} else {
				goto WaitClose;
			}
	}
}



Wow... The problem is, you don't even seem to understand procedural programming, much less the object oriented kind.

First, let's just clean up the rest, so we have proper procedures and an object.
class DeletionNotLogin {
	private string RootBrowserPathChrome, RootBrowserPathChromeCache, JavaCachePath;
	private string [] processList;
	
	public DeletionNotLogin() {
		string MainUserPath = System.Environment.GetEnvironmentVariable("USERPROFILE");  // Main User directory which is where Internet Data Is Stored
		this.RootBrowserPathChrome = MainUserPath + 
			@"\AppData\Local\Google\Chrome\User Data\Default";
		this.RootBrowserPathChromeCache = MainUserPath 
			+ @"\AppData\Local\Google\Chrome\User Data\Default\Cache";
		this.JavaCachePath = MainUserPath 
			+ @"\AppData\LocalLow\Sun\Java\Deployment\cache";
		
		this.processList = new string[] {"chrome", "iexplore", "firefox"};
	}
	
	private bool IsRunning() {
		foreach(string name in this.processList) {
			if (Process.GetProcessesByName(name).Length !=0) { return true; }
		}
		return false;
	}
	
	private void Kill(string path, bool includeDir) {
		DirectoryInfo dir = new DirectoryInfo(path);
		foreach (FileInfo files in dir.GetFiles()) { files.Delete(); }
		if (includeDir) {
			foreach (DirectoryInfo dirs in dir.GetDirectories()) { dirs.Delete(true); }
		}
	}
	
	private void KillAll() {
		Kill(RootBrowserPathChrome, false);
		Kill(RootBrowserPathChromeCache, false);
		Kill(JavaCachePath, true);
	}
	
	public void Run() {
		Start:
			Thread.Sleep(500);
			if (IsRunning()) {
				goto WaitClose;
			} else {
				goto Start;
			}
		WaitClose:
			Thread.Sleep(500);
			if (!IsRunning()) {
				KillAll();
			goto Start;
			} else {
				goto WaitClose;
			}
	}
	
	
	static void Main(string[] args) {
		new DeletionNotLogin().Run();
	}
}




Now all that goto mess is at least clearer. Let's get rid of it.
public void Run() {
	bool waitClose = IsRunning();
	while(true) { // you seem to want a forever loop
		Thread.Sleep(500);
		if (waitClose) {
			if(!IsRunning()) {
				KillAll();
				waitClose = false;
			}
		} else {
			waitClose = IsRunning();
		}
	}
}


Was This Post Helpful? 2
  • +
  • -

#7 adn258  Icon User is offline

  • D.I.C Addict

Reputation: 11
  • View blog
  • Posts: 761
  • Joined: 31-August 11

Re: Delete Program Uses Too Many GOTO Statements?

Posted 03 September 2011 - 11:44 AM

Wow you guys are genius. I mean...I understand the code for the most part but I would never think of being able to implement it like that in those structures at this point. I know what the code means but I don't know how to put it all together very well yet is essentially my problem...lol ....You guys have massive skill sets. Thank you all so much for your help By The way....
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1