Unofficial Programming Thread II

Post » Tue May 17, 2011 10:42 am

You cannot define a constructor in an interface, at least in Java. (If you want to force creation of objects of different types with the same type of parameters, you should take a look at the factory pattern.)

But other than that, yes, that's the general idea.

An interface is generally used to abstract the protocol from its implementation. For example, if all you want is to write some data, you might define an interface DataWriter, with a method write(byte[] buffer). A class that uses a DataWriter can then use any implementation of the DataWriter interface, regardless of how write(byte[] buffer) is implemented. This is the gist of the strategy pattern.

I hope I'm making sense.


Just to add to this, an interface is a useful tool for writing code for multiple platforms. A good example is a game engine of some kind. You might want to have both a DirectX and OpenGL implementation for it. In this case, you could have an interface for each class, such as an IRenderer class. You would then have a Renderer class implemented in DirectX and one implemented in OpenGL. This way you can use the same function calls and everything to the class regardless of which platform it's running on, but the underlying implementation will be different depending on which platform you are running on. I don't know if that helps or not.
User avatar
Kelly Upshall
 
Posts: 3475
Joined: Sat Oct 28, 2006 6:26 pm

Post » Tue May 17, 2011 9:59 am

Just to add to this, an interface is a useful tool for writing code for multiple platforms. A good example is a game engine of some kind. You might want to have both a DirectX and OpenGL implementation for it. In this case, you could have an interface for each class, such as an IRenderer class. You would then have a Renderer class implemented in DirectX and one implemented in OpenGL. This way you can use the same function calls and everything to the class regardless of which platform it's running on, but the underlying implementation will be different depending on which platform you are running on. I don't know if that helps or not.

Good example! Better than my vague DataWriter. :)
User avatar
Yonah
 
Posts: 3462
Joined: Thu Aug 02, 2007 4:42 am

Post » Tue May 17, 2011 11:05 am

I still don't really follow exactly why I should use them for small programs I will be writing.

Also which of these two books would you guys recommend for learning WPF (I prefer a book in this case but I do have a website bookmarked for it): http://www.amazon.com/Pro-WPF-2010-Presentation-Foundation/dp/1430272058/ref=sr_1_2?s=books&ie=UTF8&qid=1293125383&sr=1-2 or http://www.amazon.com/WPF-4-Unleashed-Adam-Nathan/dp/0672331195/ref=sr_1_1?s=books&ie=UTF8&qid=1293125383&sr=1-1.

I figure WPF is the way forward and WinForms are not that difficult to pick up so I was curious. I already checked local books stores and they do not have either of these books for me to look at in stock.
User avatar
Veronica Martinez
 
Posts: 3498
Joined: Tue Jun 20, 2006 9:43 am

Post » Tue May 17, 2011 12:56 am

I still don't really follow exactly why I should use them for small programs I will be writing.


You probably shouldn't. They're only really useful for programs that are supposed to run on different platforms and therefore need different implementations.
User avatar
Mel E
 
Posts: 3354
Joined: Mon Apr 09, 2007 11:23 pm

Post » Tue May 17, 2011 8:13 am

You probably shouldn't. They're only really useful for programs that are supposed to run on different platforms and therefore need different implementations.

I guess I missed that in the original couple of messages. All my programs are small and used only for Windows machines (since I will be using WPF from now on if I can).

I have decided to write a gradebook program using .NET 4.0, WPF, and C#. After I get some code down I will be setting up a GoogleCode project for this if anyone wants to work on it with me. To start with it is going to be a student version only so they can keep track on a per class basis. It will also generate an overall percentage for thier class grade using currently entered grades.
User avatar
Emily Martell
 
Posts: 3469
Joined: Sun Dec 03, 2006 7:41 am

Post » Tue May 17, 2011 3:13 am

They're only really useful for programs that are supposed to run on different platforms and therefore need different implementations.

While I agree that for tiny programs interfaces can sometimes be an overkill, I have to disagree with the quoted part of you post. While implementations for multiple platforms are a good example of interfaces, it's certainly not limited to that. They're useful in a huge variety of other places. For example, if your program can save the same data in several formats (e.g. an image as JPG, PNG or BMP), you'll want to have a serializer implementation for each format and have them all share a single interface. That way the client can use just one block of code to perform the saving, and switch between the implementations only during instantiation.
User avatar
Adrian Powers
 
Posts: 3368
Joined: Fri Oct 26, 2007 4:44 pm

Post » Tue May 17, 2011 2:35 pm

I know persistence is key but does anyone have suggestions on how to stay focused and motivated when getting discouraged due to difficult concepts or hurdles in programming? Lately I have been asking myself why do I keep trying when it keeps frustrating me so much, and I ordered about $120 worth of books to work through to learn the language. I think because I don't use it enough the only stuff that stuck to me is the basics and trying to get farther comfuses me, especially when I pice together programs. What I mean by this is I will find one part I want to work on and start that, but then when I get an idea for another part I do that instead.

For instance in my current program I chose to focus on getting items added and removed to a ListView rather then learning DataBindings for WPF to get controls to attach to propertiesbetter. But yet I still need to learn about custom events and XML stuff. So I have been jump all over and it get sme frustrated and then I get discouraged.

Any suggestions other than keep working at it and practice?
User avatar
Ana Torrecilla Cabeza
 
Posts: 3427
Joined: Wed Jun 28, 2006 6:15 pm

Post » Tue May 17, 2011 12:39 pm

I know persistence is key but does anyone have suggestions on how to stay focused and motivated when getting discouraged due to difficult concepts or hurdles in programming? Lately I have been asking myself why do I keep trying when it keeps frustrating me so much, and I ordered about $120 worth of books to work through to learn the language. I think because I don't use it enough the only stuff that stuck to me is the basics and trying to get farther comfuses me, especially when I pice together programs. What I mean by this is I will find one part I want to work on and start that, but then when I get an idea for another part I do that instead.

For instance in my current program I chose to focus on getting items added and removed to a ListView rather then learning DataBindings for WPF to get controls to attach to propertiesbetter. But yet I still need to learn about custom events and XML stuff. So I have been jump all over and it get sme frustrated and then I get discouraged.

Any suggestions other than keep working at it and practice?

Work on something that other people will see and/or use.
User avatar
Juanita Hernandez
 
Posts: 3269
Joined: Sat Jan 06, 2007 10:36 am

Post » Tue May 17, 2011 9:23 am

Work on something that other people will see and/or use.

That is what I was currently working on, it is supposed to be agradebook for students. Rather than use an Excel spreadsheet or paper they can input grades which will automatically calculate their totals and average for the class.
User avatar
Bones47
 
Posts: 3399
Joined: Fri Nov 09, 2007 11:15 pm

Post » Tue May 17, 2011 8:25 am

I can't help it, but sounds like it could be done as a web service of some kind. Maybe have an SQL database for all the grades and a web applet interfacing with it. Maybe have the students compare their own grades to averages, on class->school->town->nation level, but there would be no quarantee the results were valid as the students are adding the data themselves. Heh, I'm getting slightly ahead, aren't I. And then you would also get to figure out logins, privacy law and security issues. It gets complex quickly. Benefit is that there is no need to install anything as it would run inside a web browser. Starting with a C# application sounds good. Try and write some designs and plans for yourself on it. Even if it was a simple application, it's a good practice to learn. I have to admit, I'm not much of a planner myself and just rush head on on the implementation part.
User avatar
Heather beauchamp
 
Posts: 3456
Joined: Mon Aug 13, 2007 6:05 pm

Post » Tue May 17, 2011 5:04 am

I can't help it, but sounds like it could be done as a web service of some kind. Maybe have an SQL database for all the grades and a web applet interfacing with it. Maybe have the students compare their own grades to averages, on class->school->town->nation level, but there would be no quarantee the results were valid as the students are adding the data themselves. Heh, I'm getting slightly ahead, aren't I. And then you would also get to figure out logins, privacy law and security issues. It gets complex quickly. Benefit is that there is no need to install anything as it would run inside a web browser. Starting with a C# application sounds good. Try and write some designs and plans for yourself on it. Even if it was a simple application, it's a good practice to learn. I have to admit, I'm not much of a planner myself and just rush head on on the implementation part.

I was using 1 XML file per class (I figure anything more is excessive) and was going to have the class average (for student using the program) displayed at the top, but WPF was driving me mad so I temporarily shelved the project. My books came intoday so homefully by the end of the week I can get some progress made on it.
User avatar
kat no x
 
Posts: 3247
Joined: Mon Apr 16, 2007 5:39 pm

Post » Tue May 17, 2011 3:00 am

Work on something that other people will see and/or use.

I find that if I put my code on a pubic site (something like Google Code) that the code quality is higher and I am more likely to try and stick to good design principals. Irrespective of the fact that I know no one has looked at the code, the possibility that they might ensures a better quality.
User avatar
Luna Lovegood
 
Posts: 3325
Joined: Thu Sep 14, 2006 6:45 pm

Post » Tue May 17, 2011 2:11 pm

So I need to ask about a design decision from you all.

I am making a program that will (hopefully) be used on more computer than just mine. What it does is take in a long list of Windows services and will automatiically change the start type of all on the list to the specified value. I am debating between one large data file for it or multiple ones. With multiple the user can customize it to their liking and just runwhat they want rather then go through and change ones in a larger list. But with the bigger list there is the better chance of getting some weird ones that may only come up once or twice.

The program will be open source when I get it to a certain point and hopefully members here will start to use it. I am using .NET4 which is only a 30mb download for the client profile which is what is required for this, and WPF which means Windows XP service pack 2 or higher.

So far though I have an interface and am working on reading in the XML and populating a list.
User avatar
Roberto Gaeta
 
Posts: 3451
Joined: Tue Nov 06, 2007 2:23 am

Post » Tue May 17, 2011 8:56 am

ugh, I have a problem and I have no idea how to solve it. I need to create a working progress bar in my application. It's a simple backup application that copies some files for me.

                if (!System.IO.Directory.Exists(targetPath))                {                    System.IO.Directory.CreateDirectory(targetPath);                }                if (System.IO.Directory.Exists(sourcePath))                {                    foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories))                        Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath));                    foreach (string newPath in Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories))                        File.Copy(newPath, newPath.Replace(sourcePath, targetPath), true);                    MessageBox.Show("Backup complete!");                }                else                {                    MessageBox.Show("Source path does not exist!");                }


That's the backup process ^

how can I create a progress bar that somehow finds how long that ^ is going to take and reports the progress. :banghead:


EDIT: also, don't question the code :stare: I'm very tired and suffering from caffeine-withdrawal. I'll re-write it in the morning.
User avatar
Suzie Dalziel
 
Posts: 3443
Joined: Thu Jun 15, 2006 8:19 pm

Post » Mon May 16, 2011 11:12 pm

how can I create a progress bar that somehow finds how long that ^ is going to take and reports the progress. :banghead:

Well first of all you need to find out the total size of the files which will be copied.
User avatar
louise fortin
 
Posts: 3327
Joined: Wed Apr 04, 2007 4:51 am

Post » Tue May 17, 2011 5:20 am

You could use a BackgroundWorker which can report the progress then update the progress bar as nessesary. Or as stated above write a custom event to update the bar every so often.
User avatar
LuBiE LoU
 
Posts: 3391
Joined: Sun Jun 18, 2006 4:43 pm

Post » Tue May 17, 2011 5:58 am

ok, I've added this to the code:

while (backgroundWorker.IsBusy){progressBar.Increment(1);Application.DoEvents();}


Now the processbar updates constantly but it goes to 100% way before the actual progress is completed. :banghead:
User avatar
cheryl wright
 
Posts: 3382
Joined: Sat Nov 25, 2006 4:43 am

Post » Tue May 17, 2011 4:45 am

I haven't used C# in about 3 years, but I don't think that is what you want to do. You still hang the main thread as it is constantly checking if the worker thread is busy. There should be (I assume) some method to set callbacks from the worker thread to the main thread. Then when you want to update the progress bar from the worker thread, all you do is use the callback mechanism the worker thread class provides. I may be really really wrong though.

Also, all it does is increment the progress bar while the background worker is working. It will only take 100 iterations for the progress bar to go to 100%, where as it could take weeks for the background worker to complete the work. So you need to use some sort of callback from the background worker.
User avatar
Izzy Coleman
 
Posts: 3336
Joined: Tue Jun 20, 2006 3:34 am

Post » Tue May 17, 2011 1:39 pm

I found this code from a http://stackoverflow.com/questions/3873683/best-way-to-report-thread-progress

class Program{    static event EventHandler Progress;    static void Main(string[] args)    {        var thread = new Thread(            () =>            {                var local = GetEvent();                while (local == null)                {                    local = GetEvent();                }            });        thread.Start();        Thread.Sleep(1000);        Progress += (s, a) => { Console.WriteLine("Progress"); };        thread.Join();        Console.WriteLine("Stopped");        Console.ReadLine();    }    static EventHandler GetEvent()    {        //Thread.MemoryBarrier();        var local = Progress;        return local;    }}


Any chance someone could explain in a way that a C# beginner would understand? :unsure:
User avatar
My blood
 
Posts: 3455
Joined: Fri Jun 16, 2006 8:09 am

Post » Tue May 17, 2011 2:59 am

ok, I've added this to the code:

while (backgroundWorker.IsBusy){progressBar.Increment(1);Application.DoEvents();}


Now the processbar updates constantly but it goes to 100% way before the actual progress is completed. :banghead:

Thats because its incrementing on its own by one regardless of actual progress. I remember you said you were doing something with files? Suppose you are copying files. Get the size of all the files you are copying, find out how many bytes 1% is. For every 1% of bytes increment you're progress bar by 1. Set its max to 100.

Another way is to set the max on the progress bar to how many bytes total there are. Increment by how many bytes are copied.

I wouldnt use a random code snippet when dealing with threads. Background worker is a simpler solution you just need to tweak it I think. If you wanna make a new thread to update a status bar you need to do the work in that thread and update the progress bar on the main form itself. Or you can have the progress bar created by said thread and update it that way.

Even simpler would be to just update the progress bar in the loop you are doing the work. No bgworker or threads involved.
User avatar
jesse villaneda
 
Posts: 3359
Joined: Wed Aug 08, 2007 1:37 pm

Post » Tue May 17, 2011 1:24 am

Even simpler would be to just update the progress bar in the loop you are doing the work. No bgworker or threads involved.

Does that work? As said, I haven't used C# in a long time. However all GUI libraries I have used, the library uses the main thread for redrawing the UI so if you are doing work in the main thread you hang the UI until that work is finished.

Hence the need for some sort of threading.
User avatar
Kristina Campbell
 
Posts: 3512
Joined: Sun Oct 15, 2006 7:08 am

Post » Tue May 17, 2011 12:33 pm

If updating the progress bar is part of the work its no problem right :) In the case of copying files you might need to update the progress bar between a variable amount of bytes. Not as accurate but you could just update between files completely. This would be easiest.

psudeo code with imaginary functions.
While  (!done) {     progressbarmax = numberoffiles;    MyFunCopy(filenumber);    progressbar++;}


I've only used a progress bar once really, the way I did it was I updated it every second using a timer (timers work in separate threads like background worker).
User avatar
Sammygirl
 
Posts: 3378
Joined: Fri Jun 16, 2006 6:15 pm

Post » Tue May 17, 2011 3:05 pm

Does that work? As said, I haven't used C# in a long time. However all GUI libraries I have used, the library uses the main thread for redrawing the UI so if you are doing work in the main thread you hang the UI until that work is finished.

Hence the need for some sort of threading.

It would if you had number values for your loop but in a foreach it won't because youw ould have to estaimte the time it will take and lal that other. But you are right, the second thread cannot access the UI from itself. You have to setup a helper method to me able to do this, and that requires a delegate and event for each control. I did it once before and even with comments I am not 100% sure how I managed to do it.

I would say just try to use the ReportProgress method of the backgroundWorker being used. Of course the BackgroundWorker has to be report its progres, and you have to somehow tie the progress bar into the ProgressChanged event.

I tried to experiment with this but was having difficulties earlier, but am going to try it again.
User avatar
Brandon Wilson
 
Posts: 3487
Joined: Sat Oct 13, 2007 1:31 am

Post » Tue May 17, 2011 12:37 pm


Here's a quick working example to give you the idea. Create a form with a button "button", a progress bar "progress" and a background worker "worker", then set up the events as follows:

private void button_Click(object sender, EventArgs e) {  var files = Directory.GetFiles("C:/", "*.*");  progress.Minimum = 0;  progress.Maximum = 100;  progress.Value = http://forums.bethsoft.com/index.php?/topic/1123394-unofficial-programming-thread-ii/0;  button.Enabled = false;  worker.WorkerReportsProgress = true;  worker.RunWorkerAsync(files);}private void worker_DoWork(object sender, DoWorkEventArgs e) {  var files = (string[])e.Argument;  for (int i=0; i

Clicking the button will disable it and start the worker. The worker will update the progress bar on each iteration of its copying loop. Once done, it will reenable the button.
User avatar
Shaylee Shaw
 
Posts: 3457
Joined: Wed Feb 21, 2007 8:55 pm

Post » Tue May 17, 2011 12:29 am

Here's a quick working example to give you the idea. Create a form with a button "button", a progress bar "progress" and a background worker "worker", then set up the events as follows:

private void button_Click(object sender, EventArgs e) {  var files = Directory.GetFiles("C:/", "*.*");  progress.Minimum = 0;  progress.Maximum = 100;  progress.Value = http://forums.bethsoft.com/index.php?/topic/1123394-unofficial-programming-thread-ii/0;  button.Enabled = false;  worker.WorkerReportsProgress = true;  worker.RunWorkerAsync(files);}private void worker_DoWork(object sender, DoWorkEventArgs e) {  var files = (string[])e.Argument;  for (int i=0; i

Clicking the button will disable it and start the worker. The worker will update the progress bar on each iteration of its copying loop. Once done, it will reenable the button.

nifty, background worker seems like such a pain in the butt. I just create a new thread and do what I gotta do. If it works it works though hu.
User avatar
Ezekiel Macallister
 
Posts: 3493
Joined: Fri Jun 22, 2007 12:08 pm

PreviousNext

Return to Othor Games