Menú

Mostrar Mensajes

Esta sección te permite ver todos los mensajes escritos por este usuario. Ten en cuenta que sólo puedes ver los mensajes escritos en zonas a las que tienes acceso en este momento.

Mostrar Mensajes Menú

Mensajes - Eleкtro

#7201

Un ejemplo de uso muy básico de la librería NCalc ~> http://ncalc.codeplex.com/

Código (vbnet) [Seleccionar]
        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:

Código (vbnet) [Seleccionar]
    ' 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:

Código (vbnet) [Seleccionar]
' ***********************************************************************
' 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
#7202
De verdad, yo no se en que piensan ustedes cuando invierten su tiempo en formular una pregunta para pedir ayuda, ya que se ponen a hacerlo, ¿que menos que hacerlo bien?.

Hablas sobre un programa obsoleto (muerto) y underground, teniendo eso en cuenta, como mínimo deberías especificar:
· de donde lo descargaste
· versión del programa
· el SO donde lo utilizas (aunque sea obvio)


Además de eso hay ciertos datos fundamentales que se deben proporcionar para formular una duda sobre un lenguaje (no por que lo diga yo ni las normas, sinó por pura lógica si ustedes esperan recibir ayudar):
· el lenguaje que utilizas
· los detalles mínimos del error
· el código que utiizas


Pero aun así, sin aportar a tu duda toda esa información, ¿esperas que alguien te entienda y te pueda ofrecer ayuda sin más?, ¿de verdad lo esperas?.

...Bueno, por pura casualidad yo sé de que programa hablas ya que he usado ese tipo de herramientas durante gran parte de mi vida, dudo que más de 5 personas en todo el foro conozcan o hayan usado ese programa, deberías plantearte mejor la información que porporcionas en los posts que formules en el futuro.






el id3 mass tagger se distribuía como una aplicación de interface commandline (antes de morir), es decir, no se distribuia como un instalador, así que esto no me cuadra, ya que no tiene ningún sentido este error si no existe ningún instalador:
Citar"no se pudo instalar hubo un error".
...Y tampoco das muchos detalles sobre donde te aparece ese mensaje ni de donde lo descargaste ...ni nada.

CitarEl sistema no puede hallar el controlador especificado.
id3: no files matching 35_PISTA.mp3

Un output sin el código no sirve de mucho....

De todas formas el error parece suceder antes de que tu Script procese la orden que ejecuta al id3.exe, ya que parece que el id3.exe se inicializa corréctamente porque este llama al método que procesa los parámetros que le enviaste para buscar archivos mp3, y te da la respuesta, así que si el error crítico fuese del id3.exe, lo más normal sería que finalizase la ejecución del programa, pero el output indica que no finalizó.

Así que, en mi opinión, no creo que el problema se del id3, los errores que tienes parecen estar más bien relacionados con componentes perdidos/corruptos en Windows, todo parece apuntar a que te falta alguna dll (controlador) inexistente en tu PC, y eso me lleva a pensar... ¿Te has instalado el típico y dañino Windows Lite?.

PD: Yo siempre he usado sin problemas el id3 mass tagger en Win Vista, 7, 8, y 8.1.

Saludos
#7203
Scripting / Re: [DUDA] Batch o FTP
8 Marzo 2014, 02:02 AM
La imagen de error sin la linea que lanza el error no sirve para nada, ¿Nos muestras lo que hay en la linea 3 del código?  :¬¬

De todas formas, el error se explica por si mismo, no tienes los permisos de usuario necesarios para realizar "X" acción (acción que se realiza en la linea 3).

Imagino que la linea 3 de tu código será la misma que esta:
CitarSet objFile = objFSO.CreateTextFile(outFile,True)


Saludos
#7204
Algunos métodos de uso genérico sobre las cuentas de usuario.





Código (vbnet) [Seleccionar]
    ' Get UserNames
    ' ( By Elektro )
    '
    ' Instructions:
    ' 1. Add a reference to 'System.DirectoryServices.AccountManagement'.
    ' 2. Imports System.DirectoryServices.AccountManagement
    '
    ' Example Usages:
    ' Dim UserNames As String() = GetUserNames()
    '
    ''' <summary>
    ''' Get the username accounts of the current machine.
    ''' </summary>
    ''' <returns>System.String[][].</returns>
    Public Function GetUserNames() As String()

        Dim pContext As New PrincipalContext(ContextType.Machine)
        Dim pUser As New UserPrincipal(pContext)
        Dim pSearcher As New PrincipalSearcher(pUser)
        Dim UserNames As String() = (From u As Principal In pSearcher.FindAll Select u.Name).ToArray

        pContext.Dispose()
        pSearcher.Dispose()
        pUser.Dispose()

        Return UserNames

    End Function





Código (vbnet) [Seleccionar]
    ' Get Users
    ' ( By Elektro )
    '
    ' Instructions:
    ' 1. Add a reference to 'System.DirectoryServices.AccountManagement'.
    ' 2. Imports System.DirectoryServices.AccountManagement
    '
    ' Example Usages:
    ' Dim Users As Principal() = GetUsers()
    ' For Each User As Principal In Users()
    '     MsgBox(User.Name)
    ' Next
    '
    ''' <summary>
    ''' Get the users of the current machine.
    ''' </summary>
    ''' <returns>Principal[][].</returns>
    Public Function GetUsers() As Principal()

        Dim pContext As New PrincipalContext(ContextType.Machine)
        Dim pUser As New UserPrincipal(pContext)
        Dim pSearcher As New PrincipalSearcher(pUser)
        Dim Users As Principal() = (From User As Principal In pSearcher.FindAll).ToArray

        Return Users

    End Function





Código (vbnet) [Seleccionar]
   ' Delete User Account
    ' ( By Elektro )
    '
    ' Instructions:
    ' 1. Add a reference to 'System.DirectoryServices.AccountManagement'.
    ' 2. Imports System.DirectoryServices.AccountManagement
    '
    ' Example Usages:
    ' DeleteUserAccount("Username")
    ' DeleteUserAccount(New Security.Principal.SecurityIdentifier("S-1-5-21-250596608-219436059-1115792336-500"))
    '
    ''' <summary>
    ''' Deletes an existing user account in the current machine.
    ''' </summary>
    ''' <param name="UserName">Indicates the account Username.</param>
    ''' <returns><c>true</c> if deletion success, <c>false</c> otherwise.</returns>
    Public Function DeleteUserAccount(ByVal UserName As String) As Boolean

        Dim pContext As New PrincipalContext(ContextType.Machine)
        Dim pUser As New UserPrincipal(pContext)
        Dim pSearcher As New PrincipalSearcher(pUser)

        Dim User As Principal =
            (From u As Principal In pSearcher.FindAll
            Where u.Name.Equals(UserName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault

        If User Is Nothing Then
            Throw New Exception(String.Format("User with name '{0}' not found.", UserName))
        End If

        Try
            User.Delete()
            Return True

        Catch ex As InvalidOperationException
            Throw New Exception(ex.Message)

        Finally
            pContext.Dispose()
            pSearcher.Dispose()
            pUser.Dispose()

        End Try

        Return False ' Failed.

    End Function


Código (vbnet) [Seleccionar]
    ''' <summary>
    ''' Deletes an existing user account in the current machine.
    ''' </summary>
    ''' <param name="UserSID">Indicates the account security identifier (SID).</param>
    ''' <returns><c>true</c> if deletion success, <c>false</c> otherwise.</returns>
    Public Function DeleteUserAccount(ByVal UserSID As Security.Principal.SecurityIdentifier) As Boolean

        Dim pContext As New PrincipalContext(ContextType.Machine)
        Dim pUser As New UserPrincipal(pContext)
        Dim pSearcher As New PrincipalSearcher(pUser)

        Dim User As Principal =
            (From u As Principal In pSearcher.FindAll
            Where u.Sid = UserSID).FirstOrDefault

        If User Is Nothing Then
            Throw New Exception(String.Format("User with SID '{0}' not found.", UserSID.Value))
        End If

        Try
            User.Delete()
            Return True

        Catch ex As InvalidOperationException
            Throw New Exception(ex.Message)

        Finally
            pContext.Dispose()
            pSearcher.Dispose()
            pUser.Dispose()

        End Try

        Return False ' Failed.

    End Function





Código (vbnet) [Seleccionar]
    ' User Is Admin?
    ' ( By Elektro )
    '
    ' Instructions:
    ' 1. Add a reference to 'System.DirectoryServices.AccountManagement'.
    ' 2. Imports System.DirectoryServices.AccountManagement
    '
    ' Example Usages:
    ' MsgBox(UserIsAdmin("Administrador"))
    ' MsgBox(UserIsAdmin(New Security.Principal.SecurityIdentifier("S-1-5-21-250596608-219436059-1115792336-500")))
    '
    ''' <summary>
    ''' Determines whether an User is an Administrator.
    ''' </summary>
    ''' <param name="UserName">Indicates the account Username.</param>
    ''' <returns><c>true</c> if user is an Administrator, <c>false</c> otherwise.</returns>
    Public Function UserIsAdmin(ByVal UserName As String) As Boolean

        Dim AdminGroupSID As New SecurityIdentifier("S-1-5-32-544")

        Dim pContext As New PrincipalContext(ContextType.Machine)
        Dim pUser As New UserPrincipal(pContext)
        Dim pSearcher As New PrincipalSearcher(pUser)

        Dim User As Principal =
            (From u As Principal In pSearcher.FindAll
            Where u.Name.Equals(UserName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault

        If User Is Nothing Then
            Throw New Exception(String.Format("User with name '{0}' not found.", UserName))
        End If

        Dim IsAdmin As Boolean =
            (From Group As GroupPrincipal In User.GetGroups
             Where Group.Sid = AdminGroupSID).Any

        pContext.Dispose()
        pSearcher.Dispose()
        pUser.Dispose()

        Return IsAdmin

    End Function


Código (vbnet) [Seleccionar]
    ''' <summary>
    ''' Determines whether an User is an Administrator.
    ''' </summary>
    ''' <param name="UserSID">Indicates the SID of the user account.</param>
    ''' <returns><c>true</c> if user is an Administrator, <c>false</c> otherwise.</returns>
    Public Function UserIsAdmin(ByVal UserSID As Security.Principal.SecurityIdentifier) As Boolean

        Dim AdminGroupSID As New SecurityIdentifier("S-1-5-32-544")

        Dim pContext As New PrincipalContext(ContextType.Machine)
        Dim pUser As New UserPrincipal(pContext)
        Dim pSearcher As New PrincipalSearcher(pUser)

        Dim User As Principal =
            (From u As Principal In pSearcher.FindAll
            Where u.Sid = UserSID).FirstOrDefault

        If User Is Nothing Then
            Throw New Exception(String.Format("User with SID '{0}' not found.", UserSID.Value))
        End If

        Dim IsAdmin As Boolean =
            (From Group As GroupPrincipal In User.GetGroups
             Where Group.Sid = AdminGroupSID).Any

        pContext.Dispose()
        pSearcher.Dispose()
        pUser.Dispose()

        Return IsAdmin

    End Function





Código (vbnet) [Seleccionar]
   ' Set UserName
    ' ( By Elektro )
    '
    ' Instructions:
    ' 1. Add a reference to 'System.DirectoryServices.AccountManagement'.
    ' 2. Imports System.DirectoryServices.AccountManagement
    '
    ' Example Usages:
    ' SetUserName("Username", "New Name")
    ' SetUserName(New Security.Principal.SecurityIdentifier("S-1-5-21-250596608-219436059-1115792336-500"), "New Name")
    '
    ''' <summary>
    ''' Sets the UserName of an existing User account.
    ''' </summary>
    ''' <param name="OldUserName">Indicates an existing username account.</param>
    ''' <param name="NewUserName">Indicates the new name for the user account.</param>
    ''' <returns><c>true</c> if change success, <c>false</c> otherwise.</returns>
    Public Function SetUserName(ByVal OldUserName As String,
                                ByVal NewUserName As String) As Boolean

        Dim pContext As New PrincipalContext(ContextType.Machine)
        Dim pUser As New UserPrincipal(pContext)
        Dim pSearcher As New PrincipalSearcher(pUser)

        Dim User As Principal =
            (From u As Principal In pSearcher.FindAll
            Where u.Name.Equals(OldUserName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault

        If User Is Nothing Then
            Throw New Exception(String.Format("User with name '{0}' not found.", OldUserName))
        End If

        Try
            User.Name = NewUserName
            User.Save()
            Return True

        Catch ex As InvalidOperationException
            Throw New Exception(ex.Message)

        Finally
            pContext.Dispose()
            pSearcher.Dispose()
            pUser.Dispose()

        End Try

        Return False ' Failed.

    End Function


Código (vbnet) [Seleccionar]
    ''' <summary>
    ''' Sets the UserName of an existing User account.
    ''' </summary>
    ''' <param name="UserSID">Indicates the SID of the user account.</param>
    ''' <param name="NewUserName">Indicates the new name for the user account.</param>
    ''' <returns><c>true</c> if change success, <c>false</c> otherwise.</returns>
    Public Function SetUserName(ByVal UserSID As Security.Principal.SecurityIdentifier,
                                ByVal NewUserName As String) As Boolean

        Dim pContext As New PrincipalContext(ContextType.Machine)
        Dim pUser As New UserPrincipal(pContext)
        Dim pSearcher As New PrincipalSearcher(pUser)

        Dim User As Principal =
            (From u As Principal In pSearcher.FindAll
            Where u.Sid = UserSID).FirstOrDefault

        If User Is Nothing Then
            Throw New Exception(String.Format("User with SID '{0}' not found.", UserSID.Value))
        End If

        Try
            User.Name = NewUserName
            User.Save()
            Return True

        Catch ex As InvalidOperationException
            Throw New Exception(ex.Message)

        Finally
            pContext.Dispose()
            pSearcher.Dispose()
            pUser.Dispose()

        End Try

        Return False ' Failed.

    End Function




Código (vbnet) [Seleccionar]
   ' Set Account DisplayName
    ' ( By Elektro )
    '
    ' Instructions:
    ' 1. Add a reference to 'System.DirectoryServices.AccountManagement'.
    ' 2. Imports System.DirectoryServices.AccountManagement
    '
    ' Example Usages:
    ' SetAccountDisplayName("Username", "New Name")
    ' SetAccountDisplayName(New Security.Principal.SecurityIdentifier("S-1-5-21-250596608-219436059-1115792336-500"), "New Name")
    '
    ''' <summary>
    ''' Sets the display name of an existing User account.
    ''' </summary>
    ''' <param name="OldDisplayName">Indicates an existing display name user account.</param>
    ''' <param name="NewDisplayName">Indicates the new display name for the user account.</param>
    ''' <returns><c>true</c> if change success, <c>false</c> otherwise.</returns>
    Public Function SetAccountDisplayName(ByVal OldDisplayName As String,
                                          ByVal NewDisplayName As String) As Boolean

        Dim pContext As New PrincipalContext(ContextType.Machine)
        Dim pUser As New UserPrincipal(pContext)
        Dim pSearcher As New PrincipalSearcher(pUser)

        Dim User As Principal =
            (From u As Principal In pSearcher.FindAll
            Where u.Name.Equals(OldDisplayName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault

        If User Is Nothing Then
            Throw New Exception(String.Format("User with display name '{0}' not found.", OldDisplayName))
        End If

        Try
            User.DisplayName = NewDisplayName
            User.Save()
            Return True

        Catch ex As InvalidOperationException
            Throw New Exception(ex.Message)

        Finally
            pContext.Dispose()
            pSearcher.Dispose()
            pUser.Dispose()

        End Try

        Return False ' Failed.

    End Function


Código (vbnet) [Seleccionar]
    ''' <summary>
    ''' Sets the display name of an existing User account.
    ''' </summary>
    ''' <param name="UserSID">Indicates the SID of the user account.</param>
    ''' <param name="NewDisplayName">Indicates the new display name for the user account.</param>
    ''' <returns><c>true</c> if change success, <c>false</c> otherwise.</returns>
    Public Function SetAccountDisplayName(ByVal UserSID As Security.Principal.SecurityIdentifier,
                                          ByVal NewDisplayName As String) As Boolean

        Dim pContext As New PrincipalContext(ContextType.Machine)
        Dim pUser As New UserPrincipal(pContext)
        Dim pSearcher As New PrincipalSearcher(pUser)

        Dim User As Principal =
            (From u As Principal In pSearcher.FindAll
            Where u.Sid = UserSID).FirstOrDefault

        If User Is Nothing Then
            Throw New Exception(String.Format("User with SID '{0}' not found.", UserSID.Value))
        End If

        Try
            User.DisplayName = NewDisplayName
            User.Save()
            Return True

        Catch ex As InvalidOperationException
            Throw New Exception(ex.Message)

        Finally
            pContext.Dispose()
            pSearcher.Dispose()
            pUser.Dispose()

        End Try

        Return False ' Failed.

    End Function

#7205
Scripting / Re: [DUDA] Batch o FTP
7 Marzo 2014, 19:13 PM
Cita de: PedroDJavier en  7 Marzo 2014, 18:13 PMhaciendo 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
#7206
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!
#7207
Dudas Generales / Re: Timostar a lo suyo...
7 Marzo 2014, 01:57 AM
Cita de: Randomize en  6 Marzo 2014, 09:48 AM
Yo tengo ganas de una cosa "asín"...

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

Cita de: B€T€B€ en  6 Marzo 2014, 22:49 PMDonde 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!
#7208
Cita de: Intrus0 en  6 Marzo 2014, 22:13 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!
#7209
Cita de: Darhius en  6 Marzo 2014, 18:15 PM
Una aplicación que tengo dice que es esta.

application/octet-stream


Ok, gracias :)
#7210
FileType Detective

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

(Tipo 'MediaInfo')

Código (vbnet) [Seleccionar]
' ***********************************************************************
' Author   : Original: http://filetypedetective.codeplex.com/
'            Source translated, revised and extended by Elektro.
'
' Modified : 03-06-2014
' ***********************************************************************
' <copyright file="FileTypeDetective.vb" company="Elektro Studios">
'     Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************

#Region " Info "

' file headers are taken from here:
'http://www.garykessler.net/library/file_sigs.html

' mime types are taken from here:
' http://www.webmaster-toolkit.com/mime-types.shtml

#End Region

#Region " Usage Examples "

'Imports FileTypeDetective

'Public Class Form1

'    Private Sub Test() Handles MyBase.Load

'        MessageBox.Show(Detective.isType("C:\File.reg", FileType.REG)) ' NOTE: The regfile should be Unicode, not ANSI.
'        MessageBox.Show(Detective.GetFileType("C:\File.reg").mime)

'    End Sub

'End Class

#End Region

#Region " Imports "

Imports System.IO
Imports FileTypeDetective.FileType

#End Region

#Region " FileType Detective "

''' <summary>
''' Little data structure to hold information about file types.
''' Holds information about binary header at the start of the file
''' </summary>
Public Class FileType

    ' MS Office files
    Public Shared ReadOnly WORD As New FileType(
        New Nullable(Of Byte)() {&HEC, &HA5, &HC1, &H0}, 512I, "doc", "application/msword")

    Public Shared ReadOnly EXCEL As New FileType(
        New Nullable(Of Byte)() {&H9, &H8, &H10, &H0, &H0, &H6, &H5, &H0}, 512I, "xls", "application/excel")

    Public Shared ReadOnly PPT As New FileType(
        New Nullable(Of Byte)() {&HFD, &HFF, &HFF, &HFF, Nothing, &H0, &H0, &H0}, 512I, "ppt", "application/mspowerpoint")

    ' common documents
    Public Shared ReadOnly RTF As New FileType(
        New Nullable(Of Byte)() {&H7B, &H5C, &H72, &H74, &H66, &H31}, "rtf", "application/rtf")

    Public Shared ReadOnly PDF As New FileType(
        New Nullable(Of Byte)() {&H25, &H50, &H44, &H46}, "pdf", "application/pdf")

    Public Shared ReadOnly REG As New FileType(
        New Nullable(Of Byte)() {&HFF, &HFE}, "reg", "text/plain")

    ' grafics
    Public Shared ReadOnly JPEG As New FileType(
        New Nullable(Of Byte)() {&HFF, &HD8, &HFF}, "jpg", "image/jpeg")

    Public Shared ReadOnly PNG As New FileType(
        New Nullable(Of Byte)() {&H89, &H50, &H4E, &H47, &HD, &HA, &H1A, &HA}, "png", "image/png")

    Public Shared ReadOnly GIF As New FileType(
        New Nullable(Of Byte)() {&H47, &H49, &H46, &H38, Nothing, &H61}, "gif", "image/gif")

    ' Compressed
    Public Shared ReadOnly ZIP As New FileType(
        New Nullable(Of Byte)() {&H50, &H4B, &H3, &H4}, "zip", "application/x-compressed")

    Public Shared ReadOnly RAR As New FileType(
        New Nullable(Of Byte)() {&H52, &H61, &H72, &H21}, "rar", "application/x-compressed")

    ' all the file types to be put into one list
    Friend Shared ReadOnly types As New List(Of FileType)() From { _
        PDF,
        WORD,
        EXCEL,
        JPEG,
        ZIP,
        RAR,
        RTF,
        PNG,
        PPT,
        GIF,
        REG
    }

    ' number of bytes we read from a file
    Friend Const MaxHeaderSize As Integer = 560
    ' some file formats have headers offset to 512 bytes

    ' most of the times we only need first 8 bytes, but sometimes extend for 16
    Private m_header As Nullable(Of Byte)()
    Public Property header() As Nullable(Of Byte)()
        Get
            Return m_header
        End Get
        Private Set(value As Nullable(Of Byte)())
            m_header = value
        End Set
    End Property

    Private m_headerOffset As Integer
    Public Property headerOffset() As Integer
        Get
            Return m_headerOffset
        End Get
        Private Set(value As Integer)
            m_headerOffset = value
        End Set
    End Property

    Private m_extension As String
    Public Property extension() As String
        Get
            Return m_extension
        End Get
        Private Set(value As String)
            m_extension = value
        End Set
    End Property

    Private m_mime As String
    Public Property mime() As String
        Get
            Return m_mime
        End Get
        Private Set(value As String)
            m_mime = value
        End Set
    End Property

#Region " Constructors "

    ''' <summary>
    ''' Initializes a new instance of the <see cref="FileType"/> class.
    ''' Default construction with the header offset being set to zero by default
    ''' </summary>
    ''' <param name="header">Byte array with header.</param>
    ''' <param name="extension">String with extension.</param>
    ''' <param name="mime">The description of MIME.</param>
    Public Sub New(header As Nullable(Of Byte)(), extension As String, mime As String)
        Me.header = header
        Me.extension = extension
        Me.mime = mime
        Me.headerOffset = 0
    End Sub

    ''' <summary>
    ''' Initializes a new instance of the <see cref="FileType"/> struct.
    ''' Takes the details of offset for the header
    ''' </summary>
    ''' <param name="header">Byte array with header.</param>
    ''' <param name="offset">The header offset - how far into the file we need to read the header</param>
    ''' <param name="extension">String with extension.</param>
    ''' <param name="mime">The description of MIME.</param>
    Public Sub New(header As Nullable(Of Byte)(), offset As Integer, extension As String, mime As String)
        Me.header = Nothing
        Me.header = header
        Me.headerOffset = offset
        Me.extension = extension
        Me.mime = mime
    End Sub

#End Region

    Public Overrides Function Equals(other As Object) As Boolean

        If Not MyBase.Equals(other) Then
            Return False
        End If

        If Not (TypeOf other Is FileType) Then
            Return False
        End If

        Dim otherType As FileType = DirectCast(other, FileType)

        If Not Me.header Is otherType.header Then
            Return False
        End If

        If Me.headerOffset <> otherType.headerOffset Then
            Return False
        End If

        If Me.extension <> otherType.extension Then
            Return False
        End If

        If Me.mime <> otherType.mime Then
            Return False
        End If

        Return True

    End Function

    Public Overrides Function ToString() As String
        Return extension
    End Function

End Class

''' <summary>
''' Helper class to identify file type by the file header, not file extension.
''' </summary>
Public NotInheritable Class FileTypeDetective

    ''' <summary>
    ''' Prevents a default instance of the <see cref="FileTypeDetective"/> class from being created.
    ''' </summary>
    Private Sub New()
    End Sub

#Region "Main Methods"

    ''' <summary>
    ''' Gets the list of FileTypes based on list of extensions in Comma-Separated-Values string
    ''' </summary>
    ''' <param name="CSV">The CSV String with extensions</param>
    ''' <returns>List of FileTypes</returns>
    Private Shared Function GetFileTypesByExtensions(CSV As String) As List(Of FileType)
        Dim extensions As [String]() = CSV.ToUpper().Replace(" ", "").Split(","c)

        Dim result As New List(Of FileType)()

        For Each type As FileType In types
            If extensions.Contains(type.extension.ToUpper()) Then
                result.Add(type)
            End If
        Next
        Return result
    End Function

    ''' <summary>
    ''' Reads the file header - first (16) bytes from the file
    ''' </summary>
    ''' <param name="file">The file to work with</param>
    ''' <returns>Array of bytes</returns>
    Private Shared Function ReadFileHeader(file As FileInfo, MaxHeaderSize As Integer) As [Byte]()
        Dim header As [Byte]() = New Byte(MaxHeaderSize - 1) {}
        Try
            ' read file
            Using fsSource As New FileStream(file.FullName, FileMode.Open, FileAccess.Read)
                ' read first symbols from file into array of bytes.
                fsSource.Read(header, 0, MaxHeaderSize)
                ' close the file stream
            End Using
        Catch e As Exception
            ' file could not be found/read
            Throw New ApplicationException("Could not read file : " & e.Message)
        End Try

        Return header
    End Function

    ''' <summary>
    ''' Read header of a file and depending on the information in the header
    ''' return object FileType.
    ''' Return null in case when the file type is not identified.
    ''' Throws Application exception if the file can not be read or does not exist
    ''' </summary>
    ''' <param name="file">The FileInfo object.</param>
    ''' <returns>FileType or null not identified</returns>
    Public Shared Function GetFileType(file As FileInfo) As FileType
        ' read first n-bytes from the file
        Dim fileHeader As [Byte]() = ReadFileHeader(file, MaxHeaderSize)

        ' compare the file header to the stored file headers
        For Each type As FileType In types
            Dim matchingCount As Integer = 0
            For i As Integer = 0 To type.header.Length - 1
                ' if file offset is not set to zero, we need to take this into account when comparing.
                ' if byte in type.header is set to null, means this byte is variable, ignore it
                If type.header(i) IsNot Nothing AndAlso type.header(i) <> fileHeader(i + type.headerOffset) Then
                    ' if one of the bytes does not match, move on to the next type
                    matchingCount = 0
                    Exit For
                Else
                    matchingCount += 1
                End If
            Next
            If matchingCount = type.header.Length Then
                ' if all the bytes match, return the type
                Return type
            End If
        Next
        ' if none of the types match, return null
        Return Nothing
    End Function

    ''' <summary>
    ''' Read header of a file and depending on the information in the header
    ''' return object FileType.
    ''' Return null in case when the file type is not identified.
    ''' Throws Application exception if the file can not be read or does not exist
    ''' </summary>
    ''' <param name="file">The FileInfo object.</param>
    ''' <returns>FileType or null not identified</returns>
    Public Shared Function GetFileType(file As String) As FileType
        Return GetFileType(New FileInfo(file))
    End Function

    ''' <summary>
    ''' Determines whether provided file belongs to one of the provided list of files
    ''' </summary>
    ''' <param name="file">The file.</param>
    ''' <param name="requiredTypes">The required types.</param>
    ''' <returns>
    '''   <c>true</c> if file of the one of the provided types; otherwise, <c>false</c>.
    ''' </returns>
    Public Shared Function isFileOfTypes(file As FileInfo, requiredTypes As List(Of FileType)) As Boolean

        Dim currentType As FileType = GetFileType(file)

        If currentType Is Nothing Then
            Return False
        End If

        Return requiredTypes.Contains(currentType)

    End Function

    ''' <summary>
    ''' Determines whether provided file belongs to one of the provided list of files,
    ''' where list of files provided by string with Comma-Separated-Values of extensions
    ''' </summary>
    ''' <param name="file">The file.</param>
    ''' <returns>
    '''   <c>true</c> if file of the one of the provided types; otherwise, <c>false</c>.
    ''' </returns>
    Public Shared Function isFileOfTypes(file As FileInfo, CSV As String) As Boolean

        Dim providedTypes As List(Of FileType) = GetFileTypesByExtensions(CSV)

        Return isFileOfTypes(file, providedTypes)

    End Function

#End Region

#Region "isType functions"

    ''' <summary>
    ''' Determines whether the specified file is of provided type
    ''' </summary>
    ''' <param name="file">The file.</param>
    ''' <param name="type">The FileType</param>
    ''' <returns>
    '''   <c>true</c> if the specified file is type; otherwise, <c>false</c>.
    ''' </returns>
    Public Shared Function isType(file As FileInfo, type As FileType) As Boolean

        Dim actualType As FileType = GetFileType(file)

        If actualType Is Nothing Then
            Return False
        End If

        Return (actualType.Equals(type))

    End Function

    ''' <summary>
    ''' Determines whether the specified file is of provided type
    ''' </summary>
    ''' <param name="file">The file.</param>
    ''' <param name="type">The FileType</param>
    ''' <returns>
    '''   <c>true</c> if the specified file is type; otherwise, <c>false</c>.
    ''' </returns>
    Public Shared Function isType(file As String, type As FileType) As Boolean

        Return isType(New FileInfo(file), type)

    End Function

#End Region

End Class

#End Region