null reference exceptions when adding - subsonic

I discovered SubSonic this evening, and after a little bit of playing with it and MySQL Connector versions, I finally got it to accept my connection string setting up a simple repository.
So I created a simple class, and went to town adding some data to the class then creating a repo, and trying to save the record.
All I can seem to get out of it is null exception errors when I call:
repo.Add(user);
No idea what's null though, and the error isn't very clear.
At one point, I changed the type of my ID field in my User class to a long and got another error out of SubSonic (saying it couldn't tell what field was my ID field, telling me to name it ID or put a tag on it, but it was already named ID)
I've put data in every field in the class, even those that are not required per the database, but nothing.
I spent the rest of the evening googling for information on my error, but no luck, and the documentation on the site didn't get me anywhere either.
Any idea what I'm doing wrong, or how I could possibly diagnose this?
Thanks in advance for any help...
Here's the exception details
System.NullReferenceException was unhandled
Message=Object reference not set to an instance of an object.
Source=MySql.Data
StackTrace:
at MySql.Data.MySqlClient.MySqlConnection.get_ServerThread()
at MySql.Data.MySqlClient.MySqlConnection.Abort()
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
at MySql.Data.MySqlClient.MySqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at SubSonic.DataProviders.DbDataProvider.ExecuteReader(QueryCommand qry)
at SubSonic.Query.Insert.ExecuteReader()
at SubSonic.Repository.SimpleRepository.Add[T](T item)
at gc_ss.Program.Main(String[] args) in C:\Users\Michaelm\Desktop\Subsonic_Demo\gc_ss\gc_ss\Program.cs:line 27
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
Another Update
I'm noticing that if I change the class (User) and modify one of the properties, that the property changes get reflected in the database. Also if I drop the table, it gets constructed based on my Class. So the migrations part is working, it's something happening after that.
Final Update
Okay, I deleted the table, and changed the class to use a long as the ID field. Set to RunMigrations, and ran again, and it failed because of no default value for ID. I set the column in MySQL to AutoIncrement and all is working fine now. Not sure how it's different than setting it to long yesterday (unless changes weren't getting applied like I thought they were).
Anyway, so I guess this question is closed...

This is a issue with the mysql.data provider. Normally the connector would throw a meaningful exception but has an internal nullreference exception itself before that happens.
Look at my answer here: Subsonic 3.0.0.4 ActiveRecord Template for MySQL error on inserting new record
That explains how to work around that.

Related

Property 'stageid' is of an unrecognized EdmPropertyKind. Entity new_test has duplicate navigation property names

