EnableDocumentFunction Asp.net XSLT XML - asp.net

how do I enable xsltSettingf EnableDocumentFunction in Asp.net/VB in order to use document() in XSLT?
Public Shared Function xmlGetter(ByVal strXSLTFile As String, ByVal strXMLFile As String) As String
Dim reader As XmlReader = XmlReader.Create(strXMLFile)
Dim objXSLTransform As New XslCompiledTransform()
Dim xsltSettings As New XsltSettings()
xsltSettings.EnableDocumentFunction = True
objXSLTransform.Load(strXSLTFile)
Dim htmlOutput As New StringBuilder()
Dim htmlWriter As TextWriter = New StringWriter(htmlOutput)
objXSLTransform.Transform(reader, Nothing, htmlWriter)
Dim s As String
s = htmlOutput.ToString()
Return s
reader.Close()
End Function

There are overloads of the Load method (such as http://msdn.microsoft.com/en-us/library/ms163426.aspx) that take XsltSettings: objXSLTransform.Load(strXSLTFile, xsltSettings, Nothing).

Related

QueryStringModule with FriendlyUrls does not working

Good morning, I need to encrypt my querystring and i found an interesting method in this link and I convert it in vb.net:
Imports System
Imports System.IO
Imports System.Web
Imports System.Text
Imports System.Security.Cryptography
Public Class QueryStringModule
Implements IHttpModule
Public Sub Dispose() Implements IHttpModule.Dispose
End Sub
Public Sub Init(ByVal context As HttpApplication) Implements IHttpModule.Init
AddHandler context.BeginRequest, New EventHandler(AddressOf context_BeginRequest)
End Sub
Private Const PARAMETER_NAME As String = "enc="
Private Const ENCRYPTION_KEY As String = "key"
Private Sub context_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
Dim context As HttpContext = HttpContext.Current
If context.Request.Url.OriginalString.Contains("aspx") AndAlso context.Request.RawUrl.Contains("?") Then
Dim query As String = ExtractQuery(context.Request.RawUrl)
Dim path As String = GetVirtualPath()
If query.StartsWith(PARAMETER_NAME, StringComparison.OrdinalIgnoreCase) Then
Dim rawQuery As String = query.Replace(PARAMETER_NAME, String.Empty)
Dim decryptedQuery As String = Decrypt(rawQuery)
context.RewritePath(path, String.Empty, decryptedQuery)
ElseIf context.Request.HttpMethod = "GET" Then
Dim encryptedQuery As String = Encrypt(query)
context.Response.Redirect(path & encryptedQuery)
End If
End If
End Sub
Private Shared Function GetVirtualPath() As String
Dim path As String = HttpContext.Current.Request.RawUrl
path = path.Substring(0, path.IndexOf("?"))
path = path.Substring(path.LastIndexOf("/") + 1)
Return path
End Function
Private Shared Function ExtractQuery(ByVal url As String) As String
Dim index As Integer = url.IndexOf("?") + 1
Return url.Substring(index)
End Function
Private ReadOnly Shared SALT As Byte() = Encoding.ASCII.GetBytes(ENCRYPTION_KEY.Length.ToString())
Public Shared Function Encrypt(ByVal inputText As String) As String
Dim rijndaelCipher As RijndaelManaged = New RijndaelManaged()
Dim plainText As Byte() = Encoding.Unicode.GetBytes(inputText)
Dim SecretKey As PasswordDeriveBytes = New PasswordDeriveBytes(ENCRYPTION_KEY, SALT)
Using encryptor As ICryptoTransform = rijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16))
Using memoryStream As MemoryStream = New MemoryStream()
Using cryptoStream As CryptoStream = New CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)
cryptoStream.Write(plainText, 0, plainText.Length)
cryptoStream.FlushFinalBlock()
Return "?" & PARAMETER_NAME & Convert.ToBase64String(memoryStream.ToArray())
End Using
End Using
End Using
End Function
Public Shared Function Decrypt(ByVal inputText As String) As String
Dim rijndaelCipher As RijndaelManaged = New RijndaelManaged()
Dim encryptedData As Byte() = Convert.FromBase64String(inputText)
Dim secretKey As PasswordDeriveBytes = New PasswordDeriveBytes(ENCRYPTION_KEY, SALT)
Using decryptor As ICryptoTransform = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16))
Using memoryStream As MemoryStream = New MemoryStream(encryptedData)
Using cryptoStream As CryptoStream = New CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)
Dim plainText As Byte() = New Byte(encryptedData.Length - 1) {}
Dim decryptedCount As Integer = cryptoStream.Read(plainText, 0, plainText.Length)
Return Encoding.Unicode.GetString(plainText, 0, decryptedCount)
End Using
End Using
End Using
End Function
End Class
but also my project use FriendlyUrls and I figured out that with FriendlyUrls the things does not working and always return the url without the extension ".aspx" but with the querystring not encrypted
Imports System.Web.Routing
Imports Microsoft.AspNet.FriendlyUrls
Public Module RouteConfig
Sub RegisterRoutes(ByVal routes As RouteCollection)
Dim settings As FriendlyUrlSettings = New FriendlyUrlSettings() With {
.AutoRedirectMode = RedirectMode.Permanent
}
routes.EnableFriendlyUrls(settings)
End Sub
End Module
of course if I set .AutoRedirectMode to Off it works but without friendlyurls.
Am I doing something wrong?
EDIT 09/10/2019:
We figured out that remove the test of OriginalString.Contains("aspx") in the context_BeginRequest the encryption works, now the code is like:
Private Sub context_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
Dim context As HttpContext = HttpContext.Current
If context.Request.RawUrl.Contains("?") Then
Dim query As String = ExtractQuery(context.Request.RawUrl)
Dim path As String = GetVirtualPath()
If query.StartsWith(PARAMETER_NAME, StringComparison.OrdinalIgnoreCase) Then
Dim rawQuery As String = query.Replace(PARAMETER_NAME, String.Empty)
Dim decryptedQuery As String = Decrypt(rawQuery)
context.RewritePath(path, String.Empty, decryptedQuery)
ElseIf context.Request.HttpMethod = "GET" Then
Dim encryptedQuery As String = Encrypt(query)
context.Response.Redirect(path & encryptedQuery)
End If
End If
End Sub
But now the question is: there is other method to target an aspx page without test the extension? I think there is a risk that targeting things that not should target like "ashx" or cache-busting code that use querystring.

Asp.net vb An error occurred during local report processing in Web Service

I have a web service gift redemption.After redeeem successfull, I want to generate a invoice(pdf content) and store into database. When in debug, it prompts me "An error occurred during local report processing" when it is at the renderedBytes process.
The rdlc is in the web service folder.
The below code works in web application but not in web service.
Public dtInvDtl As New DataTable
Protected Function GenerateInvoice(ByVal sID As String) As Boolean
Dim dtInvoice As DataTable = (get record from database)
Dim dtInvoiceDtl = (get record from database)
dtInvDtl = dtInvoiceDtl
oLocalReport = New LocalReport
oLocalReport.ReportPath = HttpContext.Current.Server.MapPath("Invoice.rdlc")
Dim reportDataSource As ReportDataSource = New ReportDataSource("DS_INVOICE", dtInvoice)
oLocalReport.DataSources.Add(reportDataSource)
' Add handler for subreporting binding function
AddHandler oLocalReport.SubreportProcessing, AddressOf Subreport
Dim reportType As String = "PDF"
Dim mimeType As String = String.Empty
Dim encoding As String = String.Empty
Dim fileNameExtension As String = String.Empty
Dim deviceInfo As String = "<DeviceInfo>" & _
" <OutputFormat>PDF</OutputFormat>" & _
" <PageWidth>8.5in</PageWidth>" & _
" <PageHeight>11in</PageHeight>" & _
"</DeviceInfo>"
Dim warnings() As Warning = Nothing
Dim streams() As String = Nothing
Dim renderedBytes() As Byte
' Render the report
renderedBytes = oLocalReport.Render(reportType, deviceInfo, mimeType, encoding, fileNameExtension, streams, warnings)
End Function
'SubReporting Binding Function
Protected Sub Subreport(ByVal sender As Object, ByVal e As SubreportProcessingEventArgs)
e.DataSources.Clear()
Dim rds = New ReportDataSource("INVOICE_DTL", dtInvDtl)
e.DataSources.Add(rds)
End Sub

cannot display image in image control

