How to multiple a cell range (in Excel) by a value

I was working on an application which reads data from supplied spreadsheets. In one column it expected a %. It expected it to be written as 30 (for example for 30%). However some spreadsheets arrived with the % written as 0.30.

So to change these value within the spreadsheet (for any selected range) I wanted to simply multiple the selected cells by 100.

To achieve this is very simple. Just follow these steps

  1. In an empty cell type 100
  2. Now select the altered cell and copy it
  3. Next, select the range of cells you wish to multiply by the copied value
  4. Right mouse click on the cells and select Paste Special
  5. Select the Operation Multiple and press OK
  6. Finally delete the cell we added in step 1

Separating out configuration files in .NET

Occasionally we might wish to de-clutter our App.config by moving parts of the configuration into separate files. Ofcourse this process is also useful where we might wish to simply reuse existing config parts.

This capability is built into .NET, so for example we can have

<appSettings configSource="MyAppSettings.config" />

We can also use the appSettings attribute file, for example

<appSettings file="MyAppSettings.config" />

The MyAppSettings.config file might look something like

<?xml version="1.0" encoding="utf-8" ?>
<appSettings>
  <add key="configuration" value="..\..\..\..\Samples\SpaceMonitor.xml"/>
  <add key="artifacts" value="..\..\..\..\..\Samples\artifacts"/>
</appSettings>

Note: the appSettings section starts the file (after the xml declaration), i.e. we do not have a configuration section within this file.

So this is cool, appSettings shows the configSource attribute in intellisense in Visual Studio, but we can in fact use the configSource on any section. Maybe we’ve created a section called CustomSection, then it implicitly has a configSource attribute built in.

It’s important though to note that sectionGroups do not have an implicit configSource. Say we have something like

<configSections>
  <sectionGroup name="orchestrator">
    <section name="aliases" type="Orchestrator.Configuration.AliasesSectionHandler,   
                                  Orchestrator.Configuration"/>
    <section name="plugins" type="Orchestrator.Configuration.PluginsSectionHandler, 
                                  Orchestrator.Configuration"/>
  </sectionGroup>
</configSections>

Now you might think you can write <orchestrator configSource=”Orchestrator.config”/> but I’m afraid not.

Only sections can use the configSource

Instead what we’d need to do is something like this

<orchestrator>
  <aliases configSource="Alias.config" />
  <plugins configSource="Plugins.config"/>
</orchestrator>

and the actual files would look something like

<?xml version="1.0" encoding="utf-8" ?>
<aliases>
  <alias key="cron" value="StandardTriggers.CronTrigger, StandardTriggers"/>
</aliases>

and

<?xml version="1.0" encoding="utf-8" ?>
<plugins>
  <plugin type="StandardPlugins.WCFMonitorPlugin, StandardPlugins"/>
</plugins>

So with the above information you can see that if you wanted to separate out a system.serviceModel, for example, you would only be able to separate the behaviors, services etc. as the system.serviceModel is a sectionGroup.

.NET Installer cannot access your App.config

I’ve been caught by this once before and so it’s time to ensure it’s documented.

I’ve created an Installer for a Windows Service in .NET, it’s a fairly generic service (or more succinctly it’s an application that allows me to create services with minimal code) so I want it to be easy to give it a service name that properly represents it’s functionality (not the generic container’s name). So I added an appSettings section to the App.config and tried to install the service using InstallUtil and ofcourse it failed to get the info. from the App.Config.

Whilst the code for the Installer is within the EXE assembly, it’s run via InstallUtil so cannot pick up the correct App.config automatically. It’s simple to implement this functionality, see the code below

string configFile = Assembly.GetExecutingAssembly().Location + ".config";

ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = configFile;

Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map,   
                              ConfigurationUserLevel.None);
	
string serviceName = config.AppSettings.Settings["ServiceName"].Value;
serviceInstaller.ServiceName = serviceName ?? DEFAULT_SERVICE_NAME;

