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

 

 


Tema destacado:


  Mostrar Mensajes
Páginas: 1 ... 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 [473] 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 ... 1236
4721  Programación / .NET (C#, VB.NET, ASP) / Re: [SOURCE] Algoritmo KeyLogger (RawInput) en: 5 Septiembre 2015, 17:38 pm
Estuve leyendo sobre GetRawInputData, y hay que establecer el parseo de mensajes en WM_INPUT, si hay alguna ventana privilegiada en el sistema puede no funcionar verdad? Dado que el parseo de mensajes tanto como el de eventos sobre las coordenadas o durante la ejecucion de algo con privilegios en las ultimas versiones de Windows siempre me ha dado problemas consulto :P

Parece como que dispararia varias alarmas a nivel de sistema tambien.. Has hecho alguna prueba de concepto como para probar?

La documentación oficial en MSDN explica poquito y me deja algunas cosas con interrogantes, pero de todas formas el mensaje de ventana WM_INPUT es posteado en la cola de mensajes de la o las aplicaciones que se hayan registrado con RegisterRawInputDevices, particularmente del thread desde el que se haya registrado (normalmente el thread de la UI, ya que se necesita un HWND para la estructura RAWINPUTDEVICE), por ende, en principio creo que no tendría por qué dar problema alguno ya que teorica o supuestamente el mensaje le llegará a todas las ventanas que cumplan ese requisito, sean privilegiadas o no, sin embargo, quizás tambien pueda depender de otros factores (limitaciones, errores humanos, u otras cosas secundarias a tener en cuenta), ya que por ejemplo, con el tipo de hooking convencional, es decir, el uso de LowLevelKeyboardProc y LowLevelMouseProc, hay que tener mucho cuidado con el parámetro nCode que se devuelva tras procesar los mensajes, ya que si no se hace correctamente, entonces podría provocar un conflicto en el sistema que acabaría "bloqueando" el mensaje para el resto de aplicaciones, las cuales no podría procesarlo (durante el tiempo de vida de la app o thread, no es algo permanente claro está), tal vez eso sea lo que hayas podido experimentar en el pasado con los hooks, ya que al menos yo pasé por eso mismo cuando empecé a trastear con los windows_messages para un ll-hook del mouse, o tal vez te refieras a otro tipo de conflicto ?.

Sobre las pruebas, hombre, no voy a compartir algo sin comprobar que funciona lo que hice xD, pero fueron pruebas de uso básico o digamos "ético", quiero decir, no con seguridad de terceros implementada en el S.O, ni tampoco UAC ni nada, ni con otras aplicaciones en segundo plano registradas con RAWINPUT, pero ya digo, que en pricnipio no debería dar problemas...

Si descubres algo, un conflicto o lo que sea que se pueda mejorar, házmelo saber.

saludos!
4722  Programación / .NET (C#, VB.NET, ASP) / Re: [C#] [Aporte] Administrador de archivos (crear/leer/editar/borrar) en: 5 Septiembre 2015, 16:29 pm
Gracias por compartir con los demás.

saludos
4723  Programación / .NET (C#, VB.NET, ASP) / Re: [C#] ¿Programas ha realizar en consola? (Pregunta) en: 5 Septiembre 2015, 16:23 pm
¿Y por qué no es recomendado hacer juegos en .NET? ¿no tiene potencial?

Cuando escucho "desarrollo de juegos" tengo la mala costumbre de pensar a lo grande (un GTA V), sin embargo, para un ahorcado por supuesto que te sirve .Net.

También tengo la costumbre de pensar en VB.Net al escuchar ".Net", donde, al contrario que C# (aunque esta es una de las escasas diferencias entre ambos lenguajes, ya que internamente son practicamente igual), no se puede aplicar la manipulación directa de punteros (con el uso del operador de eliminación de referencias) por ejemplo sobre gigantescos Arrays de datos que contengan los píxeles de una imagen, lo que de ser posible, bien hecho aceleraría el rendimiento del juego en general.

Realmente se muy, muy poquito sobre el Game development, pero dime al menos 3 juegos, 3 buenos juegos que no consistan en mover simples imágenes estáticas (naves, rpgs, ahorcados, etc), que estén desarrollados bajo .Net (no hibridados, no Unity) y entonces cambiaré de idea xD.

Saludos
4724  Programación / .NET (C#, VB.NET, ASP) / Re: [C#] Editar líneas de archivos de texto en: 5 Septiembre 2015, 15:54 pm
El problema lo has solucionado de la manera más incorrecta, ya que no has aprendido a cómo solucionar los errores que tenías, simplemente has preferido optar por utilizar otra metodología distinta para evitar encontrarte con esos errores. ¿te compensa?, piensalo.

Lee el comentario de @Dark_Firefox y si no entiendes algo pregunta hasta que lo entiendas, por que de lo contrario el mismo conflicto te va a volver a suceder una y otra vez y no sabrás por qué, ya que un objeto sin inicializar (accidentálmente) es un despiste humano muy típico, y algo muy sencillo de comprender y solucionar.



me salta este error:



En esta línea:
Código
  1. using (StreamReader fileRead = new StreamReader(@"C:\Users\Usuario\Desktop\Textos\carpetaArchivos\" + nombreArchivo + ".txt"))

El mensaje de error se explica por si mismo, justo antes de esa instrucción ya tienes el archivo abierto con esto:
Citar
Código
  1. Using fileWrite As New StreamWriter("C:\Users\Usuario\Desktop\Textos\carpetaArchivos\" + nombreArchivo + ".txt")

Cuando "abres" un archivo se crea un handle especial en el sistema, el cual no puedes compartir con otro proceso (ni con tu propio proceso) a menos que así lo indiques, entonces no puedes esperar mantener abierto el archivo para su lectura mientras al mismo tiempo intentas abrirlo de nuevo para su escritura, sin embargo, si que puedes mantenerlo abierto con ambos permisos al mismo tiempo.

Lo que puedes hacer es utilizar el overload que toma cómo parámetro un stream, de la siguiente manera:

Código
  1. using (FileStream fs = File.Open("C:\\file.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.None)) {
  2.  
  3. using (StreamReader sr = new StreamReader(stream: fs, encoding: Encoding.Default)) {
  4.  
  5. using (StreamWriter sw = new StreamWriter(stream: fs, encoding: Encoding.Default)) {
  6.  
  7. while (!(sr.EndOfStream)) {
  8.  
  9.                                string line = sr.ReadLine;
  10.                                // Leer o escribir en el stream...
  11.  
  12. }
  13.  
  14. } // sw
  15.  
  16. } // sr
  17.  
  18. } // fs

De todas formas yo optaría por evitar el uso de StreamReader, StreamWriter y demás, ya que tu intención no es mantener el archivo abierto mientras le haces cambios durante el tiempo de vida del proceso (ej. un sistema de logging), es un cambio pequeño y sencillo así que no requiere más que la solución que encontraste usando LINQ, aunque es imprecisa, pues yo, siguiendo la linea del último ejemplo, y siendo consciente de "donde está todo escrito" y cómo lo está, sin posibilidad a errores, lo haría más bien así:

Código
  1.    <Serializable>
  2.    Public NotInheritable Class Contact
  3.  
  4.        Public Property Name As String
  5.        Public Property Surname As String
  6.  
  7.    End Class
  8.  
  9.    Private Function GetContact(ByVal filePath As String) As Contact
  10.  
  11.        Const FieldName As String = "Nombre:"
  12.        Const FieldSurname As String = "Apellidos:"
  13.  
  14.        Dim lines As IEnumerable(Of String) = File.ReadAllLines(filePath, Encoding.Default)
  15.  
  16.        If (lines.Count <> 2) Then
  17.            Throw New Exception(message:="Número incorrecto de lineas.")
  18.        End If
  19.  
  20.        Dim currentName As String =
  21.            lines(0).Substring(lines(0).IndexOf(FieldName, StringComparison.OrdinalIgnoreCase) + FieldName.Length).
  22.                 Trim(" "c)
  23.  
  24.        Dim currentSurname As String =
  25.            lines(1).Substring(lines(1).IndexOf(FieldSurname, StringComparison.OrdinalIgnoreCase) + FieldSurname.Length).
  26.                 Trim(" "c)
  27.  
  28.        Return New Contact With
  29.               {
  30.                   .Name = currentName,
  31.                   .Surname = currentSurname
  32.               }
  33.  
  34.    End Function
  35.  
  36.    Private Sub SetContact(ByVal filepath As String, ByVal contact As Contact)
  37.  
  38.        Const FieldName As String = "Nombre"
  39.        Const FieldSurname As String = "Apellidos"
  40.  
  41.        Dim sb As New StringBuilder
  42.        sb.AppendLine(String.Format("{0}: {1}", FieldName, contact.Name))
  43.        sb.AppendLine(String.Format("{0}: {1}", FieldSurname, contact.Surname))
  44.  
  45.        File.WriteAllText(filepath, sb.ToString, Encoding.Default)
  46.  
  47.    End Sub

Para darle el siguiente uso:

Código
  1. Dim filePath As String = "C:\file.txt"
  2.  
  3. Dim currentContact As Contact = GetContact(filePath)
  4.  
  5. Console.WriteLine(String.Format("Name...: {0}", currentcontact.Name))
  6. Console.WriteLine(String.Format("Surname: {0}", currentcontact.Surname))
  7.  
  8. currentContact.Name = "Pepito"
  9. currentContact.Surname = "Palotes"
  10.  
  11. Me.SetContact("C:\file.txt", currentContact)

Código traducido a C#:

Código
  1. [Serializable()]
  2. public sealed class Contact
  3. {
  4.  
  5. public string Name { get; set; }
  6. public string Surname { get; set; }
  7.  
  8. }

Código
  1. using Microsoft.VisualBasic;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Data;
  6. using System.Diagnostics;
  7. using System.IO;
  8. using System.Text;
  9.  
  10. public sealed class Form1 : Form
  11. {
  12.  
  13. private void Test()
  14. {
  15. string filePath = "C:\\file.txt";
  16.  
  17. Contact currentContact = GetContact(filePath);
  18.  
  19. Console.WriteLine(string.Format("Name...: {0}", currentContact.Name));
  20. Console.WriteLine(string.Format("Surname: {0}", currentContact.Surname));
  21.  
  22. currentContact.Name = "Pepito";
  23. currentContact.Surname = "Palotes";
  24.  
  25. this.SetContact("C:\\file.txt", currentContact);
  26.  
  27. }
  28.  
  29. private Contact GetContact(string filePath)
  30. {
  31.  
  32. const string FieldName = "Nombre:";
  33. const string FieldSurname = "Apellidos:";
  34.  
  35. IEnumerable<string> lines = File.ReadAllLines(filePath, Encoding.Default);
  36.  
  37. if ((lines.Count != 2)) {
  38. throw new Exception(message: "Número incorrecto de lineas.");
  39. }
  40.  
  41. string currentName = lines(0).Substring(lines(0).IndexOf(FieldName, StringComparison.OrdinalIgnoreCase) + FieldName.Length).Trim(' ');
  42.  
  43. string currentSurname = lines(1).Substring(lines(1).IndexOf(FieldSurname, StringComparison.OrdinalIgnoreCase) + FieldSurname.Length).Trim(' ');
  44.  
  45. return new Contact {
  46. Name = currentName,
  47. Surname = currentSurname
  48. };
  49.  
  50. }
  51.  
  52.  
  53. private void SetContact(string filepath, Contact contact)
  54. {
  55. const string FieldName = "Nombre";
  56. const string FieldSurname = "Apellidos";
  57.  
  58. StringBuilder sb = new StringBuilder();
  59. sb.AppendLine(string.Format("{0}: {1}", FieldName, contact.Name));
  60. sb.AppendLine(string.Format("{0}: {1}", FieldSurname, contact.Surname));
  61.  
  62. File.WriteAllText(filepath, sb.ToString, Encoding.Default);
  63.  
  64. }
  65.  
  66. }
  67.  
  68. //=======================================================
  69. //Service provided by Telerik (www.telerik.com)
  70. //=======================================================



PEEEEEEEEERO... en mi humilde opinión debo mencionar que la metodología que empleas en el primer y el segundo ejemplo que has mostrado (y también la que yo he empleado en el último ejemplo de arriba) en realidad es bastante primitiva, ya que aprendiendo a cómo manipular un archivo de texto tipo "contacto" de esa manera en realidad no aprendes nada útil. Si fuese para otra cosa, tal vez, pero para contactos lo que deberías usar, repito, en mi opinión, sería la serialización de datos, no por la ofuscación de datos, sino simplemente por que aporta mucho más control y seguridad sobre las acciones que haces en el archivo, en lugar de tener que estar "partiendo" y evaluando string a string ya que hay muchos posibles fallos que necesitarían ser controlados manualmente. Al menos deberías probar la serialización de datos para familiarizarte con esto.

Un ejemplo:

(si quieres que los datos sean legibles, puedes utilizar la serialización XML)

Código
  1. ' ***********************************************************************
  2. ' Author   : Elektro
  3. ' Modified : 05-September-2015
  4. ' ***********************************************************************
  5. ' <copyright file="SerializationUtil.vb" company="Elektro Studios">
  6. '     Copyright (c) Elektro Studios. All rights reserved.
  7. ' </copyright>
  8. ' ***********************************************************************
  9.  
  10.  
  11.  
  12. ' ESTA CLASE ESTÁ PARCIALMENTE DEFINIDA (O PARCIALMENTE CAPADA) SOLO PARA SATISFACER LAS NECESIDADES DE ESTA PREGUNTA.
  13.  
  14.  
  15.  
  16. #Region " Imports "
  17.  
  18. Imports System
  19. Imports System.Data
  20. Imports System.IO
  21. Imports System.Linq
  22. Imports System.Runtime.Serialization.Formatters.Binary
  23. Imports System.Xml.Serialization
  24.  
  25. #End Region
  26.  
  27. ''' <summary>
  28. ''' Contains related serialization utilities.
  29. ''' </summary>
  30. Public NotInheritable Class SerializationUtil
  31.  
  32. #Region " Constructors "
  33.  
  34.    ''' ----------------------------------------------------------------------------------------------------
  35.    ''' <summary>
  36.    ''' Prevents a default instance of the <see cref="SerializationUtil"/> class from being created.
  37.    ''' </summary>
  38.    ''' ----------------------------------------------------------------------------------------------------
  39.    Private Sub New()
  40.    End Sub
  41.  
  42. #End Region
  43.  
  44. #Region " Private Methods "
  45.  
  46.    ''' ----------------------------------------------------------------------------------------------------
  47.    ''' <exception cref="System.ArgumentException">
  48.    ''' Wrong Serialization Format.
  49.    ''' </exception>
  50.    ''' ----------------------------------------------------------------------------------------------------
  51.    <DebuggerStepThrough>
  52.    <DebuggerHidden>
  53.    Private Shared Function GetSerializer(Of T)(ByVal format As SerializationFormat) As Object
  54.  
  55.        Select Case format
  56.  
  57.            Case SerializationFormat.Binary
  58.                Return New BinaryFormatter
  59.  
  60.            Case SerializationFormat.Xml
  61.                Return New XmlSerializer(type:=GetType(T))
  62.  
  63.            Case Else
  64.                Throw New ArgumentException(message:="Wrong Serialization Format.", paramName:="serializationFormat")
  65.  
  66.        End Select
  67.  
  68.    End Function
  69.  
  70. #End Region
  71.  
  72. #Region " Public Methods "
  73.  
  74.    ''' ----------------------------------------------------------------------------------------------------
  75.    ''' <summary>
  76.    ''' Serializes the data of an Object to the specified file, using the specified serialization format.
  77.    ''' </summary>
  78.    ''' ----------------------------------------------------------------------------------------------------
  79.    ''' <typeparam name="T">
  80.    ''' </typeparam>
  81.    '''
  82.    ''' <param name="obj">
  83.    ''' The object to be serialized.
  84.    ''' </param>
  85.    '''
  86.    ''' <param name="filepath">
  87.    ''' The filepath where to save the serialized data.
  88.    ''' </param>
  89.    '''
  90.    ''' <param name="format">
  91.    ''' The serialization format.
  92.    ''' </param>
  93.    ''' ----------------------------------------------------------------------------------------------------
  94.    <DebuggerStepThrough>
  95.    <DebuggerHidden>
  96.    Public Shared Sub Serialize(Of T)(ByVal obj As T,
  97.                                      ByVal filepath As String,
  98.                                      ByVal format As SerializationFormat)
  99.  
  100.        Dim serializer As Object = SerializationUtil.GetSerializer(Of T)(format)
  101.  
  102.        Using fs As New FileStream(filepath, FileMode.Create, FileAccess.Write, FileShare.Read)
  103.  
  104.            Select Case serializer.GetType
  105.  
  106.                Case GetType(BinaryFormatter)
  107.                    DirectCast(serializer, BinaryFormatter).Serialize(fs, obj)
  108.  
  109.                Case GetType(XmlSerializer)
  110.                    DirectCast(serializer, XmlSerializer).Serialize(fs, obj)
  111.  
  112.            End Select
  113.  
  114.        End Using
  115.  
  116.    End Sub
  117.  
  118.    ''' ----------------------------------------------------------------------------------------------------
  119.    ''' <summary>
  120.    ''' Deserializes the data of an Object from the specified file, using the specified deserialization format.
  121.    ''' </summary>
  122.    ''' ----------------------------------------------------------------------------------------------------
  123.    ''' <typeparam name="T">
  124.    ''' </typeparam>
  125.    '''
  126.    ''' <param name="filepath">
  127.    ''' The filepath where from deserialize the serialized data.
  128.    ''' </param>
  129.    '''
  130.    ''' <param name="format">
  131.    ''' The serialization format.
  132.    ''' </param>
  133.    ''' ----------------------------------------------------------------------------------------------------
  134.    <DebuggerStepThrough>
  135.    <DebuggerHidden>
  136.    Public Shared Function Deserialize(Of T)(ByVal filepath As String,
  137.                                             ByVal format As SerializationFormat) As T
  138.  
  139.        Dim serializer As Object = SerializationUtil.GetSerializer(Of T)(format)
  140.  
  141.        Using fs As New FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read)
  142.  
  143.            Select Case serializer.GetType
  144.  
  145.                Case GetType(BinaryFormatter)
  146.                    Return DirectCast(DirectCast(serializer, BinaryFormatter).Deserialize(fs), T)
  147.  
  148.                Case GetType(XmlSerializer)
  149.                    Return DirectCast(DirectCast(serializer, XmlSerializer).Deserialize(fs), T)
  150.  
  151.            End Select
  152.  
  153.        End Using
  154.  
  155.    End Function
  156.  
  157.    ''' ----------------------------------------------------------------------------------------------------
  158.    ''' <summary>
  159.    ''' Deserializes the data of an Object from the specified file, using the specified deserialization format.
  160.    ''' </summary>
  161.    ''' ----------------------------------------------------------------------------------------------------
  162.    ''' <typeparam name="T">
  163.    ''' </typeparam>
  164.    '''
  165.    ''' <param name="filepath">
  166.    ''' The filepath where from deserialize the serialized data.
  167.    ''' </param>
  168.    '''
  169.    ''' <param name="format">
  170.    ''' The serialization format.
  171.    ''' </param>
  172.    ''' ----------------------------------------------------------------------------------------------------
  173.    <DebuggerStepThrough>
  174.    <DebuggerHidden>
  175.    Public Shared Sub Deserialize(Of T)(ByRef refObj As T,
  176.                                        ByVal filepath As String,
  177.                                        ByVal format As SerializationFormat)
  178.  
  179.        refObj = SerializationUtil.Deserialize(Of T)(filepath, format)
  180.  
  181.    End Sub
  182.  
  183. #End Region
  184.  
  185. End Class

Modo de empleo:

Código
  1. <Serializable>
  2. Public NotInheritable Class Contact
  3.  
  4.    Public Property Name As String
  5.    Public Property Surname As String
  6.  
  7. End Class

Código
  1. Public NotInheritable Class Form1 : Inherits Form
  2.  
  3.    Private Sub Form1_Load() Handles MyBase.Shown
  4.        Test()
  5.    End Sub
  6.  
  7.    Private Sub Test()
  8.  
  9.        Dim filePath As String = "C:\file.dat"
  10.  
  11.        Dim currentContact As Contact = GetContact(filePath)
  12.  
  13.        Console.WriteLine(String.Format("Name...: {0}", currentContact.Name))
  14.        Console.WriteLine(String.Format("Surname: {0}", currentContact.Surname))
  15.  
  16.        currentContact.Name = "Pepito"
  17.        currentContact.Surname = "Palotes"
  18.  
  19.        Me.SetContact("C:\file.dat", currentContact)
  20.  
  21.    End Sub
  22.  
  23.    Private Function GetContact(ByVal filePath As String) As Contact
  24.  
  25.        Return SerializationUtil.Deserialize(Of Contact)(filePath, SerializationFormat.Binary)
  26.  
  27.    End Function
  28.  
  29.    Private Sub SetContact(ByVal filepath As String, ByVal contact As Contact)
  30.  
  31.        SerializationUtil.Serialize(contact, filepath, SerializationFormat.Binary)
  32.  
  33.    End Sub
  34.  
  35. End Class

Todo traducido a C#:
Código
  1. // ***********************************************************************
  2. // Author   : Elektro
  3. // Modified : 05-September-2015
  4. // ***********************************************************************
  5. // <copyright file="SerializationUtil.vb" company="Elektro Studios">
  6. //     Copyright (c) Elektro Studios. All rights reserved.
  7. // </copyright>
  8. // ***********************************************************************
  9.  
  10.  
  11.  
  12. // ESTA CLASE ESTÁ PARCIALMENTE DEFINIDA (O PARCIALMENTE CAPADA) SOLO PARA SATISFACER LAS NECESIDADES DE ESTA PREGUNTA.
  13.  
  14.  
  15.  
  16. #region " Usings "
  17.  
  18. using Microsoft.VisualBasic;
  19. using System;
  20. using System.Collections;
  21. using System.Collections.Generic;
  22. using System.Data;
  23. using System.Diagnostics;
  24. using System.IO;
  25. using System.Linq;
  26. using System.Runtime.Serialization.Formatters.Binary;
  27. using System.Xml.Serialization;
  28.  
  29. #endregion
  30.  
  31. /// <summary>
  32. /// Contains related serialization utilities.
  33. /// </summary>
  34. public sealed class SerializationUtil
  35. {
  36.  
  37. #region " Constructors "
  38.  
  39. /// ----------------------------------------------------------------------------------------------------
  40. /// <summary>
  41. /// Prevents a default instance of the <see cref="SerializationUtil"/> class from being created.
  42. /// </summary>
  43. /// ----------------------------------------------------------------------------------------------------
  44. private SerializationUtil()
  45. {
  46. }
  47.  
  48. #endregion
  49.  
  50. #region " Private Methods "
  51.  
  52. /// ----------------------------------------------------------------------------------------------------
  53. /// <exception cref="System.ArgumentException">
  54. /// Wrong Serialization Format.
  55. /// </exception>
  56. /// ----------------------------------------------------------------------------------------------------
  57. [DebuggerStepThrough()]
  58. [DebuggerHidden()]
  59. private static object GetSerializer<T>(SerializationFormat format)
  60. {
  61.  
  62. switch (format) {
  63.  
  64. case SerializationFormat.Binary:
  65.  
  66. return new BinaryFormatter();
  67. case SerializationFormat.Xml:
  68.  
  69. return new XmlSerializer(type: typeof(T));
  70. default:
  71.  
  72. throw new ArgumentException(message: "Wrong Serialization Format.", paramName: "serializationFormat");
  73. }
  74.  
  75. }
  76.  
  77. #endregion
  78.  
  79. #region " Public Methods "
  80.  
  81. /// ----------------------------------------------------------------------------------------------------
  82. /// <summary>
  83. /// Serializes the data of an Object to the specified file, using the specified serialization format.
  84. /// </summary>
  85. /// ----------------------------------------------------------------------------------------------------
  86. /// <typeparam name="T">
  87. /// </typeparam>
  88. ///
  89. /// <param name="obj">
  90. /// The object to be serialized.
  91. /// </param>
  92. ///
  93. /// <param name="filepath">
  94. /// The filepath where to save the serialized data.
  95. /// </param>
  96. ///
  97. /// <param name="format">
  98. /// The serialization format.
  99. /// </param>
  100. /// ----------------------------------------------------------------------------------------------------
  101. [DebuggerStepThrough()]
  102. [DebuggerHidden()]
  103. public static void Serialize<T>(T obj, string filepath, SerializationFormat format)
  104. {
  105. object serializer = SerializationUtil.GetSerializer<T>(format);
  106.  
  107. using (FileStream fs = new FileStream(filepath, FileMode.Create, FileAccess.Write, FileShare.Read)) {
  108.  
  109. switch (serializer.GetType) {
  110.  
  111. case typeof(BinaryFormatter):
  112. ((BinaryFormatter)serializer).Serialize(fs, obj);
  113.  
  114. break;
  115. case typeof(XmlSerializer):
  116. ((XmlSerializer)serializer).Serialize(fs, obj);
  117.  
  118. break;
  119. }
  120.  
  121. }
  122.  
  123. }
  124.  
  125. /// ----------------------------------------------------------------------------------------------------
  126. /// <summary>
  127. /// Deserializes the data of an Object from the specified file, using the specified deserialization format.
  128. /// </summary>
  129. /// ----------------------------------------------------------------------------------------------------
  130. /// <typeparam name="T">
  131. /// </typeparam>
  132. ///
  133. /// <param name="filepath">
  134. /// The filepath where from deserialize the serialized data.
  135. /// </param>
  136. ///
  137. /// <param name="format">
  138. /// The serialization format.
  139. /// </param>
  140. /// ----------------------------------------------------------------------------------------------------
  141. [DebuggerStepThrough()]
  142. [DebuggerHidden()]
  143. public static T Deserialize<T>(string filepath, SerializationFormat format)
  144. {
  145.  
  146. object serializer = SerializationUtil.GetSerializer<T>(format);
  147.  
  148. using (FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read)) {
  149.  
  150. switch (serializer.GetType) {
  151.  
  152. case typeof(BinaryFormatter):
  153.  
  154. return (T)((BinaryFormatter)serializer).Deserialize(fs);
  155. case typeof(XmlSerializer):
  156.  
  157. return (T)((XmlSerializer)serializer).Deserialize(fs);
  158. }
  159.  
  160. }
  161.  
  162. }
  163.  
  164. /// ----------------------------------------------------------------------------------------------------
  165. /// <summary>
  166. /// Deserializes the data of an Object from the specified file, using the specified deserialization format.
  167. /// </summary>
  168. /// ----------------------------------------------------------------------------------------------------
  169. /// <typeparam name="T">
  170. /// </typeparam>
  171. ///
  172. /// <param name="filepath">
  173. /// The filepath where from deserialize the serialized data.
  174. /// </param>
  175. ///
  176. /// <param name="format">
  177. /// The serialization format.
  178. /// </param>
  179. /// ----------------------------------------------------------------------------------------------------
  180. [DebuggerStepThrough()]
  181. [DebuggerHidden()]
  182. public static void Deserialize<T>(ref T refObj, string filepath, SerializationFormat format)
  183. {
  184. refObj = SerializationUtil.Deserialize<T>(filepath, format);
  185.  
  186. }
  187.  
  188. #endregion
  189.  
  190. }
  191.  
  192. //=======================================================
  193. //Service provided by Telerik (www.telerik.com)
  194. //=======================================================

Código
  1. using Microsoft.VisualBasic;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Data;
  6. using System.Diagnostics;
  7.  
  8. public sealed class Form1 : Form
  9. {
  10.  
  11. private void Form1_Load()
  12. {
  13. Test();
  14. }
  15.  
  16.  
  17. private void Test()
  18. {
  19. string filePath = "C:\\file.dat";
  20.  
  21. Contact currentContact = GetContact(filePath);
  22.  
  23. Console.WriteLine(string.Format("Name...: {0}", currentContact.Name));
  24. Console.WriteLine(string.Format("Surname: {0}", currentContact.Surname));
  25.  
  26. currentContact.Name = "Pepito";
  27. currentContact.Surname = "Palotes";
  28.  
  29. this.SetContact("C:\\file.dat", currentContact);
  30.  
  31. }
  32.  
  33. private Contact GetContact(string filePath)
  34. {
  35.  
  36. return SerializationUtil.Deserialize<Contact>(filePath, SerializationFormat.Binary);
  37.  
  38. }
  39.  
  40.  
  41. private void SetContact(string filepath, Contact contact)
  42. {
  43. SerializationUtil.Serialize(contact, filepath, SerializationFormat.Binary);
  44.  
  45. }
  46. public Form1()
  47. {
  48. Shown += Form1_Load;
  49. }
  50.  
  51. }

Código
  1. [Serializable()]
  2. public sealed class Contact
  3. {
  4.  
  5. public string Name { get; set; }
  6. public string Surname { get; set; }
  7.  
  8. }
  9.  
  10. //=======================================================
  11. //Service provided by Telerik (www.telerik.com)
  12. //=======================================================
  13.  

EDITO:
Ejemplo al utilizar la serialización XML:
Código
  1. <?xml version="1.0"?>
  2. <Contact xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  3.  <Name>Pepito</Name>
  4.  <Surname>Palotes</Surname>
  5. </Contact>

Saludos.
4725  Programación / .NET (C#, VB.NET, ASP) / Re: [C#] ¿Programas ha realizar en consola? (Pregunta) en: 5 Septiembre 2015, 12:47 pm
Algo que no he intentado son los juegos

Ni falta que te hace para aprender programación. pero si lo haces, no lo hagas en .Net ya que no merece la pena, y si lo hces en .Net, al menos hazlo mediante un framework basado en DirectX, o usa XNA.

Saludos.
4726  Foros Generales / Foro Libre / Re: [Los Burlaos] ¿Estás burlao? en: 4 Septiembre 2015, 14:37 pm
Si tienes monchis ve a por chicharrón!

Esto escucharlo duele en el alma.

x'D

Es una frase tan profunda...

Los "monchis" es una estúpida palabra (de tantas) a lo Spanglish que hace referencia al término "munchies" (o snacks), ahora... ¿chicharrón?, quizás sea la forma de llamar a "la chicha" (el hachís) en la zona donde viva, al menos así es cómo lo llamabamos en mi barrio.
Yo supongo que el poético Dudu intenta decirnos que si tienes comida no te lo pienses y vayas a por porros de maria (para matar dos pájaros de un tiro), ya que luego dan hambre y la comida crujiente entra muy bien.

Saludos!
4727  Foros Generales / Foro Libre / Re: [Los Burlaos] ¿Estás burlao? en: 4 Septiembre 2015, 12:19 pm
El video de los burlaos, la jodida frasecita de "estás burlao" que se ha puesto de moda, y la noticia en si misma ya está todo muy quemado de hace meses xD, incluso a Josemi le dió tiempo a hacer otro "videoclip" en plan contrarespuesta a los youtubers y demás...

¡Aviso!.
El siguiente material es altamente irrecomendable para personas en terapia anti-suicidio o contra la drogodependencia.
Por favor abstenerse de ver el siguiente video las mujeres embarazadas, pues podría causar daños irreparables en el feto, de por vida.


Los síntomas causados más comunes descubiertos tras la visualización de este video son:
  • Escozor anal.
  • Embolia cerebral.
  • Ganas de matar.
  • Nauseas y mareos.
  • Verguenza ajena de la especie humana.
  • Susceptible al suicidio, con tendencia a pegarse un tiro.

Quedan avisados.

Dudu X CharfleX - COMPUTERS RMX


...Son sus costumbres y hay que respetarlas :-X.

PD: Sus padres, sin duda alguna, tienen que estar muy orgullosos de él ...por cómo ha adelgazado y eso digo  :silbar:.



Ese vídeo me hizo reír muchísimo, pero mas me descojone la primera vez cuando lo vi que lo analizo el gran youtuber AuronPlay

Sin duda los análisis de AuronPlay son para partirse el culo, y ese que mencionas lo fue.

Que no se nos olvide mencionar ...para quien quiera verlo en su canal de Youtube, que Auron también hizo un análisis de este último "videoclip", el cual tampoco tiene desperdicio xD.

Saludos.
4728  Sistemas Operativos / Windows / Re: ¿Cómo activar o desactivar características en Windows 10? en: 31 Agosto 2015, 15:43 pm
¿Si desactivo IIS supondría algún problema de seguridad para la PC?

No. IIS es un servidor Web (cómo Apache por ponerte un ejemplo), si no lo usas para servir contenido, es decir, una página web, entonces desactívalo.

Saludos
4729  Sistemas Operativos / Windows / Re: ¿Cómo activar o desactivar características en Windows 10? en: 31 Agosto 2015, 13:37 pm
no encuentro como activas o desactivar características en Windows 10. He intentado buscar referenciales pero nada todo para versiones anteriores.

La metodología sigue siendo la misma tanto para Windows 8/8.1 (y anteriores) cómo para el nuevo Windows Spy 10,
lo que debes hacer es dirigirte al menú del administrador de aplicaciones y características instaladas (aka AppWiz o Appication Wizard) y desactivar la característica que desees.

Para un acceso rápido a dicho menú, en "Ejecutar", o en un acceso directo, o también en la consola de Windows (CMD), puedes escribir el nombre del applet del panel de control seguido del índice de la pestaña o ventana que quieres mostrar.

Dicho de otro modo, simplemente escribe esto:
Código:
appwiz.cpl,2

...y te saldrá esto otro:




También puedes hacerlo mediante la aplicación commandline DISM (Deployment Image Servicing and Management Tool), la cual está incluida en Windows y en el SDK de Windows.

Para listar los nombres y el estado de las características:
Código:
Dism.exe /Online /Get-Features /Format:Table

Para desactivar una característica:
Código:
DISM.exe /Online /Disable-Feature /FeatureName:"Nombre de la característica" /English /LogPath:".\DISM.log" /LogLevel:3

Si la característica que deseas desactivar no se encuentra en dicha lista (ej. Hyper-V,, Virtual PC, Windows Defender, Windows Media Player), siempre puedes desinstalar/eliminar el paquete que contenga la funcionalidad:

Para listar los nombres y el estado de los paquetes:
Código:
DISM.exe /Online /Get-Packages /Format:Table

Para desinstalar un paquete:
Código:
DISM.exe /Online /Remove-Package /PackageName:"Nombre del paquete" /English /LogPath:".\DISM.log" /LogLevel:3

PD: Ten en cuenta que Microsoft utiliza identificadores únicos para nombrar los paquetes, así que el nombre de estos varian entre las distintas versiones de Windows, no vayas a usar el mismo nombre de paquete en otra versión más antigua de Windows esperando que funcione (o tras instalar un Service Pack), ya que el paquete tendrá un identificador distinto que hará referencia a una versión anterior del mismo.

Saludos
4730  Sistemas Operativos / Windows / Re: derecho de adm en win 10 en: 31 Agosto 2015, 13:06 pm
ya use
net user Administrador /active:yes

De acuerdo, pero despues de haber activado la cuenta oculta llamada "Administrador", ¿entraste a esa cuenta para realizar la operación de escitura del archivo?, por que de lo contrario no has cambiado nada :P.

De todas formas, desde una cuenta con privilegios de Admin siempre puedes conceder o condecerte los privilegios de lectura/escritura/eliminación sobre un directorio/archivo desde la UI de Windows o desde la consola de comandos, cómo en este ejemplo escrito en Batch:

Script.cmd
Código:
Echo OFF & Color 1F

Set "dirPath=%USERPROFILE%\Pictures"

"Takeown.exe" /F "%dirPath%" /R /D S               && ^
"Icacls.exe"     "%dirPath%" /Grant "%USERNAME%":"F" /T

Pause&Exit /B 0

Saludos
Páginas: 1 ... 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 [473] 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 ... 1236
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines