通过 OAuth 访问 imgUr(上传到用户帐户)

2023-12-03

为了开始执行这个“简单”任务,我研究了一个作为示例的程序here要遵循并重现这些步骤,该过程可以“匿名”上传图像:

Private ReadOnly ClientId As String = "My Client ID" ' => "..............."
Private ReadOnly ClientSecret As String = "My Client Secret" ' => "........................................"

' Usage:
' Dim url As String = UploadImage("C:\Image.jpg") : MessageBox.Show(url)
Public Function UploadImage(ByVal image As String)

    Dim w As New WebClient()
    w.Headers.Add("Authorization", "Client-ID " & ClientId)
    Dim Keys As New System.Collections.Specialized.NameValueCollection

    Try

        Keys.Add("image", Convert.ToBase64String(File.ReadAllBytes(image)))
        Dim responseArray As Byte() = w.UploadValues("https://api.imgur.com/3/image", Keys)
        Dim result = Encoding.ASCII.GetString(responseArray)
        Dim reg As New System.Text.RegularExpressions.Regex("link"":""(.*?)""")
        Dim match As Match = reg.Match(result)
        Dim url As String = match.ToString.Replace("link"":""", "").Replace("""", "").Replace("\/", "/")
        Return url

    Catch s As Exception

        MessageBox.Show("Something went wrong. " & s.Message)
        Return "Failed!"

    End Try

End Function

但我真正想做的是将图像上传到我的用户帐户,即http://elektrostudios.imgur.com.

我找到了this问题,但他在答案中所说的内容对我来说并不清楚(由于我的新手知识),无论如何,我尝试使用上面的功能,但只是发送BEARER标题与我的ClientSecretID 因为如果我明白什么是oauth 2 API 文档说令牌也可能是ClientSecretId?,但我没有得到预期的结果。

因此,我正在寻找获取正确访问令牌的方法this其他问题帮助我发现休息锐利库并了解如何发送请求,我做了一些修改以将其与 Imgur API 一起使用,但我收到了以下错误响应:

{"data":{"error":"client_id and response_type are required","request":"\/oauth2\/authorize","method":"POST"},"success":false,"status":400}

这就是我所拥有的:

Public Sub GetAccessToken()

    Dim xrc As RestClient = New RestClient
    Dim grant_type As String = "authorization_code"
    Dim request As New RestRequest(Method.POST)
    Dim strBody As String
    Dim response As RestResponse
    Dim strResponse As String

    request.Method = Method.POST
    request.RequestFormat = DataFormat.Xml

    'Base URL
    xrc.BaseUrl = "https://api.imgur.com"

    'Resource
    request.Resource = "oauth2/authorize"

    'Format body
    strBody = String.Format("client_id={0}&response_type={1}", ClientId, ClientSecret)

    'Add body to request
    request.AddBody("Authorization", strBody)

    'Execute
    response = xrc.Execute(request)

    'Parse Response
    strResponse = response.Content

    MessageBox.Show(response.Content.ToString)

End Sub

所以我的问题是二合一:

如何将图像上传到 Imgur 用户 使用必需的东西(例如访问令牌)的帐户?

PS:请记住,即使获得访问令牌,我也不知道如何在存储后使用它。

UPDATE:

我正在尝试使用@Plutonix解决方案,但当我尝试请求令牌时,它会抛出异常”Need a valid PIN first”,我正在使用有效的 ClientId 和 ClientSecret,我还缺少更多内容吗?,这是代码:

Private imgUR As New imgurAPI("my client id", "my client secret")

Private Sub Button1_Click() Handles Button1.Click

    Dim wb As New WebBrowser
    imgUR.RequestPinBrowser(wb)

    ' The instruction below throws an exception:
    ' "Need a valid PIN first"
    Dim result As imgurAPI.imgUrResults = imgUR.RequestToken
    wb.Dispose()

    ' check result
    If result = imgurAPI.imgUrResults.OK Then

        ' assumes the file exists
        imgUR.UploadImage("C:\Test.jpg", False)

        Clipboard.SetText(imgUR.LastImageLink)
        MessageBox.Show(imgUR.LastImageLink)

    Else
        MessageBox.Show(String.Format("Error getting access token. Status:{0}",
            result.ToString))
    End If

End Sub

这很长,因为它或多或少是一个完整的 API:

Public Class imgurAPI
    ' combination of this API and imgUR server responses
    Public Enum imgUrResults
        OK = 200                        ' AKA Status200 

        ' errors WE return
        OtherAPIError = -1              ' so far, just missing ImgLink
        InvalidToken = -2
        InvalidPIN = -3                 ' pins expire
        InvalidRequest = -4
        TokenParseError = -5

        ' results we get from server
        BadRequestFormat = 400          ' Status400   
        AuthorizationError = 401        ' Status401  

        Forbidden = 403                 ' Status403   
        NotFound = 404                  ' Status404   ' bad URL Endpoint
        RateLimitError = 429            ' Status429   ' RateLimit Error
        ServerError = 500               ' Status500   ' internal server error

        UknownStatus = 700              ' We havent accounted for it (yet), 
                                        '   may be trivial or new
    End Enum

    ' container for the cool stuff they send us
    Friend Class Token
        Public Property AcctUserName As String
        Public Property AccessToken As String
        Public Property RefreshToken As String
        Public Property Expiry As DateTime

        Public Sub New()
            AcctUserName = ""
            AccessToken = ""
            RefreshToken = ""
            Expiry = DateTime.MinValue
        End Sub

        Friend Function IsExpired() As Boolean

            If (Expiry > DateTime.Now) Then
                Return False
            Else
                ' if expired reset everything so some moron doesnt
                ' expose AccessToken and test for ""
                AcctUserName = ""
                AccessToken = ""
                RefreshToken = ""
                Expiry = DateTime.MinValue
                Return True
            End If
        End Function

    End Class

    ' NO simple ctor!!!
    ' constructor initialized with ClientID and SecretID
    Public Sub New(clID As String, secret As String)
        clientID = clID
        clientSecret = secret
        myPin = ""
        imgToken = New Token
        LastImageLink = ""
        UseClipboard = True
        AnonOnly = False
    End Sub

    ' constructor initialized with ClientID and SecretID
    Public Sub New(clID As String)
        clientID = clID
        clientSecret = ""
        myPin = ""
        imgToken = New Token
        LastImageLink = ""
        UseClipboard = True
        AnonOnly = True
    End Sub


    Private clientID As String
    Private clientSecret As String

    Private AnonOnly As Boolean = True

    ' tokens are not public
    Private imgToken As Token

    Public Property LastImageLink As String

    Public Property UseClipboard As Boolean

    ' precise moment when it expires for use in code
    Public ReadOnly Property TokenExpiry As DateTime
        Get
            If imgToken IsNot Nothing Then
                Return imgToken.Expiry
            Else
                Return Nothing
            End If
        End Get
    End Property

    Public Function GetExpiryCountdown() As String
        Return String.Format("{0:hh\:mm\:ss}", GetExpiryTimeRemaining)
    End Function

    ' time left as a TimeSpan
    Public Function GetExpiryTimeRemaining() As TimeSpan
        Dim ts As New TimeSpan(0)

        If imgToken Is Nothing Then
            Return ts
        End If

        If DateTime.Now > imgToken.Expiry Then
            Return ts
        Else
            ts = imgToken.Expiry - DateTime.Now
            Return ts
        End If

    End Function

    Public Function IsTokenValid() As Boolean

        If imgToken Is Nothing Then
            Return False
        End If

        If String.IsNullOrEmpty(imgToken.AcctUserName) Then
            Return False
        End If

        If imgToken.IsExpired Then
            Return False
        End If

        Return True

    End Function

    ' Currently, the PIN is set from a calling App.  Might be possible
    ' to feed the log in to imgUr to get a PIN
    Private myPin As String
    Public WriteOnly Property Pin As String
        Set(value As String)
            myPin = value
        End Set
    End Property


    ' Navigates to the web page.
    ' see wb_DocumentCompleted for code to 
    ' parse the PIN from the document
    Public Sub RequestPinBrowser(BrowserCtl As WebBrowser)

        If AnonOnly Then
            ' you do not need a PIN for Anon
            Throw New ApplicationException("A PIN is not needed for ANON Uploads")
            Exit Sub
        End If

        If BrowserCtl Is Nothing Then
            Throw New ArgumentException("Missing a valid WebBrowser reference")
            Exit Sub
        End If

        ' imgur API format
        ' https://api.imgur.com/oauth2/authorize?client_id=YOUR_CLIENT_ID&response_type=REQUESTED_RESPONSE_TYPE&state=APPLICATION_STATE

        Dim OAuthUrlTemplate = "https://api.imgur.com/oauth2/authorize?client_id={0}&response_type={1}&state={2}"
        Dim ReqURL As String = String.Format(OAuthUrlTemplate, clientID, "pin", "ziggy")

        BrowserCtl.Url = New Uri(ReqURL)
    End Sub


    Public Function GetAccessToken() As imgUrResults
        ' there are different types of token requests
        ' which vary only by the data submitted

        Dim sReq As String = String.Format("client_id={0}&client_secret={1}&grant_type=pin&pin={2}",
                                            clientID, clientSecret, myPin)
        If myPin = String.Empty Then
            Return imgUrResults.InvalidPIN
        End If

        If AnonOnly Then Return imgUrResults.InvalidRequest

        ' call generic token processor
        Return RequestToken(sReq)

    End Function

    ' request a Token 
    Private Function RequestToken(sRequest As String) As imgUrResults
        Dim url As String = "https://api.imgur.com/oauth2/token/"

        Dim myResult As imgUrResults = imgUrResults.OK

        ' create request for the URL, using POST method
        Dim request As WebRequest = WebRequest.Create(url)
        request.Method = "POST"

        ' convert the request, set content format, length
        Dim data As Byte() = System.Text.Encoding.UTF8.GetBytes(sRequest)
        request.ContentType = "application/x-www-form-urlencoded"
        request.ContentLength = data.Length

        ' write the date to request stream
        Dim dstream As Stream = request.GetRequestStream
        dstream.Write(data, 0, data.Length)
        dstream.Close()

        ' json used on the response and potential WebException
        Dim json As New JavaScriptSerializer()

        ' prepare for a response
        Dim response As WebResponse = Nothing
        Dim SvrResponses As Dictionary(Of String, Object)

        Try
            response = request.GetResponse
            ' convert status code to programmatic result
            myResult = GetResultFromStatus(CType(response, HttpWebResponse).StatusCode)

        Catch ex As WebException
            ' a bad/used pin will throw an exception
            Dim resp As String = New StreamReader(ex.Response.GetResponseStream()).ReadToEnd()

            SvrResponses = CType(json.DeserializeObject(resp.ToString), 
                                    Dictionary(Of String, Object))
            myResult = GetResultFromStatus(Convert.ToString(SvrResponses("status")))

        End Try

        'Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
        'Console.WriteLine(CType(response, HttpWebResponse).StatusCode)

        ' premature evacuation
        If myResult <> imgUrResults.OK Then
            If dstream IsNot Nothing Then
                dstream.Close()
                dstream.Dispose()
            End If
            If response IsNot Nothing Then
                response.Close()
            End If

            Return myResult
        End If

        ' read the response stream
        dstream = response.GetResponseStream
        Dim SvrResponseStr As String
        Using sr As StreamReader = New StreamReader(dstream)
            ' stream to string
            SvrResponseStr = sr.ReadToEnd
            'Console.WriteLine(SvrResponse)
        End Using

        ' close streams
        dstream.Close()
        dstream.Dispose()
        response.Close()

        Try
            ' use json serialier to parse the result(s)
            ' convert SvrRsponse to Dictionary
            SvrResponses = CType(json.DeserializeObject(SvrResponseStr), 
                                    Dictionary(Of String, Object))

            ' get stuff from Dictionary
            imgToken.AccessToken = Convert.ToString(SvrResponses("access_token"))
            imgToken.RefreshToken = Convert.ToString(SvrResponses("refresh_token"))
            imgToken.AcctUserName = Convert.ToString(SvrResponses("account_username"))

            ' convert expires_in to a point in time
            Dim nExp As Integer = Convert.ToInt32(Convert.ToString(SvrResponses("expires_in")))
            imgToken.Expiry = Date.Now.Add(New TimeSpan(0, 0, nExp))

            ' Pins are single use
            ' throw it away since it is no longer valid 
            myPin = ""

        Catch ex As Exception
            'MessageBox.Show(ex.Message)
            myResult = imgUrResults.TokenParseError
        End Try

        Return myResult


    End Function

    ' public interface to check params before trying to upload
    Public Function UploadImage(filename As String, Optional Anon As Boolean = False) As imgUrResults

        If AnonOnly Then
            Return DoImageUpLoad(filename, AnonOnly)
        Else
            If IsTokenValid() = False Then
                Return imgUrResults.InvalidToken
            End If
        End If

        ' should be the job of the calling app to test for FileExist
        Return DoImageUpLoad(filename, Anon)

    End Function

    ' actual file uploader
    Private Function DoImageUpLoad(fileName As String, Optional Anon As Boolean = False) As imgUrResults
        Dim result As imgUrResults = imgUrResults.OK
        LastImageLink = ""

        Try
            ' create a WebClient 
            Using wc = New Net.WebClient()
                ' read image
                Dim values = New NameValueCollection() From
                        {
                            {"image", Convert.ToBase64String(File.ReadAllBytes(fileName))}
                        }
                ' type of headers depends on whether this is an ANON or ACCOUNT upload
                If Anon Then
                    wc.Headers.Add("Authorization", "Client-ID " + clientID)
                Else
                    wc.Headers.Add("Authorization", "Bearer " & imgToken.AccessToken)
                End If

                ' upload, get response
                Dim response = wc.UploadValues("https://api.imgur.com/3/upload.xml", values)

                ' read response converting byte array to stream
                Using sr As New StreamReader(New MemoryStream(response))
                    Dim uplStatus As String
                    Dim SvrResponse As String = sr.ReadToEnd

                    Dim xdoc As XDocument = XDocument.Parse(SvrResponse)
                    ' get the status of the request
                    uplStatus = xdoc.Root.Attribute("status").Value
                    result = GetResultFromStatus(uplStatus)

                    If result = imgUrResults.OK Then
                        LastImageLink = xdoc.Descendants("link").Value

                        ' only overwrite the server result status
                        If String.IsNullOrEmpty(LastImageLink) Then
                            ' avoid NRE elsewhere
                            LastImageLink = ""
                            ' we did something wrong parsing the result
                            ' but this one is kind of minor
                            result = imgUrResults.OtherAPIError
                        End If
                    End If

                End Using

                If UseClipboard AndAlso (result = imgUrResults.OK) Then
                    Clipboard.SetText(LastImageLink)
                End If

            End Using
        Catch ex As Exception
            Dim errMsg As String = ex.Message

            ' rate limit
            If ex.Message.Contains("429") Then
                result = imgUrResults.RateLimitError

                ' internal error
            ElseIf ex.Message.Contains("500") Then
                result = imgUrResults.ServerError

            End If
        End Try

        Return result
    End Function

    Private Function GetResultFromStatus(status As String) As imgUrResults

        Select Case status.Trim
            Case "200"
                Return imgUrResults.OK
            Case "400"
                Return imgUrResults.BadRequestFormat
            Case "401"
                Return imgUrResults.AuthorizationError
            Case "403"
                Return imgUrResults.Forbidden
            Case "404"
                Return imgUrResults.NotFound
            Case "429"
                Return imgUrResults.RateLimitError
            Case "500"
                Return imgUrResults.ServerError
            Case Else
                ' Stop - work out other returns
                Return imgUrResults.UknownStatus
        End Select
    End Function

    Private Function GetResultFromStatus(status As Int32) As imgUrResults
        ' some places we get a string, others an integer
        Return GetResultFromStatus(status.ToString)
    End Function

End Class

如何使用它

该过程需要用户使用 Web 浏览器进行导航并请求 PIN。为了测试/开发,我使用了 WebBrowser 控件并从返回的页面中获取了 PIN。

注意:为了测试,我的 imgUR 帐户设置为 DESKTOP,因为我们是从 DESKTOP 应用程序发送的。另外,这适用于您将图像发送到您的帐户。如果不透露您的秘密 ID 和/或在应用程序中嵌入您的主 ImgUR 登录名和密码,其他人就无法上传到您的帐户。 ImgUR 就是这样设计的。

A. 创建一个 imgUR 对象:

Friend imgUR As imgurAPI
imgUR = New imgurAPI(<your Client ID>,<your secret code>)

B. 获取 Pin 图 - 方法一

' pass the app's WebBrowser Control
imgUR.RequestPinBrowser(wb)

这将带您进入 imgur 页面,您必须在其中授权颁发 PIN 码才能上传到您的帐户。输入您的帐户名、密码,然后单击“允许”。将显示包含 PIN 码的新页面。将 PIN 从网页复制到其他某个控件,该控件可以将其提供给 imgurAPI 类。

下面的代码可以解析 PIN 页面并将其放入另一个控件中。

方法二

  • 使用您自己的外部浏览器,转至

https://api.imgur.com/oauth2/authorize? client_id=YOUR_CLIENT_ID&response_type=pin&state=ziggy

  • Log In
  • 将您收到的 PIN 码复制到TextBox或者将其发送到 imgurAPI 的东西:
  • 设置引脚:imgUR.Pin = <<PIN YOU RECEIVED>>

无论哪种方式,过程都是相同的,只是您是否希望在表单中包含 WebBrowser 控件的问题。 PIN 码的有效期很短,因此您必须立即使用它来获取访问令牌。

C. 获取访问令牌

' imgUrResults is an enum exposed by the class
Dim result As imgurAPI.imgUrResults = imgUR.RequestToken

Notes:

  • imgUR 类将保留令牌
  • 令牌目前将在 1 小时(3600 秒)后过期

D:上传文件
上传使用imgUR.UploadImage(filename, boolAnon)

文件名 - 要上传的文件

boolAnon - 布尔标志。 False = 将此文件上传到您的帐户,而不是 Anon 通用池方法。

Example:

' get token
Dim result As imgurAPI.imgUrResults = imgUR.RequestToken

' check result
If result = imgurAPI.imgUrResults.OK Then
    ' assumes the file exists
    imgUR.UploadImage("C:\Temp\London.jpg", False)
Else
    MessageBox.Show(String.Format("Error getting access token. Status:{0}",
        result.ToString))
End If

文件上传后,该过程会在响应中查找链接。如果可以解析链接,则可以从LastImageLink属性并粘贴到剪贴板。

其他属性、设置和方法

最后一张图片链接(字符串)- 最后上传的图像的 URL

使用剪贴板(Bool) - 如果为 true,imgurAPI 类会将上传图像的链接发布到剪贴板

令牌到期(Date) - 当前令牌过期的日期时间

获取令牌剩余时间() As TimeSpan - 表示当前令牌到期前多长时间的 TimeSpan

公共函数 GetTokenCountdown()As String - TimeRemaining 的格式化字符串

公共只写属性引脚作为字符串 - 获取访问令牌所需的 PIN

公共函数 IsTokenValid()As Boolean - 当前令牌是否有效

公共函数 IsTokenExpired() As Boolean - TimeRemaining 与 DateTime.Now 的简单布尔版本

Notes

  • 令牌可以更新或延长。但由于它们持续一个小时,这似乎已经足够了。
  • PINS 只能在短时间内有效。一旦 PIN 被交换为令牌,imgurAPI(此类)就会清除 PIN。如果获取令牌时出现问题,您必须先获取新的 PIN(如果您是几分钟前才获取的,则粘贴最后一个 PIN)。
  • 上传的图像对全世界来说是不可见的,除非/直到您更改帐户的设置。
  • 您可以重置您的 SecretID(设置 -> 应用程序)。如果这样做,您还需要为使​​用此 API 类的应用程序重置它,并重新编译(或从配置文件中读取它)。

如果您使用WebBrowser控件以获取 PIN,您可以将此代码添加到DocumentCompleted从 HTML 中抓取 PIN 的事件:

' wb is the control
Dim htmlDoc As System.Windows.Forms.HtmlDocument = wb.Document
Dim elP As System.Windows.Forms.HtmlElement = htmlDoc.GetElementById("pin")

If elP IsNot Nothing Then
    sPin = elP.GetAttribute("value")
    If String.IsNullOrEmpty(sPin) = False Then
       ' user has to push the button for `imgUR.Pin = tbPIN.Text`
       ' this is in case the HTML changes, the user can override
       ' and input the correct PIN
       Me.tbPIN.Text = sPin
    End If

End If

关于 OAuth 模型

这是非官方的 - 从阅读文档和使用 API 中学到的信息。截至目前,适用于 imgur API v3。

nothing自动获取 PIN。您必须以某种方式导航到浏览器中的 URL,然后输入您的帐户名和密码才能获取 PIN。这是设计使然,以便您本人亲自授权某些外部应用程序访问您的帐户内容。

方法一上面使用 .NET WebBrowser 控件来执行此操作。通过这种方法,我们可以确保您和 imgur 类都使用相同的 Endpoint/URL,因为它通过浏览器控件将您发送到那里。

方法二只是你在某个浏览器中去那里,任何浏览器。登录,获取 PIN,并将其粘贴到 imgurAPI 类中。

无论采用哪种方法,正确使用的端点/URL 是:

在使用 imgurAPI 类的表单上使用浏览器,我们显然可以确定您和该类都使用相同的 URL 和 ClientID。代码为DocumentComplete将 PIN 码提取到文本框中only你仍然需要在类中设置它:

myimgUR.PIN = tbPinCode.Text

PINS 是一次性的,并且会过期。

因此,特别是在开发时,如果您停止代码,添加一些内容然后自然地重新运行,代码将不再具有旧的令牌或PIN。如果最后一个 PIN 是最近使用的并且not提交后,您可能不必再买一个新的,但我发现很难记住是否是这样。

该类将 PINS 视为一次性使用。一旦收到令牌,它就会清除变量,因为它们已被使用并且不再有效。


最终编辑

  • 添加了一个仅限匿名 mode

要使用该类仅以匿名模式上传(到一般站点,而不是您的帐户),不需要 SecretID。为此,请使用新的构造函数重载:

Public Sub New(clientID As String)

这将类设置为仅在 Anon 上工作,并且在使用基于帐户的方法(例如)时,某些方法将返回错误或出现异常GetToken。如果您仅使用 ClientID 对其进行初始化,它将保留在AnonOnly模式,直到您使用 ClientID 和 SecretID 重新创建对象。

没有真正的理由将其用作 AnonOnly(除非您没有帐户),因为 UploadImage 方法允许您将其指定为按文件匿名上传:

Function UploadImage(filename As String, 
                     Optional Anon As Boolean = False) As imgUrResults
  • 修订/澄清了 imgUrResults 枚举

这意味着包罗万象:一些返回指示类检测到的问题,其他返回是简单传递的服务器响应。

  • Removed IsTokenExpired

IsTokenValid更彻底。还有其他方法可以获取剩余时间或实际到期时间。

  • Added assorted error trapping/handling
    • 请求 PIN 时检查有效的 WebBrowser 控件
    • 完善图片上传后获取服务器状态码的方法
    • 重新设计了一些处理,使远程服务器状态优先于类返回

.

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

通过 OAuth 访问 imgUr(上传到用户帐户) 的相关文章

  • 如何在不下载内容的情况下执行 GET 请求?

    我正在开发一个链接检查器 一般来说我可以执行HEAD请求 但是有些网站似乎禁用了这个动词 所以在失败时我还需要执行GET请求 仔细检查链接是否确实已失效 我使用以下代码作为我的链接测试器 public class ValidateResul
  • 如何从 SOAP 响应中删除额外的结果标签

    我知道这个问题以前曾被问过 但我在任何地方都找不到答案 问题是我的 asmx 文件中有以下代码 namespace IrancellSmsServer SoapDocumentService RoutingStyle SoapService
  • 在 VB.NET 中 a = b = 5 - 不可能吗?

    VB NET 中可以这样做吗a b 5 我知道 也是比较运算符 我的意思是做not结果 例如 如果 b 2 a false b 2 然而 在下面的情况下该怎么做呢 不方便在我的代码中引起了这个问题 一些对象a b z由方法中的 ref 传递
  • 数组与列表的性能

    假设您需要一个需要频繁迭代的整数列表 数组 我的意思是非常频繁 原因可能有所不同 但可以说它位于大容量处理的最内层循环的核心 一般来说 人们会选择使用列表 List 因为它们的大小具有灵活性 最重要的是 msdn 文档声称列表在内部使用数组
  • 在 VB2010 Windows 窗体开始时播放 .wav/.mp3 文件?

    制作 VB2010 已经大约一年了 最近开始突破我可以将哪种媒体合并到我的表单中的界限 但我无法播放 wav 或 mp3 文件 我尝试按照微软和其他编码网站上的教程进行操作 但没有成功 任何帮助 将不胜感激 要播放波形文件 您可以简单地使用
  • 生成Excel文件错误

    我在经典 ASP 中使用以下代码生成 Excel 文件 代码很简单并且有效 我在 Windows Vista x86 上的 IIS 7 0 下运行代码 两个问题 有一个奇怪的警告框 这是屏幕快照 http i27 tinypic com 2
  • WebClient读取错误页面的内容

    我有一个加载页面内容的应用程序 我使用 WebClient 类 即使服务器返回 404 500 等错误 我也需要检索内容 我需要这样的东西 WebClient wc new WebClient string pageContent try
  • 如何将字节块读入结构体

    我有一个需要处理的资源文件 它包含一组文件 首先 资源文件列出了其中包含的所有文件 以及一些其他数据 例如在此结构中 struct FileEntry byte Value1 char Filename 12 byte Value2 byt
  • Glassfish 4、JSF 2.2 和 PrimeFaces FileUploadEvent 无法协同工作

    升级到 GlassFish 4 和 JSF 2 2 Primefaces 后 FileUploadEvent 停止工作 对于 JSF 2 1 它可以正常工作 除了文件上传之外 一切正常 我有什么遗漏的吗 GlassFish 4 JSF 2
  • 重写某些 .Net Framework 控件的绘制以更改其边框颜色?

    SCENARIO 我正在使用第三方 Windows 视觉主题 当我看到我的应用程序时 它看起来像这样 但是当我使用正常的Aero主题 它看起来到处都有可怕的白色边框 QUESTION 我知道应用程序中使用的配色方案取决于视觉风格 但是 我可
  • 在 VB.Net 中将字节数组转换为整数

    我想知道在 vb net 中将字节数组 长度 4 转换为整数的最佳方法是什么 我知道 BitConverter 但执行函数调用来执行应该可以通过复制 4 字节内存来完成的操作似乎相当浪费 同样 将单 双精度数从二进制表示形式转换为单 双精度
  • C#:询问用户密码,然后将其存储在 SecureString 中

    在我目前为客户开发的小型应用程序中 我需要询问用户他的 Windows 登录用户名 密码和域 然后使用这些信息系统 诊断 进程 启动启动一个应用程序 我有一个带有 UseSystemPasswordChar 的文本框来屏蔽输入的密码 我需要
  • string.Empty 与 null。您使用哪一个?

    最近工作的同事告诉我不要使用string Empty设置字符串变量时但使用null因为它污染了堆栈 他说不做 string myString string Empty but do string mystring null 真的有关系吗 我
  • 为使用 SSH.NET SshClient.CreateShellStream 执行的命令 (sudo/su) 提供子命令

    我正在尝试使用 Renci SSH NET 从 C Web 应用程序连接到远程 Linux 服务器并执行 shell 脚本 我想一个接一个地运行脚本 但不知道如何运行脚本并读取输出并将其存储在标签中 我已经尝试了下面的代码 但无法一行接一行
  • 注销租约抛出 InvalidOperationException

    我有一个使用插件的应用程序 我在另一个应用程序域中加载插件 我使用 RemoteHandle 类http www pocketsilicon com post Things That Make My Life Hell Part 1 App
  • 错误:表达式不产生值

    我尝试将以下 C 代码转换为 VB NET 但在编译代码时出现 表达式不产生值 错误 C Code return Fluently Configure Mappings m gt m FluentMappings AddFromAssemb
  • 等待进程释放文件

    我如何等待文件空闲以便ss Save 可以用新的覆盖它吗 如果我紧密地运行两次 左右 我会得到一个generic GDI error
  • 调用堆栈中的“外部代码”是什么意思?

    我在 Visual Studio 中调用一个方法 并尝试通过检查调用堆栈来调试它 其中一些行标记为 外部代码 这到底是什么意思 方法来自 dll已被处决 外部代码 意味着该dll没有可用的调试信息 你能做的就是在Call Stack窗口中单
  • 当从finally中抛出异常时,Catch块不会被评估

    出现这个问题的原因是之前在 NET 4 0 中运行的代码在 NET 4 5 中因未处理的异常而失败 部分原因是 try finallys 如果您想了解详细信息 请阅读更多内容微软连接 https connect microsoft com
  • 从列表中选择项目以求和

    我有一个包含数值的项目列表 我需要使用这些项目求和 我需要你的帮助来构建这样的算法 下面是一个用 C 编写的示例 描述了我的问题 int sum 21 List

随机推荐

  • 如何从安装部署项目中排除 app.config

    如何从安装部署项目中排除 app config 我必须维护 app config 中的加密部分 我知道的唯一 半 嵌入方式是使用 RsaProtectedConfigurationProvider 或 DPAPI 提供程序运行代码 由于我必
  • 如何使decimal.TryParse保留尾随零?

    目前如果我这样做 decimal d temp 22 00 decimal TryParse temp NumberStyles Any CultureInfo InvariantCulture out d 然后 d 结果是 22 有什么方
  • System.Timer elapsed 事件似乎在 .Net 中短时间间隔内延迟触发

    我通过 UART 端口对系统进行采样 然后将信息记录在带有时间戳 包括毫秒 的文件中 如果我以 1 秒的间隔采样 数据会按预期返回 类似于 1 52 45 PM 750 data 1 52 45 PM 750 data 1 52 45 PM
  • r:缺失日期的完整值

    在 R 中 如果我有这些数据 date hour temp 2014 01 05 20 00 00 16 2014 01 06 20 00 00 14 2014 01 06 22 00 00 18 与seq我可以获得日期时间序列 begin
  • JSON如何判断成功与错误?

    我是 JSON 新手 一直在 MVC3 ASP NET 中使用它 但是有人可以阐明如何根据 JSON 结果返回错误吗 我的视图中有以下调用 ajax type POST dataType json url EditJSON data Fil
  • 使用 XMLHttpRequest 加载大型 json 文件 (250mb+)

    虽然我查看了此处和其他来源 但我似乎无法完全找到在 javascript 中使用 XMLHttpRequest 加载更大的 JSON 从文件 的问题 我从 C 应用程序生成此 JSON 文件 并且从未遇到过任何无效 json 的问题 较小的
  • 在 swift 3 中使用计时器自动更改 UIPageViewController 中的页面?

    I have UIPageViewController包含 4 个视图控制器 我设置了自动更改视图控制器的计时器 转到下一个视图控制器 这个计时器和方法将起作用但问题是它仅适用于第一张幻灯片以及应用程序运行时和 5 秒后UIPageView
  • Python - 获取命令输出无法解码

    我目前正在开发一个项目 我需要在 powershell 中运行命令 并且部分输出不是英语 特别是希伯来语 例如 问题的简化版本 如果我想获取桌面的内容 并且有一个希伯来语文件名 import subprocess command power
  • 我的 PHP 代码被注释掉了

    在这一切发生之前 我正在运行这个 wordpress 安装来使用 xampp 开发主题 但我决定将这台机器的内存从 2GB 升级到 6GB 因为我需要额外的空间来容纳应用程序 我通过复制代码将代码备份到单独的分区中 由于我当时的操作系统是3
  • 如何在 swift 中使信用卡 (xxxx-xxxx-xxxx) 输入文本

    我正在尝试使用以下代码创建信用卡类型文本 但无法做到这一点 有什么办法吗 func textField textField UITextField shouldChangeCharactersInRange range NSRange re
  • PHP内存分配不起作用

    WordPress 网站 Centos6 阿帕奇2 2 PHP 5 5 内存 4GB 我有以下 php 错误消息 致命错误 允许的内存大小 268435456 字节已耗尽 问题是我已经分配了512M on php 我已经改变了正确的变量ph
  • 如何提醒 Tic Tac Toe 中的获胜者?

    除其他事项外 我在试图提醒获胜者时遇到了麻烦 当用户尝试单击已按下的按钮时 我也尝试发出警报 但也不知道我在这方面正在做什么 感谢所有帮助 感谢你们 table tr td 00 td td 01 td td 02 td tr tr td
  • 将字符串月年(其中年份只有两位数)转换为 pandas 中的日期时间

    我有一个带有列的数据框month year这是一个字符串 其中年份只有两位数 我想转换month year列到日期时间列 df month year Jan 98 Feb 98 Mar 99 Apr 99 May 99 Oct 00 Nov
  • `__attribute__((some_attribute))` 和 `[[some_attribute]]` 之间有区别吗?

    我刚刚第一次遇到方括号中的属性 并且我做了一些背景阅读 http en cppreference com w cpp language attributes 至少对于 gcc 来说 似乎允许使用多种技术 attribute some att
  • 在单线程上下文中使用 JMS Session 对象的原因

    我是 JMS 的新手 所以对于这里的专家来说这可能是一个非常菜鸟的问题 然而 我很难理解 JMS 是如何工作的一个非常重要的概念 来自Javadoc 的JMS 会话 粗体强调我的 会话对象是单线程上下文用于生产和 消费消息 尽管它可以分配提
  • 读取 ASN.1 DER 编码的 RSA 公钥

    我正在编写一个应用程序来更好地了解 DKIM 规范说我从域 TXT 记录中检索 ASN 1 DER 编码 公钥 我可以在 s1024 domainkey yahoo com MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBi
  • MySQL显示两个值之差之和

    以下是我的查询 SELECT n name n customer id m msn m kwh m kwh LAG m kwh OVER PARTITION BY n customer id ORDER BY m data date tim
  • 要使我的网站在移动浏览器上运行,我需要了解什么?

    我正在使用 ASP NET 3 5 和 Visual Studio 2008 我有一些关于我的网站和移动用户的问题 我的网站能在手机上正确显示吗 哪些项目无法在手机上使用 我知道闪存可能是个问题 为了让我的网站 100 在移动设备上运行 您
  • 即使在 %c 前面添加空格后仍继续跳过提示

    根据我看到的关于同一问题的大多数来源和问题 我尝试添加空格 例如 scanf c variable 但由于某种原因 它最终跳过了更多本应由用户输入的提示 include
  • 通过 OAuth 访问 imgUr(上传到用户帐户)

    为了开始执行这个 简单 任务 我研究了一个作为示例的程序here要遵循并重现这些步骤 该过程可以 匿名 上传图像 Private ReadOnly ClientId As String My Client ID gt Private Rea