Skip to main content

What's in Microsoft.VisualBasic for C# Developers: Part 3 - Financial

monolith[This blog is part of a larger series, to find more parts in the series please see the Series Index]

Yesterday’s post covered some interesting, yet very simple features in Microsoft.VisualBasic so today I thought I would cover some more complex code: Financial.

This is a class with 13 static method who all return a Double, and if financial code wasn’t complex to begin with the method names are as cryptic as you can get. I’ve broken them into three groups: cash flow, general, depreciation and annuity based.

Cash Flow

These calculations look at investments and cash flows:

  • IRR: Provides the internal rate of return for a series of periodic cash flows.
  • MIRR: Provides the modified internal rate of return for a series of periodic cash flows.
  • NPV: Provides the net present value of an investment.

Example of using the above methods:

// need to place to store profit/loss
// must have atleast one negative and one postive value in it
IList<double> values = new List<double>();

values.Add(-100000); // startup costs - cost money to make money
values.Add(10000); // income in first year
values.Add(15000); // income in second year
values.Add(17500); // income in third year
values.Add(75000); // income in forth year - got govt. contract that year ;)

double[] valuesArray = values.ToArray();

double loanRateGuess = 0.1; // start guessing loan at 10%
double rateIRR = Financial.IRR(ref valuesArray, loanRateGuess) * 100;

double reinvestmentRate = 0.12; // MIRR also includes the reinvestment rate 12%
double rateMIRR = Financial.MIRR(ref valuesArray, loanRateGuess, reinvestmentRate) * 100;

// working out net present value needs a fixed rate
double fixedRate = 0.08; // 8%
double netPresentValue = Financial.NPV(fixedRate, ref valuesArray);

Console.WriteLine("Net present value: {0:0.00}", netPresentValue);
Console.WriteLine("Rate of return is:");
Console.WriteLine("\t{0:0.00}% (Calculated using IRR)", rateIRR);
Console.WriteLine("\t{0:0.00}% (Calculated using MIRR)", rateMIRR);

Gives us:

image

Depreciation

I understand depreciation as: how much value an item loses over time.

  • DDB: Allows you to work out depreciation using the double-declining balance method (DDB) or a custom method. The DDB calculation per period is: Depreciation / Period = ((Cost – Salvage) * Factor) / Life
  • SLN: Provides a value specifying the straight-line depreciation of an asset for a single period. SLN is calculated using:(Cost - Salvage) / Life
  • SYD: Provides a value specifying the sum-of-years digits depreciation of an asset for a specified period. This is similar to DDB but calculated differently.

Example of using all the above methods to figure out how much you lose on an iPhone over two years:

double iPhoneInitialCost = 10000;
double iPhoneResale = 3500;
double YearsUntilNextUpdate = 2;

// work out deprecation per year
double deprectionPerYear = Financial.SLN(iPhoneInitialCost, iPhoneResale, YearsUntilNextUpdate);
double sydValue = iPhoneInitialCost;
double ddbValue = iPhoneInitialCost;
for (int year = 1; year < YearsUntilNextUpdate + 1; year++)
{
    double syd = Financial.SYD(iPhoneInitialCost, iPhoneResale, YearsUntilNextUpdate, year);
    double ddb = Financial.DDB(iPhoneInitialCost, iPhoneResale, YearsUntilNextUpdate, year);
    sydValue -= syd;
    ddbValue -= ddb;     
    Console.WriteLine("In year {0} you will lose", year);
    Console.WriteLine("\t {0:0.00} (Calculated using SYD)", syd);
    Console.WriteLine("\t {0:0.00} (Calculated using DDB)", ddb);
    Console.WriteLine("Phone value");
    Console.WriteLine("\t {0:0.00} (Calculated using SYD)", sydValue);
    Console.WriteLine("\t {0:0.00} (Calculated using DDB)", ddbValue);
    Console.WriteLine();
}

Which gives us the painful realisation of how quick value is lost:

image

Annuity Based

An annuity is a series of fixed cash payments made over time. An annuity can be a loan (such as a home mortgage) or an investment (such as a monthly savings plan).

