Autor
|
Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) (Leído 527,144 veces)
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.866
|
Un ejemplo de uso muy básico de la librería NCalc ~> http://ncalc.codeplex.com/ Dim MathExpression As String = "(2 + 3) * 2" ' Result: 10 Dim NCalcExpression As New NCalc.Expression(MathExpression) MsgBox(NCalcExpression.Evaluate().ToString)
Una forma de comprobar si un archivo es un ensamblado .NET: ' Usage Examples: ' ' MsgBox(IsNetAssembly("C:\File.exe")) ' MsgBox(IsNetAssembly("C:\File.dll")) ''' <summary> ''' Gets the common language runtime (CLR) version information of the specified file, using the specified buffer. ''' </summary> ''' <param name="filepath">Indicates the filepath of the file to be examined.</param> ''' <param name="buffer">Indicates the buffer allocated for the version information that is returned.</param> ''' <param name="buflen">Indicates the size, in wide characters, of the buffer.</param> ''' <param name="written">Indicates the size, in bytes, of the returned buffer.</param> ''' <returns>System.Int32.</returns> <System.Runtime.InteropServices.DllImport("mscoree.dll", CharSet:=System.Runtime.InteropServices.CharSet.Unicode)> Private Shared Function GetFileVersion( ByVal filepath As String, ByVal buffer As System.Text.StringBuilder, ByVal buflen As Integer, ByRef written As Integer ) As Integer End Function ''' <summary> ''' Determines whether an exe/dll file is an .Net assembly. ''' </summary> ''' <param name="File">Indicates the exe/dll file to check.</param> ''' <returns><c>true</c> if file is an .Net assembly; otherwise, <c>false</c>.</returns> Public Shared Function IsNetAssembly (ByVal [File] As String) As Boolean Dim sb = New System.Text.StringBuilder(256) Dim written As Integer = 0 Dim hr = GetFileVersion ([File], sb, sb. Capacity, written ) Return hr = 0 End Function
Un simple efecto de máquina de escribir: ' *********************************************************************** ' Author : Elektro ' Modified : 03-08-2014 ' *********************************************************************** ' <copyright file="TypeWritter.vb" company="Elektro Studios"> ' Copyright (c) Elektro Studios. All rights reserved. ' </copyright> ' *********************************************************************** #Region " Usage Examples " 'Sub Main() ' Console.WriteLine() ' TypeWritter.WriteLine("[ Typewritter ] - By Elektro") ' TypeWritter.WriteLine() ' TypeWritter.WriteLine() ' TypeWritter.WriteLine("Hola a todos!, les presento este humilde y simple efecto de máquina de escribir") ' TypeWritter.WriteLine() ' TypeWritter.WriteLine("Si os fijais aténtamente, quizás ya habreis notado, que hay pausas realistas, al escribir signos de puntuación...") ' TypeWritter.WriteLine() ' TypeWritter.WriteLine("[+] Podemos establecer la velocidad de escritura, por ejemplo, a 20 ms. :") ' TypeWritter.WriteLine("abcdefghijklmnopqrstuvwxyz", 20) ' TypeWritter.WriteLine() ' TypeWritter.WriteLine("[+] Podemos establecer la velocidad de las pausas, por ejemplo, a 2 seg. :") ' TypeWritter.WriteLine(".,;:", , 2 * 1000) ' TypeWritter.WriteLine() ' TypeWritter.WriteLine("[+] El efecto corre en una tarea asíncrona, por lo que se pueden hacer otras cosas mientras tanto, sin frezzear una GUI, y también podemos cancelar la escritura en cualquier momento, gracias al Token de cancelación.") ' TypeWritter.WriteLine() ' TypeWritter.WriteLine() ' TypeWritter.WriteLine("Esto es todo por ahora.") ' Console.ReadKey() 'End Sub #End Region #Region " TypeWritter " ''' <summary> ''' Simulates text-typying effect like a Typewritter. ''' </summary> Public Class TypeWritter #Region " Properties " ''' <summary> ''' When set to 'True', the running 'Typewritter' task will be cancelled. ''' ( The property is set again to 'False' automatically after a 'Task' is cancelled ) ''' </summary> Public Shared Property RequestCancel As Boolean = False #End Region #Region " Task Objects " ''' <summary> ''' The typewritter asynchronous Task. ''' </summary> Private Shared TypeWritterTask As Threading.Tasks.Task ''' <summary> ''' The typewritter Task Cancellation TokenSource. ''' </summary> Private Shared TypeWritterTaskCTS As New Threading.CancellationTokenSource ''' <summary> ''' The typewritter Task Cancellation Token. ''' </summary> Private Shared TypeWritterTaskCT As Threading.CancellationToken = TypeWritterTaskCTS.Token #End Region #Region " Private Methods " ''' <summary> ''' Writes text simulating a Typewritter effect. ''' </summary> ''' <param name="CancellationToken">Indicates the cancellation token of the Task.</param> ''' <param name="Text">Indicates the text to type.</param> ''' <param name="TypeSpeed">Indicates the typying speed, in ms.</param> ''' <param name="PauseDuration">Indicates the pause duration of the punctuation characters, in ms.</param> Private Shared Sub TypeWritter(ByVal CancellationToken As Threading.CancellationToken, ByVal [Text] As String, ByVal TypeSpeed As Integer, ByVal PauseDuration As Integer) ' If Text is empty then write an empty line... If String.IsNullOrEmpty([Text]) Then ' If not cancellation is already requested then... If Not CancellationToken.IsCancellationRequested Then ' Write an empty line. Console.WriteLine() ' Wait-Speed (empty line). Threading.Thread.Sleep(PauseDuration) End If ' CancellationToken.IsCancellationRequested End If ' String.IsNullOrEmpty([Text]) ' For each Character in Text to type... For Each c As Char In [Text] ' If not cancellation is already requested then... If Not CancellationToken.IsCancellationRequested Then ' Type the character. Console.Write(CStr(c)) ' Type-Wait. Threading.Thread.Sleep(TypeSpeed) If ".,;:".Contains(c) Then ' Pause-Wait. Threading.Thread.Sleep(PauseDuration) End If Else ' want to cancel. ' Exit iteration. Exit For End If ' CancellationToken.IsCancellationRequested Next c ' As Char In [Text] End Sub #End Region #Region " Public Methods " ''' <summary> ''' Writes text simulating a Typewritter effect. ''' </summary> ''' <param name="Text">Indicates the text to type.</param> ''' <param name="TypeSpeed">Indicates the typying speed, in ms.</param> ''' <param name="PauseDuration">Indicates the pause duration of the punctuation characters, in ms.</param> Public Shared Sub Write(ByVal [Text] As String, Optional ByVal TypeSpeed As Integer = 75, Optional ByVal PauseDuration As Integer = 400) ' Run the asynchronous Task. TypeWritterTask = Threading.Tasks. Task.Factory.StartNew(Sub() TypeWritter(TypeWritterTaskCT, [Text], TypeSpeed, PauseDuration) End Sub, TypeWritterTaskCT) ' Until Task is not completed or is not cancelled, do... Do Until TypeWritterTask.IsCompleted OrElse TypeWritterTask.IsCanceled ' If want to cancel then... If RequestCancel Then ' If not cancellation is already requested then... If Not TypeWritterTaskCTS.IsCancellationRequested Then ' Cancel the Task. TypeWritterTaskCTS.Cancel() ' Renew the cancellation token and tokensource. TypeWritterTaskCTS = New Threading.CancellationTokenSource TypeWritterTaskCT = TypeWritterTaskCTS.Token End If ' Reset the cancellation flag var. RequestCancel = False ' Exit iteration. Exit Do End If Loop ' TypeTask.IsCompleted OrElse TypeTask.IsCanceled End Sub ''' <summary> ''' Writes text simulating a Typewritter effect, and adds a break-line at the end. ''' </summary> ''' <param name="Text">Indicates the text to type.</param> ''' <param name="TypeSpeed">Indicates the typying speed, in ms.</param> ''' <param name="PauseDuration">Indicates the pause duration of the punctuation characters, in ms.</param> Public Shared Sub WriteLine(ByVal [Text] As String, Optional ByVal TypeSpeed As Integer = 75, Optional ByVal PauseDuration As Integer = 400) Write([Text], TypeSpeed, PauseDuration) Console.WriteLine() End Sub ''' <summary> ''' Writes an empty line. ''' </summary> ''' <param name="PauseDuration">Indicates the pause duration of the empty line, in ms.</param> Public Shared Sub WriteLine(Optional ByVal PauseDuration As Integer = 750) Write(String.Empty, 1, PauseDuration) End Sub #End Region End Class #End Region
|
|
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.866
|
Unos snippets para imitar las macros "LoByte", "LoWord", "LoDword", etc, usando la Class BitConverter, la cual, aunque necesita hacer más trabajo, me parece una solución mucho mas elegante que las que se pueden encontrar por ahí, e igual de efectiva. ' Get LoByte ' ( By Elektro ) ' ' Usage Examples: ' MsgBox(GetLoByte(1587S)) ' Result: 51 ' ''' <summary> ''' Gets the low-order byte of an 'Int16' value. ''' </summary> ''' <param name="Value">Indicates the 'Int16' value that contains both the LoByte and the HiByte.</param> ''' <returns>The return value is the low-order byte.</returns> Public Shared Function GetLoByte(ByVal value As Short) As Byte Return BitConverter.GetBytes(value).First End Function
' Get HiByte ' ( By Elektro ) ' ' Usage Examples: ' MsgBox(GetHiByte(1587S)) ' Result: 6 ' ''' <summary> ''' Gets the high-order byte of an 'Int16' value. ''' </summary> ''' <param name="Value">Indicates the 'Int16' value that contains both the LoByte and the HiByte.</param> ''' <returns>The return value is the high-order byte.</returns> Public Shared Function GetHiByte(ByVal value As Short) As Byte Return BitConverter.GetBytes(value).Last End Function
' Get LoWord ' ( By Elektro ) ' ' Usage Examples: ' MsgBox(GetLoWord(13959358I)) ' Result: 190S ' ''' <summary> ''' Gets the low-order word of an 'Int32' value. ''' </summary> ''' <param name="Value">Indicates the 'Int32' value that contains both the LoWord and the HiWord.</param> ''' <returns>The return value is the low-order word.</returns> Public Shared Function GetLoWord(ByVal value As Integer) As Short Return BitConverter.ToInt16(BitConverter.GetBytes(value), 0) End Function
' Get HiWord ' ( By Elektro ) ' ' Usage Examples: ' MsgBox(GetHiWord(13959358I)) ' Result: 213S ' ''' <summary> ''' Gets the high-order word of an 'Int32' value. ''' </summary> ''' <param name="Value">Indicates the 'Int32' value that contains both the LoWord and the HiWord.</param> ''' <returns>The return value is the high-order word.</returns> Public Shared Function GetHiWord(ByVal value As Integer) As Short Return BitConverter.ToInt16(BitConverter.GetBytes(value), 2) End Function
' Get LoDword (As Unsigned Integer) ' ( By Elektro ) ' ' Usage Examples: ' MsgBox(GetLoDword(328576329396160UL)) ' Result: 2741317568UI ' ''' <summary> ''' Gets the low-order double word of an 'UInt64' value. ''' </summary> ''' <param name="Value">Indicates the 'UInt64' value that contains both the LoDword and the HiDword.</param> ''' <returns>The return value is the low-order double word.</returns> Public Shared Function GetLoDword(ByVal value As ULong) As UInteger Return BitConverter.ToUInt32(BitConverter.GetBytes(value), 0) End Function
' Get HiDword (As Unsigned Integer) ' ( By Elektro ) ' ' Usage Examples: ' MsgBox(GetHiDword(328576329396160UL)) ' Result: 76502UI ' ''' <summary> ''' Gets the high-order double word of an 'UInt64' value. ''' </summary> ''' <param name="Value">Indicates the 'UInt64' value that contains both the LoDword and the HiDword.</param> ''' <returns>The return value is the high-order double word.</returns> Public Shared Function GetHiDword(ByVal value As ULong) As UInteger Return BitConverter.ToUInt32(BitConverter.GetBytes(value), 4) End Function
' Get LoDword (As Signed Integer) ' ( By Elektro ) ' ' Usage Examples: ' MsgBox(GetLoDword(328576329396160L)) ' Result: -1553649728I ' ''' <summary> ''' Gets the low-order double word of an 'Int64' value. ''' </summary> ''' <param name="Value">Indicates the 'Int64' value that contains both the LoDword and the HiDword.</param> ''' <returns>The return value is the low-order double word.</returns> Public Shared Function GetLoDword(ByVal value As Long) As Integer Return BitConverter.ToInt32(BitConverter.GetBytes(value), 0) End Function
' Get HiDword (As Signed Integer) ' ( By Elektro ) ' ' Usage Examples: ' MsgBox(GetHiDword(328576329396160L)) ' Result: 76502I ' ''' <summary> ''' Gets the high-order double word of an 'Int64' value. ''' </summary> ''' <param name="Value">Indicates the 'Int64' value that contains both the LoDword and the HiDword.</param> ''' <returns>The return value is the high-order double word.</returns> Public Shared Function GetHiDword(ByVal value As Long) As Integer Return BitConverter.ToInt32(BitConverter.GetBytes(value), 4) End Function
' Make Word ' ( By Elektro ) ' ' Usage Examples: ' MsgBox(MakeWord(51S, 6S)) ' Result: 1587S ' ''' <summary> ''' Makes an 'Int16' value from two bytes. ''' </summary> ''' <param name="LoByte">Indicates the low-order byte.</param> ''' <param name="HiByte">Indicates the high-order byte.</param> ''' <returns>The 'Int16' value.</returns> Public Shared Function MakeWord(ByVal LoByte As Byte, ByVal HiByte As Byte) As Short Return BitConverter.ToInt16(New Byte() {LoByte, HiByte}, 0) End Function
' Make Dword ' ( By Elektro ) ' ' Usage Examples: ' MsgBox(MakedWord(190S, 213S)) ' Result: 13959358I ' ''' <summary> ''' Makes an 'Int32' value from two 'Int16' values. ''' </summary> ''' <param name="LoWord">Indicates the low-order word.</param> ''' <param name="HiWord">Indicates the high-order word.</param> ''' <returns>The 'Int32' value.</returns> Public Shared Function MakeDword(ByVal LoWord As Short, ByVal HiWord As Short) As Integer Dim LoBytes As Byte() = BitConverter.GetBytes(LoWord) Dim HiBytes As Byte() = BitConverter.GetBytes(HiWord) Dim Combined As Byte() = LoBytes.Concat(HiBytes).ToArray Return BitConverter.ToInt32(Combined, 0) End Function
' Make Long (From An Unsigned Integer) ' ( By Elektro ) ' ' Usage Examples: ' MsgBox(MakeLong(2741317568UI, 76502UI)) ' Result: 328576329396160UL ' ''' <summary> ''' Makes an 'UInt64' value from two 'UInt32' values. ''' </summary> ''' <param name="LoDword">Indicates the low-order Dword.</param> ''' <param name="HiDword">Indicates the high-order Dword.</param> ''' <returns>The 'UInt64' value.</returns> Public Shared Function MakeLong(ByVal LoDword As UInteger, ByVal HiDword As UInteger) As ULong Dim LoBytes As Byte() = BitConverter.GetBytes(LoDword) Dim HiBytes As Byte() = BitConverter.GetBytes(HiDword) Dim Combined As Byte() = LoBytes.Concat(HiBytes).ToArray Return BitConverter.ToUInt64(Combined, 0) End Function
' Make Long (From a Signed Integer) ' ( By Elektro ) ' ' Usage Examples: ' MsgBox(MakeLong(-1553649728I, 76502I)) ' Result: 328576329396160L ' ''' <summary> ''' Makes an 'Int64' value from two 'Int32' values. ''' </summary> ''' <param name="LoDword">Indicates the low-order Dword.</param> ''' <param name="HiDword">Indicates the high-order Dword.</param> ''' <returns>The 'Int64' value.</returns> Public Shared Function MakeLong(ByVal LoDword As Integer, ByVal HiDword As Integer) As Long Dim LoBytes As Byte() = BitConverter.GetBytes(LoDword) Dim HiBytes As Byte() = BitConverter.GetBytes(HiDword) Dim Combined As Byte() = LoBytes.Concat(HiBytes).ToArray Return BitConverter.ToInt64(Combined, 0) End Function
|
|
« Última modificación: 9 Marzo 2014, 16:34 pm por Eleкtro »
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.866
|
Algunos métodos más sobre bytes. ' Set LoByte ' ( By Elektro ) ' ' Usage Examples: ' MsgBox(SetHiByte(321, 0S)) ' Result: 65S ' ''' <summary> ''' Sets the low-order byte of an 'Int16' value. ''' </summary> ''' <param name="Value">Indicates the 'Int16' value that contains both the LoByte and the HiByte.</param> ''' <param name="NewLoByte">Indicates the new LoByte, a 'Byte' value.</param> ''' <returns>The 'Int16' value containing both the HiByte and the new LoByte.</returns> Private Function SetLoByte(ByVal Value As Short, ByVal NewLoByte As Byte) As Short Dim ValueBytes As Byte() = BitConverter.GetBytes(Value) ValueBytes(0) = NewLoByte Return BitConverter.ToInt16(ValueBytes, 0) End Function
' Set HiByte ' ( By Elektro ) ' ' Usage Examples: ' MsgBox(SetHiByte(65S, 1S)) ' Result: 321S ' ''' <summary> ''' Sets the high-order byte of an 'Int16' value. ''' </summary> ''' <param name="Value">Indicates the 'Int16' value that contains both the LoByte and the HiByte.</param> ''' <param name="NewHiByte">Indicates the new HiByte, a 'Byte' value.</param> ''' <returns>The 'Int16' value containing both the LoByte and the new HiByte.</returns> Private Function SetHiByte(ByVal Value As Short, ByVal NewHiByte As Byte) As Short Dim ValueBytes As Byte() = BitConverter.GetBytes(Value) ValueBytes(1) = NewHiByte Return BitConverter.ToInt16(ValueBytes, 0) End Function
' Set LoWord ' ( By Elektro ) ' ' Usage Examples: ' MsgBox(SetLoWord(13959358I, 6S)) ' Result: 13959174I ' ''' <summary> ''' Sets the low-order word of an 'Int32' value. ''' </summary> ''' <param name="Value">Indicates the 'Int32' value that contains both the LoWord and the HiWord.</param> ''' <param name="NewLoWord">Indicates the new LoWord, an 'Int16' value.</param> ''' <returns>The 'Int32' value containing both the HiWord and the new LoWord.</returns> Private Function SetLoWord(ByVal Value As Integer, ByVal NewLoWord As Short) As Integer Dim ValueBytes As Byte() = BitConverter.GetBytes(Value) Dim LoWordBytes As Byte() = BitConverter.GetBytes(NewLoWord) ValueBytes(0) = LoWordBytes(0) ValueBytes(1) = LoWordBytes(1) Return BitConverter.ToInt32(ValueBytes, 0) End Function
' Set HiWord ' ( By Elektro ) ' ' Usage Examples: ' MsgBox(SetHiWord(13959358I, 25S)) ' Result: 1638590I ' ''' <summary> ''' Sets the high-order word of an 'Int32' value. ''' </summary> ''' <param name="Value">Indicates the 'Int32' value that contains both the LoWord and the HiWord.</param> ''' <param name="NewHiWord">Indicates the new HiWord, an 'Int16' value.</param> ''' <returns>The 'Int32' value containing both the LoWord and the new HiWord.</returns> Private Function SetHiWord(ByVal Value As Integer, ByVal NewHiWord As Short) As Integer Dim ValueBytes As Byte() = BitConverter.GetBytes(Value) Dim HiWordBytes As Byte() = BitConverter.GetBytes(NewHiWord) ValueBytes(2) = HiWordBytes(0) ValueBytes(3) = HiWordBytes(1) Return BitConverter.ToInt32(ValueBytes, 0) End Function
' Set LoDword (From a Signed Integer) ' ( By Elektro ) ' ' Usage Examples: ' MsgBox(SetLoDword(328576329396160L, -1553649828I)) ' Result: 328576329396060L ' ''' <summary> ''' Sets the low-order double word of an 'Int64' value. ''' </summary> ''' <param name="Value">Indicates the 'Int64' value that contains both the LoDword and the HiDword.</param> ''' <param name="NewLoDword">Indicates the new LoDword, an 'Int32' value.</param> ''' <returns>The 'Int64' value containing both the HiDword and the new LoDword.</returns> Private Function SetLoDword(ByVal Value As Long, ByVal NewLoDword As Integer) As Long Dim ValueBytes As Byte() = BitConverter.GetBytes(Value) Dim LoDwordBytes As Byte() = BitConverter.GetBytes(NewLoDword) ValueBytes(0) = LoDwordBytes(0) ValueBytes(1) = LoDwordBytes(1) ValueBytes(2) = LoDwordBytes(2) ValueBytes(3) = LoDwordBytes(3) Return BitConverter.ToInt64(ValueBytes, 0) End Function
' Set HiDword (From a Signed Integer) ' ( By Elektro ) ' ' Usage Examples: ' MsgBox(SetHiDword(328576329396160L, 987654321I)) ' Result: 4241943011189403584L ' ''' <summary> ''' Sets the high-order double word of an 'Int64' value. ''' </summary> ''' <param name="Value">Indicates the 'Int64' value that contains both the LoDword and the HiDword.</param> ''' <param name="NewHiDword">Indicates the new HiDword, an 'Int32' value.</param> ''' <returns>The 'Int64' value containing both the LoDword and the new HiDword.</returns> Private Function SetHiDword(ByVal Value As Long, ByVal NewHiDword As Integer) As Long Dim ValueBytes As Byte() = BitConverter.GetBytes(Value) Dim HiDwordBytes As Byte() = BitConverter.GetBytes(NewHiDword) ValueBytes(4) = HiDwordBytes(0) ValueBytes(5) = HiDwordBytes(1) ValueBytes(6) = HiDwordBytes(2) ValueBytes(7) = HiDwordBytes(3) Return BitConverter.ToInt64(ValueBytes, 0) End Function
' Set LoDword (From an Unsigned Integer) ' ( By Elektro ) ' ' Usage Examples: ' MsgBox(SetLoDword(328576329396160L, 123456789UI)) ' Result: 328573711535381L ' ''' <summary> ''' Sets the low-order double word of an 'Int64' value. ''' </summary> ''' <param name="Value">Indicates the 'Int64' value that contains both the LoDword and the HiDword.</param> ''' <param name="NewLoDword">Indicates the new LoDword, an 'UInt32' value.</param> ''' <returns>The 'Int64' value containing both the HiDword and the new LoDword.</returns> Private Function SetLoDword(ByVal Value As Long, ByVal NewLoDword As UInteger) As Long Dim ValueBytes As Byte() = BitConverter.GetBytes(Value) Dim LoDwordBytes As Byte() = BitConverter.GetBytes(NewLoDword) ValueBytes(0) = LoDwordBytes(0) ValueBytes(1) = LoDwordBytes(1) ValueBytes(2) = LoDwordBytes(2) ValueBytes(3) = LoDwordBytes(3) Return BitConverter.ToInt64(ValueBytes, 0) End Function
' Set HiDword (From an Unsigned Integer) ' ( By Elektro ) ' ' Usage Examples: ' MsgBox(SetHiDword(328576329396160L, 987654321UI)) ' Result: 4241943011189403584L ' ''' <summary> ''' Sets the high-order double word of an 'Int64' value. ''' </summary> ''' <param name="Value">Indicates the 'Int64' value that contains both the LoDword and the HiDword.</param> ''' <param name="NewHiDword">Indicates the new HiDword, an 'UInt32' value.</param> ''' <returns>The 'Int64' value containing both the LoDword and the new HiDword.</returns> Private Function SetHiDword(ByVal Value As Long, ByVal NewHiDword As UInteger) As Long Dim ValueBytes As Byte() = BitConverter.GetBytes(Value) Dim HiDwordBytes As Byte() = BitConverter.GetBytes(NewHiDword) ValueBytes(4) = HiDwordBytes(0) ValueBytes(5) = HiDwordBytes(1) ValueBytes(6) = HiDwordBytes(2) ValueBytes(7) = HiDwordBytes(3) Return BitConverter.ToInt64(ValueBytes, 0) End Function
|
|
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.866
|
Determina si un caracter es diacrítico o si contiene una marca diacrítica (no es 100% efectivo con caracteres demasiado raros de otras culturas) ' Character Is Diacritic? ' ( By Elektro ) ' ' Usage Examples: ' MsgBox(CharacterIsDiacritic("á")) ' Result: True ' ''' <summary> ''' Determines whether a character is diacritic or else contains a diacritical mark. ''' </summary> ''' <param name="Character">Indicates the character.</param> ''' <returns><c>true</c> if character is diacritic or contains a diacritical mark, <c>false</c> otherwise.</returns> Public Function CharacterIsDiacritic(ByVal Character As Char) As Boolean If String.IsNullOrEmpty(CharacterIsDiacritic) Then Return False Else Dim Descomposed As Char() = Character.ToString.Normalize(System.Text.NormalizationForm.FormKD).ToCharArray Return (Descomposed.Count <> 1 OrElse String.IsNullOrWhiteSpace(Descomposed)) End If End Function
Convierte un caracter diacritico ' Convert Diacritic Character ' ( By Elektro ) ' ' Usage Examples: ' MsgBox(ConvertDiacritic("á", UnicodeNormalization:=System.Text.NormalizationForm.FormKD)) ' Result: 'a' ' ''' <summary> ''' Converts the diacritic characters in a String to an equivalent normalized English characters. ''' </summary> ''' <param name="Character"> ''' Indicates the diacritic character. ''' </param> ''' <param name="UnicodeNormalization"> ''' Defines the type of Unicode character normalization to perform. ''' (Default is 'NormalizationForm.FormKD') ''' </param> ''' <returns>The converted character.</returns> Public Function ConvertDiacritic(ByVal Character As Char, Optional ByVal UnicodeNormalization As System.Text.NormalizationForm = System.Text.NormalizationForm.FormKD) As String Dim Chars As Char() = CStr(Character).Normalize(System.Text.NormalizationForm.FormKD).ToCharArray For Each c As Char In Chars Select Case Globalization.CharUnicodeInfo.GetUnicodeCategory(c) Case Globalization.UnicodeCategory.NonSpacingMark, Globalization.UnicodeCategory.SpacingCombiningMark, Globalization.UnicodeCategory.EnclosingMark ' Do nothing. Exit Select Case Else Return c End Select Next c Return Character End Function
Obtiene el keyboardlayout ' Get Keyboard Layout ' ( By Elektro ) ' ' Usage Examples: ' MsgBox(GetKeyboardLayout(IntPtr.Zero)) ' Result: 10 ' MsgBox(GetKeyboardLayout(Process.GetCurrentProcess.MainWindowHandle)) ' Result: 10 ' ''' <summary> ''' Retrieves the active input locale identifier (formerly called the keyboard layout). ''' </summary> ''' <param name="idThread"> ''' A window handle identifier of the thread to query, or 'IntPtr.Zero' to query the current thread. ''' </param> ''' <returns> ''' The return value is the input locale identifier for the thread. ''' </returns> Public Shared Function GetKeyboardLayout(Optional ByVal idThread As IntPtr = Nothing) As Short Return BitConverter.GetBytes(APIGetKeyboardLayout(idThread)).First End Function ''' <summary> ''' Retrieves the active input locale identifier (formerly called the keyboard layout). ''' </summary> ''' <param name="idThread"> ''' A window handle identifier of the thread to query, or 'IntPtr.Zero' to query the current thread. ''' </param> ''' <returns> ''' The return value is the input locale identifier for the thread. ''' ''' The low-order byte contains a Language Identifier for the input language, ''' and the high-order byte contains a device handle to the physical layout of the keyboard. ''' </returns> <System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint:="GetKeyboardLayout", CharSet:=System.Runtime.InteropServices.CharSet.Unicode)> Private Shared Function APIGetKeyboardLayout( Optional ByVal idThread As IntPtr = Nothing ) As UInteger End Function
Obtiene el keycode de un caracter (ojo, no el keycode virtual). ' Get KeyCode ' ( By Elektro ) ' ' Usage Examples: ' MsgBox(GetKeyCode("a")) ' Result: 65 ' MsgBox(GetKeyCode("á")) ' Result: 65 ' MsgBox(GetKeyCode("á", IntPtr.Zero)) ' Result: 65 ' MsgBox(GetKeyCode("a", Process.GetCurrentProcess.MainWindowHandle)) ' Result: 65 ' 'Private Sub Test() Handles MyBase.Shown ' Dim sb As New System.Text.StringBuilder ' Dim Characters As Char() = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ñÑçÇ áéíóú ÁÉÍÓÚ àèìòù ÀÈÌÒÙ äëïÖÜ ÄËÏÖÜ º\'¡`+´-.,ª!·$%&/()=?¿".ToCharArray ' For Each c As Char In Characters ' sb.AppendFormat("Character: {0}", CStr(c)) ' sb.AppendLine() ' sb.AppendFormat("KeyCode : {0}", CStr(GetKeyCode(c, IntPtr.Zero))) ' MessageBox.Show(sb.ToString) ' sb.Clear() ' Next c 'End Sub ''' <summary> ''' Translates a character to the corresponding keycode. ''' </summary> ''' <param name="Character">Indicates the character.</param> ''' <param name="KeyboardLayout">Indicates the keyboard layout.</param> ''' <returns> ''' If the function succeeds, the return value contains the keycode. ''' ''' If the function finds no key that translates to the passed character code, ''' the return value contains "-1". ''' </returns> Public Shared Function GetKeyCode(ByVal Character As Char, Optional ByVal KeyboardLayout As IntPtr = Nothing) As Short ' Get the Keycode of the character. Dim Keycode As Short = BitConverter.GetBytes(VkKeyScanEx(Character)).First Select Case Keycode Case Is <> 255S ' Character is found on the current KeyboardLayout. Return Keycode Case Else ' Character is not found on the current KeyboardLayout. ' Descompose the character. Dim Descomposed As Char() = Character.ToString.Normalize(System.Text.NormalizationForm.FormKD).ToCharArray ' If character is diacritic then... If Descomposed.Count <> 1 OrElse String.IsNullOrWhiteSpace(Descomposed) Then For Each c As Char In Descomposed Select Case Globalization.CharUnicodeInfo.GetUnicodeCategory(c) Case Globalization.UnicodeCategory.NonSpacingMark, Globalization.UnicodeCategory.SpacingCombiningMark, Globalization.UnicodeCategory.EnclosingMark ' Do nothing. Exit Select Case Else ' Character is diacritic so we convert the diacritic and try to find the Keycode. Return GetKeyCode(c, KeyboardLayout) End Select Next c End If ' Chars.Count <> 1 End Select ' Keycode Return -1S ' Character is not diacritic and the keycode is not found. End Function ''' <summary> ''' Translates a character to the corresponding virtual-key code and shift state. ''' The function translates the character using the input language and ''' physical keyboard layout identified by the input locale identifier. ''' For more info see here: ''' http://msdn.microsoft.com/en-us/library/ms646332%28v=VS.85%29.aspx ''' </summary> ''' <param name="c">Indicates the character.</param> ''' <param name="KeyboardLayout">Indicates the keyboard layout.</param> ''' <returns> ''' If the function succeeds, ''' the low-order byte of the return value contains the virtual-key code, ''' and the high-order byte contains the shift state. ''' ''' If the function finds no key that translates to the passed character code, ''' both the low-order and high-order bytes contain '255'. ''' </returns> <System.Runtime.InteropServices.DllImport("user32.dll", CharSet:=System.Runtime.InteropServices.CharSet.Unicode)> Private Shared Function VkKeyScanEx( ByVal c As Char, Optional ByVal KeyboardLayout As IntPtr = Nothing ) As Short End Function
Envio de peticion por el método POST ' Send POST ' ( By Elektro ) ' ' Usage Examples: ' 'Dim Response As String = ' SendPOST("http://es.wikipedia.org/wiki/Special:Search?", ' New Dictionary(Of String, String) From { ' {"search", "Petición+POST"}, ' {"sourceid", "Mozilla-search"} ' }) ' Formated POST Data: "search=Petición+POST&sourceid=Mozilla-search" 'Clipboard.SetText(Response) ' Copy the response to Clipboard. ' ''' <summary> ''' Sends a POST method petition and returns the server response. ''' </summary> ''' <param name="URL">Indicates the URL.</param> ''' <param name="PostData">Indicates the post data.</param> ''' <returns>The response.</returns> Public Function SendPOST(ByVal URL As String, ByVal PostData As Dictionary(Of String, String)) As String Dim Data As New System.Text.StringBuilder ' PostData to send, formated. Dim Request As Net.HttpWebRequest = HttpWebRequest.Create(URL) ' HTTP Request. Dim Response As HttpWebResponse ' Server response. Dim ResponseContent As String ' Server response result. ' Set and format the post data of the query. For Each Item As KeyValuePair(Of String, String) In PostData Data.AppendFormat("{0}={1}&", Item.Key, Item.Value) Next Item ' Set the Request properties. With Request .Method = "POST" .ContentType = "application/x-www-form-urlencoded" .ContentLength = Data.ToString.Length .Proxy = Nothing ' .UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0" End With ' Write the POST data bytes into the Stream. Using RequestStream As IO.Stream = Request.GetRequestStream() RequestStream.Write(System.Text.Encoding.UTF8.GetBytes(Data.ToString), 0, Data.ToString.Length) RequestStream.Close() End Using ' Get the response. Response = Request.GetResponse() ' Get the response content. Using Reader As New IO.StreamReader(Response.GetResponseStream) ResponseContent = Reader.ReadToEnd Response.Close() End Using ' Return the response content. Return ResponseContent End Function
|
|
« Última modificación: 11 Marzo 2014, 21:53 pm por Eleкtro »
|
En línea
|
|
|
|
Synth3tik0
Desconectado
Mensajes: 126
|
uuh u_u esperaba q fueran para c#
|
|
« Última modificación: 10 Abril 2014, 01:13 am por ๖ۣۜPム||ムđ1ůɱ »
|
En línea
|
..........
|
|
|
z3nth10n
Desconectado
Mensajes: 1.583
"Jack of all trades, master of none." - Zenthion
|
|
|
|
En línea
|
⏩ Interesados hablad por Discord.
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.866
|
Como limpiar la consola de depuración, en cualquier momento: Nota: Asegurarse de no tener más de 1 instancia de VisualStudio en ejecución. ' Clear Debug-Console Output ' By Elektro ' ' Instructions: ' 1. Add a reference to 'EnvDTE' and 'envdte80' ' ''' <summary> ''' Clears the debug console output. ''' </summary> Public Sub ClearDebugConsoleOutput() DirectCast(Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.12.0"), EnvDTE80.DTE2). ToolWindows.OutputWindow.OutputWindowPanes.Item("Debug").Clear() End Sub
Como obtener el output de la consola de depuración, en cualquier momento: Nota: Asegurarse de no tener más de 1 instancia de VisualStudio en ejecución. ' Get Debug-Console Output ' By Elektro ' ' Instructions: ' 1. Add a reference to 'EnvDTE' and 'envdte80' ' ' Usage Examples: ' ' Clipboard.SetText(GetDebugConsoleOutput) ' ''' <summary> ''' Gets the debug console output. ''' </summary> ''' <returns>System.String.</returns> Public Function GetDebugConsoleOutput() As String Dim Output As EnvDTE.TextSelection = DirectCast(Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.12.0"), EnvDTE80.DTE2). ToolWindows.OutputWindow.OutputWindowPanes.Item("Debug").TextDocument.Selection Output.SelectAll() Return Output.Text End Function
|
|
« Última modificación: 3 Agosto 2014, 15:44 pm por Eleкtro »
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.866
|
Como promprobar si un Type es serializable: ' Is Type Serializable? ' By Elektro ' ' Usage Examples: ' 'MsgBox(IsTypeSerializable(Of String)) 'MsgBox(IsTypeSerializable(GetType(Form))) 'MsgBox(IsTypeSerializable(0.0F.GetType)) ' ''' <summary> ''' Determines whether a Type can be serialized. ''' </summary> ''' <typeparam name="T"></typeparam> ''' <returns><c>true</c> if Type can be serialized; otherwise, <c>false</c>.</returns> Private Function IsTypeSerializable(Of T)() As Boolean Return Attribute.IsDefined(GetType(T), GetType(SerializableAttribute)) End Function ''' <summary> ''' Determines whether a Type can be serialized. ''' </summary> ''' <typeparam name="T"></typeparam> ''' <param name="Type">The Type.</param> ''' <returns><c>true</c> if Type can be serialized; otherwise, <c>false</c>.</returns> Private Function IsTypeSerializable(Of T)(ByVal Type As T) As Boolean Return Attribute.IsDefined(GetType(T), GetType(SerializableAttribute)) End Function
Como comprobar si un objeto es serializable: ' Is Object Serializable? ' By Elektro ' ' Usage Examples: ' 'MsgBox(IsObjectSerializable(New ArrayList From {"String Item"}, SerializationFormat.Xml)) ' Result: True 'MsgBox(IsObjectSerializable(New ArrayList From {New Object() {"Collection", "Of", "Strings"}})) ' Result: False ' ''' <summary> ''' Determines whether an object can be serialized. ''' </summary> ''' <param name="Object">The object.</param> ''' <returns><c>true</c> if object can be serialized; otherwise, <c>false</c>.</returns> Private Function IsObjectSerializable(ByVal [Object] As Object, Optional ByVal SerializationFormat As SerializationFormat = SerializationFormat.Xml) As Boolean Dim Serializer As Object Using fs As New IO.MemoryStream Select Case SerializationFormat Case Data.SerializationFormat.Binary Serializer = New Runtime.Serialization.Formatters.Binary.BinaryFormatter() Case Data.SerializationFormat.Xml Serializer = New Xml.Serialization.XmlSerializer([Object].GetType) Case Else Throw New ArgumentException("Invalid SerializationFormat", SerializationFormat) End Select Try Serializer.Serialize(fs, [Object]) Return True Catch ex As InvalidOperationException Return False End Try End Using ' fs As New MemoryStream End Function
Ejemplo de sintaxis para una condicional de .Net Framework del proyecto. #If NET20 Then ' This happens when the app targets .NEt Framework 2.0 #ElseIf NET40 Then ' This happens when the app targets .NEt Framework 4.0 #End If
|
|
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.866
|
Ejemplo detallado de como parsear la salida estándar y la salida de error de un proceso, de forma asíncrona. ' Usage Examples: ' MessageBox.Show(RunCommand(Command:="Dir /B /S C:\*.*", Find:=".exe")) ' MessageBox.Show(RunCommand(Command:="Dir /B /S C:\*.*", Find:=".xXx")) ''' <summary> ''' The Process Object. ''' </summary> Private WithEvents MyProcess As Process = New Process With {.StartInfo = New ProcessStartInfo With { .CreateNoWindow = True, .UseShellExecute = False, .RedirectStandardError = True, .RedirectStandardOutput = True } } ''' <summary> ''' Indicates the string to search. ''' </summary> Private Find As String = String.Empty ''' <summary> ''' Determines whether a result is found. ''' </summary> Private ResultFound As Boolean = False ''' <summary> ''' Runs a command on the CMD. ''' </summary> ''' <param name="Command">Indicates the Command to run.</param> ''' <param name="Find">Indicates a string to find in the Output.</param> ''' <returns><c>true</c> if the specified string is found, <c>false</c> otherwise.</returns> Public Function RunCommand(ByVal Command As String, ByVal Find As String) As Boolean Me.Find = Find Me.ResultFound = False With MyProcess AddHandler .OutputDataReceived, AddressOf RunCommand_OutputDataReceived AddHandler .ErrorDataReceived, AddressOf RunCommand_ErrorDataReceived .StartInfo.FileName = "CMD.exe" .StartInfo.Arguments = "/C " & ControlChars.Quote & Command & ControlChars.Quote .Start() .BeginOutputReadLine() .BeginErrorReadLine() .WaitForExit() RemoveHandler .OutputDataReceived, AddressOf RunCommand_OutputDataReceived RemoveHandler .ErrorDataReceived, AddressOf RunCommand_ErrorDataReceived End With Return Me.ResultFound End Function ''' <summary> ''' Handles the 'OutputDataReceived' of the 'RunCommand' method. ''' </summary> ''' <param name="sender">The source of the event.</param> ''' <param name="e">The <see cref="DataReceivedEventArgs"/> instance containing the event data.</param> Private Sub RunCommand_OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs) If e.Data Is Nothing OrElse Me.ResultFound Then With MyProcess .CancelOutputRead() If Not .HasExited Then Try .Kill() Debug. WriteLine("Process killed successfully!") Catch ex As Exception Debug. WriteLine(ex. Message) End Try End If End With ElseIf e.Data.ToLower.Contains(Me.Find.ToLower) Then Me.ResultFound = True Debug. WriteLine("StdOut: " & e. Data) Debug. WriteLine("Result Found!") Debug. WriteLine("Stopping CMD execution at this point...") Else Debug. WriteLine("StdOut: " & e. Data) End If End Sub ''' <summary> ''' Handles the 'ErrorDataReceived' of the 'RunCommand' method. ''' </summary> ''' <param name="sender">The source of the event.</param> ''' <param name="e">The <see cref="DataReceivedEventArgs"/> instance containing the event data.</param> Private Sub RunCommand_ErrorDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs) If e.Data Is Nothing OrElse Me.ResultFound Then With MyProcess .CancelErrorRead() If Not .HasExited Then Try .Kill() Debug. WriteLine("Process killed successfully!") Catch ex As Exception Debug. WriteLine(ex. Message) End Try End If End With Else Debug. WriteLine("StdErr: " & e. Data) End If End Sub
Un ayudante del proceso MKVMerge (de MKVToolnix) No le aádí casi funcionalidades, solamente las que necesité usar: ' *********************************************************************** ' Author : Elektro ' Last Modified On : 07-24-2014 ' *********************************************************************** ' <copyright file="MKVMergeHelper.vb" company="Elektro Studios"> ' Copyright (c) Elektro Studios. All rights reserved. ' </copyright> ' *********************************************************************** #Region " Usage Examples " 'Using MKVMerge As New MKVMergeHelper ' MessageBox.Show(MKVMerge.Version) ' MessageBox.Show(MKVMerge.ContainsTrackType("File.mkv", MKVMergeHelper.TrackType.Subtitle)) 'End Using #End Region Public Class MKVMergeHelper : Implements IDisposable #Region " Properties " ''' <summary> ''' Gets or sets the mkvmerge.exe file location. ''' </summary> ''' <value>The MKVmerge.exe file location.</value> Public Property MKVMergeLocation As String = ".\mkvmerge.exe" ''' <summary> ''' Gets the MKVMerge.exe version. ''' </summary> ''' <value>The MKVMerge.exe version.</value> Public ReadOnly Property Version As String Get Me.GetVersion() Return Me._Version End Get End Property Private _Version As String = String.Empty #End Region #Region " Other Objects " ''' <summary> ''' The MKVMerge Process Object. ''' </summary> Private WithEvents procMKVMerge As Process = New Process With {.StartInfo = New ProcessStartInfo With { .CreateNoWindow = True, .UseShellExecute = False, .RedirectStandardError = True, .RedirectStandardOutput = True } } ''' <summary> ''' Determines whether a file contains the specified track type. ''' </summary> Private TrackTypeFound As Boolean = False ''' <summary> ''' Indicates the current tracktype to search. ''' </summary> Private CurrentTrackType As TrackType = Nothing #End Region #Region " Enumerations " ''' <summary> ''' Specifies a type of track. ''' </summary> Public Enum TrackType As Integer ''' <summary> ''' Video track. ''' </summary> Video = 0 ''' <summary> ''' Audio track. ''' </summary> Audio = 1 ''' <summary> ''' Subtitle. ''' </summary> Subtitle = 2 ''' <summary> ''' Attachment. ''' </summary> Attachment = 3 End Enum #End Region #Region " Public Methods " ''' <summary> ''' Determines whether mkvmerge.exe file exist. ''' </summary> ''' <returns><c>true</c> if mkvmerge.exe file exist; otherwise, <c>false</c>.</returns> Public Function IsAvaliable() As Boolean Return IO. File. Exists(Me. MKVMergeLocation) End Function ''' <summary> ''' Determines whether a file contains the specified track type. ''' </summary> ''' <param name="file">Indicates the file.</param> ''' <param name="TrackType">Indicates the type of the track.</param> ''' <returns><c>true</c> if the specified track type is found, <c>false</c> otherwise.</returns> Public Function ContainsTrackType (ByVal file As String, ByVal TrackType As TrackType ) As Boolean Me.CurrentTrackType = TrackType Me.TrackTypeFound = False With procMKVMerge AddHandler .OutputDataReceived, AddressOf ContainsTrackType_OutputDataReceived .StartInfo.FileName = Me.MKVMergeLocation . StartInfo. Arguments = String. Format("--identify ""{0}""", file) .Start() .BeginOutputReadLine() .WaitForExit() RemoveHandler .OutputDataReceived, AddressOf ContainsTrackType_OutputDataReceived End With Return Me.TrackTypeFound End Function #End Region #Region " Private Methods " ''' <summary> ''' Gets the MKVMerge.exe file version. ''' </summary> ''' <returns>The MKVMerge.exe file version.</returns> Private Function GetVersion() As String Me._Version = String.Empty With procMKVMerge AddHandler .OutputDataReceived, AddressOf GetVersion_OutputDataReceived .StartInfo.FileName = Me.MKVMergeLocation .StartInfo.Arguments = String.Format("--version") .Start() .BeginOutputReadLine() .WaitForExit() RemoveHandler .OutputDataReceived, AddressOf GetVersion_OutputDataReceived End With Return Me.TrackTypeFound End Function #End Region #Region " Event Handlers " ''' <summary> ''' Handles the OutputDataReceived of the ContainsTrackType method. ''' </summary> ''' <param name="sender">The source of the event.</param> ''' <param name="e">The <see cref="DataReceivedEventArgs"/> instance containing the event data.</param> ''' <exception cref="System.Exception"></exception> Private Sub ContainsTrackType_OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs) If e.Data Is Nothing OrElse Me.TrackTypeFound Then With procMKVMerge .CancelOutputRead() If Not .HasExited Then Try .Kill() Catch End Try End If End With ElseIf e.Data.StartsWith("Error:", StringComparison.OrdinalIgnoreCase) Then Throw New Exception(e.Data) ElseIf Me.CurrentTrackType = TrackType.Video _ AndAlso e.Data.ToLower Like "track id #*: video*" Then Me.TrackTypeFound = True ElseIf Me.CurrentTrackType = TrackType.Audio _ AndAlso e.Data.ToLower Like "track id #*: audio*" Then Me.TrackTypeFound = True ElseIf Me.CurrentTrackType = TrackType.Subtitle _ AndAlso e.Data.ToLower Like "track id #*: subtitle*" Then Me.TrackTypeFound = True ElseIf Me.CurrentTrackType = TrackType.Attachment _ AndAlso e.Data.ToLower Like "attachment id*" Then Me.TrackTypeFound = True End If End Sub ''' <summary> ''' Handles the OutputDataReceived of the GetVersion method. ''' </summary> ''' <param name="sender">The source of the event.</param> ''' <param name="e">The <see cref="DataReceivedEventArgs"/> instance containing the event data.</param> ''' <exception cref="System.Exception"></exception> Private Sub GetVersion_OutputDataReceived(ByVal sender As Object, ByVal e As DataReceivedEventArgs) If e.Data Is Nothing OrElse Not String.IsNullOrEmpty(Me._Version) Then With procMKVMerge .CancelOutputRead() If Not .HasExited Then Try .Kill() Catch End Try End If End With ElseIf e.Data.StartsWith("Error:", StringComparison.OrdinalIgnoreCase) Then Throw New Exception(e.Data) ElseIf e.Data.ToLower Like "mkvmerge v#.*" Then Me._Version = e.Data.Split()(1).Substring(1) End If End Sub #End Region #Region " IDisposable " ''' <summary> ''' To detect redundant calls when disposing. ''' </summary> Private IsDisposed As Boolean = False ''' <summary> ''' Prevents calls to methods after disposing. ''' </summary> Private Sub DisposedCheck() If Me.IsDisposed Then Throw New ObjectDisposedException(Me.GetType().FullName) End If End Sub ''' <summary> ''' Disposes the objects generated by this instance. ''' </summary> Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub ' IDisposable Protected Overridable Sub Dispose(IsDisposing As Boolean) If Not Me.IsDisposed Then If IsDisposing Then procMKVMerge.Dispose() End If End If Me.IsDisposed = True End Sub #End Region End Class
¿Como prevenir la instancia de una Class si ya tienes otra Class instanciada a la que le pasaste el mismo parámetro a su constructor?, pues de esta manera: #Region " Example Usage " 'Private Sub Test() Handles MyBase.Shown ' ' Dim MyObject As Byte = 0 ' ' Using TestObj1 As New TestClass(MyObject) ' ' Try ' Dim TestObj2 As New TestClass(MyObject) ' ' Catch ex As Exception ' MessageBox.Show(ex.Message) ' ' End Try ' ' End Using ' 'End Sub #End Region #Region " TestClass " Public Class TestClass : Implements IDisposable Private Shared InstancedObjects As New List(Of Object) Private _MyObject As Object Public Sub New(ByVal Parameter As Object) If Not InstancedObjects.Contains(Parameter) Then Me._MyObject = Parameter InstancedObjects.Add(Parameter) Else Throw New Exception(String.Format("Another open instance of the '{0}' class is using the same '{1}' object.", MyBase.GetType.Name, Parameter.GetType.Name)) End If End Sub #Region " IDisposable " ''' <summary> ''' To detect redundant calls when disposing. ''' </summary> Private IsDisposed As Boolean = False ''' <summary> ''' Prevent calls to methods after disposing. ''' </summary> ''' <exception cref="System.ObjectDisposedException"></exception> Private Sub DisposedCheck() If Me.IsDisposed Then Throw New ObjectDisposedException(Me.GetType.FullName) End If End Sub ''' <summary> ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. ''' </summary> Public Sub Dispose() Implements IDisposable.Dispose Me.Dispose(True) GC.SuppressFinalize(Me) End Sub ''' <summary> ''' Releases unmanaged and - optionally - managed resources. ''' </summary> ''' <param name="IsDisposing"> ''' <c>true</c> to release both managed and unmanaged resources; ''' <c>false</c> to release only unmanaged resources. ''' </param> Protected Sub Dispose(ByVal IsDisposing As Boolean) If Not Me.IsDisposed Then If IsDisposing Then InstancedObjects.Remove(Me._MyObject) End If End If Me.IsDisposed = True End Sub #End Region End Class #End Region
|
|
|
En línea
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.866
|
Como crear un archivo dummy (vacío) de cualquier tamaño: ' Create Dummy File ' By Elektro ' ' Usage Examples: ' CreateDummyFile("C:\DummyFile.tmp", 1024L ^ 3L) ' File with 1 GB size. ' ''' <summary> ''' Creates a dummy zero-filled file. ''' </summary> ''' <param name="Filepath">Indicates the filepath.</param> ''' <param name="Length">Indicates the size, in Bytes.</param> Public Sub CreateDummyFile(ByVal Filepath As String, Optional ByVal Length As Long = 0) Using fs As New IO.FileStream(Filepath, IO.FileMode.CreateNew) fs.SetLength(Length) End Using End Sub
Preserva, Restaura, o Establece las fechas de un archivo. Nota: Esta versión tiene ciertas mejoras a la versión que publiqué en el foro, la mejora en concreto es la de poder restaurar las fechas si un archivo ha cambiado de ubicación o de nombre. ' *********************************************************************** ' Author : Elektro ' Modified : 07-22-2014 ' *********************************************************************** ' <copyright file="FileDater.vb" company="Elektro Studios"> ' Copyright (c) Elektro Studios. All rights reserved. ' </copyright> ' *********************************************************************** #Region " Usage Examples " #Region " Example 1 " '' Instance a test FileInfo using an unique temp file. 'Using fd As New FileDater(File:=New IO.FileInfo(IO.Path.GetTempFileName)) ' ' ' Preserve the current date-modified of the file. ' fd.Preserve(FileDater.DateType.Modified) ' ' ' Do some kind of operation that alters the current date-modified of the file. ' IO.File.AppendAllText(fd.File.FullName, New String("X"c, 10I)) ' ' ' Restore the previously preserved date-modified on the TestFile. ' fd.Restore(FileDater.DateType.Modified) 'End Using '/ fd #End Region #Region " Example 2 " '' Declare a test filepath. 'Dim TestFile As String = "C:\Testfile.tmp" ' '' Create the test file. 'If Not IO.File.Exists(TestFile) Then ' Using fs As New IO.FileStream(TestFile, IO.FileMode.CreateNew, IO.FileAccess.ReadWrite) ' End Using 'End If ' '' Instance the FileDater Class. 'Using fd As New FileDater(File:=TestFile) ' ' ' Preserve all the current dates of the TestFile. ' fd.Preserve() ' ' ' Print the preserved dates in the debug console. ' Debug.WriteLine(String.Format("Preserved Creation Date: {0}", fd.PreservedCreationDate.ToString)) ' Debug.WriteLine(String.Format("Preserved LastAccess Date: {0}", fd.PreservedLastAccessDate.ToString)) ' Debug.WriteLine(String.Format("Preserved LastModify Date: {0}", fd.PreservedLastModifyDate.ToString)) ' ' ' Copy the testfile to other location. ' IO.File.Copy(fd.File.FullName, "C:\New Testfile.tmp", True) ' ' ' Assign the new location in the instanced FileDater. ' fd.SetFileLocation("C:\New Testfile.tmp") ' ' ' Modify all the dated on the copied TestFile. ' fd.Set(Date.Parse("01/01/2015")) ' ' ' Restore all the previously preserved dates on the new TestFile. ' fd.Restore() ' ' ' Print the current testfile dates in the debug console. ' Debug.WriteLine(String.Format("Current Creation Date: {0}", fd.File.CreationTime.ToString)) ' Debug.WriteLine(String.Format("Current LastAccess Date: {0}", fd.File.LastAccessTime.ToString)) ' Debug.WriteLine(String.Format("Current LastModify Date: {0}", fd.File.LastWriteTime.ToString)) ' 'End Using #End Region #End Region #Region " Imports " Imports System.ComponentModel Imports System.IO #End Region #Region " FileDater " ''' <summary> ''' Contains methods to preserve, set, and restore the dates contained on file. ''' </summary> Public NotInheritable Class FileDater : Implements IDisposable #Region " Objects " ''' <summary> ''' Contains the files that are already used in the constructor to prevent a duplicated instance for the same file. ''' </summary> Private Shared InstancedFiles As New List(Of FileInfo) #End Region #Region " Properties " ''' <summary> ''' Gets the file. ''' </summary> ''' <value>The file.</value> Public ReadOnly Property [File] As FileInfo Get Return Me._File End Get End Property Private _File As FileInfo ''' <summary> ''' Gets the type of the current preserved dates. ''' </summary> Public ReadOnly Property PreservedTypes As DateType Get Return Me._PreservedTypes End Get End Property Private _PreservedTypes As DateType = Nothing ''' <summary> ''' Gets the preserved creation date. ''' </summary> ''' <value>The preserved creation date.</value> Public ReadOnly Property PreservedCreationDate As Date Get Return Me._PreservedCreationDate End Get End Property Private _PreservedCreationDate As Date ''' <summary> ''' Gets the preserved last-access date. ''' </summary> ''' <value>The preserved creation date.</value> Public ReadOnly Property PreservedLastAccessDate As Date Get Return Me._PreservedLastAccessDate End Get End Property Private _PreservedLastAccessDate As Date ''' <summary> ''' Gets the preserved last-modify date. ''' </summary> ''' <value>The preserved creation date.</value> Public ReadOnly Property PreservedLastModifyDate As Date Get Return Me._PreservedLastModifyDate End Get End Property Private _PreservedLastModifyDate As Date #End Region #Region " Enumerations " ''' <summary> ''' Contains a FileDate flag. ''' </summary> <FlagsAttribute> Public Enum DateType As Integer ''' <summary> ''' The date when the file was created. ''' </summary> Created = 1I ''' <summary> ''' The date when the file was accessed by last time. ''' </summary> Accessed = 2I ''' <summary> ''' The date when the file was modified by last time. ''' </summary> Modified = 4I End Enum #End Region #Region " Constructors " ''' <summary> ''' Initializes a new instance of the <see cref="FileDater"/> class. ''' </summary> ''' <param name="File">Indicates the <see cref="FileInfo"/> instance.</param> ''' <exception cref="System.Exception"></exception> Public Sub New(ByVal [File] As FileInfo ) If Not InstancedFiles. Contains([File]) Then InstancedFiles. Add([File]) Else Throw New Exception(String.Format("Another instance of the '{0}' class is using the same file.", MyBase.GetType.Name)) End If End Sub ''' <summary> ''' Initializes a new instance of the <see cref="FileDater"/> class. ''' </summary> ''' <param name="File">Indicates the file.</param> Public Sub New(ByVal [File] As String) Me. New(New FileInfo ([File])) End Sub ''' <summary> ''' Prevents a default instance of the <see cref="FileDater"/> class from being created. ''' </summary> Private Sub New() End Sub #End Region #Region " Hidden Methods " ''' <summary> ''' Serves as a hash function for a particular type. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Sub GetHashCode() End Sub ''' <summary> ''' Determines whether the specified System.Object instances are considered equal. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Sub Equals() End Sub ''' <summary> ''' Determines whether the specified System.Object instances are the same instance. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Private Shadows Sub ReferenceEquals() End Sub ''' <summary> ''' Returns a String that represents the current object. ''' </summary> <EditorBrowsable(EditorBrowsableState.Never)> Public Shadows Sub ToString() End Sub #End Region #Region " Public Methods " ''' <summary> ''' Preserves the specified dates of the file to restore them later at any time. ''' Note: Dates can be preserved again at any time. ''' </summary> ''' <param name="DateType">Indicates the type of dates to preserve.</param> Public Sub Preserve(ByVal DateType As DateType) Me.DisposedCheck() ' Creation If DateType.HasFlag(FileDater.DateType.Created) Then Me._PreservedCreationDate = Me._File.CreationTime End If ' Accessed If DateType.HasFlag(FileDater.DateType.Accessed) Then Me._PreservedLastAccessDate = Me._File.LastAccessTime End If ' Modified If DateType.HasFlag(FileDater.DateType.Modified) Then Me._PreservedLastModifyDate = Me._File.LastWriteTime End If Me._PreservedTypes = DateType End Sub ''' <summary> ''' Preserves at once all the dates of the file to restore them later at any time. ''' Note: Dates can be preserved again at any time. ''' </summary> Public Sub Preserve() Me.DisposedCheck() Me._PreservedCreationDate = Me._File.CreationTime Me._PreservedLastAccessDate = Me._File.LastAccessTime Me._PreservedLastModifyDate = Me._File.LastWriteTime Me._PreservedTypes = DateType.Created Or DateType.Accessed Or DateType.Modified End Sub ''' <summary> ''' Restores the specified preserved dates on the file. ''' Note: Calling this method does not cause the deletion of any preserved date. ''' </summary> ''' <param name="DateType">Indicates the type of dates to restore on the file.</param> ''' <exception cref="System.Exception">Any date was preserved.</exception> Public Sub Restore(ByVal DateType As DateType) Me.DisposedCheck() ' Creation If DateType.HasFlag(FileDater.DateType.Created) _ AndAlso Me._PreservedTypes.HasFlag(FileDater.DateType.Created) Then Me._File.CreationTime = Me._PreservedCreationDate ElseIf DateType.HasFlag(FileDater.DateType.Created) _ AndAlso Not Me._PreservedTypes.HasFlag(FileDater.DateType.Created) Then Throw New Exception(String.Format("The specified date was not preserved.")) With { .Source = FileDater.DateType.Created.ToString } End If ' Accessed If DateType.HasFlag(FileDater.DateType.Accessed) _ AndAlso Me._PreservedTypes.HasFlag(FileDater.DateType.Accessed) Then Me._File.LastAccessTime = Me._PreservedLastAccessDate ElseIf DateType.HasFlag(FileDater.DateType.Accessed) _ AndAlso Not Me._PreservedTypes.HasFlag(FileDater.DateType.Accessed) Then Throw New Exception(String.Format("The specified date was not preserved.")) With { .Source = FileDater.DateType.Accessed.ToString } End If ' Modified If DateType.HasFlag(FileDater.DateType.Modified) _ AndAlso Me._PreservedTypes.HasFlag(FileDater.DateType.Modified) Then Me._File.LastWriteTime = Me._PreservedLastModifyDate ElseIf DateType.HasFlag(FileDater.DateType.Modified) _ AndAlso Not Me._PreservedTypes.HasFlag(FileDater.DateType.Modified) Then Throw New Exception(String.Format("The specified date was not preserved.")) With { .Source = FileDater.DateType.Modified.ToString } End If End Sub ''' <summary> ''' Restores at once all the preserved dates on the file. ''' Note: Calling this method does not cause the deletion of any preserved date. ''' </summary> Public Sub Restore() Me.DisposedCheck() ' Creation If Me._PreservedTypes.HasFlag(FileDater.DateType.Created) Then Me._File.CreationTime = Me._PreservedCreationDate End If ' Accessed If Me._PreservedTypes.HasFlag(FileDater.DateType.Accessed) Then Me._File.LastAccessTime = Me._PreservedLastAccessDate End If ' Modified If Me._PreservedTypes.HasFlag(FileDater.DateType.Modified) Then Me._File.LastWriteTime = Me._PreservedLastModifyDate End If End Sub ''' <summary> ''' Sets the specified dates on the file. ''' Note: ''' Calling this method does not cause the deletion of any preserved date. ''' After setting a date, must call once the <see cref="Preserve"/> method if want to preserve any new date established. ''' </summary> ''' <param name="DateType">Indicates the type of dates to set on the file.</param> ''' <param name="Date">Indicates the date.</param> Public Sub [Set](ByVal DateType As DateType, ByVal [Date] As Date) Me.DisposedCheck() ' Creation If DateType.HasFlag(FileDater.DateType.Created) Then Me._File.CreationTime = [Date] End If ' Accessed If DateType.HasFlag(FileDater.DateType.Accessed) Then Me._File.LastAccessTime = [Date] End If ' Modified If DateType.HasFlag(FileDater.DateType.Modified) Then Me._File.LastWriteTime = [Date] End If End Sub ''' <summary> ''' Sets at once all the dates on the file. ''' Note: ''' Calling this method does not cause the deletion of any preserved date. ''' After setting a date, must call once the <see cref="Preserve"/> method if want to preserve any new date established. ''' </summary> ''' <param name="Date">Indicates the date.</param> Public Sub [Set](ByVal [Date] As Date) Me.DisposedCheck() Me._File.CreationTime = [Date] Me._File.LastAccessTime = [Date] Me._File.LastWriteTime = [Date] End Sub ''' <summary> ''' Causes this <see cref="FileDater"/> instance to assign a new location for the current file. ''' This could be useful if the preserved dates should be restored in a file that has changed its name/ubication. ''' Note: Calling this method does not cause the deletion of any preserved date. ''' </summary> ''' <param name="File">Indicates the <see cref="FileInfo"/> instance.</param> ''' <exception cref="System.Exception"></exception> Public Sub SetFileLocation (ByVal [File] As FileInfo ) If Not InstancedFiles. Contains([File]) Then InstancedFiles.Remove(Me._File) InstancedFiles. Add([File]) Else Throw New Exception(String.Format("Another instance of the '{0}' class is using the same file.", MyBase.GetType.Name)) End If End Sub ''' <summary> ''' Causes this <see cref="FileDater"/> instance to assign a new location for the current file. ''' This could be useful if the preserved dates should be restored in a file that has changed its name/ubication. ''' Note: Calling this method does not cause the deletion of any preserved date. ''' </summary> ''' <param name="File">Indicates the file.</param> ''' <exception cref="System.Exception"></exception> Public Sub SetFileLocation (ByVal [File] As String) Me. SetFileLocation(New FileInfo ([File])) End Sub #End Region #Region " IDisposable " ''' <summary> ''' To detect redundant calls when disposing. ''' </summary> Private IsDisposed As Boolean = False ''' <summary> ''' Prevent calls to methods after disposing. ''' </summary> ''' <exception cref="System.ObjectDisposedException"></exception> Private Sub DisposedCheck() If Me.IsDisposed Then Throw New ObjectDisposedException(Me.GetType().FullName) End If End Sub ''' <summary> ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. ''' </summary> Public Sub Dispose() Implements IDisposable.Dispose Dispose(True) GC.SuppressFinalize(Me) End Sub ''' <summary> ''' Releases unmanaged and - optionally - managed resources. ''' </summary> ''' <param name="IsDisposing"> ''' <c>true</c> to release both managed and unmanaged resources; ''' <c>false</c> to release only unmanaged resources. ''' </param> Protected Sub Dispose(ByVal IsDisposing As Boolean) If Not Me.IsDisposed Then If IsDisposing Then InstancedFiles.Remove(Me._File) End If End If Me.IsDisposed = True End Sub #End Region End Class #End Region
|
|
|
En línea
|
|
|
|
|
Mensajes similares |
|
Asunto |
Iniciado por |
Respuestas |
Vistas |
Último mensaje |
|
|
Librería de Snippets en C/C++
« 1 2 3 4 »
Programación C/C++
|
z3nth10n
|
31
|
25,820
|
2 Agosto 2013, 17:13 pm
por 0xDani
|
|
|
[APORTE] [VBS] Snippets para manipular reglas de bloqueo del firewall de Windows
Scripting
|
Eleкtro
|
1
|
4,068
|
3 Febrero 2014, 20:19 pm
por Eleкtro
|
|
|
Librería de Snippets para Delphi
« 1 2 »
Programación General
|
crack81
|
15
|
21,058
|
25 Marzo 2016, 18:39 pm
por crack81
|
|
|
Una organización en Github para subir, proyectos, snippets y otros?
Sugerencias y dudas sobre el Foro
|
z3nth10n
|
0
|
3,065
|
21 Febrero 2017, 10:47 am
por z3nth10n
|
|
|
índice de la Librería de Snippets para VB.NET !!
.NET (C#, VB.NET, ASP)
|
Eleкtro
|
7
|
6,508
|
4 Julio 2018, 21:35 pm
por Eleкtro
|
|