Parsing in Json not in XML . VB.Net - vb.net

At the moment I am using VB.Net.
I build my string, post it out and then parse the results.
Parsing Example for XML
Dim xml As New MWXMLDocument()
Dim sReason As String = "Unknown"
Try
xml.LoadXml(sresult)
If xml.SelectSimpleNode("AcceptedLead").InnerText = "true" Then
app.Outcome.RedirectURL = xml.SelectSimpleNode("result/redirecturl").InnerText
AcceptLead()
Return True
End If
sReason = xml.SelectSimpleNode("Reason").InnerText
Catch ex As Exception
sReason = "Error: " & ex.Message
End Try
DeclineLead(sReason)
Return False
End Function
How would I parse a result sent back in JSON, here is an example of the result I want to parse in using VB : Can i not just get the data from the string and parse as normal XML.
{"RedirectUrl":"www.test.com","Commission":5.0000,"Status":"accepted"}

You can use the JSON.NET Library
Example in C#:
var result = JsonConvert.DeserializeObject<RootObject>(string json);
The RootObject should be your own class.

You could use the .Net built in JavaScriptSerialiser
First add a reference to System.Web.Extensions and then
Imports System.Web.Script.Serialization
Followed by...
Dim sExampleJSON As String = "{""RedirectUrl"":""www.test.com"",""Commission"":5.0000,""Status"":""accepted""}"
Dim MySerializer As JavaScriptSerializer = New JavaScriptSerializer()
Dim MyDictionary As Dictionary(Of String, Object) = MySerializer.Deserialize(Of Dictionary(Of String, Object))(sExampleJSON)
If MyDictionary.ContainsKey("RedirectUrl") Then
Console.WriteLine(MyDictionary("RedirectUrl"))
End If

in global.asax.cs
using System.Data.Entity;
namespace RpManticSolAPI
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
}
}
}

The complete Answer
sResult = sResult.Replace("""", String.Empty)
If sResult.Contains("Status:accepted") Then
Dim parts = sResult.Replace("{", String.Empty).Replace("}", String.Empty).Split(",")
For i As Int16 = 0 To parts.Length - 1
If parts(i).StartsWith("RedirectUrl") Then
app.Outcome.RedirectURL = parts(i).Substring(12)
End If
If parts(i).StartsWith("Commission") Then
lendertier.LenderComm = CDec(parts(i).Substring(11))
End If
If parts(i).StartsWith("ApplicationRef") Then
app.Outcome.LenderReference = parts(i).Substring(15)
End If
Next
AcceptLead()
Return True
End If
If sResult.Contains("Reason:Duplicate") Then
sReason = "Duplicate"
ElseIf sResult.Contains("{Error:invalid credentials") Then
sReason = "Error: Invalid credentials"
ElseIf sResult.Contains("ValidationErrors:") Then
sReason = "Invalid call:" + sResult.Replace("ValidationErrors:", String.Empty).Replace(",Status:rejected", String.Empty)
Else
sReason = "Rejected"
End If
DeclineLead(sReason)
Return False

Related

StreamString(pipeClient) throws error Type is not defined

I am trying to unlock the machine by passing user id and password in UiPath when scheduled bot trying to run the process in locked system
Below is my code
'Create a new pipe client
Using pipeClient As New System.IO.Pipes.NamedPipeClientStream(
".",
"CredentialProviderPipe",
PipeDirection.InOut,
PipeOptions.None,
System.Security.Principal.TokenImpersonationLevel.Impersonation)
'Attempt to connect to it
pipeClient.Connect(10000)
'Send credentials
Dim dom As String
If Domain = "" Then
dom = Environment.UserDomainName
Else
dom = Domain
End If
Dim ss As New StreamString(pipeClient)
ss.WriteString(String.Format("LOGON{0}{1}{0}{2}{0}{3}", vbLf, dom, Username, Password))
'Wait for reply
Using pr As New StreamReader(pipeClient, System.Text.Encoding.Unicode)
Response = pr.ReadLine()
If Response = "OK" OrElse Response = "UNKNOWN" Then Return
ErrorCode = pr.ReadLine()
ErrorMessage = pr.ReadLine()
End Using
End Using
Catch ex As TimeoutException
Response = "ERROR"
ErrorCode = "0x80131505"
ErrorMessage = ex.Message
Catch ex As Exception
Response = "ERROR"
ErrorCode = ""
ErrorMessage = ex.Message
End Try
I am getting below error that error BC30002: Type StringStream is not defined.
I dont know how to resolve the issue. Please help
It looks like all those uses of StreamString are based on the example here, which includes the definition of that class as below:
' Defines the data protocol for reading and writing strings on our stream
Public Class StreamString
Private ioStream As Stream
Private streamEncoding As UnicodeEncoding
Public Sub New(ioStream As Stream)
Me.ioStream = ioStream
streamEncoding = New UnicodeEncoding(False, False)
End Sub
Public Function ReadString() As String
Dim len As Integer = 0
len = CType(ioStream.ReadByte(), Integer) * 256
len += CType(ioStream.ReadByte(), Integer)
Dim inBuffer As Array = Array.CreateInstance(GetType(Byte), len)
ioStream.Read(inBuffer, 0, len)
Return streamEncoding.GetString(inBuffer)
End Function
Public Function WriteString(outString As String) As Integer
Dim outBuffer() As Byte = streamEncoding.GetBytes(outString)
Dim len As Integer = outBuffer.Length
If len > UInt16.MaxValue Then
len = CType(UInt16.MaxValue, Integer)
End If
ioStream.WriteByte(CType(len \ 256, Byte))
ioStream.WriteByte(CType(len And 255, Byte))
ioStream.Write(outBuffer, 0, outBuffer.Length)
ioStream.Flush()
Return outBuffer.Length + 2
End Function
End Class

Create an object in VB.Net to use in VBA

Firstly, I'm quite new to this so be gentle!
I am trying to create a class/object in VB.net for use in vba. I have used Gary Whitcher's code from the bottom of this post:
Sample vb.net code to upload file to Amazon S3 storage
I have created a class in Visual Studio and managed to get it to output a TLB file which i can import to VBA in Excel.
I can then use the object in VBA to create a new folder in the S3 storage system however I am running into problems when using the 'AddFileToFolder' method.
I have had to edit Gary's code a little to get it to compile in VS, the edited version is below.
Imports Amazon.S3
Imports Amazon.S3.Model
Imports Amazon
Imports Amazon.S3.Util
Imports System.Collections.ObjectModel
Imports System.IO
Public Class aws_s3
Const AWS_ACCESS_KEY As String = "AccessKey" 'is set to MY actual key
Const AWS_SECRET_KEY As String = "SecretKey" 'is set to MY actual key
Private Property s3Client As IAmazonS3
Sub New()
Try
s3Client = New AmazonS3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY, RegionEndpoint.USEast1)
Catch ex As Exception
End Try
End Sub
Public Function CreateFolder(bucketName As String, folderName() As String) As String
Dim returnval As String = ""
Try
Try
Dim folderKey As String = ""
If Not AmazonS3Util.DoesS3BucketExist(s3Client, bucketName) Then
returnval = "Bucket does not exist"
Else
For i = 0 To folderName.Length - 1
folderKey += folderName(i) & "/"
Next
' folderKey = folderKey & "/" 'end the folder name with "/"
Dim request As PutObjectRequest = New PutObjectRequest()
request.BucketName = bucketName
request.StorageClass = S3StorageClass.Standard
request.ServerSideEncryptionMethod = ServerSideEncryptionMethod.None
' request.CannedACL = S3CannedACL.BucketOwnerFullControl
request.Key = folderKey
request.ContentBody = String.Empty
s3Client.PutObject(request)
End If
Catch ex As Exception
returnval = ex.Message
End Try
Catch ex As AmazonS3Exception
returnval = ex.Message
End Try
Return returnval
End Function
Public Function AddFileToFolder(FileName As String, bucketName As String, folderName As String) As String
Dim returnval As String = ""
Try
Try
If Not AmazonS3Util.DoesS3BucketExist(s3Client, bucketName) Then
Dim fname() As String = folderName.Split("/")
CreateFolder(bucketName, fname)
Else
Dim path As String = FileName
Dim file As FileInfo = New FileInfo(path)
Dim key As String = String.Format("{0}/{1}", folderName, file.Name)
Dim por As PutObjectRequest = New PutObjectRequest()
por.BucketName = bucketName
por.StorageClass = S3StorageClass.Standard
por.ServerSideEncryptionMethod = ServerSideEncryptionMethod.None
por.CannedACL = S3CannedACL.PublicRead
por.Key = key
por.InputStream = file.OpenRead()
s3Client.PutObject(por)
End If
Catch ex As Exception
returnval = ex.Message
End Try
Catch ex As AmazonS3Exception
returnval = ex.Message
End Try
Return returnval & " dll"
End Function
End Class
Using VBA, I have created the above object and can successfully execute CreateFolder but when executing addfiletofolder i get the error "Class does not support automation or does not support expected interface"
the VBA code looks like this:
Dim aws As AWS_S3
Dim Result As String
Dim UploadFile As String
UploadFile = "C:\Zipped Builds\Hinchley Legion.zip"
Set aws = New AWS_S3
Dim fld(1) As String
fld(0) = "folder"
fld(1) = "subfolder"
Result = aws.CreateFolder("nsmcustomercontent", fld)
If Result <> "" Then GoTo errHandle
Result = aws.AddFileToFolder(UploadFile, "nsmcustomercontent", fld)
If Result <> "" Then GoTo errHandle
Exit Sub
errHandle:
MsgBox Result
End Sub
I'm guessing from the fact that CreateFolder works fine but AddFileToFolder doesn't, there is a problem in the class as created in VS, missing a dependancy or something?
Thanks Anu6is, that was indeed the problem. The author of the class had wrote the following for usage which had thrown me off:
ADD FILE TO FOLDER
Dim fld(1) As String
fld(0) = <foldername>
fld(1) = <subfoldername>
'List each sub folder as an element in array
Dim rtrn As String = aws.AddFileToFolder(<local file name>,<bucketname>, fld)
I need to get better at reading VB.Net i think! Many thanks for your quick reply, much appreciated.

Adding a dynamic member to an ExpandoObject

In the following method I am trying to add a dynamic member to an expando object but it throws an exception:
public member not found for expand object
Private Sub GetAckValues()
Try
Dim ack_duration As String = String.Empty
Dim ack_by_user_fkid As String = String.Empty
Dim ack_time As String = String.Empty
ack_duration = txtdefaultack.Text
ack_by_user_fkid = Convert.ToString(Session("user_code"))
Dim Ack_Detail As Object = New ExpandoObject()
Ack_Detail.ack_duration = ack_duration
Ack_Detail.ack_by_user_fkid = ack_by_user_fkid
receiptObject.StatusObject = Ack_Detail
Catch ex As Exception
logger.Error("Enter JobRequest form done by :" & LoggedinUserId, ex)
End Try
End Sub
Should this:
Ack_Detail.ack_duration = Ack_Detail.ack_duration
actually be this:
Ack_Detail.ack_duration = ack_duration

Serialize and Base64 convert and vice versa in vb.net

I have functions which serialize and base64 convert objects and vice versa. It uses Newtonsoft to serialize and deserialize Objects. The code works but is there a way to do this without using Newtonsoft?
Public Shared Function SerializeAndBase64(ObjectToSerialize As Object) As ReturnObject(Of String)
Dim rtnObj As New ReturnObject(Of String)
Try
Dim SerializedObjectJson As String = Newtonsoft.Json.JsonConvert.SerializeObject(ObjectToSerialize)
Dim Base64String As String = Convert.ToBase64String(Encoding.UTF8.GetBytes(SerializedObjectJson))
rtnObj.Item = Base64String
Catch ex As Exception
rtnObj.ErrorID = ErrorHandler.handleError(ex)
rtnObj.ErrorMessage = ex.Message
rtnObj.IsError = True
End Try
Return rtnObj
End Function
Public Shared Function DeserializeFromBase64(Of t)(Base64Json As String) As ReturnObject(Of t)
Dim rtnObj As New ReturnObject(Of t)
Try
Dim SerializedObjectJson As String = Encoding.UTF8.GetString(Convert.FromBase64String(Base64Json))
Dim DeserializedObject As t = Newtonsoft.Json.JsonConvert.DeserializeObject(Of t)(SerializedObjectJson)
rtnObj.Item = DeserializedObject
Catch ex As Exception
rtnObj.ErrorID = ErrorHandler.handleError(ex)
rtnObj.ErrorMessage = ex.Message
rtnObj.IsError = True
End Try
Return rtnObj
End Function
Thanks in advance.
You can Serialize/Deserialize it yourself. You just have to come up with a way to save everything into a single string, or XML or even a byte array if you want. Your choice.
Public Class Class1
Public Property MyValue As String
Public Function Serialize() As String
Return MyValue
End Function
Public Sub Deserialize(ByVal value As String)
MyValue = value
End Sub
End Class

how to export the data from a queried database to excel in SQL

I have a page where a database is filtered by many factors: Name, Id, Status, etc. I want to be able to press a button that says "Open this query in excel" and it will download the results into excel. How is this possible? I have seen something like this:
"SELECT * INTO OUTFILE 'query.csv' FROM RMS WHERE 1 = '1'";
But this is not working for me. I already have the database querying right, I just need the functionality to export that query to excel by pressing a button that will download the complete query into an excel file. If someone could help I will really appreciate it!
This is how the page looks
That's not how it works.
If you do it that way, the file gets saved on the sql server.
You need to do
select * from your_table
into a datatable. Then you use the FileHelpers Library to create a csv file:
FileHelpers.CsvEngine.DataTableToCsv(dataTable, filename);
Then you write this csv-file to HttpContext.Response and set the attach header.
Public Class TextHandler
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
'context.Response.ContentType = "text/plain"
'context.Response.Write("Hello World!")
Dim memoryStream As New System.IO.MemoryStream()
Dim textWriter As System.IO.TextWriter = New System.IO.StreamWriter(memoryStream)
textWriter.WriteLine("YOUR CSV CONTENT")
textWriter.Flush()
memoryStream.Position = 0
Dim bytesInStream As Byte() = New Byte(memoryStream.Length - 1) {}
'memoryStream.Write(bytesInStream, 0, bytesInStream.Length)
memoryStream.Read(bytesInStream, 0, CInt(memoryStream.Length))
memoryStream.Close()
context.Response.Clear()
context.Response.ContentType = "application/octet-stream"
context.Response.AddHeader("Content-Disposition", GetContentDisposition(strFileName))
context.Response.BinaryWrite(bytesInStream)
context.Response.End()
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
Public Shared Function StripInvalidPathChars(str As String) As String
If str Is Nothing Then
Return Nothing
End If
Dim strReturnValue As String = ""
Dim strInvalidPathChars As New String(System.IO.Path.GetInvalidPathChars())
Dim bIsValid As Boolean = True
For Each cThisChar As Char In str
bIsValid = True
For Each cInvalid As Char In strInvalidPathChars
If cThisChar = cInvalid Then
bIsValid = False
Exit For
End If
Next cInvalid
If bIsValid Then
strReturnValue += cThisChar
End If
Next cThisChar
Return strReturnValue
End Function ' StripInvalidPathChars
Public Shared Function GetContentDisposition(ByVal strFileName As String) As String
' http://stackoverflow.com/questions/93551/how-to-encode-the-filename-parameter-of-content-disposition-header-in-http
Dim contentDisposition As String
strFileName = StripInvalidPathChars(strFileName)
If System.Web.HttpContext.Current IsNot Nothing AndAlso System.Web.HttpContext.Current.Request.Browser IsNot Nothing Then
If (System.Web.HttpContext.Current.Request.Browser.Browser = "IE" And (System.Web.HttpContext.Current.Request.Browser.Version = "7.0" Or System.Web.HttpContext.Current.Request.Browser.Version = "8.0")) Then
contentDisposition = "attachment; filename=" + Uri.EscapeDataString(strFileName).Replace("'", Uri.HexEscape("'"c))
ElseIf (System.Web.HttpContext.Current.Request.Browser.Browser = "Safari") Then
contentDisposition = "attachment; filename=" + strFileName
Else
contentDisposition = "attachment; filename*=UTF-8''" + Uri.EscapeDataString(strFileName)
End If
Else
contentDisposition = "attachment; filename*=UTF-8''" + Uri.EscapeDataString(strFileName)
End If
Return contentDisposition
End Function ' GetContentDisposition
Since CSV is plain text, you could probably just set the ContentType, Attach + write the text to the Response directly, without using MemoryStream.