Automating Excel 2010 using F# - visual-studio

I have been searching for a FAQ to tell me how to open a Excel Workbook/Worksheet and also how to Save the File once I have finished.
I notice that in most FAQ and all the books I have purchased on F# one is show how to create a new Workbook/Worksheet but is never shown how to either open or Save it.
Being a newbie to F# I would very much appreciate it if anyone could kindly provide me with either an answer or perhaps a few pointers?
Update
As for why F# and not C# or VB?
I am pleased to say that inspite of being a newbie (with the exception of Forth, VBA & Excel 2003, 2007 & 2010 and Visual Basic) I can do this in both VB, VBA & C# and since I've been retired on medical grounds, with plenty of time unfortunately on my hands, I like to continually set myself challenges to keep my little grey cells active and being a sucker for trying new languages....well!
F# is now an intergral part of Visual Studio 2010 so I thought - why not. Consider this - if we are not willing to use or at least try a new languages - I would always be wonder if I might have prefer it to VBA, VB, C# ..... and if you look at it from another point of view, if no one is going to use it - why create it in the first place? I suppose you can say if cave men hadn't experimented and made fire by rubbing two sticks together - where would we be now and would matches have been invented?
Although an complete answer would be good, I prefer a few pointers, to keep my challenge going.
And lastly but not least - thank you for taking the trouble to respond!

I don't think their is a specific F# library for Office, so you will just use the exact same .NET library that you use in VB.NET/C#. F# is a .NET language, so anything that can be done in C# can be done in F# (but you probably already knew that :) ). The API call will be exactly the same, it just that they will be done using the F# syntax instead of the VB/C# one. So for example something that look like this
public void SaveMyWorkbook() {
string filePath = #"C:\failworkbooks\catfail.xlsx";
workbook.Save(filepath);
}
Will be expressed in F# as
let filePath = "C:\\failworkbooks\\catfail.xlsx";
let saveWorkbook() = workbook.Save(filePath) |> ignore //if the Save method return something
Now, what you will soon realize is that the API isn't exactly designed to be easily used from a functional language. It can be done, but this task in particuliar is much more tailored to C#/VB.NET.
If you really want to enjoy F#, I suggest you use in area where its strength really show. My personal experience is that functional language are awesome when a lot of math is involved. It is also marvellous if you want to easily introduce parallelism in your application (since F# code is usually side effect free). So anything that require data crunching on a lot of data is perfect for it. But for task that consist mainly of putting together a bunch of API call to an external library, F# is kind of meh. You could say that F# is kind of like a graphic card programming language, while C# a general purpose CPU programming language. A lot of thing run better with C#, but the stuff that run better on F# run really better on it.
But if you really want to go that route, my suggestion is to try to use the Office API as you already know it, but with a F# syntax. If at some point you really have no idea how to do a specific task, ask a question about it on stackoverflow with your code and exactly want you want to do. Those question get answered ridiculously fast compared to broad all-encompassing question, so you won't wait long. (Programmer seem to love precise question with a specific answer ^^)
I hope that it helped a little.

