Add document to record

Simple code snippet to add a document attachment to a record:

static void addDoc( Common common,
                    DocuTypeId docuTypeId,
                    FileName fileName)
{
    DocuRef docuRef;
    DocuValue docuValue;

    if(common && docuTypeId)
    {
        ttsBegin;
        docuRef.clear();
        docuRef.initValue();
        docuRef.TypeId = docuTypeId;
        docuRef.Name = filename;
        docuRef.RefRecId = common.RecId;
        docuRef.RefTableId = common.TableId;
        docuRef.RefCompanyId = curext();
        docuValue.initFromDocuRef(docuRef);
        docuValue.insert();
        docuRef.ValueRecId = docuValue.RecId;
        docuRef.insert();
        ttsCommit;
        if(filename)
        {
            DocuValue::writeDocuValue(docuRef,filename); //after ttsCommit to enable catching of file system errors
        }
    }
}

Edit System Fields

Simple example for creating a record with systems fields set by code:

protected static server CaseLog createCaseLog(RefRecId _caseDatail, CreatedBy _createdBy, CreatedDateTime _createdDateTime)
{
    CaseLog caseLog;
    if(_createdBy && _caseDatail)
    {
        caseLog.initValue();
        caseLog.CaseRecId = _caseDatail;
        new OverwriteSystemFieldsPermission().assert();
        caseLog.overwriteSystemfields(true);
        caseLog.(fieldNum(CaseLog,CreatedBy)) = _createdBy;
        caseLog.(fieldNum(CaseLog,CreatedDateTime)) = _createdDateTime;
        caseLog.doInsert();
        caseLog.overwriteSystemfields(false);
        CodeAccessPermission::revertAssert();
    }
    return caseLog;
}