elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.


Tema destacado:


  Mostrar Mensajes
Páginas: 1 ... 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 [812] 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 ... 1253
8111  Foros Generales / Foro Libre / Re: Que producto usas mas seguido en: 21 Octubre 2013, 16:33 pm
Mi primer PC fue un Intel, un Pentium y algo, el PC a pesar de ser nuevo (y yo un novato con Windows y con la informática, todo hay que decirlo) el procesador iba a patadas, no tiraba ni a la de trés, y se colgaba cada 2x3, en fín daba muchos muchos problemas de cuelgues.

Todos mis siguientes productos han sido AMD, y nunca he tenido problemas con estos procesadores, estoy más que satisfecho con esta marca por su relación calidad/precio.

PD: Óbviamente en todos estos años Intel ha podido ir mejorando mucho en cuanto a la estabilidad de sus procesadores pero... para mi es mejor bueno conocido que malo por conocer.

Saludos!
8112  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets) en: 21 Octubre 2013, 14:07 pm
Una Class que nos facilitará mucho la tarea de descargar archivos de forma asincronica, para descargar archivos de forma simultanea.

Código
  1. #Region " DownloadFileAsyncExtended "
  2.  
  3. #Region " Usage Examples "
  4.  
  5. ' Public Class Form1
  6. '
  7. ' ' // Instance a new Downlaoder Class
  8. ' Private WithEvents Downloader As New DownloadFileAsyncExtended
  9. '
  10. ' ' // create a listview to update.
  11. ' Private lv As New ListView With {.View = View.Details, .Dock = DockStyle.Fill}
  12. '
  13. ' ' // create a listview item to update.
  14. ' Private lvi As New ListViewItem
  15. '
  16. ' ' // Set an url file to downloads.
  17. ' Dim url As String = "http://msft.digitalrivercontent.net/win/X17-58857.iso"
  18.  
  19.  
  20. ' Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
  21. '
  22. '     ' Add columns to listview.
  23. '     lv.Columns.AddRange({New ColumnHeader With {.Text = "Filename"}, _
  24. '                          New ColumnHeader With {.Text = "Size"}, _
  25. '                          New ColumnHeader With {.Text = "Status"}, _
  26. '                          New ColumnHeader With {.Text = "Completed"}, _
  27. '                          New ColumnHeader With {.Text = "Progress"}, _
  28. '                          New ColumnHeader With {.Text = "Speed"}, _
  29. '                          New ColumnHeader With {.Text = "Time Elapsed"}, _
  30. '                          New ColumnHeader With {.Text = "Time Left"} _
  31. '                        })
  32. '
  33. '     ' Add subitems to listview item.
  34. '     lvi.SubItems.AddRange({"Filename", "Size", "Status", "Completed", "Progress", "Speed", "Time Elapsed", "Time Left"})
  35. '
  36. '     ' Add a Object tag to the listview item,
  37. '     ' so later we can reffer to this download to pause/resume or cancel it.
  38. '     lvi.Tag = Downloader
  39. '
  40. '     ' Add the Listview control into the UI.
  41. '     Me.Controls.Add(lv)
  42. '     ' Add the Listview item into the Listview.
  43. '     lv.Items.Add(lvi)
  44. '
  45. '     ' Set Application simultaneous internet downloads limit.
  46. '     Net.ServicePointManager.DefaultConnectionLimit = 5
  47. '
  48. '     '// IMPORTANT !!
  49. '     '// If you don't add this line, then all events are raised on a separate thread,
  50. '     '// and you will get cross-thread errors when accessing the Listview,
  51. '     '// or other controls directly in the raised events.
  52. '     Downloader.SynchronizingObject = Me
  53. '
  54. '     '// Update frequency.
  55. '     '// A value higher than 500 ms will prevent the DownloadProgressChanged event,
  56. '     '// from firing continuously and hogging CPU when updating the controls.
  57. '     '// If you download small files that could be downloaded within a second,
  58. '     '// then set it to "NoDelay" or the progress might not be visible.
  59. '     Downloader.ProgressUpdateFrequency = DownloadFileAsyncExtended.UpdateFrequency.MilliSeconds_500
  60. '
  61. '     '// The method to actually download a file. The "userToken" parameter can,
  62. '     '// for example be a control you wish to update in the DownloadProgressChanged,
  63. '     '// and DownloadCompleted events. It is a ListViewItem in this example.
  64. '     Downloader.DowloadFileAsync(url, "C:\Downloaded file.iso", lvi)
  65. '
  66. ' End Sub
  67.  
  68.  
  69. ' '// This event allows you to show the download progress to the user.
  70. '
  71. ' ' e.BytesReceived = Bytes received so far.
  72. ' ' e.DownloadSpeedBytesPerSec = Download speed in bytes per second.
  73. ' ' e.DownloadTimeSeconds = Download time in seconds so far.
  74. ' ' e.ProgressPercentage = Percentage of the file downloaded.
  75. ' ' e.RemainingTimeSeconds = Remaining download time in seconds.
  76. ' ' e.TotalBytesToReceive = Total size of the file that is being downloaded.
  77. ' ' e.userToken = Usually the control(s) you wish to update.
  78. ' Private Sub DownloadProgressChanged(ByVal sender As Object, ByVal e As FileDownloadProgressChangedEventArgs) _
  79. ' Handles Downloader.DownloadProgressChanged
  80. '
  81. '     ' Get the ListViewItem we passed as "userToken" parameter, so we can update it.
  82. '     Dim lvi As ListViewItem = DirectCast(e.userToken, ListViewItem)
  83. '
  84. '     ' Update the ListView item subitems.
  85. '     lvi.SubItems(0).Text = url
  86. '     lvi.SubItems(1).Text = String.Format("{0:#,#} KB", (e.TotalBytesToReceive / 1024))
  87. '     lvi.SubItems(2).Text = "Downloading"
  88. '     lvi.SubItems(3).Text = String.Format("{0:#,#} KB", (e.BytesReceived / 1024))
  89. '     lvi.SubItems(4).Text = e.ProgressPercentage & "%"
  90. '     lvi.SubItems(5).Text = (e.DownloadSpeedBytesPerSec \ 1024).ToString & " kB/s"
  91. '     lvi.SubItems(6).Text = String.Format("{0}:{1}:{2}", _
  92. '                            (e.DownloadTimeSeconds \ 3600).ToString("00"), _
  93. '                            ((e.DownloadTimeSeconds Mod 3600) \ 60).ToString("00"), _
  94. '                            (e.DownloadTimeSeconds Mod 60).ToString("00"))
  95. '     lvi.SubItems(7).Text = String.Format("{0}:{1}:{2}", _
  96. '                            (e.RemainingTimeSeconds \ 3600).ToString("00"), _
  97. '                            ((e.RemainingTimeSeconds Mod 3600) \ 60).ToString("00"), _
  98. '                            (e.RemainingTimeSeconds Mod 60).ToString("00"))
  99. '
  100. ' End Sub
  101.  
  102.  
  103. ' '// This event lets you know when the download is complete.
  104. ' '// The download finished successfully, the user cancelled the download or there was an error.
  105. ' Private Sub DownloadCompleted(ByVal sender As Object, ByVal e As FileDownloadCompletedEventArgs) _
  106. ' Handles Downloader.DownloadCompleted
  107. '
  108. '     ' Get the ListViewItem we passed as userToken parameter, so we can update it.
  109. '     Dim lvi As ListViewItem = DirectCast(e.userToken, ListViewItem)
  110. '
  111. '     If e.ErrorMessage IsNot Nothing Then ' Was there an error.
  112. '
  113. '         lvi.SubItems(2).Text = "Error: " & e.ErrorMessage.Message.ToString
  114. '
  115. '         ' Set an Error ImageKey.
  116. '         ' lvi.ImageKey = "Error"
  117. '
  118. '     ElseIf e.Cancelled Then ' The user cancelled the download.
  119. '
  120. '         lvi.SubItems(2).Text = "Paused"
  121. '
  122. '         ' Set a Paused ImageKey.
  123. '         ' lvi.ImageKey = "Paused"
  124. '
  125. '     Else ' Download was successful.
  126. '
  127. '         lvi.SubItems(2).Text = "Finished"
  128. '
  129. '         ' Set a Finished ImageKey.
  130. '         ' lvi.ImageKey = "Finished"
  131. '
  132. '     End If
  133. '
  134. '     ' Set Tag to Nothing in order to remove the wClient class instance,
  135. '     ' so this way we know we can't resume the download.
  136. '     lvi.Tag = Nothing
  137. '
  138. ' End Sub
  139.  
  140.  
  141. ' '// To Resume a file:
  142. ' ' Download_Helper.Resume_Download(lvi.Tag)
  143.  
  144. ' '// To pause or cancel a file:
  145. ' ' Download_Helper.PauseCancel_Download(lvi.Tag)
  146.  
  147.  
  148. ' End Class
  149.  
  150. #End Region
  151.  
  152. Imports System.IO
  153. Imports System.Net
  154. Imports System.Threading
  155.  
  156. '// This is the main download class.
  157. Public Class DownloadFileAsyncExtended
  158.  
  159. #Region "Methods"
  160.  
  161.    Private _URL As String = String.Empty
  162.    Private _LocalFilePath As String = String.Empty
  163.    Private _userToken As Object = Nothing
  164.    Private _ContentLenght As Long = 0
  165.    Private _TotalBytesReceived As Long = 0
  166.  
  167.    '// Start the asynchronous download.
  168.    Public Sub DowloadFileAsync(ByVal URL As String, ByVal LocalFilePath As String, ByVal userToken As Object)
  169.  
  170.        Dim Request As HttpWebRequest
  171.        Dim fileURI As New Uri(URL) '// Will throw exception if empty or random string.
  172.  
  173.        '// Make sure it's a valid http:// or https:// url.
  174.        If fileURI.Scheme <> Uri.UriSchemeHttp And fileURI.Scheme <> Uri.UriSchemeHttps Then
  175.            Throw New Exception("Invalid URL. Must be http:// or https://")
  176.        End If
  177.  
  178.        '// Save this to private variables in case we need to resume.
  179.        _URL = URL
  180.        _LocalFilePath = LocalFilePath
  181.        _userToken = userToken
  182.  
  183.        '// Create the request.
  184.        Request = CType(HttpWebRequest.Create(New Uri(URL)), HttpWebRequest)
  185.        Request.Credentials = Credentials
  186.        Request.AllowAutoRedirect = True
  187.        Request.ReadWriteTimeout = 30000
  188.        Request.Proxy = Proxy
  189.        Request.KeepAlive = False
  190.        Request.Headers = _Headers '// NOTE: Will throw exception if wrong headers supplied.
  191.  
  192.        '// If we're resuming, then add the AddRange header.
  193.        If _ResumeAsync Then
  194.            Dim FileInfo As New FileInfo(LocalFilePath)
  195.            If FileInfo.Exists Then
  196.                Request.AddRange(FileInfo.Length)
  197.            End If
  198.        End If
  199.  
  200.        '// Signal we're busy downloading
  201.        _isbusy = True
  202.  
  203.        '// Make sure this is set to False or the download will stop immediately.
  204.        _CancelAsync = False
  205.  
  206.        '// This is the data we're sending to the GetResponse Callback.
  207.        Dim State As New HttpWebRequestState(LocalFilePath, Request, _ResumeAsync, userToken)
  208.  
  209.        '// Begin to get a response from the server.
  210.        Dim result As IAsyncResult = Request.BeginGetResponse(AddressOf GetResponse_Callback, State)
  211.  
  212.        '// Add custom 30 second timeout for connecting.
  213.        '// The Timeout property is ignored when using the asynchronous BeginGetResponse.
  214.        ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, New WaitOrTimerCallback(AddressOf TimeoutCallback), State, 30000, True)
  215.  
  216.    End Sub
  217.  
  218.    '// Here we receive the response from the server. We do not check for the "Accept-Ranges"
  219.    '// response header, in order to find out if the server supports resuming, because it MAY
  220.    '// send the "Accept-Ranges" response header, but is not required to do so. This is
  221.    '// unreliable, so we'll just continue and catch the exception that will occur if not
  222.    '// supported and send it the DownloadCompleted event. We also don't check if the
  223.    '// Content-Length is '-1', because some servers return '-1', eventhough the file/webpage
  224.    '// you're trying to download is valid. e.ProgressPercentage returns '-1' in that case.
  225.    Private Sub GetResponse_Callback(ByVal result As IAsyncResult)
  226.  
  227.        Dim State As HttpWebRequestState = CType(result.AsyncState, HttpWebRequestState)
  228.        Dim DestinationStream As FileStream = Nothing
  229.        Dim Response As HttpWebResponse = Nothing
  230.        Dim Duration As New Stopwatch
  231.        Dim Buffer(8191) As Byte
  232.        Dim BytesRead As Long = 0
  233.        Dim ElapsedSeconds As Long = 0
  234.        Dim DownloadSpeed As Long = 0
  235.        Dim DownloadProgress As Long = 0
  236.        Dim BytesReceivedThisSession As Long = 0
  237.  
  238.        ''// Get response
  239.        Response = CType(State.Request.EndGetResponse(result), HttpWebResponse)
  240.  
  241.        '// Asign Response headers to ReadOnly ResponseHeaders property.
  242.        _ResponseHeaders = Response.Headers
  243.  
  244.        '// If the server does not reply with an 'OK (200)' message when starting
  245.        '// the download or a 'PartialContent (206)' message when resuming.
  246.        If Response.StatusCode <> HttpStatusCode.OK And Response.StatusCode <> HttpStatusCode.PartialContent Then
  247.            '// Send error message to anyone who is listening.
  248.            OnDownloadCompleted(New FileDownloadCompletedEventArgs(New Exception(Response.StatusCode), False, State.userToken))
  249.            Return
  250.        End If
  251.  
  252.        '// Create/open the file to write to.
  253.        If State.ResumeDownload Then
  254.            '// If resumed, then create or open the file.
  255.            DestinationStream = New FileStream(State.LocalFilePath, FileMode.OpenOrCreate, FileAccess.Write)
  256.        Else
  257.            '// If not resumed, then create the file, which will delete the existing file if it already exists.
  258.            DestinationStream = New FileStream(State.LocalFilePath, FileMode.Create, FileAccess.Write)
  259.            '// Get the ContentLength only when we're starting the download. Not when resuming.
  260.            _ContentLenght = Response.ContentLength
  261.        End If
  262.  
  263.        '// Moves stream position to beginning of the file when starting the download.
  264.        '// Moves stream position to end of the file when resuming the download.
  265.        DestinationStream.Seek(0, SeekOrigin.End)
  266.  
  267.        '// Start timer to get download duration / download speed, etc.
  268.        Duration.Start()
  269.  
  270.        '// Get the Response Stream.
  271.        Using responseStream As Stream = Response.GetResponseStream()
  272.            Do
  273.                '// Read some bytes.
  274.                BytesRead = responseStream.Read(Buffer, 0, Buffer.Length)
  275.  
  276.                If BytesRead > 0 Then
  277.                    '// Write incoming data to the file.
  278.                    DestinationStream.Write(Buffer, 0, BytesRead)
  279.                    '// Count the total number of bytes downloaded.
  280.                    _TotalBytesReceived += BytesRead
  281.                    '// Count the number of bytes downloaded this session (Resume).
  282.                    BytesReceivedThisSession += BytesRead
  283.                    '// Get number of elapsed seconds (need round number to prevent 'division by zero' error).
  284.                    ElapsedSeconds = CLng(Duration.Elapsed.TotalSeconds)
  285.  
  286.                    '// Update frequency
  287.                    If (Duration.ElapsedMilliseconds - DownloadProgress) >= ProgressUpdateFrequency Then
  288.                        DownloadProgress = Duration.ElapsedMilliseconds
  289.                        '// Calculate download speed in bytes per second.
  290.                        If ElapsedSeconds > 0 Then
  291.                            DownloadSpeed = (BytesReceivedThisSession \ ElapsedSeconds)
  292.                        End If
  293.                        '// Send download progress to anyone who is listening.
  294.                        OnDownloadProgressChanged(New FileDownloadProgressChangedEventArgs(_TotalBytesReceived, _ContentLenght, ElapsedSeconds, DownloadSpeed, State.userToken))
  295.                    End If
  296.  
  297.                    '// Exit loop when paused.
  298.                    If _CancelAsync Then Exit Do
  299.  
  300.                End If
  301.            Loop Until BytesRead = 0
  302.  
  303.        End Using
  304.  
  305.        Try
  306.            '// Send download progress once more. If the UpdateFrequency has been set to
  307.            '// HalfSecond or Seconds, then the last percentage returned might be 98% or 99%.
  308.            '// This makes sure it's 100%.
  309.            OnDownloadProgressChanged(New FileDownloadProgressChangedEventArgs(_TotalBytesReceived, _ContentLenght, Duration.Elapsed.TotalSeconds, DownloadSpeed, State.userToken))
  310.  
  311.            If _CancelAsync Then
  312.                '// Send completed message (Paused) to anyone who is listening.
  313.                OnDownloadCompleted(New FileDownloadCompletedEventArgs(Nothing, True, State.userToken))
  314.            Else
  315.                '// Send completed message (Finished) to anyone who is listening.
  316.                OnDownloadCompleted(New FileDownloadCompletedEventArgs(Nothing, False, State.userToken))
  317.            End If
  318.  
  319.        Catch ex As Exception
  320.            '// Send completed message (Error) to anyone who is listening.
  321.            OnDownloadCompleted(New FileDownloadCompletedEventArgs(ex, False, State.userToken))
  322.  
  323.        Finally
  324.            '// Close the file.
  325.            If DestinationStream IsNot Nothing Then
  326.                DestinationStream.Flush()
  327.                DestinationStream.Close()
  328.                DestinationStream = Nothing
  329.            End If
  330.            '// Stop and reset the duration timer.
  331.            Duration.Reset()
  332.            Duration = Nothing
  333.            '// Signal we're not downloading anymore.
  334.            _isbusy = False
  335.  
  336.        End Try
  337.  
  338.    End Sub
  339.  
  340.    '// Here we will abort the download if it takes more than 30 seconds to connect, because
  341.    '// the Timeout property is ignored when using the asynchronous BeginGetResponse.
  342.    Private Sub TimeoutCallback(ByVal State As Object, ByVal TimedOut As Boolean)
  343.  
  344.        If TimedOut Then
  345.            Dim RequestState As HttpWebRequestState = CType(State, HttpWebRequestState)
  346.            If RequestState IsNot Nothing Then
  347.                RequestState.Request.Abort()
  348.            End If
  349.        End If
  350.  
  351.    End Sub
  352.  
  353.    '// Cancel the asynchronous download.
  354.    Private _CancelAsync As Boolean = False
  355.    Public Sub CancelAsync()
  356.        _CancelAsync = True
  357.    End Sub
  358.  
  359.    '// Resume the asynchronous download.
  360.    Private _ResumeAsync As Boolean = False
  361.    Public Sub ResumeAsync()
  362.  
  363.        '// Throw exception if download is already in progress.
  364.        If _isbusy Then
  365.            Throw New Exception("Download is still busy. Use IsBusy property to check if download is already busy.")
  366.        End If
  367.  
  368.        '// Throw exception if URL or LocalFilePath is empty, which means
  369.        '// the download wasn't even started yet with DowloadFileAsync.
  370.        If String.IsNullOrEmpty(_URL) AndAlso String.IsNullOrEmpty(_LocalFilePath) Then
  371.            Throw New Exception("Cannot resume a download which hasn't been started yet. Call DowloadFileAsync first.")
  372.        Else
  373.            '// Set _ResumeDownload to True, so we know we need to add
  374.            '// the Range header in order to resume the download.
  375.            _ResumeAsync = True
  376.            '// Restart (Resume) the download.
  377.            DowloadFileAsync(_URL, _LocalFilePath, _userToken)
  378.        End If
  379.  
  380.    End Sub
  381.  
  382. #End Region
  383.  
  384. #Region "Properties"
  385.  
  386.    Public Enum UpdateFrequency
  387.        _NoDelay = 0
  388.        MilliSeconds_100 = 100
  389.        MilliSeconds_200 = 200
  390.        MilliSeconds_300 = 300
  391.        MilliSeconds_400 = 400
  392.        MilliSeconds_500 = 500
  393.        MilliSeconds_600 = 600
  394.        MilliSeconds_700 = 700
  395.        MilliSeconds_800 = 800
  396.        MilliSeconds_900 = 900
  397.        Seconds_1 = 1000
  398.        Seconds_2 = 2000
  399.        Seconds_3 = 3000
  400.        Seconds_4 = 4000
  401.        Seconds_5 = 5000
  402.        Seconds_6 = 6000
  403.        Seconds_7 = 7000
  404.        Seconds_8 = 8000
  405.        Seconds_9 = 9000
  406.        Seconds_10 = 10000
  407.    End Enum
  408.  
  409.    '// Progress Update Frequency.
  410.    Public Property ProgressUpdateFrequency() As UpdateFrequency
  411.  
  412.    '// Proxy.
  413.    Public Property Proxy() As IWebProxy
  414.  
  415.    '// Credentials.
  416.    Public Property Credentials() As ICredentials
  417.  
  418.    '// Headers.
  419.    Public Property Headers() As New WebHeaderCollection
  420.  
  421.    '// Is download busy.
  422.    Private _isbusy As Boolean = False
  423.    Public ReadOnly Property IsBusy() As Boolean
  424.        Get
  425.            Return _isbusy
  426.        End Get
  427.    End Property
  428.  
  429.    '// ResponseHeaders.
  430.    Private _ResponseHeaders As WebHeaderCollection = Nothing
  431.    Public ReadOnly Property ResponseHeaders() As WebHeaderCollection
  432.        Get
  433.            Return _ResponseHeaders
  434.        End Get
  435.    End Property
  436.  
  437.    '// SynchronizingObject property to marshal events back to the UI thread.
  438.    Private _synchronizingObject As System.ComponentModel.ISynchronizeInvoke
  439.    Public Property SynchronizingObject() As System.ComponentModel.ISynchronizeInvoke
  440.        Get
  441.            Return Me._synchronizingObject
  442.        End Get
  443.        Set(ByVal value As System.ComponentModel.ISynchronizeInvoke)
  444.            Me._synchronizingObject = value
  445.        End Set
  446.    End Property
  447.  
  448. #End Region
  449.  
  450. #Region "Events"
  451.  
  452.    Public Event DownloadProgressChanged As EventHandler(Of FileDownloadProgressChangedEventArgs)
  453.    Private Delegate Sub DownloadProgressChangedEventInvoker(ByVal e As FileDownloadProgressChangedEventArgs)
  454.    Protected Overridable Sub OnDownloadProgressChanged(ByVal e As FileDownloadProgressChangedEventArgs)
  455.        If Me.SynchronizingObject IsNot Nothing AndAlso Me.SynchronizingObject.InvokeRequired Then
  456.            'Marshal the call to the thread that owns the synchronizing object.
  457.            Me.SynchronizingObject.Invoke(New DownloadProgressChangedEventInvoker(AddressOf OnDownloadProgressChanged), _
  458.                                          New Object() {e})
  459.        Else
  460.            RaiseEvent DownloadProgressChanged(Me, e)
  461.        End If
  462.    End Sub
  463.  
  464.    Public Event DownloadCompleted As EventHandler(Of FileDownloadCompletedEventArgs)
  465.    Private Delegate Sub DownloadCompletedEventInvoker(ByVal e As FileDownloadCompletedEventArgs)
  466.    Protected Overridable Sub OnDownloadCompleted(ByVal e As FileDownloadCompletedEventArgs)
  467.        If Me.SynchronizingObject IsNot Nothing AndAlso Me.SynchronizingObject.InvokeRequired Then
  468.            'Marshal the call to the thread that owns the synchronizing object.
  469.            Me.SynchronizingObject.Invoke(New DownloadCompletedEventInvoker(AddressOf OnDownloadCompleted), _
  470.                                          New Object() {e})
  471.        Else
  472.            RaiseEvent DownloadCompleted(Me, e)
  473.        End If
  474.    End Sub
  475.  
  476. #End Region
  477.  
  478. End Class
  479.  
  480. Public Class Download_Helper
  481.  
  482.    ''' <summary>
  483.    ''' Resumes a file download.
  484.    ''' </summary>
  485.    Public Shared Sub Resume_Download(ByVal File As Object)
  486.  
  487.        Dim Downloader As DownloadFileAsyncExtended
  488.  
  489.        Try
  490.            Downloader = DirectCast(File, DownloadFileAsyncExtended)
  491.            Downloader.CancelAsync()
  492.  
  493.        Catch ex As Exception
  494.            MessageBox.Show(ex.Message, Nothing, MessageBoxButtons.OK, MessageBoxIcon.Error)
  495.  
  496.        End Try
  497.  
  498.  
  499.    End Sub
  500.  
  501.    ''' <summary>
  502.    ''' Pauses or cancel a file download.
  503.    ''' </summary>
  504.    Public Shared Sub PauseCancel_Download(ByVal File As Object)
  505.  
  506.        Dim Downloader As DownloadFileAsyncExtended
  507.  
  508.        Try
  509.  
  510.            Downloader = DirectCast(File, DownloadFileAsyncExtended)
  511.  
  512.            If Not Downloader.IsBusy Then
  513.                Downloader.ResumeAsync()
  514.            End If
  515.  
  516.        Catch ex As Exception
  517.            MessageBox.Show(ex.Message, Nothing, MessageBoxButtons.OK, MessageBoxIcon.Error)
  518.  
  519.        End Try
  520.  
  521.    End Sub
  522.  
  523. End Class
  524.  
  525. '// This class is passed as a parameter to the GetResponse Callback,
  526. '// so we can work with the data in the Response Callback.
  527. Public Class HttpWebRequestState
  528.  
  529.    Private _LocalFilePath As String
  530.    Private _Request As HttpWebRequest
  531.    Private _ResumeDownload As Boolean
  532.    Private _userToken As Object
  533.  
  534.    Public Sub New(ByVal LocalFilePath As String, ByVal Request As HttpWebRequest, ByVal ResumeDownload As Boolean, ByVal userToken As Object)
  535.        _LocalFilePath = LocalFilePath
  536.        _Request = Request
  537.        _ResumeDownload = ResumeDownload
  538.        _userToken = userToken
  539.    End Sub
  540.  
  541.    Public ReadOnly Property LocalFilePath() As String
  542.        Get
  543.            Return _LocalFilePath
  544.        End Get
  545.    End Property
  546.  
  547.    Public ReadOnly Property Request() As HttpWebRequest
  548.        Get
  549.            Return _Request
  550.        End Get
  551.    End Property
  552.  
  553.    Public ReadOnly Property ResumeDownload() As Boolean
  554.        Get
  555.            Return _ResumeDownload
  556.        End Get
  557.    End Property
  558.  
  559.    Public ReadOnly Property userToken() As Object
  560.        Get
  561.            Return _userToken
  562.        End Get
  563.    End Property
  564.  
  565. End Class
  566.  
  567.  
  568. '// This is the data returned to the user for each download in the
  569. '// Progress Changed event, so you can update controls with the progress.
  570. Public Class FileDownloadProgressChangedEventArgs
  571.    Inherits EventArgs
  572.  
  573.    Private _BytesReceived As Long
  574.    Private _TotalBytesToReceive As Long
  575.    Private _DownloadTime As Long
  576.    Private _DownloadSpeed As Long
  577.    Private _userToken As Object
  578.  
  579.    Public Sub New(ByVal BytesReceived As Long, ByVal TotalBytesToReceive As Long, ByVal DownloadTime As Long, ByVal DownloadSpeed As Long, ByVal userToken As Object)
  580.        _BytesReceived = BytesReceived
  581.        _TotalBytesToReceive = TotalBytesToReceive
  582.        _DownloadTime = DownloadTime
  583.        _DownloadSpeed = DownloadSpeed
  584.        _userToken = userToken
  585.    End Sub
  586.  
  587.    Public ReadOnly Property BytesReceived() As Long
  588.        Get
  589.            Return _BytesReceived
  590.        End Get
  591.    End Property
  592.  
  593.    Public ReadOnly Property TotalBytesToReceive() As Long
  594.        Get
  595.            Return _TotalBytesToReceive
  596.        End Get
  597.    End Property
  598.  
  599.    Public ReadOnly Property ProgressPercentage() As Long
  600.        Get
  601.            If _TotalBytesToReceive > 0 Then
  602.                Return Math.Ceiling((_BytesReceived / _TotalBytesToReceive) * 100)
  603.            Else
  604.                Return -1
  605.            End If
  606.        End Get
  607.    End Property
  608.  
  609.    Public ReadOnly Property DownloadTimeSeconds() As Long
  610.        Get
  611.            Return _DownloadTime
  612.        End Get
  613.    End Property
  614.  
  615.    Public ReadOnly Property RemainingTimeSeconds() As Long
  616.        Get
  617.            If DownloadSpeedBytesPerSec > 0 Then
  618.                Return Math.Ceiling((_TotalBytesToReceive - _BytesReceived) / DownloadSpeedBytesPerSec)
  619.            Else
  620.                Return 0
  621.            End If
  622.        End Get
  623.    End Property
  624.  
  625.    Public ReadOnly Property DownloadSpeedBytesPerSec() As Long
  626.        Get
  627.            Return _DownloadSpeed
  628.        End Get
  629.    End Property
  630.  
  631.    Public ReadOnly Property userToken() As Object
  632.        Get
  633.            Return _userToken
  634.        End Get
  635.    End Property
  636.  
  637. End Class
  638.  
  639.  
  640. '// This is the data returned to the user for each download in the
  641. '// Download Completed event, so you can update controls with the result.
  642. Public Class FileDownloadCompletedEventArgs
  643.    Inherits EventArgs
  644.  
  645.    Private _ErrorMessage As Exception
  646.    Private _Cancelled As Boolean
  647.    Private _userToken As Object
  648.  
  649.    Public Sub New(ByVal ErrorMessage As Exception, ByVal Cancelled As Boolean, ByVal userToken As Object)
  650.        _ErrorMessage = ErrorMessage
  651.        _Cancelled = Cancelled
  652.        _userToken = userToken
  653.    End Sub
  654.  
  655.    Public ReadOnly Property ErrorMessage() As Exception
  656.        Get
  657.            Return _ErrorMessage
  658.        End Get
  659.    End Property
  660.  
  661.    Public ReadOnly Property Cancelled() As Boolean
  662.        Get
  663.            Return _Cancelled
  664.        End Get
  665.    End Property
  666.  
  667.    Public ReadOnly Property userToken() As Object
  668.        Get
  669.            Return _userToken
  670.        End Get
  671.    End Property
  672.  
  673. End Class
  674.  
  675. #End Region


Y aquí una Class para entender su funcionamiento.
(Copiar y pegar la class y compilar)




Código
  1. Public Class Form1
  2.  
  3.    ' // Instance a new Downlaoder Class
  4.    Private WithEvents Downloader As New DownloadFileAsyncExtended
  5.  
  6.    ' // create a listview to update.
  7.    Private lv As New ListView With {.View = View.Details, .Dock = DockStyle.Fill}
  8.  
  9.    ' // create a listview item to update.
  10.    Private lvi As New ListViewItem
  11.  
  12.    '// Set an url file to downloads.
  13.    Dim url As String = "http://msft.digitalrivercontent.net/win/X17-58857.iso"
  14.  
  15.    Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
  16.  
  17.        ' Add columns to listview.
  18.        lv.Columns.AddRange({New ColumnHeader With {.Text = "Filename"}, _
  19.                             New ColumnHeader With {.Text = "Size"}, _
  20.                             New ColumnHeader With {.Text = "Status"}, _
  21.                             New ColumnHeader With {.Text = "Completed"}, _
  22.                             New ColumnHeader With {.Text = "Progress"}, _
  23.                             New ColumnHeader With {.Text = "Speed"}, _
  24.                             New ColumnHeader With {.Text = "Time Elapsed"}, _
  25.                             New ColumnHeader With {.Text = "Time Left"} _
  26.                           })
  27.  
  28.        ' Add subitems to listview item.
  29.        lvi.SubItems.AddRange({"Filename", "Size", "Status", "Completed", "Progress", "Speed", "Time Elapsed", "Time Left"})
  30.  
  31.        ' Add a Object tag to the listview item,
  32.        ' so later we can reffer to this download to pause/resume or cancel it.
  33.        lvi.Tag = Downloader
  34.  
  35.        ' Add the Listview control into the UI.
  36.        Me.Controls.Add(lv)
  37.        ' Add the Listview item into the Listview.
  38.        lv.Items.Add(lvi)
  39.  
  40.        ' Set Application simultaneous internet downloads limit.
  41.        Net.ServicePointManager.DefaultConnectionLimit = 5
  42.  
  43.        '// IMPORTANT !!
  44.        '// If you don't add this line, then all events are raised on a separate thread,
  45.        '// and you will get cross-thread errors when accessing the Listview,
  46.        '// or other controls directly in the raised events.
  47.        Downloader.SynchronizingObject = Me
  48.  
  49.        '// Update frequency.
  50.        '// A value higher than 500 ms will prevent the DownloadProgressChanged event,
  51.        '// from firing continuously and hogging CPU when updating the controls.
  52.        '// If you download small files that could be downloaded within a second,
  53.        '// then set it to "NoDelay" or the progress might not be visible.
  54.        Downloader.ProgressUpdateFrequency = DownloadFileAsyncExtended.UpdateFrequency.MilliSeconds_500
  55.  
  56.        '// The method to actually download a file. The "userToken" parameter can,
  57.        '// for example be a control you wish to update in the DownloadProgressChanged,
  58.        '// and DownloadCompleted events. It is a ListViewItem in this example.
  59.        Downloader.DowloadFileAsync(url, "C:\Downloaded file.iso", lvi)
  60.  
  61.    End Sub
  62.  
  63.  
  64.    '// This event allows you to show the download progress to the user.
  65.    '
  66.    ' e.BytesReceived = Bytes received so far.
  67.    ' e.DownloadSpeedBytesPerSec = Download speed in bytes per second.
  68.    ' e.DownloadTimeSeconds = Download time in seconds so far.
  69.    ' e.ProgressPercentage = Percentage of the file downloaded.
  70.    ' e.RemainingTimeSeconds = Remaining download time in seconds.
  71.    ' e.TotalBytesToReceive = Total size of the file that is being downloaded.
  72.    ' e.userToken = Usually the control(s) you wish to update.
  73.    Private Sub DownloadProgressChanged(ByVal sender As Object, ByVal e As FileDownloadProgressChangedEventArgs) _
  74.    Handles Downloader.DownloadProgressChanged
  75.  
  76.        ' Get the ListViewItem we passed as "userToken" parameter, so we can update it.
  77.        Dim lvi As ListViewItem = DirectCast(e.userToken, ListViewItem)
  78.  
  79.        ' Update the ListView item subitems.
  80.        lvi.SubItems(0).Text = url
  81.        lvi.SubItems(1).Text = String.Format("{0:#,#} KB", (e.TotalBytesToReceive / 1024))
  82.        lvi.SubItems(2).Text = "Downloading"
  83.        lvi.SubItems(3).Text = String.Format("{0:#,#} KB", (e.BytesReceived / 1024))
  84.        lvi.SubItems(4).Text = e.ProgressPercentage & "%"
  85.        lvi.SubItems(5).Text = (e.DownloadSpeedBytesPerSec \ 1024).ToString & " kB/s"
  86.        lvi.SubItems(6).Text = String.Format("{0}:{1}:{2}", _
  87.                               (e.DownloadTimeSeconds \ 3600).ToString("00"), _
  88.                               ((e.DownloadTimeSeconds Mod 3600) \ 60).ToString("00"), _
  89.                               (e.DownloadTimeSeconds Mod 60).ToString("00"))
  90.        lvi.SubItems(7).Text = String.Format("{0}:{1}:{2}", _
  91.                               (e.RemainingTimeSeconds \ 3600).ToString("00"), _
  92.                               ((e.RemainingTimeSeconds Mod 3600) \ 60).ToString("00"), _
  93.                               (e.RemainingTimeSeconds Mod 60).ToString("00"))
  94.  
  95.    End Sub
  96.  
  97.  
  98.    '// This event lets you know when the download is complete.
  99.    '// The download finished successfully, the user cancelled the download or there was an error.
  100.    Private Sub DownloadCompleted(ByVal sender As Object, ByVal e As FileDownloadCompletedEventArgs) _
  101.    Handles Downloader.DownloadCompleted
  102.  
  103.        ' Get the ListViewItem we passed as userToken parameter, so we can update it.
  104.        Dim lvi As ListViewItem = DirectCast(e.userToken, ListViewItem)
  105.  
  106.        If e.ErrorMessage IsNot Nothing Then ' Was there an error.
  107.  
  108.            lvi.SubItems(2).Text = "Error: " & e.ErrorMessage.Message.ToString
  109.  
  110.            ' Set an Error ImageKey.
  111.            ' lvi.ImageKey = "Error"
  112.  
  113.        ElseIf e.Cancelled Then ' The user cancelled the download.
  114.  
  115.            lvi.SubItems(2).Text = "Paused"
  116.  
  117.            ' Set a Paused ImageKey.
  118.            ' lvi.ImageKey = "Paused"
  119.  
  120.        Else ' Download was successful.
  121.  
  122.            lvi.SubItems(2).Text = "Finished"
  123.  
  124.            ' Set a Finished ImageKey.
  125.            ' lvi.ImageKey = "Finished"
  126.  
  127.        End If
  128.  
  129.        ' Set Tag to Nothing in order to remove the wClient class instance,
  130.        ' so this way we know we can't resume the download.
  131.        lvi.Tag = Nothing
  132.  
  133.    End Sub
  134.  
  135.    ' Private Sub Button_Resume_Click(sender As Object, e As EventArgs) Handles Button_Resume.Click
  136.    '// To Resume a file:
  137.    ' Download_Helper.Resume_Download(lvi.Tag)
  138.    'End Sub
  139.  
  140.    'Private Sub Button_Pause_Click(sender As Object, e As EventArgs) Handles Button_Pause.Click
  141.    '// To pause or cancel a file:
  142.    ' Download_Helper.PauseCancel_Download(lvi.Tag)
  143.    'End Sub
  144.  
  145. End Class