Its my handler (.ashx)
Dim EmployeeID As Integer
If (Not (context.Request.QueryString("EmployeeID")) Is Nothing) Then EmployeeID = Convert.ToInt32(context.Request.QueryString("EmployeeID"))
Else Throw New ArgumentException("No parameter specified") End If
Dim imageData() As Byte = {}
' get the image data from the database using the employeeId Querystring context.Response.ContentType = "image/jpeg"
context.Response.BinaryWrite(imageData)
Everything is working fine.Only the imageData length is 0 so the image is unable to display.
#Sean: its elsewhr.. here the querystring correctly takes the employeeid passed...
heres the code for db access:
Public Sub bind()
Dim ds1 As New DataSet()
Dim con As New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("ConnectionString").ToString)
con.Open()
Dim query As String = "select * from EmployeeTable"
Dim cmd As New SqlCommand()
Dim da1 As New SqlDataAdapter(query, con)
da1.Fill(ds1, "EmployeeTable")
GridView1.DataSource = ds1.Tables("EmployeeTable")
GridView1.DataBind()
con.Close()
End Sub
You're loading a load of data into the GridView but nothing is being loaded into your imageData variable. So we'll just connect to the database and pull that data out. I'm assuming your image column is called imageData but please change as appropriate.
Dim EmployeeID As Integer
If (Not (context.Request.QueryString("EmployeeID")) Is Nothing) Then
EmployeeID = Convert.ToInt32(context.Request.QueryString("EmployeeID"))
Else
Throw New ArgumentException("No parameter specified")
End If
Dim imageData() As Byte = {}
' get the image data from the database using the employeeId Querystring
Using con As New SqlConnection(ConfigurationManager.AppSettings("ConnectionString"))
Using cmd As New SqlCommand("SELECT imageData FROM EmployeeTable WHERE EmployeeID = #EmployeeID", con) 'select imageData column, change column name as appropriate
cmd.Parameters.AddWithValue("#EmployeeID", EmployeeID)
Try
con.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader()
If rdr.Read() Then
imageData = CType(rdr("imageData"), Byte()) 'convert imageData column from result set to byte array and assign to variable
End If
End Using
Catch ex As Exception
'do any error handling here
End Try
End Using
End Using
context.Response.ContentType = "image/jpeg"
context.Response.BinaryWrite(imageData)
Changed the code in the handler to this:
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim EmployeeID As Integer
If (Not (context.Request.QueryString("EmployeeID")) Is Nothing) Then
EmployeeID = Convert.ToInt32(context.Request.QueryString("EmployeeID"))
Else
Throw New ArgumentException("No parameter specified")
End If
Dim Image() As Byte = {}
' get the image data from the database using the employeeId Querystring
Dim con As New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("ConnectionString").ToString)
Dim cmd As New SqlCommand("SELECT Image FROM EmployeeTable WHERE EmployeeID = #EmployeeID", con)
'select imageData column, change column name as appropriate
cmd.Parameters.AddWithValue("#EmployeeID", EmployeeID)
Try
con.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader()
While rdr.Read()
Image = CType(rdr("Image"), Byte())
'convert imageData column from result set to byte array and assign to variable
End While
Catch ex As Exception
'do any error handling here
End Try
context.Response.ContentType = "image/jpeg"
context.Response.BinaryWrite(Image)
End Sub
Worked for me, may be it will work for you too...

Microsoft Translator for multiple textbox?

I get problem when use Microsoft Bing translator for show output on 3 labels for different languages.
Here is my code :
Imports System
Imports System.Collections.Generic
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Xml.Linq
Public Class AdmAccessToken
Public Property access_token() As String
Get
Return m_access_token
End Get
Set(ByVal value As String)
m_access_token = value
End Set
End Property
Private m_access_token As String
Public Property token_type() As String
Get
Return m_token_type
End Get
Set(ByVal value As String)
m_token_type = value
End Set
End Property
Private m_token_type As String
Public Property expires_in() As String
Get
Return m_expires_in
End Get
Set(ByVal value As String)
m_expires_in = value
End Set
End Property
Private m_expires_in As String
Public Property scope() As String
Get
Return m_scope
End Get
Set(ByVal value As String)
m_scope = value
End Set
End Property
Private m_scope As String
End Class
Partial Class translated
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
'Button1.Click += New EventHandler(Button1_Click1)
End Sub
Protected Sub Button1_Click1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim clientID As String = "*******"
Dim clientSecret As String = "************"
Dim strTranslatorAccessURI As String = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"
Dim strRequestDetails As String = String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(clientID), HttpUtility.UrlEncode(clientSecret))
Dim webRequest As System.Net.WebRequest = System.Net.WebRequest.Create(strTranslatorAccessURI)
webRequest.ContentType = "application/x-www-form-urlencoded"
webRequest.Method = "POST"
Dim bytes As Byte() = System.Text.Encoding.ASCII.GetBytes(strRequestDetails)
webRequest.ContentLength = bytes.Length
Using outputStream As System.IO.Stream = webRequest.GetRequestStream()
outputStream.Write(bytes, 0, bytes.Length)
End Using
Dim webResponse As System.Net.WebResponse = webRequest.GetResponse()
Dim serializer As New System.Runtime.Serialization.Json.DataContractJsonSerializer(GetType(AdmAccessToken))
Dim token As AdmAccessToken = DirectCast(serializer.ReadObject(webResponse.GetResponseStream()), AdmAccessToken)
Dim headerValue As String = "Bearer " + token.access_token
Dim txtToTranslate As String = TextBox1.Text
Dim uri As String = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(txtToTranslate) + "&from=en&to=es"
Dim translationWebRequest As System.Net.WebRequest = System.Net.WebRequest.Create(uri)
translationWebRequest.Headers.Add("Authorization", headerValue)
Dim response As System.Net.WebResponse = Nothing
response = translationWebRequest.GetResponse()
Dim stream As System.IO.Stream = response.GetResponseStream()
Dim encode As System.Text.Encoding = System.Text.Encoding.GetEncoding("utf-8")
Dim translatedStream As New System.IO.StreamReader(stream, encode)
Dim xTranslation As New System.Xml.XmlDocument()
xTranslation.LoadXml(translatedStream.ReadToEnd())
Label1.Text = "Your Translation is: " + xTranslation.InnerText
End Sub
End Class
Can anyone give some advice?
I just need to know how I can get translated text to 3 different label language: label 1 for dutch language, label 2 for english language, and label 3 for indonesian language.
The final chunk of code in your example does the translation from English to Spanish. (The part that starts with Dim txtToTranslate...)
You will have to just use that 3 times (put it in a function) with once doing a translation from your target language to Dutch, once to English, once to Indonesian.
The part where the translation is specified is this:
Dim uri As String = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(txtToTranslate) + "&from=en&to=es"
From=en means 'from English'
To=es means 'to Spanish'
So just amend that for the languages you need...

