GetField Equaivalent for C# using Generics

Many people who customize SalesLogix have become accustomed to using the built in “SLX Database Support” script to provide things like the quick and easy GetField function to return a single database value. If you’ve ventured into the .NET Extensions realm, you might want an easy equivalent. The following is a repost of something I posted around a year ago in the Sage Business Partner newsgroups:

QUESTION:
Does anyone have a generic GetField function for C# .Net? One that can handle N DataTypes, Nulls, DbNull, etc.? I am playing with the SLX VB script function, and it doesn’t adapt well to the strongly typed fields of C# .NET. Specifically the ExecuteScalar() blows up on 1) TheValue has no type 2) can’t handle nulls 3) can’t handle int….Any ideas or do I need specific GetFieldInt, GetFieldDateTime, GetFieldString stuff?

This is why we have generics! You could implement the GetField method as method that returns a generic type. That would be the best way to do it! Here’s a quick sample:

public T GetField<T>(string Field, string Table, string Where)
{
    string sql = string.Format("select {0} from {1} where {2}", Field, Table, (Where.Equals(string.Empty) ? "1=1" : Where));

    using (OleDbConnection conn = new OleDbConnection(SlxConnectionString))
    {
        conn.Open();
        using (OleDbCommand cmd = new OleDbCommand(sql, conn))
        {
            object fieldval = cmd.ExecuteScalar();
            return fieldval == DBNull.Value ? default(T) : (T)fieldval;
        }
    }
}

Now to use it, you’ll specify the type like this:

// for a string field
string accname = GetField<string>("account", "account", "accountid = '" + accid + "'");

// or for an int field
int numemp = GetField<int>("employees", "account", "accountid = '" + accid + "'");

//or for a datetime field
DateTime createdon = GetField<DateTime>("createdate", "account", "accountid = '" + accid + "'");

Get the idea? How’s that for cool?! [:)]

 

ABOUT THE AUTHOR

Ryan Farley

Ryan Farley is the Director of Development for Customer FX and creator of slxdeveloper.com. He's been blogging regularly about SalesLogix, now Infor CRM, since 2001 and believes in sharing with the community. His new passion for CRM is Creatio, formerly bpm'online. He loves C#, Javascript, web development, open source, and Linux. He also loves his hobby as an amateur filmmaker.

1 Comment

  1. Perfect… Thank Ryan

    Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe To Our Newsletter

Join our mailing list to receive the latest Infor CRM (Saleslogix) and Creatio (bpm'online) news and product updates!

You have Successfully Subscribed!