.NET and ColdFusion: Yes, We Can Work Together!
While working on a ColdFusion project, you might find a library someone has made that does exactly what you need and will save you lots of development time and money, but it’s written in .NET. Problem right? Not with ColdFusion 8. You can now access .NET assemblies as easily you can other ColdFusion components.
Take a look at the following C# class:
using System;
using System.IO;
using System.Text;
namespace Sanative
{
public class TempFolder
{
private string tempPath = Environment.GetEnvironmentVariable("TEMP");
private DirectoryInfo tempDirectory;
public TempFolder()
{
tempDirectory = new DirectoryInfo(tempPath);
}
public long GetSize()
{
return GetSize(tempDirectory);
}
public long GetSize(DirectoryInfo directory)
{
long size = 0;
foreach (FileInfo file in directory.GetFiles())
{
size += file.Length;
}
foreach (DirectoryInfo dir in directory.GetDirectories())
{
size += GetSize(dir);
}
return size;
}
}
}
Whenever GetSize() is called in the code, it will look at the folder that is set in the TEMP system variable in Windows and then return the amount of space on the disk that its files and folders take up.
This class will need to be compiled into a DLL so ColdFusion can access it. I compiled it to “F:\assemblies\TempFolder.dll”. It’s probably a good idea to keep your .NET assemblies in a central location outside of your webroot.
As you can see in the following ColdFusion code it’s very easy to consume the TempFolder class.
<cfscript>
tempFolder = CreateObject(".NET","Sanative.TempFolder",
"F:\assemblies\TempFolder.dll");
Writeoutput(tempFolder.getSize());
</cfscript>
The argument for the object type can either be “.NET” or “dotnet”. The second argument, for the class name, must include the namespace for the class or an exception will be thrown. The last argument is the full path to the assembly which contains the class. (Note: you can reference more than one assembly, if needed, separated by commas. Also, if you need to access any of the .NET core classes, such as “System.Environment” core classes, or any classes that are contained in assemblies in the global assembly cache, you do not need to specify the assembly argument.)
The first time a .NET class is called, ColdFusion will generate proxy Java classes to use with its built in Java/.NET bridge. The .NET Integration service will need stopped if any updates need to be made to the assembly.
There are some data conversion gotchas as well as some limitations because of going back and forth from Java to .NET. Full information about them as well as how to call .NET classes and assemblies that are located on a different server can be located on the Adobe ColdFusion 8 Livedocs at http://livedocs.adobe.com/coldfusion/8/htmldocs/dotNet_01.html
Sample Files
0 comments - Posted by Jeff Anderson at 4:23 PM - Categories:
