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


Tema destacado:


  Mostrar Mensajes
Páginas: 1 ... 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 [711] 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 ... 1258
7101  Programación / .NET (C#, VB.NET, ASP) / Re: Mis malas combinaciones :( en: 9 Agosto 2014, 21:01 pm
funciona bien hasta llegar a la función de combinar los numeros pero es un código de basic que quiero implementar pero no soy capaz ( como siempre)

¿Que es exactamente lo que "falla"?, y en caso de dar error, ¿cual es el error?.

saludos
7102  Foros Generales / Foro Libre / Re: Recomendacion sobre torrente en: 9 Agosto 2014, 16:45 pm
uTorrent es el o de los más pioneros, además es el más liviano.

saludos
7103  Programación / .NET (C#, VB.NET, ASP) / Re: Ayuda con un proyecto de c# en: 9 Agosto 2014, 00:44 am
Muchas gracias, cuando dijiste que si podía hacer ping a la página web no dude en buscar en Internet como se hacia en c# ya he conseguido lo que quería muchas gracias

No hay de que, no me merezco las gracias (ese código no es nada) pero te lo agradezco yo también.

Lo siento si soy muy malo pero como ya dije soy nuevo y no entiendo mucho de C#. Pero seguramente si no es este año sera el próximo le domine espero que me ayudes Gracias

Solo quiero comentar para dejar claro que:
Considero que no importa si una persona es buena o mala en lo que haga, lo que importa es el empeño que le ponga a lo que hace (y también el interés que demuestra a los demás), eso es lo que intenté decirte, por supuesto eres bien recibido por mi parte y mis (humildes) conocimientos están para que sirva de ayuda a los demás, pero no está bien visto (ni por mi, ni por la mayoría) que por muy experto o novato que sea alguien, éste pida cualquier tipo de ayuda relacionada con la programación sin haberlo intentado por si mismo, porque muchas personas se aprovechan de esto y lo piden todo echo sin querer aprender nada ...eso para mi es hacerle perder el tiempo a los demás, pero ya se que no es el caso contigo, solo lo estaba comentando y te sugiero que la próxima vez intentes mostrar un código, o urls en las que hayas investigado el problema, eso siempre ayuda.

Saludos!
7104  Programación / .NET (C#, VB.NET, ASP) / Re: Un par de consultas sobre teoría VB.net? son preguntas rápidas en: 9 Agosto 2014, 00:19 am
Citar
Que tiene de diferente crear una Aplicación WPF?

WPF (WindowsPresentationFoundation) usa un modelo muy distinto y más actual que un WF (WindowsForms), es el sucesor de WinForms (y desde hace mucho tiempo ya), el desarrollo de este tipo de aplicación WPF es completamente distinto, es más dificil, dando entrada a conceptos muy distintos que la mayoria de programadores de WinForms desconocen y/o les podría costar entender (como por ejemplo separar los Datos de la UI) dando entrada al uso de un lenguaje llamado XAML.

· Introduction to WPF
· Getting Started with WPF



Citar
Que es la Biblioteca de Clases?

(Doy por echo que entiendes lo que es una Class)

Un set/colección de Classes, no es más que eso, la librería de Classes de .NET Framework contiene todo tipo de miembros, Namespaces, Interfaces, Estructuras, Eventos, Excepciones, Enumeraciones, Delegados, etc...), se podría decir que practicamente contiene toda la funcionalidad del lenguaje.

Tienes un claro ejemplo en el propio Framework de Microsoft.

· Class Library (definición)
· .NET Framework Class Library



Citar
Que diferencia hay entre:

En mi opinión la pregunta debería ser "¿Que diferencia hay entre la Class "Form1" y el resto de Classes?"

Citar
Agregar Windows forms

Un Form (Formulario) es una representación visual de la interfaz gráfica, la class "Form1" (y el Form2 que agregarías desde el menú) se genera automaticamente por el Designer de VS, y dicha Class automaticamente hereda la Class Form, de otra manera no sería un Form. y no podría compilar

Código
  1. <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
  2. Partial Class Form1
  3.    Inherits System.Windows.Forms.Form
  4.    ...

Esa es la simple razón por la cual la Class Form1 te parece distinta al resto de Classes que puedes añadir a un proyecto, y porque puedes acceder a métodos como "Form1.Show()", "Form1.ShowDialog()", etc.


Citar
Agregar Clase

Una Class corriente vacía es una plantilla para la creación de Objetos, es decir, la creación de un conjunto de miembros entre los cuales suele haber métodos, variables, propiedades, etc...

Ejemplo:
La estructura inicial de una Class agregada es así:

Código
  1. Public Class Class1
  2.  
  3. End Class

Para que una Class pueda ser un Form, deberíamos herederar los miembros de la Class Form:

Código
  1. Public Class Class1 : Inherits Form
  2.  
  3. End Class

...Y entonces podrías utilizar la class Class1 como un Form, sería algo parecido a añadir un Form desde el menú contextual, pero sin haber creado la parte del Designer.

Citar
Agregar Nuevo elemento

Un 'nuevo elemento' es... es algo que no se puede globalizar, no soy capaz de hallar una respuesta apropiada que englobe esta pregunta, ya que cada elemento existente es muy distinto del otro.
7105  Programación / .NET (C#, VB.NET, ASP) / Re: Ayuda con un proyecto de c# en: 8 Agosto 2014, 23:28 pm
¿Cual es la duda exactamente, y donde está el código que demuestra tu progreso en ello?, debes saber que aquí no le hacemos el trabajo a nadie, ayudamos a hacerlo.

Por ese motivo quiero que sepas que no apruebo NADA ayudar y/o proporcionar este tipo de material a alguien que no muestra esfuerzo alguno, pero por otro lado este código ya lo tenía echo y no me cuesta nada compartirlo, eso sí, dado el caso no lo voy a traducir a C#, si tienes dificultades puedes proporcionar los datos necesarios que ya expliqué, o puedes usar convertidores online (ej: Telerik):

EDITO: Código eliminado, el código era muy extenso.

Podrías hacer un Ping a la dirección Web:

Código
  1.        Try
  2.            My.Computer.Network.Ping("www.google.com")
  3.            TextBox1.Text = "Conexión Satisfactoria"
  4.  
  5.        Catch ex As Net.NetworkInformation.PingException
  6.            TextBox1.Text = "Conexión Fallida"
  7.  
  8.        End Tryf

Imagino que con eso sería suficiente, aunque si tu conexión se encontrase demasiado saturada podría dar un falso positivo (porque no podría conectar con el server aunque estuviese online).

Saludos
7106  Foros Generales / Foro Libre / Re: Contrato de servicios de Microsoft en: 8 Agosto 2014, 23:22 pm
¿Que sentido tiene este mensaje?, digo yo que podrías haber echo una pequeña introducción a la informacion que pretendías mostrar...

De todas formas también creo que habia sido suficiente con mostrar el enlace ofial sin copiar su contenido, para tener una referencia oficial la cual como bien se especifica podría estar en constante actualización, y también para no perder los HyperLinks:

· Contrato de servicios de Microsoft

Saludos!
7107  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 8 Agosto 2014, 21:13 pm
como vi que funciono la primera vez pues no le presté mucha atención...

Funciona a la primera según se mire, ya que el que escribió ese snippet definió el uso de la codificación UTF-16 (Encoding.Unicode) para todos los casos.

Ahora como verás me he pasado poniendo usings, pero bueno >:D

No te has pasado, has echo lo correcto (me refiero a corregir los fallos del código, aparte de tener que escuchar mi típico sermón xD)

Saludos
7108  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 8 Agosto 2014, 20:59 pm
Ejemplo de como implementar la interface ISerializable e IXMLSerializable:

Código
  1. #Region " Imports "
  2.  
  3. Imports System.Runtime.Serialization
  4. Imports System.Security.Permissions
  5. Imports System.Xml.Serialization
  6. Imports System.Xml
  7.  
  8. #End Region
  9.  
  10. ''' <summary>
  11. ''' SerializableClassTest.
  12. ''' This class can be serialized.
  13. ''' </summary>
  14. <Serializable>
  15. <XmlRoot("SerializableClassTest")>
  16. Public Class SerializableClassTest : Implements ISerializable : Implements IXmlSerializable
  17.  
  18. #Region "Properties"
  19.  
  20.    Public Property StrValue As String
  21.    Public Property Int32Value As Integer
  22.  
  23. #End Region
  24.  
  25. #Region "Constructors"
  26.  
  27.    ''' <summary>
  28.    ''' Prevents a default instance of the <see cref="SerializableClassTest"/> class from being created.
  29.    ''' </summary>
  30.    Private Sub New()
  31.    End Sub
  32.  
  33.    ''' <summary>
  34.    ''' Initializes a new instance of the <see cref="SerializableClassTest"/> class.
  35.    ''' </summary>
  36.    Public Sub New(ByVal StrValue As String,
  37.                   ByVal Int32Value As Integer)
  38.  
  39.        Me.StrValue = StrValue
  40.        Me.Int32Value = Int32Value
  41.  
  42.    End Sub
  43.  
  44. #End Region
  45.  
  46. #Region "ISerializable implementation" ' For Binary serialization.
  47.  
  48.    ''' <summary>
  49.    ''' Populates a <see cref="T:SerializationInfo"/> with the data needed to serialize the target object.
  50.    ''' </summary>
  51.    ''' <param name="info">The <see cref="T:SerializationInfo"/> to populate with data.</param>
  52.    ''' <param name="context">The destination (see <see cref="T:StreamingContext"/>) for this serialization.</param>
  53.    <SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags:=SecurityPermissionFlag.SerializationFormatter)>
  54.    Protected Overridable Sub GetObjectData(ByVal info As SerializationInfo,
  55.                                            ByVal context As StreamingContext) Implements ISerializable.GetObjectData
  56.  
  57.        If info Is Nothing Then
  58.            Throw New ArgumentNullException("info")
  59.        End If
  60.  
  61.        With info
  62.  
  63.            .AddValue("PropertyName1", Me.StrValue, Me.StrValue.GetType)
  64.            .AddValue("PropertyName2", Me.Int32Value, Me.Int32Value.GetType)
  65.  
  66.        End With
  67.  
  68.    End Sub
  69.  
  70.    ''' <summary>
  71.    ''' Initializes a new instance of the <see cref="SerializableClassTest"/> class.
  72.    ''' This constructor is used to deserialize values.
  73.    ''' </summary>
  74.    ''' <param name="info">The information.</param>
  75.    ''' <param name="context">The context.</param>
  76.    Protected Sub New(ByVal info As SerializationInfo,
  77.                      ByVal context As StreamingContext)
  78.  
  79.        If info Is Nothing Then
  80.            Throw New ArgumentNullException("info")
  81.        End If
  82.  
  83.        Me.StrValue = info.GetString("PropertyName1")
  84.        Me.Int32Value = info.GetInt32("PropertyName2")
  85.  
  86.    End Sub
  87.  
  88. #End Region
  89.  
  90. #Region "IXMLSerializable implementation" ' For XML serialization.
  91.  
  92.    ''' <summary>
  93.    ''' This method is reserved and should not be used.
  94.    ''' When implementing the IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method,
  95.    ''' and instead, if specifying a custom schema is required, apply the <see cref="T:XmlSchemaProviderAttribute"/> to the class.
  96.    ''' </summary>
  97.    ''' <returns>
  98.    ''' An <see cref="T:Xml.Schema.XmlSchema"/> that describes the XML representation of the object
  99.    ''' that is produced by the <see cref="M:IXmlSerializable.WriteXml(Xml.XmlWriter)"/> method
  100.    ''' and consumed by the <see cref="M:IXmlSerializable.ReadXml(Xml.XmlReader)"/> method.
  101.    ''' </returns>
  102.    Public Function GetSchema() As Schema.XmlSchema Implements IXmlSerializable.GetSchema
  103.  
  104.        Return Nothing
  105.  
  106.    End Function
  107.  
  108.    ''' <summary>
  109.    ''' Converts an object into its XML representation.
  110.    ''' </summary>
  111.    ''' <param name="writer">The <see cref="T:Xml.XmlWriter"/> stream to which the object is serialized.</param>
  112.    Public Sub WriteXml(ByVal writer As XmlWriter) Implements IXmlSerializable.WriteXml
  113.  
  114.        writer.WriteElementString("PropertyName1", Me.StrValue)
  115.        writer.WriteElementString("PropertyName2", CStr(Me.Int32Value))
  116.  
  117.    End Sub
  118.  
  119.    ''' <summary>
  120.    ''' Generates an object from its XML representation.
  121.    ''' </summary>
  122.    ''' <param name="reader">The <see cref="T:Xml.XmlReader"/> stream from which the object is deserialized.</param>
  123.    Public Sub ReadXml(ByVal reader As XmlReader) Implements IXmlSerializable.ReadXml
  124.  
  125.        With reader
  126.  
  127.            .ReadStartElement(MyBase.GetType.Name)
  128.  
  129.            Me.StrValue = .ReadElementContentAsString
  130.            Me.Int32Value = .ReadElementContentAsInt
  131.  
  132.        End With
  133.  
  134.    End Sub
  135.  
  136. #End Region
  137.  
  138. End Class



Ejemplo de como usar la Class DeviceWatcher en un WinForms, sirve para detectar los eventos de inserción/extracción de los dispositivos, quizás se pueda utilizar como reemplazamiento del típico código de WMI para monitorizar USB's, pero todavía no le he podido sacar todo el jugo al asunto, poca documentación...

Código
  1. #Region " Instructions "
  2.  
  3.  
  4. ' 1. Create a new WinForms project targeting .NET Framework 4.5.
  5.  
  6.  
  7. ' 2. Close VisualStudio, open the 'YourProjectName.vbproj' file in a text-editor and add this property:
  8. ' *****************************************************************************************************
  9. '<PropertyGroup>
  10. '    ...
  11. '    <TargetPlatformVersion>8.0</TargetPlatformVersion>
  12. '    ...
  13. '</PropertyGroup>
  14.  
  15.  
  16. ' 3. Load the project in VisualStudio, open the 'References' menu and add these references:
  17. ' *****************************************************************************************
  18. ' C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\Facades\System.Runtime.dll
  19. ' C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\Facades\System.Runtime.InteropServices.WindowsRuntime.dll
  20.  
  21.  
  22. ' 4. In the 'References' menu, go to 'Windows > Core' tab and add these references:
  23. ' *********************************************************************************
  24. ' Windows.Devices
  25. ' Windows.Foundation
  26.  
  27.  
  28. #End Region
  29.  
  30. #Region " Imports "
  31.  
  32. Imports Windows.Devices.Enumeration
  33. Imports Windows.Foundation
  34.  
  35. #End Region
  36.  
  37. Public Class DeviceWatcher_Test
  38.  
  39.    Friend WithEvents dw As DeviceWatcher = DeviceInformation.CreateWatcher
  40.  
  41.    Private Sub Test() Handles MyBase.Load
  42.  
  43.        dw.Start()
  44.  
  45.    End Sub
  46.  
  47.    ''' <summary>
  48.    ''' Event that is raised when a device is added to the collection enumerated by the DeviceWatcher.
  49.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.enumeration.devicewatcher.added.aspx
  50.    ''' </summary>
  51.    ''' <param name="sender">The source of the event.</param>
  52.    ''' <param name="e">The <see cref="DeviceInformation"/> instance containing the event data.</param>
  53.    Private Sub dw_Added(ByVal sender As DeviceWatcher, ByVal e As DeviceInformation) _
  54.    Handles dw.Added
  55.  
  56.        Dim sb As New System.Text.StringBuilder
  57.  
  58.        With sb
  59.            .AppendLine("dw_added")
  60.            .AppendLine("********")
  61.            .AppendLine(String.Format("Interface ID.: {0}", e.Id))
  62.            .AppendLine(String.Format("Friendly Name: {0}", e.Name))
  63.            .AppendLine(String.Format("Is Enabled?..: {0}", e.IsEnabled))
  64.  
  65.            If e.Properties IsNot Nothing Then
  66.  
  67.                For Each item As KeyValuePair(Of String, Object) In e.Properties
  68.  
  69.                    If item.Value IsNot Nothing Then
  70.  
  71.                        .AppendLine(String.Format("TKey:{0}, TVal:{1} (TVal Type:{2})",
  72.                                                  item.Key, item.Value.ToString, item.Value.GetType.Name))
  73.  
  74.                    End If
  75.  
  76.                Next
  77.  
  78.            End If
  79.  
  80.        End With
  81.  
  82.        Debug.WriteLine(sb.ToString)
  83.  
  84.    End Sub
  85.  
  86.    ''' <summary>
  87.    ''' Event that is raised when a device is removed from the collection of enumerated devices.
  88.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.enumeration.devicewatcher.removed.aspx
  89.    ''' </summary>
  90.    ''' <param name="sender">The source of the event.</param>
  91.    ''' <param name="e">The <see cref="DeviceInformationUpdate"/> instance containing the event data.</param>
  92.    Private Sub dw_Removed(ByVal sender As DeviceWatcher, ByVal e As DeviceInformationUpdate) _
  93.    Handles dw.Removed
  94.  
  95.        Dim sb As New System.Text.StringBuilder
  96.  
  97.        With sb
  98.            .AppendLine("dw_Removed")
  99.            .AppendLine("**********")
  100.            .AppendLine(String.Format("Interface ID:{0}", e.Id))
  101.  
  102.            For Each item As KeyValuePair(Of String, Object) In e.Properties
  103.                .AppendLine(String.Format("TKey:{0}, TVal:{1} (TVal Type:{2})",
  104.                                          item.Key, item.Value.ToString, item.Value.GetType.Name))
  105.            Next
  106.  
  107.        End With
  108.  
  109.        Debug.WriteLine(sb.ToString)
  110.  
  111.    End Sub
  112.  
  113.    ''' <summary>
  114.    ''' Event that is raised when a device is updated in the collection of enumerated devices.
  115.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.enumeration.devicewatcher.updated.aspx
  116.    ''' </summary>
  117.    ''' <param name="sender">The source of the event.</param>
  118.    ''' <param name="e">The <see cref="DeviceInformationUpdate"/> instance containing the event data.</param>
  119.    Private Sub dw_Updated(ByVal sender As DeviceWatcher, ByVal e As DeviceInformationUpdate) _
  120.    Handles dw.Updated
  121.  
  122.        Dim sb As New System.Text.StringBuilder
  123.  
  124.        With sb
  125.            .AppendLine("dw_Updated")
  126.            .AppendLine("**********")
  127.            .AppendLine(String.Format("Interface ID: {0}", e.Id))
  128.  
  129.            For Each item As KeyValuePair(Of String, Object) In e.Properties
  130.  
  131.                If item.Key.EndsWith("InterfaceEnabled", StringComparison.OrdinalIgnoreCase) Then
  132.                    Dim Result As Boolean = CBool(item.Value)
  133.                    .AppendLine(String.Format("The device is accessible?:{0}", CStr(Result)))
  134.  
  135.                Else
  136.                    .AppendLine(String.Format("TKwy:{0}, TVal:{1} (TVal Type:{2})",
  137.                                              item.Key, item.Value.ToString, item.Value.GetType.Name))
  138.  
  139.                End If
  140.  
  141.            Next
  142.  
  143.        End With
  144.  
  145.        Debug.WriteLine(sb.ToString)
  146.  
  147.    End Sub
  148.  
  149.    ''' <summary>
  150.    ''' Event that is raised when the enumeration operation has been stopped.
  151.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.enumeration.devicewatcher.stopped.aspx
  152.    ''' </summary>
  153.    ''' <param name="sender">The source of the event.</param>
  154.    ''' <param name="e">The object containing the event data.</param>
  155.    Private Sub dw_Stopped(ByVal sender As DeviceWatcher, ByVal e As Object) _
  156.    Handles dw.Stopped
  157.  
  158.        Dim sb As New System.Text.StringBuilder
  159.  
  160.        With sb
  161.            .AppendLine("dw_Stopped")
  162.            .AppendLine("**********")
  163.            .AppendLine(String.Format("e:{1} (e Type:{2})",
  164.                                      e.ToString, e.GetType.Name))
  165.  
  166.        End With
  167.  
  168.        Debug.WriteLine(sb.ToString)
  169.  
  170.    End Sub
  171.  
  172.    ''' <summary>
  173.    ''' Event that is raised when the enumeration of devices completes.
  174.    ''' MSDN Documentation: http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.enumeration.devicewatcher.enumerationcompleted.aspx
  175.    ''' </summary>
  176.    ''' <param name="sender">The source of the event.</param>
  177.    ''' <param name="e">The object containing the event data.</param>
  178.    Private Sub dw_EnumerationCompleted(ByVal sender As DeviceWatcher, ByVal e As Object) _
  179.    Handles dw.EnumerationCompleted
  180.  
  181.        If e IsNot Nothing Then
  182.  
  183.            Dim sb As New System.Text.StringBuilder
  184.  
  185.            With sb
  186.                .AppendLine("EnumerationCompleted")
  187.                .AppendLine("********************")
  188.                .AppendLine(String.Format("e:{1} (e Type:{2})",
  189.                                          e.ToString, e.GetType.Name))
  190.  
  191.            End With
  192.  
  193.            Debug.WriteLine(sb.ToString)
  194.  
  195.        End If
  196.  
  197.    End Sub
  198.  
  199. End Class
  200.  
7109  Programación / .NET (C#, VB.NET, ASP) / Re: Problema con formatos VB.NET 2010, Access 2007[SOLUCIONADO] en: 8 Agosto 2014, 18:31 pm
Aun queda la duda de como es posible que los permisos de usuario de "X" App influyan en el código hasta el punto de lanzar una excepción de Casteo? xD, ¿es posible que el objeto "cmd" sea un proceso que ejecutes vía CMD y al no tener permisos suficientes éste en lugar de devoler un valor numérico devolviese un mensaje de error (String) sobre los permisos o algo? ...esa podría ser una causa, bueno sea como sea me alegro de que lo hayas solucionado.

Saludos
7110  Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets !! (Compartan aquí sus snippets) en: 8 Agosto 2014, 18:11 pm
Creo que algunas de estas utilidades están ya presentes dentro de lo que es la super colección de Elektro, pero bueno supongo que un indentador XML nunca se ha visto por aquí así que aquí va:

precisamente estoy harto de que cierta utilidad de Microsoft me genere los archivos de manifiesto sin ningún tipo de indentación, esto me sirve ;).

EDITO: en un principio iba a ahorrarme comentarios sobre posibles mejoras de código o etc, pero hay un fallo importante que se debe corregir, no estás liberando el memorystream:
Citar
Código
  1. Dim w As New MemoryStream()

Ni tampoco el Writer ni el Reader xD

Por cierto la Class XMLTextWriter está obsoleta, en su defecto Microsoft recomienda el uso de XMLWriter.

EDITO 2: Me he tomado la libertad de editar el código original enfocándolo de otra manera (aunque tampoco es tan distinto):

Ejemplo de uso:

Código
  1.        Dim TextEncoding As System.Text.Encoding = System.Text.Encoding.Default
  2.        Dim UnformattedXMLDocument As String = IO.File.ReadAllText("C:\Unformatted Document.xml", TextEncoding)
  3.        Dim FormattedXMLDocument As String = XMLBeautify(XMLText:=UnformattedXMLDocument,
  4.                                                         IndentChars:=New String(" "c, 2),
  5.                                                         IndentOnAttributes:=False,
  6.                                                         TextEncoding:=TextEncoding)
  7.  
  8.        IO.File.WriteAllText("C:\Formatted Document.xml", FormattedXMLDocument, TextEncoding)


Snippet:

Código
  1.    ''' <summary>
  2.    ''' Beautifies the contents of an unindented XML document.
  3.    ''' </summary>
  4.    ''' <param name="XMLText">
  5.    ''' The XML text content.
  6.    ''' It can be an entire document or a fragment.
  7.    ''' </param>
  8.    ''' <param name="IndentChars">
  9.    ''' The string that is used to indent the XML.
  10.    ''' Default value is: <see cref="ControlChars.Tab"/>
  11.    ''' </param>
  12.    ''' <param name="IndentOnAttributes">
  13.    ''' If set to <c>true</c>, attributes will be separated by newlines.
  14.    ''' Default value is: <c>false</c>
  15.    ''' </param>
  16.    ''' <param name="TextEncoding">
  17.    ''' The XML text encoding to use.
  18.    ''' Default value is: <see cref="System.Text.Encoding.Default"/>.
  19.    ''' </param>
  20.    ''' <returns>The beautified XML text.</returns>
  21.    ''' <exception cref="System.ArgumentNullException"></exception>
  22.    Public Shared Function XMLBeautify(ByVal XMLText As String,
  23.                                       Optional ByVal IndentChars As String = Nothing,
  24.                                       Optional ByVal IndentOnAttributes As Boolean = False,
  25.                                       Optional ByVal TextEncoding As System.Text.Encoding = Nothing) As String
  26.  
  27.        If String.IsNullOrEmpty(XMLText) Then
  28.            Throw New ArgumentNullException(XMLText)
  29.        End If
  30.  
  31.        Dim sb As New System.Text.StringBuilder
  32.        Dim doc As New Xml.XmlDocument()
  33.        Dim settings As New Xml.XmlWriterSettings
  34.  
  35.        With settings
  36.            .Indent = True
  37.            .CheckCharacters = True
  38.            .OmitXmlDeclaration = False
  39.            .ConformanceLevel = Xml.ConformanceLevel.Auto
  40.            .NamespaceHandling = Xml.NamespaceHandling.Default
  41.            .NewLineHandling = Xml.NewLineHandling.Replace
  42.            .NewLineChars = ControlChars.NewLine
  43.            .NewLineOnAttributes = IndentOnAttributes
  44.            .IndentChars = If(IndentChars IsNot Nothing, IndentChars, ControlChars.Tab)
  45.            .Encoding = If(TextEncoding IsNot Nothing, TextEncoding, System.Text.Encoding.Default)
  46.        End With
  47.  
  48.        Using writer As Xml.XmlWriter = Xml.XmlWriter.Create(sb, settings)
  49.            doc.LoadXml(XMLText)
  50.            doc.WriteContentTo(writer)
  51.            writer.Flush()
  52.            Return sb.ToString
  53.        End Using
  54.  
  55.    End Function
  56.  
  57.    ''' <summary>
  58.    ''' Beautifies the contents of an unindented XML document.
  59.    ''' </summary>
  60.    ''' <param name="XMLFile">
  61.    ''' An <see cref="T:IO.FileInfo"/> that contains the XML info.
  62.    ''' It can be an entire document or a fragment.
  63.    ''' </param>
  64.    ''' <param name="IndentChars">
  65.    ''' The string that is used to indent the XML.
  66.    ''' Default value is: <see cref="ControlChars.Tab"/>
  67.    ''' </param>
  68.    ''' <param name="IndentOnAttributes">
  69.    ''' If set to <c>true</c>, attributes will be separated by newlines.
  70.    ''' Default value is: <c>false</c>
  71.    ''' </param>
  72.    ''' <param name="TextEncoding">
  73.    ''' The XML text encoding to use.
  74.    ''' Default value is: <see cref="System.Text.Encoding.Default"/>.
  75.    ''' </param>
  76.    ''' <returns>The beautified XML text.</returns>
  77.    ''' <exception cref="System.ArgumentNullException"></exception>
  78.    Public Shared Function XMLBeautify(XMLFile As IO.FileInfo,
  79.                                       Optional ByVal IndentChars As String = Nothing,
  80.                                       Optional ByVal IndentOnAttributes As Boolean = False,
  81.                                       Optional ByVal TextEncoding As System.Text.Encoding = Nothing) As String
  82.  
  83.        Return XMLBeautify(IO.File.ReadAllText(XMLFile.FullName, TextEncoding), IndentChars, IndentOnAttributes, TextEncoding)
  84.  
  85.    End Function



Posibles outputs:

1º:

Código
  1. <savedata>
  2.  <SoftwareType>Freeware</SoftwareType>
  3.  <SoftwareID>Moo0 FileMonitor</SoftwareID>
  4.  <Version>1.11</Version>
  5.  <MainWindow>
  6.    <SoftwareType>Freeware</SoftwareType>
  7.    <SoftwareID>Moo0 FileMonitor</SoftwareID>
  8.    <Version>1.11</Version>
  9.    <View F="0" E="0" D="0" RefreshFrequency="500" LogUpTo="20000" EasyDrag="1" Maximized="0" X="958" Y="453" Width="962" Height="585" KeepOnTop="0"></View>
  10.    <ChangesColumnOrder length="6" _0="0" _1="1" _2="2" _3="3" _4="4" _5="5"></ChangesColumnOrder>
  11.  </MainWindow>
  12.  <Skin>Classic LG</Skin>
  13. </savedata>


2º:
Código
  1. <savedata>
  2.  <SoftwareType>Freeware</SoftwareType>
  3.  <SoftwareID>Moo0 FileMonitor</SoftwareID>
  4.  <Version>1.11</Version>
  5.  <MainWindow>
  6.    <SoftwareType>Freeware</SoftwareType>
  7.    <SoftwareID>Moo0 FileMonitor</SoftwareID>
  8.    <Version>1.11</Version>
  9.    <View
  10.      F="0"
  11.      E="0"
  12.      D="0"
  13.      RefreshFrequency="500"
  14.      LogUpTo="20000"
  15.      EasyDrag="1"
  16.      Maximized="0"
  17.      X="958"
  18.      Y="453"
  19.      Width="962"
  20.      Height="585"
  21.      KeepOnTop="0"></View>
  22.    <ChangesColumnOrder
  23.      length="6"
  24.      _0="0"
  25.      _1="1"
  26.      _2="2"
  27.      _3="3"
  28.      _4="4"
  29.      _5="5"></ChangesColumnOrder>
  30.  </MainWindow>
  31.  <Skin>Classic LG</Skin>
  32. </savedata>

Saludos
Páginas: 1 ... 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 [711] 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 ... 1258
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines