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.
 
  • Locked thread
Begby
Apr 7, 2005

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

uXs posted:

So when I generate the code, it warns me to pick one. I don't want to take one or the other as default because I want to be forced to manually choose.

Instead of doing it like this, whey don't you create a loader, than inject the loader you want into the base class.

code:

interface ITableLoader
{
   IList<mystuff> LoadData();
}


public abstract class BaseController<T>()
{
 protected ITableLoader loader;
 public BaseController(ITableLoader loader)
 {
   this.loader = loader;
 }

}
Now you are forced to choose one of the loader types and can shelve this. A side effect is helping with separation of concerns and making it so you can add a new loading type down the road without having to create more abstract classes.

Adbot
ADBOT LOVES YOU

Prefect Six
Mar 27, 2009

Munkeymon posted:

It's possible to manipulate Excel spreadsheets from C#, but that's different from a macro and, in my limited experience writing (or trying to write) Excel macros, it's actually easier to use C# than deal with the awful macro editing environment in Excel. See http://stackoverflow.com/questions/15828/reading-excel-files-from-c-sharp and http://support.microsoft.com/kb/302084 for more on that and I'm sure other people in this thread have more advice on the subject.

Depending on what you're actually doing, it might be easier to pull data into C# to process it and spit out a CSV or something than write an Excel macro to do it.


Ithaqua posted:

VB .NET and C# (and F#!) run on the CLR, so you can do all of the same things in both. The syntax is different, and there are a few minor things that one can do that the other can't (although the gap has been pretty well closed at this point), so go with what you prefer. If you're developing in Visual Studio, you're using .NET.


Thanks guys, this is great info! I think I'm going to go with C#. Now to find some good beginners books/tutorials/resources/etc.

mobby_6kl
Aug 9, 2009

by Fluffdaddy

Dromio posted:

I found itextsharp to be very easy to use. I'd use any standard graphing library to generate an image of the graph, then put that into the PDF that itextsharp generates.

I spent some time with itextsharp today. It is, indeed, about as simple to use as I could've hoped:
code:
var doc = new Document();
PdfWriter.GetInstance(doc, new FileStream("test.pdf", FileMode.Create));
doc.Open();
doc.Add(new Paragraph("Hello world!"));
doc.Close()
However, setting everything up in code this way would be ridiculous and it seems like itextsharp does have some sort of XML-based templating support... except it doesn't? The documentation is atrocious - the link literally just tries to sell you a book (which is Java focused) or consulting. From various forum posts it appears that there was something in one version, then it was removed, then there was something else but it's not fully supported.

Just to make this clear - I'm not talking about pdf forms, but rather having the static layout and content defined separately from the code (perhaps even in XML), loading that into memory, and then dynamically adding sections with charts and descriptions and other crap as necessary, much as one wold do with an HTML template. Does something like this exist and I just suck at searching, or should I roll my own?

Ithaqua posted:

I've used PDFSharp and Migradoc for that kind of thing. Worked pretty well.

PDFSharp doesn't seem to have anything like this either, or am I missing something? Not that it's not a good suggestion, but I'd just like to avoid reinventing templating systems pointlessly.

wither posted:

I'm a huge fan of TeX and you can definitely do it maybe with some additional packages (I forget how but I've seen pretty .eps charts outputted, grad students do it all the time). If you want to stick with generating graphs use Excel's interop and itextsharp.

http://csharp.net-informations.com/excel/csharp-excel-chart.htm might be helpful. It's been a few years since I've done any of this, but last I remember there were some serious performance issues with large datasets. Hopefully this has been fixed in recent Office/.NET Framework issues but just a heads up.

Sadly I didn't manage to find any TeX libraries either. I'm sure I could use some other templating system to handle TeX template generation and then run them through complication but it seems like distributing and maintaining this whole thing would be a pain in the rear end. Which is a shame, because this would produce ridiculously nice looking reports.

I have some experience with Excel interop but never had to do any graphs, thanks for the link. As much as I am not a fan of this, gluing the office apps together just might be the least painful option in this situation.

PDP-1 posted:

The chart class can do all that you need and much, much more. In fact my only complaint about the class is that it can do so many things that you spend a ton of time digging around in the hundreds of possible settings looking for what you want.

e: For the PDF thing, you can also install a printer emulator like PDF Creator and then just have your program print to that.
I dunno why I didn't consider just drawing charts myself with GDI or whatever as this is what I (easily) did in a small C app recently. But with this native chart class that would be pointless, it really is pretty awesome. I set everything up as needed visually and then just tracked down the relevant fields to do that programatically. Easy-peasy and looks good.

Dromio
Oct 16, 2002
Sleeper

mobby_6kl posted:

I spent some time with itextsharp today. It is, indeed, about as simple to use as I could've hoped:
code:
var doc = new Document();
PdfWriter.GetInstance(doc, new FileStream("test.pdf", FileMode.Create));
doc.Open();
doc.Add(new Paragraph("Hello world!"));
doc.Close()
However, setting everything up in code this way would be ridiculous and it seems like itextsharp does have some sort of XML-based templating support... except it doesn't?

We have a pdf "template" with form fields, then use itextsharp's PdfStamper class to fill out the fields. Something like this:

code:
var pdfReader = new PdfReader(TemplateFileName);
using (var stream = new MemoryStream()){
  var pdfStamper = new PdfStamper(pdfReader, stream);
  var formFields = pdfStamper.AcroFields;
  formFields.SetField("thefieldidentifier", "The text to insert");
}

Even if you're not really filling out a form, you might be able to do something like this to make the output you want. I do see several blog posts about doing this with images as well.

Dromio fucked around with this message at 21:00 on Aug 23, 2012

putteand
Jun 9, 2001
I'm having some trouble with the code coverage functionality in VS2012. My SO question isn't getting much love (http://stackoverflow.com/questions/12087560/vs2012-code-coverage-only-analyzes-the-test-dll), so I thought I'd ask here.

Let me paste, for convenience:

quote:

I'm trying to get code coverage working in VS2012 premium, and I'm having some trouble.

I have a C# solution with a few different projects, but most notably a Kernel.dll to be tested and a Kernel.Tests.dll that tests using NUnit and Rhino Mocks.

Using the NUnit Test Adapter (Beta 2), getting the tests into the test explorer works fine, as does running them. But when it comes to code coverage, I only get analysis from the test dll itself, not the code that is tested. This is when I do not use a .runsettings file.

I have also tried using a .runsettings file (like here: http://msdn.microsoft.com/en-us/library/jj159530.aspx) with this specification:

<Include>
<ModulePath>.*\.dll$</ModulePath>
</Include>

<Exclude>
<ModulePath>.*\.Tests\.dll$</ModulePath>
</Exclude>

but this just gives me an empty result, because now the test dll doesn't get included either.

The problem seems to be that it doesn't find the other parts of the solution, but I'm not sure where exactly it looks, or what I need to set up in order for it to be found.

Has anyone run into the same issue? Any ideas on how to fix it?


So, any ideas?

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

putteand posted:

I'm having some trouble with the code coverage functionality in VS2012. My SO question isn't getting much love (http://stackoverflow.com/questions/12087560/vs2012-code-coverage-only-analyzes-the-test-dll), so I thought I'd ask here.

Let me paste, for convenience:


So, any ideas?

I gave you an upvote, no idea though :(

uXs
May 3, 2005

Mark it zero!

putteand posted:

I'm having some trouble with the code coverage functionality in VS2012. My SO question isn't getting much love (http://stackoverflow.com/questions/12087560/vs2012-code-coverage-only-analyzes-the-test-dll), so I thought I'd ask here.

Let me paste, for convenience:


So, any ideas?

Have you looked at NCrunch? Haven't tested it with VS2012 yet but it should work. It's also completely awesome and everybody should use it.

uXs
May 3, 2005

Mark it zero!

Ithaqua posted:

Am I missing something or do you just really need to use a protected constructor?

You're probably missing something.

Begby posted:

Instead of doing it like this, whey don't you create a loader, than inject the loader you want into the base class.

code:

interface ITableLoader
{
   IList<mystuff> LoadData();
}


public abstract class BaseController<T>()
{
 protected ITableLoader loader;
 public BaseController(ITableLoader loader)
 {
   this.loader = loader;
 }

}
Now you are forced to choose one of the loader types and can shelve this. A side effect is helping with separation of concerns and making it so you can add a new loading type down the road without having to create more abstract classes.

Hmh, interesting. That does look more clean.

Having to add a new loading type seems unlikely at this point, the choice I have to make is pretty binary. Basically, the program has some kind of history. It has to do with semi-annual budgets, so twice each year I have to freeze the data and start a new budgetting cycle.

Anyway, the tables that have 'historic' data always need to be filtered by budget cycle, so that's type 1. And type 2 is data where I don't have to do that.

So you see, either I have to filter or I don't. Maybe I'll need something else at some point, but right now I don't see it.

The design is a lot more clean than it used to be though, I used to just make a backup of the database when a new budgetting cycle had to start. :v: (In my defense, we only had like 3 months to create this and we really didn't have the time to add history to its features. Backup was a dirty, dirty system but it worked rather well.)

Fiend
Dec 2, 2001

epalm posted:

I want to write testable code, but I'm running into situations where it's hard to do so. I have a private method I want to test. That in itself might be a red flag, but here's the simplified situation:

C# code:
public class GpsPollingService
{
    public event EventHandler<GpsEventArgs> UpdateReceived;
    
    public void Poll()
    {
        // fetch xml from some service
        
        string xml = GetXml("http://www.blah.com");
        
        // parse xml
        
        GpsEventArgs args = ParseXml(xml);
        
        // fire UpdateReceived event
        
        UpdateReceived(this, args);
    }
    
    private string GetXml(string url)
    {
        using (var client = new WebClient())
        {
            return "some xml";
        }
    }
    
    private GpsEventArgs ParseXml(string xml)
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xml);
        
        // ...gently caress xml...
        
        return new GpsEventArgs(...);
    }
}
I want to write unit tests for the ParseXml method, but it is (and should be) private.

Is this where mocking comes in?

Can you make it internal and use Friendly Assemblies?

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Fiend posted:

Can you make it internal and use Friendly Assemblies?

You don't want to write unit tests for your private/internal methods -- your private methods are tested through the public methods that use them. If your Widget class has a public GetWidgets method, all you care about is that it's returning the widgets you're expecting. If getting widgets requires parsing some XML, so be it. That code will be exercised when you're testing all of the permutations of widget-getting.

Fiend
Dec 2, 2001

Ithaqua posted:

You don't want to write unit tests for your private/internal methods -- your private methods are tested through the public methods that use them. If your Widget class has a public GetWidgets method, all you care about is that it's returning the widgets you're expecting. If getting widgets requires parsing some XML, so be it. That code will be exercised when you're testing all of the permutations of widget-getting.

Yes but what about atomicity and having a fuckload of tests?

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Fiend posted:

Yes but what about atomicity and having a fuckload of tests?

What about them?

ljw1004
Jan 18, 2005

rum

Prefect Six posted:

Just to prove my ignorance, I didn't realize there was a difference between vb.net and vb. However, I've been using 2010 express IDE and a beginners book on both C# 2010 and VB 2010 to play around with and see what I like, so I assume I'm using the .NET versions of both.
Is it possible to make macros for excel in C# or would VB be the best choice? Is there much of a difference between the two?
Finally, does anyone have any opinions on resources or a beginners book or two I should look into for either language?

Just thinking outside the box about other things you might be interested in, since you mention Excel...

Microsoft is in the process of adding a new way to program Excel through Javascript. You can read more about it here, along with instructions on how to get started.
http://blogs.msdn.com/b/jasonz/archive/2012/07/17/introducing-napa-office-365-development-tools.aspx


There's another Microsoft .NET language called "F#" that's making inroads into the financial world. It's used by the so-called "rocket scientists", the quants, in financial firms e.g. to do their trading algorithms. The reason is that F# has syntax that's understandable both to the financial whizz-kids, and also to the programmers, so they all can just use a single common language (rather than having the finance experts write in Matlab, and then have coders translate into C++, with danger of bugs in the translation). Another reason is that F# has a tighter tight system, e.g. it catches unit-conversion-bugs in your code so you don't mix USD and EUR. I know F#, and so get periodic emails from places like Credit Suisse and Goldman Sachs asking me to interview with them.

Microsoft have also been working on "Azure Data Marketplace". Azure is the name for their datacenters that companies can rent space on. The Data Marketplace is a sort of clearinghouse where people who have their own huge datasets can host them on Azure and sell access to them. There are also Excel tools to download and visualize and work with them.


Anyway, your question was specifically about Excel. For doing stuff within Excel, the choice is either VBA (an offshoot of VB6, the predecessor to VB.Net) or Excel formulas, or the new javascript stuff I mentioned above.

If you want to write a plugin for Excel, you instead use something called "VSTO" -- Visual Studio Tools For Office -- in any of the .NET languages, e.g. VB.Net (usually called VB), C#, F#.

ljw1004 fucked around with this message at 18:04 on Aug 24, 2012

Tres Burritos
Sep 3, 2009

ljw1004 posted:

I know F#, and so get periodic emails from places like Credit Suisse and Goldman Sachs asking me to interview with them.

Oh no poo poo? I keep telling myself to pick up and read this drat F# book that I bought, this is great motivation.

uXs
May 3, 2005

Mark it zero!

Tres Burritos posted:

Oh no poo poo? I keep telling myself to pick up and read this drat F# book that I bought, this is great motivation.

Interesting. Maybe I should finish my haskell book and then have a look at F#.

Rooster Brooster
Mar 30, 2001

Maybe it doesn't really matter anymore.
Speaking of F#... I've been studying up on functional programming, with this book. I'm learning some F#, but also have been trying to "functional"-ize my C# by making immutable classes for my model and view-models. One thing it hasn't covered is best practices for mutating state. It shows the how, but not the where and why. Keeping state changes out of object methods obviously makes them much easier to test, and much more parallel friendly, but at some point I have to actually change something, right? What are the best practices?

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Rooster Brooster posted:

Speaking of F#... I've been studying up on functional programming, with this book. I'm learning some F#, but also have been trying to "functional"-ize my C# by making immutable classes for my model and view-models. One thing it hasn't covered is best practices for mutating state. It shows the how, but not the where and why. Keeping state changes out of object methods obviously makes them much easier to test, and much more parallel friendly, but at some point I have to actually change something, right? What are the best practices?

(Take this with a huge grain of salt, I'm a functional language apprentice myself).

I thought that was one of the big selling points of functional languages: Don't mutate things. Take X, do stuff to it, return Y. X is always X once you create it. Y will always be Y once you create it.

raminasi
Jan 25, 2005

a last drink with no ice

Rooster Brooster posted:

Speaking of F#... I've been studying up on functional programming, with this book. I'm learning some F#, but also have been trying to "functional"-ize my C# by making immutable classes for my model and view-models. One thing it hasn't covered is best practices for mutating state. It shows the how, but not the where and why. Keeping state changes out of object methods obviously makes them much easier to test, and much more parallel friendly, but at some point I have to actually change something, right? What are the best practices?

Something like a view model is literally nothing more than a big state. I wouldn't worry much about trying to cram that particular square peg into the functional/immutable round hole. I know that when I work in C# I make my fields readonly until I realize I need to mutate them, at which point I just drop the readonly and don't worry about it.

I've found that when just putting an algorithm together in F#, the issue comes up surprisingly rarely, and when it does, the solution is pretty straightforward. (With F# I think the rule of thumb is "use mutable unless the compiler tells you you have to use a reference cell", but I could be wrong.)

I love F# :3:

Rooster Brooster
Mar 30, 2001

Maybe it doesn't really matter anymore.

Ithaqua posted:

(Take this with a huge grain of salt, I'm a functional language apprentice myself).

I thought that was one of the big selling points of functional languages: Don't mutate things. Take X, do stuff to it, return Y. X is always X once you create it. Y will always be Y once you create it.

Yeah, I guess I get stuck when I'm dealing with UI <-> Bunch o' Stuff <-> Data Source. If a user sets a value in the UI, and that changes a model object, and that model object is referenced by other objects, then if it's all immutable I have to regenerate basically the whole object graph, right? That seems like a lot of work if a user wants to change, say, an email address in a field.

GrumpyDoctor posted:

Something like a view model is literally nothing more than a big state. I wouldn't worry much about trying to cram that particular square peg into the functional/immutable round hole. I know that when I work in C# I make my fields readonly until I realize I need to mutate them, at which point I just drop the readonly and don't worry about it.

You could totally be right here, I may be trying to shoehorn functional programming techniques in for their own sake. I'm hoping to get a better understanding of when they're appropriate and when I should stick to the regular old OO-style.

I guess I feel like there is something I'm not getting. Maybe I need to back up and work on a smaller example in F# to get things to click.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Rooster Brooster posted:

Yeah, I guess I get stuck when I'm dealing with UI <-> Bunch o' Stuff <-> Data Source. If a user sets a value in the UI, and that changes a model object, and that model object is referenced by other objects, then if it's all immutable I have to regenerate basically the whole object graph, right? That seems like a lot of work if a user wants to change, say, an email address in a field.


You could totally be right here, I may be trying to shoehorn functional programming techniques in for their own sake. I'm hoping to get a better understanding of when they're appropriate and when I should stick to the regular old OO-style.

I guess I feel like there is something I'm not getting. Maybe I need to back up and work on a smaller example in F# to get things to click.

Yeah, you're definitely shoehorning functional concepts into the object-oriented world. Models are supposed to be mutable.

Static methods are a perfect example of when immutability makes sense. You should never have a static method that takes an object and modifies its state. Same with structs. A struct is perfect if you have a bunch of related value types that you want to pass as a parameter, or return from a method.

ninjeff
Jan 19, 2004

Rooster Brooster posted:

Keeping state changes out of object methods obviously makes them much easier to test, and much more parallel friendly, but at some point I have to actually change something, right? What are the best practices?

Here's a discipline that's been working for me lately, and that I think makes sense as a kind of OOP-FP fusion:

I like to clearly distinguish 'objects' from 'data structures', even though both are written as objects in C# and VB. Every class should be one or the other, and never both.

Objects are defined by their interface and its contract; they don't expose their state except as it relates to calling their interface (e.g. IList<T> exposes its Count property so that you know which indices you can refer to). Callers should treat an object as a black box defined by its methods (and properties, indexers, and events) just like the Java folks have been saying for a while. Objects should not have any public fields, as that would be exposing implementation details.

Bringing an object into a function is an admission that something that function does can have lasting effects on other callers of that object, and that the object's properties could change at any time.

Data structures should not have (most) methods, properties, indexers, or events. They should have some public (and readonly as the default) fields and a constructor that sets them. Some methods you should put on data structures are Equals and GetHashCode. Data structures work well as the return values of methods or as messages to be passed between objects.

Why readonly fields and not properties? A readonly property only prevents the caller from changing the property's value, while a readonly field is a promise that the field's value will never change. When moving data between services or threads, that kind of guarantee is more useful.

This discipline might not be for everyone - it's a divergence from the 'everything is an object' notions of the 90s - but it's really helped me to reason about where mutable state lies and how it might change.

Prefect Six
Mar 27, 2009

So no preferences on what self-help C# book to get? I'm also running through https://www.csharp-station.com.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Prefect Six posted:

So no preferences on what self-help C# book to get? I'm also running through https://www.csharp-station.com.

It looks okay-ish to learn the basics. I only noticed one major error, which isn't going to be really important to you as a beginner. In chapter 7, the author talks about destructors. C# does not have destructors, it has finalizers. There is a subtle but important difference, which again is irrelevant to a beginner. He should probably mention that unless you know exactly why you need one, don't put one in your class, though.

I really wish more tutorials had little sections on best practices, too. Just little tidbits like "this isn't important for learning, but keep in mind...". Like his chapter on exception handling could easily mention Pokemon Exception Handling and why it's bad (it even has a catchy, memorable name!).

[edit]
Admittedly, the destructor/finalizer thing can be confusing since the Microsoft language spec calls them destructors, but the ECMA spec calls them finalizers. The terms get used interchangably. :argh:

New Yorp New Yorp fucked around with this message at 06:02 on Aug 25, 2012

raminasi
Jan 25, 2005

a last drink with no ice
The best is C++/CLI, which has them both :v:

Prefect Six
Mar 27, 2009

Ithaqua posted:

I really wish more tutorials had little sections on best practices, too. Just little tidbits like "this isn't important for learning, but keep in mind...". Like his chapter on exception handling could easily mention Pokemon Exception Handling and why it's bad (it even has a catchy, memorable name!).

This is something I'm a tad bit worried about. Not many of the tutorials online I've found talk about best practices a whole lot. I found one video series that talks a little bit about refactoring, but hasn't gone in depth with it yet.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Prefect Six posted:

This is something I'm a tad bit worried about. Not many of the tutorials online I've found talk about best practices a whole lot. I found one video series that talks a little bit about refactoring, but hasn't gone in depth with it yet.

Part of the problem is that best practices tend vary from person to person. You'll pick them up over time.

Do you have any projects that you're working on? That tutorial you linked looks like it's teaching you the purpose and syntax of things, but it doesn't really demonstrate how to use them to accomplish goals.

Here's something easy you can do if you haven't already. It's called "FizzBuzz" and it's a common interview question, because it's relatively easy to do and if an experienced developer can't poo poo out a solution in a few minutes, he's not qualified to write software.

- Print the numbers from 1 to 100.
- If a number is divisible by 3, print "Fizz"
- If a number is divisible by 5, print "Buzz"
- If a number is divisible by both 3 and 5, print "FizzBuzz"

Here's another one:
Write a method that takes a string returns the reverse of that string. Ex: "cat" -> "tac"

Feel free to come back with questions or if you want a code review when you're done :)

Prefect Six
Mar 27, 2009

Ithaqua posted:

Part of the problem is that best practices tend vary from person to person. You'll pick them up over time.

Do you have any projects that you're working on? That tutorial you linked looks like it's teaching you the purpose and syntax of things, but it doesn't really demonstrate how to use them to accomplish goals.

Here's something easy you can do if you haven't already. It's called "FizzBuzz" and it's a common interview question, because it's relatively easy to do and if an experienced developer can't poo poo out a solution in a few minutes, he's not qualified to write software.

- Print the numbers from 1 to 100.
- If a number is divisible by 3, print "Fizz"
- If a number is divisible by 5, print "Buzz"
- If a number is divisible by both 3 and 5, print "FizzBuzz"

Here's another one:
Write a method that takes a string returns the reverse of that string. Ex: "cat" -> "tac"

Feel free to come back with questions or if you want a code review when you're done :)

No specific projects, I'm just trying to learn the language right now.

Ugh, I assume all that can be done with int, string and for loops? I'm only to lesson 4 on that tutorial! I appreciate the challenge though, it will give me something to work toward!

I'm really not doing this to get a job coding or to change positions, I simply think having a working knowledge of a language like C# will allow me to develop proprietary programs to make what I do more efficient (which is design electric power substations).

A lot of what I want to do will involve taking stuff from excel or a database and manipulating it towards some end goal. I think, maybe.

Finally, I just want to learn a language. I've written so many hello world programs in so many different languages, but never followed completely through.

Soooo that's where I'm coming from I guess? That probably wasn't helpful at all.

e: Challenge one complete!

code:
namespace IthaquaChallenge1
{
    class FizzBuzz
    {
        static void Main(string[] args)
        {
            /*Print numbers 1-100. If a number is divisible by 3, print
             * "Fizz". If it is divisible by 5, print "Buzz". If divisible
             * by both, print "FizzBuzz".*/
            
            // For loop to count from 1 to 100.
            for (int i = 1; i < 101; i++)
            {
                // Output integer "i".
                Console.Write("{0} ", i);

                // If statement to check for "Fizz".
                if (i % 3 == 0)
                    Console.Write("Fizz");

                // If statement to check for "Buzz".
                if (i % 5 == 0)
                    Console.Write("Buzz");

                // New line.
                Console.WriteLine();
            }
            // Keep console open.
            Console.ReadLine();
        }
    }
}

Prefect Six fucked around with this message at 21:51 on Aug 25, 2012

raminasi
Jan 25, 2005

a last drink with no ice
A proper FizzBuzz doesn't print out the number if it's a multiple of 3 or 5. :colbert: That's what makes it "hard."

Prefect Six
Mar 27, 2009

GrumpyDoctor posted:

A proper FizzBuzz doesn't print out the number if it's a multiple of 3 or 5. :colbert: That's what makes it "hard."

Oooohhh. Ok, back to the drawing board then.

code:
namespace IthaquaChallenge1
{
    class FizzBuzz
    {
        static void Main(string[] args)
        {
            /*Print numbers 1-100. If a number is divisible by 3, print
             * "Fizz". If it is divisible by 5, print "Buzz". If divisible
             * by both, print "FizzBuzz".*/
            
            // Initialize ints for FizzBuzz test.
            int intFizz;
            int intBuzz;

            // For loop to count from 1 to 100.
            for (int i = 1; i < 101; i++)
            {
                intFizz = i % 3;
                intBuzz = i % 5;

                // If statement to check for "Fizz".
                if (i % 3 == 0)
                    Console.Write("Fizz");

                // If statement to check for "Buzz".
                if (i % 5 == 0)
                    Console.Write("Buzz");

                // If statement to print number if "FizzBuzz" test fail.
                if (intFizz != 0 && intBuzz != 0)              
                Console.Write("{0} ", i);

                // New line.
                Console.WriteLine();
            }
            // Keep console open.
            Console.ReadLine();
        }
    }
}
Better?

I'm going to have to get a pointer on the cat -> tac thing, unless you just want me to start plugging away at google. Really don't have the slightest clue where to begin.

Prefect Six fucked around with this message at 03:57 on Aug 26, 2012

SirViver
Oct 22, 2008

GrumpyDoctor posted:

A proper FizzBuzz doesn't print out the number if it's a multiple of 3 or 5. :colbert: That's what makes it "hard."
Really? Where in the specs does it say that? :colbert:

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

SirViver posted:

Really? Where in the specs does it say that? :colbert:

You are correct! I am a bad spec-writer!

Prefect Six posted:

Oooohhh. Ok, back to the drawing board then.

code

Better?

I'm going to have to get a pointer on the cat -> tac thing, unless you just want me to start plugging away at google. Really don't have the slightest clue where to begin.

Hey, it's a working solution! Excellent.

A few points:
1) It's considered bad practice to put the type of the variable in the variable's name. Variable names should be as long as necessary to be descriptive.
2) Your intFizz and intBuzz variables can be declared in the scope of the for loop. The way you did it, it was reusing the same variable over and over. It's not a big deal in a small program, but it might be in a larger one.
3) You do int intFizz = i % 3;, but then you also do if (i % 3 == 0). You're doing the same comparison twice unnecessarily!

For the string reversal problem, try breaking it down into the smallest possible steps. You have a string. You can access the individual characters of a string by index, e.g. string sampleString = "cat"; char firstCharacter = sampleString[0];

With that in mind, how would you go about reversing a word if you had a pen and paper in front of you and weren't telling the computer how to do it?

Prefect Six
Mar 27, 2009

Ithaqua posted:

A few points:
1) It's considered bad practice to put the type of the variable in the variable's name. Variable names should be as long as necessary to be descriptive.

Huh, for some reason I thought having the variable type in a shortened form at the front of the variable was a good idea. Int is just the same shorting as the actual type. So like for string you'd do strString or fltFloat. Is this bad form still? How would you recommend naming variables?

quote:

2) Your intFizz and intBuzz variables can be declared in the scope of the for loop. The way you did it, it was reusing the same variable over and over. It's not a big deal in a small program, but it might be in a larger one.

Not sure I fully understand what you mean "reusing the same variable over and over". Wouldn't you be using the same intFizz and intBuzz if it were inside the for loop? How is it any different?

quote:

3) You do int intFizz = i % 3;, but then you also do if (i % 3 == 0). You're doing the same comparison twice unnecessarily!

That's a good point. I went back and tacked on that extra stuff to not print the number if it Fizz'd or Buzz'd, but I should have seen I had already done those tests and replaced the boolean test with the variables.

quote:

For the string reversal problem, try breaking it down into the smallest possible steps. You have a string. You can access the individual characters of a string by index, e.g. string sampleString = "cat"; char firstCharacter = sampleString[0];

Do you have any tips on comments? Am I headed in the right direction of "oh god, comment everything"?

I see where you're going with the string, although I'm not sure how to figure out how many characters are in a given string. I'm sure there's a way. I'll do a little digging and get you some code.

Thanks for all the pointers!

Prefect Six fucked around with this message at 18:24 on Aug 26, 2012

PDP-1
Oct 12, 2004

It's a beautiful day in the neighborhood.

Prefect Six posted:

Do you have any tips on comments? Am I headed in the right direction of "oh god, comment everything"?

Comment format can be a matter of personal taste to some degree, but I'd suggest that you're using way too many. It's not necessary to add comments to code that would be immediately understandable to a competent programmer in uncommented form. For example,
C# code:
            // Initialize ints for FizzBuzz test.
            int intFizz;
            int intBuzz;

            // For loop to count from 1 to 100.
            for (int i = 1; i < 101; i++)
these comments are pretty useless since any C# programmer would immediately understand the uncommented code.

Adding too many comments can actually make the code 'noisy' visually and harder to read, so it's best to use them only on sections of code that do something that is complicated or unusual enough to not be instantly understandable.

You can also use comments to organize a large block of code into sub-sections, e.g. if you have a large method that does A, B, and C you could create 'paragraphs' of code that begin with // doing A here, etc. (But, if your method does A, B, and C you should think about whether or not to break those out into different methods but that's a discussion for another time)

Milotic
Mar 4, 2009

9CL apologist
Slippery Tilde

Prefect Six posted:

Huh, for some reason I thought having the variable type in a shortened form at the front of the variable was a good idea. Int is just the same shorting as the actual type. So like for string you'd do strString or fltFloat. Is this bad form still? How would you recommend naming variables?

That style of naming is known as hungarian notation. It's mostly a holdover from languages which aren't as strongly typed as C# (so you could compile a program which let you treat strings as non-strings etc. and then have unexpected bugs and crashes at runtime), and also from the days where IDEs weren't as sophisticated at showing type information when programming.

Arguably in C# the only good place to still use hungarian notation is when doing UI programming (e.g. cmbSomeComboBox, btnSomeButton, chkSomeCheckBox) for various reasons which I won't go into.

Name your variables so that they make sense to people looking at the code. Any decent IDE will do variable completion for you when typing (and Visual Studio supports some quite clever completion tricks), so you can give them fairly long names.

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Prefect Six posted:

Huh, for some reason I thought having the variable type in a shortened form at the front of the variable was a good idea. Int is just the same shorting as the actual type. So like for string you'd do strString or fltFloat. Is this bad form still? How would you recommend naming variables?

It's widely considered to be a bad practice these days. The compiler knows what time things are, and the IDE can tell you all about it. It's just noise. Plus, what if you have to change the type of something? You end up withdouble iOhShit. Like I said, variables should be named as descriptively as possible.

quote:

Not sure I fully understand what you mean "reusing the same variable over and over". Wouldn't you be using the same intFizz and intBuzz if it were inside the for loop? How is it any different?

Nope! Within a loop, any variables created are in the scope of that loop and won't be available outside of it. For example, this code wouldn't compile:
code:
for (int i = 0; i < 100; i++) 
{
	int squared = i*i;
}
Console.WriteLine(squared);
The variable squared is created for every iteration of the loop.

Now, on the other hand, what if I did this?
code:
int squared = 0;
for (int i = 0; i < 100; i++) 
{
	squared = i*i;
}
Console.WriteLine(squared);
It would print 9801. But every other iteration of the loop would be "lost".

In the case of your FizzBuzz project, you didn't need those variables outside of your loop, so declaring them out of the proper scope leaves a potential source of confusion.

quote:

Do you have any tips on comments? Am I headed in the right direction of "oh god, comment everything"?

This is a question that's endlessly debated. Comment as much as you feel is right. I strongly believe that well-written code should be largely self-documenting.

quote:

I see where you're going with the string, although I'm not sure how to figure out how many characters are in a given string. I'm sure there's a way. I'll do a little digging and get you some code.

Thanks for all the pointers!

code:
string word = "cat";
int wordLength = word.Length; // 3
Don't be afraid of typing a variable name followed by a dot in Visual Studio and looking through the properties and methods that come up. MSDN is also useful as a resource for knowing what's available.

Prefect Six
Mar 27, 2009

Thanks for all the replies, great information!

Ok so I came up with this for the string challenge:
code:
    class Program
    {
        static void Main(string[] args)
        {
            string word;
                        
            Console.WriteLine("Enter your word: ");
            word = Console.ReadLine();

            for (int wordLength = word.Length; wordLength > 0; wordLength--)
            {
                int wordIndex = wordLength - 1;
                char indexCharacter = word[wordIndex];
                Console.Write("{0}", indexCharacter);           
            }

            Console.WriteLine();
            Console.ReadLine();
        }
    }
I don't have the faintest clue how to store and concatenate the individual character back into a string though.

uXs
May 3, 2005

Mark it zero!

Ithaqua posted:

You are correct! I am a bad spec-writer!

Coding from bad specs is an essential skill he needs to learn anyway :v:

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Prefect Six posted:

Thanks for all the replies, great information!

Ok so I came up with this for the string challenge:

I don't have the faintest clue how to store and concatenate the individual character back into a string though.

I said a method! But that's okay.

For string concatenation, you have two options:

1)
code:
string s = string.Empty;
s += 'a'; //s = "a"
s += 'b'; //s = "ab"
s += 'c'; //s = "abc"
Console.WriteLine(s);
This is functional but not optimal due to the way that strings are handled by the .NET framework. The more generally accepted way to build strings is to use a StringBuilder

2)
code:
var myNewString = new StringBuilder();
myNewString.Append('a');
myNewString.Append('b');
myNewString.Append('c');
Console.WriteLine(myNewString.ToString());

Prefect Six
Mar 27, 2009

I don't know what a method is yet :ohdear:

e: outside that "Main" is a method that starts every program.

Adbot
ADBOT LOVES YOU

wwb
Aug 17, 2004

That is basically all it is -- .NET looks for a static void method called Main() to kick things off. Nothing more nothing less.

It is a pretty necessary item, and a naming convention that comes from C and other older languages.

  • Locked thread