IndexOutOfRangeException in the Ajax.Net extensions framework - c#

For some reason when I attempt to make a request to an Ajax.net web service with the ScriptService attribute set, an exception occurs deep inside the protocol class which I have no control over. Anyone seen this before?
Here is the exact msg:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at System.Web.Services.Protocols.HttpServerType..ctor(Type type)
at System.Web.Services.Protocols.HttpServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocol.SetContext(Type type, HttpContext ontext, HttpRequest request, HttpResponse response)
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)
thx
Trev

This is usually an exception while reading parameters into the web service method...are you sure you're passing the number/type of parameters the method is expecting?

Also make sure your web.config is setup properly for asp.net ajax:
http://www.asp.net/AJAX/Documentation/Live/ConfiguringASPNETAJAX.aspx

Related

C# dotnet core 2 pass data from middleware/filter to controller method

currently we are writing a web application with dotnet core 2.
We actually create some kind of multi-hosting platform where we can register new clients based on the url passed to our application.
However currently we wanted to create a middleware/filter to validate our client's.
Actually what we wanted to do is pull an object from the database and check if it exists, if yes, we want to call the controller method and make the object accessible, if it does not exist, we actually want to abort and show an error page.
What we already have done is created a filter/middleware that does exactly that, however we couldn't figure out a way to access the object that we already pulled in our filter/middleware inside the controller method.
is there actually any documentation for doing that?
I actually tried to figure it out from:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware?tabs=aspnetcore2x
https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/filters
but they don't describe a way to do it, only to actually do something before/after the action.
You could add the object to the context using HttpContext.Items which the docs state:
The Items collection is a good location to store data that is needed only while processing one particular request. The collection's contents are discarded after each request. The Items collection is best used as a way for components or middleware to communicate when they operate at different points in time during a request and have no direct way to pass parameters.
For example, in your middleware:
public class MySuperAmazingMiddleware
{
private readonly RequestDelegate _next;
public MySuperAmazingMiddleware(RequestDelegate next)
{
_next = next;
}
public Task Invoke(HttpContext context)
{
var mySuperAmazingObject = GetSuperAmazingObject();
context.Items.Add("SuperAmazingObject", mySuperAmazingObject );
// Call the next delegate/middleware in the pipeline
return this._next(context);
}
}
Then later on in your action method, you can read the value:
var mySuperAmazingObject = (SuperAmazingObject)HttpContext.Items["mySuperAmazingObject"];
One way of doing it (not saying it's the only or the best) is to have DI inject a proxy of the object, you set the real value of the object in your middleware, then you can access it from the proxy in the controller.
Note: if you'll pass the proxy object in the method call instead of controller, don't forget to mark it with [FromServices] attribute.
Another way would be adding the object to the request Items property. but when you read it you'll need casting from object to your actual class.

LightInject Attempt to create a scoped instance without a current scope

I (noob to light inject mvc) am using LightInject MVC in my asp.mvc 4 app with great results except an occasional exception. Now I am seeing it in pre-production. The exception is: System.InvalidOperationException: Attempt to create a scoped instance without a current scope.
My app start code is:
var container = new LightInject.ServiceContainer();
container.RegisterControllers();
container.RegisterAssembly(typeof(AppDDD.RegisterMe).Assembly, () => new PerScopeLifetime());
... scoped registrations
container.EnableMvc();
I get the error with a stack trace like:
System.InvalidOperationException: An error occurred when trying to
create a controller of type 'MvcAPP.Controllers.HomeController'. Make
sure that the controller has a parameterless public constructor. --->
System.InvalidOperationException: Attempt to create a scoped instance
without a current scope. at
LightInject.PerScopeLifetime.GetInstance(Func1 createInstance, Scope
scope) at DynamicMethod(Object[] ) at
LightInject.ServiceContainer.<>c__DisplayClass40.<WrapAsFuncDelegate>b__3f()
at LightInject.PerRequestLifeTime.GetInstance(Func1 createInstance,
Scope scope) at DynamicMethod(Object[] ) at
LightInject.ServiceContainer.TryGetInstance(Type serviceType) at
System.Web.Mvc.DefaultControllerFactory.DefaultControllerActivator.Create(RequestContext
requestContext, Type controllerType) --- End of inner exception
stack trace --- at
System.Web.Mvc.DefaultControllerFactory.DefaultControllerActivator.Create(RequestContext
requestContext, Type controllerType) at
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext
requestContext, String controllerName) at
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase
httpContext, IController& controller, IControllerFactory& factory)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase
httpContext, AsyncCallback callback, Object state) at
System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step,
Boolean& completedSynchronously)
I have created a couple of small test ASP MVC projects to isolate the exception with no success.
The Controllers are scoped per instance, and all the objects with in each instance are designated PerScopeLifetime.
Is there a tweak I can make, or should I stop using PerScopeLifetime? I must have scoped lifetimes for my EF contexts.
The exception is thrown before my controllers finish constructing, so it appears.
I would like you to know that the issue has been resolved and getting the latest and greatest from NuGet should fix your problem.
Best regards
Bernhard Richter

How can I create a new HttpContext?

public void getContent() {
string VirtualPath = "~/Content.aspx";
var page = BuildManager.CreateInstanceFromVirtualPath( VirtualPath, typeof( Page ) ) as IHttpHandler;
page.ProcessRequest( HttpContext.Current );
}
I'm using that function to load the content from different files, but the "page.ProcessRequest( HttpContext.Current )" inserts the content at the current context, and what I need is the function to return the content of the specified file.
I wonder if there's a working way to create a new HttpContext, so that "page.ProcessRequest" don't insert anything into the current response.
Oded is correct as far as I know. You can't easily create your own instance of the HttpContext. However you can still achieve your goals thorugh other means.
Use a Server.Execute. http://msdn.microsoft.com/en-us/library/ms150027.aspx.
You can specify the HttpHandler to execute along with a TextWriter to dump the content into.
You can't create a new HttpContext, not without lots of work arounds.
It is one of the failings of ASP.NET and the BCL - makes web applications untestable (or at least very difficult to test without HttpContext.
I am not clear on your requirement what I need is the function to return the content of the specified file - can you please explain exactly what you mean by that?
Check out Pex/Moles its includes a mocking framework that can mock almost any type or member, even if its sealed or static.
(it does this by using a custom test host)

Response is not available in this context

I have problem. Locally everything works fine but in the production server it always throws exception 'Response is not available in this context'. What can be the problem? I've noticed that a lot of people experience this problem due to some changes of global.asax. Here is the code of global.asax, the part related to application start.
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
Application["SystemUser"] = TUser.GetUserByIdentifier("system").UID;
InitializeSolrInstances();
SearchIndexer.DoIndex();
StartRatingTimer();
SolrManager.RecalculateMostRequested();
}
private static void InitializeSolrInstances() {
SolrConfigurationManager.InitSolrConnection<OfferItemPresenter>(Resources.ApplicationResources.SolrServiceURL + "/offer");
SolrConfigurationManager.InitSolrConnection<SavedQueryItemPresenter>(Resources.ApplicationResources.SolrServiceURL + "/savedquery");
SolrConfigurationManager.InitSolrConnection<TopProductsPresenter>(Resources.ApplicationResources.SolrServiceURL + "/topproducts");
SolrConfigurationManager.InitSolrConnection<TopSellersPresenter>(Resources.ApplicationResources.SolrServiceURL + "/topsellers");
SolrConfigurationManager.InitSolrConnection<MostRequestedItemPresenter>(Resources.ApplicationResources.SolrServiceURL + "/mostrequested");
SolrConfigurationManager.InitSolrConnection<MostRequestedQuery>(Resources.ApplicationResources.SolrServiceURL + "/requestedquery");
}
private void StartRatingTimer() {
_LastRatingRenewedTime = DateTime.Now;
DateTime CurrentTime = DateTime.Now;
DateTime StartTime = new DateTime(2011, 1, 1);
GlobalSettings.ReIndexMainSolrCores(StartTime, CurrentTime);
Timer OfferAndUserRatingRenewerTimer = new Timer() {
/*Timer interval for 24 hours*/
Interval = 24 * 60 * 60 * 1000, Enabled = true };
OfferAndUserRatingRenewerTimer.Elapsed += new ElapsedEventHandler(OfferAndUserRatingRenewerTimer_Elapsed);
}
public void OfferAndUserRatingRenewerTimer_Elapsed(Object Sender, ElapsedEventArgs e) {
GlobalSettings.ReIndexMainSolrCores(_LastRatingRenewedTime, e.SignalTime);
_LastRatingRenewedTime = e.SignalTime;
}
I do not use Response or Request properties of HttpContext at all. Neither in global asax itself, nor within the methods to be called. Help me.
That what it shows.
`
Server Error in '/' Application.
Response is not available in this context.
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.Web.HttpException: Response is not available in this context.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[HttpException (0x80004005): Response is not available in this context.]
System.Web.Util.HttpEncoder.get_Current() +11406684
System.Web.HttpUtility.UrlEncode(String str, Encoding e) +137
SolrNet.Impl.SolrConnection.<Get>b__0(KeyValuePair`2 input) +89
SolrNet.Utils.<Select>d__1a`2.MoveNext() +612
SolrNet.Utils.Func.Reduce(IEnumerable`1 source, TResult startValue, Accumulator`2 accumulator) +393
SolrNet.Impl.SolrConnection.Get(String relativeUrl, IEnumerable`1 parameters) +908
SolrNet.Impl.SolrQueryExecuter`1.Execute(ISolrQuery q, QueryOptions options) +195
SolrNet.Impl.SolrBasicServer`1.Query(ISolrQuery query, QueryOptions options) +176
SolrNet.Impl.SolrServer`1.Query(ISolrQuery query, QueryOptions options) +176
TebeComSearchEngine.SolrManager.RecalculateMostRequested() in SolrManager.cs:77
TebeCom.MvcApplication.Application_Start() in Global.asax.cs:101
[HttpException (0x80004005): Response is not available in this context.]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +4043621
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +191
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +352
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +407
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +375
[HttpException (0x80004005): Response is not available in this context.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +11612256
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +141
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +4842149`
'Response is not available in this context'. What can be the problem?
You are running this in IIS7 Integrated Application Pool mode instead of Classic mode. In Integrated mode you don't have access to the HttpResponse in Application_Start any any attempt to access it will blow.
Here's a blog post which covers a similar situation but with the HttpRequest.
After a lot of digging and looking around the SolrNet code, they don't appear to be doing anything wrong. Also, as Darin pointed out in an indirect manner, HttpUtility.UrlEncode should work fine in code without a HttpContext, such as a console application, and it does.
However, as VinayC pointed out in his comment on that answer of Darin's:
Actually, it appears to be a bug. From
reflector, actual code appears to be
"if (null != current && null !=
current.Response && ...)" where
current is current http context. Issue
here is that Response getter throws an
exception, instead of returning null
Instead of throwing that overly descriptive exception (no doubt they were trying to be helpful), they should have just returned null and let null reference exceptions happen. In this case, they were simply checking for nulls, so the exception wouldn't have happened anyway! I'll report it as a bug if it hasn't been already.
Unfortunately, what this means to you is that you have pretty much no choice but to run in Classic mode. Technically you could put the call to TebeComSearchEngine.SolrManager.RecalculateMostRequested() in a thread that you spawn in application_start and delay its execution until after the app finishes starting. As far as I know, there is no surefire way to programmatically signal the end of the application starting so, that approach may be a little messy.
If you're up for it though, you could probably get that delayed startup mechanism implemented. Compared to punishing the first visitor to the site, it doesn't seem too bad.
This was discussed about a month ago in the SolrNet mailing list.
It's a regression in ASP.NET 4, here's a mention of this bug.
A future release of SolrNet will replace System.Web.HttpUtility.UrlEncode to work around this bug. (or if you really need this, why not fork the source code and fix it?)
EDIT: I just fixed this.

MVC Deserialization Error

Okay. This is my company's customer portal, it's an MVC 2 project. We have a back end SAP system that the portal draws data from. But it does not directly hit SAP, it sends an xml request to a VB app that gets the data and sends it back in an xml response. There is an interface IRequest that all the various requests implement examples would be CustomerNumberRequest, CompanyNameRequest, etc. These all implement the method ToXml which as the name suggests simply builds xml to send. All of the existing requests work fine. (Let me preface this by saying that I inherited this project and the guy who wrote it is no longer with us) I am now trying to send a request to get the Rep Groups from SAP. I basically copied one of the other requests verbatim, making the necessary tweaks to send the appropriate request. But it keeps failing with error messages that I don't understand:
The formatter threw an exception while
trying to deserialize the message:
There was an error while trying to
deserialize parameter
http://tempuri.org/:request. The
InnerException message was 'The
deserializer cannot load the type to
deserialize because type
'XXXXX.CustomerPortal.Domain.RepGroupRequest'
could not be found in assembly
'XXXXX.CustomerPortal.Domain,
Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null'. Check that the
type being serialized has the same
contract as the type being
deserialized and the same assembly is
used.'. Please see InnerException for
more details.
This error happens right at _communicationService.ProcessRequest(request); (shown below) It does not enter the ProcessRequest method it just tries to create a NetDataContractSerializer here:
public override XmlObjectSerializer CreateSerializer(Type type, XmlDictionaryString name, XmlDictionaryString ns, IList<Type> knownTypes)
{
return new NetDataContractSerializer();
}
and then it dies. These are the methods being called:
private void PopulateRepGroups()
{
List<string> repGroups = new List<string>();
RepGroupRequest request = new RepGroupRequest();
foreach (RepGroup repGroup in _repService.GetRepGroups(request))
repGroups.Add(repGroup.RepGroupName);
ViewData["RepGroups"] = new SelectList(repGroups);
}
public List<RepGroup> GetRepGroups(RepGroupRequest request)
{
string response = _communicationService.ProcessRequest(request);
return RepGroupResponseFactory.GetRepGroupResponse(response);
}
Can anybody tell me what this error message is telling me? It says the type cannot be found but the type should be IRequest (that's what it says when the CreateSerializer is hit) which is used all over this. I'm clearly lost, please help!
Quoting your exception
Check that the type being serialized has the same contract as the type being deserialized and the same assembly is used
Check the version of the library on both ends that CustomerPortal.Domain.RepGroupRequest resides in to make sure they are the same version exactly.

Categories