contentManager.Create -> Object reference not set to an instance of an object

Topics: Troubleshooting
Aug 23, 2013 at 12:50 PM
Hi I am getting an error Object reference not set to an instance of an object when the following line is executed articlePart.As<ArticlePart>().ArticleId = article.id;. and I cannot figure what I am missing as the exception is not giving sufficient information.

Below you can see the full code.
[1]

--Migrations

public int Create() {
    SchemaBuilder.CreateTable("ArticlePartRecord", builder => builder
        .ContentPartRecord()
        .Column<string>("ArticleId")
        .Column<string>("Pair")
        .Column<DateTime>("PubDate")
        .Column<string>("Provider")
        .Column<string>("Market")
        .Column<string>("Headline")
        .Column<string>("Title")
        .Column<string>("Content")
        .Column<string>("Summary")
    );
}

public int UpdateFrom1()
{
    ContentDefinitionManager.AlterTypeDefinition("Article", builder => builder.WithPart("ArticlePart").Draftable());
}   

[2]
private readonly IContentManager _contentManager;

public AController(IContentManager contentManager)
{
    _contentManager = contentManager;
}

[3]
public class ArticlePartHandler : ContentHandler 
    {
        public ArticlePartHandler(IRepository<ArticlePartRecord> repository)
        {
            Filters.Add(StorageFilter.For(repository));
        }
    }   

[4]
var articlePart = _contentManager.Create("Article", VersionOptions.AllVersions);                    
articlePart.As<ArticlePart>().ArticleId = article.id;     ----Object reference not set to an instance of an object.
articlePart.As<ArticlePart>().Pair = article.pair;
articlePart.As<ArticlePart>().PubDate = article.pubDate;
articlePart.As<ArticlePart>().Provider = article.provider;
Aug 23, 2013 at 2:22 PM
I have added the below driver for article, but when I run my code at the end I am getting the below exception. Any suggestions will be highly appreciated.
public class ArticlePartDriver : ContentPartDriver<ArticlePart>
    {
        private readonly IOrchardServices _services;

        public ArticlePartDriver(IOrchardServices services)
        {
            _services = services;
            T = NullLocalizer.Instance;
        }

        public Localizer T { get; set; }
    }
Exception
2013-08-23 16:19:18,968 [8] NHibernate.Util.ADOExceptionReporter - System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near the keyword 'Open'.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at System.Data.SqlClient.SqlCommandSet.ExecuteNonQuery()
   at NHibernate.AdoNet.SqlClientBatchingBatcher.DoExecuteBatch(IDbCommand ps)
ClientConnectionId:ed11df78-dbb5-4263-8260-62670ebe4b22
2013-08-23 16:19:18,976 [8] NHibernate.Util.ADOExceptionReporter - Incorrect syntax near the keyword 'Open'.
2013-08-23 16:19:18,980 [8] NHibernate.Event.Default.AbstractFlushingEventListener - Could not synchronize database state with session
NHibernate.Exceptions.GenericADOException: could not execute batch command.[SQL: SQL not available] ---> System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'Open'.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at System.Data.SqlClient.SqlCommandSet.ExecuteNonQuery()
   at NHibernate.AdoNet.SqlClientBatchingBatcher.DoExecuteBatch(IDbCommand ps)
   --- End of inner exception stack trace ---
   at NHibernate.AdoNet.SqlClientBatchingBatcher.DoExecuteBatch(IDbCommand ps)
   at NHibernate.AdoNet.AbstractBatcher.ExecuteBatchWithTiming(IDbCommand ps)
   at NHibernate.AdoNet.AbstractBatcher.ExecuteBatch()
   at NHibernate.AdoNet.AbstractBatcher.PrepareBatchCommand(CommandType type, SqlString sql, SqlType[] parameterTypes)
   at NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Boolean[] notNull, Int32 j, SqlCommandInfo sql, Object obj, ISessionImplementor session)
   at NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Object obj, ISessionImplementor session)
   at NHibernate.Action.EntityInsertAction.Execute()
   at NHibernate.Engine.ActionQueue.Execute(IExecutable executable)
   at NHibernate.Engine.ActionQueue.ExecuteActions(IList list)
   at NHibernate.Engine.ActionQueue.ExecuteActions()
   at NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource session)
2013-08-23 16:19:18,986 [8] NHibernate.Transaction.ITransactionFactory - DTC transaction prepre phase failed
NHibernate.Exceptions.GenericADOException: could not execute batch command.[SQL: SQL not available] ---> System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'Open'.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at System.Data.SqlClient.SqlCommandSet.ExecuteNonQuery()
   at NHibernate.AdoNet.SqlClientBatchingBatcher.DoExecuteBatch(IDbCommand ps)
   --- End of inner exception stack trace ---
   at NHibernate.AdoNet.SqlClientBatchingBatcher.DoExecuteBatch(IDbCommand ps)
   at NHibernate.AdoNet.AbstractBatcher.ExecuteBatchWithTiming(IDbCommand ps)
   at NHibernate.AdoNet.AbstractBatcher.ExecuteBatch()
   at NHibernate.AdoNet.AbstractBatcher.PrepareBatchCommand(CommandType type, SqlString sql, SqlType[] parameterTypes)
   at NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Boolean[] notNull, Int32 j, SqlCommandInfo sql, Object obj, ISessionImplementor session)
   at NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Object obj, ISessionImplementor session)
   at NHibernate.Action.EntityInsertAction.Execute()
   at NHibernate.Engine.ActionQueue.Execute(IExecutable executable)
   at NHibernate.Engine.ActionQueue.ExecuteActions(IList list)
   at NHibernate.Engine.ActionQueue.ExecuteActions()
   at NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource session)
   at NHibernate.Event.Default.DefaultFlushEventListener.OnFlush(FlushEvent event)
   at NHibernate.Impl.SessionImpl.Flush()
   at NHibernate.Transaction.AdoNetWithDistributedTransactionFactory.DistributedTransactionContext.System.Transactions.IEnlistmentNotification.Prepare(PreparingEnlistment preparingEnlistment)

Developer
Aug 23, 2013 at 2:33 PM
Can you show me the code for ArticlePart and ArticlePartRecord?
Aug 23, 2013 at 3:30 PM
I found the issue, I uninstall my module, build orchard and then re-install again. I do have another question though if you can help me.

After the article record is created, I am checking in db and try to get it but its null as the transaction has not been yet commited as a result I cannot linked the charts with the article as shown below. Any idea?
var articlePart = _contentManager.Create("Article");
articlePart.As<ArticlePart>().ArticleId = article.id;
articlePart.As<ArticlePart>().Pair = article.pair;
articlePart.As<ArticlePart>().PubDate = article.pubDate;
articlePart.As<ArticlePart>().Provider = article.provider;
articlePart.As<ArticlePart>().Market = article.market;
articlePart.As<ArticlePart>().Headline = article.headline;
articlePart.As<ArticlePart>().Title = article.title;
articlePart.As<ArticlePart>().Content = article.content;
articlePart.As<ArticlePart>().Summary = article.summary;

var _article =  (from s in _repository.Table.ToList()
                 where s.ArticleId == article.id
                 select s).FirstOrDefault();                    

if (article.charts != null)
{
    foreach(var c in article.charts)
    {                            
        var chartPart = _contentManager.Create("Chart");
        chartPart.As<ChartPart>().Path = c.path;
        chartPart.As<ChartPart>().Url = c.url;
        chartPart.As<ChartPart>().Article = _article;                            
        _contentManager.Create(chartPart);                            
    }                        
}
Developer
Aug 23, 2013 at 6:07 PM
Edited Aug 23, 2013 at 6:11 PM
What you see is a totally correct behavior. The updated data has not yet been stored at the moment you perform query on the repository. Updating record fields does not automatically update the database.

In order to make it work you need to change this:
var articlePart = _contentManager.Create("Article");
<assignments>
to
var articlePart = _contentManager.New("Article");
<assignments>
 _contentManager.Create(articlePart);
This way all record data will get pushed to the database when Create is called and your repository query will work.

There is also an error in the loop below - do not call _contentManager.Create twice - call _contentManager.New at the beginning and _contentManager.Create at the end instead.
Aug 26, 2013 at 10:09 AM
That worked, it would be great if responses like the above were in the documentation :)
Coordinator
Aug 26, 2013 at 10:24 PM
Sure, documentation is a public GitHub repository ;)