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

 

 


Tema destacado: Curso de javascript por TickTack


  Mostrar Mensajes
Páginas: 1 ... 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 [735] 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 ... 1236
7341  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 7 Marzo 2014, 19:52 pm
Algunos métodos de uso genérico sobre las cuentas de usuario.




Código
  1.    ' Get UserNames
  2.    ' ( By Elektro )
  3.    '
  4.    ' Instructions:
  5.    ' 1. Add a reference to 'System.DirectoryServices.AccountManagement'.
  6.    ' 2. Imports System.DirectoryServices.AccountManagement
  7.    '
  8.    ' Example Usages:
  9.    ' Dim UserNames As String() = GetUserNames()
  10.    '
  11.    ''' <summary>
  12.    ''' Get the username accounts of the current machine.
  13.    ''' </summary>
  14.    ''' <returns>System.String[][].</returns>
  15.    Public Function GetUserNames() As String()
  16.  
  17.        Dim pContext As New PrincipalContext(ContextType.Machine)
  18.        Dim pUser As New UserPrincipal(pContext)
  19.        Dim pSearcher As New PrincipalSearcher(pUser)
  20.        Dim UserNames As String() = (From u As Principal In pSearcher.FindAll Select u.Name).ToArray
  21.  
  22.        pContext.Dispose()
  23.        pSearcher.Dispose()
  24.        pUser.Dispose()
  25.  
  26.        Return UserNames
  27.  
  28.    End Function



Código
  1.    ' Get Users
  2.    ' ( By Elektro )
  3.    '
  4.    ' Instructions:
  5.    ' 1. Add a reference to 'System.DirectoryServices.AccountManagement'.
  6.    ' 2. Imports System.DirectoryServices.AccountManagement
  7.    '
  8.    ' Example Usages:
  9.    ' Dim Users As Principal() = GetUsers()
  10.    ' For Each User As Principal In Users()
  11.    '     MsgBox(User.Name)
  12.    ' Next
  13.    '
  14.    ''' <summary>
  15.    ''' Get the users of the current machine.
  16.    ''' </summary>
  17.    ''' <returns>Principal[][].</returns>
  18.    Public Function GetUsers() As Principal()
  19.  
  20.        Dim pContext As New PrincipalContext(ContextType.Machine)
  21.        Dim pUser As New UserPrincipal(pContext)
  22.        Dim pSearcher As New PrincipalSearcher(pUser)
  23.        Dim Users As Principal() = (From User As Principal In pSearcher.FindAll).ToArray
  24.  
  25.        Return Users
  26.  
  27.    End Function



Código
  1.   ' Delete User Account
  2.    ' ( By Elektro )
  3.    '
  4.    ' Instructions:
  5.    ' 1. Add a reference to 'System.DirectoryServices.AccountManagement'.
  6.    ' 2. Imports System.DirectoryServices.AccountManagement
  7.    '
  8.    ' Example Usages:
  9.    ' DeleteUserAccount("Username")
  10.    ' DeleteUserAccount(New Security.Principal.SecurityIdentifier("S-1-5-21-250596608-219436059-1115792336-500"))
  11.    '
  12.    ''' <summary>
  13.    ''' Deletes an existing user account in the current machine.
  14.    ''' </summary>
  15.    ''' <param name="UserName">Indicates the account Username.</param>
  16.    ''' <returns><c>true</c> if deletion success, <c>false</c> otherwise.</returns>
  17.    Public Function DeleteUserAccount(ByVal UserName As String) As Boolean
  18.  
  19.        Dim pContext As New PrincipalContext(ContextType.Machine)
  20.        Dim pUser As New UserPrincipal(pContext)
  21.        Dim pSearcher As New PrincipalSearcher(pUser)
  22.  
  23.        Dim User As Principal =
  24.            (From u As Principal In pSearcher.FindAll
  25.            Where u.Name.Equals(UserName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault
  26.  
  27.        If User Is Nothing Then
  28.            Throw New Exception(String.Format("User with name '{0}' not found.", UserName))
  29.        End If
  30.  
  31.        Try
  32.            User.Delete()
  33.            Return True
  34.  
  35.        Catch ex As InvalidOperationException
  36.            Throw New Exception(ex.Message)
  37.  
  38.        Finally
  39.            pContext.Dispose()
  40.            pSearcher.Dispose()
  41.            pUser.Dispose()
  42.  
  43.        End Try
  44.  
  45.        Return False ' Failed.
  46.  
  47.    End Function

Código
  1.    ''' <summary>
  2.    ''' Deletes an existing user account in the current machine.
  3.    ''' </summary>
  4.    ''' <param name="UserSID">Indicates the account security identifier (SID).</param>
  5.    ''' <returns><c>true</c> if deletion success, <c>false</c> otherwise.</returns>
  6.    Public Function DeleteUserAccount(ByVal UserSID As Security.Principal.SecurityIdentifier) As Boolean
  7.  
  8.        Dim pContext As New PrincipalContext(ContextType.Machine)
  9.        Dim pUser As New UserPrincipal(pContext)
  10.        Dim pSearcher As New PrincipalSearcher(pUser)
  11.  
  12.        Dim User As Principal =
  13.            (From u As Principal In pSearcher.FindAll
  14.            Where u.Sid = UserSID).FirstOrDefault
  15.  
  16.        If User Is Nothing Then
  17.            Throw New Exception(String.Format("User with SID '{0}' not found.", UserSID.Value))
  18.        End If
  19.  
  20.        Try
  21.            User.Delete()
  22.            Return True
  23.  
  24.        Catch ex As InvalidOperationException
  25.            Throw New Exception(ex.Message)
  26.  
  27.        Finally
  28.            pContext.Dispose()
  29.            pSearcher.Dispose()
  30.            pUser.Dispose()
  31.  
  32.        End Try
  33.  
  34.        Return False ' Failed.
  35.  
  36.    End Function



Código
  1.    ' User Is Admin?
  2.    ' ( By Elektro )
  3.    '
  4.    ' Instructions:
  5.    ' 1. Add a reference to 'System.DirectoryServices.AccountManagement'.
  6.    ' 2. Imports System.DirectoryServices.AccountManagement
  7.    '
  8.    ' Example Usages:
  9.    ' MsgBox(UserIsAdmin("Administrador"))
  10.    ' MsgBox(UserIsAdmin(New Security.Principal.SecurityIdentifier("S-1-5-21-250596608-219436059-1115792336-500")))
  11.    '
  12.    ''' <summary>
  13.    ''' Determines whether an User is an Administrator.
  14.    ''' </summary>
  15.    ''' <param name="UserName">Indicates the account Username.</param>
  16.    ''' <returns><c>true</c> if user is an Administrator, <c>false</c> otherwise.</returns>
  17.    Public Function UserIsAdmin(ByVal UserName As String) As Boolean
  18.  
  19.        Dim AdminGroupSID As New SecurityIdentifier("S-1-5-32-544")
  20.  
  21.        Dim pContext As New PrincipalContext(ContextType.Machine)
  22.        Dim pUser As New UserPrincipal(pContext)
  23.        Dim pSearcher As New PrincipalSearcher(pUser)
  24.  
  25.        Dim User As Principal =
  26.            (From u As Principal In pSearcher.FindAll
  27.            Where u.Name.Equals(UserName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault
  28.  
  29.        If User Is Nothing Then
  30.            Throw New Exception(String.Format("User with name '{0}' not found.", UserName))
  31.        End If
  32.  
  33.        Dim IsAdmin As Boolean =
  34.            (From Group As GroupPrincipal In User.GetGroups
  35.             Where Group.Sid = AdminGroupSID).Any
  36.  
  37.        pContext.Dispose()
  38.        pSearcher.Dispose()
  39.        pUser.Dispose()
  40.  
  41.        Return IsAdmin
  42.  
  43.    End Function

Código
  1.    ''' <summary>
  2.    ''' Determines whether an User is an Administrator.
  3.    ''' </summary>
  4.    ''' <param name="UserSID">Indicates the SID of the user account.</param>
  5.    ''' <returns><c>true</c> if user is an Administrator, <c>false</c> otherwise.</returns>
  6.    Public Function UserIsAdmin(ByVal UserSID As Security.Principal.SecurityIdentifier) As Boolean
  7.  
  8.        Dim AdminGroupSID As New SecurityIdentifier("S-1-5-32-544")
  9.  
  10.        Dim pContext As New PrincipalContext(ContextType.Machine)
  11.        Dim pUser As New UserPrincipal(pContext)
  12.        Dim pSearcher As New PrincipalSearcher(pUser)
  13.  
  14.        Dim User As Principal =
  15.            (From u As Principal In pSearcher.FindAll
  16.            Where u.Sid = UserSID).FirstOrDefault
  17.  
  18.        If User Is Nothing Then
  19.            Throw New Exception(String.Format("User with SID '{0}' not found.", UserSID.Value))
  20.        End If
  21.  
  22.        Dim IsAdmin As Boolean =
  23.            (From Group As GroupPrincipal In User.GetGroups
  24.             Where Group.Sid = AdminGroupSID).Any
  25.  
  26.        pContext.Dispose()
  27.        pSearcher.Dispose()
  28.        pUser.Dispose()
  29.  
  30.        Return IsAdmin
  31.  
  32.    End Function



