Invalid Character reading xml file from Azure ServiceFabric Service - azure

When I add Swagger (v2.5) on any Web Api service of my Azure ServiceFabric cluster, and the swagger documentation file contains accent marks (á, é, í...), I get this error:
Invalid character in the given encoding
I was passing the uri (path) of the xml file to swagger:
services.AddSwaggerGen(options =>
{
...
options.IncludeXmlComments(myxmlpath);
...
}
But according to this post I should pass a StreamReader to specify the encoding, so I swapped the code for this:
services.AddSwaggerGen(options =>
{
...
options.IncludeXmlComments(() => new XPathDocument(
new StreamReader(myxmlpath, Encoding.UTF8)));
...
}
In this way I managed to avoid the error, but in the swagger UI I see strange characters. For example, instead of áéíóú it shows:
����������
I don't understand why it works in my local cluster but it gives me encoding issues in my Azure cluster. I have not managed to reproduce the error in my local cluster.
Why the file parsing depends in any way on the node where the service is deployed (local or Azure)?
This is my entire stack trace before swapping the code:
Unhealthy event: SourceId='System.RA', Property='ReplicaOpenStatus', HealthState='Warning', ConsiderWarningAsError=false.
Replica had multiple failures during open on mynode01. API call: IStatelessServiceInstance.Open(); Error = System.Xml.XmlException (-2146232000)
Invalid character in the given encoding. Line 35, position 12.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.Throw(String res, String arg)
at System.Xml.XmlTextReaderImpl.InvalidCharRecovery(Int32& bytesCount, Int32& charsCount)
at System.Xml.XmlTextReaderImpl.GetChars(Int32 maxCharsCount)
at System.Xml.XmlTextReaderImpl.ReadData()
at System.Xml.XmlTextReaderImpl.ParseText(Int32& startPos, Int32& endPos, Int32& outOrChars)
at System.Xml.XmlTextReaderImpl.ParseText()
at System.Xml.XmlTextReaderImpl.ParseElementContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XPath.XPathDocument.LoadFromReader(XmlReader reader, XmlSpace space)
at System.Xml.XPath.XPathDocument..ctor(String uri, XmlSpace space)
at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenOptions.<>c__DisplayClass31_0.b__0()
at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenOptions.CreateSwaggerProvider(IServiceProvider serviceProvider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitTransient(TransientCallSite transientCallSite, ServiceProviderEngineScope scope)
at Microsoft.Extensions.Internal.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass4_0.b__0(RequestDelegate next)
at Microsoft.AspNetCore.Builder.Internal.ApplicationBuilder.Build()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.StartAsync(CancellationToken cancellationToken)
at Microsoft.AspNetCore.Hosting.Internal.WebHost.Start()
at Microsoft.ServiceFabric.Services.Communication.AspNetCore.AspNetCoreCommunicationListener.OpenAsync(CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Runtime.StatelessServiceInstanceAdapter.OpenCommunicationListenersAsync(CancellationToken cancellationToken)
at Microsoft.ServiceFabric.Services.Runtime.StatelessServiceInstanceAdapter.System.Fabric.IStatelessServiceInstance.OpenAsync(IStatelessServicePartition partition, CancellationToken cancellationToken)
For more information see: http://aka.ms/sfhealth

I finally found the problem. It was not a problem in the Azure environment. I had a release step in VSTS Replace Tokens with the Files Encoding option in auto. I changed it to utf-8 and it works!

Related

IronPDF System.Exception Error while generating PDF from Url in Azure function

I have an Azure (durable) function that is using the new Runtime Version 3 which is supposed to generate a PDF using IronPDF from a URL. The function keeps failing and the only error that gets logged to Insights is something like this:
Exception: Exception while executing function: A_GetPdfDataFromUrl
Type: Microsoft.Azure.WebJobs.Host.FunctionInvocationException
Stack Trace
Microsoft.Azure.WebJobs.Host.FunctionInvocationException: Exception while executing function: A_GetPdfDataFromUrl
---> System.Exception: Error while generating PDF from 'https://www.myurl.com'
at .(String , CefRenderSettings , CefBrowserSettings )
at .RenderPdfDocumentFromUri(ChromePdfRenderOptions Options, ChromeHttpLoginCredentials Login, Uri url)
at IronPdf.Rendering.Abstractions.PdfRenderProxy'2.RenderUrlAsPdf(Uri Url)
at IronPdf.Rendering.Abstractions.PdfRenderProxy'2.RenderUrlAsPdf(String UrlOrPath)
at IronPdf.Rendering.Abstractions.PdfRenderProxy'2.<>c__DisplayClass19_0.b__0()
at System.Threading.Tasks.Task'1.InnerInvoke()
at System.Threading.Tasks.Task.<>c.<.cctor>b__274_0(Object obj)
at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
at MyFuncs.PdfFunc.GetPdfDataFromUrl(String url) in D:\a\1\s\Funcs\PdfFunc.cs:line 155
at Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker'2.InvokeAsync(Object instance, Object[] arguments) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionInvoker.cs:line 52
at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.InvokeWithTimeoutAsync(IFunctionInvoker invoker, ParameterHelper parameterHelper, CancellationTokenSource timeoutTokenSource, CancellationTokenSource functionCancellationTokenSource, Boolean throwOnTimeout, TimeSpan timerInterval, IFunctionInstance instance) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 572
at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithWatchersAsync(IFunctionInstanceEx instance, ParameterHelper parameterHelper, ILogger logger, CancellationTokenSource functionCancellationTokenSource) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 518
at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(IFunctionInstanceEx instance, FunctionStartedMessage message, FunctionInstanceLogEntry instanceLogEntry, ParameterHelper parameterHelper, ILogger logger, CancellationToken cancellationToken) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs:line 296
Unfortunately, IronPDF logs dont get generated in Azure due to a bug in their current version which they said will be fixed in the next release. So until then I'm unable to figure out why this simple code is failing in Azure.
[FunctionName("A_GetPdfDataFromUrl")]
public async Task<byte[]> GetPdfDataFromUrl([ActivityTrigger] string url)
{
IronPdf.License.LicenseKey = "";
IronPdf.Logging.Logger.EnableDebugging = true;
IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;
ChromePdfRenderer chromePdfRenderer = new ChromePdfRenderer();
var trackReportPdf = chromePdfRenderer.RenderUrlAsPdf(url);
return trackReportPdf.BinaryData;
}
Thank you darren. Posting your suggestions as an answer to help other community members.
The logs will be generated in Azure where all the logs will be stored in a container called $logs. The container $logs is automatically generated when the storage account is created.
All logs are stored in block blobs in a container named $logs.
This is automatically created when Storage Analytics is enabled for a storage account.
The $logs container is located in the blob namespace of the storage account
To answer your question Raihan-Iqbal
Do you mean the storage account that is assigned to the azure function
Yes the storage account that creates when we create Azure Function or it may be any of the storage account the $logs container will be generated automatically.
For further details see Iron Log Files.

Request body too large

When I try to upload a 80mb file from postman to my local endpoint running in Visual Studio 2019 on IISExpress I get the following error:
The request filtering module is configured to deny a request that exceeds the request content length.
So I added this to applicationhost.config for the project:
<system.web>
<httpRuntime maxRequestLength="1050000" />
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824"/>
</requestFiltering>
</security>
This stop the error coming when I make the API request but now I just get a ServiceStack generated "snapshot" page telling me how long request took and the date but my actual endpoint is never hit.
Inside my logs I can see ServiceStack throwing this exception:
2020-07-20 01:57:56.0497||ERROR|ServiceStackHost|Request body too
large. Microsoft.AspNetCore.Server.IIS.BadHttpRequestException:
Request body too large. at
Microsoft.AspNetCore.Server.IIS.BadHttpRequestException.Throw(RequestRejectionReason
reason) at
Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.InitializeRequestIO()
at
Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.ReadAsync(Memory1 memory, CancellationToken cancellationToken) at Microsoft.AspNetCore.Server.IIS.Core.HttpRequestStream.ReadAsyncInternal(Memory1
buffer, CancellationToken cancellationToken) at
Microsoft.AspNetCore.WebUtilities.BufferedReadStream.EnsureBufferedAsync(Int32
minCount, CancellationToken cancellationToken) at
Microsoft.AspNetCore.WebUtilities.MultipartReaderStream.ReadAsync(Byte[]
buffer, Int32 offset, Int32 count, CancellationToken
cancellationToken) at
Microsoft.AspNetCore.WebUtilities.StreamHelperExtensions.DrainAsync(Stream
stream, ArrayPool1 bytePool, Nullable1 limit, CancellationToken
cancellationToken) at
Microsoft.AspNetCore.WebUtilities.MultipartReader.ReadNextSectionAsync(CancellationToken
cancellationToken) at
Microsoft.AspNetCore.Http.Features.FormFeature.InnerReadFormAsync(CancellationToken
cancellationToken) at
Microsoft.AspNetCore.Http.Features.FormFeature.ReadForm() at
Microsoft.AspNetCore.Http.DefaultHttpRequest.get_Form() at
ServiceStack.Host.NetCore.NetCoreRequest.get_FormData() in
C:\BuildAgent\work\3481147c480f4a2f\src\ServiceStack\Host\NetCore\NetCoreRequest.cs:line
167 at
ServiceStack.HttpRequestExtensions.GetFlattenedRequestParams(IRequest
request) in
C:\BuildAgent\work\3481147c480f4a2f\src\ServiceStack\HttpRequestExtensions.cs:line
555 at ServiceStack.Host.RestHandler.CreateRequestAsync(IRequest
httpReq, IRestPath restPath) in
C:\BuildAgent\work\3481147c480f4a2f\src\ServiceStack\Host\RestHandler.cs:line
132 at ServiceStack.Host.RestHandler.ProcessRequestAsync(IRequest
req, IResponse httpRes, String operationName) in
C:\BuildAgent\work\3481147c480f4a2f\src\ServiceStack\Host\RestHandler.cs:line
89|url: |action:
So the Body length still needs to be set somewhere but everywhere I look points back to the config I have already used.
Is there additional setting required or is this a ServiceStack issue?
I was missing this option in startup:
services.Configure<IISServerOptions>(options =>
{
options.MaxRequestBodySize = int.MaxValue;
});
services.Configure<KestrelServerOptions>(options =>
{
options.Limits.MaxRequestBodySize = int.MaxValue; // if don't set default value is: 30 MB
});

RBAC issues using MassTransit with Azure service bus and MSI authentication

We are using MassTransit (v.5.5.5) with Azure Service Bus in a .net core v.2.2 application running in a container within Kubernetes. During the Bus setup we create a token using the managed service identity (MSI), like this...
var tokenProvider = TokenProvider.CreateManagedServiceIdentityTokenProvider();
var busControl = Bus.Factory.CreateUsingAzureServiceBus(cfg =>
{
IServiceBusHost busHost = cfg.Host(new Uri(Settings.Host), h =>
{
h.OperationTimeout = TimeSpan.FromSeconds(5);
h.TokenProvider = tokenProvider;
h.TransportType = Settings.TransportType;
});
...
}
Within Azure, the MSI is configured with all 3 Service Bus permissions (Owner, Sender and Receiver) - as decribed here.
When the application starts authentication seems to happen successfully but when MassTransit begins to listen on the specific queues we create it fails with the following error:
MassTransit.Azure.ServiceBus.Core.Transport.ReceiveTransport Error: 0 :
ReceiveTransport Faulted: sb://hostname.servicebus.windows.net/some-custom-queue,
Microsoft.Azure.ServiceBus.UnauthorizedException: Generic: Failed during RBAC check,
please make sure service resource provider is registered on your tenant.
Points to note:
The application does create the temporary bus queue, and there are no errors to do with accessing it.
The application does not create our custom queues.
If the MSI permissions are removed then no queues are created and the error is different: Authorization failed for specified action: Manage,EntityWrite.
For what it's worth we are using the AmqpWebSockets transport type.
It seems weird that the temporary queue is created but not our application-specific ones.
So I guess my question is this... have I done anything wrong or is this something that is not yet available for MassTransit using Service Bus with MSI?
Thanks in advance.
We came across the same issue. We are using Mass Transit 6.* and Azure Service Bus. When switched to MSI we start see the same error:
Microsoft.Azure.ServiceBus.UnauthorizedException: Generic: Failed during RBAC check, please make sure service resource provider is registered on your tenant. TrackingId:2644d62a-83a9-444f-8aeb-b4bdee2fa84d_G30, SystemTracker:NoSystemTracker, Timestamp:2020-02-13T15:54:49
at Microsoft.Azure.ServiceBus.Management.ManagementClient.SendHttpRequest(HttpRequestMessage request, CancellationToken cancellationToken)
at Microsoft.Azure.ServiceBus.Management.ManagementClient.PutEntity(String path, String requestBody, Boolean isUpdate, String forwardTo, String fwdDeadLetterTo, CancellationToken cancellationToken)
at Microsoft.Azure.ServiceBus.Management.ManagementClient.CreateTopicAsync(TopicDescription topicDescription, CancellationToken cancellationToken)
at MassTransit.Azure.ServiceBus.Core.Contexts.NamespaceManager.<>c__DisplayClass25_0`1.<<RunOperation>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.Azure.ServiceBus.RetryPolicy.RunOperation(Func`1 operation, TimeSpan operationTimeout)
at Microsoft.Azure.ServiceBus.RetryPolicy.RunOperation(Func`1 operation, TimeSpan operationTimeout)
at MassTransit.Azure.ServiceBus.Core.Contexts.NamespaceManager.RunOperation[T](Func`1 operation)
at MassTransit.Azure.ServiceBus.Core.Contexts.ServiceBusNamespaceContext.CreateTopic(TopicDescription topicDescription)
at MassTransit.Azure.ServiceBus.Core.Pipeline.ConfigureTopologyFilter`1.ConfigureTopology(NamespaceContext context)
at MassTransit.Azure.ServiceBus.Core.Pipeline.ConfigureTopologyFilter`1.<>c__DisplayClass5_0.<<Send>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at GreenPipes.PipeExtensions.OneTimeSetup[T](PipeContext context, Func`2 setupMethod, PayloadFactory`1 payloadFactory)
at MassTransit.Azure.ServiceBus.Core.Pipeline.ConfigureTopologyFilter`1.Send(NamespaceContext context, IPipe`1 next)
at GreenPipes.Agents.AsyncPipeContextPipe`1.Send(TContext context)
at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
at MassTransit.Azure.ServiceBus.Core.Pipeline.JoinContextFactory`3.<>c__DisplayClass7_0.<<CreateJoinContext>g__Join|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at MassTransit.Azure.ServiceBus.Core.Pipeline.ClientContextFactory.CreateSharedContext(Task`1 context, CancellationToken cancellationToken)
at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
at MassTransit.Azure.ServiceBus.Core.Transport.ReceiveTransport.<Receiver>b__12_0()
at MassTransit.Azure.ServiceBus.Core.Pipeline.JoinContextFactory`3.<>c__DisplayClass7_0.<<CreateJoinContext>g__Join|0>d.MoveNext()
Finally we found that ASB Sdk Microsoft.Azure.ServiceBus.Management.ManagementClient doesn't allow to create topics with slashes in path when tokens from MSI used. This code below return the same error:
try
{
var address = "sb://[name].servicebus.windows.net";
var tokenProvider = new TokenProvider.CreateManagedIdentityTokenProvider();();
var _managementClient = new ManagementClient(address.ToString(), tokenProvider);
var topicDefinition = new TopicDescription("myNewTopic/22222");
await _managementClient.CreateTopicAsync(topicDefinition);
}
catch (Exception e)
{
Debug.WriteLine(e);
throw;
}
Since MT uses special naming convention to setup messaging topology, we get topic path with namespace of particular message type. If we have message MassTransitTest.Message1 it will be converted to topic MassTransitTest/Message1 (with slash). To fix this we setup our own IEntityNameFormatter
public class MyEntityNameFormatter : IEntityNameFormatter
{
readonly IMessageNameFormatter _formatter;
public MyEntityNameFormatter()
{
_formatter = new ServiceBusMessageNameFormatter();
}
public string FormatEntityName<T>()
{
var entityName = _formatter.GetMessageName(typeof(T)).ToString().Replace("/",".");
return entityName;
}
}
and then
var bus = Bus.Factory.CreateUsingAzureServiceBus(configurator =>
{
...
configurator.MessageTopology.SetEntityNameFormatter(new MyEntityNameFormatter());
...
This fixed our issue. (We tried use ~ instead of . but got some validation errors, so decided use dots)
I have been able to reproduce the same error using Azure Service Bus SDK code directly in a .NET Core (3.0) ASP.NET application hosted in an AppService with Managed Identity.
string serviceBusNamespace = "busnamespace_here";
string queueName = "with_service_name/test"; // NOT working with RBAC
// string queueName = "testrbac"; // Works with RBAC - no /
var msiTokenProvider = TokenProvider.CreateManagedIdentityTokenProvider();
var qc = new QueueClient(new Uri($"sb://{serviceBusNamespace}.servicebus.windows.net/").ToString(), queueName, msiTokenProvider);
var message = new Message(Encoding.UTF8.GetBytes($"Test {DateTime.Now.ToShortTimeString()}"))
{
ContentType = "application/text",
Label = "Scientist",
MessageId = Guid.NewGuid().ToString()
};
try
{
await qc.SendAsync(message);
}
catch (Exception ex)
{
return View(ex.ToString());
}
I found out that the error seems to be caused by the presence of a / in the queue name. It's a character that is allowed in the Service Bus but it doesn't seems to works quite nicely with RBAC Service Bus feature.
The same code works well if you use a SAS Policy instead of Managed Identity/Client Secret.
Here is my test Service Bus in image (using Service Bus Explorer) :
Mass Transit
I know Mass Transit can use entity path with slash character in it. Does that means we can't use RBAC to access those entities ?
I wasn't able to find what is the root cause.

Occasional 500s using Faces plugin - Delegates cannot be marshalled

We're using 3.4.3 of ImageResizer, and the elite plugins. It seems any trouble we’ve had have been related to the Faces plugin. Images will not show up, and upon looking at the network response, the stacktrace shows "Delegates cannot be marshaled from native code into a domain other than their home domain". Full trace is here
[NotSupportedException: Delegates cannot be marshaled from native code into a domain other than their home domain.]
System.Runtime.InteropServices.Marshal.GetDelegateForFunctionPointerInternal(IntPtr ptr, Type t) +0
System.Runtime.InteropServices.Marshal.GetDelegateForFunctionPointer(IntPtr ptr, Type t) +267
OpenCvSharp.CvInvoke..cctor() +328
[TypeInitializationException: The type initializer for 'OpenCvSharp.CvInvoke' threw an exception.]
OpenCvSharp.Cv.Load(String filename, CvMemStorage memstorage, String name, String& real_name) +222
ImageResizer.Plugins.Faces.FeatureDetectionBase`1.LoadFiles() +621
ImageResizer.Plugins.Faces.FeatureDetectionBase`1.DetectFeatures(Bitmap b) +82
ImageResizer.Plugins.Faces.FacesPlugin.PostPrepareSourceBitmap(ImageState s) +341
ImageResizer.Resizing.AbstractImageProcessor.PostPrepareSourceBitmap(ImageState s) +99
ImageResizer.ImageBuilder.Process(ImageState s) +60
ImageResizer.ImageBuilder.buildToBitmap(Bitmap source, ResizeSettings settings, Boolean transparencySupported) +276
ImageResizer.ImageBuilder.buildToStream(Bitmap source, Stream dest, ResizeSettings settings) +149
ImageResizer.ImageBuilder.BuildJob(ImageJob job) +1353
ImageResizer.ImageBuilder.Build(ImageJob job) +268
ImageResizer.ImageBuilder.Build(Object source, Object dest, ResizeSettings settings, Boolean disposeSource, Boolean addFileExtension) +124
ImageResizer.ImageBuilder.Build(Object source, Object dest, ResizeSettings settings, Boolean disposeSource) +36
ImageResizer.ImageBuilder.Build(Object source, Object dest, ResizeSettings settings) +23
ImageResizer.<>c__DisplayClass3.<HandleRequest>b__2(Stream stream) +287
ImageResizer.Plugins.DiskCache.<>c__DisplayClasse.<TryWriteFile>b__d() +593
ImageResizer.Plugins.DiskCache.LockProvider.TryExecute(String key, Int32 timeoutMs, LockCallback success) +424
ImageResizer.Plugins.DiskCache.CustomDiskCache.TryWriteFile(CacheResult result, String physicalPath, String relativePath, ResizeImageDelegate writeCallback, DateTime sourceModifiedUtc, Int32 timeoutMs, Boolean recheckFS) +517
ImageResizer.Plugins.DiskCache.CustomDiskCache.GetCachedFile(String keyBasis, String extension, ResizeImageDelegate writeCallback, DateTime sourceModifiedUtc, Int32 timeoutMs, Boolean asynchronous) +819
ImageResizer.Plugins.DiskCache.DiskCache.Process(IResponseArgs e) +209
ImageResizer.Plugins.DiskCache.DiskCache.Process(HttpContext context, IResponseArgs e) +47
ImageResizer.InterceptModule.HandleRequest(HttpContext context, String virtualPath, NameValueCollection queryString, IVirtualFile vf) +1687
ImageResizer.InterceptModule.CheckRequest_PostAuthorizeRequest(Object sender, EventArgs e) +1163
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +92
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +165
I found this page and ensured we weren't using overlapped recycling. I tried upgrading to 4.1.7, but it was a bit of a nightmare trying to get all the opencv versions/bitness to line up. The app would crash often and hold the rest of the sites depending on it hostage, so we rolled back to 3.4.3 which at least works, then doesn't. Our regular issues go away temporarily when we restart the IR app pool.
We have our web apps hosted on two VMS load-balanced by BigIP. Each VM has two web apps, and they share a single image resizer hosted on the same server as them which and utilizes the URL API to make resize requests, face detection + cropping, etc.
One other bit of info I was able to obtain was from DebugDiag. I grabbed a crash of the app with the following message:
In w3wp__ImageResizer__PID__5284__Date__06_14_2017__Time_08_23_10AM__122__First chance exception 0XE0434352.dmp the assembly instruction at KERNELBASE!RaiseException in C:\Windows\System32\KERNELBASE.dll from Microsoft Corporation has caused a CLR Exception on thread 28 with the following error information:
Type: ImageResizer.Plugins.Faces.AlternateResponseException
Message: Resizing was canceled as JSON data was requested instead
This exception originated from ImageResizer.Plugins.Faces.FacesPlugin.Render(ImageResizer.Resizing.ImageState).
Debug page can be found here

Azure ACS with HTTPS and multiple instances Error

I just followed the following instructions here.
And found a couple blog entries here and here to be rather helpful.
But I am still getting weird issues with my ASP.NET MVC3 app running on Azure on an HTTPS end point. I have the HTTPS certificate loaded and it has deployed consistently on a single role instance for quite some time without any issue. However, just recently I started deploying multiple instances and ran into the 'Key not valid for use in specified state' and the 'Value cannot be null. Parameter name: certificate' erors.
But I have a new one now:
'Unable to read beyond the end of the stream.'
Looks pretty vanilla. It doesn't become obvious that its an issue with the move from DPAPI to the RSA cookie transform until you look at the stack trace.
[EndOfStreamException: Unable to read beyond the end of the stream.]
System.IO.MemoryStream.InternalReadInt32() +12750266
Microsoft.IdentityModel.Web.RsaEncryptionCookieTransform.Decode(Byte[] encoded) +369
Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ApplyTransforms(Byte[] cookie, Boolean outbound) +189
Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(XmlReader reader, SecurityTokenResolver tokenResolver) +862
Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(Byte[] token, SecurityTokenResolver tokenResolver) +109
Microsoft.IdentityModel.Web.SessionAuthenticationModule.ReadSessionTokenFromCookie(Byte[] sessionCookie) +356
Microsoft.IdentityModel.Web.SessionAuthenticationModule.TryReadSessionTokenFromCookie(SessionSecurityToken& sessionToken) +123
Microsoft.IdentityModel.Web.SessionAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs eventArgs) +61
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +270
I have added the following code to global.asax:
void OnServiceConfigurationCreated(object sender, ServiceConfigurationCreatedEventArgs e)
{
//
// Use the <serviceCertificate> to protect the cookies that are sent to the client.
//
List<CookieTransform> sessionTransforms = new List<CookieTransform>(
new CookieTransform[] {
new DeflateCookieTransform(),
new RsaEncryptionCookieTransform(e.ServiceConfiguration.ServiceCertificate) });
SessionSecurityTokenHandler sessionHandler = new SessionSecurityTokenHandler(sessionTransforms.AsReadOnly());
e.ServiceConfiguration.SecurityTokenHandlers.AddOrReplace(sessionHandler);
}
As well as this code:
void WSFederationAuthenticationModule_RedirectingToIdentityProvider(object sender, RedirectingToIdentityProviderEventArgs e)
{
// In the Windows Azure environment, build a wreply parameter for the SignIn request
// that reflects the real address of the application.
HttpRequest request = HttpContext.Current.Request;
Uri requestUrl = request.Url;
StringBuilder wreply = new StringBuilder();
wreply.Append(requestUrl.Scheme); // e.g. "http" or "https"
wreply.Append("://");
wreply.Append(request.Headers["Host"] ?? requestUrl.Authority);
wreply.Append(request.ApplicationPath);
if (!request.ApplicationPath.EndsWith("/")) wreply.Append("/"); e.SignInRequestMessage.Reply = wreply.ToString();
}
I recently worked on similar problem and the potential reason was combination of older SDK and ACS. If you try using SDK 1.6 and ACSv2 setting, i hope this problem will not occur and if you still see the problem, I would be glad to work with you to root cause it.

Resources