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

 

 


Tema destacado: Guía actualizada para evitar que un ransomware ataque tu empresa


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: 1 2 [3] 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ... 58 Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 480,117 veces)
Novlucker
Ninja y
Colaborador
***
Desconectado Desconectado

Mensajes: 10.683

Yo que tu lo pienso dos veces


Ver Perfil
Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
« Respuesta #20 en: 14 Enero 2013, 03:52 am »

@Novlucker
Que grande,
antes de nada debo decir que para mi tus críticas o sugerencias (O ataques personales si se da el caos xD) son más que bien recibidas
Mientras no pienses que es un ataque, la idea es que puedas mejorar :P

Lo malo de esto, es que si declaro el tipo en boolean (Por ejemplo), entonces ya no puedo retornar el mensaje de la excepción (Return ex.message), ¿O si?.
En realidad no es posible. Por lo general cuando es necesario hacer eso se debe de retornar un objeto Result (o clase similar creada por ti). Algo así por ejemplo;
Código
  1. Public Class Result
  2.    Public ReturnValue as Boolean
  3.    Public Message as String
  4. End Class
Si esta todo ok, se asigna el valor a ReturnValue y se deja el Message vacío, sino se hace lo contrario.
De cualquier modo, lo habitual es simplemente hacer un throw de la exception, las propias funciones del .NET Framework lo hacen por ejemplo. Por decir algo más y siguiendo con .NET, en C# por ejemplo no puedes declarar un método/función sin tipo de retorno y luego retornar algo.

Código
  1. Attributes.Select(Function(a) DirectCast(a, Integer)).Sum()
De ahí lo único que entiendo es que modificas el valor "a" a tipo entero (no se lo que significa esa "a"), lo de "Select", "Function", y "Sum, ni idea XD
Para acortar un poco usé LINQ con una expresión lambda :P, la explicación es la siguiente;
  • Attributes es una lista, por lo cual puedo aplicar LINQ
  • Por cada item "a" de la lista, lo casteo a Integer. Esto es porque el enumerador FileAttributes contiene los valores para estos
  • Dado que ahora tengo una lista de Integer, los puedo sumar con Sum

2 ejemplos de uso;
Código
  1. Attrib("D:\\archivo.txt", New List(Of System.IO.FileAttributes)(New System.IO.FileAttributes() {System.IO.FileAttributes.Hidden, System.IO.FileAttributes.ReadOnly}))
Código
  1. Dim atributos As List(Of System.IO.FileAttributes) = New List(Of IO.FileAttributes)
  2. atributos.Add(System.IO.FileAttributes.Hidden)
  3. atributos.Add(System.IO.FileAttributes.ReadOnly)
  4. Attrib("D:\\archivo.txt", atributos)
Me doy cuenta que tengo que usar más las constantes y las enumeraciones si quiero perfeccionar y simplificar las cosas (Si te digo la verdad pensé que esa función no se podía simplificar más, hasta que he visto tu modificación xDDD, me kawen tó)
La idea era justamente de que vieras que no hay que perder de vista la legibilidad del código, y que puedes mejorar en eso :)

Saludos


En línea

Contribuye con la limpieza del foro, reporta los "casos perdidos" a un MOD XD
"Hay dos cosas infinitas: el Universo y la estupidez  humana. Y de la primera no estoy muy seguro."
Albert Einstein
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
« Respuesta #21 en: 14 Enero 2013, 08:09 am »

Para convertir un string a lower,upper,wordcase o titlecase, con opción de invertir el string

Código
  1. #Region " String To Case Function "
  2.  
  3.    ' [ String To Case Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(String_To_Case("ThiS is A TeST", StringCase.Lower))
  10.    ' MsgBox(String_To_Case("ThiS is A TeST", StringCase.Upper))
  11.    ' MsgBox(String_To_Case("ThiS is A TeST", StringCase.Word))
  12.    ' MsgBox(String_To_Case("ThiS is A TeST", StringCase.Title))
  13.    ' MsgBox(String_To_Case("ThiS is A TeST", StringCase.Title, True))
  14.  
  15.    Enum StringCase
  16.        Lower
  17.        Upper
  18.        Title
  19.        Word
  20.    End Enum
  21.  
  22.    Public Function String_To_Case(ByVal Input_String As String, ByVal StringCase As StringCase, Optional ByVal Reverse As Boolean = False) As String
  23.        If Not Input_String = Nothing And Not Input_String = "" Then
  24.            Dim Output_String As String = Nothing
  25.            Select Case StringCase
  26.                Case StringCase.Lower : Output_String = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToLower(Input_String)
  27.                Case StringCase.Upper : Output_String = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToUpper(Input_String)
  28.                Case StringCase.Title : Output_String = Char.ToUpper(Input_String(0)) + StrConv(Input_String.Substring(1), VbStrConv.Lowercase)
  29.                Case StringCase.Word : Output_String = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Input_String)
  30.            End Select
  31.            If Reverse Then Return Microsoft.VisualBasic.StrReverse(Output_String) Else Return Output_String
  32.        Else : Return False ' Any string to convert
  33.        End If
  34.    End Function
  35.  
  36. #End Region


« Última modificación: 14 Enero 2013, 10:59 am por EleKtro H@cker » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
« Respuesta #22 en: 15 Enero 2013, 05:05 am »

Make Dir, para crear directorios con opción de añadir atributos.

Código
  1. #Region " Make Dir Function "
  2.  
  3.    ' [ Make Dir Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(MakeDir("C:\Test"))
  10.  
  11.    Private Function Make_Dir(ByVal Path As String, Optional ByVal Attributes As System.IO.FileAttributes = IO.FileAttributes.Normal)
  12.        If My.Computer.FileSystem.DirectoryExists(Path) Then Return Nothing ' Directory already exists
  13.        Try
  14.            My.Computer.FileSystem.CreateDirectory(Path) ' Create directory
  15.            If Not Attributes = IO.FileAttributes.Normal Then My.Computer.FileSystem.GetDirectoryInfo(Path).Attributes = Attributes ' Apply Folder Attributes
  16.            Return True ' Directory is created OK
  17.        Catch ex As Exception
  18.            Return False ' Can't create the directory maybe because user permissions
  19.            ' Return ex.Message
  20.        End Try
  21.    End Function
  22.  
  23. #End Region
Copy File , para copiar archivos, con opción de crear el directorio si no existe, opción de reemplazar archivos, y opcion de aplicar atributos al archivo.

Código
  1. #Region " Copy File Function "
  2.  
  3.    ' [ Copy File Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' MsgBox(Copy_File("C:\File.txt", "C:\Test\")) ' Standard copy
  10.    ' MsgBox(Copy_File("C:\File.txt", "C:\Test\", True)) ' Create the directory if doesn't exists
  11.    ' MsgBox(Copy_File("C:\File.txt", "C:\Test\", , True)) ' Replace any existing file
  12.    ' MsgBox(Copy_File("C:\File.txt", "C:\Test\", , , IO.FileAttributes.Hidden + IO.FileAttributes.ReadOnly)) ' Apply new attributes
  13.  
  14.    Private Function Copy_File(ByVal File As String, ByVal Target_Path As String, _
  15.                               Optional ByVal Force_Target_Path As Boolean = False, Optional ByVal Force_File_Replace As Boolean = False, _
  16.                               Optional ByVal Attributes As System.IO.FileAttributes = IO.FileAttributes.Normal)
  17.  
  18.        Dim File_Information = My.Computer.FileSystem.GetFileInfo(File) ' Get Input File Information
  19.  
  20.        ' Directory
  21.        If Not Force_Target_Path And Not My.Computer.FileSystem.DirectoryExists(Target_Path) Then
  22.            Return False ' Target Directory don't exists
  23.        ElseIf Force_Target_Path Then
  24.            Try
  25.                My.Computer.FileSystem.CreateDirectory(Target_Path) ' Create directory
  26.            Catch ex As Exception
  27.                'Return False
  28.                Return ex.Message ' Directory can't be created maybe beacuse user permissions
  29.            End Try
  30.        End If
  31.  
  32.        ' File
  33.        Try
  34.            My.Computer.FileSystem.CopyFile(File, Target_Path & "\" & File_Information.Name, Force_File_Replace) ' Copies the file
  35.            If Not Attributes = IO.FileAttributes.Normal Then My.Computer.FileSystem.GetFileInfo(Target_Path & "\" & File_Information.Name).Attributes = Attributes ' Apply File Attributes
  36.            Return True ' File is copied OK
  37.        Catch ex As Exception
  38.            'Return False
  39.            Return ex.Message ' File can't be created maybe beacuse user permissions
  40.        End Try
  41.    End Function
  42.  
  43. #End Region
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
« Respuesta #23 en: 15 Enero 2013, 07:11 am »

Crea un acceso directo a una aplicación o a una página web, con muchas opciones.

Código
  1. #Region " Create ShortCut Function "
  2.  
  3.    ' [ Create ShortCut Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    '
  9.    ' Create_ShortCut(ShortcutPath.MyDocuments, "My APP Shortcut.lnk", "C:\File.exe")
  10.    ' Create_ShortCut(ShortcutPath.Desktop, "My CMD Shortcut.lnk", "CMD.exe", "/C Echo Hello World & Pause")
  11.    ' Create_ShortCut(ShortcutPath.Favorites, "My INTERNET Shortcut.lnk", "http://www.Google.com", , "CTRL+SHIFT+S")
  12.    ' Create_ShortCut(ShortcutPath.Favorites, "My INTERNET Shortcut.lnk", "http://www.Google.com", , "CTRL+SHIFT+S", "Description of the shortcut")
  13.  
  14.    Enum ShortcutPath
  15.        AppData = Environment.SpecialFolder.ApplicationData
  16.        Desktop = Environment.SpecialFolder.Desktop
  17.        Favorites = Environment.SpecialFolder.Favorites
  18.        LocalAppData = Environment.SpecialFolder.LocalApplicationData
  19.        MyDocuments = Environment.SpecialFolder.MyDocuments
  20.        ProgramFiles = Environment.SpecialFolder.ProgramFiles
  21.        ProgramFilesx86 = Environment.SpecialFolder.ProgramFilesX86
  22.        StartMenu = Environment.SpecialFolder.StartMenu
  23.        System32 = Environment.SpecialFolder.System
  24.        SysWOW64 = Environment.SpecialFolder.SystemX86
  25.        UserProfile = Environment.SpecialFolder.UserProfile
  26.        Windows = Environment.SpecialFolder.Windows
  27.    End Enum
  28.  
  29.    Function Create_ShortCut(ByVal Shortcut_Path As ShortcutPath, _
  30.                            ByVal Shortcut_Name As String, _
  31.                            ByVal APP As String, _
  32.                            Optional ByVal APP_Arguments As String = Nothing, _
  33.                            Optional ByVal HotKey As String = Nothing, _
  34.                            Optional ByVal Icon As String = Nothing, _
  35.                            Optional ByVal Description As String = Nothing) As Boolean
  36.  
  37.        Dim Dir = New IO.DirectoryInfo(System.Environment.GetFolderPath(Shortcut_Path))
  38.        Dim WorkingDir As IO.FileInfo
  39.        If Not APP.Contains("/") Then WorkingDir = New IO.FileInfo(APP) Else WorkingDir = Nothing
  40.        Try
  41.            Dim WSHShell As Object = CreateObject("WScript.Shell")
  42.            Dim Shortcut As Object
  43.            Shortcut = WSHShell.CreateShortcut(Dir.FullName & "\" & Shortcut_Name)
  44.            Shortcut.TargetPath = APP
  45.            Shortcut.Arguments = APP_Arguments
  46.            Shortcut.WindowStyle = 2
  47.            Shortcut.Hotkey = HotKey
  48.            Shortcut.Description = Description
  49.            If Not APP.Contains("/") Then Shortcut.WorkingDirectory = WorkingDir.DirectoryName
  50.            If Icon IsNot Nothing Then Shortcut.IconLocation = Icon Else Shortcut.IconLocation = APP
  51.            Shortcut.Save()
  52.            Return True
  53.        Catch ex As Exception
  54.            Return False
  55.        End Try
  56.    End Function
  57.  
  58. #End Region
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
« Respuesta #24 en: 15 Enero 2013, 07:33 am »

He añadido, ordenado, y mejorado bastantes snippets del pack de snippets, el nuevo enlace está en el comentario principal.

 
Función para eliminar atributos de un archivo, preservando el resto de atributos.

Código
  1. #Region " File Remove Attribute Function "
  2.  
  3.    ' [ File Remove Attribute Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' MsgBox(File_Remove_Attribute("C:\Test.txt", FileAttribute.ReadOnly))
  8.    ' MsgBox(File_Remove_Attribute("C:\Test.txt", FileAttribute.ReadOnly + FileAttribute.Hidden))
  9.  
  10.    Public Function File_Remove_Attribute(ByVal File As String, ByVal Remove_Attribute As FileAttribute) As Boolean
  11.        Try
  12.            Dim FileAttributes As FileAttribute = IO.File.GetAttributes(File)
  13.            IO.File.SetAttributes(File, FileAttributes And Not Remove_Attribute)
  14.            Return True
  15.        Catch ex As Exception
  16.            Return False
  17.        End Try
  18.    End Function
  19.  
  20. #End Region


Función para añadir atributos a un archivo, preservando el resto de atributos.

Código
  1. #Region " File Add Attribute Function "
  2.  
  3.    ' [ File Add Attribute Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' MsgBox(File_Add_Attribute("C:\Test.txt", FileAttribute.ReadOnly))
  8.    ' MsgBox(File_Add_Attribute("C:\Test.txt", FileAttribute.ReadOnly + FileAttribute.Hidden))
  9.  
  10.    Public Function File_Add_Attribute(ByVal File As String, ByVal Add_Attribute As FileAttribute) As Boolean
  11.        Try
  12.            Dim FileAttributes As FileAttribute = IO.File.GetAttributes(File)
  13.            IO.File.SetAttributes(File, FileAttributes Or Add_Attribute)
  14.            Return True
  15.        Catch ex As Exception
  16.            Return False
  17.        End Try
  18.    End Function
  19.  
  20. #End Region

Función que comprueba si un archivo tiene un atributo

Código
  1. #Region " File Have Attribute Function "
  2.  
  3.    ' [ File Have Attribute Function ]
  4.    '
  5.    ' Examples :
  6.    '
  7.    ' MsgBox(File_Have_Attribute("C:\Test.txt", FileAttribute.ReadOnly))
  8.    ' MsgBox(File_Have_Attribute("C:\Test.txt", FileAttribute.ReadOnly + FileAttribute.Hidden))
  9.  
  10.    Public Function File_Have_Attribute(ByVal File As String, ByVal CheckAttribute As FileAttribute) As Boolean
  11.        Try
  12.            Dim FileAttributes As FileAttribute = IO.File.GetAttributes(File)
  13.            If (FileAttributes And CheckAttribute) = CheckAttribute Then Return True Else Return False
  14.        Catch ex As Exception
  15.            Return Nothing
  16.        End Try
  17.  
  18.    End Function
  19.  
  20. #End Region
« Última modificación: 15 Enero 2013, 07:47 am por EleKtro H@cker » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
« Respuesta #25 en: 15 Enero 2013, 20:48 pm »

Oscurecer una imagen a escala de grises (Disable image)

PD: He retocado la función original para añadirle opción de elegir distintos tonos de gris, me ha quedado bastante bien.

Código
  1. #Region " GrayScale Image Function "
  2.  
  3.    ' [ GrayScale Image Function ]
  4.    '
  5.    ' Examples:
  6.    '
  7.    ' PictureBox1.Image = GrayScale_Image(PictureBox1.Image, GrayScale.Light_Gray)
  8.    ' PictureBox1.Image = GrayScale_Image(PictureBox1.Image, GrayScale.Mid_Gray)
  9.    ' PictureBox1.Image = GrayScale_Image(PictureBox1.Image, GrayScale.Dark_Gray)
  10.  
  11.    Enum GrayScale
  12.        Light_Gray
  13.        Mid_Gray
  14.        Dark_Gray
  15.    End Enum
  16.  
  17.    Private Function GrayScale_Image(ByVal Image As Image, ByVal Gray_Tone As GrayScale) As Bitmap
  18.        Dim Image_Bitmap As Bitmap = New Bitmap(Image.Width, Image.Height)
  19.        Dim Image_Graphic As Graphics = Graphics.FromImage(Image_Bitmap)
  20.        Dim Color_Matrix As System.Drawing.Imaging.ColorMatrix = Nothing
  21.        Select Case Gray_Tone
  22.            Case GrayScale.Light_Gray : Color_Matrix = New System.Drawing.Imaging.ColorMatrix(New Single()() {New Single() {0.2, 0.2, 0.2, 0, 0}, New Single() {0.2, 0.2, 0.2, 0, 0}, New Single() {0.5, 0.5, 0.5, 0, 0}, New Single() {0, 0, 0, 1, 0}, New Single() {0, 0, 0, 0, 1}})
  23.            Case GrayScale.Mid_Gray : Color_Matrix = New System.Drawing.Imaging.ColorMatrix(New Single()() {New Single() {0, 0, 0, 0, 0}, New Single() {0, 0, 0, 0, 0}, New Single() {0.5, 0.5, 0.5, 0, 0}, New Single() {0, 0, 0, 1, 0}, New Single() {0, 0, 0, 0, 1}})
  24.            Case GrayScale.Dark_Gray : Color_Matrix = New System.Drawing.Imaging.ColorMatrix(New Single()() {New Single() {0, 0, 0, 0, 0}, New Single() {0, 0, 0, 0, 0}, New Single() {0.2, 0.2, 0.2, 0, 0}, New Single() {0, 0, 0, 1, 0}, New Single() {0, 0, 0, 0, 1}})
  25.        End Select
  26.        Dim Image_Attributes As System.Drawing.Imaging.ImageAttributes = New System.Drawing.Imaging.ImageAttributes()
  27.        Image_Attributes.SetColorMatrix(Color_Matrix)
  28.        Image_Graphic.DrawImage(Image, New Rectangle(0, 0, Image.Width, Image.Height), 0, 0, Image.Width, Image.Height, GraphicsUnit.Pixel, Image_Attributes)
  29.        Image_Graphic.Dispose()
  30.        Return Image_Bitmap
  31.    End Function
  32.  
  33. #End Region
En línea

ABDERRAMAH


Desconectado Desconectado

Mensajes: 431


en ocasiones uso goto ¬¬


Ver Perfil WWW
Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
« Respuesta #26 en: 16 Enero 2013, 06:45 am »

Interesante!

Podrías también, si quieres, pasar la imágen por referencia, como hago yo. Ésto es para no duplicarla, así trabajamos sobre la misma imágen de entrada. Ahorra memoria aunque realizará el cambio aunque no hagamos:

img = grayscale_image(img,grayscale.mid_gray)
« Última modificación: 16 Enero 2013, 07:42 am por ABDERRAMAH » En línea

spiritdead

Desconectado Desconectado

Mensajes: 296


Ver Perfil
Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
« Respuesta #27 en: 16 Enero 2013, 07:44 am »

Interesante!

Podrías también, si quieres, pasar la imágen por referencia, como hago yo. Ésto es para no duplicarla, así trabajamos sobre la misma imágen de entrada. Ahorra memoria aunque realizará el cambio aunque no hagamos:

img = grayscale_image(img,grayscale.mid_gray)

en vez de usar 1 function usa 1 sub ....
En línea

Facilitador De Tareas - Task Simplifier (FDT)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
« Respuesta #28 en: 16 Enero 2013, 19:15 pm »

Podrías también, si quieres, pasar la imágen por referencia, como hago yo. Ésto es para no duplicarla, así trabajamos sobre la misma imágen de entrada. Ahorra memoria aunque realizará el cambio aunque no hagamos:

No conocía esos beneficios de ByRef, gracias!
En línea

Novlucker
Ninja y
Colaborador
***
Desconectado Desconectado

Mensajes: 10.683

Yo que tu lo pienso dos veces


Ver Perfil
Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
« Respuesta #29 en: 16 Enero 2013, 20:20 pm »

No conocía esos beneficios de ByRef, gracias!
Tienes que intentar mejorar tus conceptos  :¬¬ es algo bastante básico
En línea

Contribuye con la limpieza del foro, reporta los "casos perdidos" a un MOD XD
"Hay dos cosas infinitas: el Universo y la estupidez  humana. Y de la primera no estoy muy seguro."
Albert Einstein
Páginas: 1 2 [3] 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ... 58 Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines