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

 

 


Tema destacado: Estamos en la red social de Mastodon


  Mostrar Mensajes
Páginas: 1 ... 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 [560] 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 ... 1236
5591  Programación / .NET (C#, VB.NET, ASP) / Re: Fallo al iniciar sesion en: 30 Marzo 2015, 11:13 am
¿Que puedo estar pasando por alto?, saludos y gracias.

1. ¿Te has asegurado de codificar los valores de los parámetros en caso de que contengan caracteres especiales como espacios en blanco, puntos, etc?:
Código
  1. HttpUtility.UrlEncode(usuario);
  2. HttpUtility.UrlEncode(contraseña);

2. ¿Has comprobado que le estás pasando las cabeceras correctas?.

3. De todas formas podrías necesitar más que eso, prueba a obtener la Cookie de visitante en la página principal, y luego a loguearte usando dicha cookie,
escribí este snippet al que se le puede dar un uso más o menos genérico que podría servir para tu situación, le hice unas pequeñas modificaciones para adaptarlo a tus necesidades, solo modifica los valores de la propiedades 'UrlMain', 'UrlLogin', 'UrlLoginQueryFormat', comprueba las cabeceras que asigno en 'RequestHeadersPostLogin' sean correctas y no falten más, y por último llama al método 'CheckLogin' para evaluar el login.

VB.Net:
Código
  1.  
  2.    ''' <summary>
  3.    ''' Gets the main url.
  4.    ''' </summary>
  5.    ''' <value>The main url.</value>
  6.    Public ReadOnly Property UrlMain As String
  7.        Get
  8.            Return "http://www.cgwallpapers.com/"
  9.        End Get
  10.    End Property
  11.  
  12.    ''' <summary>
  13.    ''' Gets the login url.
  14.    ''' </summary>
  15.    ''' <value>The login url.</value>
  16.    Public ReadOnly Property UrlLogin As String
  17.        Get
  18.            Return "http://www.cgwallpapers.com/login.php"
  19.        End Get
  20.    End Property
  21.  
  22.    ''' <summary>
  23.    ''' Gets the login query string format.
  24.    ''' </summary>
  25.    ''' <value>The login query string format.</value>
  26.    Public ReadOnly Property UrlLoginQueryFormat As String
  27.        Get
  28.            Return "usuario={0}&contrasena={1}"
  29.        End Get
  30.    End Property
  31.  
  32.    ''' <summary>
  33.    ''' Gets the headers for a Login POST request.
  34.    ''' </summary>
  35.    ''' <value>The headers for a Login POST request.</value>
  36.    Public ReadOnly Property RequestHeadersPostLogin As WebHeaderCollection
  37.        Get
  38.  
  39.            Dim headers As New WebHeaderCollection
  40.            With headers
  41.                .Add("Accept-Language", "en-us,en;q=0.5")
  42.                .Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7")
  43.                .Add("Keep-Alive", "99999")
  44.            End With
  45.            Return headers
  46.  
  47.        End Get
  48.    End Property
  49.  
  50.    ''' <summary>
  51.    ''' Determines whether the user is logged in the site.
  52.    ''' </summary>
  53.    Private isLogged As Boolean
  54.  
  55.    ''' <summary>
  56.    ''' Gets the cookie container.
  57.    ''' </summary>
  58.    ''' <value>The cookie container.</value>
  59.    Public ReadOnly Property CookieCollection As CookieCollection
  60.        Get
  61.            Return Me.cookieCollection1
  62.        End Get
  63.    End Property
  64.    ''' <summary>
  65.    ''' The cookie container.
  66.    ''' </summary>
  67.    Private cookieCollection1 As CookieCollection
  68.  
  69.    ''' <summary>
  70.    ''' Defines the query data for a LoginPost request.
  71.    ''' </summary>
  72.    Private NotInheritable Class LoginQueryData
  73.  
  74.        ''' <summary>
  75.        ''' Gets the Usuario field.
  76.        ''' </summary>
  77.        ''' <value>The Usuario field.</value>
  78.        Public Property Usuario As String
  79.  
  80.        ''' <summary>
  81.        ''' Gets or sets the Conteasena field.
  82.        ''' </summary>
  83.        ''' <value>The Conteasena field.</value>
  84.        Public Property Contrasena As String
  85.  
  86.    End Class
  87.  
  88.    ''' <summary>
  89.    ''' Gets a formatted <see cref="String"/> representation of a <see cref="LoginQueryData"/> object.
  90.    ''' </summary>
  91.    ''' <param name="loginQueryData">The <see cref="LoginQueryData"/> object that contains the login query fields.</param>
  92.    ''' <returns>A formatted <see cref="String"/> representation of a <see cref="LoginQueryData"/> object.</returns>
  93.    Private Function GetLoginQueryString(ByVal loginQueryData As LoginQueryData) As String
  94.  
  95.        Return String.Format(Me.UrlLoginQueryFormat,
  96.                             loginQueryData.Usuario,
  97.                             loginQueryData.Contrasena)
  98.  
  99.    End Function
  100.  
  101.    ''' <summary>
  102.    ''' Sets the cookie container.
  103.    ''' </summary>
  104.    ''' <param name="url">The url.</param>
  105.    ''' <param name="cookieCollection">The cookie collection.</param>
  106.    ''' <returns>CookieContainer.</returns>
  107.    Private Function SetCookieContainer(ByVal url As String,
  108.                                        ByVal cookieCollection As CookieCollection) As CookieContainer
  109.  
  110.        Dim cookieContainer As New CookieContainer
  111.        Dim refDate As Date
  112.  
  113.        For Each oldCookie As Cookie In cookieCollection
  114.  
  115.            If Not DateTime.TryParse(oldCookie.Value, refDate) Then
  116.  
  117.                Dim newCookie As New Cookie
  118.                With newCookie
  119.                    .Name = oldCookie.Name
  120.                    .Value = oldCookie.Value
  121.                    .Domain = New Uri(url).Host
  122.                    .Secure = False
  123.                End With
  124.  
  125.                cookieContainer.Add(newCookie)
  126.  
  127.            End If
  128.  
  129.        Next oldCookie
  130.  
  131.        Return cookieContainer
  132.  
  133.    End Function
  134.  
  135.    ''' <summary>
  136.    ''' Converts cookie string to global cookie collection object.
  137.    ''' </summary>
  138.    ''' <param name="cookie">The cookie string.</param>
  139.    ''' <param name="cookieCollection">The cookie collection.</param>
  140.    Private Sub SaveCookies(ByVal cookie As String,
  141.                            ByRef cookieCollection As CookieCollection)
  142.  
  143.        Dim cookieStrings() As String = cookie.Trim.
  144.                                               Replace("path=/,", String.Empty).
  145.                                               Replace("path=/", String.Empty).
  146.                                               Split({";"c}, StringSplitOptions.RemoveEmptyEntries)
  147.  
  148.        cookieCollection = New CookieCollection
  149.  
  150.        For Each cookieString As String In cookieStrings
  151.  
  152.            If Not String.IsNullOrEmpty(cookieString.Trim) Then
  153.  
  154.                cookieCollection.Add(New Cookie(name:=cookieString.Trim.Split("="c)(0),
  155.                                                value:=cookieString.Trim.Split("="c)(1)))
  156.  
  157.            End If
  158.  
  159.        Next cookieString
  160.  
  161.    End Sub
  162.  
  163.    ''' <summary>
  164.    ''' Convert cookie container object to global cookie collection object.
  165.    ''' </summary>
  166.    ''' <param name="cookieContainer">The cookie container.</param>
  167.    ''' <param name="cookieCollection">The cookie collection.</param>
  168.    ''' <param name="url">The url.</param>
  169.    Private Sub SaveCookies(ByVal cookieContainer As CookieContainer,
  170.                            ByRef cookieCollection As CookieCollection,
  171.                            ByVal url As String)
  172.  
  173.        cookieCollection = New CookieCollection
  174.  
  175.        For Each cookie As Cookie In cookieContainer.GetCookies(New Uri(url))
  176.  
  177.            cookieCollection.Add(cookie)
  178.  
  179.        Next cookie
  180.  
  181.    End Sub
  182.  
  183.    ''' <param name="url">The url.</param>
  184.    ''' <param name="cookieCollection">The cookie collection.</param>
  185.    ''' <returns><c>true</c> if successfull, <c>false</c> otherwise.</returns>
  186.    Private Function GetMethod(ByVal url As String,
  187.                               ByRef cookieCollection As CookieCollection) As Boolean
  188.  
  189.        Debug.WriteLine("[+] GetMethod function started.")
  190.  
  191.        Dim request As HttpWebRequest = Nothing
  192.        Dim response As HttpWebResponse = Nothing
  193.        Dim sr As StreamReader = Nothing
  194.        Dim result As Boolean = False
  195.  
  196.        Try
  197.            Debug.WriteLine("[+] Attempting to perform a request with:")
  198.            Debug.WriteLine(String.Format("Method: {0}", "GET"))
  199.            Debug.WriteLine(String.Format("Headers: {0}", String.Join(Environment.NewLine, Me.RequestHeadersPostLogin)))
  200.  
  201.            request = DirectCast(HttpWebRequest.Create(url), HttpWebRequest)
  202.            With request
  203.                .Method = "GET"
  204.                .Headers = Me.RequestHeadersPostLogin
  205.                .Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"
  206.                .UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0"
  207.                .AllowAutoRedirect = False
  208.                .KeepAlive = True
  209.            End With
  210.            Debug.WriteLine("[-] Request done.")
  211.  
  212.            ' Get the server response.
  213.            Debug.WriteLine("[+] Getting server response...")
  214.            response = DirectCast(request.GetResponse, HttpWebResponse)
  215.            Debug.WriteLine("[-] Getting server response done.")
  216.  
  217.            If request.HaveResponse Then
  218.  
  219.                ' Save the cookie info.
  220.                Debug.WriteLine("[+] Saving cookies...")
  221.                Me.SaveCookies(response.Headers("Set-Cookie"), cookieCollection)
  222.                Debug.WriteLine("[-] Saving cookies done.")
  223.  
  224.                ' Get the server response.
  225.                Debug.WriteLine("[+] Getting server response...")
  226.                response = DirectCast(request.GetResponse, HttpWebResponse)
  227.                Debug.WriteLine("[-] Getting server response done.")
  228.  
  229.                Debug.WriteLine("[+] Reading server response...")
  230.                sr = New StreamReader(response.GetResponseStream)
  231.                Using sr
  232.                    ' Read the response from the server, but we do not save it.
  233.                    sr.ReadToEnd()
  234.                End Using
  235.                result = True
  236.                Debug.WriteLine("[-] Reading server response done.")
  237.  
  238.            Else ' No response received from server.
  239.                Throw New Exception(String.Format("No response received from server with url: {0}", url))
  240.                result = False
  241.  
  242.            End If
  243.  
  244.        Catch ex As Exception
  245.            Throw
  246.            result = False
  247.  
  248.        Finally
  249.            If sr IsNot Nothing Then
  250.                sr.Dispose()
  251.            End If
  252.            If response IsNot Nothing Then
  253.                response.Close()
  254.            End If
  255.  
  256.        End Try
  257.  
  258.        Debug.WriteLine("[-] GetMethod function finished.")
  259.        Debug.WriteLine("[i] Returning result value...")
  260.        Return result
  261.  
  262.    End Function
  263.  
  264.    ''' <param name="loginData">The login post data.</param>
  265.    ''' <param name="cookieCollection">The cookie collection.</param>
  266.    ''' <returns><c>true</c> if successfull, <c>false</c> otherwise.</returns>
  267.    Private Function PostLoginMethod(ByVal loginData As LoginQueryData,
  268.                                     ByRef cookieCollection As CookieCollection) As Boolean
  269.  
  270.        Debug.WriteLine("[+] PostLoginMethod function started.")
  271.  
  272.        Dim request As HttpWebRequest = Nothing
  273.        Dim response As HttpWebResponse = Nothing
  274.        Dim sw As StreamWriter = Nothing
  275.        Dim initialCookieCount As Integer = 0
  276.        Dim postData As String
  277.        Dim result As Boolean = False
  278.  
  279.        Try
  280.            Debug.WriteLine("[+] Attempting to perform a login request with:")
  281.            Debug.WriteLine(String.Format("Method: {0}", "POST"))
  282.            Debug.WriteLine(String.Format("Referer: {0}", Me.UrlMain))
  283.            Debug.WriteLine(String.Format("Accept: {0}", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"))
  284.            Debug.WriteLine(String.Format("ContentType: {0}", "application/x-www-form-urlencoded"))
  285.            Debug.WriteLine(String.Format("Headers: {0}", String.Join(Environment.NewLine, Me.RequestHeadersPostLogin)))
  286.  
  287.            request = DirectCast(HttpWebRequest.Create(Me.UrlLogin), HttpWebRequest)
  288.            With request
  289.                .Method = "POST"
  290.                .Headers = Me.RequestHeadersPostLogin
  291.                .Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
  292.                .ContentType = "application/x-www-form-urlencoded"
  293.                .UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0"
  294.                .Referer = Me.UrlMain
  295.            End With
  296.            Debug.WriteLine("[-] Request done.")
  297.  
  298.            Debug.WriteLine("[+] Passing request cookie info...")
  299.            If cookieCollection IsNot Nothing Then ' Pass cookie info from the login page.
  300.                request.CookieContainer = Me.SetCookieContainer(Me.UrlLogin, cookieCollection)
  301.            End If
  302.            Debug.WriteLine("[-] Passing request cookie info done.")
  303.  
  304.            ' Set the post data.
  305.            Debug.WriteLine("[+] Setting post data with:")
  306.            Debug.WriteLine(String.Format("Usuario: {0}", loginData.Usuario))
  307.            Debug.WriteLine(String.Format("Contrasena: {0}", loginData.Contrasena))
  308.            postData = Me.GetLoginQueryString(loginData)
  309.  
  310.            sw = New StreamWriter(request.GetRequestStream)
  311.            Using sw
  312.                sw.Write(postData) ' Post the data to the server.
  313.            End Using
  314.            Debug.WriteLine("[-] Setting post data done.")
  315.  
  316.            ' Get the server response.
  317.            Debug.WriteLine("[+] Getting server response...")
  318.            initialCookieCount = request.CookieContainer.Count
  319.            response = DirectCast(request.GetResponse, HttpWebResponse)
  320.            Debug.WriteLine("[-] Getting server response done.")
  321.  
  322.            If request.CookieContainer.Count > initialCookieCount Then ' Login successful.
  323.                result = True
  324.  
  325.            Else ' Login unsuccessful.
  326.                result = False
  327.  
  328.            End If
  329.  
  330.            Debug.WriteLine(String.Format("[i] Login response result is: {0}",
  331.                                          If(result, "Successful (True)",
  332.                                                     "Unsuccessful (False)")))
  333.  
  334.            If result Then ' Save new login cookies.
  335.                Debug.WriteLine("[+] Saving new login cookies...")
  336.                Me.SaveCookies(request.CookieContainer, cookieCollection, Me.UrlMain)
  337.                Debug.WriteLine("[-] Saving new login cookies done.")
  338.            End If
  339.  
  340.        Catch ex As Exception
  341.            Throw
  342.  
  343.        Finally
  344.            If sw IsNot Nothing Then
  345.                sw.Dispose()
  346.            End If
  347.            If response IsNot Nothing Then
  348.                response.Close()
  349.            End If
  350.  
  351.        End Try
  352.  
  353.        Debug.WriteLine("[-] PostLoginMethod function finished.")
  354.        Debug.WriteLine("[i] Returning result value...")
  355.        Me.isLogged = result
  356.        Return result
  357.  
  358.    End Function
  359.  
  360.    ''' <summary>
  361.    ''' Determines whether the account can log in CGWallpapers site.
  362.    ''' </summary>
  363.    ''' <returns><c>true</c> if the account can log in CGWallpapers site, <c>false</c> otherwise.</returns>
  364.    Public Function CheckLogin(ByVal username As String,
  365.                               ByVal password As String) As Boolean
  366.  
  367.        If Me.GetMethod(Me.UrlMain, Me.cookieCollection1) Then
  368.  
  369.            Dim loginQueryData As New LoginQueryData With
  370.                  {
  371.                      .Usuario = HttpUtility.UrlEncode(username),
  372.                      .Contrasena = HttpUtility.UrlEncode(password)
  373.                  }
  374.            Return Me.PostLoginMethod(loginQueryData, Me.cookieCollection1)
  375.  
  376.        Else
  377.            Return False
  378.  
  379.        End If ' Me.GetMethod
  380.  
  381.    End Function
  382.  

Traducción online a C# (sin testear):
Código
  1. /// <summary>
  2. /// Gets the main url.
  3. /// </summary>
  4. /// <value>The main url.</value>
  5. public string UrlMain {
  6. get { return "http://www.cgwallpapers.com/"; }
  7. }
  8.  
  9. /// <summary>
  10. /// Gets the login url.
  11. /// </summary>
  12. /// <value>The login url.</value>
  13. public string UrlLogin {
  14. get { return "http://www.cgwallpapers.com/login.php"; }
  15. }
  16.  
  17. /// <summary>
  18. /// Gets the login query string format.
  19. /// </summary>
  20. /// <value>The login query string format.</value>
  21. public string UrlLoginQueryFormat {
  22. get { return "usuario={0}&contrasena={1}"; }
  23. }
  24.  
  25. /// <summary>
  26. /// Gets the headers for a Login POST request.
  27. /// </summary>
  28. /// <value>The headers for a Login POST request.</value>
  29. public WebHeaderCollection RequestHeadersPostLogin {
  30.  
  31. get {
  32. WebHeaderCollection headers = new WebHeaderCollection();
  33. var _with1 = headers;
  34. _with1.Add("Accept-Language", "en-us,en;q=0.5");
  35. _with1.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
  36. _with1.Add("Keep-Alive", "99999");
  37. return headers;
  38.  
  39. }
  40. }
  41.  
  42. /// <summary>
  43. /// Determines whether the user is logged in the site.
  44. /// </summary>
  45.  
  46. private bool isLogged;
  47. /// <summary>
  48. /// Gets the cookie container.
  49. /// </summary>
  50. /// <value>The cookie container.</value>
  51. public CookieCollection CookieCollection {
  52. get { return this.cookieCollection1; }
  53. }
  54. /// <summary>
  55. /// The cookie container.
  56. /// </summary>
  57.  
  58. private CookieCollection cookieCollection1;
  59. /// <summary>
  60. /// Defines the query data for a LoginPost request.
  61. /// </summary>
  62. private sealed class LoginQueryData
  63. {
  64.  
  65. /// <summary>
  66. /// Gets the Usuario field.
  67. /// </summary>
  68. /// <value>The Usuario field.</value>
  69. public string Usuario { get; set; }
  70.  
  71. /// <summary>
  72. /// Gets or sets the Conteasena field.
  73. /// </summary>
  74. /// <value>The Conteasena field.</value>
  75. public string Contrasena { get; set; }
  76.  
  77. }
  78.  
  79. /// <summary>
  80. /// Gets a formatted <see cref="String"/> representation of a <see cref="LoginQueryData"/> object.
  81. /// </summary>
  82. /// <param name="loginQueryData">The <see cref="LoginQueryData"/> object that contains the login query fields.</param>
  83. /// <returns>A formatted <see cref="String"/> representation of a <see cref="LoginQueryData"/> object.</returns>
  84. private string GetLoginQueryString(LoginQueryData loginQueryData)
  85. {
  86.  
  87. return string.Format(this.UrlLoginQueryFormat, loginQueryData.Usuario, loginQueryData.Contrasena);
  88.  
  89. }
  90.  
  91. /// <summary>
  92. /// Sets the cookie container.
  93. /// </summary>
  94. /// <param name="url">The url.</param>
  95. /// <param name="cookieCollection">The cookie collection.</param>
  96. /// <returns>CookieContainer.</returns>
  97. private CookieContainer SetCookieContainer(string url, CookieCollection cookieCollection)
  98. {
  99.  
  100. CookieContainer cookieContainer = new CookieContainer();
  101. System.DateTime refDate = default(System.DateTime);
  102.  
  103.  
  104. foreach (Cookie oldCookie in cookieCollection) {
  105.  
  106. if (!DateTime.TryParse(oldCookie.Value, refDate)) {
  107. Cookie newCookie = new Cookie();
  108. var _with2 = newCookie;
  109. _with2.Name = oldCookie.Name;
  110. _with2.Value = oldCookie.Value;
  111. _with2.Domain = new Uri(url).Host;
  112. _with2.Secure = false;
  113.  
  114. cookieContainer.Add(newCookie);
  115.  
  116. }
  117.  
  118. }
  119.  
  120. return cookieContainer;
  121.  
  122. }
  123.  
  124. /// <summary>
  125. /// Converts cookie string to global cookie collection object.
  126. /// </summary>
  127. /// <param name="cookie">The cookie string.</param>
  128. /// <param name="cookieCollection">The cookie collection.</param>
  129.  
  130. private void SaveCookies(string cookie, ref CookieCollection cookieCollection)
  131. {
  132. string[] cookieStrings = cookie.Trim.Replace("path=/,", string.Empty).Replace("path=/", string.Empty).Split({ ';' }, StringSplitOptions.RemoveEmptyEntries);
  133.  
  134. cookieCollection = new CookieCollection();
  135.  
  136.  
  137. foreach (string cookieString in cookieStrings) {
  138.  
  139. if (!string.IsNullOrEmpty(cookieString.Trim)) {
  140. cookieCollection.Add(new Cookie(name: cookieString.Trim.Split('=')(0), value: cookieString.Trim.Split('=')(1)));
  141.  
  142. }
  143.  
  144. }
  145.  
  146. }
  147.  
  148. /// <summary>
  149. /// Convert cookie container object to global cookie collection object.
  150. /// </summary>
  151. /// <param name="cookieContainer">The cookie container.</param>
  152. /// <param name="cookieCollection">The cookie collection.</param>
  153. /// <param name="url">The url.</param>
  154.  
  155. private void SaveCookies(CookieContainer cookieContainer, ref CookieCollection cookieCollection, string url)
  156. {
  157. cookieCollection = new CookieCollection();
  158.  
  159.  
  160. foreach (Cookie cookie in cookieContainer.GetCookies(new Uri(url))) {
  161. cookieCollection.Add(cookie);
  162.  
  163. }
  164.  
  165. }
  166.  
  167. /// <param name="url">The url.</param>
  168. /// <param name="cookieCollection">The cookie collection.</param>
  169. /// <returns><c>true</c> if successfull, <c>false</c> otherwise.</returns>
  170. private bool GetMethod(string url, ref CookieCollection cookieCollection)
  171. {
  172.  
  173. Debug.WriteLine("[+] GetMethod function started.");
  174.  
  175. HttpWebRequest request = null;
  176. HttpWebResponse response = null;
  177. StreamReader sr = null;
  178. bool result = false;
  179.  
  180. try {
  181. Debug.WriteLine("[+] Attempting to perform a request with:");
  182. Debug.WriteLine(string.Format("Method: {0}", "GET"));
  183. Debug.WriteLine(string.Format("Headers: {0}", string.Join(Environment.NewLine, this.RequestHeadersPostLogin)));
  184.  
  185. request = (HttpWebRequest)HttpWebRequest.Create(url);
  186. var _with3 = request;
  187. _with3.Method = "GET";
  188. _with3.Headers = this.RequestHeadersPostLogin;
  189. _with3.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
  190. _with3.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0";
  191. _with3.AllowAutoRedirect = false;
  192. _with3.KeepAlive = true;
  193. Debug.WriteLine("[-] Request done.");
  194.  
  195. // Get the server response.
  196. Debug.WriteLine("[+] Getting server response...");
  197. response = (HttpWebResponse)request.GetResponse;
  198. Debug.WriteLine("[-] Getting server response done.");
  199.  
  200.  
  201. if (request.HaveResponse) {
  202. // Save the cookie info.
  203. Debug.WriteLine("[+] Saving cookies...");
  204. this.SaveCookies(response.Headers("Set-Cookie"), ref cookieCollection);
  205. Debug.WriteLine("[-] Saving cookies done.");
  206.  
  207. // Get the server response.
  208. Debug.WriteLine("[+] Getting server response...");
  209. response = (HttpWebResponse)request.GetResponse;
  210. Debug.WriteLine("[-] Getting server response done.");
  211.  
  212. Debug.WriteLine("[+] Reading server response...");
  213. sr = new StreamReader(response.GetResponseStream);
  214. using (sr) {
  215. // Read the response from the server, but we do not save it.
  216. sr.ReadToEnd();
  217. }
  218. result = true;
  219. Debug.WriteLine("[-] Reading server response done.");
  220.  
  221. // No response received from server.
  222. } else {
  223. throw new Exception(string.Format("No response received from server with url: {0}", url));
  224. result = false;
  225.  
  226. }
  227.  
  228. } catch (Exception ex) {
  229. throw;
  230. result = false;
  231.  
  232. } finally {
  233. if (sr != null) {
  234. sr.Dispose();
  235. }
  236. if (response != null) {
  237. response.Close();
  238. }
  239.  
  240. }
  241.  
  242. Debug.WriteLine("[-] GetMethod function finished.");
  243. Debug.WriteLine("[i] Returning result value...");
  244. return result;
  245.  
  246. }
  247.  
  248. /// <param name="loginData">The login post data.</param>
  249. /// <param name="cookieCollection">The cookie collection.</param>
  250. /// <returns><c>true</c> if successfull, <c>false</c> otherwise.</returns>
  251. private bool PostLoginMethod(LoginQueryData loginData, ref CookieCollection cookieCollection)
  252. {
  253.  
  254. Debug.WriteLine("[+] PostLoginMethod function started.");
  255.  
  256. HttpWebRequest request = null;
  257. HttpWebResponse response = null;
  258. StreamWriter sw = null;
  259. int initialCookieCount = 0;
  260. string postData = null;
  261. bool result = false;
  262.  
  263. try {
  264. Debug.WriteLine("[+] Attempting to perform a login request with:");
  265. Debug.WriteLine(string.Format("Method: {0}", "POST"));
  266. Debug.WriteLine(string.Format("Referer: {0}", this.UrlMain));
  267. Debug.WriteLine(string.Format("Accept: {0}", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
  268. Debug.WriteLine(string.Format("ContentType: {0}", "application/x-www-form-urlencoded"));
  269. Debug.WriteLine(string.Format("Headers: {0}", string.Join(Environment.NewLine, this.RequestHeadersPostLogin)));
  270.  
  271. request = (HttpWebRequest)HttpWebRequest.Create(this.UrlLogin);
  272. var _with4 = request;
  273. _with4.Method = "POST";
  274. _with4.Headers = this.RequestHeadersPostLogin;
  275. _with4.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
  276. _with4.ContentType = "application/x-www-form-urlencoded";
  277. _with4.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0";
  278. _with4.Referer = this.UrlMain;
  279. Debug.WriteLine("[-] Request done.");
  280.  
  281. Debug.WriteLine("[+] Passing request cookie info...");
  282. // Pass cookie info from the login page.
  283. if (cookieCollection != null) {
  284. request.CookieContainer = this.SetCookieContainer(this.UrlLogin, cookieCollection);
  285. }
  286. Debug.WriteLine("[-] Passing request cookie info done.");
  287.  
  288. // Set the post data.
  289. Debug.WriteLine("[+] Setting post data with:");
  290. Debug.WriteLine(string.Format("Usuario: {0}", loginData.Usuario));
  291. Debug.WriteLine(string.Format("Contrasena: {0}", loginData.Contrasena));
  292. postData = this.GetLoginQueryString(loginData);
  293.  
  294. sw = new StreamWriter(request.GetRequestStream);
  295. using (sw) {
  296. sw.Write(postData);
  297. // Post the data to the server.
  298. }
  299. Debug.WriteLine("[-] Setting post data done.");
  300.  
  301. // Get the server response.
  302. Debug.WriteLine("[+] Getting server response...");
  303. initialCookieCount = request.CookieContainer.Count;
  304. response = (HttpWebResponse)request.GetResponse;
  305. Debug.WriteLine("[-] Getting server response done.");
  306.  
  307. // Login successful.
  308. if (request.CookieContainer.Count > initialCookieCount) {
  309. result = true;
  310.  
  311. // Login unsuccessful.
  312. } else {
  313. result = false;
  314.  
  315. }
  316.  
  317. Debug.WriteLine(string.Format("[i] Login response result is: {0}", result ? "Successful (True)" : "Unsuccessful (False)"));
  318.  
  319. // Save new login cookies.
  320. if (result) {
  321. Debug.WriteLine("[+] Saving new login cookies...");
  322. this.SaveCookies(request.CookieContainer, ref cookieCollection, this.UrlMain);
  323. Debug.WriteLine("[-] Saving new login cookies done.");
  324. }
  325.  
  326. } catch (Exception ex) {
  327. throw;
  328.  
  329. } finally {
  330. if (sw != null) {
  331. sw.Dispose();
  332. }
  333. if (response != null) {
  334. response.Close();
  335. }
  336.  
  337. }
  338.  
  339. Debug.WriteLine("[-] PostLoginMethod function finished.");
  340. Debug.WriteLine("[i] Returning result value...");
  341. this.isLogged = result;
  342. return result;
  343.  
  344. }
  345.  
  346.  
  347. /// <summary>
  348. /// Determines whether the account can log in CGWallpapers site.
  349. /// </summary>
  350. /// <returns><c>true</c> if the account can log in CGWallpapers site, <c>false</c> otherwise.</returns>
  351. public bool CheckLogin(string username, string password)
  352. {
  353.  
  354.  
  355. if (this.GetMethod(this.UrlMain, this.cookieCollection1)) {
  356. LoginQueryData loginQueryData = new LoginQueryData {
  357. Usuario = HttpUtility.UrlEncode(username),
  358. Contrasena = HttpUtility.UrlEncode(password)
  359. };
  360. return this.PostLoginMethod(loginQueryData, this.cookieCollection1);
  361.  
  362. } else {
  363. return false;
  364.  
  365. }
  366. // Me.GetMethod
  367.  
  368. }
  369.  
  370. //=======================================================
  371. //Service provided by Telerik (www.telerik.com)
  372. //=======================================================
5592  Programación / Scripting / Re: Acciones sobre archivos de texto. [Batch] en: 30 Marzo 2015, 10:14 am
Yo tengo una duda sobre algo que he intentado hacer con VB6.0 y nada mas no he podido sera que lo podre hacer con un batch?, la idea es agregar datos entre la ultima etiqueta    "</tr>"y la etiqueta "</table>"a fin de ir armandome una tabla con datos de una variable

Si, es posible hacerlo, pero la forma de llevar a cabo esa tarea en un lenguaje simple cómo Batch resultaría en un código bastante tedioso e ineficiente, Batch no puede manipular documentos Html, y además, ya que estás utilizando un lenguaje más apto no deberías rebajar el nivel a una herramienta simplona cómo Batch, no hay necesidad ni justificación para hacer eso,
lo mejor es que intentes seguir haciéndolo en un lenguaje capacitado, yo personalmente te recomiendo VB.Net/C#, aunque de todas formas en VB6 puedes utilizar expresiones regulares para hacerlo de una manera menos efectiva.

Saludos
5593  Programación / Scripting / Re: [AYUDA] Generador de link a partir de cryptograma en batch en: 30 Marzo 2015, 09:54 am
Puedes hacerlo dinamicamente, de la siguiente manera:

Código:
@Echo OFF & SetLocal EnableDelayedExpansion

Set    "chars=qrstuvwxyz"
Set /P "text=Introduce el valor: "
REM Tus evaluaciones aquí.
REM ej: If "%text%" EQU "" ()...

For /L %%# In (0, 1, 9) Do (
    Set "char=!chars:~%%#,1!"
    Call Set "text=!text:%%#=%%char%%!"
)

Start /B "url" "http://www.misitio.com/generar.index.jsp?id=%text%"

Pause&Exit /B 0

Saludos
5594  Informática / Software / Re: Preparador fisico en: 29 Marzo 2015, 19:48 pm
La temática de ese tipo de software es bastante peculiar, intenta buscando palabras clave en Google:

http://lmgtfy.com/?q=body+trainer+software

EDITO:
Éste es gratis (subscripción gratuita) por lo que he leido, pero ni idea de si es bueno: http://www.fitsw.com/

Y este tiene buena pinta, aunque es de pago: https://www.totalcoaching.com/

Saludos!
5595  Programación / .NET (C#, VB.NET, ASP) / Re: Array vb.net 2010 en: 29 Marzo 2015, 19:29 pm
Buenas

Lamento decirte que absolutamente todo es inapropiado en el código, empezando por los tipos que estás utilizando (Array) cómo la masiva repetición de código (...¿49 variables para lo mismo?...), la manera de iterar un array, el intento de asignar un valor a un elemento inexistente fuera del rango del Array, y por último la construcción "manual" del documento XML, donde podrías utilizar classes específicas para ello cómo XmlWriter.

El motivo que das de no ser programador no me sirve cómo justificación, puesto que, aparte de estar programando, conoces y sabes utilizar un loop (aunque sea de tipo While)  :¬¬.

El problema con el primer código que mostraste es que estás intentando asignar un valor a un elemento inexistente del Array, al intentar acceder al índice obviamente esto causa una excepción de índice fuera de rango.
De la forma en que pretendías corregir ese problema (llenando con Ceros) primero deberías haber inicializado un Array adicional (es decir, 12 Arrays adicionales más) con más espacio (más elementos) y copiar el contenido de uno a otro Array, algo que sin duda sería bastante engorroso,
en lugar de Arrays podrías haber utilizado listas genéricas y así utilizar el método List.Add() para añadir elementos "vacíos", pero eso tampoco me parece una solución apropiada, ya que no solo los Arrays del código suponen un problema, sino todo lo demás, por ese motivo te sugiero que vuelvas a re-escribir todo lo que tienes hecho para generar un código ausente de problemas.

Te ayudaría a corregirlo y simplificar todo mostrándote un código con un enfoque distinto, pero no entiendo muy bien lo que pretendes hacer con esos 12 TextBoxes (¿por qué no son 11 o 13 por ejemplo?)...

Prueba a empezar por eliminar todo esto:

Código
  1.        Dim c1 As String
  2.        Dim c2 As String
  3.        Dim c3 As String
  4.        Dim c4 As String
  5.        Dim c5 As String
  6.        Dim c6 As String
  7.        Dim c7 As String
  8.        Dim c8 As String
  9.        Dim c9 As String
  10.        Dim c10 As String
  11.        Dim c11 As String
  12.        Dim c12 As String
  13.        Dim c13 As String
  14.        Dim c14 As String
  15.        Dim c15 As String
  16.        Dim c16 As String
  17.        Dim c17 As String
  18.        Dim c18 As String
  19.        Dim c19 As String
  20.        Dim c20 As String
  21.        Dim c21 As String
  22.        Dim c22 As String
  23.        Dim c23 As String
  24.        Dim c24 As String
  25.        Dim c25 As String
  26.        Dim c26 As String
  27.        Dim c27 As String
  28.        Dim c28 As String
  29.        Dim c29 As String
  30.        Dim c30 As String
  31.        Dim c31 As String
  32.        Dim c32 As String
  33.        Dim c33 As String
  34.        Dim c34 As String
  35.        Dim c35 As String
  36.        Dim c36 As String
  37.        Dim c37 As String
  38.        Dim c38 As String
  39.        Dim c39 As String
  40.        Dim c40 As String
  41.        Dim c41 As String
  42.        Dim c42 As String
  43.        Dim c43 As String
  44.        Dim c44 As String
  45.        Dim c45 As String
  46.        Dim c46 As String
  47.        Dim c47 As String
  48.        Dim c48 As String
  49.        Dim c49 As String
  50.  
  51.  
  52.        Do While tmp1 <= var1.Length
  53.            If var2(tmp1) = Nothing Then
  54.                var2(tmp1) = 0
  55.            End If
  56.            If var3(tmp1) = Nothing Then
  57.                var3(tmp1) = 0
  58.            End If
  59.            If var4(tmp1) = Nothing Then
  60.                var4(tmp1) = 0
  61.            End If
  62.            If var5(tmp1) = Nothing Then
  63.                var5(tmp1) = 0
  64.            End If
  65.            If var6(tmp1) = Nothing Then
  66.                var6(tmp1) = 0
  67.            End If
  68.            If var7(tmp1) = Nothing Then
  69.                var7(tmp1) = 0
  70.            End If
  71.            If var8(tmp1) = Nothing Then
  72.                var8(tmp1) = 0
  73.            End If
  74.            If var9(tmp1) = Nothing Then
  75.                var9(tmp1) = 0
  76.            End If
  77.            If var10(tmp1) = Nothing Then
  78.                var10(tmp1) = 0
  79.            End If
  80.            If var11(tmp1) = Nothing Then
  81.                var11(tmp1) = 0
  82.            End If
  83.            If var12(tmp1) = Nothing Then
  84.                var12(tmp1) = 0
  85.            End If
  86.            tmp1 += 1
  87.        Loop
  88.  
  89.        Do While i <= var1.Length
  90.  
  91.            c1 = <a><![CDATA[<v:sampleDataSet dataSetName="]]></a>.Value & "datos" & i & <a><![CDATA[">]]></a>.Value
  92.            c2 = <a><![CDATA[<]]></a>.Value & nombre1 & <a><![CDATA[>]]></a>.Value
  93.            c3 = <a><![CDATA[<p>]]></a>.Value & var1(i) & <a><![CDATA[</p>]]></a>.Value
  94.            c4 = <a><![CDATA[</]]></a>.Value & nombre1 & <a><![CDATA[>]]></a>.Value
  95.  
  96.            c5 = <a><![CDATA[<v:sampleDataSet dataSetName="]]></a>.Value & "datos" & i & <a><![CDATA[">]]></a>.Value
  97.            c6 = <a><![CDATA[<]]></a>.Value & nombre2 & <a><![CDATA[>]]></a>.Value
  98.            c7 = <a><![CDATA[<p>]]></a>.Value & var2(i) & <a><![CDATA[</p>]]></a>.Value
  99.            c8 = <a><![CDATA[</]]></a>.Value & nombre2 & <a><![CDATA[>]]></a>.Value
  100.  
  101.            c9 = <a><![CDATA[<v:sampleDataSet dataSetName="]]></a>.Value & "datos" & i & <a><![CDATA[">]]></a>.Value
  102.            c10 = <a><![CDATA[<]]></a>.Value & nombre3 & <a><![CDATA[>]]></a>.Value
  103.            c11 = <a><![CDATA[<p>]]></a>.Value & var3(i) & <a><![CDATA[</p>]]></a>.Value
  104.            c12 = <a><![CDATA[</]]></a>.Value & nombre3 & <a><![CDATA[>]]></a>.Value
  105.  
  106.            c13 = <a><![CDATA[<v:sampleDataSet dataSetName="]]></a>.Value & "datos" & i & <a><![CDATA[">]]></a>.Value
  107.            c14 = <a><![CDATA[<]]></a>.Value & nombre4 & <a><![CDATA[>]]></a>.Value
  108.            c15 = <a><![CDATA[<p>]]></a>.Value & var4(i) & <a><![CDATA[</p>]]></a>.Value
  109.            c16 = <a><![CDATA[</]]></a>.Value & nombre4 & <a><![CDATA[>]]></a>.Value
  110.  
  111.            c17 = <a><![CDATA[<v:sampleDataSet dataSetName="]]></a>.Value & "datos" & i & <a><![CDATA[">]]></a>.Value
  112.            c18 = <a><![CDATA[<]]></a>.Value & nombre5 & <a><![CDATA[>]]></a>.Value
  113.            c19 = <a><![CDATA[<p>]]></a>.Value & var5(i) & <a><![CDATA[</p>]]></a>.Value
  114.            c20 = <a><![CDATA[</]]></a>.Value & nombre5 & <a><![CDATA[>]]></a>.Value
  115.  
  116.            c21 = <a><![CDATA[<v:sampleDataSet dataSetName="]]></a>.Value & "datos" & i & <a><![CDATA[">]]></a>.Value
  117.            c22 = <a><![CDATA[<]]></a>.Value & nombre6 & <a><![CDATA[>]]></a>.Value
  118.            c23 = <a><![CDATA[<p>]]></a>.Value & var6(i) & <a><![CDATA[</p>]]></a>.Value
  119.            c24 = <a><![CDATA[</]]></a>.Value & nombre6 & <a><![CDATA[>]]></a>.Value
  120.  
  121.            c25 = <a><![CDATA[<v:sampleDataSet dataSetName="]]></a>.Value & "datos" & i & <a><![CDATA[">]]></a>.Value
  122.            c26 = <a><![CDATA[<]]></a>.Value & nombre7 & <a><![CDATA[>]]></a>.Value
  123.            c27 = <a><![CDATA[<p>]]></a>.Value & var7(i) & <a><![CDATA[</p>]]></a>.Value
  124.            c28 = <a><![CDATA[</]]></a>.Value & nombre7 & <a><![CDATA[>]]></a>.Value
  125.  
  126.            c29 = <a><![CDATA[<v:sampleDataSet dataSetName="]]></a>.Value & "datos" & i & <a><![CDATA[">]]></a>.Value
  127.            c30 = <a><![CDATA[<]]></a>.Value & nombre8 & <a><![CDATA[>]]></a>.Value
  128.            c31 = <a><![CDATA[<p>]]></a>.Value & var8(i) & <a><![CDATA[</p>]]></a>.Value
  129.            c32 = <a><![CDATA[</]]></a>.Value & nombre8 & <a><![CDATA[>]]></a>.Value
  130.  
  131.            c33 = <a><![CDATA[<v:sampleDataSet dataSetName="]]></a>.Value & "datos" & i & <a><![CDATA[">]]></a>.Value
  132.            c34 = <a><![CDATA[<]]></a>.Value & nombre9 & <a><![CDATA[>]]></a>.Value
  133.            c35 = <a><![CDATA[<p>]]></a>.Value & var9(i) & <a><![CDATA[</p>]]></a>.Value
  134.            c36 = <a><![CDATA[</]]></a>.Value & nombre9 & <a><![CDATA[>]]></a>.Value
  135.  
  136.            c37 = <a><![CDATA[<v:sampleDataSet dataSetName="]]></a>.Value & "datos" & i & <a><![CDATA[">]]></a>.Value
  137.            c38 = <a><![CDATA[<]]></a>.Value & nombre10 & <a><![CDATA[>]]></a>.Value
  138.            c39 = <a><![CDATA[<p>]]></a>.Value & var10(i) & <a><![CDATA[</p>]]></a>.Value
  139.            c40 = <a><![CDATA[</]]></a>.Value & nombre10 & <a><![CDATA[>]]></a>.Value
  140.  
  141.            c41 = <a><![CDATA[<v:sampleDataSet dataSetName="]]></a>.Value & "datos" & i & <a><![CDATA[">]]></a>.Value
  142.            c42 = <a><![CDATA[<]]></a>.Value & nombre11 & <a><![CDATA[>]]></a>.Value
  143.            c43 = <a><![CDATA[<p>]]></a>.Value & var11(i) & <a><![CDATA[</p>]]></a>.Value
  144.            c44 = <a><![CDATA[</]]></a>.Value & nombre11 & <a><![CDATA[>]]></a>.Value
  145.  
  146.            c45 = <a><![CDATA[<v:sampleDataSet dataSetName="]]></a>.Value & "datos" & i & <a><![CDATA[">]]></a>.Value
  147.            c46 = <a><![CDATA[<]]></a>.Value & nombre12 & <a><![CDATA[>]]></a>.Value
  148.            c47 = <a><![CDATA[<p>]]></a>.Value & var12(i) & <a><![CDATA[</p>]]></a>.Value
  149.            c48 = <a><![CDATA[</]]></a>.Value & nombre12 & <a><![CDATA[>]]></a>.Value
  150.  
  151.            c49 = <a><![CDATA[</v:sampleDataSet>]]></a>.Value
  152.  
  153.            Cuerpo_xml = Cuerpo_xml & vbCrLf & c1 & vbCrLf & c2 & vbCrLf & c3 & vbCrLf & c4 & vbCrLf & c5 & _
  154.             vbCrLf & c6 & vbCrLf & c7 & vbCrLf & c8 & vbCrLf & c9 & vbCrLf & c10 & _
  155.              vbCrLf & c11 & vbCrLf & c12 & vbCrLf & c13 & vbCrLf & c14 & vbCrLf & c15 & _
  156.               vbCrLf & c16 & vbCrLf & c17 & vbCrLf & c18 & vbCrLf & c19 & vbCrLf & c20 & _
  157.                vbCrLf & c21 & vbCrLf & c22 & vbCrLf & c23 & vbCrLf & c24 & vbCrLf & c25 & _
  158.                 vbCrLf & c26 & vbCrLf & c27 & vbCrLf & c28 & vbCrLf & c29 & vbCrLf & c30 & _
  159.                  vbCrLf & c31 & vbCrLf & c32 & vbCrLf & c33 & vbCrLf & c34 & vbCrLf & c35 & _
  160.                   vbCrLf & c36 & vbCrLf & c37 & vbCrLf & c38 & vbCrLf & c39 & vbCrLf & c40 & _
  161.                    vbCrLf & c41 & vbCrLf & c42 & vbCrLf & c43 & vbCrLf & c44 & vbCrLf & c45 & _
  162.                     vbCrLf & c46 & vbCrLf & c47 & vbCrLf & c48 & vbCrLf & c49 & vbCrLf
  163.  
  164.            i += 1
  165.  
  166.        Loop

Y reemplaza todo ese código eliminado por un loop que itere los elementos de cada array, podría ser algo cómo esto (no se si produce el formato que deseas):

Código
  1.        Dim arrays As IEnumerable(Of Array) =
  2.            {
  3.                var1, var2, var3,
  4.                var4, var5, var6,
  5.                var7, var8, var9,
  6.                var10, var11, var12
  7.            }
  8.  
  9.        Dim count As Integer = 0
  10.  
  11.        Dim sb As New System.Text.StringBuilder
  12.        With sb
  13.  
  14.            For Each arr As Array In arrays
  15.  
  16.                For Each value As String In arr
  17.  
  18.                    count += 1
  19.  
  20.                    .AppendLine(String.Format("<v:sampleDataSet dataSetName=""datos {0}"">", CStr(count)))
  21.                    .AppendLine(String.Format("<{0}>", nombre1))
  22.                    .AppendLine(String.Format("<p>{0}</p>", value))
  23.                    .AppendLine(String.Format("</{0}>", nombre1))
  24.                    .AppendLine()
  25.  
  26.                Next value
  27.  
  28.            Next arr
  29.  
  30.        End With
  31.  
  32.        Dim xmlText As String = Me.cuerpo_xml & sb.ToString & Me.fin_xml

Saludos!
5596  Programación / Scripting / Re: Duda para ordenar arreglos en Ruby. en: 29 Marzo 2015, 14:04 pm
Tampoco sé si hay alguna diferencia entre el código mío y ese, si cambiará en algo el resultado a corto o largo plazo.

La diferencia deberias tenerla clara ya que el propio nombre de las funciones Reverse y Sort indican su funcionalidad:

Reverse invierte el orden de los elementos de la secuencia.
Sort ordena los elementos de la secuencia, según el resultado de una evaluación entre los elementos.

En el código de Code Academy la colección ya te la dan ordenada de manera ascendente:
Citar
Código
  1. libros.sort! { |primerLibro, segundoLibro| primerLibro <=> segundoLibro }

Entonces, si le haces un Reverse lo que estás haciendo es invertir el orden de Ascendente a Descendente, por ese motivo y en este caso específico la solución de usar Reverse sería perfectamente aplicable, sólo que Code Academy no acepta esa solución por el motivo que sea (el motivo podría ser lo que ya epxliqué en mi comentario anterior).

Sigo sin entender muy bien ese código.

El operador <=> toma dos objetos, A y B, los compara y devuelve -1, 0, o 1:

Si A es mayor que B, devolverá -1
Si B es mayor que A, devolverá 1
Si A y B son iguales, devolverá 0

El algoritmo de ordenación utiliza el resultado de esa evaluación para determinar en que posición de la colección deben ir los elementos:

Si el resultado de la evaluación es -1, A debe posicionarse despues de B.
Si el resultado de la evaluación es 1, B debe posicionarse despues de A.
Si el resultado de la evaluación es 0, no importa le orden.

Slaudos



EDITO:

He escrito este ejemplo por si te ayuda a entenderlo mejor utilizando un bloque de código para una evaluación personalizada:

Código
  1. # -*- coding: WINDOWS-1252 -*-
  2.  
  3. col = [ "d", "a", "e", "c", "b" ]
  4.  
  5. ascendantCol =
  6. col.sort {
  7.    |a, b|  
  8.    case
  9.        when a > b
  10.            +1
  11.        when b > a
  12.            -1
  13.        else
  14.            0
  15.    end
  16. }
  17.  
  18. descendantCol =
  19. col.sort {
  20.    |a, b|  
  21.    case
  22.        when a > b
  23.            -1
  24.        when b > a
  25.            +1
  26.        else
  27.            0
  28.    end
  29. }
  30.  
  31. print "Ascendant : #{ ascendantCol.join(', ')}\n"
  32. print "Descendant: #{descendantCol.join(', ')}\n"
  33.  
  34. __END__

Saludos
5597  Programación / .NET (C#, VB.NET, ASP) / Re: Rellenar con rand no me funciona en: 29 Marzo 2015, 13:02 pm
No te funciona cómo esperas porque, en los dos casos que has mostrado, estás aplicando el Distinct y el Select solamente a la última concatenación, puesto que tienes las agrupaciones del Concat abiertas:

Citar
Código
  1. (splits(3).Concat(splits(10).Concat(splits(11).Concat(splits(12).
  2. Distinct.
  3. Select(Function(Value As Integer)
  4.       Return If(Value < MAX, Value, Rand1.Next(1, MAX))
  5. End Function)))))

Para solucionarlo, simplemente fíjate mejor en las concatenaciones que haces en 'ReAsult2255e' y 'AReAAsult2255e', cierra las agrupaciones de ambos correctamente:

Código
  1. (splits(3).Concat(splits(10)).Concat(splits(11)).Concat(splits(12))).
  2. Distinct.
  3. Select(Function(value As Integer)
  4.       Return If(Value < MAX, Value, Rand1.Next(1, MAX))
  5. End Function)

Se que no te gusta oir esto, pero es que no tendrías ese tipo de problemas si ordenases y estructurases mejor tú código, es un completo lio lo que tienes ...y lo sabes.

En mi opinión, lo mejor para ti es que fueses haciendo las cosas por partes, poco a poco, cómo en este ejemplo de abajo donde construyo la colección paso a paso,
haciendolo de esta manera te ayudarías a ti mismo a debuguear el código mejor, al poder recurrir/conocer facilmente el estado de la colección antes de hacerle una modificación (cómo la del Select) para hacerle cambios con menos esfuerzo, y también reducir los errores que tienes de mal agrupamiento, o etc:

Código
  1. Dim concatCol As IEnumerable(Of Integer) = col1.Concat(col2)
  2. Dim distinctCol As IEnumerable(Of Integer) = concatCol.Distinct
  3. Dim selectCol As IEnumerable(Of Integer) = distinctCol.Select(Function(value As Integer)
  4.                                                                  If value < max Then
  5.                                                                      Return value
  6.                                                                  Else
  7.                                                                      Return rand.Next(1, max)
  8.                                                                  End If
  9.                                                              End Function)

Saludos
5598  Programación / .NET (C#, VB.NET, ASP) / Re: Array vb.net 2010 en: 29 Marzo 2015, 10:39 am
Estoy convencido de que lo que estás intentando hacer, llenar con ceros, no es la solución más adecuada y debe ser causa de un problema que viene detrás.

Muestra las declaraciones de dichos Arrays, de la variable tmp1, y el método de escritura que te genera problemas, explica el problema que tienes un poco más a fondo para poder proponerte el enfoque adecuado.

De todas formas, ten en cuenta que puedes inicializar el Array al declararlo, de la siguiente manera por ejemplo:
Código
  1. Dim arr1 As Integer() = Enumerable.Repeat(Of Integer)(element:=-1, count:=10).ToArray()

Eso podría evitar los problemas de elementos nulos que comentas y que no sabemos exactamente por qué tienes ese problema.

Saludos
5599  Programación / Programación General / MOVIDO: Duda con código simple (creo) en Ruby. en: 29 Marzo 2015, 10:18 am
El tema ha sido movido a Scripting.

http://foro.elhacker.net/index.php?topic=432584.0
5600  Programación / Programación General / MOVIDO: Duda para ordenar arreglos en Ruby. en: 29 Marzo 2015, 10:14 am
El tema ha sido movido a Scripting.

http://foro.elhacker.net/index.php?topic=432594.0
Páginas: 1 ... 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 [560] 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 ... 1236
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines