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
Related
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!
I would like to set the DefaultServiceVersion for my azure storage instance, so I wrote the following code:
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("CloudStorageConnectionString"));
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
var serviceProperties = blobClient.GetServiceProperties();
if (serviceProperties.DefaultServiceVersion != "2011-08-18")
{
serviceProperties.DefaultServiceVersion = "2011-08-18";
blobClient.SetServiceProperties(serviceProperties);
}
I then tried to run it with the development storage server, and got an exception (erroring in the dev server by the looks) from blobClient.GetServiceProperties()
Microsoft.WindowsAzure.StorageClient.StorageServerException was unhandled by user code
HResult=-2146233088
Message=Server encountered an internal error. Please try again after some time.
Source=Microsoft.WindowsAzure.StorageClient
StackTrace:
at Microsoft.WindowsAzure.StorageClient.Tasks.Task`1.get_Result()
at Microsoft.WindowsAzure.StorageClient.Tasks.Task`1.ExecuteAndWait()
at Microsoft.WindowsAzure.StorageClient.TaskImplHelper.ExecuteImplWithRetry[T](Func`2 impl, RetryPolicy policy)
at Microsoft.WindowsAzure.StorageClient.CloudBlobClient.GetServiceProperties()
at ConsoleApp.GetContainer() in c:\app\Program.cs:line 90
at ConsoleApp.Main() in c:\app\Program.cs:line 47
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
InnerException: System.Net.WebException
HResult=-2146233079
Message=The remote server returned an error: (500) Internal Server Error.
Source=System
StackTrace:
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at Microsoft.WindowsAzure.StorageClient.EventHelper.ProcessWebResponse(WebRequest req, IAsyncResult asyncResult, EventHandler`1 handler, Object sender)
InnerException:
Is it possible to set the DefualtServiceVersion with a dev server? I haven't tried with the real thing as I really only want to test if this solves another issue I'm having.
Based on the documentation here: http://msdn.microsoft.com/en-us/library/windowsazure/microsoft.windowsazure.storage.blob.cloudblobclient.getserviceproperties.aspx (scroll down to "Remarks" section), this operation is not currently supported on local storage. Also SetServiceProperties operation which enables/disables storage analytics is also not supported.
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.
I have the following code
var factory = new ChannelFactory<INewsClient>();
factory.Credentials.ClientCertificate.Certificate = GetCertificate();
factory.Endpoint.Address = new EndpointAddress("https://blabla.com/myservice/");
var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
factory.Endpoint.Binding = binding;
var channel = factory.CreateChannel();
channel.GetNews();
It works in .NET 3.5, but not in .NET4.0. Bizzare huh?
The Certificate I am using doesn't validate on the local machine (no chain). In 3.5, the client cert's validity is irrelevant to establishing SSL, but when migrating to 4.0, the certificate is validated before being used for SSL. (I can see errors in the CAPI2 Event logs). Resulting in an ugly SecurityNegotiationException...
Stack Trace:
System.ServiceModel.Security.SecurityNegotiationException: Could not establish secure channel for SSL/TLS with authority 'pep.uat.dialectpayments.com'. ---> System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
--- End of inner exception stack trace ---
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
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 ConsoleApplication2.Program.INewsClient.Get()
at ConsoleApplication2.Program.Main(String[] args) in d:\dev\ConsoleApplication2\Program.cs:line 44
In our security architecture, certs are validated against an LDAP directory on the server, therefore no need for clients to know the full chain.
Question is, how do I disable this new behaviour?
Ok, I'll provide my own answer here...
In a nutshell: It seems you cannot use a non-persistent CSP with .NET 4 for X509. I.e. Your CSP must have a KeyContainerName for it to work.
My GetCertificate() method was doing the following: (i.e. Non-Persistent)
var certificate = new X509Certificate2(#"C:\public.cer");
var rsa = RSA.Create();
rsa.FromXmlString("<RSAKeyValue>......</RSAKeyValue>");
certificate.PrivateKey = rsa;
return certificate;
Changing it to this makes my sample work in 3.5 and 4.0: (Setting KeyContainerName will create a physical entry in your crypto folders)
var certificate = new X509Certificate2(#"C:\public.cer");
CspParameters parameters = new CspParameters { KeyContainerName = "KeyContainer" };
var rsa = new RSACryptoServiceProvider(parameters);
rsa.FromXmlString("<RSAKeyValue>......</RSAKeyValue>");
certificate.PrivateKey = rsa;
return certificate;
For simplicity, I was trying to export the private key into a .pfx file, but couldn't using the first approach in .NET 4.0, but could using .NET 3.5. Somwhow, the private key is not exportable in .NET 4.0.
This link helped me fix it.
Still, would be nice to know what's changed between 3.5 and 4.0 here.
I am using the below code to take print screen of my web page.
using (Bitmap bitmap = new Bitmap(620, 850))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
}
bitmap.Save(System.AppDomain.CurrentDomain.BaseDirectory.ToString() + 1 + ".JPEG", ImageFormat.Jpeg);
}
It works fine in the development machine,but once i deploy it in the Server
it gives below error
Error Message:
The handle is invalid
Source: System.DrawingError
Stack Trace: at System.Drawing.Graphics.CopyFromScreen(Int32 sourceX, Int32 sourceY, Int32 destinationX, Int32 destinationY, Size blockRegionSize, CopyPixelOperation copyPixelOperation)
at System.Drawing.Graphics.CopyFromScreen(Int32 sourceX, Int32 sourceY, Int32 destinationX, Int32 destinationY, Size blockRegionSize)
at System.Drawing.Graphics.CopyFromScreen(Point upperLeftSource, Point upperLeftDestination, Size blockRegionSize)
at Secure_SearchReport.btnSearch_Click(Object sender, EventArgs e)
at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
Its very urgent.
Any suggestion please.......
I would guess the graphics functionality is only available in rich-client applications. (Windows Forms)
This would be a huge security issue if webpages could capture snapshots of users' desktop.
You may try VisualJS.NET, the video under http://www.visualjs.net/Tutorials/WhatisVisualJSNET.aspx page could be helpful. They using Cassini Dev server in addition to built-in VisualJS.NET features in order to demonstrate very simple remote desktop over web application.