8113  Foros Generales / Foro Libre / Re: Cuentanos tu mejor chiste!! en: 21 Octubre 2013, 12:26 pm
Esto no es un chiste textual pero me ha hecho mucha gracia xDDD

 (Fox): Hey... pssst pssst...


8114  Programación / Scripting / Re: (Solucionado) [Batch] Randomizar lineas en un txt? en: 21 Octubre 2013, 11:22 am
Hola

Estás equivocado, todos los archivos (todos, no los 5 primeros) se escriben de forma ordenada en el archivo Playlist.tmp, pero añadiéndole un número aleatorio a la izquierda, de esta manera:

Código:
70341602815107;C:\archivo1
48242686216352;C:\archivo2
65562921929452;C:\archivo3
240062826615990;C:\archivo4
11032263219974;C:\archivo5
etc...

Luego la lista se ordena de menor a mayor según los números aleatorios, consiguiende así un shuffle, los nombres de la derecha quedan desordenados:

Código:
11032263219974;C:\archivo5
240062826615990;C:\archivo4
48242686216352;C:\archivo2
65562921929452;C:\archivo3
70341602815107;C:\archivo1
etc...

Y por último se eliminan los números, y se toman los primeros 5 archivos de la lista:

Código:
C:\archivo5
C:\archivo4
C:\archivo2
C:\archivo3
C:\archivo1

Nunca tendrán el mismo orden, ni serán siempre los mismos archivos.

PD: He vuelto a probar el código por si acaso, pero no, no llevas razón, nunca obtengo los mismos archivos.

Si le has hecho alguna modificación al código original deberías postearla para buscar y corregir el error.

Saludos!
8115  Programación / .NET (C#, VB.NET, ASP) / [C#] [VB.NET] Enums con valores duplicados en: 21 Octubre 2013, 11:03 am
A ver, tengo un pequeño lio mental con el método [Enum].Parse, en el cual, según nos cuenta el MSDN, se le puede pasar un parámetro de IgnoreCase:

Citar
Parse(Type, String, Boolean)

Bien, esto en un principio para mi no tiene lógica alguna, teniendo en cuenta que en VB.NET no se puede escribir una enumeración con nombres duplicados de esta manera:

Código
  1. Private Enum Test
  2.    A
  3.    a
  4. End Enum

Pero según he leido, en C# si que es totálmente válido ese tipo de Enums, y entonces esto ya comienza a tener algo de sentido.

El caso es que según me han comentado también sería posible compilar ese tipo de enumeraciones en VB.NET, pero no me han especificado de que manera se podría hacer,
Aunque yo no estoy nada interesado en crear una Enum con valores duplicados la verdad, pero si esto es así de cierto entonces podría significar que las Enums internas del Framework podrían contener nombres de valores "duplicados"?

...en VB.NET, supongamos que hemos escrito una función genérica para parsear un valor de una Enum:
Código
  1. Private Function Enum_Parser(Of T)(Value As Object) As T
  2.  
  3.    Try
  4.        Return [Enum].Parse(GetType(T), Value, True)
  5.  
  6.    Catch ex As ArgumentException
  7.        Throw New Exception("Value not found")
  8.  
  9.    Catch ex As Exception
  10.        Throw New Exception(String.Format("{0}: {1}}", ex.Message, ex.StackTrace))
  11.  
  12.    End Try
  13.  
  14. End Function

La pregunta es, ¿existe algún riesgo de que la función devuelva un falso positivo?.

O en otras palabras, ¿alguna de las Enums del Framework contiene valores que se diferencian en el StringCase pudiendo dar así un falso positivo?

También me atrevería a preguntar porque alguien sería tan estúpido de poner nombres duplicados en una Enum... pero bueno, imagino que habrá razones válidas y quizás no serán tan estúpidas como pienso.
8116  Informática / Software / Re: Desempaquetar DLC en: 21 Octubre 2013, 07:30 am
Mirando por Google puedes encontrar unpackers para DLC's de Steam de juegos específicos, pero ningún unpacker universal, así que imagino que para cada juego debe ser distinto, de todas formas, no lo sé.

Saludos!
8117  Foros Generales / Foro Libre / Re: Trabajitos en: 20 Octubre 2013, 21:02 pm
(...) freelancer.com yo no lo recomiendo para nada.  (...)

Si quieres buscar algo puedes visitar los enlaces (...) http://foro.elhacker.net/dudas_generales/cual_es_la_mejor_forma_de_ganar_dinero_en_internet_en_la_actualidad-t394849.15.html

Es una buena recomendación para todos!

No se si lo ha comentado alguien ya, pero también se puede ganar dinero por la cantidad de visitas de Youtube.

Saludos!
8118  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets) en: 20 Octubre 2013, 20:03 pm
· Seleccionar items en un Listbox sin que el Listbox salte a la posición del nuevo item seleccionado.

Código
  1. #Region " [ListBox] Select item without jump "
  2.  
  3.    ' [ListBox] Select item without jump
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' Select_Item_Without_Jump(ListBox1, 50, ListBoxItemSelected.Select)
  10.    '
  11.    ' For x As Integer = 0 To ListBox1.Items.Count - 1
  12.    '    Select_Item_Without_Jump(ListBox1, x, ListBoxItemSelected.Select)
  13.    ' Next
  14.  
  15.    Public Enum ListBoxItemSelected
  16.        [Select] = 1
  17.        [Unselect] = 0
  18.    End Enum
  19.  
  20.    Public Shared Sub Select_Item_Without_Jump(lb As ListBox, index As Integer, selected As ListBoxItemSelected)
  21.        Dim i As Integer = lb.TopIndex ' Store the selected item index
  22.        lb.BeginUpdate() ' Disable drawing on control
  23.        lb.SetSelected(index, selected) ' Select the item
  24.        lb.TopIndex = i ' Jump to the previous selected item
  25.        lb.EndUpdate() ' Eenable drawing
  26.    End Sub
  27.  
  28. #End Region





· Desactivar/Activar el Dibujado (Drawing) en un control

Código
  1. #Region " Enable-Disable Drawing on Control"
  2.  
  3.    ' Enable-Disable Drawing on Control
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' To disable drawing:
  10.    ' Control_Drawing(ListBox1, DrawingEnabled.Disable)
  11.    '  
  12.    ' To enable drawing:
  13.    ' Control_Drawing(ListBox1, DrawingEnabled.Enable)
  14.  
  15.    <System.Runtime.InteropServices.DllImport("user32.dll", _
  16.    EntryPoint:="LockWindowUpdate", SetLastError:=True, CharSet:=System.Runtime.InteropServices.CharSet.Auto)> _
  17.    Public Shared Function LockWindow(Handle As IntPtr) As IntPtr
  18.    End Function
  19.  
  20.    Private Enum DrawingEnabled
  21.        Enable
  22.        Disable
  23.    End Enum
  24.  
  25.    Private Sub Control_Drawing(ByVal ctrl As Control, ByVal DrawingEnabled As DrawingEnabled)
  26.  
  27.        Select Case DrawingEnabled
  28.  
  29.            Case DrawingEnabled.Enable
  30.                LockWindow(ctrl.Handle)
  31.                LockWindow(IntPtr.Zero)
  32.  
  33.  
  34.            Case DrawingEnabled.Disable
  35.                LockWindow(ctrl.Handle)
  36.  
  37.        End Select
  38.  
  39.    End Sub
  40.  
  41. #End Region
8119  Programación / Programación General / Re: ¿Cual es mas complejo los idiomas o lenguajes de programaciòn? en: 20 Octubre 2013, 17:33 pm
-> Indian Programmers vs. American Programmers: Whose Code Is Best?

Los indios no son los mejores en todos los aspectos de la programación.

Saludos!
8120  Sistemas Operativos / Windows / Re: Microsoft muestra el esperado botón de Inicio de Windows 8.1 en un nuevo anuncio en: 19 Octubre 2013, 18:24 pm
Me encanta el criterio de " no me gusta a mi y generalizo y digo que es una ***** " . Llevo un par de años (casi 3) con Windows 8 y cada vez que tengo que usar el menu de Windows 7 me parece mucho peor. Y en Windows 8.1 las mejoras son sustanciales.

De acuerdo, está claro que tenemos gustos diferentes como consumidores del producto, pero no me puedes negar, desde cualquier punto de perspectiva, que añadir un botón de inicio sólamente para que el usuario pueda elegir LAS MISMAS opciones que ese usuario puede encontrar moviendo el ratón hacia una esquina del PC o pulsando una combinaciónd e teclas... como "nueva y esperada" caracteristica de Windows ...¿es una basura, o no lo es?, creo que no generalizo en ningún aspecto.

Yo de verdad no le encuentro ninguna lógica a que Microsoft no quiera satisfacer a sus consumidores con un clásico botón de inicio en Windows 8, Microsoft en su día puso como excusa que la mayoría de los usuarios no usaban el botón de inicio... y bueno, me imagino que algún topo infiltrado de Apple fue el que redactó esas estadísticas, porque de verdad, no tiene lógica alguna.

Y en mi opinión Microsoft ahora ha encontrado un punto debil del que se quiere aprovechar, de  la ignorancia de todos aquellos usuarios inexpertos que lean la noticia de que "el botón de inicio vuelve en Windows 8.1" como una táctica de marketing para vender más productos, pero cuando ese usuario vea que en realidad no es un botón de inicio lo que le han metido... pues se va a quedar con cara de tonto, y con 200 € menos en el bolsillo.

Saludos!
Páginas: 1 ... 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 [812] 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 ... 1253
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines