31 May 2012

Math - Scaling a value

Sometimes you have this thing where you have two ranges, and you need to scale a value from the one to the other; e.g.:
Range 1: 0.....x.....100   x=50
Range 2: 0.....y.....500   y=?
Thus:
100 > 500
 50 >   ?
  x >   y

C# code

Thus, I want to know the value of y. I wrote this extension to get it:
internal static double Scale(this double value, double maxValue, double maxScale) {
  if (maxValue == 0 || maxScale == 0)
    return 0;
  else if (maxValue == maxScale)
    return value;
  else
    return value / (maxValue / maxScale);
}

result = 50.Scale(100, 500); //Result will be 250

Try it


if (max. value)equals (max. scale)
then (value)is (result)
...

See also

Interpolating a value

29 May 2012

.NET - get assembly attributes

Referencing assembly attributes

In .NET, when you go to the properties of a project and select Application > Assembly Information, you can fill in some basic information about the application you're making. It would be convenient if you could reference these fields from within your code, to avoid having to duplicate this information. There is a fairly easy way to do this. To get the company:

public static string Company {
  get {
    object[] attr = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
    if (attr == null || attr.Length <= 0)
      return string.Empty;
    else
      return (attr[0] as AssemblyCompanyAttribute).Company;
  }
}

This can now be written shorter. To get the title:

private static string GetTitle() => Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyTitleAttribute>()?.Title;

I put this as static properties in the Program class. That way I can reference these fields anywere I need them.

Using them in XAML

One useful purpose for this is setting the window title of a WPF application. To do this, you need to declare the namespace of the application in XAML. By convention, it's tag is xmlns:local. Then you can simply write:

Title="{x:Static local:App.Title}"

Assuming you have a method that retrieves the AssemblyTitleAttribute in the App class, the window will now display this title. Also note that the method has to be public for this.