Solved

Translate API from c# to vb.net

Posted on 2010-09-17
7
880 Views
Last Modified: 2013-12-14
Can anyone help me translate these 2 files attached?

I've been working on it for ever and just can't get it right.
BotRAPI.cs
Program.cs
0
Comment
Question by:wilcor14
7 Comments
 
LVL 69

Expert Comment

by:Éric Moreau
ID: 33704693
0
 

Author Comment

by:wilcor14
ID: 33704724
Emoreau,
I have and it didn't work very well.
0
 
LVL 96

Accepted Solution

by:
Bob Learned earned 250 total points
ID: 33705188
What wrong with the code that gets converted?  I don't see any compiler errors.


Imports System.Collections.Generic

Imports System.Linq

Imports System.Text

Imports System.Net

Imports System.IO

Imports System.Collections.Specialized

Imports System.Security.Cryptography

Imports System.Web



Namespace BotR.API



    Public Class BotRAPI



        Private _apiURL As String = ""



        Private _args As String = ""



        Private _queryString As NameValueCollection = Nothing



        Public Property Key() As String

            Get

                Return m_Key

            End Get

            Set(ByVal value As String)

                m_Key = Value

            End Set

        End Property

        Private m_Key As String



        Public Property Secret() As String

            Get

                Return m_Secret

            End Get

            Set(ByVal value As String)

                m_Secret = Value

            End Set

        End Property

        Private m_Secret As String



        Public Property APIFormat() As String

            Get

                Return m_APIFormat

            End Get

            Set(ByVal value As String)

                m_APIFormat = Value

            End Set

        End Property

        Private m_APIFormat As String



        Public Sub New(ByVal key As String, ByVal secret As String)

            Me.New("http://api.bitsontherun.com", "v1", key, secret)

        End Sub



        Public Sub New(ByVal url As String, ByVal version As String, ByVal key__1 As String, ByVal secret__2 As String)



            Key = key__1

            Secret = secret__2



            _apiURL = String.Format("{0}/{1}", url, version)

        End Sub



        ''' <summary>

        ''' Call the API method with no params beyond the required

        ''' </summary>

        ''' <param name="apiCall">The path to the API method call (/videos/list)</param>

        ''' <returns>The string response from the API call</returns>

        Public Function [Call](ByVal apiCall As String) As String

            Return [Call](apiCall, Nothing)

        End Function



        ''' <summary>

        ''' Call the API method with additional, non-required params

        ''' </summary>

        ''' <param name="apiCall">The path to the API method call (/videos/list)</param>

        ''' <param name="args">Additional, non-required arguments</param>

        ''' <returns>The string response from the API call</returns>

        Public Function [Call](ByVal apiCall As String, ByVal args As NameValueCollection) As String



            _queryString = New NameValueCollection()



            'add the non-required args to the required args

            If args IsNot Nothing Then

                _queryString.Add(args)

            End If



            buildArgs()

            Dim client As WebClient = createWebClient()



            Dim callUrl As String = _apiURL & apiCall



            Try

                Return client.DownloadString(callUrl)

            Catch

                Return ""

            End Try

        End Function



        ''' <summary>

        ''' Upload a file to account

        ''' </summary>

        ''' <param name="uploadUrl">The url returned from /videos/create call</param>

        ''' <param name="args">Optional args (video meta data)</param>

        ''' <param name="filePath">Path to file to upload</param>

        ''' <returns>The string response from the API call</returns>

        Public Function Upload(ByVal uploadUrl As String, ByVal args As NameValueCollection, ByVal filePath As String) As String



            _queryString = args

            'no required args

            Dim client As WebClient = createWebClient()

            _queryString("api_format") = If(APIFormat, "xml")

            'xml if not specified - normally set in required args routine                                   

            queryStringToArgs()



            Dim callUrl As String = _apiURL & uploadUrl & "?" & _args

            callUrl = uploadUrl & "?" & _args



            Try

                Dim response As Byte() = client.UploadFile(callUrl, filePath)

                Return Encoding.UTF8.GetString(response)

            Catch

                Return ""

            End Try

        End Function



        ''' <summary>

        ''' Hash the provided arguments

        ''' </summary>

        Private Function signArgs() As String



            queryStringToArgs()



            Dim ha As HashAlgorithm = HashAlgorithm.Create("SHA")

            Dim hashed As Byte() = ha.ComputeHash(Encoding.UTF8.GetBytes(_args & Secret))

            Return BitConverter.ToString(hashed).Replace("-", "").ToLower()

        End Function



        ''' <summary>

        ''' Convert args collection to ordered string

        ''' </summary>

        Private Sub queryStringToArgs()



            Array.Sort(_queryString.AllKeys)

            Dim sb As New StringBuilder()



            For Each key As String In _queryString.AllKeys

                sb.AppendFormat("{0}={1}&", key, _queryString(key))

            Next

            sb.Remove(sb.Length - 1, 1)

            'remove trailing &

            _args = sb.ToString()



        End Sub



        ''' <summary>

        ''' Append required arguments to URL

        ''' </summary>

        Private Sub buildArgs()



            _queryString("api_format") = If(APIFormat, "xml")

            'xml if not specified

            _queryString("api_key") = Key

            _queryString("api_nonce") = String.Format("{0:00000000}", New Random().[Next](99999999))

            _queryString("api_timestamp") = getUnixTime().ToString()

            _queryString("api_signature") = signArgs()



            _args = String.Concat(_args, "&api_signature=", _queryString("api_signature"))

        End Sub



        ''' <summary>

        ''' Construct instance of WebClient for request

        ''' </summary>

        ''' <returns></returns>

        Private Function createWebClient() As WebClient



            ServicePointManager.Expect100Continue = False

            'upload will fail w/o 

            Dim client As New WebClient()

            client.BaseAddress = _apiURL

            client.QueryString = _queryString

            client.Encoding = UTF8Encoding.UTF8

            Return client

        End Function



        ''' <summary>

        ''' Get timestamp in Unix format

        ''' </summary>

        ''' <returns></returns>

        Private Function getUnixTime() As Integer

            Return CInt((DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds)

        End Function

    End Class

End Namespace

Open in new window

0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 19

Assisted Solution

by:Amandeep Singh Bhullar
Amandeep Singh Bhullar earned 250 total points
ID: 33707173
Another class file is attached

Hope this will help you
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports Spring.Context
Imports Spring.Context.Support
Imports BotR.API
Imports System.Xml.Linq
Imports System.IO
Imports System.Collections.Specialized
Imports System.Security.Cryptography

Namespace BotRAPIConsole
	Friend Class Program

		Shared Sub Main(ByVal args() As String)
			Try

				Dim ctx As IApplicationContext = ContextRegistry.GetContext()
				Dim api As BotRAPI = TryCast(ctx.GetObject("BotRAPI"), BotRAPI)

				'test video listing
				Console.WriteLine(api.Call("/videos/list"))

				'params to store with a new video
				Dim col As New NameValueCollection (new String() { {"title", "New test video"}, {"tags", "new, test, video, upload"}, {"description", "New video2"}, {"link", "http://www.bitsontherun.com"}, {"author", "Bits on the Run"} })

				'create the new vidoe
				Dim xml As String = api.Call("/videos/create", col)

				Console.WriteLine(xml)

				Dim doc As XDocument = XDocument.Parse(xml)
				Dim result = ( _
				    From d In doc.Descendants("status") _
				    Select New With {Key .Status = d.Value}).FirstOrDefault()

				'make sure the status was "ok" before trying to upload
				If result.Status.Equals("ok", StringComparison.CurrentCultureIgnoreCase) Then

					Dim response = doc.Descendants("link").FirstOrDefault()
					Dim url As String = String.Format("{0}://{1}{2}", response.Element("protocol").Value, response.Element("address").Value, response.Element("path").Value)

					Dim filePath As String = "C:/Documents and Settings/wilco.ravestijn/My Documents/My Videos/0519.flv"
					filePath = Path.Combine(Environment.CurrentDirectory, filePath)

					col = New NameValueCollection()
					Dim fs As New FileStream(filePath, FileMode.Open)

					col("file_size") = fs.Length.ToString()
					col("file_md5") = BitConverter.ToString(HashAlgorithm.Create("MD5").ComputeHash(fs)).Replace("-", "").ToLower()
					col("key") = response.Element("query").Element("key").Value
					col("token") = response.Element("query").Element("token").Value

					fs.Dispose()
					Dim uploadResponse As String = api.Upload(url, col, filePath)

					Console.WriteLine(uploadResponse)
				End If

			Catch ex As Exception
				Console.WriteLine(ex.GetBaseException().Message)
			End Try
		End Sub
	End Class
End Namespace

Open in new window

0
 

Author Comment

by:wilcor14
ID: 33707863
I'm trying to Use this API but in trying to convert it to vb.net I'm having some issues.
With the Code below, I am successfully able to upload a file from within my project but if I upload a file from my C: drive, it produces the following error:
 Run-time exception thrown : System.Web.HttpException - 'C:\Documents and Settings\me\My Documents\My Videos\0519.flv' is not a valid virtual path.

I'm not sure where to start with figuring this out because most of it is over my head. Any ideas? Thanks a ton for your time.

Protected Sub cmdUpload_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmdUpload.Click

      Dim oBOTR As BotR.API.BotRAPI

      Dim oCollections As System.Collections.Specialized.NameValueCollection

      Dim sXML As String

      Dim oXML As System.Xml.XmlDocument

      Dim oNode As System.Xml.XmlNode

      Dim oLinkNode As System.Xml.XmlNode

      Dim oQueryNode As System.Xml.XmlNode

      Dim sKey As String

      Dim sToken As String



      Dim sProtocol As String

      Dim sAddress As String

      Dim sPath As String

      Dim sFile As String

      Dim oFileStream As System.IO.FileStream



      Dim PFile As System.Web.HttpPostedFile = Page.Request.Files(0)



      lblMesg.Text = ""

      lstValues.Items.Clear()



      oCollections = New System.Collections.Specialized.NameValueCollection()

      oCollections.Add("title", "Test Title")

      oCollections.Add("tags", "Public")

      oCollections.Add("description", "This is a public video Upload.")

      oCollections.Add("link", "http://www.google.com")

      oCollections.Add("author", "CS")



      oBOTR = New BotR.API.BotRAPI("########", "#################")

      sXML = oBOTR.Call("/videos/create", oCollections)



      oXML = New System.Xml.XmlDocument

      oXML.LoadXml(sXML)



      oNode = oXML.SelectSingleNode(".//status")



      If oNode Is Nothing Then

         lblMesg.Text = "No Status Node"

         oBOTR = Nothing

         Exit Sub

      End If



      If oNode.InnerText.ToLower = "ok" Then

      Else

         lblMesg.Text = "Status Not OK - " & oNode.InnerText

         oBOTR = Nothing

         Exit Sub

      End If



      oLinkNode = oXML.SelectSingleNode(".//link")





      If oLinkNode Is Nothing Then

         sProtocol = ""

         sAddress = ""

         sPath = ""

      Else

         oNode = oLinkNode.SelectSingleNode(".//protocol")

         sProtocol = oNode.InnerText

         oNode = oLinkNode.SelectSingleNode(".//address")

         sAddress = oNode.InnerText

         oNode = oLinkNode.SelectSingleNode(".//path")

         sPath = oNode.InnerText

      End If



      lstValues.Items.Add("protocol=" & sProtocol)

      lstValues.Items.Add("address=" & sAddress)

      lstValues.Items.Add("path=" & sPath)



      oQueryNode = oXML.SelectSingleNode(".//query")



      If oQueryNode Is Nothing Then

         lblMesg.Text = "No query Node"

         oBOTR = Nothing

         Exit Sub

      End If



      oNode = oQueryNode.SelectSingleNode(".//key")

      sKey = oNode.InnerText

      oNode = oQueryNode.SelectSingleNode(".//token")

      sToken = oNode.InnerText



      'sFile = Server.MapPath("video")

      'sFile = sFile & "\0519.flv"

      sFile = PFile.FileName



      oCollections = New System.Collections.Specialized.NameValueCollection()



      oFileStream = System.IO.File.OpenRead(sFile)



      Dim sMD5 As String

      Dim sURL As String



      sURL = sProtocol & "://" & sAddress & sPath



      sMD5 = System.BitConverter.ToString(System.Security.Cryptography.HashAlgorithm.Create("MD5").ComputeHash(oFileStream)).Replace("-", "").ToLower()



      oCollections.Add("file_size", oFileStream.Length)

      oCollections.Add("file_md5", sMD5)

      oCollections.Add("key", sKey)

      oCollections.Add("token", sToken)



      oFileStream.Close()

      oFileStream = Nothing



      Dim sResponse As String



      sResponse = oBOTR.Upload(sURL, oCollections, sFile)



      lblMesg.Text = "Final Response = " & sResponse



      oBOTR = Nothing



   End Sub

Open in new window

0
 

Author Comment

by:wilcor14
ID: 33711777
The API is not that large, it can be downloaded at: http://www.bitsontherun.com/download/dotnet-api-kit.zip
 
 
0
 

Author Closing Comment

by:wilcor14
ID: 33765154
Got it figured out
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
The viewer will learn how to use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…
The viewer will learn how to use and create new code templates in NetBeans IDE 8.0 for Windows.

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now