If you are working out annuities there is a number of calculations around those:

  • If you have the payment, period and interest you can work out the future value using FV over a period.
  • If you have the future value, payment and period you can work out the interest using IPmt over a period.
  • If you have the future value, payment, and interest you can work out the period using NPer over a period.
  • If you have the future value, period and interest you can work out the payment using Pmtt over a period.

Other methods around annuities:

  • PPmt: Calculate the principal payment of an annuity.
  • PV: Calculate the present value of an annuity.
  • Rate: the interest rate per period for an annuity calculated by iteration.

Example of using FV to work out savings:

double monthlySavings = 1000;
double interestRate = 8;
double yearsYouWillSave = 10;
double deposit = 0;

// specifies if you save at start or end of month
DueDate dueDate = DueDate.EndOfPeriod; 

if (interestRate > 1)
{
    // must be expressed as a percentage
    interestRate = interestRate / 100;
}

// converted to interested per month
interestRate = interestRate / 12;

// figure out how many months that is
double months = yearsYouWillSave * 12;

// note savings and deposit are converted to negative as we are saving
// if we were paying off they would be positives
double savings = Financial.FV(interestRate, months, -monthlySavings, -deposit, dueDate);
Console.WriteLine("In {0} years, you will have saved: {1:0.00}", yearsYouWillSave, savings);

gives us:

image

What's in Microsoft.VisualBasic for C# Developers: Part 2 - Constants & Control Characters

[This blog is part of a larger series, to find more parts in the series please see the Series Index]

monolithWe will start off the series with something very simple, two classes which give us access to some constant definitions that may be useful to use.

Control Characters

Microsoft.VisualBasic.ControlChars contains 10 constant fields for commonly used items:

public const char Back = '\b';
public const char Cr = '\r';
public const string CrLf = "\r\n";
public const char FormFeed = '\f';
public const char Lf = '\n';
public const string NewLine = "\r\n";
public const char NullChar = '\0';
public const char Quote = '"';
public const char Tab = '\t';
public const char VerticalTab = '\v';

As you can see this is just a useful list to have and can make code much easier to read.

As a C# developer there is one on that list I wouldn’t use – NewLine. In the mscorlib assembly, there is an Environment class which contains a property called NewLine which, on my machine is the exact same as the one above. So why would I use that over the VB one? This is because Environment.NewLine changes based on underlying OS – so on systems which use just \n it will be that where the VB one is always the same regardless of what the OS uses.

Constants

Microsoft.VisualBasic.Constants contains a lot of constant definitions which are used through out the whole Microsoft.VisualBasic assembly. A lot are to be used with specific functions, for example vbAbort is meant to be used with the MsgBox function, but there are a few which are interesting:

Control Characters

The first interesting group is that almost all the Control Characters from Microsoft.VisualBasic.ControlChars are repeated here – the only one missing is Quote. So now you have two ways (or three ways for Newline) to get control characters.

public const string vbBack = "\b";
public const string vbCr = "\r";
public const string vbCrLf = "\r\n";
public const string vbFormFeed = "\f";
public const string vbLf = "\n";
public const string vbNewLine = "\r\n";
public const string vbNullChar = "\0";
public const string vbTab = "\t";
public const string vbVerticalTab = "\v"

Tristate

Developers often have an bad habit of thinking that they can build it better than other people have done so in the past. There is a famous example of someone who decided that a boolean (something that is either true or false), needed a third option – FileNotFound.

It appears the VB guys also decided this would be a good route to go too, so we have the Tristate enum, which is atleast a little more logical than the above example.

public enum TriState
{
    False = 0,
    True = -1,
    UseDefault = -2
}

The values here match to the Convert.ToBoolean(int value) method where 0 is always false and anything else is true.

With the .NET Framework 4, I suspect this is not that useful anymore as you can set the default value on the parameters of a method (see example below), but if you are on older versions then this may be useful.

private void Demo(bool value = true)

Finally an AWESOME competition for South African Developers

logoI often find too many competitions from Microsoft ignore the southern tip of Africa or focus on specific markets, like education with the great ImagineCup event. Finally us hard working developers get a great competition: Internet Explorer 9 Top Developer Competition

This competition wants* developers to either create an awesome IE 9 add-on or light up a web site with some of the new awesome IE 9 features – so if you a web dev, html monkey, C++ or .NET developer you can take part!

The prize? A trip to PDC – the conference were two years ago everyone got hand build super laptops and last year Windows Phone 7 devices**, not to mention it is where the top Microsoft development speakers meet!

So get coding, you only have until March!!

Some things you may want to check out:

* Side note: “The competition wants” really sounds like the competition is a living entity and will punish you if you don’t do this… it isn’t and it won’t.

** My guess for this year at PDC is giving everyone tablets - just looking at what was announced at CES.

What's in Microsoft.VisualBasic for C# Developers: Part 1 - An Introduction

monolith[This blog is part of a larger series, to find more parts in the series please see the Series Index]

The .NET Framework is a large and complex system supporting many languages and when I do battle with the gods of code, my weapon of choice is C#.

When you create a C# project you get a reference to Microsoft.CSharp added and if you ever looked in there it is really sparse – just two classes:

image

2001-a-space-odyssey-apeAs all other languages have a similar assembly, and maybe you had the same monkey thought I did “Those are just some low level stuff for the language, nothing I want.”

I was wrong, again. Maybe the C# doesn’t have much, but the Microsoft.VisualBasic is not just low level plumbing but includes an monolith full of goodness!

WHOA THERE!

You may be asking how can C# developers use an assembly written in VB.NET? The answer is: very easily Smile 

All assemblies are actually IL (intermediate language) which means that no matter what language a .NET assembly is developed in, you can use it in the language of your choice.

This blog series will cover some of the goodness is available in this assembly and hopefully at the end, you will be a better, faster and more productive C# developer thanks to VB.NET!

Presentation Dump: End of 2010

Previous presentation dumps:

All slides can be found at: http://www.slideshare.net/rmaclean

This is the smallest presentation dump so far, mostly because a lot of the work I did in the second half of 2010 was at public events, like Tech-Ed, and those have already been upload.  One of the big pushes I did in the last part of the year was around design of the presentation and I think the T4 presentation is a highlight of that work for me.

T4 Templates

OData

Developing RESTful Services in .NET

Workflow Foundation 4

What's in Microsoft.VisualBasic for C# Developers: Series Index

This page lists all the parts of the series, if a part is not hyper-linked it means that it will come up in the near future and you should subscribe to the RSS feed to get notified when it arrives.

This list is subject to change as I write posts.

Resolving the AppFabric: ErrorCode<ERRCA0017>:SubStatus<ES0006>

AppFabric Caching has one error which you will learn to hate:

ErrorCode<ERRCA0017>:SubStatus<ES0006>:There is a temporary failure. Please retry later. (One or more specified Cache servers are unavailable, which could be caused by busy network or servers. Ensure that security permission has been granted for this client account on the cluster and that the AppFabric Caching Service is allowed through the firewall on all cache hosts. Retry later.)

This message could mean a variety of different things, such as:

However for me none of those were the cause of my pain. My issues was:

Copy & Paste Stupidity

imageI copied and pasted the settings for my deployment and so I had the following config issue:

<dataCacheClient>
    <!-- cache host(s) -->
    <hosts>
        <host name="cacheServer1" cachePort="22233"/>
    </hosts>
</dataCacheClient>

However my server was DEMO-PC,  so I needed to change that to the following:

<host name="DEMO-PC" cachePort="22233"/>

The only way I found this was to hit the event log and scroll down through the error message. About halfway down was the cause, as clear as day.

It's MVP time again

mvp

Exactly a year and a day ago, I blogged about being awarded a MVP from Microsoft and I am proud to announce that I have been awarded a MVP for a second time!

Thank you to all that were part of making this happen, I am very honoured by all of you.

What is an MVP? In short it is a thank you for helping Microsoft communities. The long version can be found here.

My planning for MVP Summit in Feb/Mar has already been done so I am looking forward to seeing the other MVP’s and product team!

I would also like to congratulate my fellow January MVP’s in particular the South African ones: Zayd Kara (ALM for the second time) and new to the MVP’s Veronique Palmer (SharePoint).

Reporting Services - Missing features in SRS 2008

clip_image002I recently helped on an interesting problem with SQL Reporting Services, where features of SRS 2008 were just gone!

History

The team had created a number of reports in SQL Server 2005 and used them successfully for a number of years. During their upgrade to SQL Server 2008 they needed to upgrade the reports to SRS 2008 format.

To be clear here, SRS doesn’t support backwards compatibility so if you want to run a report built in 2005 on a 2008 server, it must be upgraded. Thankfully this is a simple process, just open the report solution in Business Intelligence Development Studio (BIDS) 2008 and it will upgrade it.

The Problem

The team knew this process and opened the 2005 reports in BIDS 2008, no errors were reported, all reports saved correctly and were published to the SRS server. The server then rendered them, which to everyone meant that the reports had upgraded successfully.

However there was some changes to how the reports were rendered and the team needed to change the ConsumeContainerWhitespace property on the report to true to fix that rendering issue.

This is a new property in 2008, and the problem the team had is that when the report was opened in BIDS 2008 the property just wasn’t there! They could create new reports and see it, but their existing reports did not contain it.

Diagnosis

My first thing to check was that they were opening the right version of BIDS – this is the SRS persons way of saying “Have you tried turning it off and on?”.

They verified that quickly, so my next step was to check if BIDS was actually doing the upgrade. A report is just an XML file so you can open it up in notepad and check the schema to verify what version of the report it is. If it is http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition it is a 2008 report and if it is http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition it is a 2005 report.

You know what, after the upgrade it was STILL showing as a 2005 report! This confused me to no end – how could SRS 2008 render a 2005 report and why was BIDS not upgrading it?

Solution

I was close to getting the team to call Microsoft, or an exorcist, for assistance – but re-reading the email conversation between the team and me a number of times I stumbled across the piece of missing information which explained the cause. The team was using .rdlc files – these are SRS files designed for client side rendering. SRS supports these and the “normal” .rdl files.

The interesting thing about .rdlc files is that they are frozen on 2005:

  • So they do not get new features of 2008 or 2008 R2, which is why the new properties (like the one the team wanted) does not appear.
  • The schema remains on 2005 (no upgrade in BIDS)
  • and to confuse everyone, they still render on 2008 and 2008 R2!

Thankfully you can convert from .rdlc to .rdl, which means then the reports get upgraded to the 2008 or 2008 R2 formats and get all the features. The team did this and have been smiling ever since!

Pulled Apart - Part XV: Understanding usage with Runtime Intelligence

Note: This is part of a series, you can find the rest of the parts in the series index.

A vital component of keeping a piece of software alive, is to keep it useful to your users – but how do you know what your users are thinking about your software and what do they think are valuable pieces of functionality?

Pull does this using a fantastic piece of software called Runtime Intelligence from PreEmptive Solutions which is easy to plug in to your application to get interesting and useful details on the usage of your application.

Lottery Winner?

Yesterday I blogged about DevExpress and today another toolset (which isn’t free) so maybe thinking I won the lottery recently – unfortunately I haven’t Sad smile 

What I found one July morning, is that PreEmptive gives away the software and services required for Runtime Intelligence FOR FREE,to CodePlex projects for them to use.

This may be the biggest secret of CodePlex and another fantastic reason to use CodePlex for your open source hosting.

Stats

imageThe first interesting stat given is how many times the application has run, for Pull that is over 700 times Open-mouthed smile It is always great to see that it is used.

image

You can then drill down on to the stats, which are publically available and provide details on what features are used, what OS’s and versions of the .NET Framework are available and also where in the world it is being used!

Technical

How do you add this to your application? It is really simple, just follow the official guide. My one word of warning is the ClickOnce, another great feature of CodePlex, doesn’t play well with this and so you want to be aware of that.