|
8051
|
Programación / Scripting / Re: [b]Retos python ... u otro lenguaje de scripting....[/b]
|
en: 11 Noviembre 2013, 04:45 am
|
De esto ya había una sección abierta, has preguntado si sigue activa o si se tiene intención de seguir? La verdad es que yo también estoy interesado, pues es una buena forma de practicar. El ultimo registro de temas como este es de junio del 2012 ...  Aquél post está con chincheta, por algo será, no importa que el último reto sea del año pasado, que la gente no haya querido aportar no significa que la zona de retos haya dejado de existir. Es más, mientras haya gente que se dedique a crear nuevos recopilatorios de retos y/o rankings por su cuenta (como este), jamás se podrá llevar a cabo una estructura ni una zona de retos con suficiente sensatez, pues este post con el paso dle tiempo habría quedado en el olvido como todos los demás, por ese motivo se creó un post con chincheta, para permanecer y no crear decenas de posts sobre la misma temática. Siento decirtelo, @Fran2013, pero deberías haber preguntado como ya te han dicho, el foro es libre, pero preguntar es lo mínimo que podrías haber hecho símplemente por respeto hacia las iniciativas de las demás personas. He estado ausente unos dias y me encuentro con esto. Siento ser un aguafiestas chavales, quizás alguno me vaya a ver como una especie de monstruo por esto pero voy a tener que imponer una nueva norma en las normas ya impuestas del subforo de Scripting para que no se publiquen más rankings de retos existiendo ya una sección totálmente dedicada por y para los retos. (La próxima vez fijarse un poco más los temas con chinchetas, o preguntar) Imagino que muchos os agradecerán la iniciativa y la participación, sobretodo yo, de verdad, gracias, pero esta no ha sido la mejor manera @Fran2013. Aquí pueden leer las nuevas normas del foro de Scripting: http://foro.elhacker.net/scripting/normas_del_tablon_leer_antes_de_postear-t201567.0.html;msg957615#msg957615 Para todos los interesados, la zona de retos sigue abierta para todos aquellos que quieran participar y contribuir, solo tienen que hacerlo, considero que la estructura del juego es muy sencilla.Espero que no dejeis de contribuir con vuestros aportes y vuestros retos, podeis crear posts con retos, porsupuesto, pero sólamente un post por reto y yo me encargaré de añadirlo a los retos de Scripting, ...no plagieis una recopilación de retos con un ranking, eso ya existe y ya forma parte del foro. Y porfavor, al publicar un reto en solitario, hacerlo siguiendo las reglas de participación del siguiente hilo, que para eso fue creado por un servidor: http://foro.elhacker.net/scripting/zona_de_retos_scripting-t360782.0.html Cierro el tema, cualquier cosa me la pueden comentar por mensaje privado. Saludos!
|
|
|
8052
|
Programación / Scripting / Re: Pequeños Proyectos Python...
|
en: 11 Noviembre 2013, 03:12 am
|
Creo este tema para que se propongan pequeños proyectos en python... ¿Que hay que no se haya inventado ya?  Algún WebSpider para alguna página en concreto no estaría nada mal... siempre me han gustado, este tipo de proyectos suelen estar infravalorados (o al menos eso pienso, depende que tipo de página sea quizás solo lo usen 4 gatos, si haces uno relacionado con Facebook quien sabe...) pero la verdad es que son muy útiles y ahorran mucho tiempo, aquí tienes un muy buen ejemplo en Python con GUI por el compañero @ 0x5d (aunque no es un código muy extenso, según lo que intuyo por la sintaxis y los keywords solo hace una única petición a la url y parsea el source de la respuesta): http://foro.elhacker.net/scripting/codigopyqt4_iconfinder_jaavier_0x5d-t401819.0.htmlPD: Python no es lo mio, que tengas suerte!
|
|
|
8053
|
Programación / Scripting / Re: Batch Regedit [En que fallo?]
|
en: 11 Noviembre 2013, 02:53 am
|
@Sonco Primero de nada, porfavor, no sigas abusando de las letras en colores, es una norma del foro. Lo que has marcado con un circulo rojo en la imagen, es la representación decimal del valor hexadecimal, y tu estás intentando usar un valor hexadecimal, No hay ningún problema en especificarle el valor hexadecimal al comando, pero estás usando incorréctamente la sintaxis, tienes que especificar el valor hexadecimal de esta manera: reg add "HKCU\Software\Microsoft\Command Processor" /v DefaultColor /t reg_dword /d "0x1e" /f
Y también, si lo prefieres, puedes usar la representación decimal: reg add "HKCU\Software\Microsoft\Command Processor" /v DefaultColor /t reg_dword /d "30" /f
Saludos.
|
|
|
8054
|
Programación / Scripting / Re: Duda
|
en: 11 Noviembre 2013, 02:39 am
|
No se toleran los títulos de tipo "ayuda", "duda", "wtf", etc, etc, etc... Además, tu duda habría sido mejor posteada en el subforo de desarrollo web. Porfavor, leer las reglas. -> foro.elhacker.net/reglasI.A.1.a. Formato.
El título de los mensajes debe ser descriptivo con acuerdo al contenido. No son descriptivos asuntos que sólo piden ayuda o hacen referencia a la temática general del tablón en los que son escritos. Los mensajes deben ser legibles y fácilmente entendibles, esto incluye... Tema cerrado.
|
|
|
8055
|
Programación / Scripting / Re: Modificacion de archivos de texto (ini)
|
en: 11 Noviembre 2013, 02:32 am
|
@krizalidk Se te puede dar una solución adaptada al problema si respondes a las siguientes preguntas: 1. ¿El número de la linea siempre es el mismo, o la posición de la IP puede cambiar a otra linea? 2. ¿Solo hay una IP en el archivo INI? 3. ¿Lalinea de la IP está escrita de esta manera?: NombreDelValor=xxx.xxx.xxx.xxx ¿...O de esta otra manera como has dicho en un principio?: Saludos.
|
|
|
8056
|
Programación / Scripting / Re: Comparar parte de una IP en bash
|
en: 11 Noviembre 2013, 02:19 am
|
Por si acaso, te muestro el RegEx, no me cuesta nada  ^\d{1,3}\.\d{1,3}\.\d{1,3}\. PD: La saqué en 10 segundos con una aplicación que desarrollé para diseñar expresiones regulares (según la sintaxis del motor RegEx de .NET), si necesitas la aplicación para futuras ocasiones solo dímelo por MP. Saludos
|
|
|
8057
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets)
|
en: 11 Noviembre 2013, 01:44 am
|
Un pequeño hook para capturar los mensajes del menú de edición del menú contextual (por defecto) de un Textbox (las opciones de copiar, pegar, cortar, y eliminar). En un post anterior posteé la forma de capturarl dichos mensajes heredando el Textbox, pero este código es diferente, no depende de ningun control, se puede usar como otra Class cualquiera para capturar los mensajes en cualquier textbox (menos los textbox de Krypton y otros...) sin necesidad de heredar el control. PD: El código no es del todo de mi propiedad, me han ayudado un poquito. #Region " Capture Windows ContextMenu Edit Options " ' [ Capture Windows ContextMenu Edit Options ] ' ' Examples : ' ' Public Class Form1 ' ' Private WithEvents EditMenu As New EditMenuHook ' ' Protected Overrides Sub OnLoad(e As EventArgs) ' MyBase.OnLoad(e) ' ' Capture the EditMenu Messages for TextBox1 and TextBox2 ' EditMenuHook.Controls = {TextBox1, TextBox2} ' ' Enable the Hook ' EditMenuHook.Enable(True) ' End Sub ' ' Protected Overrides Sub OnClosed(e As EventArgs) ' ' Disable the Hook ' EditMenuHook.Enable(False) ' MyBase.OnClosed(e) ' End Sub ' ' Private Sub TextBox_OnTextCommand(sender As Object, e As EditMenuHook.TextCommandEventArgs) _ ' Handles EditMenu.OnCopy, EditMenu.OnCut, EditMenu.OnPaste, EditMenu.OnDelete ' ' MessageBox.Show(String.Format("Control:{0} Message:{1}", sender.name, e.Command.ToString)) ' ' End Sub ' ' End Class Imports System.Runtime.InteropServices Friend Class EditMenuHook <DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall)> _ Public Overloads Shared Function SetWindowsHookEx _ (ByVal idHook As Integer, ByVal HookProc As CallBack, ByVal hInstance As IntPtr, ByVal wParam As Integer) As Integer End Function <DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall)> _ Public Overloads Shared Function CallNextHookEx _ (ByVal idHook As Integer, ByVal nCode As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer End Function <DllImport("User32.dll", CharSet:=CharSet.Auto, CallingConvention:=CallingConvention.StdCall)> _ Public Overloads Shared Function UnhookWindowsHookEx _ (ByVal idHook As Integer) As Boolean End Function Public Enum TextCommandMessage WM_CUT = &H300 WM_COPY = &H301 WM_PASTE = &H302 WM_DELETE = &H303 End Enum Public Structure CWPSTRUCT Public lParam As IntPtr Public wParam As IntPtr Public message As UInt32 Public hWnd As IntPtr End Structure Public Delegate Function CallBack( _ ByVal nCode As Integer, _ ByVal wParam As IntPtr, _ ByVal lParam As IntPtr) As Integer Private Shared WithEvents CopyOrCut_Timer As New Timer _ With {.Interval = 50, .Enabled = False} ' The Control to monitor and report the TextCommand Messages. Public Shared Controls As Control() = Nothing Public Shared MessagesEnabled As Boolean = True Private Shared CopyMessageEnabled As Boolean = True Shared hHook As Integer = 0 Private Shared cwp As CWPSTRUCT Private Const WH_CALLWNDPROC = 4 'Keep the reference so that the delegate is not garbage collected. Private Shared hookproc As CallBack Public Class TextCommandEventArgs Inherits EventArgs Public Property Command As TextCommandMessage End Class Shared Event OnCut(sender As Object, e As TextCommandEventArgs) Shared Event OnCopy(sender As Object, e As TextCommandEventArgs) Shared Event OnPaste(sender As Object, e As TextCommandEventArgs) Shared Event OnDelete(sender As Object, e As TextCommandEventArgs) Friend Shared Sub Enable(enable As Boolean) If hHook = 0 AndAlso enable = True Then hookproc = AddressOf EditCommandHook hHook = SetWindowsHookEx(WH_CALLWNDPROC, _ hookproc, _ IntPtr.Zero, _ AppDomain.GetCurrentThreadId()) If hHook.Equals(0) Then MsgBox("SetWindowsHookEx Failed") Return End If ElseIf hHook <> 0 AndAlso enable = False Then Dim ret As Boolean = UnhookWindowsHookEx(hHook) If ret.Equals(False) Then MsgBox("UnhookWindowsHookEx Failed") Return Else hHook = 0 End If End If End Sub Private Shared Function EditCommandHook(ByVal nCode As Integer, _ ByVal wParam As IntPtr, _ ByVal lParam As IntPtr) As Integer If nCode < 0 Then Return CallNextHookEx(hHook, nCode, wParam, lParam) End If cwp = DirectCast(Marshal.PtrToStructure(lParam, GetType(CWPSTRUCT)), CWPSTRUCT) For Each ctrl As Control In Controls If cwp.hWnd = ctrl.Handle Then Select Case cwp.message Case TextCommandMessage.WM_CUT CopyMessageEnabled = False RaiseEvent OnCut(ctrl, New TextCommandEventArgs() _ With {.Command = TextCommandMessage.WM_CUT}) Case TextCommandMessage.WM_COPY If CopyMessageEnabled Then RaiseEvent OnCopy(ctrl, New TextCommandEventArgs() _ With {.Command = TextCommandMessage.WM_COPY}) Else CopyMessageEnabled = True End If Case TextCommandMessage.WM_PASTE RaiseEvent OnPaste(ctrl, New TextCommandEventArgs() _ With {.Command = TextCommandMessage.WM_PASTE}) Case TextCommandMessage.WM_DELETE RaiseEvent OnDelete(ctrl, New TextCommandEventArgs() _ With {.Command = TextCommandMessage.WM_DELETE}) End Select End If Next Return CallNextHookEx(hHook, nCode, wParam, lParam) End Function End Class #End Region
|
|
|
8058
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets)
|
en: 11 Noviembre 2013, 01:40 am
|
Una versión mejorada de mi ayudante para la aplicación mp3val... mejoré lo que pude el código y le añadi algunos eventos esenciales... Un ejemplo de uso: Public Class Form1 Private WithEvents _mp3val As New mp3val _ With {.mp3val_location = "C:\windows\system32\mp3val.exe", .CheckFileExist = True} Private Sub Test() Handles MyBase.Shown MsgBox(_mp3val.Is_Avaliable()) ' Checks if mp3gain executable is avaliable. MsgBox(_mp3val.Get_Tags(New IO.FileInfo("C:\File.mp3"))) ' Return the TagTypes of an MP3 file. _mp3val.Analyze("C:\File.mp3") ' Analyzes an MP3 file. _mp3val.Fix("C:\File.mp3") ' Fix an MP3 file. End Sub ' mp3val [Started] Private Sub mp3val_Started(ByVal sender As Process, ByVal e As mp3val.StartedEventArgs) _ Handles _mp3val.Started Dim sb As New System.Text.StringBuilder sb.AppendLine(String.Format("Started an ""{0}"" operation", e.Operation.ToString)) sb. AppendLine(String. Format("Input file is: ""{0}""", e. File)) sb.AppendLine(String.Format("mp3val process PID is: ""{0}""", CStr(sender.Id))) MessageBox.Show(sb.ToString, "mp3val", MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub ' mp3val [Exited] Private Sub mp3val_Exited(ByVal sender As Process, ByVal e As mp3val.ExitedEventArgs) _ Handles _mp3val.Exited Dim sb As New System.Text.StringBuilder sb.AppendLine(String.Format("Finished an ""{1}"" operation in file ""{2}""{0}", Environment.NewLine, e.Operation.ToString, sb.AppendLine(String.Format("File information:{0}{1}{0}", Environment.NewLine, e.Info)) sb.AppendLine("Warnings found:") If e.Warnings.Count Then For Each wrn As String In e.Warnings sb.AppendLine(wrn) Next wrn Else sb.AppendLine("Any" & Environment.NewLine) End If sb.AppendLine("Errors found:") If e.Errors.Count Then For Each err As String In e. Errors Else sb.AppendLine("Any" & Environment.NewLine) End If If e.Operation = mp3val.Operation.Fix Then sb.AppendLine(String.Format("File was fixed?: {0}", e.FileIsFixed)) End If MessageBox.Show(sb.ToString, "mp3val", MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub End Class
El ayudante: ' [ mp3val Helper ] ' ' // By Elektro H@cker ' ' Instructions: ' 1. Add the "mp3val.exe" into the directory project. #Region " mp3val Helper " Public Class mp3val : Implements IDisposable #Region " CommandLine parametter legend " ' -f | try to fix errors ' -nb | delete .bak file ' -t | keep file timestamp #End Region #Region " Variables, Properties, Enums " ''' <summary> ''' Gets or sets the mp3val executable path. ''' </summary> Public Property mp3val_location As String = ".\mp3val.exe" ''' <summary> ''' Indicates if should check that the MP3 file exist before realize an operation. ''' If True, an exception will be launched if file does not exist. ''' </summary> Public Property CheckFileExist As Boolean = False ''' <summary> ''' Stores the process StandardOutput. ''' </summary> Private StandardOutput As String = String.Empty ''' <summary> ''' Stores the process StandardError. ''' </summary> Private StandardError As String = String.Empty ''' <summary> ''' Stores some information about the file. ''' </summary> Private Info As String = String.Empty ''' <summary> ''' Stores all the warnings of the file. ''' </summary> Private Warnings As New List(Of String) ''' <summary> ''' Stores all the errors of the file. ''' </summary> Private Errors As New List(Of String) ''' <summary> ''' Stores the tags of the file. ''' </summary> Private Tags As String = String.Empty ''' <summary> ''' Gets some information about the file. ''' </summary> Private Info_RegEx As New System.Text.RegularExpressions.Regex("INFO:.*:\s(.*)", System.Text.RegularExpressions.RegexOptions.Multiline) ''' <summary> ''' Gets all the warning occurences. ''' </summary> Private Warning_RegEx As New System.Text.RegularExpressions.Regex("WARNING:.*:\s(.*)", System.Text.RegularExpressions.RegexOptions.Multiline) ''' <summary> ''' Gets a value indicating if the file was fixed or not. ''' </summary> Private Fixed_RegEx As New System.Text.RegularExpressions.Regex("^FIXED:", System.Text.RegularExpressions.RegexOptions.Multiline) ''' <summary> ''' mp3val Process ''' </summary> Private p As Process = New Process With {.StartInfo = New ProcessStartInfo With { .CreateNoWindow = True, .UseShellExecute = False, .RedirectStandardError = True, .RedirectStandardOutput = True _ } } ''' <summary> ''' Stores the StartedEventArgs Arguments. ''' </summary> Private StartedArgs As New StartedEventArgs ''' <summary> ''' Stores the ExitedEventArgs Arguments. ''' </summary> Private ExitedArgs As New ExitedEventArgs ''' <summary> ''' MP3Val Type Of Operation. ''' </summary> Public Enum Operation As Short Analyze = 0 Fix = 1 Get_Tags = 2 End Enum #End Region #Region " Events " ''' <summary> ''' Event raised when the process has started. ''' </summary> Public Event Started As EventHandler(Of StartedEventArgs) Public Class StartedEventArgs : Inherits EventArgs ''' <summary> ''' Gets the file that was passed as argument to the process. ''' </summary> Public Property File As String ''' <summary> ''' Gets the type of operation to realize. ''' </summary> Public Property Operation As Operation End Class ''' <summary> ''' Event raised when the process has exited. ''' </summary> Public Event Exited As EventHandler(Of ExitedEventArgs) Public Class ExitedEventArgs : Inherits EventArgs ''' <summary> ''' Gets the file that was passed as argument to the process. ''' </summary> Public Property File As String ''' <summary> ''' Gets the type of operation to realize. ''' </summary> Public Property Operation As Operation ''' <summary> ''' Gets some information about the file. ''' </summary> Public Property Info As String ''' <summary> ''' Gets the warnings found. ''' </summary> Public Property Warnings As New List(Of String) ''' <summary> ''' Gets the errors found. ''' </summary> Public Property Errors As New List(Of String) ''' <summary> ''' Gets a value indicating if file was fixed. ''' This is only usefull when doing a Fix operation. ''' </summary> Public Property FileIsFixed As Boolean End Class #End Region #Region " MP3Val Procedures " ''' <summary> ''' Checks if mp3val process is avaliable. ''' </summary> Public Function Is_Avaliable() As Boolean Return IO. File. Exists(Me. mp3val_location) End Function ''' <summary> ''' Analyzes a file and returns the problems (if any). ''' </summary> Public Function Analyze(ByVal MP3_File As String) As List(Of String) Return Run_MP3VAL(MP3_File, Operation.Analyze, ControlChars.Quote & MP3_File & ControlChars.Quote) End Function ''' <summary> ''' Analyzes a file and returns the problems (if any). ''' </summary> Public Function Analyze(ByVal MP3_File As IO.FileInfo) As List(Of String) Return Run_MP3VAL(MP3_File.FullName, Operation.Analyze, ControlChars.Quote & MP3_File.FullName & ControlChars.Quote) End Function ''' <summary> ''' Try to Fix/Rebuild problems of a file, ''' and returns a value indicating if file was fixed or not. ''' </summary> Public Function Fix(ByVal MP3_File As String, Optional ByVal Delete_Backup_File As Boolean = False, Optional ByVal Preserve_Datestamp As Boolean = True) As Boolean Return Run_MP3VAL(MP3_File, Operation.Fix, String.Format("-f {0} {1} ""{2}""", If(Delete_Backup_File, "-nb", ""), If(Preserve_Datestamp, "-t", ""), MP3_File)) End Function ''' <summary> ''' Try to Fix/Rebuild problems of a file, ''' and returns a value indicating if file was fixed or not. ''' </summary> Public Function Fix(ByVal MP3_File As IO.FileInfo, Optional ByVal Delete_Backup_File As Boolean = False, Optional ByVal Preserve_Datestamp As Boolean = True) As Boolean Return Run_MP3VAL(MP3_File.FullName, Operation.Fix, String.Format("-f {0} {1} ""{2}""", If(Delete_Backup_File, "-nb", ""), If(Preserve_Datestamp, "-t", ""), MP3_File.FullName)) End Function ''' <summary> ''' Return the metadata ID types of a file. ''' </summary> Public Function Get_Tags(ByVal MP3_File As String) As String Return Run_MP3VAL(MP3_File, Operation.Get_Tags, ControlChars.Quote & MP3_File & ControlChars.Quote) End Function ''' <summary> ''' Return the metadata ID types of a file. ''' </summary> Public Function Get_Tags(ByVal MP3_File As IO.FileInfo) As String Return Run_MP3VAL(MP3_File.FullName, Operation.Get_Tags, ControlChars.Quote & MP3_File.FullName & ControlChars.Quote) End Function #End Region #Region " Run Procedure " ''' <summary> ''' Runs mp3val process. ''' </summary> Private Function Run_MP3VAL(ByVal MP3_File As String, ByVal operation As Operation, ByVal arguments As String) As Object If Me.CheckFileExist Then FileExist(MP3_File) End If With p.StartInfo .FileName = Me.mp3val_location .Arguments = arguments End With Warnings.Clear() : Errors.Clear() p.Start() RaiseEvent_Started(MP3_File, operation) p.WaitForExit() StandardError = p.StandardError.ReadToEnd StandardOutput = p.StandardOutput.ReadToEnd Info = Info_RegEx.Match(StandardOutput).Groups(1).Value.Trim For Each m As System.Text.RegularExpressions.Match In Warning_RegEx.Matches(StandardOutput) Warnings.Add(m.Groups(1).Value) Next m For Each e As String In StandardError.Split(Environment.NewLine) If Not String.IsNullOrEmpty(e.Trim) Then Errors.Add(e) End If Next e Select Case operation Case mp3val.Operation.Analyze RaiseEvent_Exited(MP3_File, operation.Analyze, Info, Warnings.Distinct.ToList, Errors, False) Return Warnings.Concat(Errors).Distinct.ToList Case mp3val.Operation.Fix RaiseEvent_Exited(MP3_File, operation.Fix, Info, Warnings.Distinct.ToList, Errors, Fixed_RegEx.IsMatch(StandardOutput)) Return Fixed_RegEx.IsMatch(StandardOutput) Case mp3val.Operation.Get_Tags RaiseEvent_Exited(MP3_File, operation.Get_Tags, Info, Warnings.Distinct.ToList, Errors, False) If Not String.IsNullOrEmpty(Info) Then Tags = Info.Split(",")(1).Trim If Tags = "no tags" Then Return "No tags" Else Return Tags.Substring(1).Replace("+", ", ") End If Else Return "Can't examine tag type." End If Case Else Return Nothing End Select End Function #End Region #Region " Miscellaneous preocedures " ''' <summary> ''' Checks if a file exists. ''' </summary> Private Sub FileExist (ByVal File As String) Throw New Exception (String. Format("File doesn't exist: ""{0}""", File)) ' MessageBox.Show(String.Format("File doesn't exist: ""{0}""", File), "mp3val", MessageBoxButtons.OK, MessageBoxIcon.Error) End If End Sub ''' <summary> ''' Raises the Event Started ''' </summary> Private Sub RaiseEvent_Started (ByVal File As String, ByVal Operation As Operation) With StartedArgs .Operation = Operation End With RaiseEvent Started(p, StartedArgs) End Sub ''' <summary> ''' Raises the Event Exited ''' </summary> Private Sub RaiseEvent_Exited (ByVal File As String, ByVal Operation As Operation, ByVal Info As String, ByVal Warnings As List(Of String), ByVal Errors As List(Of String), ByVal IsFixed As Boolean) With ExitedArgs .Operation = Operation .Info = Info .Warnings = Warnings .Errors = Errors .FileIsFixed = IsFixed End With RaiseEvent Exited(p, ExitedArgs) End Sub #End Region #Region " IDisposable " ''' <summary> ''' Disposes the objects generated by this instance. ''' </summary> Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overridable Sub Dispose(IsDisposing As Boolean) Static IsBusy As Boolean ' To detect redundant calls. If Not IsBusy AndAlso IsDisposing Then p.Dispose() End If IsBusy = True End Sub #End Region End Class #End Region
|
|
|
8059
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets)
|
en: 11 Noviembre 2013, 01:36 am
|
Una versión mejorada de mi ayudante para la aplicación CoreConverter... mejoré lo que pude el código y le añadi algunos eventos esenciales... Un ejemplo de uso: Public Class Form1 Private WithEvents _converter As New CoreConverter _ With {.CoreConverter_location = "C:\windows\system32\coreconverter.exe", .CheckFileExist = True} Private Sub Test() Handles MyBase.Shown ' Checks if CoreConverter executable is avaliable. MsgBox(_converter.Is_Avaliable()) ' Convert a file to MP3 _converter.Convert_To_MP3("C:\Input.wav", "C:\Output.mp3", CoreConverter.Lame_Bitrate.kbps_320, CoreConverter.Lame_Bitrate_Mode.cbr, CoreConverter.Lame_Profile.SLOW, CoreConverter.Lame_Quality.Q0_Maximum, CoreConverter.Lame_Khz.Same_As_Source, CoreConverter.Lame_Channels.auto, { CoreConverter.DSP_Effects.Delete_Output_File_on_Error, CoreConverter.DSP_Effects.Recycle_Source_File_After_Conversion }, False, CoreConverter.Priority.normal) ' Convert a file to WAV _converter.Convert_To_WAV_Uncompressed("C:\Input.mp3", "C:\Output.wav", _ CoreConverter.WAV_Uncompressed_Bitrate.Same_As_Source, _ CoreConverter.WAV_Uncompressed_Khz.Same_As_Source, _ CoreConverter.WAV_Uncompressed_Channels.Same_As_Source, , False) ' Convert a file to WMA _converter.Convert_To_WMA("C:\Input.mp3", "C:\Output.wma", _ CoreConverter.WMA_9_2_BitRates.Kbps_128, _ CoreConverter.WMA_9_2_Khz.Khz_44100, _ CoreConverter.WMA_9_2_Channels.stereo, , False) End Sub ' CoreConverter [Started] Private Sub CoreConverter_Started(ByVal sender As Process, ByVal e As CoreConverter.StartedEventArgs) _ Handles _converter.Started ProgressBar1.Value = ProgressBar1.Minimum Dim sb As New System.Text.StringBuilder sb.AppendLine(String.Format("Started an ""{0}"" operation", e.Operation.ToString)) sb. AppendLine(String. Format("Input file is: ""{0}""", e. File)) sb.AppendLine(String.Format("CoreConverter process PID is: ""{0}""", CStr(sender.Id))) MessageBox.Show(sb.ToString, "CoreConverter", MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub ' CoreConverter [Exited] Private Sub CoreConverter_Exited(ByVal sender As Process, ByVal e As CoreConverter.ExitedEventArgs) _ Handles _converter.Exited Dim sb As New System.Text.StringBuilder sb.AppendLine(String.Format("Finished an ""{0}"" operation", e.Operation.ToString)) sb. AppendLine(String. Format("Input file is: ""{0}""", e. File)) sb.AppendLine(String.Format("CoreConverter process PID is: {0}", CStr(sender.Id))) If Not String.IsNullOrEmpty(e.InfoMessage) Then sb.AppendLine(String.Format("Operation Information: {0}", e.InfoMessage)) End If If Not String.IsNullOrEmpty(e.ErrorMessage) Then sb.AppendLine(String.Format("Error Information: {0}", e.ErrorMessage)) End If If Not String.IsNullOrEmpty(e.ElapsedTime) Then sb.AppendLine(String.Format("Total elapsed time: {0}", e.ElapsedTime)) End If MessageBox.Show(sb.ToString, "CoreConverter", MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub ' CoreConverter [Progress] Sub CoreConverter_Progress(sender As Process, e As CoreConverter.ProgressEventArgs) _ Handles _converter.Progress ProgressBar1.Value = e.Percent End Sub End Class
El ayudante: ' [ CoreConverter Helper ] ' ' // By Elektro H@cker ' ' Instructions:
' 1. Add the "CoreConverter.exe" into the project, ' together with dbPoweramp Effects and Codec folders. #Region " CoreConverter Helper " Public Class CoreConverter : Implements IDisposable #Region " Variables, Properties, Enumerations " ''' <summary> ''' Gets or sets CoreConverter.exe executable path. ''' </summary> Public Property CoreConverter_location As String = ".\CoreConverter.exe" ''' <summary> ''' Indicates if should check that the file exist before realize an operation. ''' If True, an exception would be launched if file does not exist. ''' </summary> Public Property CheckFileExist As Boolean = False ''' <summary> ''' Stores the converter process progress ''' </summary> Private CurrentProgress As Integer = 0 ''' <summary> ''' Stores an information message of the realized operation (if any). ''' </summary> Private InfoMessage As String = Nothing ''' <summary> ''' Stores an error message of the realized operation (if any). ''' </summary> Private ErrorMessage As String = Nothing ''' <summary> ''' Stores the next converter process output character. ''' </summary> Private OutputCharacter As Char = Nothing ''' <summary> ''' Stores the DSP Effects formatted string. ''' </summary> Private Effects As String = Nothing ''' <summary> ''' Stores the total elapsed time of conversion. ''' </summary> Private ElapsedTime As String = Nothing ''' <summary> ''' Stores additional information about the conversion. ''' </summary> Private ExtraInfo() As String = Nothing ''' <summary> ''' Stores the StartedEventArgs Arguments. ''' </summary> Private StartedArgs As New StartedEventArgs ''' <summary> ''' Stores the ExitedEventArgs Arguments. ''' </summary> Private ExitedArgs As New ExitedEventArgs ''' <summary> ''' Stores the ProgressEventArgs Arguments. ''' </summary> Private ProgressArgs As New ProgressEventArgs ''' <summary> ''' CoreConverter Type Of Operation. ''' </summary> Public Enum Operation MP3_Conversion = 0 WAV_Conversion = 1 WMA_Conversion = 2 End Enum ''' <summary> ''' Priority level of CoreConverter process. ''' </summary> Public Enum Priority idle low normal high End Enum ''' <summary> ''' DSP Effects. ''' </summary> Public Enum DSP_Effects Delete_Output_File_on_Error ' Delete failed conversion (not deletes source file). Delete_Source_File_After_Conversion ' Delete source file after conversion. Recycle_Source_File_After_Conversion ' Send source file to recycle bin after conversion. Karaoke_Remove_Voice ' Remove voice from file. Karaoke_Remove_Instrument ' Remove instruments from file. Reverse ' Reverse complete audio file. Write_Silence ' Write silence at start of file. End Enum ''' <summary> ''' CoreConverter Process. ''' </summary> Private p As Process = New Process With {.StartInfo = New ProcessStartInfo With { .CreateNoWindow = True, _ .UseShellExecute = False, _ .RedirectStandardError = True, _ .RedirectStandardOutput = True, _ .StandardErrorEncoding = System.Text.Encoding.Unicode, _ .StandardOutputEncoding = System.Text.Encoding.Unicode } } #End Region #Region " Events " ''' <summary> ''' Event raised when CoreConverter operation progress changes. ''' </summary> Public Event Progress As EventHandler(Of ProgressEventArgs) Public Class ProgressEventArgs : Inherits EventArgs ''' <summary> ''' Gets the CoreConverter operation percent done. ''' </summary> Public Property Percent As Integer End Class ''' <summary> ''' Event raised when CoreConverter process has started. ''' </summary> Public Event Started As EventHandler(Of StartedEventArgs) Public Class StartedEventArgs : Inherits EventArgs ''' <summary> ''' Gets the file that was passed as argument to the process. ''' </summary> Public Property File As String ''' <summary> ''' Gets the type of operation to realize. ''' </summary> Public Property Operation As Operation End Class ''' <summary> ''' Event raised when CoreConverter process has exited. ''' </summary> Public Event Exited As EventHandler(Of ExitedEventArgs) Public Class ExitedEventArgs : Inherits EventArgs ''' <summary> ''' Gets the file that was passed as argument to the process. ''' </summary> Public Property File As String ''' <summary> ''' Gets the type of operation to realize. ''' </summary> Public Property Operation As Operation ''' <summary> ''' Gets an information message of the realized operation. ''' </summary> Public Property InfoMessage As String ''' <summary> ''' Gets an error message of the realized operation (if any). ''' </summary> Public Property ErrorMessage As String ''' <summary> ''' Gets the total elapsed time of the operation. ''' </summary> Public Property ElapsedTime As String End Class #End Region #Region " Codec Enumerations " #Region " MP3 Lame " Public Enum Lame_Bitrate kbps_8 = 8 kbps_16 = 16 kbps_24 = 24 kbps_32 = 32 kbps_40 = 40 kbps_48 = 48 kbps_56 = 56 kbps_64 = 64 kbps_80 = 80 kbps_96 = 96 kbps_112 = 112 kbps_128 = 128 kbps_144 = 144 kbps_160 = 160 kbps_192 = 192 kbps_224 = 224 kbps_256 = 256 kbps_320 = 320 End Enum Public Enum Lame_Bitrate_Mode cbr abr End Enum Public Enum Lame_Profile NORMAL FAST SLOW End Enum Public Enum Lame_Quality Q0_Maximum = 0 Q1 = 1 Q2 = 2 Q3 = 3 Q4 = 4 Q5 = 5 Q6 = 6 Q7 = 7 Q8 = 8 Q9_Minimum = 9 End Enum Public Enum Lame_Khz Same_As_Source khz_8000 = 8000 khz_11025 = 11025 khz_12000 = 12000 khz_16000 = 16000 khz_22050 = 22050 khz_24000 = 24000 khz_32000 = 32000 khz_44100 = 44100 khz_48000 = 48000 End Enum Public Enum Lame_Channels auto mono stereo joint_stereo forced_joint_stereo forced_stereo dual_channels End Enum #End Region #Region " WAV Uncompressed " Public Enum WAV_Uncompressed_Bitrate Same_As_Source bits_8 = 8 bits_16 = 16 bits_24 = 24 bits_32 = 32 End Enum Public Enum WAV_Uncompressed_Khz Same_As_Source khz_8000 = 8000 khz_11025 = 11025 khz_12000 = 12000 khz_16000 = 16000 khz_22050 = 22050 khz_24000 = 24000 khz_32000 = 32000 khz_44100 = 44100 khz_48000 = 48000 khz_96000 = 96000 khz_192000 = 192000 End Enum Public Enum WAV_Uncompressed_Channels Same_As_Source Channels_1_Mono = 1 Channels_2_Stereo = 2 Channels_3 = 3 Channels_4_Quadraphonic = 4 Channels_5_Surround = 5 Channels_6_Surround_DVD = 6 Channels_7 = 7 Channels_8_Theater = 8 End Enum #End Region #Region " WMA 9.2 " Public Enum WMA_9_2_BitRates Kbps_12 = 12 Kbps_16 = 16 Kbps_20 = 20 Kbps_22 = 22 Kbps_24 = 24 Kbps_32 = 32 Kbps_40 = 40 Kbps_48 = 48 Kbps_64 = 64 Kbps_80 = 80 Kbps_96 = 96 Kbps_128 = 128 Kbps_160 = 160 Kbps_192 = 192 Kbps_256 = 256 Kbps_320 = 320 End Enum Enum WMA_9_2_Khz Khz_8000 = 8 Khz_16000 = 16 Khz_22050 = 22 Khz_32000 = 32 Khz_44100 = 44 Khz_48000 = 48 End Enum Enum WMA_9_2_Channels mono stereo End Enum #End Region #End Region #Region " CoreConverter Procedures " ''' <summary> ''' Checks if CoreConverter process is avaliable. ''' </summary> Public Function Is_Avaliable() As Boolean Return IO. File. Exists(Me. CoreConverter_location) End Function ''' <summary> ''' Converts a file to MP3 using Lame codec. ''' </summary> Public Sub Convert_To_MP3(ByVal In_File As String, _ ByVal Out_File As String, _ ByVal Bitrate As Lame_Bitrate, _ ByVal Bitrate_Mode As Lame_Bitrate_Mode, _ ByVal Encoding_Profile As Lame_Profile, _ ByVal Quality As Lame_Quality, _ ByVal Khz As Lame_Khz, _ ByVal Channels As Lame_Channels, _ Optional ByVal DSP_Effects() As DSP_Effects = Nothing, _ Optional ByVal Update_Tag As Boolean = True, _ Optional ByVal Priority As Priority = Priority.normal, _ Optional ByVal Processor As Short = 1) Get_Effects(DSP_Effects) Set_Main_Arguments("mp3 (Lame)", In_File, Out_File, If(Not Update_Tag, "-noidtag", ""), Effects, Priority.ToString, Processor.ToString) p.StartInfo.Arguments &= _ String.Format("-b {0} --{1} -encoding=""{2}"" -freq=""{3}"" -channels=""{4}"" --noreplaygain --extracli=""-q {5}""", _ CInt(Bitrate), _ Bitrate_Mode.ToString, _ Encoding_Profile.ToString, _ If(Khz = Lame_Khz.Same_As_Source, "", CInt(Khz)), _ If(Channels = Lame_Channels.auto, "", Channels), _ CInt(Quality)) Run_CoreConverter(In_File, Operation.MP3_Conversion) End Sub ''' <summary> ''' Converts a file to Uncompressed WAV. ''' </summary> Public Sub Convert_To_WAV_Uncompressed(ByVal In_File As String, _ ByVal Out_File As String, _ ByVal Bitrate As WAV_Uncompressed_Bitrate, _ ByVal Khz As WAV_Uncompressed_Khz, _ ByVal Channels As WAV_Uncompressed_Channels, _ Optional ByVal DSP_Effects() As DSP_Effects = Nothing, _ Optional ByVal Update_Tag As Boolean = True, _ Optional ByVal Priority As Priority = Priority.normal, _ Optional ByVal Processor As Short = 1) Get_Effects(DSP_Effects) Set_Main_Arguments("Wave", In_File, Out_File, If(Not Update_Tag, "-noidtag", ""), Effects, Priority.ToString, Processor.ToString) p.StartInfo.Arguments &= _ String.Format("-compression=""PCM"" -bits=""{0}"" -freq=""{1}"" -channels=""{2}""", _ If(Bitrate = WAV_Uncompressed_Bitrate.Same_As_Source, "", CInt(Bitrate)), _ If(Khz = WAV_Uncompressed_Khz.Same_As_Source, "", CInt(Khz)), _ If(Channels = WAV_Uncompressed_Channels.Same_As_Source, "", CInt(Channels))) Run_CoreConverter(In_File, Operation.WAV_Conversion) End Sub ''' <summary> ''' Converts a file to WMA v9.2 ''' </summary> Public Sub Convert_To_WMA(ByVal In_File As String, _ ByVal Out_File As String, _ ByVal Bitrate As WMA_9_2_BitRates, _ ByVal Khz As WMA_9_2_Khz, _ ByVal Channels As WMA_9_2_Channels, _ Optional ByVal DSP_Effects() As DSP_Effects = Nothing, _ Optional ByVal Update_Tag As Boolean = True, _ Optional ByVal Priority As Priority = Priority.normal, _ Optional ByVal Processor As Short = 1) Get_Effects(DSP_Effects) Set_Main_Arguments("Windows Media Audio 10", In_File, Out_File, If(Not Update_Tag, "-noidtag", ""), Effects, Priority.ToString, Processor.ToString) p.StartInfo.Arguments &= _ String.Format("-codec=""Windows Media Audio 9.2"" -settings=""{0} kbps, {1} kHz, {2} CBR""", CInt(Bitrate), _ CInt(Khz), _ Channels.ToString) Run_CoreConverter(In_File, Operation.WMA_Conversion) End Sub #End Region #Region " Run Procedure " ''' <summary> ''' Runs a specific operation of CoreConverter. ''' </summary> Private Sub Run_CoreConverter (ByVal file As String, ByVal operation As Operation) If Me.CheckFileExist Then End If CurrentProgress = 0 p.StartInfo.FileName = Me.CoreConverter_location p.Start() With StartedArgs .Operation = operation End With RaiseEvent Started(p, StartedArgs) While Not p.HasExited OutputCharacter = ChrW(p.StandardOutput.Read) If OutputCharacter = "*" Then ProgressArgs.Percent = CInt((Threading.Interlocked.Increment(CurrentProgress) / 59) * 100) RaiseEvent Progress(p, ProgressArgs) End If If CurrentProgress = 59 Then ' I store the last line(s) because it has interesting information: ' Example Output: "Conversion completed in 30 seconds x44 realtime encoding" InfoMessage = p.StandardOutput.ReadToEnd.Trim End If End While ' Stores the Error Message (If any) ErrorMessage = p.StandardError.ReadToEnd.Trim If Not String.IsNullOrEmpty(InfoMessage) Then ' Stores additional information ExtraInfo = InfoMessage.Split(Environment.NewLine) Select Case ExtraInfo.Length Case 1 ElapsedTime = ExtraInfo.Last.Split()(3) & " " & ExtraInfo.Last.Split()(4) ' Example: "50,2 seconds" Case 2 ElapsedTime = ExtraInfo.Last.Split()(4) & " " & ExtraInfo.Last.Split()(5) ' Example: "50,2 seconds" Case Is < 1, Is > 2 Throw New Exception("Unmanaged Process Output Length") End Select End If With ExitedArgs .Operation = operation .InfoMessage = InfoMessage .ErrorMessage = ErrorMessage .ElapsedTime = ElapsedTime End With RaiseEvent Exited(p, ExitedArgs) ' CoreConverter.Close() End Sub #End Region #Region " Miscellaneous procedures " ''' <summary> ''' Checks if a file exists. ''' </summary> Private Sub FileExist (ByVal File As String) ' Throw New Exception("File doesn't exist: " & File) MessageBox. Show("File doesn't exist: " & File, "CoreConverter", MessageBoxButtons. OK, MessageBoxIcon. Error) End If End Sub ''' <summary> ''' Sets the static arguments of CoreConverter process. ''' </summary> Private Sub Set_Main_Arguments(ByVal Codec_Name As String, _ ByVal In_File As String, _ ByVal Out_File As String, _ ByVal Update_Tag As String, _ ByVal Effects As String, _ ByVal Priority As String, _ ByVal Processor As String) p.StartInfo.Arguments = _ String.Format("-infile=""{0}"" -outfile=""{1}"" -convert_to=""{2}"" {3} {4} -priority=""{5}"" -processor=""{6}"" ", In_File, Out_File, Codec_Name, Update_Tag, Effects, Priority, Processor) End Sub ''' <summary> ''' Join all DSP Effects and returns a formatted string. ''' </summary> Private Function Get_Effects(ByVal DSP_Effects() As DSP_Effects) As String If DSP_Effects Is Nothing Then Return Nothing Else For Effect As Integer = 0 To DSP_Effects.Length - 1 Effects &= String.Format(" -dspeffect{0}={1}", _ Effect + 1, _ Format_DSP_Effect(DSP_Effects(Effect).ToString)) Next Effect Return Effects End If End Function ''' <summary> ''' Returns a formatted string of a single DSP Effects. ''' </summary> Private Shared Function Format_DSP_Effect(ByVal Effect As String) Select Case Effect Case "Reverse" Return """Reverse""" Case "Delete_Output_File_on_Error" Return """Delete Destination File on Error=""" Case "Recycle_Source_File_After_Conversion" Return """Delete Source File=-recycle""" Case "Delete_Source_File_After_Conversion" Return """Delete Source File=""" Case "Karaoke_Remove_Voice" Return """Karaoke (Voice_ Instrument Removal)=""" Case "Karaoke_Remove_Instrument" Return """Karaoke (Voice_ Instrument Removal)=-i""" Case "Write_Silence" Return """Write Silence=-lengthms={qt}2000{qt}""" ' 2 seconds Case Else Return String.Empty End Select End Function #End Region #Region " IDisposable " ''' <summary> ''' Disposes the objects generated by this instance. ''' </summary> Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overridable Sub Dispose(IsDisposing As Boolean) Static IsBusy As Boolean ' To detect redundant calls. If Not IsBusy AndAlso IsDisposing Then p.Dispose() End If IsBusy = True End Sub #End Region End Class #End Region
|
|
|
8060
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Posteen aquí sus snippets)
|
en: 11 Noviembre 2013, 01:34 am
|
Una versión mejorada de mi ayudante para la aplicación mp3gain... mejoré lo que pude el código y le añadi algunos eventos esenciales... Un ejemplo de uso: Public Class Form1 Private WithEvents _mp3gain As New mp3gain _ With {.mp3gain_location = "C:\windows\system32\mp3gain.exe", .CheckFileExist = True} Private Sub Test() Handles MyBase.Shown ' Checks if mp3gain executable is avaliable. MsgBox(_mp3gain.Is_Avaliable()) ' Checks if file contains APEv2 mp3gain tag MsgBox(_mp3gain.File_Has_MP3Gain_Tag("C:\File.mp3")) ' Set the global volume Gain of file to "89" db (In a scale of "0-100"), ' and preserve the datetime of file. _mp3gain.Set_Gain("C:\File.mp3", 89, True) ' Apply a volume change of +5 db, ' in the curent global volume gain of file. _mp3gain.Apply_Gain("C:\File.mp3", +5) ' Apply a volume change of -5 db, ' in the curent global volume gain of file. _mp3gain.Apply_Gain("C:\File.mp3", -5) ' Apply a volume change of +10 db, ' in the curent volume gain of the Left channel of an Stereo file. _mp3gain.Apply_Channel_Gain("C:\File.mp3", mp3gain.Channel.Left, +10) ' Apply a volume change of -10 db, ' in the curent volume gain of the Right channel of an Stereo file. _mp3gain.Apply_Channel_Gain("C:\File.mp3", mp3gain.Channel.Right, -10) ' Undos all volume gain changes made in file. _mp3gain.Undo_Gain("C:\File.mp3") End Sub ' mp3gain [Started] Private Sub mp3gain_Started(ByVal sender As Process, ByVal e As mp3gain.StartedEventArgs) _ Handles _mp3gain.Started ProgressBar1.Value = ProgressBar1.Minimum Dim sb As New System.Text.StringBuilder sb.AppendLine(String.Format("Started an ""{0}"" operation", e.Operation.ToString)) sb. AppendLine(String. Format("Input file is: ""{0}""", e. File)) sb.AppendLine(String.Format("mp3gain process PID is: ""{0}""", CStr(sender.Id))) MessageBox.Show(sb.ToString, "mp3gain", MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub ' mp3gain [Exited] Private Sub mp3gain_Exited(ByVal sender As Process, ByVal e As mp3gain.ExitedEventArgs) _ Handles _mp3gain.Exited Dim sb As New System.Text.StringBuilder If e.Operation <> mp3gain.Operation.Check_Tag Then sb.AppendLine(String.Format("Finished an ""{0}"" operation", e.Operation.ToString)) sb. AppendLine(String. Format("Input file is: ""{0}""", e. File)) sb.AppendLine(String.Format("mp3gain process PID is: {0}", CStr(sender.Id))) If Not String.IsNullOrEmpty(e.InfoMessage) Then sb.AppendLine(String.Format("Operation Information: {0}", e.InfoMessage)) End If If Not String.IsNullOrEmpty(e.ErrorMessage) Then sb.AppendLine(String.Format("Error Information: {0}", e.ErrorMessage)) End If If e.db <> 0 Then sb.AppendLine(String.Format("Volume gain change: {0}", CStr(e.db))) End If MessageBox.Show(sb.ToString, "mp3gain", MessageBoxButtons.OK, MessageBoxIcon.Information) End If End Sub ' mp3gain [Progress] Sub mp3gain_Progress(sender As Process, e As mp3gain.ProgressEventArgs) _ Handles _mp3gain.Progress ProgressBar1.Value = e.Percent End Sub End Class
El ayudante: ' [ mp3gain Helper ] ' ' // By Elektro H@cker ' ' Instructions: ' 1. Add the "mp3gain.exe" into the project. #region " mp3gain Helper " Public Class mp3gain : Implements IDisposable #Region " CommandLine parametter legend " ' /c - Ignore clipping warning when applying gain. ' /d - Set global gain. ' /e - Skip Album analysis, even if multiple files listed. ' /g - apply gain ' /p - Preserve original file timestamp. ' /r - apply Track gain automatically (all files set to equal loudness) ' /t - Writes modified data to temp file, then deletes original instead of modifying bytes in original file. ' /u - Undo changes made (based on stored APEv2 mp3gain tag info). ' /s c - Check stored APEv2 mp3gain tag info. #End Region #Region " Variables, Properties, Enumerations " ''' <summary> ''' Gets or sets the mp3gain.exe executable path. ''' </summary> Public Property mp3gain_location As String = ".\mp3gain.exe" ''' <summary> ''' Indicates if should check that the file exist before realize an operation. ''' If True, an exception would be launched if file does not exist. ''' </summary> Public Property CheckFileExist As Boolean = False ''' <summary> ''' Sets a Flag to indicate if file has APEv2 mp3gain tag or not. ''' </summary> Private HasTag As Boolean = False ''' <summary> ''' Stores the StandardOutput. ''' </summary> Private Output As String() = Nothing ''' <summary> ''' Stores an information message of the realized operation (if any). ''' </summary> Private InfoMessage As String = String.Empty ''' <summary> ''' Stores an error message of the realized operation (if any). ''' </summary> Private ErrorMessage As String = String.Empty ''' <summary> ''' Stores the volume gain level change applied to file (if any). ''' </summary> Private db As Integer = 0 ''' <summary> ''' Gets some information about the file. ''' </summary> Private db_RegEx As New System.Text.RegularExpressions.Regex("Applying.+change of (.*) to", System.Text.RegularExpressions.RegexOptions.None) ''' <summary> ''' Process to realize an operation, ''' for files that already contains APEv2 mp3gain tag. ''' Also is used to realize a single TagCheck operation. ''' </summary> Private Process_For_Tag As Process = New Process With {.StartInfo = New ProcessStartInfo With { .CreateNoWindow = True, .UseShellExecute = False, .RedirectStandardError = False, .RedirectStandardOutput = True } } ''' <summary> ''' Process to realize an operation, ''' for files that does not contains mp3gain Tag. ''' </summary> Private Process_For_NonTag As Process = New Process With {.StartInfo = New ProcessStartInfo With { .CreateNoWindow = True, .UseShellExecute = False, .RedirectStandardError = True, .RedirectStandardOutput = True } } ''' <summary> ''' Stores the StartedEventArgs Arguments. ''' </summary> Private StartedArgs As New StartedEventArgs ''' <summary> ''' Stores the ExitedEventArgs Arguments. ''' </summary> Private ExitedArgs As New ExitedEventArgs ''' <summary> ''' Stores the ProgressEventArgs Arguments. ''' </summary> Private ProgressArgs As New ProgressEventArgs ''' <summary> ''' File Stereo Channel. ''' </summary> Public Enum Channel As Short Left = 0 ' /l 0 Right = 1 ' /l 1 End Enum ''' <summary> ''' MP3Gain Type Of Operation. ''' </summary> Public Enum Operation Check_Tag = 0 Apply_Gain = 1 Apply_Channel_Gain = 2 Set_Gain = 3 Undo_Gain = 4 End Enum #End Region #Region " Events " ''' <summary> ''' Event raised when the process has started. ''' </summary> Public Event Started As EventHandler(Of StartedEventArgs) Public Class StartedEventArgs : Inherits EventArgs ''' <summary> ''' Gets the file that was passed as argument to the process. ''' </summary> Public Property File As String ''' <summary> ''' Gets the type of operation to realize. ''' </summary> Public Property Operation As Operation End Class ''' <summary> ''' Event raised when the process has exited. ''' </summary> Public Event Exited As EventHandler(Of ExitedEventArgs) Public Class ExitedEventArgs : Inherits EventArgs ''' <summary> ''' Gets the file that was passed as argument to the process. ''' </summary> Public Property File As String ''' <summary> ''' Gets the type of operation to realize. ''' </summary> Public Property Operation As Operation ''' <summary> ''' Gets the information message of the realized operation (if any). ''' </summary> Public Property InfoMessage As String ''' <summary> ''' Gets the error message of the realized operation (if any). ''' </summary> Public Property ErrorMessage As String ''' <summary> ''' Gets the volume gain level change applied to file (if any). ''' </summary> Public Property db As Integer End Class ''' <summary> ''' Event raised when the process progress changes. ''' </summary> Public Event Progress As EventHandler(Of ProgressEventArgs) Public Class ProgressEventArgs : Inherits EventArgs ''' <summary> ''' Gets the process operation percent done. ''' </summary> Public Property Percent As Integer End Class #End Region #Region " MP3Gain Procedures " ''' <summary> ''' Checks if mp3gain.exe process is avaliable. ''' </summary> Public Function Is_Avaliable() As Boolean Return IO. File. Exists(Me. mp3gain_location) End Function ''' <summary> ''' Checks if APEv2 mp3gain tag exists in file. ''' </summary> Public Function File_Has_MP3Gain_Tag(ByVal MP3_File As String) As Boolean Run_MP3Gain(MP3_File, Operation.Check_Tag, String.Format("/s c ""{0}""", MP3_File), True) Return HasTag End Function ''' <summary> ''' Set the global volume gain of file. ''' </summary> Public Sub Set_Gain(ByVal MP3_File As String, ByVal Gain As Integer, Optional ByVal Preserve_Datestamp As Boolean = True) File_Has_MP3Gain_Tag(MP3_File) Run_MP3Gain(MP3_File, Operation.Set_Gain, String.Format("/c /e /r /t {1} /d {2} ""{0}""", MP3_File, If(Preserve_Datestamp, "/p", ""), If(Gain < 0, Gain + 89.0, Gain - 89.0)), False) End Sub ''' <summary> ''' Apply a volume gain change to file. ''' </summary> Public Sub Apply_Gain(ByVal MP3_File As String, ByVal Gain As Integer, Optional ByVal Preserve_Datestamp As Boolean = True) File_Has_MP3Gain_Tag(MP3_File) Run_MP3Gain(MP3_File, Operation.Apply_Gain, String.Format("/c /e /r /t {1} /g {2} ""{0}""", MP3_File, If(Preserve_Datestamp, "/p", ""), Gain), False) End Sub ''' <summary> ''' Apply a volume gain change to file only in left or right channel. ''' Only works for Stereo MP3 files. ''' </summary> Public Sub Apply_Channel_Gain(ByVal MP3_File As String, ByVal Channel As Channel, ByVal Gain As Integer, Optional ByVal Preserve_Datestamp As Boolean = True) File_Has_MP3Gain_Tag(MP3_File) Run_MP3Gain(MP3_File, Operation.Apply_Channel_Gain, String.Format("/c /e /r /l {2} {3} ""{0}""", MP3_File, If(Preserve_Datestamp, "/p", ""), If(Channel = Channel.Left, 0, 1), Gain), False) End Sub ''' <summary> ''' Undos all mp3gain volume changes made in a file, ''' based on stored APEv2 mp3gain tag info. ''' </summary> Public Sub Undo_Gain(ByVal MP3_File As String, Optional ByVal Preserve_Datestamp As Boolean = True) File_Has_MP3Gain_Tag(MP3_File) Run_MP3Gain(MP3_File, Operation.Undo_Gain, String.Format("/c /t {1} /u ""{0}""", MP3_File, If(Preserve_Datestamp, "/p", "")), False) End Sub #End Region #Region " Run Procedures " ''' <summary> ''' Run MP3Gain process. ''' </summary> Private Sub Run_MP3Gain(ByVal MP3_File As String, ByVal operation As Operation, ByVal Parametters As String, ByVal IsCheckTagOperation As Boolean) If Me.CheckFileExist Then FileExist(MP3_File) End If With Process_For_Tag.StartInfo .FileName = Me.mp3gain_location .Arguments = Parametters End With With Process_For_NonTag.StartInfo .FileName = Me.mp3gain_location .Arguments = Parametters End With ' Reset Variables before relaize the operation. InfoMessage = Nothing ErrorMessage = Nothing db = 0 ' Check if file has APEv2 mp3gain tag or not, ' before doing any other operation. If IsCheckTagOperation Then Run_MP3Gain_For_Tag(Process_For_Tag, MP3_File, operation.Check_Tag, True) Exit Sub ' If only would to check the tag then exit from this sub. Else ' Else, continue with the operation (Modify volume gain)... Select Case HasTag Case True Run_MP3Gain_For_Tag(Process_For_Tag, MP3_File, operation, False) Case False Run_MP3Gain_For_NonTag(Process_For_NonTag, MP3_File, operation) End Select ' HasTag End If ' IsCheckTagOperation End Sub ''' <summary> ''' Runs mp3gain for files that already contains APEv2 mp3gain tag. ''' </summary> Private Sub Run_MP3Gain_For_Tag(ByVal p As Process, ByVal MP3_File As String, ByVal operation As Operation, ByVal IsTagCheckOperation As Boolean) p.Start() RaiseEvent_Started(p, MP3_File, operation) p.WaitForExit() If IsTagCheckOperation Then HasTag = CBool(p.StandardOutput.ReadToEnd.Trim.Split(Environment.NewLine).Count - 1) End If ProgressArgs.Percent = 100 RaiseEvent Progress(p, ProgressArgs) SetMessages(p.StandardOutput.ReadToEnd()) RaiseEvent_Exited(p, MP3_File, operation, If(IsTagCheckOperation, "File Has Tag?: " & CStr(HasTag), InfoMessage), ErrorMessage, db) ' p.Close() End Sub ''' <summary> ''' Runs mp3gain for files that doesn't contains APEv2 mp3gain tag. ''' </summary> Private Sub Run_MP3Gain_For_NonTag(ByVal p As Process, ByVal MP3_File As String, ByVal operation As Operation) p.Start() RaiseEvent_Started(p, MP3_File, operation) Do Until p.HasExited Try ProgressArgs.Percent = CInt(p.StandardError.ReadLine.Split("%").First.Trim) If ProgressArgs.Percent < 101 Then RaiseEvent Progress(p, ProgressArgs) End If Catch End Try Loop ProgressArgs.Percent = 100 RaiseEvent Progress(p, ProgressArgs) SetMessages(p.StandardOutput.ReadToEnd()) RaiseEvent_Exited(p, MP3_File, operation, InfoMessage, ErrorMessage, db) ' p.Close() End Sub #End Region #Region " Miscellaneous Procedures " ''' <summary> ''' Checks if a file exists. ''' </summary> Private Sub FileExist (ByVal File As String) Throw New Exception (String. Format("File doesn't exist: ""{0}""", File)) ' MessageBox.Show(String.Format("File doesn't exist: ""{0}""", File), "mp3gain", MessageBoxButtons.OK, MessageBoxIcon.Error) End If End Sub ''' <summary> ''' Raises the Event Started ''' </summary> Private Sub RaiseEvent_Started(ByVal p As Process, ByVal operation As Operation) With StartedArgs .Operation = operation End With RaiseEvent Started(p, StartedArgs) End Sub ''' <summary> ''' Raises the Event Exited ''' </summary> Private Sub RaiseEvent_Exited(ByVal p As Process, ByVal operation As Operation, ByVal InfoMessage As String, ByVal ErrorMessage As String, ByVal db As Integer) With ExitedArgs .Operation = operation .InfoMessage = InfoMessage .ErrorMessage = ErrorMessage .db = db End With RaiseEvent Exited(p, ExitedArgs) End Sub ''' <summary> ''' Sets the InfoMessage, ErrorMessage and db variables. ''' </summary> Private Sub SetMessages(ByVal StandardOutput As String) Output = StandardOutput. Split(Environment.NewLine). Select(Function(line) line.Replace(Environment.NewLine, "").Trim). Where(Function(null) Not String.IsNullOrEmpty(null)).ToArray For Each line In Output Select Case True Case line.StartsWith("No changes") InfoMessage = "No volume gain changes are necessary." Case line.StartsWith("Applying") db = db_RegEx.Match(line).Groups(1).Value If String.IsNullOrEmpty(InfoMessage) Then InfoMessage = line End If Case line.StartsWith("Can't") ErrorMessage = line End Select Next line End Sub #End Region #Region " IDisposable " ''' <summary> ''' Disposes the objects generated by this instance. ''' </summary> Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub Protected Overridable Sub Dispose(IsDisposing As Boolean) Static IsBusy As Boolean ' To detect redundant calls. If Not IsBusy AndAlso IsDisposing Then Process_For_Tag.Dispose() Process_For_NonTag.Dispose() End If IsBusy = True End Sub #End Region End Class #End Region
|
|
|
|
|
|
|