I found this http://iouri-khramtsov.blogspot.co.uk/2011/12/automating-excel-with-f.html helpful advice. Briefly, you'd use something like this:
#r "Microsoft.Office.Interop.Excel" // Assuming it's a script
let excel = ApplicationClass(Visible = true)
let openFileName = #"C:\MyDir\MyFilenameToOpen.xls"
excel.Workbooks.Open(openFileName)
// Do stuff
let savedFileName = #"C:\MyDir\MyFilename.xls"
workbook.SaveAs(savedFileName)
Using F# with Excel seems like a natural fit.
Getting to a result in Excel requires the use of several immutable values, each driven by formulas. Excel has a brilliant user interface, a lovely model of the world - I love rows, columns and cells - but to automate or customise things requires macros. Why learn this when you can use F#? Formulas and immutable values are fundamental to its design.
Ideally you'd write formulas yourself as a User Defined Function (UDFs) also in F# - see http://excel-dna.net/ . Then, perhaps, you'd want to do something interesting with objects/types - Look for "github com mndrake ExcelObjectHandler" (I don't have enough reputation to post a 3rd link).
Jack

Related

UIPath. Vb.net? if condition

Im new to uipath and coding in general. I know most of the basics from what was taught but they didnt go through how to form "condition" statements in the "if" activity. or basically any form of conditions. Where can i go about to learning them? is it a specific language?
kinda like: not Months.Contains(ExpenseMonth)
i wouldnt be able to come up with that because i dont know what is acceptable/readable to uipath studio
also regarding those calculations. where can i find more information on those? to learn more about
kinda like: (int32.Parse(row("Value").ToString) * 100 / monthlyTotal).ToString
they didnt really give me details on how to form that
so essentially, if i wasnt spoon fed with those statements, i would be stuck
It depends on which activity you are using. Usually it's VB.net. Find more about that programming language here.
And yes you will need to get the basics of that language on your own. UiPath isn't really helping you find the correct condition. It is more a tool that can use VB.net.
And soon you can switch to C# completely. But that is not yet ready and still experimental. Also, I would recommend you to stay with VB.net as it is way easier to learn as a first language. Currently, you can only use C# and Invoke Code activity.
To your first example from above:
not Months.Contains(ExpenseMonth)
That depends on your variable type. That looks like a DateTime or a String type and so you are able to use predefined functions that come with it. You can show them but simply clicking CTRL + SPACE after the dot.
And your second one:
(int32.Parse(row("Value").ToString) * 100 / monthlyTotal).ToString
I would always recommend you to use CInt instead of int32.parse. Look here. And it is often not needed to convert the row value into a String. As it is usually already in that type by default.
But again. You will need to learn the basics of VB.net before you are able to write a good business logic in UiPath that makes sense and is best practice.

GUI basics in Smalltalk

I'm quite new to Smalltalk and I've been searching a whole day how I could write a GUI. I've found loads of information on how to work with Morphs and what Halos are, but I don't seem to be able to find what I need (It's only a table with the entries from a Dictionary).
Next to Morphs, I also found quite something on how smalltalk introduced the MVC-principle. I even found the ST-80 Views Category, containing everything I would need, but again I am not sure on how to use it correctly and somehow I don't seem to find the right sources to get me started.
Therefore my question(s): Where to start to build a simple GUI? How should I choose from the billion Morphs available and how do I combine them to a solid interface? Should MVC only be used when it gets more complex or are they also useful for simple GUIs? Is there any general overview on what to use in which cases?
To illustrate what I would like to do, I added some pseudo-code of how I would have it in mind:
d := Dictionary new.
"add data to the dictionary..."
view := DictionaryView new.
view addDictionary: d.
button := SimpleButtonMorph new.
"e.g. change label to sum of values"
button target: [button label: d sum.].
window := SystemWindow labelled: test.
window addMorph: view.
window addMorph: button.
Any help to get me started with this is highly appreciated.
Update:
I recently found a chapter from a book that helped me understand morphic better with some nice explanation and example code and for people who want to know more, there is a whole list of free books too. Also useful were the tutorials from the squeak wiki. Especially the one on Pluggable Morphs helped me to understand this concept better. Note that this tutorial is hidden in the list of unreviewed tutorials (possibly because there is a little error in the project that can be downloaded).
In Squeak (I presume you use Squeak, because you speak of Morphs and ST80),
there are several ways to build GUIs.
Plain Morphs
You can just put together Morphs. Typically, you need some Widget, like a SimpleHierarchicalListMorph. But this process gets tedious fast.
ToolBuilder
If you're creating an application that somehow resembles a tool, of whatever kind, the ToolBuilder might be your friend. Tools like the System Browser, the Debugger, or more recently, the FontImporter are built with ToolBuilder. It requires a Model with the #buildWith: message. Search for implementers of this message to get an idea how to use ToolBuilder.
But probably the easiest way:
Morphic Designer
The Morphic Designer lets you put together your Application UI graphically. You can re-use the design and do not need too many code to hook you program up to the UI. Examples included.
Note: You also found the MVC implementation. It has come out of fashion in Squeak, but it still should be usable. However, you must create a new Project to use MVC. It is, by the way, possible to create tools that can run in both Morphic and MVC projects when you use ToolBuilder.

Coding-style: How to improve coding-styles and standards at a company

What are the best ways to improve the standards of coding-styles at a company? Let's use C# as an example here.
I guess there are many differences between developers that need to be taken into consideration. The concrete ones could be education, experience and past programming-languages.
How does one justify that something is right over something else?
One person may say "I move my body to the place where I earn my money with my 4-wheeled vehicle". So why is it more "right" to say "I drive to work in my car"?
Some people might like code more explicit with more lines of code. Some might like more tight code.
// Explicit
string text = defaultValue;
if (string.IsNullOrEmpty(text)) {
text = fallbackValue;
}
// Tighter
string text = defaultValue ?? fallbackValue;
Or the old protective programming-style, where you check for error-cases in the beginning and not wrap the whole method body inside a positive if-clause:
public string ChangeText(string text)
{
if (!string.IsNullOrEmpty(text))
{
// Do a lot of stuff
}
else {
throw new Exception();
}
}
// vs.
public string ChangeText(string text)
{
if (string.IsNullOrEmpty(text)) {
throw new Exception();
}
// Do a lot of stuff
}
Is the old "I'm having troubles reading this code" valid here? It's the same situation that was when Generics was introduced to C#, people had an initial trouble reading it.
Where is the line drawn between unreadable code and code that some developers are not used to?
Which part of Phil Haacks "7 Stages of new language keyword grief" has valid points here?
Are there any easy ways to set coding-standards and uphold them in a company?
UPDATE: Take in consideration things like variable-naming, that can't really be defined in a document. Or can it?
The easiest way to set coding-standards at a company:
Create a Standards Document and enforce it.
...people love to complain about code quality, but few will sit down and take the time to create a standards document. It's worth the effort and as long as you can enforce it (code reviews, etc.) then you're bound to notice an improvement in your code.
You always can use free tools like StyleCop from Microsoft.
You can disable or modify rules you don't like
There are two main sides of coding style:
"Where do I put the opening brace?" type issues - These are usually unimportant, i.e. there are no real reasons to prefer one style over the other.
Actual coding rules, like do we use return's in the middle of a function.
The way I see it, for #1 type issues, there is no point in any debate. Just set a standard in a standards document, and enforce it (more on this later).
As for the second issue, I'm honestly not sure whether it should be regulater. I personally love sprinkling functions with return values to check for error conditions, and I know some people who cringe at the practice. But at the end of the day, we can usually read each other's code just fine. These kinds of issues are much more about how you prefer expressing yourself, what is easier for you to write, and I wouldn't want a company making rules that get to this level.
As for how to enforce things, standards documents are good, but in my experience, are just never read or followed closely, and are soon forgotten. The best way is to have some kind of automated tool which tells you that you're violating the standard.
For example, even as a completely new Java programmer, I knew when to uppercase/lowercase my identifiers, simply because Eclipse let me (quietly, unobtrusively) know what the standard is.
First, you will always have to enforce the coding styles - there will never be a consent.
That's, why I would try to automate the check for consistency. Depending on your language you can use StyleCop (for .Net) or something like indent under linux.
Every developer can work with his own code style in his environment (the reformat can be very easy, depending on your environment), but all checked-in code has to be of the company's style.
Which style do you choose? Well, often there are already popular styles - depending on the language. For your example (C#) I would choose the Microsoft style. At last: only the project manager (senior programmer) has the right to adjust it.
Most companies use Coding-Style-Guidelines/Conventions. These are documents telling that you should always do braces around the if body even for one command, that you should indent with tabs/spaces, and so on.
There are a lot of tools for (automatically) check and enforce the coding-style. (An example for the java-world is checkstyle, which can be integrated into eclipse and also in a continuous integration solution like 'hudson'.)
How does one justify that something is
right over something else?
Easy: just don't. Pick a coding style, communicate it, and enforce it.
I think consistency is important here. There's not a lot of point in getting into a semantic debate over which way is better than the other unless the current methodology is particularly bad.
What is important is that the team writes their code consistently so that if someone resigns or gets hit by a bus then his/her colleagues know what is going on with the code when they are forced to work with it.

Good examples when teaching refactoring?

I'm running a refactoring code dojo for some coworkers who asked how refactoring and patterns go together, and I need a sample code base. Anyone know of a good starting point that isn't to horrible they can't make heads or tails of the code, but can rewrite their way to something useful?
I would actually suggesting refactoring some of your and your coworkers' code.
There are always places that an existing codebase can be refactored, and the familiarity with the existing code will help make it feel more like a useful thing and less like an exercise. Find something in your company's code to use as an example, if possible.
Here are some codes, both the original and the refactored version, so you can prepare your kata or simply compare the results once the refactoring is performed:
My books have both shorter examples and a longer, actually a book long example. Code is free to download.
VB Code Examples
C# Code Examples
A nice example from Refactoring Workbook
There are a lot of examples on the internet of simple games like Tic-Tac-Toe or Snake that have a lot of smells but are simple enough to start with refactoring.
The first chapter in Martin Fowler "Refactoring" is a good starting point to refactoring. I understood most of the concepts when one of my teachers at school used this example.
What is the general knowledge level of your coworkers?
Something basic as code duplication should be easy to wrap their heads around. Two pieces of (nearly) identical code that can be refactored into a reusable method, class, whatever. Using a (past) example from your own codebase would be good.
I would recommend you to develop a simple example project for a specific requirement.
Then you add one more requirement and make changes to the existing classes . You keep on doing this and show them how you are finding it difficult to make each change when the code is not designed properly. This will make them realize easily because, this is what those ppl will be doing in their day to day work. Make them realize that , if patterns and principles are not followed from beginning, how are they going to end up in mess at the end.
When they realize that,then you start from scratch or refactor the existing messed up code .Now add a requirement and make them realize that it is easy to make a change in the refactored code, so that you need to test only a few classes. One change would not affect others and so on.
You could use the computer ,keyboard and printer class as an example. Add requirements like, you will be wanting the computer to read from mouse , then one more requirement can be like your computer would want to save it in hard disk than printing. Finally your refactored code should be like, your computer class should depend on abstract input device class and output device class. And your keyboard class should inherit from Inputdevice class.
Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin considers refactoring.
I'm loving Refactoring Guru examples.
In there you can find design patterns examples too.
Refactoring is non-functional requirement when code perform correct functionality for which it is designed however difficult to debug, requires more effort to maintain and some performance bottleneck. Refactoring is to change to be easily maintainable, good readability and improve efficiency.
Thus we need to focus on criteria to make code more readable, easy to maintain.
Its obvious that having very large method/function might be difficult to understand.
Class depends on other hundreds of class make thing worst while debugging.
Code should be readable just like reading some workflow.
You can also use tools like sonar which can help you to identify critical criteria such as "Cyclomatic Complexity"
http://www.sonarsource.org/managing-cyclomatic-complexity-to-increase-maintainability/
You ask them to write code them self and check how tool does refactoring.
Apart from that, you can write code in eclipse and there is option available which does refactoring for you...
It's a bit dated (2003), but IBM has several refactoring examples (that work[ed?] in Eclipse) at http://www.ibm.com/developerworks/library/os-ecref/

Code Length in IDE ( w/o modeling support ) versus Code Efficiecy in Compilation in Delphi

So - highly hypothetical question and more like discussion about your coding style and practice you use daily.
I will take as example: CodeGear RAD Studio 2009 (sorry to all D7 fans, but Unicode rules).
I have capability to expand/collapse functions/procedures/records and few other complex data structures, but what if code is lengthy?
What makes the task and its accomplishment efficient - the time required to add comments (its req actually) and expand/collapse necessary area or use OMT offered possibilities?
To give example input from myself - I have small app, about 1,5k lines and I do not use Modeling. Is it smart enough or do I lose a lot of time if I need to find some simple references or (event) calls?
If I understand your question correctly, it is a bout finding your way into code (yours or someone elses').
I use Model Maker Code Explorer for browsing through source code (and for refactoring existing code, and creating new code). At EUR 99, it is dead cheap for what it does.
It usually gives me a perfect overview of what I need, and has a nice 'search' interface as well.
If I need more complex searches, I usually use the GExperts (grep) search function: it is blazingly fast, and with good naming of your identifiers, it is usually a breeze to find stuff.
If I understand your question correctly, you want to know what is more efficient:
Use comments and expandable sections.
Use moddeling techniques.
I think it depends on personal style. Modeling can be great, but has dangers of spending too much time creating nice pictures.
We have a large app 500k+ lines. We do not use collapsable sections because we keep our file size acceptable and we have a good file organisation structure. We sometimes use modeling if complex parts are added (class diagrams and state diagrams). And we use lots of comment to explain difficult parts.
If you have Delphi 2009 you can use also the Delphi Class Explorer (in the View menu) in order to see your classes. It seems a little bit cryptic but only for the first 5 minutes. After this you will get used with it.
Also you can use CnPack a very impressive package in order to help you manage your project. Basically, in the IDE appears a new menu called 'CnPack' which has a bunch of wizards to help you find the way out in the source. Some examples:
Uses Cleaner
Procedure List (it gives you the incremental search capability for your procedures - very neat)
Bookmark Browser
etc.

Resources