DataClassInfo System.NullReferenceException

Patrick Thompson asked on May 17, 2023 16:13

Hi, I have created a .net core Console application to communicate with a kentico 13 MVC Application. I am trying to add a field to an existing Online Form / Biz Form. but when ever I Update the DataClassInfo object I get a System.NullReferenceException. I can pull data and update with other api components. I havent been able to get DataClassInfo to work correctly. I am not really sure what I am Missing. Code Example:

DataClassInfo dci = DataClassInfoProvider.GetDataClassInfo("FORM CLASS ID");
FormInfo fi = new FormInfo(dci.ClassFormDefinition);
TableManager tm = new TableManager(null); // Create Table Manager Object   
FormFieldInfo field = new FormFieldInfo(); // New Form Field Object

field.Name = "TEST";
field.Caption = "TEST";
field.AllowEmpty = true;
field.System = false;
field.Visible = true;
field.Enabled = true;
field.DataType = "nvarchar";
field.Size = 500;
field.Settings.Add("componentidentifier", "Kentico.TextInput");

fi.AddFormItem(field);
tm.AddTableColumn(dci.ClassTableName, field.Name, field.DataType + "(" + field.Size + ")", 
                  field.AllowEmpty, null);

fi.UpdateExistingFields(fi);
dci.ClassFormDefinition = fi.GetXmlDefinition();
dci.Update(); <------ Error Occurs Here
//DataClassInfoProvider.SetDataClassInfo(dci); <------ Also occurs On Set

Error: Exception Thrown - System.NullReferenceException: 'Object reference not set to an instance of an object.'

Recent Answers


Brenden Kehren answered on May 19, 2023 16:49

You might want to add some null checks in there to make sure you aren't erroring out prior because of null values.

Here's some code we use:

DataClassInfo dci = DataClassInfoProvider.GetDataClassInfo(<classID>);
if (dci != null)
{
    FormInfo fi = new FormInfo(dci.ClassFormDefinition);
    if (fi != null)
    {
        if (!fi.FieldExists(<yourFieldName>))
        {
            FormFieldInfo ffi1 = new FormFieldInfo()
            {
                Name = trackingFieldName,
                AllowEmpty = false,
                DefaultValue = "0",
                System = true, // don't let them delete it
                FieldType = FormFieldControlTypeEnum.CalendarControl,
                Visible = false,
                Caption = "Date sent to integration point",
                Enabled = true,
                DataType = "datetime",
                Precision = 0
            };
            fi.AddFormItem(ffi1);

            TableManager tm = new TableManager("CMSConnectionString");
            tm.AddTableColumn(dci.ClassTableName, ffi2.Name, "datetime2", false, "0");
            dci.ClassXmlSchema = tm.GetXmlSchema(dci.ClassTableName);
            dci.ClassFormDefinition = fi.GetXmlDefinition();
            FormHelper.UpdateInheritedClasses(dci);
        }
    }
}
0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.