In the sample above I have a fallback DEFAULT_SERVICE_NAME in case we forget to set the config as follows

<appSettings>
  <add key="ServiceName" value="My Application"/>
</appSettings>

NInject ChildKernel

I’ve been working on an application which is basically a glorified scheduler. Within it I have the concept of projects which are made up triggers, tasks etc. So we have a parent child relationship going on between the project and the child elements, the triggers etc.

One problem I came across was that the application holds a StandardKernel (as one might expect) and injects dependencies etc. into the projects, triggers and tasks but I wanted to use the same mechanism to allow me to inject the current instance of a project into the children, i.e. the triggers and tasks could (if they wanted) get access to the parent project instance.

Obviously if I add the project to the application wide kernel, all triggers and tasks would get a project object, but not necessarily the project which acts as their parent (actually it’d probably fail to allow me to resolve to multiple instances of a project anyway). Of course I could pass the instance of the project to each trigger or task at construction or explicitly calling the relevant method/property, but I wanted to reuse the NInject mechanisms so as to keep a standard way of injecting objects into this application.

Enter the ChildKernel. A Ninject extension class available via GitHub.

Using the ChildKernel we can create a new kernel, which (if you like) inherits the bindings from a parent kernel and then we add further bindings specific to it’s use, as per

ChildKernel child = new ChildKernel(kernel);
child.Bind<IProject>().ToMethod(_ => currentProject);

kernel would be our StandardKernel acting as the parent kernel.

Now we simply Get or Inject using this child kernel and if a dependency is not resolved using the child, it is passed to the parent kernel to resolve.

MemoryCache, caching in .NET 4

Having used the Enterprise Application Blocks in the past I’ve been well aware of the capabilities of the caching block, but recently was looking for some caching for a small application I have and stumbled across the MemoryCache which looks like it’s the replacement for the Caching Block.

It supports caching policy’s such as absolute expiration and sliding expiration.

You can create multiple instances of a MemoryCache or use a singleton in the form of MemoryCache.Default in the typical scenarios where only a single instance of the cache is required.

A simple example is shown below

MemoryCache cache = MemoryCache.Default;