Código
  1.   ' Set UserName
  2.    ' ( By Elektro )
  3.    '
  4.    ' Instructions:
  5.    ' 1. Add a reference to 'System.DirectoryServices.AccountManagement'.
  6.    ' 2. Imports System.DirectoryServices.AccountManagement
  7.    '
  8.    ' Example Usages:
  9.    ' SetUserName("Username", "New Name")
  10.    ' SetUserName(New Security.Principal.SecurityIdentifier("S-1-5-21-250596608-219436059-1115792336-500"), "New Name")
  11.    '
  12.    ''' <summary>
  13.    ''' Sets the UserName of an existing User account.
  14.    ''' </summary>
  15.    ''' <param name="OldUserName">Indicates an existing username account.</param>
  16.    ''' <param name="NewUserName">Indicates the new name for the user account.</param>
  17.    ''' <returns><c>true</c> if change success, <c>false</c> otherwise.</returns>
  18.    Public Function SetUserName(ByVal OldUserName As String,
  19.                                ByVal NewUserName As String) As Boolean
  20.  
  21.        Dim pContext As New PrincipalContext(ContextType.Machine)
  22.        Dim pUser As New UserPrincipal(pContext)
  23.        Dim pSearcher As New PrincipalSearcher(pUser)
  24.  
  25.        Dim User As Principal =
  26.            (From u As Principal In pSearcher.FindAll
  27.            Where u.Name.Equals(OldUserName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault
  28.  
  29.        If User Is Nothing Then
  30.            Throw New Exception(String.Format("User with name '{0}' not found.", OldUserName))
  31.        End If
  32.  
  33.        Try
  34.            User.Name = NewUserName
  35.            User.Save()
  36.            Return True
  37.  
  38.        Catch ex As InvalidOperationException
  39.            Throw New Exception(ex.Message)
  40.  
  41.        Finally
  42.            pContext.Dispose()
  43.            pSearcher.Dispose()
  44.            pUser.Dispose()
  45.  
  46.        End Try
  47.  
  48.        Return False ' Failed.
  49.  
  50.    End Function

Código
  1.    ''' <summary>
  2.    ''' Sets the UserName of an existing User account.
  3.    ''' </summary>
  4.    ''' <param name="UserSID">Indicates the SID of the user account.</param>
  5.    ''' <param name="NewUserName">Indicates the new name for the user account.</param>
  6.    ''' <returns><c>true</c> if change success, <c>false</c> otherwise.</returns>
  7.    Public Function SetUserName(ByVal UserSID As Security.Principal.SecurityIdentifier,
  8.                                ByVal NewUserName As String) As Boolean
  9.  
  10.        Dim pContext As New PrincipalContext(ContextType.Machine)
  11.        Dim pUser As New UserPrincipal(pContext)
  12.        Dim pSearcher As New PrincipalSearcher(pUser)
  13.  
  14.        Dim User As Principal =
  15.            (From u As Principal In pSearcher.FindAll
  16.            Where u.Sid = UserSID).FirstOrDefault
  17.  
  18.        If User Is Nothing Then
  19.            Throw New Exception(String.Format("User with SID '{0}' not found.", UserSID.Value))
  20.        End If
  21.  
  22.        Try
  23.            User.Name = NewUserName
  24.            User.Save()
  25.            Return True
  26.  
  27.        Catch ex As InvalidOperationException
  28.            Throw New Exception(ex.Message)
  29.  
  30.        Finally
  31.            pContext.Dispose()
  32.            pSearcher.Dispose()
  33.            pUser.Dispose()
  34.  
  35.        End Try
  36.  
  37.        Return False ' Failed.
  38.  
  39.    End Function
  40.  


Código
  1.   ' Set Account DisplayName
  2.    ' ( By Elektro )
  3.    '
  4.    ' Instructions:
  5.    ' 1. Add a reference to 'System.DirectoryServices.AccountManagement'.
  6.    ' 2. Imports System.DirectoryServices.AccountManagement
  7.    '
  8.    ' Example Usages:
  9.    ' SetAccountDisplayName("Username", "New Name")
  10.    ' SetAccountDisplayName(New Security.Principal.SecurityIdentifier("S-1-5-21-250596608-219436059-1115792336-500"), "New Name")
  11.    '
  12.    ''' <summary>
  13.    ''' Sets the display name of an existing User account.
  14.    ''' </summary>
  15.    ''' <param name="OldDisplayName">Indicates an existing display name user account.</param>
  16.    ''' <param name="NewDisplayName">Indicates the new display name for the user account.</param>
  17.    ''' <returns><c>true</c> if change success, <c>false</c> otherwise.</returns>
  18.    Public Function SetAccountDisplayName(ByVal OldDisplayName As String,
  19.                                          ByVal NewDisplayName As String) As Boolean
  20.  
  21.        Dim pContext As New PrincipalContext(ContextType.Machine)
  22.        Dim pUser As New UserPrincipal(pContext)
  23.        Dim pSearcher As New PrincipalSearcher(pUser)
  24.  
  25.        Dim User As Principal =
  26.            (From u As Principal In pSearcher.FindAll
  27.            Where u.Name.Equals(OldDisplayName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault
  28.  
  29.        If User Is Nothing Then
  30.            Throw New Exception(String.Format("User with display name '{0}' not found.", OldDisplayName))
  31.        End If
  32.  
  33.        Try
  34.            User.DisplayName = NewDisplayName
  35.            User.Save()
  36.            Return True
  37.  
  38.        Catch ex As InvalidOperationException
  39.            Throw New Exception(ex.Message)
  40.  
  41.        Finally
  42.            pContext.Dispose()
  43.            pSearcher.Dispose()
  44.            pUser.Dispose()
  45.  
  46.        End Try
  47.  
  48.        Return False ' Failed.
  49.  
  50.    End Function

Código
  1.    ''' <summary>
  2.    ''' Sets the display name of an existing User account.
  3.    ''' </summary>
  4.    ''' <param name="UserSID">Indicates the SID of the user account.</param>
  5.    ''' <param name="NewDisplayName">Indicates the new display name for the user account.</param>
  6.    ''' <returns><c>true</c> if change success, <c>false</c> otherwise.</returns>
  7.    Public Function SetAccountDisplayName(ByVal UserSID As Security.Principal.SecurityIdentifier,
  8.                                          ByVal NewDisplayName As String) As Boolean
  9.  
  10.        Dim pContext As New PrincipalContext(ContextType.Machine)
  11.        Dim pUser As New UserPrincipal(pContext)
  12.        Dim pSearcher As New PrincipalSearcher(pUser)
  13.  
  14.        Dim User As Principal =
  15.            (From u As Principal In pSearcher.FindAll
  16.            Where u.Sid = UserSID).FirstOrDefault
  17.  
  18.        If User Is Nothing Then
  19.            Throw New Exception(String.Format("User with SID '{0}' not found.", UserSID.Value))
  20.        End If
  21.  
  22.        Try
  23.            User.DisplayName = NewDisplayName
  24.            User.Save()
  25.            Return True
  26.  
  27.        Catch ex As InvalidOperationException
  28.            Throw New Exception(ex.Message)
  29.  
  30.        Finally
  31.            pContext.Dispose()
  32.            pSearcher.Dispose()
  33.            pUser.Dispose()
  34.  
  35.        End Try
  36.  
  37.        Return False ' Failed.
  38.  
  39.    End Function
7342  Programación / Scripting / Re: [DUDA] Batch o FTP en: 7 Marzo 2014, 19:13 pm
haciendo ping si no me equivoco a x direccion te devolvia tu IP publica o algo asi

En todo caso, devolverá la IP por la que viaja el Ping.

No creo que en Batch se pueda obtener la IP pública de un router.

PD: Aprovecho para repetir que no contesto a mensajes privados pidiendo ayuda, usen el foro, @KZN.

Saludos
7343  Foros Generales / Dudas Generales / Re: Quien sabe de hackear flash,html? en: 7 Marzo 2014, 02:59 am
Si, ya ..."recuperar".

Parece que a pesar de los años todos siguen como locos por intentar "hackear" ese juego...

PD: Porfavor, lee las reglas de la comunidad, no está permitido duplicar posts.

Suerte con la "recuperación",
Saludos!
7344  Foros Generales / Dudas Generales / Re: Timostar a lo suyo... en: 7 Marzo 2014, 01:57 am
Yo tengo ganas de una cosa "asín"...

http://www.iber-banda.es/

Donde yo vivo hace 3 años no llegaba el adsl por cable e Iberbanda era la única opción disponible.
El servicio era (y sigue siendo) penoso.
Cuando llegó el adsl convencional todo el mundo les dió con la puerta en las narices.

No es por mal meter, pero ...es que no hay más que contemplar la página web tan profesional que tienen! (sarcasmo), inspira mucha confianza, pero sobretodo alucino con el anuncio tan currado que hicieron en Flash, con esos efectos de texto tan ...épicos, cuanto esfuerzo y dedicación para llevar a cabo esa animación, que digo, esa obra maestra!, es toda una proeza, y quien lo hiciera es un digno rival ...para mi abuela.

Saludos!
7345  Programación / Programación General / Re: ayuda con python: user y contraseña en: 6 Marzo 2014, 23:43 pm
otra cosa... veo que has utilizado el in en vez del != o ==,y que para marcar el nombre ' en vez del "...,hay diferencia en el lenguaje al usarlo?

Ya que te pones a programar en un lenguaje que te resulta desconocido, en mi opinión lo más lógico antes de preguntar cosas semejantes como las diferencias entre operadores o las comillas dobles, sería ojear la documentación básica del lenguaje para conocer esos operadores y saber como actuan, que eso es lo primero que se debe hacer ...como mínimo.

· Python Strings

· (Unofficial) Python Operators

Saludos!
7346  Foros Generales / Dudas Generales / Re: ¿Cual es el MimeType de un archivo '.reg'? (texto unicode) en: 6 Marzo 2014, 18:18 pm
Una aplicación que tengo dice que es esta.

application/octet-stream


Ok, gracias :)
7347  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 6 Marzo 2014, 16:56 pm
FileType Detective

Comprueba el tipo de un archivo específico examinando su cabecera.

(Tipo 'MediaInfo')

Código
  1. ' ***********************************************************************
  2. ' Author   : Original: http://filetypedetective.codeplex.com/
  3. '            Source translated, revised and extended by Elektro.
  4. '
  5. ' Modified : 03-06-2014
  6. ' ***********************************************************************
  7. ' <copyright file="FileTypeDetective.vb" company="Elektro Studios">
  8. '     Copyright (c) Elektro Studios. All rights reserved.
  9. ' </copyright>
  10. ' ***********************************************************************
  11.  
  12. #Region " Info "
  13.  
  14. ' file headers are taken from here:
  15. 'http://www.garykessler.net/library/file_sigs.html
  16.  
  17. ' mime types are taken from here:
  18. ' http://www.webmaster-toolkit.com/mime-types.shtml
  19.  
  20. #End Region
  21.  
  22. #Region " Usage Examples "
  23.  
  24. 'Imports FileTypeDetective
  25.  
  26. 'Public Class Form1
  27.  
  28. '    Private Sub Test() Handles MyBase.Load
  29.  
  30. '        MessageBox.Show(Detective.isType("C:\File.reg", FileType.REG)) ' NOTE: The regfile should be Unicode, not ANSI.
  31. '        MessageBox.Show(Detective.GetFileType("C:\File.reg").mime)
  32.  
  33. '    End Sub
  34.  
  35. 'End Class
  36.  
  37. #End Region
  38.  
  39. #Region " Imports "
  40.  
  41. Imports System.IO
  42. Imports FileTypeDetective.FileType
  43.  
  44. #End Region
  45.  
  46. #Region " FileType Detective "
  47.  
  48. ''' <summary>
  49. ''' Little data structure to hold information about file types.
  50. ''' Holds information about binary header at the start of the file
  51. ''' </summary>
  52. Public Class FileType
  53.  
  54.    ' MS Office files
  55.    Public Shared ReadOnly WORD As New FileType(
  56.        New Nullable(Of Byte)() {&HEC, &HA5, &HC1, &H0}, 512I, "doc", "application/msword")
  57.  
  58.    Public Shared ReadOnly EXCEL As New FileType(
  59.        New Nullable(Of Byte)() {&H9, &H8, &H10, &H0, &H0, &H6, &H5, &H0}, 512I, "xls", "application/excel")
  60.  
  61.    Public Shared ReadOnly PPT As New FileType(
  62.        New Nullable(Of Byte)() {&HFD, &HFF, &HFF, &HFF, Nothing, &H0, &H0, &H0}, 512I, "ppt", "application/mspowerpoint")
  63.  
  64.    ' common documents
  65.    Public Shared ReadOnly RTF As New FileType(
  66.        New Nullable(Of Byte)() {&H7B, &H5C, &H72, &H74, &H66, &H31}, "rtf", "application/rtf")
  67.  
  68.    Public Shared ReadOnly PDF As New FileType(
  69.        New Nullable(Of Byte)() {&H25, &H50, &H44, &H46}, "pdf", "application/pdf")
  70.  
  71.    Public Shared ReadOnly REG As New FileType(
  72.        New Nullable(Of Byte)() {&HFF, &HFE}, "reg", "text/plain")
  73.  
  74.    ' grafics
  75.    Public Shared ReadOnly JPEG As New FileType(
  76.        New Nullable(Of Byte)() {&HFF, &HD8, &HFF}, "jpg", "image/jpeg")
  77.  
  78.    Public Shared ReadOnly PNG As New FileType(
  79.        New Nullable(Of Byte)() {&H89, &H50, &H4E, &H47, &HD, &HA, &H1A, &HA}, "png", "image/png")
  80.  
  81.    Public Shared ReadOnly GIF As New FileType(
  82.        New Nullable(Of Byte)() {&H47, &H49, &H46, &H38, Nothing, &H61}, "gif", "image/gif")
  83.  
  84.    ' Compressed
  85.    Public Shared ReadOnly ZIP As New FileType(
  86.        New Nullable(Of Byte)() {&H50, &H4B, &H3, &H4}, "zip", "application/x-compressed")
  87.  
  88.    Public Shared ReadOnly RAR As New FileType(
  89.        New Nullable(Of Byte)() {&H52, &H61, &H72, &H21}, "rar", "application/x-compressed")
  90.  
  91.    ' all the file types to be put into one list
  92.    Friend Shared ReadOnly types As New List(Of FileType)() From { _
  93.        PDF,
  94.        WORD,
  95.        EXCEL,
  96.        JPEG,
  97.        ZIP,
  98.        RAR,
  99.        RTF,
  100.        PNG,
  101.        PPT,
  102.        GIF,
  103.        REG
  104.    }
  105.  
  106.    ' number of bytes we read from a file
  107.    Friend Const MaxHeaderSize As Integer = 560
  108.    ' some file formats have headers offset to 512 bytes
  109.  
  110.    ' most of the times we only need first 8 bytes, but sometimes extend for 16
  111.    Private m_header As Nullable(Of Byte)()
  112.    Public Property header() As Nullable(Of Byte)()
  113.        Get
  114.            Return m_header
  115.        End Get
  116.        Private Set(value As Nullable(Of Byte)())
  117.            m_header = value
  118.        End Set
  119.    End Property
  120.  
  121.    Private m_headerOffset As Integer
  122.    Public Property headerOffset() As Integer
  123.        Get
  124.            Return m_headerOffset
  125.        End Get
  126.        Private Set(value As Integer)
  127.            m_headerOffset = value
  128.        End Set
  129.    End Property
  130.  
  131.    Private m_extension As String
  132.    Public Property extension() As String
  133.        Get
  134.            Return m_extension
  135.        End Get
  136.        Private Set(value As String)
  137.            m_extension = value
  138.        End Set
  139.    End Property
  140.  
  141.    Private m_mime As String
  142.    Public Property mime() As String
  143.        Get
  144.            Return m_mime
  145.        End Get
  146.        Private Set(value As String)
  147.            m_mime = value
  148.        End Set
  149.    End Property
  150.  
  151. #Region " Constructors "
  152.  
  153.    ''' <summary>
  154.    ''' Initializes a new instance of the <see cref="FileType"/> class.
  155.    ''' Default construction with the header offset being set to zero by default
  156.    ''' </summary>
  157.    ''' <param name="header">Byte array with header.</param>
  158.    ''' <param name="extension">String with extension.</param>
  159.    ''' <param name="mime">The description of MIME.</param>
  160.    Public Sub New(header As Nullable(Of Byte)(), extension As String, mime As String)
  161.        Me.header = header
  162.        Me.extension = extension
  163.        Me.mime = mime
  164.        Me.headerOffset = 0
  165.    End Sub
  166.  
  167.    ''' <summary>
  168.    ''' Initializes a new instance of the <see cref="FileType"/> struct.
  169.    ''' Takes the details of offset for the header
  170.    ''' </summary>
  171.    ''' <param name="header">Byte array with header.</param>
  172.    ''' <param name="offset">The header offset - how far into the file we need to read the header</param>
  173.    ''' <param name="extension">String with extension.</param>
  174.    ''' <param name="mime">The description of MIME.</param>
  175.    Public Sub New(header As Nullable(Of Byte)(), offset As Integer, extension As String, mime As String)
  176.        Me.header = Nothing
  177.        Me.header = header
  178.        Me.headerOffset = offset
  179.        Me.extension = extension
  180.        Me.mime = mime
  181.    End Sub
  182.  
  183. #End Region
  184.  
  185.    Public Overrides Function Equals(other As Object) As Boolean
  186.  
  187.        If Not MyBase.Equals(other) Then
  188.            Return False
  189.        End If
  190.  
  191.        If Not (TypeOf other Is FileType) Then
  192.            Return False
  193.        End If
  194.  
  195.        Dim otherType As FileType = DirectCast(other, FileType)
  196.  
  197.        If Not Me.header Is otherType.header Then
  198.            Return False
  199.        End If
  200.  
  201.        If Me.headerOffset <> otherType.headerOffset Then
  202.            Return False
  203.        End If
  204.  
  205.        If Me.extension <> otherType.extension Then
  206.            Return False
  207.        End If
  208.  
  209.        If Me.mime <> otherType.mime Then
  210.            Return False
  211.        End If
  212.  
  213.        Return True
  214.  
  215.    End Function
  216.  
  217.    Public Overrides Function ToString() As String
  218.        Return extension
  219.    End Function
  220.  
  221. End Class
  222.  
  223. ''' <summary>
  224. ''' Helper class to identify file type by the file header, not file extension.
  225. ''' </summary>
  226. Public NotInheritable Class FileTypeDetective
  227.  
  228.    ''' <summary>
  229.    ''' Prevents a default instance of the <see cref="FileTypeDetective"/> class from being created.
  230.    ''' </summary>
  231.    Private Sub New()
  232.    End Sub
  233.  
  234. #Region "Main Methods"
  235.  
  236.    ''' <summary>
  237.    ''' Gets the list of FileTypes based on list of extensions in Comma-Separated-Values string
  238.    ''' </summary>
  239.    ''' <param name="CSV">The CSV String with extensions</param>
  240.    ''' <returns>List of FileTypes</returns>
  241.    Private Shared Function GetFileTypesByExtensions(CSV As String) As List(Of FileType)
  242.        Dim extensions As [String]() = CSV.ToUpper().Replace(" ", "").Split(","c)
  243.  
  244.        Dim result As New List(Of FileType)()
  245.  
  246.        For Each type As FileType In types
  247.            If extensions.Contains(type.extension.ToUpper()) Then
  248.                result.Add(type)
  249.            End If
  250.        Next
  251.        Return result
  252.    End Function
  253.  
  254.    ''' <summary>
  255.    ''' Reads the file header - first (16) bytes from the file
  256.    ''' </summary>
  257.    ''' <param name="file">The file to work with</param>
  258.    ''' <returns>Array of bytes</returns>
  259.    Private Shared Function ReadFileHeader(file As FileInfo, MaxHeaderSize As Integer) As [Byte]()
  260.        Dim header As [Byte]() = New Byte(MaxHeaderSize - 1) {}
  261.        Try
  262.            ' read file
  263.            Using fsSource As New FileStream(file.FullName, FileMode.Open, FileAccess.Read)
  264.                ' read first symbols from file into array of bytes.
  265.                fsSource.Read(header, 0, MaxHeaderSize)
  266.                ' close the file stream
  267.            End Using
  268.        Catch e As Exception
  269.            ' file could not be found/read
  270.            Throw New ApplicationException("Could not read file : " & e.Message)
  271.        End Try
  272.  
  273.        Return header
  274.    End Function
  275.  
  276.    ''' <summary>
  277.    ''' Read header of a file and depending on the information in the header
  278.    ''' return object FileType.
  279.    ''' Return null in case when the file type is not identified.
  280.    ''' Throws Application exception if the file can not be read or does not exist
  281.    ''' </summary>
  282.    ''' <param name="file">The FileInfo object.</param>
  283.    ''' <returns>FileType or null not identified</returns>
  284.    Public Shared Function GetFileType(file As FileInfo) As FileType
  285.        ' read first n-bytes from the file
  286.        Dim fileHeader As [Byte]() = ReadFileHeader(file, MaxHeaderSize)
  287.  
  288.        ' compare the file header to the stored file headers
  289.        For Each type As FileType In types
  290.            Dim matchingCount As Integer = 0
  291.            For i As Integer = 0 To type.header.Length - 1
  292.                ' if file offset is not set to zero, we need to take this into account when comparing.
  293.                ' if byte in type.header is set to null, means this byte is variable, ignore it
  294.                If type.header(i) IsNot Nothing AndAlso type.header(i) <> fileHeader(i + type.headerOffset) Then
  295.                    ' if one of the bytes does not match, move on to the next type
  296.                    matchingCount = 0
  297.                    Exit For
  298.                Else
  299.                    matchingCount += 1
  300.                End If
  301.            Next
  302.            If matchingCount = type.header.Length Then
  303.                ' if all the bytes match, return the type
  304.                Return type
  305.            End If
  306.        Next
  307.        ' if none of the types match, return null
  308.        Return Nothing
  309.    End Function
  310.  
  311.    ''' <summary>
  312.    ''' Read header of a file and depending on the information in the header
  313.    ''' return object FileType.
  314.    ''' Return null in case when the file type is not identified.
  315.    ''' Throws Application exception if the file can not be read or does not exist
  316.    ''' </summary>
  317.    ''' <param name="file">The FileInfo object.</param>
  318.    ''' <returns>FileType or null not identified</returns>
  319.    Public Shared Function GetFileType(file As String) As FileType
  320.        Return GetFileType(New FileInfo(file))
  321.    End Function
  322.  
  323.    ''' <summary>
  324.    ''' Determines whether provided file belongs to one of the provided list of files
  325.    ''' </summary>
  326.    ''' <param name="file">The file.</param>
  327.    ''' <param name="requiredTypes">The required types.</param>
  328.    ''' <returns>
  329.    '''   <c>true</c> if file of the one of the provided types; otherwise, <c>false</c>.
  330.    ''' </returns>
  331.    Public Shared Function isFileOfTypes(file As FileInfo, requiredTypes As List(Of FileType)) As Boolean
  332.  
  333.        Dim currentType As FileType = GetFileType(file)
  334.  
  335.        If currentType Is Nothing Then
  336.            Return False
  337.        End If
  338.  
  339.        Return requiredTypes.Contains(currentType)
  340.  
  341.    End Function
  342.  
  343.    ''' <summary>
  344.    ''' Determines whether provided file belongs to one of the provided list of files,
  345.    ''' where list of files provided by string with Comma-Separated-Values of extensions
  346.    ''' </summary>
  347.    ''' <param name="file">The file.</param>
  348.    ''' <returns>
  349.    '''   <c>true</c> if file of the one of the provided types; otherwise, <c>false</c>.
  350.    ''' </returns>
  351.    Public Shared Function isFileOfTypes(file As FileInfo, CSV As String) As Boolean
  352.  
  353.        Dim providedTypes As List(Of FileType) = GetFileTypesByExtensions(CSV)
  354.  
  355.        Return isFileOfTypes(file, providedTypes)
  356.  
  357.    End Function
  358.  
  359. #End Region
  360.  
  361. #Region "isType functions"
  362.  
  363.    ''' <summary>
  364.    ''' Determines whether the specified file is of provided type
  365.    ''' </summary>
  366.    ''' <param name="file">The file.</param>
  367.    ''' <param name="type">The FileType</param>
  368.    ''' <returns>
  369.    '''   <c>true</c> if the specified file is type; otherwise, <c>false</c>.
  370.    ''' </returns>
  371.    Public Shared Function isType(file As FileInfo, type As FileType) As Boolean
  372.  
  373.        Dim actualType As FileType = GetFileType(file)
  374.  
  375.        If actualType Is Nothing Then
  376.            Return False
  377.        End If
  378.  
  379.        Return (actualType.Equals(type))
  380.  
  381.    End Function
  382.  
  383.    ''' <summary>
  384.    ''' Determines whether the specified file is of provided type
  385.    ''' </summary>
  386.    ''' <param name="file">The file.</param>
  387.    ''' <param name="type">The FileType</param>
  388.    ''' <returns>
  389.    '''   <c>true</c> if the specified file is type; otherwise, <c>false</c>.
  390.    ''' </returns>
  391.    Public Shared Function isType(file As String, type As FileType) As Boolean
  392.  
  393.        Return isType(New FileInfo(file), type)
  394.  
  395.    End Function
  396.  
  397. #End Region
  398.  
  399. End Class
  400.  
  401. #End Region
7348  Foros Generales / Dudas Generales / Re: ¿Cual es el MimeType de un archivo '.reg'? (texto unicode) en: 6 Marzo 2014, 16:47 pm
Espero que tanto tocarle los webos al registro de windows te sirva para algo.

Gracias Rando (supongo xD)
Por el momento, tanto tocar el registro y tocar la programación, no me dan como pa comer cada mes.

Estoy extendiendo la funcionalidad de un source (una librería tipo 'MediaInfo') y para hacer las cosas bien necesito incluir el mimetype equivalente de este tipo de archivo.

Un saludo



EDITO:

windows no lo tiene definido, puedes buscarlo en

HKEY_LOCAL_MACHINE\Software\classes (creo)

si por ahi no esta definido, es generico

Hola, eso ya lo examiné pero no aparece el valor 'ContentType' para la extensión .REG, pero entonces, si es genérico, ¿cual sería el mimetype generico para un archivo de texto unicode?

text/plain ?
7349  Programación / Scripting / Re: Crear respuestas de comando mediante archivos bat en: 6 Marzo 2014, 16:28 pm
El comando espera el input por parte del usuario 2 veces consecutivas, una para introducir la contraseña, y otra para confirmarla. Si, lamentáblemente esta es una de esas excepciones.

De todas formas he notado que la sintaxis del comando permite especificar una nueva contraseña para la cuenta del usuario, diréctamente:
Código:
Net.exe user "Daniel" "Contraseña"

Y eso no requiere confirmación.

Saludos!
7350  Foros Generales / Dudas Generales / ¿Cual es el MimeType de un archivo '.reg'? (texto unicode) en: 6 Marzo 2014, 16:07 pm
Pues eso, ¿alguien podría aclararme cual es el mimetype correcto para un archivo de registro (.reg) Unicode?

He buscado en la siguiente url (y varias más), pero no lo encuentro: http://www.webmaster-toolkit.com/mime-types.shtml así que quizás estoy omitiendo algo importante a tener en cuenta?.

Me imagino que debería ser algo parecido a esto:
Código:
text/win-registry-script

Pero no encuentro nada parecido.

Saludos
Páginas: 1 ... 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 [735] 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 ... 1236
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines