Add attachments to Document

Daniel Steuernol asked on August 14, 2014 18:52

I'm trying to add attachments to a document and I'm unable to do so via the api. I have a page that is using angularjs to build a form and submit it. The files are stored in session until the form is submitted, when the form is submitted I'm pulling the files out of session and trying to attach them to the new document that was created, but it's not working correctly and throwing an exception on node.Update(). Here is the code.

foreach (var kvp in (Dictionary<string, byte[]>)context.Session[attachmentKey])
{
    var temp = Path.GetTempPath();
    var tempFile = Path.Combine(temp, kvp.Key);
    File.WriteAllBytes(tempFile, kvp.Value);
    DocumentHelper.AddAttachment(node, "Attachments", tempFile, provider);
    node.Update();
    File.Delete(tempFile);
}

Here is the exception message: Object must implement IConvertible.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Object must implement IConvertible.

and StackTrace

[InvalidCastException: Object must implement IConvertible.]  
System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider) +14391443   
System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType, Boolean& coercedToDataFeed, Boolean& typeChanged, Boolean allowStreaming) +947
[InvalidCastException: Failed to convert parameter value from a Guid to a String.]  
System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType, Boolean& coercedToDataFeed, Boolean& typeChanged, Boolean allowStreaming) +6735515   
System.Data.SqlClient.SqlParameter.GetCoercedValue() +159
System.Data.SqlClient.SqlParameter.Validate(Int32 index, Boolean isCommandProc) +322
System.Data.SqlClient.SqlCommand.BuildParamList(TdsParser parser, SqlParameterCollection parameters) +246
System.Data.SqlClient.SqlCommand.BuildExecuteSql(CommandBehavior behavior, String commandText, SqlParameterCollection parameters, _SqlRPC& rpc) +295
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) +6741487
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +586
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +107
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +288
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +180   System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior) +21
System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +325
System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) +420
System.Data.Common.DbDataAdapter.Fill(DataSet dataSet) +278
CMS.DataEngine.AbstractDataConnection.ExecuteQuery(String queryText, QueryDataParameters queryParams, QueryTypeEnum queryType, Boolean requiresTransaction) +419
CMS.DataEngine.GeneralConnection.RunQuery(QueryParameters query) +415
CMS.DataEngine.GeneralConnection.ExecuteQueryInternal(QueryParameters query) +401
CMS.DataEngine.GeneralConnection.ExecuteQuery(String queryName, QueryDataParameters parameters, QueryMacros macros, Int32 offset, Int32 maxRecords, Int32& totalRecords) +63
CMS.DataEngine.DataQueryBase`1.GetDataFromDB() +278
CMS.DataEngine.DataQueryBase`1.GetData() +128
CMS.DataEngine.DataQueryBase`1.get_Result() +98
CMS.DataEngine.ConnectionHelper.ExecuteQuery(String queryName, QueryDataParameters parameters, String where, String orderBy, Int32 topN, String columns, Int32 offset, Int32 maxRecords, Int32& totalRecords) +212
CMS.DataEngine.SimpleDataClass.Update() +199
CMS.DataEngine.AbstractInfo`1.UpdateData() +487
CMS.DataEngine.AbstractInfoProvider`2.SetInfo(TInfo info) +759
CMS.DocumentEngine.TreeNode.UpdateInternal() +5570
CMS.DocumentEngine.TreeNode.Update(Boolean useDocumentHelper) +224
CMS.DocumentEngine.DocumentHelper.UpdateDocument(TreeNode node, TreeProvider tree, String updateColumns) +550
CMS.DocumentEngine.TreeNode.Update(Boolean useDocumentHelper) +180
CMSApp.hubcap.Handlers.SubmitEvent.ProcessRequest(HttpContext context) in c:\projects\hubcap\CMS\hubcap\Handlers\SubmitEvent.ashx.cs:109
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +913
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +165

Recent Answers


Joshua Adams answered on August 14, 2014 22:35

You may have to create an instance of the AttachmentInfo class, then try to use the document helper to attach the attachment.

0 votesVote for this answer Mark as a Correct answer

Daniel Steuernol answered on August 14, 2014 22:38

That was my original attempt, using the other overload for DocumentHelper.AddAttachment and I had the same error on the node.Update() line, so I re-wrote it to save the file out to disk and then import.

0 votesVote for this answer Mark as a Correct answer

Joshua Adams answered on August 14, 2014 22:44

I think if you are using the DocumentHelper and Kentico API, I would imagine creating an AttachmentInfo Object would have to be done regardless. Were you getting the same error or was it different? When you debug, where exactly does it break, and can you step into the node.Update() method?

0 votesVote for this answer Mark as a Correct answer

Daniel Steuernol answered on August 15, 2014 18:18

So changing the code to the following

foreach (var kvp in (Dictionary<string, byte[]>)context.Session[attachmentKey])
{
    var guid = Guid.NewGuid();
    var newAttachment = new AttachmentInfo
    {
        AttachmentBinary = kvp.Value,
        AttachmentDocumentID = node.DocumentID,
        AttachmentExtension = Path.GetExtension(kvp.Key),
        AttachmentSize = kvp.Value.Length,
        AttachmentName = kvp.Key,
        AttachmentMimeType = MimeTypeHelper.GetMimetype(Path.GetExtension(kvp.Key)),
        AttachmentTitle = kvp.Key,
        AttachmentDescription = "",
        AttachmentSiteID = SiteContext.CurrentSiteID,
        AttachmentGUID = guid
    };
    DocumentHelper.AddAttachment(node, "Attachments", guid, groupGuid, newAttachment, provider);
    node.Update();
}

I get the same error on the node.Update() line.

0 votesVote for this answer Mark as a Correct answer

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