12 February 2010

C#: Add history to an ACT! Group (and contacts)

My current project requires interaction with ACT!, both retrieving and setting data. 
Working with the ACT! framework is an interesting experience.  The code is very verbose and requires some expertise to understand.  And it took me a while to realize that the best way to retrieve data is through the database, while using the framework to perform the updates.
The following method writes an email history to the database.  It is useful for when you need to record automated processes to groups in the database. 
The method takes a GUID as an argument, primarily because there are no unique naming constraints in the group list.

using Act.Framework;
using Act.Framework.Contacts;
using Act.Framework.Groups;
using Act.Framework.Histories;
using Act.Framework.Lookups;
using Act.Shared.Collections;
 
// simplified connection for multiple methods
privateActFramework actFramework() {
    string cn = ConfigurationManager.ConnectionStrings["actDb"].ConnectionString;
    string login = ConfigurationManager.AppSettings["actLogin"].ToString();
    string pwd = ConfigurationManager.AppSettings["actPwd"].ToString();
ActFramework f = newActFramework();
f.LogOn(cn, login, pwd);
 
    return f;
}
// adds email history to the database
public void AddEmailGroupHistory(string GUID, string subject, string body) {
 
    // create a disposable connection to the database

    using(ActFramework f = actFramework()) {
 
    // create a new group GUID array with one element
Guid[] gGuid = new Guid[] { new Guid(GUID) };
    // get a group list - the list will contain one group
GroupList gList = f.Groups.GetGroupsByID(null, gGuid);
    // get a contact list from the first group in the list
ContactList cList = gList[0].GetContacts(null);
    // creates an all-zero GUID
Guid activityClearedId = Guid.Empty;
    // creates a system type of Email sent
HistoryType hType = new HistoryType(SystemHistoryType.EmailSent);
    // the history is public
    bool isPrivate = false;
    // start and emd (duration) are equal
DateTime startEnd = DateTime.Now;
    // Create a new history object
History h = f.Histories.CreateHistory(cList, gList, activityClearedId,
hType, isPrivate, startEnd, startEnd, subject, body);
    // commit the history to the database
h.Update();
}
}