ImageProcessor with EPiServer not working - episerver

I am trying to configure an EPiServer 9 site with ImageProcessor but can't get it to work.
I have installed the following nuget packages:
ImageProcessor
ImageProcessor.Web
ImageProcessor.Web.Config
With the default configuration nothing happens. With the following custom configuration in config/imageprocessor/security.config ...
<security>
<services>
<service name="CloudImageService" type="ImageProcessor.Web.Services.CloudImageService, ImageProcessor.Web">
<settings>
<setting key="MaxBytes" value="8194304" />
<setting key="Timeout" value="30000" />
<setting key="Host" value="http://site.local/globalassets/"/>
</settings>
</service>
<service prefix="remote.axd" name="RemoteImageService" type="ImageProcessor.Web.Services.RemoteImageService, ImageProcessor.Web">
<settings>
<setting key="MaxBytes" value="4194304" />
<setting key="Timeout" value="3000" />
<setting key="Protocol" value="http" />
</settings>
<whitelist>
</whitelist>
</service>
</services>
</security>
... it seems like ImageProcessor is trying to resize my image but I get below error ...
[ImageFormatException: Input stream is not a supported format.]
ImageProcessor.ImageFactory.Load(Stream stream) +523
ImageProcessor.Web.HttpModules.<ProcessImageAsync>d__34.MoveNext() +3308
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +31
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +62
System.Web.TaskAsyncHelper.EndTask(IAsyncResult ar) +64
System.Web.AsyncEventExecutionStep.OnAsyncEventCompletion(IAsyncResult ar) +162
... when trying to resize an image to 200px width like this:
http://site.local/globalassets/sample_image.jpg?width=200
Anyone have any suggestions on how I can get this to work? The image is showing as normal without the width parameter:
http://site.local/globalassets/sample_image.jpg

In projects where I've used EPiServer with ImageProcessor I have always had to create my own IImageService.
Something like this:
https://gist.github.com/andreas-cloudnine/34dc468205a230f0579585db17aa1593
The ImageFile used is the media type in your project that inherits from EPiServer.Core.ImageData.
Then you have to use it in web.config as well, just replace the entire section with this configuration:
<security>
<services>
<service name="EPiServerImageService" type="YourSite.EPiServerImageService, YourSite" />
</services>
</security>

Related

Need two services that share database in Tomcat 9

I would like to run two tomcat services on two ports (8080,8181) with different codeBases, but sharing the same database resource. When I do this, I get "javax.naming.NameNotFoundException: Name [comp/env/jdbc/mydb] is not bound in this Context. Unable to find [comp]." when it tries to initialize the second Service.
My Services look like this in the server.xml:
...
<GlobalNamingResources>
<Resource auth="Container" name="jdbc/mydb" url="jdbc:db2://myserver:50000/mydb" username="xxx" password="xxx" .... />
</GlobalNamingResources>
...
<Service name="Catalina8080">
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />
<Engine name="Catalina" defaultHost="localhost">
....
<Host name="localhost" appBase="webapps8080" unpackWARs="true" autoDeploy="true">
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" .... />
</Host>
</Engine>
</Service>
<Service name="Catalina8181">
<Connector port="8181" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8444" />
<Engine name="Catalina" defaultHost="localhost">
....
<Host name="localhost" appBase="webapps8181" unpackWARs="true" autoDeploy="true">
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" .... />
</Host>
</Engine>
</Service>
My server level context file looks like :
<Context>
...
<ResourceLink name="jdbc/mydb" global="jdbc/mydb" type="javax.sql.DataSource" />
</Context>
I've tried adding and removing the Resource links at the application level context file, but nothing seems to change the outcome. Any thoughts are greatly appreciated.
You should change the name of your <Engine> in the second service: there can be only one naming context for each combination of engine name, host name and context name.
In your case the combination (Catalina, localhost, your application name) probably appears twice, hence you should be able to find an entry like this:
SEVERE [main] naming.namingContextCreationFailed
in the logs and JNDI doesn't work in the second context.

Can't insert into SQL Server table with log4net AdoNetAppender

I am trying to understand how log4net works so I've added this to my app.config (I should add that Console Appender and FileAppender work perfectly, I only have trouble with the AdoNetAppender).
How can I debug this, to see if at least the connection to db succeeds?
The problem is the INSERT statement isn't executed.
I should add the
Data Source=MyWorkgroup\SQLEXPRESS;Initial Catalog=MyNewDatabase;User ID=juan;password=juan,
works perfectly when I try to connect to SQL Server manually, so not sure if that's the problem.
Also, the ConnectionType was taken from the official site:
https://logging.apache.org/log4net/log4net-1.2.11/release/sdk/log4net.Appender.AdoNetAppender.ConnectionType.html
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net"
type="log4net.Config.log4netConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<appender name="AdoNetAppender"
type="log4net.Appender.AdoNetAppender">
<bufferSize value="10" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="Data Source=MyWorkgroup\SQLEXPRESS;Initial Catalog=MyNewDatabase;User ID=juan;Password=juan;Pooling=False" />
<commandText value="INSERT INTO Logs([logDate],[logThread],[logMessage]) VALUES(getdate(),'1','1')" />
<commandType value="Text" />
</appender>
<root>
<level value="DEBUG"/>
<appender-ref ref="AdoNetAppender"/>
</root>
</log4net>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
Later edit (after using the debug method recommended by David):
haacked.com is indeed extremely interesting, great tip! However, it seems that it's describing what I'm instructing log4net to log, but not the result of those actions(?), if I'm reading this well (no failed/or succeeded?)
e.g.
log4net: Setting Property [ConnectionType] to String value
[System.Data.SqlClien t.SqlConnection, System.Data,
Version=1.0.3300.0, Culture=neutral, PublicKeyToke n=b77a5c561934e089]
log4net: Setting Property [ConnectionString] to String value [Data
Source=MyWorkgroup\SQLEXPRESS; Initial
Catalog=MyNewDatabase;
User ID=juan; Password=juan;
Pooling=False] log4net: Setting Property [CommandText] to String value [INSERT INTO Logs([logDate],[logThread],[logMessage]) VALUES(getdate(),'1','1')] log4net:
Setting Property [CommandType] to CommandType value [Text] log4net:
Created Appender [AdoNetAppender] log4net: Adding appender named
[AdoNetAppender] to logger [root]. log4net: Hierarchy Threshold []
Piece of code that helped me obtain this info (in case the site should become unavailable) is:
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="C:\temp\log4netdiagn.txt" />
</listeners>
</trace>
</system.diagnostics>

WCF Silverlight service returns custom fault but as HTTP 500 response not 200

It seems like I've been banging my head with custom faults in my Silverlight WCF service forever so I will happily DO MY BEST TO BUY A BEER for anyone who can help me solve this!!!
After much pain I finally have my WCF service throwing custom errors (ParameterValidationFault) and using Fiddler I know that the service's response contains my serialized fault object, but the HTTP response code is 500, not 200, so the client starts throwing exceptions rather than reading the response.
I know my SilverlightFaultBehavior class is supposed to take care of changing the response status code, but the breakpoints I set there are never being hit, so I'm hoping this is a simple web.config issue (web.config at end of post).
If this is relevant my web.config shows "the element 'behavior' has invalid child element 'silverlightFaults'...", in the section
<endpointBehaviors>
<behavior name="SilverlightFaultBehavior">
<silverlightFaults/>
</behavior>
</endpointBehaviors>
but I thought this wasn't a problem as I can view the service's metadata without error. However now I'm thinking this is the missing link that's preventing my status code from being changed on the way out. I have read that this error indicates a problem with the type attribute within my behaviorExtension element not exactly matching what .NET thinks it should be, but I have checked this a million times and the namespace and assembly name are definitely correct. I haven't messed with the version, culture, or public key stuff.
Is there a simple way for .NET to tell me exactly what this type string should be (spaces, commas, and all)? I have viewed the dll's properties in explorer but I'm still no closer.
Any other suggestions on where this might be coming from would be hugely appreciated.
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<extensions>
<behaviorExtensions>
<add name="silverlightFaults" type="my.namespace.SilverlightFaultBehavior, AssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</behaviorExtensions>
</extensions>
<behaviors>
<endpointBehaviors>
<behavior name="SilverlightFaultBehavior">
<silverlightFaults/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<customBinding>
<binding name="my.namespace.IService.customBinding0">
<binaryMessageEncoding />
<httpTransport />
</binding>
</customBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<services>
<service name="my.namespace.IService">
<endpoint address="" binding="customBinding" bindingConfiguration="my.namespace.IService.customBinding0" contract="my.namespace.IService" behaviorConfiguration="SilverlightFaultBehavior" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
</system.serviceModel>
</configuration>
My SilverlightFaultBehavior class starts like this and is a copy-paste of this MSDN post with a namespace change
namespace my.namespace
{
public class SilverlightFaultBehavior : BehaviorExtensionElement, IEndpointBehavior
{
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
OK so this problem has not been resolved but worked-around. I finally saw in this very useful post that I can have anonymous endpointBehaviors. The behaviour is now applied and custom faults are correctly (in a non-standard kind of way) returned as HTTP 200s. Making the behavior anonymous means it is applied to all endpoints, but as my service currently only needs a single endpoint this works for me.
It truly sucks that I had all this grief after reading the friggin manual and implementing it word for word. In the end my config parse error "the element 'behavior' has invalid child element 'silverlightFaults'..." was irrelevant, but a very smelly red-herring along the way as it very well could have been the cause (and still may be).
In case anyone is wondering, I just drank the beer.

silverlightFaultBehavior for WCF - but still getting code 500

I want to get a meaningful error message from my WCF service for my Silverlight 4 application. After some investigation, I found that I need to change the reply code from 500 to 200 if I want silverlight enable to read the meaningful error message. Here is the article: http://msdn.microsoft.com/de-de/library/ee844556(VS.95).aspx
I have implemented it as it is written there, the application compiles and I can use the service - but I still get the 500 return code. The main difference I see is that I call the service via HTTPS not HTTP. Maybe this is the reason, why it doesn't work? Any idea, how to get the return code 200?
Here is my Web.Config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="ServiceConfiguratorDataSource.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<extensions>
<behaviorExtensions>
<add name="silverlightFaults" type="ServiceConfiguratorDataSource.SilverlightFaultBehavior, ServiceConfiguratorDataSource, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</behaviorExtensions>
</extensions>
<services>
<service name="ServiceConfiguratorDataSource.Service" behaviorConfiguration="ServiceConfiguratorDataSourceBehaviour">
<endpoint address="" binding="customBinding" behaviorConfiguration="SLFaultBehavior" bindingConfiguration="ServiceConfiguratorCustomBinding" contract="ServiceConfiguratorDataSource.IService" />
</service>
</services>
<bindings>
<customBinding>
<binding name="ServiceConfiguratorCustomBinding">
<security authenticationMode="UserNameOverTransport"></security>
<binaryMessageEncoding></binaryMessageEncoding>
<httpsTransport/>
</binding>
</customBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceConfiguratorDataSourceBehaviour">
<serviceMetadata httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="True"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="ServiceConfiguratorDataSource.UserCredentialsValidator,ServiceConfiguratorDataSource" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="SLFaultBehavior">
<silverlightFaults/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
... and here the silverlightFaultBehavior.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;
using System.ServiceModel;
namespace ServiceConfiguratorDataSource
{
public class SilverlightFaultBehavior : BehaviorExtensionElement, IEndpointBehavior
{
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
SilverlightFaultMessageInspector inspector = new SilverlightFaultMessageInspector();
endpointDispatcher.DispatchRuntime.MessageInspectors.Add(inspector);
}
public class SilverlightFaultMessageInspector : IDispatchMessageInspector
{
public void BeforeSendReply(ref Message reply, object correlationState)
{
if (reply.IsFault)
{
HttpResponseMessageProperty property = new HttpResponseMessageProperty();
// Here the response code is changed to 200.
property.StatusCode = System.Net.HttpStatusCode.OK;
reply.Properties[HttpResponseMessageProperty.Name] = property;
}
}
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
// Do nothing to the incoming message.
return null;
}
}
// The following methods are stubs and not relevant.
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
}
public void Validate(ServiceEndpoint endpoint)
{
}
public override System.Type BehaviorType
{
get { return typeof(SilverlightFaultBehavior); }
}
protected override object CreateBehavior()
{
return new SilverlightFaultBehavior();
}
}
}
Someone knows if this is because of https ... and if so, how to get it to work?
Thanks in advance,
Frank
EDITH says: I just have added some logging: the ApplyDispatchBehavior - method is called, but the BeforeSendReply - method not ... any ideas why?
If I remember correctly, the UserNamePasswordValidator gets called very early in the pipeline, before the dispatcher ever gets called, which is why your custom dispatch behavior isn't affecting anything. (The reason is security: WCF wants to "throw out" unauthorized requests as early as possible, while running as little code as possible for them).
As you yourself suggested in the comments, one solution would be to just validate the credentials later in the pipeline - e.g. in every operation (or maybe even in a message inspector's AfterReceiveRequest?)

SecurityError when calling a HTTPS-WCF Service from Silverlight 4

I have created a simple WCF-Service which I want to be accessible via https. The WCF-Service uses a UserNamePasswordValidator, customBinding and UserNameOverTransport as authentication mode. I run it in the IIS7.5 where I have created a self-signed server certificate.
I try to connect to that service with an Silverlight 4 application. I create a Service Reference in my Silverlight 4 app, and VS 2010 automatically creates the needed code (so obviously it is able to connect to the service and get the information).
When I call the WCF, I get a SecurityException with no infos about the reason.
I have fiddler running to see what is happening.
GET https://my.server:8099/clientaccesspolicy.xml 404 Not Found (text/html)
GET https://my.server:8099/crossdomain.xml 200 OK (text/xml)
So the GET for the crossdomain.xml seems to be the last call to the server.
The crossdomain.xml looks as follows:
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-access-from domain="*" />
<allow-http-request-headers-from domain="*" headers="*" />
</cross-domain-policy>
The exception happens, when base.EndInvoke(...) is called on the client and the ExceptionMessage is the following:
{System.Security.SecurityException ---> System.Security.SecurityException: Sicherheitsfehler
bei System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
bei System.Net.Browser.BrowserHttpWebRequest.<>c_DisplayClass5.b_4(Object sendState)
bei System.Net.Browser.AsyncHelper.<>c_DisplayClass2.b_0(Object sendState)
--- Ende der internen Ausnahmestapelüberwachung ---
bei System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
bei System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
bei System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)}
Here is my UserNamePasswordValidator. Note, that included a logger for debugging reasons. Strange thing is, that the logger never writes anything, so it seems, that the Validate function isn't even called.
namespace ServiceConfiguratorDataSource
{
public class UserCredentialsValidator : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
if (userName != "xyz" || password != "xyz")
{
logging.Logger.instance.StatusRoutine("LogOn Error: " + userName);
throw new FaultException("Credentials are invalid");
}
else
{
logging.Logger.instance.StatusRoutine("LogOn Success: " + userName);
}
}
}
}
Here is the Web.config of my WCF-Service:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service name="ServiceConfiguratorDataSource.Service" behaviorConfiguration="ServiceConfiguratorDataSourceBehaviour">
<endpoint address="" binding="customBinding" bindingConfiguration="ServiceConfiguratorCustomBinding" contract="ServiceConfiguratorDataSource.IService" />
</service>
</services>
<bindings>
<customBinding>
<binding name="ServiceConfiguratorCustomBinding">
<security authenticationMode="UserNameOverTransport"></security>
<binaryMessageEncoding></binaryMessageEncoding>
<httpsTransport/>
</binding>
</customBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceConfiguratorDataSourceBehaviour">
<serviceMetadata httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="ServiceConfiguratorDataSource.UserCredentialsValidator,ServiceConfiguratorDataSource" />
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
and here the ServiceReferences.ClientConfig
<configuration>
<system.serviceModel>
<bindings>
<customBinding>
<binding name="CustomBinding_IService">
<security authenticationMode="UserNameOverTransport" includeTimestamp="true">
<secureConversationBootstrap />
</security>
<binaryMessageEncoding />
<httpsTransport maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" />
</binding>
</customBinding>
</bindings>
<client>
<endpoint address="https://my.server:8099/ServiceConfiguratorDataSource/Service.svc" binding="customBinding" bindingConfiguration="CustomBinding_IService" contract="WCFDataProvider.IService" name="CustomBinding_IService" />
</client>
</system.serviceModel>
</configuration>
I'm out of ideas what might be the cause of the problem.
Thanks in advance,
Frank
Does you clientaccesspolicy.xml allow https?
Here is example.
The working clientaccesspolicy.xml -> Tipp from Samvel Siradeghyan
<?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="https://*"/>
<domain uri="http://*"/>
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>

Resources