Imports ComponentPro

Namespace FunctionSample
	Friend NotInheritable Class Program

		Private Sub New()
		End Sub

		<STAThread> _
		Shared Sub Main()
			FunctionSample()
		End Sub

		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 concat 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

		Public Shared Sub FunctionSample()
			Try
				Dim dn As New TemplateEngine()
				dn.LoadFromString("Custom Pow Function demo: $x$ ^ $y$ = $Pow(x,y)$" & vbCrLf & "Custom String Concatenation: ""$str1$"" + ""$str2$"" = ""$Concat(str1, str2)$""")
				dn.SetFunction("Pow", AddressOf Power)
				dn.SetFunction("Concat", AddressOf Concat)

				dn.SetValue("x", 15.0F)
				dn.SetValue("y", 2.3F)

				dn.SetValue("str1", "Hello ")
				dn.SetValue("str2", "World")

				MessageBox.Show(dn.Run())
			Catch exc As Exception
				MessageBox.Show("An exception occurred: " & exc.Message)
			End Try
		End Sub
	End Class
End Namespace