CA2000: Object is not disposed along all exception paths

I am having trouble trying to figure out why I'm getting this warning in following code.
CA2000 : Microsoft.Reliability : In method 'Encryption64.Decrypt(String, String)', object 'des' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'des' before all references to it are out of scope.
CA2000 : Microsoft.Reliability : In method 'Encryption64.Encrypt(String, String)', object 'des' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'des' before all references to it are out of scope.
Public Class Encryption64
Private key() As Byte = {}
Private IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}
Public Function Decrypt(ByVal stringToDecrypt As String, ByVal sEncryptionKey As String) As String
Dim des As New DESCryptoServiceProvider()
Dim ms As New MemoryStream()
Dim ReturnValue As String = String.Empty
Try
Dim inputByteArray(stringToDecrypt.Length) As Byte
key = System.Text.Encoding.UTF8.GetBytes(Left(sEncryptionKey, 8))
inputByteArray = Convert.FromBase64String(stringToDecrypt)
Dim cs As New CryptoStream(ms, des.CreateDecryptor(key, IV),CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
ReturnValue = encoding.GetString(ms.ToArray())
Catch e As Exception
ReturnValue = e.Message
Finally
If des IsNot Nothing Then
des.Dispose()
End If
If ms IsNot Nothing Then
ms.Dispose()
End If
End Try
Return ReturnValue
End Function
Public Function Encrypt(ByVal stringToEncrypt As String, ByVal SEncryptionKey As String) As String
Dim des As New DESCryptoServiceProvider()
Dim ms As New MemoryStream()
Dim ReturnValue As String = String.Empty
Try
key = System.Text.Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8))
Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes(stringToEncrypt)
Dim cs As New CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
ReturnValue = Convert.ToBase64String(ms.ToArray())
Catch e As Exception
ReturnValue = e.Message
Finally
If des IsNot Nothing Then
des.Dispose()
End If
If ms IsNot Nothing Then
ms.Dispose()
End If
End Try
Return ReturnValue
End Function
End Class
Since you are declaring (and instantiating) your des objects outside of the Try ... Finally blocks, it is possible for your code to raise an exception in the line Dim ms As New MemoryStream() and your .Dispose() will not be called.
When you are working with objects that implement IDisposable, it is much preferable where possible to wrap them in a Using block instead of a Try...Finally block. For example:
Public Function Decrypt(ByVal stringToDecrypt As String, ByVal sEncryptionKey As String) As String
Dim ms As New MemoryStream()
Dim ReturnValue As String = String.Empty
Dim inputByteArray(stringToDecrypt.Length) As Byte
key = System.Text.Encoding.UTF8.GetBytes(Left(sEncryptionKey, 8))
inputByteArray = Convert.FromBase64String(stringToDecrypt)
Using ms as New MemoryStream
Using des As New DESCryptoServiceProvider
Dim cs As New CryptoStream(ms, des.CreateDecryptor(key, IV),CryptoStreamMode.Write)
cs.Write(inputByteArray, 0, inputByteArray.Length)
cs.FlushFinalBlock()
End Using ' des
Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8
ReturnValue = encoding.GetString(ms.ToArray())
End Using ' ms
Catch e As Exception
ReturnValue = e.Message
End Try
Return ReturnValue
End Function
Just a guess, but maybe it's not smart enough to realize that this code line will always be true:
If des IsNot Nothing Then
In other words, it might assume that because there is a conditional statement, the Dispose() call might not be executed.
To check, you can try commenting out the "if" and see if the warning goes away.

Resources