Get the decrypted content of the section in web.config without saving - asp.net

How can I get the content of the decrypted webconfig section before it saves the decrypted file: confg.Save()?
Dim confg As System.Configuration.Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)
Dim confgSect As ConfigurationSection = confg.GetSection("section")
If confgSect.SectionInformation.IsProtected Then
confgSect.SectionInformation.UnprotectSection()
confg.Save()
End If

Dim confg As System.Configuration.Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)
Dim confgSect As ConfigurationSection = confg.GetSection("section")
If confgSect.SectionInformation.IsProtected Then
confgSect.SectionInformation.UnprotectSection()
Dim xml As New System.Xml.XmlDocument
Dim node As System.Xml.XmlNodeList
Dim str As String
Dim answer As String
str = confgSect.SectionInformation.GetRawXml()
xml.LoadXml("<ROOT>" + str + "</ROOT>")
node = xml.GetElementsByTagName("TagnameHere")
answer= node(0).Attributes(1).Value
End If
My section in the webcobfig contains multiple tags, so I used xml to get each tag and get its value as an attribute.

Related

How to read a SOAP xml file using asp.net?

I was trying to read an xml file and loads it in an xml document. However an error prompted me that the "Data at the root level is invalid. Line 1, position 1." I need to retrieve the message from the xml file.
Below is my code:
Dim xmlPath as String = Server.MapPath("~/res.xml")
Dim xmlDoc as New XmlDocument
Dim fs As New FileStream(xmlPath, FileMode.Open, FileAccess.Read)
xmlDoc.Load(fs)
Here is the content of the xml file:
--uuid:8asdsddf-sdf24-asdasd-3121-asdasdasdasd
Content-Type: application/xop+xml; charset=UTF-8; type="text/xml";
Content-Transfer-Encoding: binary
Content-ID: <root.message#apache.org>
<SOAP-ENV:Envelope xmlns:SOAP-
ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header></SOAP-
ENV:Header><SOAP-ENV:Body><Status xmlns=""><Message>Success: 12345</Message></Status></SOAP-ENV:Body></SOAP-
ENV:Envelope>
--uuid:8asdsddf-sdf24-asdasd-3121-asdasdasdasd--
What should be the reason why the error prompted?
The following code should remove all the non xml string from file
Imports System.IO
Imports System.Xml
Module Module1
Const FILENAME As String = "c:\temp\test.xml"
Sub Main()
'Dim xmlPath As String = Server.MapPath("~/res.xml")
Dim xmlDoc As New XmlDocument
Dim reader As New StreamReader(FILENAME)
Dim xml As String = ""
Dim inputLine As String = ""
Dim foundTag = False
While (Not reader.EndOfStream)
inputLine = reader.ReadLine
If foundTag = False Then
If Not inputLine.StartsWith("<") Then Continue While
foundTag = True
End If
If Not inputLine.StartsWith("--") Then
xml = xml & inputLine
End If
End While
xmlDoc.LoadXml(xml)
End Sub
End Module

How to use ASPxFileManager 'SelectedFiles' property to attach files to MailMessage?

I am using DevExpress tools, specifically the FileManager which has a 'SelectedFiles' property which returns all the data needed to (add,insert,delete,retrieve, modify the record). However I can not figure out how to use the selectedfiles as a MailMessage.Attachment. The code below works to send the email, I've changed the credentials and host values for security. I just need some direction or thought on how to use the FileManager collection that is generated via 'SelectedFiles' and add them as an attachment to the email. I would really like to Zip the files if possible, but at this point simply attaching them is fine. Any thoughts?
Dim fileManager As ASPxFileManager = TryCast(sender, ASPxFileManager)
If ASPxFileManager1.SelectedFiles IsNot Nothing AndAlso ASPxFileManager1.SelectedFiles.Length > 0 Then
For i As Integer = 0 To ASPxFileManager1.SelectedFiles.Length - 1
Dim file = ASPxFileManager1.SelectedFiles.ToString
Dim attachments As New Attachment(fileManager.SelectedFiles.ToString)???
Next
End If
Try
Dim mail As New MailMessage("noreply", DropDownEdit.Text)
Dim smtp_Server As New SmtpClient("host") With {.Credentials = New Net.NetworkCredential("username", "password")}
mail.Subject = "SUBJECT"
mail.IsBodyHtml = False
mail.Body = "Testing"
smtp_Server.Send(mail)
successLabel.Text = "Your email was sent successfully."
Catch ex As Exception
End Try
End Sub
Dim attachments As New Attachment(ReadFile(ASPxFileManager1.SelectedFiles(i)), file)
mail.Attachments.Add(attachments)
The function below was needed to Read the bytes and then attach the items to the MailMessage.
Public Function ReadFile(file__1 As FileManagerFile) As System.IO.Stream
'This function allows us to pull the bytes from the DB value to render the file.
Dim filePath As String = (file__1.RelativeName)
Dim fileData As Byte()
Using con As New SqlConnection([Global].conn)
Dim sqlCmd As New SqlCommand()
sqlCmd.Connection = con
sqlCmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = file__1.Name
sqlCmd.Parameters.Add("#APIKey", SqlDbType.Int).Value = Session("_UserAPIKey")
sqlCmd.CommandText = "SELECT STATEMENT"
con.Open()
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
If sqlReader.HasRows Then
While sqlReader.Read()
fileData = CType(sqlReader(0), Byte())
End While
End If
End Using
Return New MemoryStream(fileData)
End Function

