Using the .NET API to Clone a Record

Less than one minute read time.

One of the Sage 200 development partners had read Jeff Richard's blog post about 'cloning' records in the COM API, (Using the COM API to Clone a Record) and asked if there was a .NET API version. As far as I could tell there wasn't so I wrote the method you will find below.

You need to add a reference to SageCRMWrapper.dll to do this.


private void CopyRecord(string entityName, int entityId)
{
Sage.CRM.Utils.TableInfo tableInfo = Metadata.GetTableInfo(entityName);
Sage.CRM.Data.Record existingRecord = FindRecord(entityName, String.Format("{0}={1}", tableInfo.IdField, entityId));
existingRecord.GoToFirst();
Sage.CRM.Data.Record newRecord = new Sage.CRM.Data.Record(entityName);

Sage.CRM.Wrapper.IeWareRecord enumerableExistingRecord = GetEnumerableRecord(existingRecord);
Sage.CRM.Wrapper.IeWareRecord enumerableNewRecord = GetEnumerableRecord(newRecord);

foreach (object i in enumerableExistingRecord)
{
string p = i.ToString();
if (p != tableInfo.IdField)
{
try
{
enumerableNewRecord[p] = enumerableExistingRecord[p];
}
catch (Exception ex)
{
//handle exception
}
}
}
enumerableNewRecord.SaveChanges();

}

private Sage.CRM.Wrapper.IeWareRecord GetEnumerableRecord(Sage.CRM.Data.Record rec)
{
System.Type t = rec.GetType();
System.Reflection.MethodInfo mi = t.GetMethod("GetInternalEntity", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
return (Sage.CRM.Wrapper.IeWareRecord)mi.Invoke(rec, new object[] { });
}