I am using CRM2016
I created a test entity to replicate the issue
I did not do any customization on it. I created a new record with default fields and form. Then I tried to access the webapi for it
http://localhost/CRMDataBase/api/data/v8.0/new_test(bgcs0249-0a06-e611-941a-003002djlnc)
It worked fine and brought the record. Then I deleted the records and created a business process flow for it, with just one stage and one step
I activated it and added a new test record and tried to access the webapi url and it threw the below error
{ "error":{
"code":"","message":"Property 'stageid' is of an unrecognized EdmPropertyKind. Entity new_test has duplicate navigation property
names. All property names (Navigation and Structural property) must be
unique in an Entity ","innererror":{
"message":"Property 'stageid' is of an unrecognized EdmPropertyKind. Entity new_test has duplicate navigation property
names. All property names (Navigation and Structural property) must be
unique in an Entity
","type":"Microsoft.Crm.CrmHttpException","stacktrace":" at
Microsoft.Crm.Extensibility.OData.CrmODataEntityTypeSerializer.CreateSelectExpandNode(EntityInstanceContext
entityInstanceContext)\r\n at
System.Web.OData.Formatter.Serialization.ODataEntityTypeSerializer.WriteEntry(Object
graph, ODataWriter writer, ODataSerializerContext writeContext)\r\n
at
System.Web.OData.Formatter.Serialization.ODataFeedSerializer.WriteFeed(IEnumerable
enumerable, IEdmTypeReference feedType, ODataWriter writer,
ODataSerializerContext writeContext)\r\n at
Microsoft.Crm.Extensibility.OData.CrmODataFeedSerializer.WriteObject(Object
graph, Type type, ODataMessageWriter messageWriter,
ODataSerializerContext writeContext)\r\n at
System.Web.OData.Formatter.ODataMediaTypeFormatter.WriteToStream(Type
type, Object value, Stream writeStream, HttpContent content,
HttpContentHeaders contentHeaders)\r\n at
System.Web.OData.Formatter.ODataMediaTypeFormatter.WriteToStreamAsync(Type
type, Object value, Stream writeStream, HttpContent content,
TransportContext transportContext, CancellationToken
cancellationToken)\r\n--- End of stack trace from previous location
where exception was thrown ---\r\n at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)\r\n at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)\r\n at
System.Web.Http.WebHost.HttpControllerHandler.d__1b.MoveNext()","internalexception":{
"message":"Property 'stageid' is of an unrecognized EdmPropertyKind.","type":"Microsoft.OData.Core.ODataException","stacktrace":"
at
Microsoft.OData.Core.UriParser.Parsers.SelectPathSegmentTokenBinder.ConvertNonTypeTokenToSegment(PathSegmentToken
tokenIn, IEdmModel model, IEdmStructuredType edmType, ODataUriResolver
resolver)\r\n at
Microsoft.OData.Core.UriParser.Visitors.SelectPropertyVisitor.ProcessTokenAsPath(NonSystemToken
tokenIn)\r\n at
Microsoft.OData.Core.UriParser.Visitors.SelectPropertyVisitor.Visit(NonSystemToken
tokenIn)\r\n at
Microsoft.OData.Core.UriParser.Parsers.SelectBinder.Bind(SelectToken
tokenIn)\r\n at
Microsoft.OData.Core.UriParser.Parsers.SelectExpandBinder.Bind(ExpandToken
tokenIn)\r\n at
Microsoft.OData.Core.UriParser.Parsers.SelectExpandSemanticBinder.Bind(IEdmStructuredType
elementType, IEdmNavigationSource navigationSource, ExpandToken
expandToken, SelectToken selectToken, ODataUriParserConfiguration
configuration)\r\n at
Microsoft.OData.Core.UriParser.ODataQueryOptionParser.ParseSelectAndExpand()\r\n
at
Microsoft.Crm.Extensibility.OData.CrmODataEntityTypeSerializer.CreateSelectExpandNode(EntityInstanceContext
entityInstanceContext)"
}
} } }
If I delete all the records-> deactivate business process -> add new data and then check the webapi, it is working fine. But when I activate the business process and add new data I am getting the above error
P.S: I have not done any coding/customization to business process flow and the entity. But I am still getting this error
What can be done to resolve this?
Looks like a bug in Web API endpoint. Community forums also reference the same issue...
The Web API endpoint still has some limitations and it doesn't fully mimic the OrganizationService behavior so, which will be for the next version (9.x.x) so if you are stuck maybe try applying an update (and then use v8.1 in the url) as, or raise a MS Support case.
If you are still stuck, just try the same using OData / OrganizationService maybe.

NullReferenceException caused by null TermPart.As<AutoroutePart>() in Orchard CMS 1.7.2

crosspost: https://orchard.codeplex.com/discussions/474456
I'm on Orchard 1.7.2 and I get this error everywhere in my site (which I assume causes the load times to slow down):
Orchard.DisplayManagement.Implementation.DefaultDisplayManager - NullReferenceException thrown from Action`1 by System.Action`1[[Orchard.DisplayManagement.Implementation.ShapeDisplayingContext, Orchard.Framework, Version=1.7.2.0, Culture=neutral, PublicKeyToken=null]]
System.NullReferenceException: Object reference not set to an instance of an object.
So I traced the issue and found the function public string Slug within TermPart.cs (line 16).
public string Slug {
get { return this.As<AutoroutePart>().DisplayAlias; }
set { this.As<AutoroutePart>().DisplayAlias = value; }
}
I found out that this.As<AutoroutePart>() is null, and checking out the parts of the Content Item (via this.ContentItem.Parts), there is no AutoroutePart. Since it is null, a null reference exception is thrown when trying to retrieve the property DisplayAlias.
See image below:
Is this a known issue? Any workarounds? Is this what's causing my site to slow down?
Although having these exceptions definitely has an impact on performance I doubt it could cause a noticeable slowdown.
The exception is caused by Taxonomies's TermPart depending on AutoroutePart; i.e. if your content item doesn't use AutoroutePart (what should be pretty rare IMO) then you'll see this exception. Making TermPart depend on Autoroute is a questionable design decision (at least it could use IAliasAspect instead). Please open a bug report about the issue because this should be addressed somehow.
In the meantime you could attach AutoroutePart to the content type in question to get rid of the exceptions.

Entity Framework Check for references before deleting

Say I have a User that I want to delete, but the User might be referenced by other tables in the database. Is there a way to check for references to this user before trying to delete or is the best option to just delete and catch/handle the exception that SaveChanges() throws?
Obviously I could check each table where the user might be referenced...but I would rather not as it is referenced in a few places and it just seems like a messy way to do things.
I don't now if you have found a solution to this yet but I'm posting since i run into a similar problem myself. I suppose you could use a query to check for references lets say something like..
bool related = db.Article.Where(i => i.CategoryId == id).Any();
But i believe it is better to catch the exception than to check for references.
For scenarios where you want a required relationship but no cascade delete you
can explicitly override the convention and configure cascade delete behavior with the
Fluent API.
The Fluent API method to use is called WillCascadeOnDelete and takes a Boolean as a
parameter. This configuration is applied to a relationship, which means that you first
need to specify the relationship using a Has/With pairing and then call WillCascadeOn
Delete. Something like:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Article>()
.HasRequired(a => a.Category)
.WithMany(i => i.Articles)
.WillCascadeOnDelete(false);
base.OnModelCreating(modelBuilder);
}
Then you usually get a DbUpdateException or a InvalidOperationException depending on how your data is loaded into memory. You can catch them with a simple statement and add a message to the user.
try
{
db.Category.Remove(category);
db.SaveChanges();
return RedirectToAction("Index");
}
catch (DataException)
{
ModelState.AddModelError("", "Your message here");
return View(category);
}
What WillCascadeOnDelete basically does is that it changes the Delete rule in your database from Cascade to No Action which causes the error to be thrown when a violation occurs.
The overall message here is that you have control over the cascade delete setting, but
you will be responsible for avoiding or resolving possible conflicts caused by
not having a cascade delete present. It worked for me, hope it helps you too.
See also:Configuring Relationships with the Fluent API

Projection, Queries missing in Orchard 1.4.2

I can't see the queries section the dashboard, neither can I see that as a part of Projection Page.
Has anything changed?
In logs, there is one error :
Object reference not set to an instance of an object.
at Szmyd.Orchard.Modules.Menu.Drivers.BreadcrumbsPartDriver.<>c__DisplayClass5.<Display>b__4()
at Orchard.ContentManagement.Drivers.ContentPartDriver`1.<>c__DisplayClassd.<ContentShape>b__c(BuildShapeContext ctx) in C:\OrchardWebsite\src\Orchard\ContentManagement\Drivers\ContentPartDriver.cs:line 108
at Orchard.ContentManagement.Drivers.ContentPartDriver`1.<>c__DisplayClass13.<ContentShapeImplementation>b__12(BuildShapeContext ctx) in C:\OrchardWebsite\src\Orchard\ContentManagement\Drivers\ContentPartDriver.cs:line 116
at Orchard.ContentManagement.Drivers.ContentShapeResult.ApplyImplementation(BuildShapeContext context, String displayType) in C:\OrchardWebsite\src\Orchard\ContentManagement\Drivers\ContentShapeResult.cs:line 37
at Orchard.ContentManagement.Drivers.ContentShapeResult.Apply(BuildDisplayContext context) in C:\OrchardWebsite\src\Orchard\ContentManagement\Drivers\ContentShapeResult.cs:line 21
at Orchard.ContentManagement.Drivers.Coordinators.ContentPartDriverCoordinator.<>c__DisplayClassa.<BuildDisplay>b__9(IContentPartDriver driver) in C:\OrchardWebsite\src\Orchard\ContentManagement\Drivers\Coordinators\ContentPartDriverCoordinator.cs:line 49
at Orchard.InvokeExtensions.Invoke[TEvents](IEnumerable`1 events, Action`1 dispatch, ILogger logger) in C:\OrchardWebsite\src\Orchard\InvokeExtensions.cs:line
I had the same issue and found out the projector module was disabled. I don't know why it was disabled but it made sense enabling it.
No, it's still there. Something else must be going on, such as a version mismatch causing an exception when loading the module. Did you check your app_data\logs folder?
I had the same issue with Queries not showing up in the Dashboard. Disabling the Autoroute module and enabling it again worked for me.

Microsoft.Xrm.Sdk.SaveChangesException in CRM 2011

I recently started working with plugins in CRM 2011 and I am facing issues with plugins registered on the Create message as a Post-operation.
When I register the create as a post-operation, I would expect that when I hit the plugin code, the entity has already been created in the database and I should be able to create a related entity(related to the newly created entity by a foreign key) in the plugin. But when I create the related entity and update it, and say SaveChanges(), it gives me a Microsoft.Xrm.SaveChangesException "An error occurred while processing this request"
And if I drill down to the inner exception, it just points to the OrganizationServiceFault. The stack trace it shows is:
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Microsoft.Xrm.Sdk.IOrganizationService.Execute(OrganizationRequest request)
at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.ExecuteCore(OrganizationRequest request)
at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.Execute(OrganizationRequest request)
at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.SaveChange(OrganizationRequest request, IList`1 results
I face this issue only on the create message, if I do the same operation on an update or delete, it works fine. Has anybody faced this issue? Please provide some inputs on the what I can try to resolve this issue. Thanks in advance!
Also, here is my plugin code.
The plugin gets fired when the ct_repcode entity is created and then in my plugin I create a ct_repcodeMember entity which has a ct_repcodeid field which links to the actual ct_repcode entity.
Entity repcodeEntity = _context.InputParameters["Target"] as Entity;
Guid repcodeId = repcodeEntity.Id;
//Create a new Ct_repcodemember object
Ct_repcodemember repcodeMember = new Ct_repcodemember();
Guid repCodeMemberId = _service.Create(repcodeMember);
repcodeMember = _serviceContext.Ct_repcodememberSet.Where(a => a.Id == repCodeMemberId).FirstOrDefault();
repcodeMember.ct_repcodeid = new EntityReference { Id = repcodeId };
//Update the object and save the changes in crm
_serviceContext.UpdateObject(repcodeMember);
_serviceContext.SaveChanges(); // --- The timeout error happens here
I've encountered this problem before as well. I believe the problem is that in CRM 2011, both the Pre and Post operations occur while you're still inside the database transaction.
The way we got around this was to flip the plugin to run asynchronously as a synchronous result was not necessary.
I'm not sure if there is another way around this with your current code structure. I haven't tried this either, but considering you can create the entity just fine, can you create the repcodeMember entity with the lookup populated? Is there a real need to do the create, retrieve, and then update? If you have some code that is running on create of the related entity, you may be able to share that with this plugin such that you can just do a straight create since it is the update that is giving you problems.
Give credit to #rocksolid and #patricgh, I just took their suggestions, combined them, and put a code example around it.
You should drop the use of the Service Context for this operation and use CRM's default CRUD functionality. Your EntityReference is incorrect because you must have a logical name, but since you already have an Entity you should just use EntityReference to set the value.
Entity repcodeEntity = _context.InputParameters["Target"] as Entity;
Ct_repcodemember repcodeMember = new Ct_repcodemember();
repcodeMember.ct_repcodeid = repcodeEntity.ToEntityReference();
_service.Create(repcodeMember);
I think what you have done: creating, finding and updating an entity via context is not a good way. You can just create an entity I mean the object update and then create it it via service. I have put the code as below.
Entity repcodeEntity = _context.InputParameters["Target"] as Entity;
Guid repcodeId = repcodeEntity.Id;
Ct_repcodemember repcodeMember = new Ct_repcodemember();
repcodeMember.ct_repcodeid = new EntityReference { Id = repcodeId };
_service.Create(repcodeMember);
You could try also setting the Logical Name for the ct_repcodeid Entity Reference, it looks like you are only setting the Id.

Resources