cache.Add("Key", "Value", new DateTimeOffset(DateTime.Now.AddSeconds(10));
object o = cache.Get("Key");

In the above (fairly useless) example we get the default instance of the cache and then add a key and value to the cache with an absolutely expiry in 10 seconds time. We then get the item from the cache and ten seconds later it will have been removed from the cache.

When I get around to it I’ll amend with some better examples.

What version of Oracle am I connecting to ?

We recently moved from using Oracle 10g to Oracle 11g

Note: I have access to the DB in this scenario but only via Oracle SQL Developer

I wanted to verify that the version I was connecting to was indeed 11g, so found this

SELECT * FROM PRODUCT_COMPONENT_VERSION;

Which returns the following

[table “” not found /]

Beware of using RegexOptions.Compiled Regex in some situations

Using the RegexOptions.Compiled option in a Regex instance means that the regular expression is compiled into IL upon creation, which sounds good.

But beware, it can be an expensive operation which highlights itself if the code is called many times. If the Regex instance is reused a lot it makes sense to use this option, but even then beware that the time to create the compiled expression might not be worth it in a one-off scenario. In such cases do not use RegexOptions.Compiled.

Let’s look at some results of a simple test.

In the first example I’m simple creating the Regex in a method and calling the Split method on it, so these results obviously include the creation and use of the object. “Option” denotes whether the Regex was compiled or interpreted and the number column denotes is the number iterations calling we make creating a Regex and using it (time is shown in ms)

[table “” not found /]

Next we’ll create the Regex and reuse it

[table “” not found /]

Obviously what you see in the second table is that when the Regex Split is called a low number of times the performance gain of compiling the expression is minimal, but it gets progressively better the more times the regex is used.

So the lesson is to not use the RegexOptions.Compiled option unless you’re pretty sure the performance hit of creating the Regex isn’t an issue and it will be called a large number of times. All other times do not used RegexOptions.Compiled.

Note: performance tests were carried out on a 32-bit Windows XP machine

This setup requires Administrator privileges for configuring IIS Virtual Roots.

Came across this error “This setup requires Administrator privileges for configuring IIS Virtual Roots.” when attempting to install some software on a work development machine. Although I had admin rights and all permissions to install this app it failed with the above error.

To save on time getting support to sort it all out (and obviously should not be done if you don’t have the permission to do this) found that I could alter a registry setting the DisableUserInstalls value to 0 in HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\Installer.

Memory limits for a 32-bit .NET application

I’m currently working on an application which is deployed to Windows XP (yes some corporates are still on XP), so whilst I hope this post will be useless soon, I still currently need to worry about memory usage on a 32-bit machine.

Whilst Windows XP has a 4GB memory limit, not all of this is available to your application. An application/process on a 32-bit version of windows has 2GB of available memory to use (if using the /3G switch on Windows Server 2003 then you can get 3GB). You may start to see Out of Memory exceptions (obviously depending upon what you’re trying to allocate and garbage collection etc.) at around 1.2GB.

Whilst this application is currently running on a 32-bit version of Windows it may move to a 64-bit version soon. If it has to remain as a 32-bit application it will have double the amount of memory available. So a 32-bit application on a 64-bit version of Windows will have 4GB available and Out of memory exceptions may occur in the region of 2.8GB memory usage.

Here’s a little bit of code that allows us to get the memory usage for a process

public class MemoryInformation
{
[DllImport(“KERNEL32.DLL”)]
private static extern int OpenProcess(uint dwDesiredAccess,
int bInheritHandle, uint dwProcessId);
[DllImport(“KERNEL32.DLL”)]
private static extern int CloseHandle(int handle);

[StructLayout(LayoutKind.Sequential)]
private class PROCESS_MEMORY_COUNTERS
{
public int cb;
public int PageFaultCount;
public int PeakWorkingSetSize;
public int WorkingSetSize;
public int QuotaPeakPagedPoolUsage;
public int QuotaPagedPoolUsage;
public int QuotaPeakNonPagedPoolUsage;
public int QuotaNonPagedPoolUsage;
public int PagefileUsage;
public int PeakPagefileUsage;
}

[DllImport(“psapi.dll”)]
private static extern int GetProcessMemoryInfo(int hProcess,
[Out] PROCESS_MEMORY_COUNTERS counters, int size);

public static long GetMemoryUsageForProcess(long pid)
{
long mem = 0;
int pHandle = OpenProcess(0x0400 | 0x0010, 0, (uint)pid);
try
{
PROCESS_MEMORY_COUNTERS pmc = new PROCESS_MEMORY_COUNTERS();
if (GetProcessMemoryInfo(pHandle, pmc, 40) != 0)
mem = pmc.WorkingSetSize;
}
finally
{
CloseHandle(pHandle);
}
return mem;
}

public static string ToString(long numOfBytes)
{
double bytes = numOfBytes;
if (bytes < 1024) return bytes.ToString(); bytes /= 1024; if (bytes < 1024) { return bytes.ToString("#.# KB"); } else { bytes /= 1024; if (bytes < 1024) { return bytes.ToString("#.# MB"); } else { bytes /= 1024; return bytes.ToString("#.# GB"); } } } public static string GetFormattedMemoryUsageForProcess(long pid) { return ToString(GetMemoryUsageForProcess(pid)); } } [/code]

Oracle, where’s my data object

Had a strange issue with Oracle SQL Developer whereby it wasn’t showing a data object which I knew existed and realised I didn’t know the SQL to find it – sure SQL Developer does it all in the GUI but it’s nice to know how to do it in code, so here goes

select * from ALL_OBJECTS where OBJECT_NAME = 'SomeTableViewProcOrWhatever'