类“QueryParameterComparer”必须实现函数比较。

2024-04-11

我在下面从 C# 转换为 VB.NET 的代码中遇到以下错误(原始代码可以在此处找到:https://developer.linkedin.com/sites/default/files/LinkedInAuth.rar.zip https://developer.linkedin.com/sites/default/files/LinkedInAuth.rar.zip):

“QueryParameterComparer”类必须为接口“System.Collections.Generic.IComparer(Of QueryParameter)”实现“Function Compare(x As oAuthBase2.QueryParameter, y As oAuthBase2.QueryParameter) As Integer”。

我到底需要改变什么?


' ' 此文件由 Fatih YASAR 于 2009 年 11 月 27 日修改 '

Imports System.Security.Cryptography
Imports System.Collections.Generic
Imports System.Text
Imports System.Web


Public Class oAuthBase2

''' <summary>
''' Provides a predefined set of algorithms that are supported officially by the protocol
''' </summary>
Public Enum SignatureTypes
    HMACSHA1
    PLAINTEXT
    RSASHA1
End Enum

''' <summary>
''' Provides an internal structure to sort the query parameter
''' </summary>
Protected Class QueryParameter
    Private m_name As String = Nothing
    Private m_value As String = Nothing

    Public Sub New(ByVal name As String, ByVal value As String)
        Me.m_name = name
        Me.m_value = value
    End Sub

    Public ReadOnly Property Name() As String
        Get
            Return m_name
        End Get
    End Property

    Public ReadOnly Property Value() As String
        Get
            Return m_value
        End Get
    End Property
End Class


Protected Class QueryParameterComparer
    Implements System.Collections.Generic.IComparer(Of oAuthBase2.QueryParameter)

#Region "IComparer<QueryParameter> Members"

    Public Function Compare(ByVal x As oAuthBase2.QueryParameter, ByVal y As oAuthBase2.QueryParameter) As Integer
        If x.Name = y.Name Then
            Return String.Compare(x.Value, y.Value)
        Else
            Return String.Compare(x.Name, y.Name)
        End If
    End Function

#End Region
End Class


Protected Const OAuthVersion As String = "1.0"
Protected Const OAuthParameterPrefix As String = "oauth_"

'
' List of know and used oauth parameters' names
'        
Protected Const OAuthConsumerKeyKey As String = "oauth_consumer_key"
Protected Const OAuthCallbackKey As String = "oauth_callback"
Protected Const OAuthVersionKey As String = "oauth_version"
Protected Const OAuthSignatureMethodKey As String = "oauth_signature_method"
Protected Const OAuthSignatureKey As String = "oauth_signature"
Protected Const OAuthTimestampKey As String = "oauth_timestamp"
Protected Const OAuthNonceKey As String = "oauth_nonce"
Protected Const OAuthTokenKey As String = "oauth_token"
Protected Const oAauthVerifier As String = "oauth_verifier"
Protected Const OAuthTokenSecretKey As String = "oauth_token_secret"

Protected Const HMACSHA1SignatureType As String = "HMAC-SHA1"
Protected Const PlainTextSignatureType As String = "PLAINTEXT"
Protected Const RSASHA1SignatureType As String = "RSA-SHA1"

Protected random As New Random()

Private oauth_verifier As String
Public Property Verifier() As String
    Get
        Return oauth_verifier
    End Get
    Set(ByVal value As String)
        oauth_verifier = value
    End Set
End Property


Protected unreservedChars As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"

''' <summary>
''' Helper function to compute a hash value
''' </summary>
''' <param name="hashAlgorithm">The hashing algoirhtm used. If that algorithm needs some initialization, like HMAC and its derivatives, they should be initialized prior to passing it to this function</param>
''' <param name="data">The data to hash</param>
''' <returns>a Base64 string of the hash value</returns>
Private Function ComputeHash(ByVal hashAlgorithm As HashAlgorithm, ByVal data As String) As String
    If hashAlgorithm Is Nothing Then
        Throw New ArgumentNullException("hashAlgorithm")
    End If

    If String.IsNullOrEmpty(data) Then
        Throw New ArgumentNullException("data")
    End If

    Dim dataBuffer As Byte() = System.Text.Encoding.ASCII.GetBytes(data)
    Dim hashBytes As Byte() = hashAlgorithm.ComputeHash(dataBuffer)

    Return Convert.ToBase64String(hashBytes)
