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 3 Visitantes están viendo este tema.
Páginas: 1 [2] 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ... 59 Ir Abajo Respuesta Imprimir
Autor Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)  (Leído 484,310 veces)
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.807



Ver Perfil
Re: [APORTE] Snippets (ACTUALIZADO 11/01/2013)
« Respuesta #10 en: 11 Enero 2013, 09:39 am »

Para una aplicación necesité dividir el tamaño de unos MEgaBytes entre la capacidad de un DVD5, así que ya puestos he hecho este snippet que divide el tamaño entre varios formatos de discos, para la próxima ocasión.

PD: Las medidas están sacadas de la Wikipedia, para los más...  :-X

Saludos.

Código
  1.    ' Usage:
  2.    '
  3.    ' MsgBox(ConvertToDiscSize(737280000, "Bytes", "CD"))
  4.    ' MsgBox(ConvertToDiscSize(700, "MB", "CD"))
  5.    ' MsgBox(Math.Ceiling(ConvertToDiscSize(6.5, "GB", "DVD")))
  6.    ' MsgBox(ConvertToDiscSize(40, "GB", "BR").ToString.Substring(0, 3) & " Discs")
  7.  
  8. #Region " Convert To Disc Size function"
  9.    Private Function ConvertToDiscSize(ByVal FileSize As Double, ByVal FileKindSize As String, ByVal To_DiscKindCapacity As String)
  10.  
  11.        ' KindSize Measures:
  12.        ' --------------------------
  13.        ' Bytes
  14.        ' KB
  15.        ' MB
  16.        ' GB
  17.  
  18.        ' ToDiscKind Measures:
  19.        ' -----------------------------
  20.        ' CD
  21.        ' CD800
  22.        ' CD900
  23.        ' DVD
  24.        ' DVD-DL
  25.        ' BR
  26.        ' BR-DL
  27.        ' BR-3L
  28.        ' BR-4L
  29.        ' BR-MD
  30.        ' BR-MD-DL
  31.  
  32.  
  33.        ' Bytes
  34.        If FileKindSize.ToUpper = "BYTES" Then
  35.            If To_DiscKindCapacity.ToUpper = "CD" Then Return FileSize / 737280000 ' CD Standard
  36.            If To_DiscKindCapacity.ToUpper = "CD800" Then Return FileSize / 829440393.216 ' CD 800 MB
  37.            If To_DiscKindCapacity.ToUpper = "CD900" Then Return FileSize / 912383803.392 ' CD 900 MB
  38.            If To_DiscKindCapacity.ToUpper = "DVD" Then Return FileSize / 4700000000 ' DVD Standard (DVD5
  39.            If To_DiscKindCapacity.ToUpper = "DVD-DL" Then Return FileSize / 8500000000 ' DVD Double Layer (DVD9)
  40.            If To_DiscKindCapacity.ToUpper = "BR" Then Return FileSize / 25025314816 ' BluRay Standard
  41.            If To_DiscKindCapacity.ToUpper = "BR-DL" Then Return FileSize / 50050629632 ' BluRay Double Layer
  42.            If To_DiscKindCapacity.ToUpper = "BR-3L" Then Return FileSize / 100103356416 ' BluRay x3 Layers
  43.            If To_DiscKindCapacity.ToUpper = "BR-4L" Then Return FileSize / 128001769472 ' BluRay x4 Layers
  44.            If To_DiscKindCapacity.ToUpper = "BR-MD" Then Return FileSize / 7791181824 ' BluRay MiniDisc Standard
  45.            If To_DiscKindCapacity.ToUpper = "BR-MD-DL" Then Return FileSize / 15582363648 ' BluRay MiniDisc Double Layer
  46.  
  47.            ' KB
  48.        ElseIf FileKindSize.ToUpper = "KB" Then
  49.            If To_DiscKindCapacity.ToUpper = "CD" Then Return FileSize / 720000 ' CD Standard
  50.            If To_DiscKindCapacity.ToUpper = "CD800" Then Return FileSize / 810000.384 ' CD 800 MB
  51.            If To_DiscKindCapacity.ToUpper = "CD900" Then Return FileSize / 890999.808 ' CD 900 MB
  52.            If To_DiscKindCapacity.ToUpper = "DVD" Then Return FileSize / 4589843.75 ' DVD Standard (DVD5)
  53.            If To_DiscKindCapacity.ToUpper = "DVD-DL" Then Return FileSize / 8300781.25 ' DVD Double Layer (DVD9)
  54.            If To_DiscKindCapacity.ToUpper = "BR" Then Return FileSize / 24438784 ' BluRay Standard
  55.            If To_DiscKindCapacity.ToUpper = "BR-DL" Then Return FileSize / 48877568 ' BluRay Double Layer
  56.            If To_DiscKindCapacity.ToUpper = "BR-3L" Then Return FileSize / 97757184 ' BluRay x3 Layers
  57.            If To_DiscKindCapacity.ToUpper = "BR-4L" Then Return FileSize / 125001728 ' BluRay x4 Layers
  58.            If To_DiscKindCapacity.ToUpper = "BR-MD" Then Return FileSize / 7608576 ' BluRay MiniDisc Standard
  59.            If To_DiscKindCapacity.ToUpper = "BR-MD-DL" Then Return FileSize / 15217152 ' BluRay MiniDisc Double Layer
  60.  
  61.            ' MB
  62.        ElseIf FileKindSize.ToUpper = "MB" Then
  63.            If To_DiscKindCapacity.ToUpper = "CD" Then Return FileSize / 703.125 ' CD Standard
  64.            If To_DiscKindCapacity.ToUpper = "CD800" Then Return FileSize / 791.016 ' CD 800 MB
  65.            If To_DiscKindCapacity.ToUpper = "CD900" Then Return FileSize / 870.117 ' CD 900 MB
  66.            If To_DiscKindCapacity.ToUpper = "DVD" Then Return FileSize / 4482.26929 ' DVD Standard (DVD5)
  67.            If To_DiscKindCapacity.ToUpper = "DVD-DL" Then Return FileSize / 8106.23169 ' DVD Double Layer (DVD9)
  68.            If To_DiscKindCapacity.ToUpper = "BR" Then Return FileSize / 23866 ' BluRay Standard
  69.            If To_DiscKindCapacity.ToUpper = "BR-DL" Then Return FileSize / 47732 ' BluRay Double Layer
  70.            If To_DiscKindCapacity.ToUpper = "BR-3L" Then Return FileSize / 95466 ' BluRay x3 Layers
  71.            If To_DiscKindCapacity.ToUpper = "BR-4L" Then Return FileSize / 122072 ' BluRay x4 Layers
  72.            If To_DiscKindCapacity.ToUpper = "BR-MD" Then Return FileSize / 7430.25 ' BluRay MiniDisc Standard
  73.            If To_DiscKindCapacity.ToUpper = "BR-MD-DL" Then Return FileSize / 14860.5 ' BluRay MiniDisc Double Layer
  74.  
  75.            ' GB
  76.        ElseIf FileKindSize.ToUpper = "GB" Then
  77.            If To_DiscKindCapacity.ToUpper = "CD" Then Return FileSize / 0.68665 ' CD Standard
  78.            If To_DiscKindCapacity.ToUpper = "CD800" Then Return FileSize / 0.77248 ' CD 800 MB
  79.            If To_DiscKindCapacity.ToUpper = "CD900" Then Return FileSize / 0.84972 ' CD 900 MB
  80.            If To_DiscKindCapacity.ToUpper = "DVD" Then Return FileSize / 4.37722 ' DVD Standard (DVD5)
  81.            If To_DiscKindCapacity.ToUpper = "DVD-DL" Then Return FileSize / 7.91624 ' DVD Double Layer (DVD9)
  82.            If To_DiscKindCapacity.ToUpper = "BR" Then Return FileSize / 23.30664 ' BluRay Standard
  83.            If To_DiscKindCapacity.ToUpper = "BR-DL" Then Return FileSize / 46.61328 ' BluRay Double Layer
  84.            If To_DiscKindCapacity.ToUpper = "BR-3L" Then Return FileSize / 93.22852 ' BluRay x3 Layers
  85.            If To_DiscKindCapacity.ToUpper = "BR-4L" Then Return FileSize / 119.21094 ' BluRay x4 Layers
  86.            If To_DiscKindCapacity.ToUpper = "BR-MD" Then Return FileSize / 7.2561 ' BluRay MiniDisc Standard
  87.            If To_DiscKindCapacity.ToUpper = "BR-MD-DL" Then Return FileSize / 14.51221 ' BluRay MiniDisc Double Layer
  88.        End If
  89.  
  90.        Return Nothing ' Argument measure not found
  91.  
  92.    End Function
  93. #End Region


En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.807



Ver Perfil
Re: [APORTE] Snippets (ACTUALIZADO 12/01/2013) Posteen aquí sus snippets!!
« Respuesta #11 en: 12 Enero 2013, 18:00 pm »

He actualizado el pack de Snippets en el post principal (Antes eran 76, ahora 114)

Si alguien quiere que incluya un pack con sus snippets en el post principal porfavor que me pase los snippets en formato de snippet (Archivo.snippet).

Y añado este snippet, un delimitador de strings, es parecido al método "Split", pero bajo mi opinión lo he mejorado bastante!

· Acepta 1 o 2 delimitadores,
· Opción de IgnoreCase
· Delimitar de izquierda a derecha o de derecha a izquierda.

Saludos!

Código
  1. #Region " Delimit_String Function "
  2.  
  3.    ' // By Elektro H@ker
  4.    '
  5.    ' USAGE:
  6.    '
  7.    ' MsgBox(Delimit_String("Welcome to my new house", "to")) ' my new house
  8.    ' MsgBox(Delimit_String("Welcome to my new house", "to", "house")) ' my new
  9.    ' MsgBox(Delimit_String("Welcome to my new house", "TO", "HoUSe", True)) ' my new
  10.    ' MsgBox(Delimit_String("Welcome to my new house", "house", "to", , "Left")) ' my new
  11.    ' MsgBox(Delimit_String("Welcome to my new house", "TO", "HoUSe", False)) ' False
  12.    ' MsgBox(Delimit_String("Welcome to my new house", "to", "to", , "Left")) ' Index was outside bounds of the array
  13.  
  14.    Private Function Delimit_String(ByVal STR As String, ByVal Delimiter_A As String, Optional ByVal Delimiter_B As String = "", Optional ByVal Ignore_Case As Boolean = False, Optional ByVal Left_Or_Right As String = "Right")
  15.        Dim Compare_Method As Integer = 0 ' Don't ignore case
  16.        If Ignore_Case = True Then Compare_Method = 1 ' Ignore Case
  17.  
  18.        If Not Left_Or_Right.ToUpper = "LEFT" And Not Left_Or_Right.ToUpper = "RIGHT" _
  19.            Then Return False ' Returns false if the Left_Or_Right argument is in incorrect format
  20.  
  21.        If Compare_Method = 0 Then
  22.            If Not STR.Contains(Delimiter_A) Or Not STR.Contains(Delimiter_B) _
  23.                Then Return False ' Returns false if one of the delimiters in NormalCase can 't be found
  24.        Else
  25.            If Not STR.ToUpper.Contains(Delimiter_A.ToUpper) Or Not STR.ToUpper.Contains(Delimiter_B.ToUpper) _
  26.            Then Return False ' Returns false if one of the delimiters in IgnoreCase can 't be found
  27.        End If
  28.  
  29.        Try
  30.            If Left_Or_Right.ToUpper = "LEFT" Then STR = Split(STR, Delimiter_A, , Compare_Method)(0) _
  31.                Else If Left_Or_Right.ToUpper = "RIGHT" Then STR = Split(STR, Delimiter_A, , Compare_Method)(1)
  32.  
  33.            If Delimiter_B IsNot Nothing Then
  34.                If Left_Or_Right.ToUpper = "LEFT" Then STR = Split(STR, Delimiter_B, , Compare_Method)(1) _
  35.                 Else If Left_Or_Right.ToUpper = "RIGHT" Then STR = Split(STR, Delimiter_B, , Compare_Method)(0)
  36.            End If
  37.  
  38.            Return STR ' Returns the splitted string
  39.        Catch ex As Exception
  40.            Return ex.Message ' Returns exception if index is out of range
  41.        End Try
  42.    End Function
  43.  
  44. #End Region



« Última modificación: 12 Enero 2013, 18:56 pm por EleKtro H@cker » En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.807



Ver Perfil
Re: [APORTE] Snippets (ACTUALIZADO 12/01/2013) Posteen aquí sus snippets!!
« Respuesta #12 en: 12 Enero 2013, 20:36 pm »

Otro convertidor, en esta ocasión un convertidor de tiempo, ms, segundos, minutos, horas.


Código
  1. #Region " Convert Time Function"
  2.  
  3.    ' // By Elektro H@cker
  4.    '
  5.    ' MsgBox(Convert_Time(1, "h", "m"))
  6.    ' MsgBox(Convert_Time(1, "h", "s"))
  7.    ' MsgBox(Convert_Time(1, "h", "ms"))
  8.    ' MsgBox(Convert_Time(6000, "milliseconds", "seconds"))
  9.    ' MsgBox(Convert_Time(6000, "seconds", "minutes"))
  10.    ' MsgBox(Convert_Time(6000, "minutes", "hours"))
  11.  
  12.    Private Function Convert_Time(ByVal Time As Int64, ByVal Input_Time_Format As String, ByVal Output_Time_Format As String)
  13.        Dim Time_Span As New TimeSpan
  14.        If Input_Time_Format.ToUpper = "MS" Or Output_Time_Format.ToUpper = "MILLISECONDS" Then Time_Span = New TimeSpan(TimeSpan.TicksPerMillisecond * Time)
  15.        If Input_Time_Format.ToUpper = "S" Or Output_Time_Format.ToUpper = "SECONDS" Then Time_Span = New TimeSpan(TimeSpan.TicksPerSecond * Time)
  16.        If Input_Time_Format.ToUpper = "M" Or Output_Time_Format.ToUpper = "MINUTES" Then Time_Span = New TimeSpan(TimeSpan.TicksPerMinute * Time)
  17.        If Input_Time_Format.ToUpper = "H" Or Output_Time_Format.ToUpper = "HOURS" Then Time_Span = New TimeSpan(TimeSpan.TicksPerHour * Time)
  18.        If Output_Time_Format.ToUpper = "MS" Or Output_Time_Format.ToUpper = "MILLISECONDS" Then Return Time_Span.TotalMilliseconds
  19.        If Output_Time_Format.ToUpper = "S" Or Output_Time_Format.ToUpper = "SECONDS" Then Return Time_Span.TotalSeconds
  20.        If Output_Time_Format.ToUpper = "M" Or Output_Time_Format.ToUpper = "MINUTES" Then Return Time_Span.TotalMinutes
  21.        If Output_Time_Format.ToUpper = "H" Or Output_Time_Format.ToUpper = "HOURS" Then Return Time_Span.TotalHours
  22.        Return False ' Returns false if argument is in incorrect format
  23.    End Function
  24.  
  25. #End Region
  26.  
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.807



Ver Perfil
Re: [APORTE] Snippets (ACTUALIZADO 12/01/2013) Posteen aquí sus snippets!!
« Respuesta #13 en: 12 Enero 2013, 23:30 pm »

Set_PC_State

Código
  1.    ' // By Elektro H@cker
  2.  
  3.    ' USAGE:
  4.    '
  5.    ' Set_PC_State(RESET)
  6.    ' Set_PC_State(SUSPEND, 30, "I'm suspending your system.")
  7.    ' Set_PC_State(LOG_OFF)
  8.    ' Set_PC_State(HIBERN)
  9.    ' Set_PC_State(ABORT)
  10.  
  11. #Region " Set PC State "
  12.  
  13.    Const RESET As String = " -R "
  14.    Const SUSPEND As String = " -S "
  15.    Const LOG_OFF As String = " -L "
  16.    Const HIBERN As String = " -H "
  17.    Const ABORT As String = " -A "
  18.  
  19.    Private Function Set_PC_State(ByVal PowerState_Action As String, Optional ByVal TimeOut As Integer = 1, Optional ByVal COMMENT As String = "")
  20.  
  21.        Dim Shutdown_Command As New ProcessStartInfo
  22.        Shutdown_Command.FileName = "Shutdown.exe"
  23.  
  24.        Try
  25.            If PowerState_Action = ABORT Or PowerState_Action = HIBERN Or PowerState_Action = LOG_OFF Then
  26.                Shutdown_Command.Arguments = PowerState_Action ' Windows don't allow TimeOut or Comment options for HIBERN, LOG_OFF or ABORT actions.
  27.            ElseIf PowerState_Action = RESET Or PowerState_Action = SUSPEND Then
  28.                If Not COMMENT = "" Then
  29.                    If COMMENT.Length > 512 Then COMMENT = COMMENT.Substring(0, 512) ' Only 512 chars are allowed for comment
  30.                    Shutdown_Command.Arguments = PowerState_Action & " -T " & TimeOut & " /C " & COMMENT
  31.                Else
  32.                    Shutdown_Command.Arguments = PowerState_Action & " -T " & TimeOut
  33.                End If
  34.                Shutdown_Command.WindowStyle = ProcessWindowStyle.Hidden
  35.                Process.Start(Shutdown_Command)
  36.                Return True
  37.            End If
  38.        Catch ex As Exception
  39.            Return ex.Message
  40.        End Try
  41.  
  42.        Return Nothing ' Invalid argument
  43.    End Function
  44.  
  45. #End Region





Día local:

Código
  1. Dim Today as string = My.Computer.Clock.LocalTime.DayOfWeek ' In English language
  2.  
  3. Dim Today as string = System.Globalization.DateTimeFormatInfo.CurrentInfo.GetDayName(Date.Today.DayOfWeek) ' In system language




String is URL?

Código
  1.    ' USAGE:
  2.    '
  3.    ' If String_Is_URL("http://google.com") Then MsgBox("Valid url!") Else MsgBox("Invalid url!")
  4.  
  5. #Region " String Is URL Function "
  6.  
  7.    Private Function String_Is_URL(ByVal STR As String)
  8.        Dim URL_Pattern As String = "^(http|https):/{2}[a-zA-Z./&\d_-]+"
  9.        Dim URL_RegEx As New System.Text.RegularExpressions.Regex(URL_Pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase Or System.Text.RegularExpressions.RegexOptions.ExplicitCapture)
  10.        If URL_RegEx.IsMatch(STR) Then Return True Else Return False
  11.    End Function
  12.  
  13. #End Region




G-Mail Sender (Envía emails)

Código
  1.    ' USAGE:
  2.    '
  3.    ' GMail_Sender("Your_Email@Gmail.com", "Your_Password", "Email Subject", "Message Body", "Destiny@Email.com")
  4.  
  5. #Region " GMail Sender function "
  6.  
  7.    Private Function GMail_Sender(ByVal Gmail_Username As String, ByVal Gmail_Password As String, ByVal Email_Subject As String, ByVal Email_Body As String, ByVal Email_Destiny As String)
  8.        Try
  9.            Dim MailSetup As New System.Net.Mail.MailMessage
  10.            MailSetup.Subject = Email_Subject
  11.            MailSetup.To.Add(Email_Destiny)
  12.            MailSetup.From = New System.Net.Mail.MailAddress(Gmail_Username)
  13.            MailSetup.Body = Email_Body
  14.            Dim SMTP As New System.Net.Mail.SmtpClient("smtp.gmail.com")
  15.            SMTP.Port = 587
  16.            SMTP.EnableSsl = True
  17.            SMTP.Credentials = New Net.NetworkCredential(Gmail_Username, Gmail_Password)
  18.            SMTP.Send(MailSetup)
  19.            Return True ' Email is sended OK
  20.        Catch ex As Exception
  21.            Return ex.Message ' Email can't be sended
  22.        End Try
  23.    End Function
  24.  
  25. #End Region

En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.807



Ver Perfil
Re: [APORTE] Snippets (ACTUALIZADO 12/01/2013) Posteen aquí sus snippets!!
« Respuesta #14 en: 13 Enero 2013, 07:34 am »

Get OS Version

Código
  1.        Dim OS_Version As String = System.Environment.OSVersion.ToString
  2.        MsgBox(OS_Version)



String Is Email

Código
  1.    ' // By Elektro H@cker
  2.    '
  3.    ' USAGE:
  4.    '
  5.    ' MsgBox(String_Is_Email("User@Email.com"))
  6.  
  7. #Region " String Is Email Function "
  8.  
  9.    Private Function String_Is_Email(ByVal Email_String As String)
  10.        Dim Emaill_RegEx As New System.Text.RegularExpressions.Regex("^[A-Za-z0-9][A-Za-z0-9]+\@[A-Za-z0-9]+\.[A-Za-z0-9][A-Za-z0-9]+$")
  11.        If Emaill_RegEx.IsMatch(Email_String) Then Return True Else Return False
  12.    End Function
  13.  
  14. #End Region



Get Random Password

Código
  1.    ' USAGE:
  2.    '
  3.    ' MsgBox(Get_Random_Password(8))
  4.    ' MsgBox(Get_Random_Password(36))
  5.  
  6. #Region " Get Random Password Function "
  7.  
  8.    Public Function Get_Random_Password(ByVal Password_Length As Double) As String
  9.        Dim New_Password As String = System.Guid.NewGuid.ToString
  10.        If Password_Length <= 0 OrElse Password_Length > New_Password.Length Then
  11.            Throw New ArgumentException("Length must be between 1 and " & New_Password.Length)
  12.        End If
  13.        Return New_Password.Substring(0, Password_Length)
  14.    End Function
  15.  
  16. #End Region



Get Printers

Código
  1.    ' // By Elektro H@cker
  2.    '
  3.    ' USAGE:
  4.    '
  5.    '  For Each Printer_Name In Get_Printers() : MsgBox(Printer_Name) : Next
  6.  
  7.    Private Function Get_Printers()
  8.        Dim Printer_Array As New List(Of String)
  9.        Try
  10.            For Each Printer_Name As String In System.Drawing.Printing.PrinterSettings.InstalledPrinters : Printer_Array.Add(Printer_Name) : Next
  11.        Catch ex As Exception
  12.            If ex.Message.Contains("RPC") Then Return "RPC Service is not avaliable"
  13.        End Try
  14.        Return Printer_Array
  15.    End Function
En línea

ABDERRAMAH


Desconectado Desconectado

Mensajes: 431


en ocasiones uso goto ¬¬


Ver Perfil WWW
Re: [APORTE] Snippets (ACTUALIZADO 12/01/2013) Posteen aquí sus snippets!!
« Respuesta #15 en: 13 Enero 2013, 15:45 pm »

Pues yo tengo una colección de funciones para crear, cargar y superponer imágenes así como para escribir texto usando gdi+:

cargar una imágen en una resolución determinada:
Código
  1.  
  2. Public Function read_image_at_res(ByRef file As String, ByRef force_sizex As Integer, ByRef force_sizey As Integer) As System.Drawing.Bitmap
  3.        Dim img As New Bitmap(file)
  4.        Dim b As New Bitmap(force_sizex, force_sizey)
  5.        Dim bg As Graphics = Graphics.FromImage(b)
  6.        Try
  7.            bg.DrawImage(img, New Rectangle(New Point(0, 0), New Size(force_sizex, force_sizey)), New Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel)
  8.        Catch ex As Exception
  9.  
  10.        End Try
  11.        bg.Dispose()
  12.        Return b
  13.    End Function
  14.  

redimensionar una imágen:
Código
  1.  
  2. Public Function resize_bmp(ByRef img As Bitmap, ByRef sizex As Integer, ByRef sizey As Integer) As Bitmap
  3.        Dim b As New Bitmap(sizex, sizey)
  4.        Dim bg As Graphics = Graphics.FromImage(b)
  5.        bg.DrawImage(img, New Rectangle(New Point(0, 0), New Size(sizex, sizey)), New Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel)
  6.        bg.Dispose()
  7.        Return b
  8.    End Function
  9.  

superponer dos imágenes sobre un lienzo:
Código
  1.  
  2. Public Function layer_sum(ByRef layer1 As Bitmap, ByRef layer2 As Bitmap) As Bitmap
  3.        Dim bg As Graphics = Graphics.FromImage(layer1)
  4.        bg.DrawImage(layer2, New Point(0, 0))
  5.        bg.Dispose()
  6.        Return layer1
  7. End Function
  8.  

escribir texto plano(con sombreado rudimentario) en un fondo transparente:
Código
  1.  
  2.    Public Function get_text_layer(ByRef size As System.Drawing.Size, ByRef text As String) As System.Drawing.Bitmap
  3.        Dim img As New Bitmap(size.Width, size.Height)
  4.        Dim bg As Graphics = Graphics.FromImage(img)
  5.        bg.DrawString(text, New Font("Lucida Console", 12, FontStyle.Bold), Brushes.Gray, New Point(1, -1))
  6.        bg.DrawString(text, New Font("Lucida Console", 12, FontStyle.Bold), Brushes.White, New Point(0, 0))
  7.        bg.Dispose()
  8.        Return img
  9.    End Function
  10.  

dividir la imagen en sectores y devolver el indicado por "index":
Código
  1.  
  2.    Public Function get_portion(ByRef image As System.Drawing.Bitmap, ByRef cuadriculax As Short, ByRef cuadriculay As Short, ByRef index As Integer) As System.Drawing.Bitmap
  3.        Dim img As New Bitmap(CInt(image.Size.Width / cuadriculax), CInt(image.Size.Height / cuadriculay))
  4.        'Dim b As New Bitmap(CInt(image.Size.Width / cuadriculax), CInt(image.Size.Height / cuadriculay))
  5.        Dim bg As Graphics = Graphics.FromImage(img)
  6.        Dim xcount = 0
  7.        Dim ycount = 0
  8.        Do While index >= cuadriculax
  9.            index = index - cuadriculax
  10.            ycount = ycount + 1
  11.        Loop
  12.        xcount = index
  13.        Dim tmpx As Integer = CInt((image.Size.Width / cuadriculax) * xcount)
  14.        Dim tmpy As Integer = CInt((image.Size.Height / cuadriculay) * ycount)
  15.        Dim port As New Rectangle(New System.Drawing.Point(0, 0), New Size(New Point(CInt(image.Size.Width / cuadriculax), CInt(image.Size.Height / cuadriculay))))
  16.        bg.DrawImage(image, port, tmpx, tmpy, CInt(port.Size.Width), CInt(port.Size.Height), GraphicsUnit.Pixel)
  17.        bg.Dispose()
  18.        Return img
  19.    End Function
  20.  
En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.807



Ver Perfil
Re: [APORTE] Snippets (ACTUALIZADO 12/01/2013) Posteen aquí sus snippets!!
« Respuesta #16 en: 13 Enero 2013, 18:32 pm »

@ABDERRAMAH

Muy buenos, el primero y el segundo me gustaron mucho, siempre tengo problemas para redimensionar imagenes y me viene bien.

El último también, es una idea muy dinámica lo de dividir la imagen en una cuadrícula y tomar un sector, no sé si eres el autor de las funciones pero a pocos se le habría ocurrido hacer algo así xD

Saludos!
En línea

ABDERRAMAH


Desconectado Desconectado

Mensajes: 431


en ocasiones uso goto ¬¬


Ver Perfil WWW
Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
« Respuesta #17 en: 13 Enero 2013, 21:38 pm »

Soy autor, si, aunque la idea de crear el objeto graphics y después destruirlo, en lugar de tener uno fijo para todo la vi en unos códigos de msdn.
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 #18 en: 13 Enero 2013, 23:29 pm »

Bueno, lo siguiente son sugerencias, críticas o comentarios sobre algunos de los snippets que has puesto en el post, así como algo más genérico sobre como estructuras tus métodos o funciones, y el código en general.

  • Es aconsejable declarar el tipo de retorno de las funciones en su declaración. Para alguien que no tiene claro el objetivo de una función es mucho más legible hacerlo de este modo, de lo contrario hay que revisar el código de la función en busca de los Return para darse cuenta de que la función retorna un booleano por ejemplo.

Código
  1. Private Function Funcion() As Boolean

  • Función Attrib. Ya que estás creando una función que te abstrae de verificar la existencia de un archivo y asignar atributos, tal vez lo mejor sería que la función reciba una lista de atributos en lugar de un atributo global. Es decir, en este caso al utilizar tu función es necesario pasar la suma de los atributos para que asigne varios (como en la función original), pero por que no abstraerse un poco más y olvidarse de la suma?

Código
  1.    Private Function Attrib(ByVal File As String, ByVal Attributes As List(Of System.IO.FileAttributes)) As Boolean
  2.        If IO.File.Exists(File) Then
  3.            Try
  4.                FileSystem.SetAttr(File, Attributes.Select(Function(a) DirectCast(a, Integer)).Sum())
  5.                Return True ' File was modified OK
  6.            Catch ex As Exception
  7.                ' MsgBox(ex.Message)
  8.                Return False ' File can't be modified maybe because User Permissions
  9.            End Try
  10.        Else
  11.            Return Nothing ' File doesn't exist
  12.        End If
  13.    End Function

  • "Controlar el mismo evento para varios controles". No es aconsejable tener un solo método con condiciones para cada control por separado, lo recomendado es tener un método por evento. Si necesitas realizar algo en específico para un control en especial, entonces asigna un método diferente al control.
  • Función ConvertToDiscSize. Si debes de pasar un string a una función, para luego tomar una decisión según se trate de un string u otro, debes de plantearte declarar un enumerador (esto mismo es aplicable a otras de tus funciones). Por otra parte, tampoco es recomendable tener todos los valores hardcodeados en un método, además de que estás repitiendo mucho código. A continuación una variante de la función reestructrada;

Código
  1. #Region " Convert To Disc Size function"
  2.  
  3. Private Function ConvertToDiscSize(ByVal fileSize As Double, ByVal fileKindSize As MagnitudeType, ByVal to_DiscKindCapacity As DiscType) As Double
  4.    Dim size As Double = GetSize(to_DiscKindCapacity)
  5.    If (size < 0) Then Throw New ArgumentException("Tamaño de disco no localizado")
  6.    Return fileSize * DirectCast(fileKindSize, Integer) / size
  7. End Function
  8.  
  9. Enum MagnitudeType
  10.    Bytes = 1
  11.    KB = 1024
  12.    MB = 1048576
  13.    GB = 1073741824
  14. End Enum
  15.  
  16. Enum DiscType
  17.    CD
  18.    CD800
  19.    CD900
  20.    DVD
  21.    DVD_DL
  22.    BR
  23.    BR_DL
  24.    BR_3L
  25.    BR_4L
  26.    BR_MD
  27.    BR_MD_DL
  28. End Enum
  29.  
  30. Private Function GetSize(ByVal discType As DiscType) As Double
  31.    Select Case discType
  32.        Case DiscType.CD
  33.            Return 737280000      ' CD Standard
  34.        Case DiscType.CD800
  35.            Return 829440393.216 ' CD 800 MB
  36.        Case DiscType.CD900
  37.            Return 912383803.392 ' CD 900 MB
  38.        Case DiscType.DVD
  39.            Return 4700000000 ' DVD Standard (DVD5
  40.        Case DiscType.DVD_DL
  41.            Return 8500000000 ' DVD Double Layer (DVD9)
  42.        Case DiscType.BR
  43.            Return 25025314816 ' BluRay Standard
  44.        Case DiscType.BR_DL
  45.            Return 50050629632 ' BluRay Double Layer
  46.        Case DiscType.BR_3L
  47.            Return 100103356416 ' BluRay x3 Layers
  48.        Case DiscType.BR_4L
  49.            Return 128001769472 ' BluRay x4 Layers
  50.        Case DiscType.BR_MD
  51.            Return 7791181824 ' BluRay MiniDisc Standard
  52.        Case DiscType.BR_MD_DL
  53.            Return 15582363648 ' BluRay MiniDisc Double Layer
  54.        Case Else
  55.            Return -1 ' Por si se declara un nuevo valor en el enumerador sin especificar tamaño
  56.    End Select
  57. End Function
  58.  
  59. #End Region

Creo que por el momento es todo lo que se me ocurre, en otro momento vuelvo a mirar :P

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.807



Ver Perfil
Re: [APORTE] Snippets !! (Posteen aquí sus snippets)
« Respuesta #19 en: 14 Enero 2013, 03:01 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, y segundo, gracias por colocarle chincheta al tema (Quien haya sido xD), a ver si la gente se anima a compartir funciones/snippets.

Voy por partes:



1.
Sincéramente yo no le daba nada de importancia a definir el tipo de retorno de una función, ¿Porque?, pues no sé, quizás séa porque como muchas funciones las he hecho yo pues sé perfectamente que tipo de valor devuelven y no debo fijarme en esos detalles que comentas, o simplemente no le he dado importancia sin razón alguna, pero me lo has hecho ver de una manera en la que no me habia fijado, y te aseguro que estoy editando los 124 snippets definiendo el tipo de retorno de cada uno xD.

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?.



2.
Con tu modificación que le has hecho a la función de los atributos me has dejado loco!

Diréctamente no la entiendo...

Código:
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

Bueno, el método "Sum" ya he visto que crea una sequencia parecida a esto:
Código:
32 + 64
Lo que equivale a los valores para cambiar los atributos, vale, pero el proceso que haces para llegar a generar esa secuencia... ni idea :xD.

Lo peor de todo es que no sé usar tu modificación de la función de atributos, es muy avanzada '¬¬

Así que mientras no me muestres un ejemplo de como usar tu función, la dejo así, que está mejor que la versión original y se asemeja al comando ATTRIB de la CMD, lo que me facilita un poco más su uso:

Código
  1. #Region " Change File Attributes Function "
  2.  
  3.    ' [ Change File Attributes Function ]
  4.    '
  5.    ' // By Elektro H@cker
  6.    '
  7.    ' Examples :
  8.    ' Change_File_Attributes("C:\File.txt", H + R)
  9.    ' Change_File_Attributes("C:\File.txt", Hidden + Read_Only)
  10.  
  11.    Const Archive As Integer = 32, A As Integer = 32
  12.    Const Directory As Integer = 16, D As Integer = 16
  13.    Const Hidden As Integer = 2, H As Integer = 2
  14.    Const Normal As Integer = 0, N As Integer = 0
  15.    Const Read_Only As Integer = 1, R As Integer = 1
  16.    Const System As Integer = 4, S As Integer = 4
  17.    Const Volume As Integer = 8, V As Integer = 8
  18.  
  19.    Private Function Change_File_Attributes(ByVal File As String, ByVal Attributes As System.IO.FileAttributes) As Boolean
  20.        If IO.File.Exists(File) Then
  21.            Try
  22.                FileSystem.SetAttr(File, Attributes)
  23.                Return True ' File was modified OK
  24.            Catch
  25.                Return False ' File can't be modified maybe because User Permissions
  26.            End Try
  27.        Else
  28.            Return Nothing ' File doesn't exist
  29.        End If
  30.    End Function
  31.  
  32. #End Region



3.
Tu modificación de la función de las capacidades de discos es inmejorable,
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ó)


Gracias por los consejos y un saludo
 
En línea

Páginas: 1 [2] 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ... 59 Ir Arriba Respuesta Imprimir 

Ir a:  

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