Web API throws exception after installing AttributeRouting - invalidoperationexception

I developed a simple VB .NET Web API project using .NET 4.5
This project was working perfectly fine, but I decided to install the AttributeRouting nuget package. After installing this package every function seems to raise the following exception:
The constraint entry 'inboundHttpMethod' on the route with route
template 'Company' must have a string value or be of a type which
implements 'IHttpRouteConstraint'.
In this message 'Company' is the route name to a simple GET method that simple returns one object. Every route results in this error message. The stacktrace is:
[InvalidOperationException: The constraint entry 'inboundHttpMethod'
on the route with route template 'Company/{Id}' must have a string
value or be of a type which implements 'IHttpRouteConstraint'.]
System.Web.Http.Routing.HttpRoute.ProcessConstraint(HttpRequestMessage
request, Object constraint, String parameterName,
HttpRouteValueDictionary values, HttpRouteDirection routeDirection)
+346 System.Web.Http.Routing.HttpRoute.ProcessConstraints(HttpRequestMessage
request, HttpRouteValueDictionary values, HttpRouteDirection
routeDirection) +201
System.Web.Http.Routing.HttpRoute.GetRouteData(String virtualPathRoot,
HttpRequestMessage request) +430
AttributeRouting.Web.Http.Framework.HttpAttributeRoute.GetRouteData(String
virtualPathRoot, HttpRequestMessage request) +250
System.Web.Http.WebHost.Routing.HttpWebRoute.GetRouteData(HttpContextBase
httpContext) +191
System.Web.Routing.RouteCollection.GetRouteData(HttpContextBase
httpContext) +233
System.Web.Routing.UrlRoutingModule.PostResolveRequestCache(HttpContextBase
context) +60
System.Web.Routing.UrlRoutingModule.OnApplicationPostResolveRequestCache(Object
sender, EventArgs e) +82
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+136 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69
I found the following thread which describes my problem: https://github.com/mccalltd/AttributeRouting/issues/191
Unfortunately, this fix does not seem to help: https://github.com/mccalltd/AttributeRouting/issues/191#issuecomment-13814025
Any ideas on how to fix this?

In your case, I definitely feel like this issue is related with in memory hosting and do have a solution in the link that you mention above.
After updating to MVC 5 I came across this issue and following the workout in this link which ultimately helped me out.
Here is how I did it.
In global.ascx page, I have the following:
AttributeRoutingHttpConfig.RegisterRoutes(GlobalConfiguration.Configuration.Routes);
In AttributeRoutingHttpConfig class, I replaced the code
routes.MapHttpAttributeRoutes();
with
routes.MapHttpAttributeRoutes(cfg =>
{
cfg.InMemory = true;
cfg.AutoGenerateRouteNames = true;
cfg.AddRoutesFromAssemblyOf<Your_API_Controller>();
});
You can overwrite Your_API_Controller with any of your ApiController class. (Yes, don't know why but any api controller you want works ;) )
Hope this helps,

Related

Object reference not set to an instance of an object. When browsing to local site

i am getting this error when i try and navigate to my local dev site. but not sure what the exception is pointing. I've got the site set up in IIS similar to another site that works fine.
[NullReferenceException: Object reference not set to an instance of an object.]
umbraco.requestHandler..ctor(XmlDocument umbracoContent, String url) +3727
umbraco.UmbracoDefault.Page_PreInit(Object sender, EventArgs e) +1217
System.EventHandler.Invoke(Object sender, EventArgs e) +0
System.Web.UI.Page.PerformPreInit() +48
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1843
The reason for this error is usually a missing or incomplete XML cache file which is located in the App_Data directory and called umbraco.config. Is this a new clean site with no content? If so then you need to login and publish something first. If you do have content then might I suggest regenerating the XML cache file by navigation to http://{yourhostname}/umbraco/dialogs/republish.aspx?xml=true
For further reference also see http://our.umbraco.org/wiki/reference/api-cheatsheet/publishing-and-republishing
NullReferenceException is thrown when you try to use a member or method of an object which is null. You need to initialize your relevant object before you use its members and methods. You should carefully check your code at the points shown in the trace pasted, find out why the exception is thrown and fix the problem.

Windows azure redis cache migration issue

We are hosting our site on windows azure where site is running on multiple instances.Due to multiple instances we were using shared cache for storing session values. As Microsoft is going to stop shared cache and recommended to use redis cache to store session. I modified project to use redis cache and it worked for most of the pages. My problem is that, we have a very important page "search page" (we are using lucene.net for search functionality) in our site which stores a lot of data in session and this page is not working. After hitting search button, it shows connecting status in address bar for a long time and goes to oops page of website. We are recording error messages in DB so after looking at there we found following error message.
System.Runtime.Serialization.SerializationException: Type 'myWeb.clsSearchCriteria+ContentCriteria' in Assembly 'HelmBriscoeWeb, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
at System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type)
at System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context)
at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo()
at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder)
at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder)
at System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck)
at Microsoft.Web.Redis.RedisUtility.GetBytesFromObject(Object data)
at Microsoft.Web.Redis.RedisUtility.AppendUpdatedOrNewItemsInList(ChangeTrackingSessionStateItemCollection sessionItems, List`1 list)
at Microsoft.Web.Redis.RedisConnectionWrapper.TryUpdateIfLockIdMatchPrepare(Object lockId, ISessionStateItemCollection data, Int32 sessionTimeout, String[]& keyArgs, Object[]& valueArgs)
at Microsoft.Web.Redis.RedisConnectionWrapper.TryUpdateIfLockIdMatch(Object lockId, ISessionStateItemCollection data, Int32 sessionTimeout)
at Microsoft.Web.Redis.RedisSessionStateProvider.SetAndReleaseItemExclusive(HttpContext context, String id, SessionStateStoreData item, Object lockId, Boolean newItem)
at System.Web.SessionState.SessionStateModule.OnReleaseState(Object source, EventArgs eventArgs)
at System.Web.SessionState.SessionStateModule.OnEndRequest(Object source, EventArgs eventArgs)
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
I am not sure if this is related to my problem but seems if this is fixed, page will work properly. Has anyone any idea why this error occurred and how can I fix it?
Thanks
I solved this problem myself by adding serialization attribute to class like below.
<Serializable()> _
Public Class clsSearchCriteria
Thanks

ServiceStack - Simulating a stronger Scope for IRequestLogger

This is not a question about the RequestLogsService or the RequestLogFeature. It is about the ServiceRunner's call to a IRequestLogger (if one is registered at the app container).
My app has regular logging in place, I dump the app's flow to log a file.
I am now implementing a database log, inspired by the RequestLogsService. This log will contain one line per request, containing all the Request and Response data.
However my endpoint produces outputs at 4 different levels:
Custom auth filter
Validation
Service
AppHostExceptionHandler
From those 4, only the Service outputs are covered by the IRequestLogger, because its ServiceRunner related. Is there any way I can cover my 4 scenarios transparently? I want to minimize the complexity introduced in the pipeline.
Thanks
I encountered a similar problem recently and resolved it as follows:
Custom Auth filter
There are 2 possibilities with this one based upon the type of logging you would like. If you throw an exception in here, you can catch it by setting up an ServiceExceptionHandler in AppHost:
this.ServiceExceptionHandler = (httpRequest, request, exception) =>
{
LogData(httpRequest, exception);
return DtoUtils.HandleException(this, request, exception);
};
If that approach won't work for you or you don't throw an exception during auth, you will have to instead create a logging filter either before or after the auth filter is run. This can be done in a few different locations using either a PreRequestFilter or a RequestFilter depending on when exactly you need it to run (see ServiceStack's Order of Operations).
Validation
I'll assume you are using ServiceStack's built in FluentValidation to perform your validation. In this case, you can hook into the plugin's ErrorResponseFilter like so. Note that if you require the IHttpRequest and IHTTPresponse objects in this method, you may have to do a hack-y workaround and stash them somewhere as they aren't supplied.:
Plugins.Add(new ValidationFeature { ErrorResponseFilter = ValidationErrorResponseFilter});
...
private object ValidationError(ValidationResult validationResult, object o)
{
var httpError = o as HttpError;
LogData(httpError);
}
AppHostExceptionHandler
If the exception occurs in setup of the AppHost, you may have to settle with a simple try/catch. If the exception occurs in AppHost during the request processing however, you can use the ExceptionHandler similar to the ServiceExceptionHandler above:
this.ExceptionHandler = (httpReq, httpRes, operationName, ex) =>
{
LogData(httpReq, httpRes);
}
In conclusion, if all of this doesn't work or is too much code in too many places, you can instead resort to overriding one or more methods in ServiceRunner to get what you need. In my case I overrode OnAfterExecute to log every request that made it to the service handler and then only had to add the exception handler to FluentValidation as noted above.

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.

null reference exceptions when adding

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.

Resources