End Function

''' <summary>
''' Internal function to cut out all non oauth query string parameters (all parameters not begining with "oauth_")
''' </summary>
''' <param name="parameters">The query string part of the Url</param>
''' <returns>A list of QueryParameter each containing the parameter name and value</returns>
Private Function GetQueryParameters(ByVal parameters As String) As List(Of QueryParameter)
    If parameters.StartsWith("?") Then
        parameters = parameters.Remove(0, 1)
    End If

    Dim result As New List(Of QueryParameter)()

    If Not String.IsNullOrEmpty(parameters) Then
        Dim p As String() = parameters.Split("&"c)
        For Each s As String In p
            If Not String.IsNullOrEmpty(s) AndAlso Not s.StartsWith(OAuthParameterPrefix) Then
                If s.IndexOf("="c) > -1 Then
                    Dim temp As String() = s.Split("="c)
                    result.Add(New QueryParameter(temp(0), temp(1)))
                Else
                    result.Add(New QueryParameter(s, String.Empty))
                End If
            End If
        Next
    End If

    Return result
End Function

''' <summary>
''' This is a different Url Encode implementation since the default .NET one outputs the percent encoding in lower case.
''' While this is not a problem with the percent encoding spec, it is used in upper case throughout OAuth
''' </summary>
''' <param name="value">The value to Url encode</param>
''' <returns>Returns a Url encoded string</returns>
Public Function UrlEncode(ByVal value As String) As String
    Dim result As New StringBuilder()

    For Each symbol As Char In value
        If unreservedChars.IndexOf(symbol) <> -1 Then
            result.Append(symbol)
        Else
            result.Append("%"c & [String].Format("{0:X2}", AscW(symbol)))
        End If
    Next

    Return result.ToString()
End Function

''' <summary>
''' Normalizes the request parameters according to the spec
''' </summary>
''' <param name="parameters">The list of parameters already sorted</param>
''' <returns>a string representing the normalized parameters</returns>
Protected Function NormalizeRequestParameters(ByVal parameters As IList(Of QueryParameter)) As String
    Dim sb As New StringBuilder()
    Dim p As QueryParameter = Nothing
    For i As Integer = 0 To parameters.Count - 1
        p = parameters(i)
        sb.AppendFormat("{0}={1}", p.Name, p.Value)

        If i < parameters.Count - 1 Then
            sb.Append("&")
        End If
    Next

    Return sb.ToString()
End Function

''' <summary>
''' Generate the signature base that is used to produce the signature
''' </summary>
''' <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
''' <param name="consumerKey">The consumer key</param>        
''' <param name="token">The token, if available. If not available pass null or an empty string</param>
''' <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
''' <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
''' <param name="signatureType">The signature type. To use the default values use <see cref="OAuthBase.SignatureTypes">OAuthBase.SignatureTypes</see>.</param>
''' <returns>The signature base</returns>
Public Function GenerateSignatureBase(ByVal url As Uri, ByVal consumerKey As String, ByVal token As String, ByVal tokenSecret As String, ByVal httpMethod As String, ByVal timeStamp As String, _
 ByVal nonce As String, ByVal signatureType As String, ByRef normalizedUrl As String, ByRef normalizedRequestParameters As String) As String
    If token Is Nothing Then
        token = String.Empty
    End If

    If tokenSecret Is Nothing Then
        tokenSecret = String.Empty
    End If

    If String.IsNullOrEmpty(consumerKey) Then
        Throw New ArgumentNullException("consumerKey")
    End If

    If String.IsNullOrEmpty(httpMethod) Then
        Throw New ArgumentNullException("httpMethod")
    End If

    If String.IsNullOrEmpty(signatureType) Then
        Throw New ArgumentNullException("signatureType")
    End If

    normalizedUrl = Nothing
    normalizedRequestParameters = Nothing

    Dim parameters As List(Of QueryParameter) = GetQueryParameters(url.Query)
    parameters.Add(New QueryParameter(OAuthVersionKey, OAuthVersion))
    parameters.Add(New QueryParameter(OAuthNonceKey, nonce))
    parameters.Add(New QueryParameter(OAuthTimestampKey, timeStamp))
    parameters.Add(New QueryParameter(OAuthSignatureMethodKey, signatureType))
    parameters.Add(New QueryParameter(OAuthConsumerKeyKey, consumerKey))

    If Not String.IsNullOrEmpty(token) Then
        parameters.Add(New QueryParameter(OAuthTokenKey, token))
    End If

    If Not String.IsNullOrEmpty(oauth_verifier) Then
        parameters.Add(New QueryParameter(oAauthVerifier, oauth_verifier))
    End If


    parameters.Sort(New QueryParameterComparer())


    normalizedUrl = String.Format("{0}://{1}", url.Scheme, url.Host)
    If Not ((url.Scheme = "http" AndAlso url.Port = 80) OrElse (url.Scheme = "https" AndAlso url.Port = 443)) Then
        normalizedUrl += ":" & url.Port
    End If
    normalizedUrl += url.AbsolutePath
    normalizedRequestParameters = NormalizeRequestParameters(parameters)

    Dim signatureBase As New StringBuilder()
    signatureBase.AppendFormat("{0}&", httpMethod.ToUpper())
    signatureBase.AppendFormat("{0}&", UrlEncode(normalizedUrl))
    signatureBase.AppendFormat("{0}", UrlEncode(normalizedRequestParameters))

    Return signatureBase.ToString()
End Function


''' <summary>
''' Generate the signature value based on the given signature base and hash algorithm
''' </summary>
''' <param name="signatureBase">The signature based as produced by the GenerateSignatureBase method or by any other means</param>
''' <param name="hash">The hash algorithm used to perform the hashing. If the hashing algorithm requires initialization or a key it should be set prior to calling this method</param>
''' <returns>A base64 string of the hash value</returns>
Public Function GenerateSignatureUsingHash(ByVal signatureBase As String, ByVal hash As HashAlgorithm) As String
    Return ComputeHash(hash, signatureBase)
End Function

''' <summary>
''' Generates a signature using the HMAC-SHA1 algorithm
''' </summary>      
''' <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
''' <param name="consumerKey">The consumer key</param>
''' <param name="consumerSecret">The consumer seceret</param>
''' <param name="token">The token, if available. If not available pass null or an empty string</param>
''' <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
''' <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
''' <returns>A base64 string of the hash value</returns>
Public Function GenerateSignature(ByVal url As Uri, ByVal consumerKey As String, ByVal consumerSecret As String, ByVal token As String, ByVal tokenSecret As String, ByVal httpMethod As String, _
 ByVal timeStamp As String, ByVal nonce As String, ByRef normalizedUrl As String, ByRef normalizedRequestParameters As String) As String
    Return GenerateSignature(url, consumerKey, consumerSecret, token, tokenSecret, httpMethod, _
     timeStamp, nonce, SignatureTypes.HMACSHA1, normalizedUrl, normalizedRequestParameters)
End Function

''' <summary>
''' Generates a signature using the specified signatureType 
''' </summary>      
''' <param name="url">The full url that needs to be signed including its non OAuth url parameters</param>
''' <param name="consumerKey">The consumer key</param>
''' <param name="consumerSecret">The consumer seceret</param>
''' <param name="token">The token, if available. If not available pass null or an empty string</param>
''' <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param>
''' <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param>
''' <param name="signatureType">The type of signature to use</param>
''' <returns>A base64 string of the hash value</returns>
Public Function GenerateSignature(ByVal url As Uri, ByVal consumerKey As String, ByVal consumerSecret As String, ByVal token As String, ByVal tokenSecret As String, ByVal httpMethod As String, _
 ByVal timeStamp As String, ByVal nonce As String, ByVal signatureType As SignatureTypes, ByRef normalizedUrl As String, ByRef normalizedRequestParameters As String) As String
    normalizedUrl = Nothing
    normalizedRequestParameters = Nothing

    Select Case signatureType
        Case SignatureTypes.PLAINTEXT
            Return HttpUtility.UrlEncode(String.Format("{0}&{1}", consumerSecret, tokenSecret))
        Case SignatureTypes.HMACSHA1
            Dim signatureBase As String = GenerateSignatureBase(url, consumerKey, token, tokenSecret, httpMethod, timeStamp, _
             nonce, HMACSHA1SignatureType, normalizedUrl, normalizedRequestParameters)

            Dim hmacsha1 As New HMACSHA1()
            hmacsha1.Key = Encoding.ASCII.GetBytes(String.Format("{0}&{1}", UrlEncode(consumerSecret), If(String.IsNullOrEmpty(tokenSecret), "", UrlEncode(tokenSecret))))

            Return GenerateSignatureUsingHash(signatureBase, hmacsha1)
        Case SignatureTypes.RSASHA1
            Throw New NotImplementedException()
        Case Else
            Throw New ArgumentException("Unknown signature type", "signatureType")
    End Select
End Function

''' <summary>
''' Generate the timestamp for the signature        
''' </summary>
''' <returns></returns>

Public Overridable Function GenerateTimeStamp() As String
    ' Default implementation of UNIX time of the current UTC time
    Dim ts As TimeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, _
     0)
    Return Convert.ToInt64(ts.TotalSeconds).ToString()
End Function

'
'      public virtual string GenerateTimeStamp() {
'          // Default implementation of UNIX time of the current UTC time
'          TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
'          string timeStamp = ts.TotalSeconds.ToString();
'          timeStamp = timeStamp.Substring(0, timeStamp.IndexOf(","));
'          return Convert.ToInt64(timeStamp).ToString(); 
'      }


''' <summary>
''' Generate a nonce
''' </summary>
''' <returns></returns>
Public Overridable Function GenerateNonce() As String
    ' Just a simple implementation of a random number between 123400 and 9999999
    Return random.[Next](123400, 9999999).ToString()
End Function

End Class

Change:

Public Function Compare(ByVal x As oAuthBase2.QueryParameter, ByVal y As oAuthBase2.QueryParameter) As Integer

to:

Public Function Compare(ByVal x As oAuthBase2.QueryParameter, ByVal y As oAuthBase2.QueryParameter) As Integer Implements IComparer(Of oAuthBase2.QueryParameter).Compare
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

类“QueryParameterComparer”必须实现函数比较。 的相关文章

  • 检查有效的 IMEI

    有人知道如何检查有效的 IMEI 吗 我找到了一个可以检查此页面的功能 http www dotnetfunda com articles article597 imeivalidator in vbnet aspx http www do
  • 使用 VB.NET 检查 Word 文档中的字体样式

    我想使用vb net检查一个word文件 并检查文档中的样式是否正确 我必须在word文档中检查这些表达式 a Verdana 16 pt Bold Red b Verdana 12 pt Bold Italic Blue c Verdan
  • 将 PDF 嵌入到 WPF 应用程序中

    我正在尝试在 WPF 应用程序中嵌入 显示 PDF 到目前为止 我已经尝试过这些解决方案 但没有成功 在 a 中显示 PDFWindowsFormsHost主持一个AxAcroPdf控制 类似于显示的内容here http hugeonio
  • SELECT 语句会受到 SQL 注入攻击吗?

    实际上有2个问题 我知道我必须尽可能多地使用存储过程 但我想知道以下内容 A 我可以从 SELECT 语句 例如 Select from MyTable 获得 SQL 注入攻击吗 B 另外 当我在 ASP NET 中使用 SQLDataSo
  • VB.NET 中的模块变量何时实例化?

    我想知道在程序的生命周期中 模块中的变量将被初始化 如下例所示 Module Helper Friend m Settings As New UserSettings Sub Foo End Sub Sub Bar End Sub End
  • UDP SocketException - 通常只允许每个套接字地址使用一次

    尽管这里有很多非常相似的问题 但提供的答案都没有帮助我 这让我很难过 我有一个非常大的管理系统 我的任务是为其编写一些 UDP 数据包发送 接收 我已经编写了一个原型 一切都很好 所以我开始将我的代码合并到所述系统中 然而 我现在弹出了一个
  • 为什么 True 等于 -1

    我想知道为什么 True 等于 1 而不是 1 如果我没记错的话 以前 在 C 语言中 true 将等于 1 Dim t f As Integer t True f False Console WriteLine t 1 Console W
  • 什么可能会在一台服务器上导致此错误,而在另一台服务器上则不会?

    我们有一个连接到外部 Web 服务的 ASP Net 网站 几天前它突然停止工作 基本代码是这样的 Try request New ExternalWebService ProcessRequestService Error occurs
  • 在 VB.NET 中 a = b = 5 - 不可能吗?

    VB NET 中可以这样做吗a b 5 我知道 也是比较运算符 我的意思是做not结果 例如 如果 b 2 a false b 2 然而 在下面的情况下该怎么做呢 不方便在我的代码中引起了这个问题 一些对象a b z由方法中的 ref 传递
  • 如何使用正则表达式验证带有可选百分比符号的小数?

    正如问题的标题 我需要使用以下值验证正则表达式 最多 2 个小数位和 9 个整数 带有可选的百分比符号 Valid 10 0 1111111 12 15 2 10 2 3 Invalid 12 02 123456789123 123 I t
  • 如果我使用客户端计算机上未安装的字体,会发生什么情况?

    有人可以告诉我 如果我在 WinForms 应用程序中使用目标计算机上不可用的字体 会发生什么情况 它是否使用同一系列的字体 只是 Sans Serif 还是其他字体 您的应用程序将回退到 Segoe UI Tahoma 然后是 MS Sa
  • 在 VB.NET 中将类标记为静态

    正如刚刚在最近的一篇文章中所说question https stackoverflow com questions 135759 why cant i inherit iodirectory and answer https stackov
  • Sub New() 在此上下文中无法访问,因为它是“Friend”

    那么这是什么意思以及如何解决它 如果我将 New 关键字放在下面的行中 则会出现此消息 如果删除它 我会在运行时收到错误消息 提示我需要使用 New 我究竟做错了什么 Dim oPS As AeccPointStyle New AeccPo
  • 短路:Or Else 与 Or 组合

    如果我有以下 a OrElse b 是True那么显然 b 永远不会被评估 但如果我添加一个Or 然后呢 a OrElse b Or c c 是否 应该被评估 如果我放入一些括号怎么办 抱歉 如果这是基本的 当然 我可以自己测试答案 但我无
  • 在 VB.NET 中调用过程的优缺点是什么?

    我想知道在VB NET中使用Call关键字和不使用Call调用程序的优缺点 Private Sub ProOne Code Are Here End Sub Private Sub Calling ProOne I would like t
  • 可点击的链接未出现在生成的锚标记的页面上

    我有一些 js 代码生成以下锚标记 a 2017 09 10 a 我从 IE 的 DOM Explorer 中剪切并粘贴了它 该链接在我显示的页面上不可单击 这是我希望它运行的 vb net Sub DownloadInspection C
  • 在vb.net中将base64解码为图像

    我一直在互联网上搜索 但没有找到答案 你想告诉我如何解码base64 to be Image像折线图一样 我一直在尝试从base64 to Byte首先数组并从Byte数组到Image Private Function convertbyt
  • 在 ASP.Net 2008 或更高版本中创建复合和自定义网格控件[关闭]

    Closed 这个问题需要调试细节 help minimal reproducible example 目前不接受答案 请建议我如何创建复合网格 即 我需要 Framework 3 5 及更高版本中 gridview 的所有功能 但还需要在
  • 创建一个从系统托盘运行的程序

    我想创建一个从 Windows 右下角系统托盘运行的程序 但我不知道从哪里开始 有人可以告诉 告诉我在哪里查找和示例或使用什么命令 研究吗 Add a NotifyIcon到主窗口窗体 使用Resize事件在Form控制何时显示Notify
  • 将参数传递给 .NET 定义的命令

    我需要在 Autocad 2000i 的命令行上编写一个命令 并且希望 autocad 提示输入参数 然后我的 vb net 程序将根据收到的参数进行操作 基本上我想我的解决方案都在这里 http through the interface

随机推荐