xml response http post - convert request.inputstream to string - asp.net

I'm receiving an xml response and I now want to parse this.
Currently what I have to receive the XML response is:
Dim textReader = New IO.StreamReader(Request.InputStream)
Request.InputStream.Seek(0, IO.SeekOrigin.Begin)
textReader.DiscardBufferedData()
Dim Xmlin = XDocument.Load(textReader)
How can I go ahead now a process this and pick out the element values?
<subscription>
<reference>abc123</reference>
<status>active</status>
<customer>
<fname>Joe</fname>
<lname>bloggs</lname>
<company>Bloggs inc</company>
<phone>1234567890</phone>
<email>joebloggs#hotmail.com</email>
</customer>
</subscription>
If I have it in string format I can do this using
Dim xmlE As XElement = XElement.Parse(strXML) ' strXML is string version of XML
Dim strRef As String = xmlE.Element("reference")
Do I need to convert the request.inputstream to a strign format or is there another better way?
Thanks
Do I need to convert the request.inputstream to a strign format or is there another better way?
You could directly load it from the request stream, you don't need to convert it to a string:
Request.InputStream.Position = 0
Dim Xmlin = XDocument.Load(Request.InputStream)
Dim reference = Xmlin.Element("subscription").Element("reference").Value
or:
Dim reference = Xmlin.Descendants("reference").First().Value
In the end after much testing I could only get this to work:
Dim textReader = New IO.StreamReader(Request.InputStream)
Request.InputStream.Seek(0, IO.SeekOrigin.Begin)
textReader.DiscardBufferedData()
Dim Xmlin = XDocument.Load(textReader)
Dim strXml As String = Xmlin.ToString
Dim xmlE As XElement = XElement.Parse(strXml)
Dim strRef As String = xmlE.Element("reference")
Dim strStatus As String = xmlE.Element("status")
Dim strFname As String = xmlE.Element("customer").Element("fname").Value()
Dim strLname As String = xmlE.Element("customer").Element("lname").Value()
Dim strCompany As String = xmlE.Element("customer").Element("company").Value()
Dim strPhone As String = xmlE.Element("customer").Element("phone").Value()
Dim strEmail As String = xmlE.Element("customer").Element("email").Value()

How to parse an xml response from a post in vb.net

I am posting to a website to get data back. The site returns it as an xml. I am able to get the data into a string. But what i really want to do is to have each item in the xml in a different string field.
Sub lookup(ByVal Source As Object, ByVal e As EventArgs)
Dim wData As String
wData = WRequest("http://PostToThisSite.com", "POST","str=31&Password=pn&UserID=Q&Postcode="+txtPcode.Text)
Response.Write(wData)
End Sub
Function WRequest(URL As String, method As String, POSTdata As String) As String
Dim responseData As String = ""
Try
Dim hwrequest As Net.HttpWebRequest = Net.Webrequest.Create(URL)
hwrequest.Accept = "*/*"
hwrequest.AllowAutoRedirect = true
hwrequest.UserAgent = "http_requester/0.1"
hwrequest.Timeout = 60000
hwrequest.Method = method
If hwrequest.Method = "POST" Then
hwrequest.ContentType = "application/x-www-form-urlencoded"
Dim encoding As New Text.ASCIIEncoding() 'Use UTF8Encoding for XML requests
Dim postByteArray() As Byte = encoding.GetBytes(POSTdata)
hwrequest.ContentLength = postByteArray.Length
Dim postStream As IO.Stream = hwrequest.GetRequestStream()
postStream.Write(postByteArray, 0, postByteArray.Length)
postStream.Close()
End If
Dim hwresponse As Net.HttpWebResponse = hwrequest.GetResponse()
If hwresponse.StatusCode = Net.HttpStatusCode.OK Then
Dim responseStream As IO.StreamReader = _
New IO.StreamReader(hwresponse.GetResponseStream())
responseData = responseStream.ReadToEnd()
End If
hwresponse.Close()
Catch e As Exception
responseData = "An error occurred: " & e.Message
End Try
Return responseData
End Function
The above code works and writes out a line...
Some Road City LU1 5QG
The Xml being returned is ..
<Address xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://site.co.uk/">
<strOrganisation />
<strProperty />
<strStreet>Some Road</strStreet>
<strLocality />
<strTown>City</strTown>
<strCounty />
<strPostcode>LU1 5QG</strPostcode>
<strDPS />
I want to be able to split these fields and set them to different text boxes on the page...help?
Load the xml string into an XmlDocument and extract the values with XPath:
Dim doc = new XmlDocument()
doc.LoadXml(yourXmlString)
Dim nsm = new XmlNamespaceManager(doc.NameTable)
nsm.AddNamespace("a", "http://site.co.uk/")
txtStreet.Text = doc.SelectSingleNode("/a:Address/a:strStreet", nsm).InnerText
Here's a working snippet:
Dim doc = New XmlDocument()
doc.LoadXml("<Address xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://site.co.uk/""><strOrganisation /> <strProperty /> <strStreet>Some Road</strStreet> <strLocality /> <strTown>City</strTown> <strCounty /> <strPostcode>LU1 5QG</strPostcode><strDPS /></Address>")
Dim nsm = New XmlNamespaceManager(doc.NameTable)
nsm.AddNamespace("a", "http://site.co.uk/")
Dim streetValue = doc.SelectSingleNode("/a:Address/a:strStreet", nsm).InnerText
Some things to note:
For XPath lookups, if your xml has a namespace you'll need to add it to an
XmlNameSpaceManager created from your XmlDocument's NameTable.
If you don't want to
bother with that, you can walk the node collections manually via
doc.ChildNodes[0].ChildNodes[0] etc.
Or try this, which is what I believe the author was asking.
' Use XML Reader
Dim xmlDoc = New XmlDocument
Dim xmlNode As Xml.XmlNode
xmlDoc.LoadXml(strResponse)
xmlNode = xmlDoc.SelectSingleNode("//" + "strStreet")
If Not xmlNode Is Nothing Then
Dim Street = xmlNode.InnerText
End If

Deny access to a persistent cookie

If someone logs in on a pc from Starbucks (for example) and they accidentally check the 'remember me' option thereby setting a persistent cookie on that pc, is there any way of denying that cookie from the server without resorting to changing the cookie name in web.config?
I solved this (a while back actually) by setting a machineKey in web.config & changing it when the username/password is changed:
Sub ChangeMachineKey()
Dim commandLineArgs As String() = System.Environment.GetCommandLineArgs()
Dim decryptionKey As String = CreateMachineKey(64)
Dim validationKey As String = CreateMachineKey(128)
'HttpContext.Current.Response.Write(decryptionKey + "<br />" + validationKey + "<hr />")
Dim filename As String = HttpContext.Current.Server.MapPath("~/Web.config")
Dim XmlReader As XmlTextReader = New XmlTextReader(filename)
Dim xDoc As XmlDocument = New XmlDocument()
xDoc.Load(XmlReader)
XmlReader.Close()
Dim Node As System.Xml.XmlNode = xDoc.SelectSingleNode("//configuration/system.web/machineKey")
Node.Attributes.GetNamedItem("validationKey").Value = validationKey
Node.Attributes.GetNamedItem("decryptionKey").Value = decryptionKey
xDoc.Save(filename)
End Sub
Public Shared Function CreateMachineKey(ByVal numBytes As Integer) As String
Dim Random As Byte() = New Byte(numBytes / 2 - 1) {}
Dim rng As New RNGCryptoServiceProvider()
rng.GetBytes(Random)
Dim machineKey As New System.Text.StringBuilder(numBytes)
Dim i As Integer = 0
Do While i < Random.Length
machineKey.Append(String.Format("{0:X2}", Random(i)))
i += 1
Loop
Return machineKey.ToString()
End Function
This forces everyone to sign in again but since there is only one admin account it works perfectly for me!

Resources