Simple.Data Insert Object - List initializers must contain at least one initializer - simple.data

When I run the following code :
var db = Database.Open();
var contact = new Contact() {FirstName = "Mark", LastName = "Rendle"} ;
db.Contacts.Insert(contact);
I get an error :
List initializers must contain at least one initializer
Stack Trace :
at System.Linq.Expressions.Expression.ListInit(NewExpression newExpression, IEnumerable1 initializers)
at Simple.Data.Extensions.ObjectEx.MakeToDictionaryFunc(Type type)
at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory)
at Simple.Data.Extensions.ObjectEx.ObjectToDictionary(Object obj)
at Simple.Data.Commands.InsertCommand.InsertEntity(Object entity, DataStrategy dataStrategy, String tableName, ErrorCallback onError, Boolean resultRequired)
at Simple.Data.Commands.InsertCommand.DoInsert(InvokeMemberBinder binder, Object[] args, DataStrategy dataStrategy, String tableName)
at Simple.Data.Commands.InsertCommand.Execute(DataStrategy dataStrategy, DynamicTable table, InvokeMemberBinder binder, Object[] args)
at Simple.Data.DynamicTable.TryInvokeMember(InvokeMemberBinder binder, Object[] args, Object& result)
at Simple.Data.ObjectReference.TryInvokeMember(InvokeMemberBinder binder, Object[] args, Object& result)
at CallSite.Target(Closure , CallSite , Object , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid2[T0,T1](CallSite site, T0 arg0, T1 arg1)
at ProjectXBaseDataImporter.DataSaver.PersistContacts(IEnumerable1 contactsx) in c:\Code\XXX\ProjectXBaseDataImporter\ProjectXBaseDataImporter\CSVImporter.cs:line 54
at ProjectXBaseDataImporter.DataImporter.Import[T](String filePath) in c:\Code\XXX\ProjectXBaseDataImporter\ProjectXBaseDataImporter\CSVImporter.cs:line 77
at ProjectXBaseDataImporter.DataImporter_Test.Import() in c:\Code\XXX\ProjectXBaseDataImporter\ProjectXBaseDataImporter\CSVImporter_Test.cs:line 32

Error on my part.
Another Library I am using requires classes to have fields opposed to properties.
I was coding against the fields not properties.

Related

What is causing the "Unable to cast object of type 'System.Data.Entity.DynamicProxies" error

I have the following POST edit action method:-
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(RackJoin rj,FormCollection formValues)
{
try
{
if (ModelState.IsValid)
{
repository.InsertOrUpdateRack(rj.Rack, User.Identity.Name, rj.Resource.RESOURCEID);
repository.Save();
return RedirectToAction("Index");
}
}
catch (DbUpdateConcurrencyException ex)
{
var entry = ex.Entries.Single();
var databaseValues = (Rack)entry.GetDatabaseValues().ToObject();
var clientValues = (Rack)entry.Entity;
var entry2 = ex.Entries.Single();
var databaseValues2 = (Resource)entry2.GetDatabaseValues().ToObject();
var clientValues2 = (Resource)entry2.Entity;
if (databaseValues.RU != clientValues.RU)
ModelState.AddModelError("Rack.RU", "Current value: "
+ databaseValues.RU);
but when the DbUpdateConcurrencyException exception is raised i am getting the following exception on the following line of code var databaseValues2 = (Resource)entry2.GetDatabaseValues().ToObject();:-
Unable to cast object of type 'System.Data.Entity.DynamicProxies.Rack_81556130B3DB7E3D4F63B9FF3F15832A81A86055EED840211E95A71E1342027D' to type 'TMS.Models.Resource'.
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: Unable to cast object of type 'System.Data.Entity.DynamicProxies.Rack_81556130B3DB7E3D4F63B9FF3F15832A81A86055EED840211E95A71E1342027D' to type 'TMS.Models.Resource'.
Source Error:
Line 175: var clientValues = (Rack)entry.Entity;
Line 176: var entry2 = ex.Entries.Single();
Line 177: var databaseValues2 = (Resource)entry2.GetDatabaseValues().ToObject();
Line 178: var clientValues2 = (Resource)entry2.Entity;
Line 179:
Source File: c:\Users\Administrator\Documents\Visual Studio 2012\Projects\TMS\TMS\Controllers\RackController.cs Line: 177
Stack Trace:
[InvalidCastException: Unable to cast object of type 'System.Data.Entity.DynamicProxies.Rack_81556130B3DB7E3D4F63B9FF3F15832A81A86055EED840211E95A71E1342027D' to type 'TMS.Models.Resource'.]
TMS.Controllers.RackController.Edit(RackJoin rj, FormCollection formValues) in c:\Users\Administrator\Documents\Visual Studio 2012\Projects\TMS\TMS\Controllers\RackController.cs:177
lambda_method(Closure , ControllerBase , Object[] ) +245
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +59
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +435
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +60
System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeSynchronousActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +50
System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +75
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +44
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +139
I'm not entirely clear what's going on in this section of code, are you meant to be retrieving the Resource from the second context you mentioned in your comment?
var entry = ex.Entries.Single();
var databaseValues = (Rack)entry.GetDatabaseValues().ToObject();
var clientValues = (Rack)entry.Entity;
var entry2 = ex.Entries.Single();
var databaseValues2 = (Resource)entry2.GetDatabaseValues().ToObject();
var clientValues2 = (Resource)entry2.Entity;
If you called Single() on a sequence that contained more than one element, you would generate an exception; since Single isn't generating an exception, you only have one entry present which you're using in both cases.
In the first you want to treat it as a Rack, which doesn't seem to generate a complaint. In the second, you're treating it as a Resource, which seems to be incompatible with Rack, the cause of your complaint.
InvalidCastException: Unable to cast object of type 'System.Data.Entity.DynamicProxies.Rack_81...' to type 'TMS.Models.Resource'.]
The reason your exception only contains that particular entity may well be found in your InsertOrUpdateRack method.

ThreadAbortException in ASP.NET + SQLite

I am facing this problem a while. Sometimes (just sometimes) i am getting ThreadAbortException in Page_PreRender of one my aspx pages.
this is so odd, i get it sometimes in somedays. I am using SQLite with NHibernate in an asp.net website hosting in a shared webhost.
The exception is :
System.Threading.ThreadAbortException: Thread was being aborted.
at System.Data.SQLite.SQLite3.Step(SQLiteStatement stmt)
at System.Data.SQLite.SQLiteDataReader.NextResult()
at System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavior behave)
at System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.SQLite.SQLiteCommand.ExecuteNonQuery()
at NHibernate.AdoNet.AbstractBatcher.ExecuteNonQuery(IDbCommand cmd)
at NHibernate.AdoNet.NonBatchingBatcher.AddToBatch(IExpectation expectation)
at NHibernate.Persister.Entity.AbstractEntityPersister.Update(Object id, Object[] fields, Object[] oldFields, Object rowId, Boolean[] includeProperty, Int32 j, Object oldVersion, Object obj, SqlCommandInfo sql, ISessionImplementor session)
at NHibernate.Persister.Entity.AbstractEntityPersister.UpdateOrInsert(Object id, Object[] fields, Object[] oldFields, Object rowId, Boolean[] includeProperty, Int32 j, Object oldVersion, Object obj, SqlCommandInfo sql, ISessionImplementor session)
at NHibernate.Persister.Entity.AbstractEntityPersister.Update(Object id, Object[] fields, Int32[] dirtyFields, Boolean hasDirtyCollection, Object[] oldFields, Object oldVersion, Object obj, Object rowId, ISessionImplementor session)
at NHibernate.Action.EntityUpdateAction.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()
do you have any idea ??
It's possible that your code took too long to execute (because of too much data, or because SQLite is waiting for another thread's lock on the database).
Try increasing httpRuntime's executionTimeout in the web.config.

Checkbox Helper: Odd string to bool conversion error

I've a web using asp.net MVC 3 with razor.
In one view I'm having an odd error with the checkbox helper.
Here is the razor code:
#Html.CheckBox("rememberPassword", Model.RememberPassword, new { tabindex = "4", style = "width:15px" })
The property in the model (which I set to true in the Model constructor):
public bool RememberPassword { get; set; }
And the logged error:
2012-04-13 01:20:33.334 [13 ] Error - Reference: 0413-012033-334 - Global site error, page: /es/login
System.InvalidOperationException: The parameter conversion from type 'System.String' to type 'System.Boolean' failed. See the inner exception for more information. ---> System.FormatException: -1' is not a valid value for Boolean. ---> System.FormatException: String was not recognized as a valid Boolean.
at System.Boolean.Parse(String value)
at System.ComponentModel.BooleanConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
--- End of inner exception stack trace ---
at System.ComponentModel.BooleanConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
at System.Web.Mvc.ValueProviderResult.ConvertSimpleType(CultureInfo culture, Object value, Type destinationType)
--- End of inner exception stack trace ---
at System.Web.Mvc.ValueProviderResult.ConvertSimpleType(CultureInfo culture, Object value, Type destinationType)
at System.Web.Mvc.ValueProviderResult.UnwrapPossibleArrayType(CultureInfo culture, Object value, Type destinationType)
at System.Web.Mvc.ValueProviderResult.ConvertTo(Type type, CultureInfo culture)
at System.Web.Mvc.HtmlHelper.GetModelStateValue(String key, Type destinationType)
at System.Web.Mvc.Html.InputExtensions.InputHelper(HtmlHelper htmlHelper, InputType inputType, ModelMetadata metadata, String name, Object value, Boolean useViewData, Boolean isChecked, Boolean setId, Boolean isExplicitValue, IDictionary`2 htmlAttributes)
at System.Web.Mvc.Html.InputExtensions.CheckBoxHelper(HtmlHelper htmlHelper, ModelMetadata metadata, String name, Nullable`1 isChecked, IDictionary`2 htmlAttributes)
at System.Web.Mvc.Html.InputExtensions.CheckBox(HtmlHelper htmlHelper, String name, Boolean isChecked, Object htmlAttributes)
at ASP._Page_Views_Login_Index_cshtml.Execute() in d:\[...]\Views\Login\Index.cshtml:line 49
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
at System.Web.WebPages.StartPage.RunPage()
at System.Web.WebPages.StartPage.ExecutePageHierarchy()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1c.<>c__DisplayClass1e.<InvokeActionResultWithFilters>b__1b()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
Why is this happening?
Note:
It keeps getting odder and odder. As magically as the error started appearing (in a productive site some day without any updates or releases) not it has stopped. It's been three days without the error. However, I'd still like to know why was it.
It had nothing to do with the way of creating the checkbox. In some very odd scenarios (which I had forgotten at all), this forms may be submitted (from other sites) without this parameter. In this cases the bool field was trying to obtained from the string "-1".
One way of resolving this issue (that I have discovered to be a good practice) is to avoid "not-nullable" fields in the Model.
Just try this instead
Html.CheckBoxFor(model => model.RememberPassword , chkHtmlAttributes)
And define the chkHtmlAttributes to these
tabindex = "4", style = "width:15px"

exception when executing sql command using sqlite in c# on windows phone

my code is like the follow:
SqliteConnection db = new SqliteConnection("uri=file:zongheng.db");db.Open();
SqliteCommand cmd = db.CreateCommand();
cmd.CommandText = "update chapters set status = 0 where bookid=" + bookid + " and chapterid = " + reading_chapter + ";";
cmd.ExecuteNonQuery();
cmd.Dispose();
db.Close();
db.Dispose();
db.Open();
cmd = db.CreateCommand();
cmd.CommandText = ("select max(chapterid), status from chapters where status > 0 and bookid = "+bookid +";");
SqliteDataReader dr = cmd.ExecuteReader(); //exception thrown from here
calling stack is like this:
Community.CsharpSqlite.SQLiteClient.SqliteSyntaxException was unhandled
Message=unable to open database file
StackTrace:
at Community.CsharpSqlite.SQLiteClient.SqliteCommand.GetNextStatement(String pzStart, String& pzTail, Vdbe& pStmt)
at Community.CsharpSqlite.SQLiteClient.SqliteCommand.ExecuteReader(CommandBehavior behavior, Boolean want_results, Int32& rows_affected)
at Community.CsharpSqlite.SQLiteClient.SqliteCommand.ExecuteReader(CommandBehavior behavior)
at Community.CsharpSqlite.SQLiteClient.SqliteCommand.ExecuteReader()
at ZonghengReader.Content.OnNavigatedTo(NavigationEventArgs e)
at Microsoft.Phone.Controls.PhoneApplicationPage.InternalOnNavigatedTo(NavigationEventArgs e)
at System.Windows.Navigation.NavigationService.RaiseNavigated(Object content, Uri uri, NavigationMode mode, Boolean isNavigationInitiator, PhoneApplicationPage existingContentPage, PhoneApplicationPage newContentPage)
at System.Windows.Navigation.NavigationService.CompleteNavigation(DependencyObject content, NavigationMode mode)
at System.Windows.Navigation.NavigationService.ContentLoader_BeginLoad_Callback(IAsyncResult result)
at System.Windows.Navigation.PageResourceContentLoader.BeginLoad_OnUIThread(AsyncCallback userCallback, PageResourceContentLoaderAsyncResult result)
at System.Windows.Navigation.PageResourceContentLoader.<>c__DisplayClass4.<BeginLoad>b__0(Object args)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at System.Delegate.DynamicInvokeOne(Object[] args)
at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)
at System.Delegate.DynamicInvoke(Object[] args)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority)
at System.Windows.Threading.Dispatcher.OnInvoke(Object context)
at System.Windows.Hosting.CallbackCookie.Invoke(Object[] args)
at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[] args)
at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)
how can i do different queries within the same connection? any advice? or any documentation? any advice would be highly appreciated.
I don't know if this question is answered yet but... in your code sample you dispose of the object:
...
db.Dispose();
db.Open();
...
I honestly think that's your problem in the current context. just remove the Dispose() call on the database connection object and I think you should be fine. Once you are really done with the object you can Dispose() it.

Error Updating Dynamic Entity When Setting Property Value of Type PickList

I've added a custom attribute ("custom_contacttype") to the Contact entity. This attribute is of type picklist which is comprised of seven values. I'm developing using Advanced Developer Extensions for Microsoft Dynamics CRM against CRM 4.0. After I set the value for this attribute and call SaveChanges() I get "Object reference not set to an instance of an object." error. I've been battling this one for a while. What am I doing wrong? Below is my code:
var crm = new CrmDataContext(context.Connection);
var saveContact = crm.GetEntities("contact").Where(p => p.GetPropertyValue<Guid> ("contactid") == contact.Id.Value).Single();
saveContact.SetPropertyValue("custom_contacttype", 2, typeof(Picklist));
crm.UpdateObject(saveContact);
crm.SaveChanges();
Trace Log from CRM Server:
[2011-07-01 16:39:33.7] Process: w3wp |Organization:f827deb3-c6cc-df11-bc07-005056887b79 |Thread: 8 |Category: Platform.Sdk |User: 822138f1-c574-e011-9dca-005056887b79 |Level: Error | PluginStep.Execute
at PluginStep.Execute(PipelineExecutionContext context)
at Pipeline.Execute(PipelineExecutionContext context)
at MessageProcessor.Execute(PipelineExecutionContext context)
at InternalMessageDispatcher.Execute(PipelineExecutionContext context)
at ExternalMessageDispatcher.Execute(String messageName, Int32 primaryObjectTypeCode, Int32 secondaryObjectTypeCode, PropertyBag fields, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId)
at CrmServiceInternal.Update(String namespaceName, BusinessEntityBase entity, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId)
at CrmService.Update(BusinessEntity entity)
at RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at LogicalMethodInfo.Invoke(Object target, Object[] values)
at WebServiceHandler.Invoke()
at WebServiceHandler.CoreProcessRequest()
at SyncSessionlessHandler.ProcessRequest(HttpContext context)
at CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
at ApplicationStepManager.ResumeSteps(Exception error)
at HttpApplication.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
at HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr)
at HttpRuntime.ProcessRequestNoDemand(HttpWorkerRequest wr)
at ISAPIRuntime.ProcessRequest(IntPtr ecb, Int32 iWRType)
Web Service Plug-in failed in SdkMessageProcessingStepId: {27DF4121-19BC-DF11-A90E-005056887B79}; EntityName: contact; Stage: 10; MessageName: Update; AssemblyName: AccessCRM.ChangeLogContactData, AccessCRM, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a030c130976783ab; ClassName: AccessCRM.ChangeLogContactData; Exception: Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
at AccessCRM.PluginUtilities.GetStringValueFromProperty(Property p)
at AccessCRM.ChangeLogContactData.Execute(IPluginExecutionContext context)
at Microsoft.Crm.Extensibility.PluginStep.Execute(PipelineExecutionContext context)
.
[2011-07-01 16:39:33.7] Process: w3wp |Organization:f827deb3-c6cc-df11-bc07-005056887b79 |Thread: 8 |Category: Platform.Sdk |User: 822138f1-c574-e011-9dca-005056887b79 |Level: Error | PluginExecutionExceptionHandler.Handle
at PluginExecutionExceptionHandler.Handle(Stream from, Stream to, Exception exception)
at CompositeSoapExtensionExceptionHandler.Handle(Stream to, Stream from, Exception exception)
at CrmAuthenticationSoapExtensionBase.ProcessMessage(SoapMessage message)
at SoapMessage.RunExtensions(SoapExtension[] extensions, Boolean throwOnException)
at SoapServerProtocol.WriteException(Exception e, Stream outputStream)
at WebServiceHandler.WriteException(Exception e)
at WebServiceHandler.Invoke()
at WebServiceHandler.CoreProcessRequest()
at SyncSessionlessHandler.ProcessRequest(HttpContext context)
at CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
at ApplicationStepManager.ResumeSteps(Exception error)
at HttpApplication.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
at HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr)
at HttpRuntime.ProcessRequestNoDemand(HttpWorkerRequest wr)
at ISAPIRuntime.ProcessRequest(IntPtr ecb, Int32 iWRType)
CrmSoapExtension detected InvalidPluginExecutionException:
System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> Microsoft.Crm.Sdk.InvalidPluginExecutionException: Object reference not set to an instance of an object. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at AccessCRM.PluginUtilities.GetStringValueFromProperty(Property p)
at AccessCRM.ChangeLogContactData.Execute(IPluginExecutionContext context)
at Microsoft.Crm.Extensibility.PluginStep.Execute(PipelineExecutionContext context)
--- End of inner exception stack trace ---
at Microsoft.Crm.Extensibility.PluginStep.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.Pipeline.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.MessageProcessor.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.InternalMessageDispatcher.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.ExternalMessageDispatcher.Execute(String messageName, Int32 primaryObjectTypeCode, Int32 secondaryObjectTypeCode, PropertyBag fields, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId)
at Microsoft.Crm.Sdk.CrmServiceInternal.Update(String namespaceName, BusinessEntityBase entity, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId)
at Microsoft.Crm.Sdk.Crm2007.CrmService.Update(BusinessEntity entity)
--- End of inner exception stack trace ---
Looking at the stack trace, the error is actually being thrown in a plugin, not in the code you have pasted above. Look at this line in particular:
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
at AccessCRM.PluginUtilities.GetStringValueFromProperty(Property p)
at AccessCRM.ChangeLogContactData.Execute(IPluginExecutionContext context)
You'd need to post up the code for that plugin for us to have another look.
Alternatively use Remote Debugging to debug this yourself.

Resources