Imports ComponentPro

Namespace AdvancedDemo.Samples.Function_and_Property
	Friend Class Custom_Function
		Inherits TemplateExampleBase
		Private Shared Function Power(ByVal dt As TemplateEngine, ByVal args() As Object) As Object
			' Function has two parameters
			If Not TemplateEngine.VerifyParameters(dt, "Pow", args, 2) Then
				Return String.Empty
			End If
			Try
				Dim x As Double = Convert.ToDouble(args(0))
				Dim y As Double = Convert.ToDouble(args(1))
				Return Math.Pow(x, y)
			Catch exc As Exception
				dt.WriteError("Invalid parameter, error: " & exc.Message)
				Return String.Empty
			End Try
		End Function

		''' <summary>
		''' Although TemplateEngine already provided a powerful + operator for string object, we purposely create a function to concatenate two strings for demonstration only.
		''' </summary>
		Private Shared Function Concat(ByVal dt As TemplateEngine, ByVal args() As Object) As Object
			' Function has two parameters in string type.
			If Not TemplateEngine.VerifyParameters(dt, "Concat", args, 2, GetType(String), GetType(String)) Then
				Return String.Empty
			End If
			Dim s1 As String = TryCast(args(0), String)
			Dim s2 As String = TryCast(args(1), String)
			Return s1 & s2
		End Function

		''' <summary>
		''' Generates output from a template file.
		''' </summary>
		''' <param name="templateSourceDirectory">The path to the directory that contains the template file.</param>
		''' <param name="templateFile">The template file path.</param>
		''' <param name="templateSource">The template source loaded from the template file.</param>
		''' <returns>The generated output.</returns>
		Public Overrides Function Generate(ByVal templateSourceDirectory As String, ByVal templateFile As String, ByVal templateSource As String) As String
			' Create a new instance of the TemplateEngine class.
			Dim dt As New TemplateEngine()

			' Load template content from a file.
			dt.LoadFromString(templateSource)
			dt.SetValue("TemplateSourceDirectory", templateSourceDirectory)

			dt.SetFunction("Pow", AddressOf Power)
			dt.SetFunction("Concat", AddressOf Concat)

			dt.SetValue("x", 15.0F)
			dt.SetValue("y", 2.3F)
			dt.SetValue("str1", "Hello ")
			dt.SetValue("str2", "World")

			' Generate output.
			Dim output As String = dt.Run()

			Return output
		End Function
	End Class
End Namespace
