Developer forum

Forum » Development » Custom module IP detection change IMC SRC

Custom module IP detection change IMC SRC

Peter Bille Larsen
Reply

Hey DWs

 

would it be possible to change all IMC SRCs in a template to another server folder, based on IP detection?

Any input to how we could make such a module (fast and cost-efficient).

 

Kind regards

Peter

 

 


Replies

 
Nicolai Høeg Pedersen
Reply
This post has been marked as an answer

You can first look up the user country by either accept language or using an IP lookup tool like this one:

http://dev.maxmind.com/geoip/geolite

 

Then create a notification subscriber that replaces all the image src attributes based on that rule - here is an example that adds a CDN host, you need to change it a bit.

 

Imports System.Text.RegularExpressions

<Dynamicweb.Extensibility.Subscribe(Dynamicweb.Notifications.Standard.Page.AfterOutput)> _
Public Class CdnReplacer
	Inherits Dynamicweb.Extensibility.NotificationSubscriber

	Public Overrides Sub OnNotify(ByVal notification As String, ByVal args As Object())
		If Not Dynamicweb.Base.ChkBoolean(Dynamicweb.Base.GetGs("/Globalsettings/System/cdn/active")) Then
			Return
		End If
		If args Is Nothing OrElse args.Length = 0 Then
			Return
		End If

		Dim obj As Object = args(0)

		If Not (TypeOf obj Is Dynamicweb.Rendering.Template) Then
			Return
		End If

		Dim tmpl As Dynamicweb.Rendering.Template = DirectCast(obj, Dynamicweb.Rendering.Template)

		Dim ResultString As String
		Try
			Dim host As String = "http://cdn.mydomain.com"
			If String.IsNullOrEmpty(host) OrElse Not host.StartsWith("http://") Then
				Return
			End If
			ResultString = GetIfRegexInstance().Replace(tmpl.Html, String.Format("$1{0}/$2", host))
			tmpl.Html = ResultString
		Catch ex As ArgumentException
			'Syntax error in the regular expression
		End Try
	End Sub

	Private Shared _RegexInstance As Regex
	Private Shared Function GetIfRegexInstance() As Regex
		If _RegexInstance Is Nothing Then
			_RegexInstance = New Regex("(<img src="")(?:[^""]*?/?)(Files/.*?"")", RegexOptions.IgnoreCase Or RegexOptions.Singleline Or RegexOptions.Compiled)
		End If
		Return _RegexInstance
	End Function
End Class

BR Nicolai

Votes for this answer: 1
 
Peter Bille Larsen
Reply

awesome, yes it is exactly the thought that it is to be used as CDN for customers in America/Asia.

 

thanks!

 

 

 

You must be logged in to post in the forum