Posts Tagged ‘.NET Framework’

.Net Framework Logo

Image via Wikipedia

.NET extension methods are very useful. Here is one that I am using frequently in a current project –

I want to trim a string of extra spaces at the ends, then check to see if it is empty. If it is empty I want to assign a default value.

With .NET extension methods, it makes it easy to create a peice of reusable code that can be called like any method.

    public static class StringExtensions
    {
        /// <summary>
        /// If the current string (trimmed) is empty then return the default string
        /// </summary>
        /// <param name=”currentString”>The current string value</param>
        /// <param name=”defaultString”>The string to return if the current string is empty</param>
        /// <returns></returns>
        public static string DefaultIfEmpty(this string currentString, string defaultString)
        {
            if (currentString.Trim() == string.Empty)
            {
                return defaultString;
            }
            else
            {
                return currentString.Trim();
            }
        }
    }

The preceding word ‘this’ in the parameter declaration means that you can call this method on any string.

Example using the new extension –

string myString = ” “;

myString.DefaultIfEmpty(“I was empty”);

Connecting to an Oracle database without installing an Oracle client software package on the server/client deployment environment:

Some application deployments to clients or servers require database connections to Oracle instances. What happens when the deployment environment doesn’t have the Oracle client software loaded? What if the server configurations are not accessible, or it takes an act of congress to install anything to the environment?

In this example I am adding  ‘instant client’ support to a .net application using the ODP.NET driver but other drivers can leverage the instant client. Also, I am using the latest ODP.NET driver for the .NET 4 framework, as it supports the Entity framework =)

Required software –

  • Oracle Instant Client
  • Oracle ODP.NET (or your preferred Oracles driver that is supported by Instant Client)

http://www.oracle.com/technetwork/indexes/downloads/index.html

In your .net application, add the following 5 DLLs (from the Oracle download) to the root directory of your project and configure the properties of each to ‘Copy if newer’.

  • ODP.NET Drivers
    • OraOps11w.dll
    • Oracle.DataAccess.dll (if this is in your ref folder, set the property to ‘Copy Locally’
  • Instant Client Files (Depending on the version you downloaded, you only need one set)
    • Basic
      • oci.dll
      • orannzsbb11.dll
      • oraociei11.dll (111M)
    • Light
      • oci.dll
      • orannzsbb11.dll
      • oraociicus11.dll (~31M)

 If you are using Entities or need access to the factory in ODP.NET, you’ll need to register the provider in the web.config (*check the version of your driver to be sure it matches) –

<system.data>
<DbProviderFactories>
<add name="Oracle Data Provider for .NET"  
invariant="Oracle.DataAccess.Client" 
description="Oracle Data Provider for .NET" 
type="Oracle.DataAccess.Client.OracleClientFactory, Oracle.DataAccess, Version=4.112.2.30, PublicKeyToken=89b483f429c47342" />
</DbProviderFactories>
</system.data>

 When you build/deploy your application, the 5 DLLs should be in the web app bin folder, or if you are building a client app – they should be in the same folder as the exe.

If you want to use the TNS-Less connection string format for entities, the Entity connection string may look something like this in the web config –
<add name=”PSDEntities” connectionString=”metadata=res://*/Data.PSD.csdl|res://*/Data.PSD.ssdl|res://*/Data.PSD.msl;provider=Oracle.DataAccess.Client;provider connection string=&quot;DATA SOURCE=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=DBService)));PASSWORD=****;USER ID=****&quot;”
      providerName=”System.Data.EntityClient” />

*notice the &quot; before and after the embedded connection string.

 

References –

Good tutorial with screen shots (http://alderprogs.blogspot.com/2009/04/deploying-odpnet-with-oracle-instant.html)

Oracle’s Developer Guide (http://download.oracle.com/docs/html/E10927_01/InstallODP.htm)

Sometimes when you are developing/debugging an application you may want a different behavior than the release/retail build. The conditional attribute in .NET let’s you do this.

Let us suppose that we have a method that loads data into an object from a remote source like a database. While debugging, you may need to restart the application many times to test different methods or changes. If it takes more than a couple of seconds to load your data, you may want to temporarily cache this data. Since your application needs real-time data in the production environment, the conditional attribute is an easy way to tell the compiler to only call our cache loader while in the DEBUG configuration.

This article is not about how to cache data, but rather how to define a method that is only called when using the debug configuration. In my experience, cached data represents a good opportunity to use the conditional attribute. There are many other situations where this would be helpful.

In this example method, I have applied the the conditional attribute, [Conditional(“DEBUG”)], so that the data is only cached when ‘DEBUG’ is defined. When running the app in Visual Studio, ‘Debug’ can be selected in the active configuration list. This will define debug during compilation for you.

///
/// This method is only called when DEBUG is defined
///
[Conditional("DEBUG")]
private void CacheIfDebug()
{
if (File.Exists(@"C:\cachedPSDFileData.xml"))
{
entireFileTree = XElement.Load(@"C:\cachedPSDFileData.xml");
}
else
{
setEntireFileTree();
entireFileTree.Save(@"C:\cachedPSDFileData.xml");
}
}

In the example below, when using the ‘Debug’ configuration, both methods will execute. When using ‘Release’ configuration, only the second method will be called. Since the ‘CacheIfDebug’ method has been decorated with the conditional attribute, the compiler removes references to it. For this reason, methods decorated with the conditional attribute must be ‘void’ return type.

private void DoSomething()
{
CacheIfDebug();
DoSomethingElse();
}

Using the conditional attribute makes it easy to debug and deploy without changing your code for each environment.
For more information about the conditional attribute check out these links.

http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx

http://community.bartdesmet.net/blogs/bart/archive/2006/08/30/4368.aspx