|
5761
|
Programación / Scripting / Re: Obtener y ordenar texto CMD y MediaInfo Cli
|
en: 31 Marzo 2015, 09:19 am
|
La solución del compañero @ Explorer es funcional y útil, pero, en lo que se refiere a rendimiento, solicitar el informe completo y despues parsearlo/partirlo/unirlo resulta inneceasario por un motivo muy importante que razonablemente quien no esté familiarizado con MediaInfo puede desconocerlo: · La aplicación MediaInfo permite obtener datos específicos en lugar de obtener el informe completo. Por ende, al solicitarle a MediaInfo menos información del archivo solicitando los campos específicos para esta tarea se aumenta el rendimiento, y al mismo tiempo se puede construir el formato deseado del string al pasarle los argumentos al MediaInfo, el mismo formato será devuelto por la salida de la aplicación. Un ejemplo, en Batch: @Echo OFF
(For %%# In ("*.mxf") DO ( MediaInfo.exe "%%~f#" "--Inform=General;%%CompleteName%% | %%Duration/String3%% | %%Encoded_Date%%" ))> ".\MediaInfo.txt"
Pause&Exit /B 0 Lee la ayuda de la aplicación para conocer el resto de parámetros: Saludos
|
|
|
5762
|
Programación / Scripting / Re: ¿Qué se puede hacer con Ruby?
|
en: 31 Marzo 2015, 08:33 am
|
¿Qué tipo de programas se puede hacer con Ruby? y con Ruby, no me refiero a Ruby on Rails. El compañero @Gus Garsaky te ha respondido de forma clara y precisa, un usuario con necesidades generales de programación, no tendrá dificultades para el desarrollo de cualquier tipo de aplicación/script en Ruby. Por ponerte un ejemplo de limitación, si tuvieses pensado desarrollar un driver para un dispositivo de Hardware pues, Ruby, que es un lenguaje alejado del código máquina, no podría llevar a cabo dicha tarea, al menos hablando en terminología "güindous" no se podría desarrollar un driver en modo Kernel (para acceder al espacio del Kernel), para un driver en modo Usuario sí, pero desde luego un lenguaje que tenga que ser interpretado cómo Ruby no sería una solución óptima para esa tarea. ¿podría crear un mini-juego con este programa? Depende de tus necesidades... cómo todo, ¿un juego simple y básico por ocio o aprendizaje?: Sí. ¿un juego serio y avanzado de ámbito comercial?: Sí, pero mejor No. Para crear un juego, resumidamente, es necesario que el lenguaje permita dibujar en la superficie de la pantalla ...es decir manejar gráficos 2D/3D, interceptar/procesar la entrada de datos del teclado/mouse, y opcionalmente reproducir audio, Ruby está capacitado para hacer todo eso. No hay problema en poder desarrollar un juego simple (o no tan simple) en Ruby o Python, y menciono a Python por que según otros comentarios tuyos me parece que es otro lenguaje que te interesa aprender. Pero, el rendimiento es un factor muy importante cuando hablamos de juegos comerciales, y Ruby (cómo Python) en ese sentido es lento, ya que es un lenguaje interpretado al fin y al cabo, recuerda que Ruby y Python son lenguajes de Scripting (al menos sus implementaciones oficiales), no son lenguajes compilados cómo por ejemplo C++, C#, Java, VB.Net, o las implementaciones Ruby.Net, IronRuby y IronPython para el CIL de .Net, o XRuby y JRuvy para el entorno de la JVM, la mayoría de juegos comerciales que integran código de Ruby o Python suelen ser juegos PARCIALMENTE desarrollados en dichos lenguajes, aunque no soy ningún experto en el game-development, creo que en muchos casos (sino todos) es debido a limitiaciones de rendimiento en dichos lenguajes, o limitaciones en la integración con algunos dispositivos. Otro factor importantisimo es que el lenguaje disponga de librerías propias o de terceros para el desarrollo de juegos, ya que de lo contrario te puedes volver loco ...literalmente hablando, en Ruby por ejemplo tienes varias opciones, ruby-opengl, Chingu, G3DRuby, Rubygame, Ruby/SDL, RUDL, o SFML, cada uno está orientado y optimizado a ciertas características en concreto en lo referente a gráficos 2D o 3D, en Open-Gl o DirectX. Saludos.
|
|
|
5764
|
Programación / .NET (C#, VB.NET, ASP) / Re: Rellenar con rand no me funciona
|
en: 30 Marzo 2015, 20:13 pm
|
El valor no puede ser nulo. Nombre del parámetro: second El error es self-explanatory, se explica por si mismo, date cuenta, la segunda secuencia que estás intentando concatenar a la primera secuencia es una referencia nula (es decir, no se le ha asignado ningún valor, la colección no existe), puede ser una de las que he marcado en rojo: Dim concatCol5 As IEnumerable(Of Integer) = splits(3).Concat(splits(13).Concat(splits(15)))(y además de eso no has corregido las agrupaciones cómo te dije en el comentario anterior, es decir, los paréntesis, aunque ese no es el motivo del error) Cómo indica el mensaje de error, para corregirlo solo debes asegurarte de que la colección que le estás pasando al parámetro "second" de la función "concat" no sea una referencia nula. revisa bien el resto del código, comprueba que splits(13) y splits(15) existan antes de intentar concatenarlos ( msgbox( splits(13) is nothing )), no te puedo ayudar a hallar el motivo ya que no forma parte del código que has mostrado. Este ejemplo que puedes examinar, produce la misma excepción que has comentado, ya que la segunda colección es nula (no confundir con "vacía" {} ): Dim col1 As IEnumerable(Of String) = {} Dim col2 As IEnumerable(Of String) ' = Nothing Dim concatCol As IEnumerable(Of String) = Enumerable.Concat(first:=col1, second:=col2)
Saludos
|
|
|
5765
|
Programación / Scripting / Re: Qué hace esta palabra y cómo devuelvo un return (Ruby).
|
en: 30 Marzo 2015, 13:05 pm
|
qué hago mal? La función to_i devuelve un valor, es solo eso, un valor Integer, si no asignas el valor a la variable numero entonces la variable seguirá siendo de tipo String. Puedes realizar la conversión del datatype de manera "persistente": numero = gets.chomp # String numero = numero.to_i # Integer # O la asignación de un valor Integer directamente convirtiendo la entrada de datos del teclado... # numero = gets.chomp.to_i if numero < 100 print "#{numero} es menor a 100." end
O puedes realizar una conversión "temporal" en la expresión de la comparación que solo tendrá efecto durante la evaluación: numero = gets.chomp # String if numero.to_i < 100 print "#{numero} es menor a 100." end
PD: Cuando publiques código debes respetar los normas y utilizar las etiquetas GeShi, se te ha avisado en varias ocasiones, trata de que no vuelva a ocurrir... LEE MI FIRMA. Cualquier futuro mensaje que incumpla dicha norma podrá ser bloqueado o eliminado sin previo aviso.Saludos!
|
|
|
5766
|
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?: HttpUtility.UrlEncode(usuario); 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: ''' <summary> ''' Gets the main url. ''' </summary> ''' <value>The main url.</value> Public ReadOnly Property UrlMain As String Get Return "http://www.cgwallpapers.com/" End Get End Property ''' <summary> ''' Gets the login url. ''' </summary> ''' <value>The login url.</value> Public ReadOnly Property UrlLogin As String Get Return "http://www.cgwallpapers.com/login.php" End Get End Property ''' <summary> ''' Gets the login query string format. ''' </summary> ''' <value>The login query string format.</value> Public ReadOnly Property UrlLoginQueryFormat As String Get Return "usuario={0}&contrasena={1}" End Get End Property ''' <summary> ''' Gets the headers for a Login POST request. ''' </summary> ''' <value>The headers for a Login POST request.</value> Public ReadOnly Property RequestHeadersPostLogin As WebHeaderCollection Get Dim headers As New WebHeaderCollection With headers .Add("Accept-Language", "en-us,en;q=0.5") .Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7") .Add("Keep-Alive", "99999") End With Return headers End Get End Property ''' <summary> ''' Determines whether the user is logged in the site. ''' </summary> Private isLogged As Boolean ''' <summary> ''' Gets the cookie container. ''' </summary> ''' <value>The cookie container.</value> Public ReadOnly Property CookieCollection As CookieCollection Get Return Me.cookieCollection1 End Get End Property ''' <summary> ''' The cookie container. ''' </summary> Private cookieCollection1 As CookieCollection ''' <summary> ''' Defines the query data for a LoginPost request. ''' </summary> Private NotInheritable Class LoginQueryData ''' <summary> ''' Gets the Usuario field. ''' </summary> ''' <value>The Usuario field.</value> Public Property Usuario As String ''' <summary> ''' Gets or sets the Conteasena field. ''' </summary> ''' <value>The Conteasena field.</value> Public Property Contrasena As String End Class ''' <summary> ''' Gets a formatted <see cref="String"/> representation of a <see cref="LoginQueryData"/> object. ''' </summary> ''' <param name="loginQueryData">The <see cref="LoginQueryData"/> object that contains the login query fields.</param> ''' <returns>A formatted <see cref="String"/> representation of a <see cref="LoginQueryData"/> object.</returns> Private Function GetLoginQueryString(ByVal loginQueryData As LoginQueryData) As String Return String.Format(Me.UrlLoginQueryFormat, loginQueryData.Usuario, loginQueryData.Contrasena) End Function ''' <summary> ''' Sets the cookie container. ''' </summary> ''' <param name="url">The url.</param> ''' <param name="cookieCollection">The cookie collection.</param> ''' <returns>CookieContainer.</returns> Private Function SetCookieContainer(ByVal url As String, ByVal cookieCollection As CookieCollection) As CookieContainer Dim cookieContainer As New CookieContainer Dim refDate As Date For Each oldCookie As Cookie In cookieCollection If Not DateTime.TryParse(oldCookie.Value, refDate) Then Dim newCookie As New Cookie With newCookie .Name = oldCookie.Name .Value = oldCookie.Value .Domain = New Uri(url).Host .Secure = False End With cookieContainer.Add(newCookie) End If Next oldCookie Return cookieContainer End Function ''' <summary> ''' Converts cookie string to global cookie collection object. ''' </summary> ''' <param name="cookie">The cookie string.</param> ''' <param name="cookieCollection">The cookie collection.</param> Private Sub SaveCookies(ByVal cookie As String, ByRef cookieCollection As CookieCollection) Dim cookieStrings() As String = cookie.Trim. Replace("path=/,", String.Empty). Replace("path=/", String.Empty). Split({";"c}, StringSplitOptions.RemoveEmptyEntries) cookieCollection = New CookieCollection For Each cookieString As String In cookieStrings If Not String.IsNullOrEmpty(cookieString.Trim) Then cookieCollection.Add(New Cookie(name:=cookieString.Trim.Split("="c)(0), value:=cookieString.Trim.Split("="c)(1))) End If Next cookieString End Sub ''' <summary> ''' Convert cookie container object to global cookie collection object. ''' </summary> ''' <param name="cookieContainer">The cookie container.</param> ''' <param name="cookieCollection">The cookie collection.</param> ''' <param name="url">The url.</param> Private Sub SaveCookies(ByVal cookieContainer As CookieContainer, ByRef cookieCollection As CookieCollection, ByVal url As String) cookieCollection = New CookieCollection For Each cookie As Cookie In cookieContainer.GetCookies(New Uri(url)) cookieCollection.Add(cookie) Next cookie End Sub ''' <param name="url">The url.</param> ''' <param name="cookieCollection">The cookie collection.</param> ''' <returns><c>true</c> if successfull, <c>false</c> otherwise.</returns> Private Function GetMethod(ByVal url As String, ByRef cookieCollection As CookieCollection) As Boolean Debug. WriteLine("[+] GetMethod function started.") Dim request As HttpWebRequest = Nothing Dim response As HttpWebResponse = Nothing Dim sr As StreamReader = Nothing Dim result As Boolean = False Try Debug. WriteLine("[+] Attempting to perform a request with:") Debug. WriteLine(String. Format("Method: {0}", "GET")) Debug. WriteLine(String. Format("Headers: {0}", String. Join(Environment. NewLine, Me. RequestHeadersPostLogin))) request = DirectCast(HttpWebRequest.Create(url), HttpWebRequest) With request .Method = "GET" .Headers = Me.RequestHeadersPostLogin .Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5" .UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0" .AllowAutoRedirect = False .KeepAlive = True End With Debug. WriteLine("[-] Request done.") ' Get the server response. Debug. WriteLine("[+] Getting server response...") response = DirectCast(request.GetResponse, HttpWebResponse) Debug. WriteLine("[-] Getting server response done.") If request.HaveResponse Then ' Save the cookie info. Debug. WriteLine("[+] Saving cookies...") Me.SaveCookies(response.Headers("Set-Cookie"), cookieCollection) Debug. WriteLine("[-] Saving cookies done.") ' Get the server response. Debug. WriteLine("[+] Getting server response...") response = DirectCast(request.GetResponse, HttpWebResponse) Debug. WriteLine("[-] Getting server response done.") Debug. WriteLine("[+] Reading server response...") sr = New StreamReader(response.GetResponseStream) Using sr ' Read the response from the server, but we do not save it. sr.ReadToEnd() End Using result = True Debug. WriteLine("[-] Reading server response done.") Else ' No response received from server. Throw New Exception(String.Format("No response received from server with url: {0}", url)) result = False End If Catch ex As Exception Throw result = False Finally If sr IsNot Nothing Then sr.Dispose() End If If response IsNot Nothing Then response.Close() End If End Try Debug. WriteLine("[-] GetMethod function finished.") Debug. WriteLine("[i] Returning result value...") Return result End Function ''' <param name="loginData">The login post data.</param> ''' <param name="cookieCollection">The cookie collection.</param> ''' <returns><c>true</c> if successfull, <c>false</c> otherwise.</returns> Private Function PostLoginMethod(ByVal loginData As LoginQueryData, ByRef cookieCollection As CookieCollection) As Boolean Debug. WriteLine("[+] PostLoginMethod function started.") Dim request As HttpWebRequest = Nothing Dim response As HttpWebResponse = Nothing Dim sw As StreamWriter = Nothing Dim initialCookieCount As Integer = 0 Dim postData As String Dim result As Boolean = False Try Debug. WriteLine("[+] Attempting to perform a login request with:") Debug. WriteLine(String. Format("Method: {0}", "POST")) Debug. WriteLine(String. Format("Referer: {0}", Me. UrlMain)) Debug. WriteLine(String. Format("Accept: {0}", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")) Debug. WriteLine(String. Format("ContentType: {0}", "application/x-www-form-urlencoded")) Debug. WriteLine(String. Format("Headers: {0}", String. Join(Environment. NewLine, Me. RequestHeadersPostLogin))) request = DirectCast(HttpWebRequest.Create(Me.UrlLogin), HttpWebRequest) With request .Method = "POST" .Headers = Me.RequestHeadersPostLogin .Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" .ContentType = "application/x-www-form-urlencoded" .UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0" .Referer = Me.UrlMain End With Debug. WriteLine("[-] Request done.") Debug. WriteLine("[+] Passing request cookie info...") If cookieCollection IsNot Nothing Then ' Pass cookie info from the login page. request.CookieContainer = Me.SetCookieContainer(Me.UrlLogin, cookieCollection) End If Debug. WriteLine("[-] Passing request cookie info done.") ' Set the post data. Debug. WriteLine("[+] Setting post data with:") Debug. WriteLine(String. Format("Usuario: {0}", loginData. Usuario)) Debug. WriteLine(String. Format("Contrasena: {0}", loginData. Contrasena)) postData = Me.GetLoginQueryString(loginData) sw = New StreamWriter(request.GetRequestStream) Using sw sw.Write(postData) ' Post the data to the server. End Using Debug. WriteLine("[-] Setting post data done.") ' Get the server response. Debug. WriteLine("[+] Getting server response...") initialCookieCount = request.CookieContainer.Count response = DirectCast(request.GetResponse, HttpWebResponse) Debug. WriteLine("[-] Getting server response done.") If request.CookieContainer.Count > initialCookieCount Then ' Login successful. result = True Else ' Login unsuccessful. result = False End If Debug. WriteLine(String. Format("[i] Login response result is: {0}", If(result, "Successful (True)", "Unsuccessful (False)"))) If result Then ' Save new login cookies. Debug. WriteLine("[+] Saving new login cookies...") Me.SaveCookies(request.CookieContainer, cookieCollection, Me.UrlMain) Debug. WriteLine("[-] Saving new login cookies done.") End If Catch ex As Exception Throw Finally If sw IsNot Nothing Then sw.Dispose() End If If response IsNot Nothing Then response.Close() End If End Try Debug. WriteLine("[-] PostLoginMethod function finished.") Debug. WriteLine("[i] Returning result value...") Me.isLogged = result Return result End Function ''' <summary> ''' Determines whether the account can log in CGWallpapers site. ''' </summary> ''' <returns><c>true</c> if the account can log in CGWallpapers site, <c>false</c> otherwise.</returns> Public Function CheckLogin(ByVal username As String, ByVal password As String) As Boolean If Me.GetMethod(Me.UrlMain, Me.cookieCollection1) Then Dim loginQueryData As New LoginQueryData With { .Usuario = HttpUtility.UrlEncode(username), .Contrasena = HttpUtility.UrlEncode(password) } Return Me.PostLoginMethod(loginQueryData, Me.cookieCollection1) Else Return False End If ' Me.GetMethod End Function
Traducción online a C# (sin testear): /// <summary> /// Gets the main url. /// </summary> /// <value>The main url.</value> public string UrlMain { get { return "http://www.cgwallpapers.com/"; } } /// <summary> /// Gets the login url. /// </summary> /// <value>The login url.</value> public string UrlLogin { get { return "http://www.cgwallpapers.com/login.php"; } } /// <summary> /// Gets the login query string format. /// </summary> /// <value>The login query string format.</value> public string UrlLoginQueryFormat { get { return "usuario={0}&contrasena={1}"; } } /// <summary> /// Gets the headers for a Login POST request. /// </summary> /// <value>The headers for a Login POST request.</value> public WebHeaderCollection RequestHeadersPostLogin { get { WebHeaderCollection headers = new WebHeaderCollection (); var _with1 = headers; _with1.Add("Accept-Language", "en-us,en;q=0.5"); _with1.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); _with1.Add("Keep-Alive", "99999"); return headers; } } /// <summary> /// Determines whether the user is logged in the site. /// </summary> private bool isLogged; /// <summary> /// Gets the cookie container. /// </summary> /// <value>The cookie container.</value> public CookieCollection CookieCollection { get { return this.cookieCollection1; } } /// <summary> /// The cookie container. /// </summary> private CookieCollection cookieCollection1; /// <summary> /// Defines the query data for a LoginPost request. /// </summary> private sealed class LoginQueryData { /// <summary> /// Gets the Usuario field. /// </summary> /// <value>The Usuario field.</value> public string Usuario { get; set; } /// <summary> /// Gets or sets the Conteasena field. /// </summary> /// <value>The Conteasena field.</value> public string Contrasena { get; set; } } /// <summary> /// Gets a formatted <see cref="String"/> representation of a <see cref="LoginQueryData"/> object. /// </summary> /// <param name="loginQueryData">The <see cref="LoginQueryData"/> object that contains the login query fields.</param> /// <returns>A formatted <see cref="String"/> representation of a <see cref="LoginQueryData"/> object.</returns> private string GetLoginQueryString(LoginQueryData loginQueryData) { return string.Format(this.UrlLoginQueryFormat, loginQueryData.Usuario, loginQueryData.Contrasena); } /// <summary> /// Sets the cookie container. /// </summary> /// <param name="url">The url.</param> /// <param name="cookieCollection">The cookie collection.</param> /// <returns>CookieContainer.</returns> private CookieContainer SetCookieContainer(string url, CookieCollection cookieCollection) { CookieContainer cookieContainer = new CookieContainer (); System.DateTime refDate = default(System.DateTime); foreach (Cookie oldCookie in cookieCollection) { if (!DateTime.TryParse(oldCookie.Value, refDate)) { Cookie newCookie = new Cookie (); var _with2 = newCookie; _with2.Name = oldCookie.Name; _with2.Value = oldCookie.Value; _with2 .Domain = new Uri (url ).Host; _with2.Secure = false; cookieContainer.Add(newCookie); } } return cookieContainer; } /// <summary> /// Converts cookie string to global cookie collection object. /// </summary> /// <param name="cookie">The cookie string.</param> /// <param name="cookieCollection">The cookie collection.</param> private void SaveCookies(string cookie, ref CookieCollection cookieCollection) { string[] cookieStrings = cookie.Trim.Replace("path=/,", string.Empty).Replace("path=/", string.Empty).Split({ ';' }, StringSplitOptions.RemoveEmptyEntries); cookieCollection = new CookieCollection (); foreach (string cookieString in cookieStrings) { if (!string.IsNullOrEmpty(cookieString.Trim)) { cookieCollection .Add(new Cookie (name : cookieString .Trim.Split('=')(0), value : cookieString .Trim.Split('=')(1))); } } } /// <summary> /// Convert cookie container object to global cookie collection object. /// </summary> /// <param name="cookieContainer">The cookie container.</param> /// <param name="cookieCollection">The cookie collection.</param> /// <param name="url">The url.</param> private void SaveCookies(CookieContainer cookieContainer, ref CookieCollection cookieCollection, string url) { cookieCollection = new CookieCollection (); foreach (Cookie cookie in cookieContainer .GetCookies(new Uri (url ))) { cookieCollection.Add(cookie); } } /// <param name="url">The url.</param> /// <param name="cookieCollection">The cookie collection.</param> /// <returns><c>true</c> if successfull, <c>false</c> otherwise.</returns> private bool GetMethod(string url, ref CookieCollection cookieCollection) { Debug.WriteLine("[+] GetMethod function started."); HttpWebRequest request = null; HttpWebResponse response = null; StreamReader sr = null; bool result = false; try { Debug.WriteLine("[+] Attempting to perform a request with:"); Debug.WriteLine(string.Format("Method: {0}", "GET")); Debug.WriteLine(string.Format("Headers: {0}", string.Join(Environment.NewLine, this.RequestHeadersPostLogin))); request = (HttpWebRequest)HttpWebRequest.Create(url); var _with3 = request; _with3.Method = "GET"; _with3.Headers = this.RequestHeadersPostLogin; _with3.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"; _with3.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0"; _with3.AllowAutoRedirect = false; _with3.KeepAlive = true; Debug.WriteLine("[-] Request done."); // Get the server response. Debug.WriteLine("[+] Getting server response..."); response = (HttpWebResponse)request.GetResponse; Debug.WriteLine("[-] Getting server response done."); if (request.HaveResponse) { // Save the cookie info. Debug.WriteLine("[+] Saving cookies..."); this.SaveCookies(response.Headers("Set-Cookie"), ref cookieCollection); Debug.WriteLine("[-] Saving cookies done."); // Get the server response. Debug.WriteLine("[+] Getting server response..."); response = (HttpWebResponse)request.GetResponse; Debug.WriteLine("[-] Getting server response done."); Debug.WriteLine("[+] Reading server response..."); sr = new StreamReader (response .GetResponseStream); using (sr) { // Read the response from the server, but we do not save it. sr.ReadToEnd(); } result = true; Debug.WriteLine("[-] Reading server response done."); // No response received from server. } else { throw new Exception (string.Format("No response received from server with url: {0}", url )); result = false; } } catch (Exception ex) { throw; result = false; } finally { if (sr != null) { sr.Dispose(); } if (response != null) { response.Close(); } } Debug.WriteLine("[-] GetMethod function finished."); Debug.WriteLine("[i] Returning result value..."); return result; } /// <param name="loginData">The login post data.</param> /// <param name="cookieCollection">The cookie collection.</param> /// <returns><c>true</c> if successfull, <c>false</c> otherwise.</returns> private bool PostLoginMethod(LoginQueryData loginData, ref CookieCollection cookieCollection) { Debug.WriteLine("[+] PostLoginMethod function started."); HttpWebRequest request = null; HttpWebResponse response = null; StreamWriter sw = null; int initialCookieCount = 0; string postData = null; bool result = false; try { Debug.WriteLine("[+] Attempting to perform a login request with:"); Debug.WriteLine(string.Format("Method: {0}", "POST")); Debug.WriteLine(string.Format("Referer: {0}", this.UrlMain)); Debug.WriteLine(string.Format("Accept: {0}", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")); Debug.WriteLine(string.Format("ContentType: {0}", "application/x-www-form-urlencoded")); Debug.WriteLine(string.Format("Headers: {0}", string.Join(Environment.NewLine, this.RequestHeadersPostLogin))); request = (HttpWebRequest)HttpWebRequest.Create(this.UrlLogin); var _with4 = request; _with4.Method = "POST"; _with4.Headers = this.RequestHeadersPostLogin; _with4.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; _with4.ContentType = "application/x-www-form-urlencoded"; _with4.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0"; _with4.Referer = this.UrlMain; Debug.WriteLine("[-] Request done."); Debug.WriteLine("[+] Passing request cookie info..."); // Pass cookie info from the login page. if (cookieCollection != null) { request.CookieContainer = this.SetCookieContainer(this.UrlLogin, cookieCollection); } Debug.WriteLine("[-] Passing request cookie info done."); // Set the post data. Debug.WriteLine("[+] Setting post data with:"); Debug.WriteLine(string.Format("Usuario: {0}", loginData.Usuario)); Debug.WriteLine(string.Format("Contrasena: {0}", loginData.Contrasena)); postData = this.GetLoginQueryString(loginData); sw = new StreamWriter (request .GetRequestStream); using (sw) { sw.Write(postData); // Post the data to the server. } Debug.WriteLine("[-] Setting post data done."); // Get the server response. Debug.WriteLine("[+] Getting server response..."); initialCookieCount = request.CookieContainer.Count; response = (HttpWebResponse)request.GetResponse; Debug.WriteLine("[-] Getting server response done."); // Login successful. if (request.CookieContainer.Count > initialCookieCount) { result = true; // Login unsuccessful. } else { result = false; } Debug.WriteLine(string.Format("[i] Login response result is: {0}", result ? "Successful (True)" : "Unsuccessful (False)")); // Save new login cookies. if (result) { Debug.WriteLine("[+] Saving new login cookies..."); this.SaveCookies(request.CookieContainer, ref cookieCollection, this.UrlMain); Debug.WriteLine("[-] Saving new login cookies done."); } } catch (Exception ex) { throw; } finally { if (sw != null) { sw.Dispose(); } if (response != null) { response.Close(); } } Debug.WriteLine("[-] PostLoginMethod function finished."); Debug.WriteLine("[i] Returning result value..."); this.isLogged = result; return result; } /// <summary> /// Determines whether the account can log in CGWallpapers site. /// </summary> /// <returns><c>true</c> if the account can log in CGWallpapers site, <c>false</c> otherwise.</returns> public bool CheckLogin(string username, string password) { if (this.GetMethod(this.UrlMain, this.cookieCollection1)) { LoginQueryData loginQueryData = new LoginQueryData { Usuario = HttpUtility.UrlEncode(username), Contrasena = HttpUtility.UrlEncode(password) }; return this.PostLoginMethod(loginQueryData, this.cookieCollection1); } else { return false; } // Me.GetMethod } //======================================================= //Service provided by Telerik (www.telerik.com) //=======================================================
|
|
|
5767
|
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
|
|
|
5768
|
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: @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
|
|
|
5770
|
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: Dim c1 As String Dim c2 As String Dim c3 As String Dim c4 As String Dim c5 As String Dim c6 As String Dim c7 As String Dim c8 As String Dim c9 As String Dim c10 As String Dim c11 As String Dim c12 As String Dim c13 As String Dim c14 As String Dim c15 As String Dim c16 As String Dim c17 As String Dim c18 As String Dim c19 As String Dim c20 As String Dim c21 As String Dim c22 As String Dim c23 As String Dim c24 As String Dim c25 As String Dim c26 As String Dim c27 As String Dim c28 As String Dim c29 As String Dim c30 As String Dim c31 As String Dim c32 As String Dim c33 As String Dim c34 As String Dim c35 As String Dim c36 As String Dim c37 As String Dim c38 As String Dim c39 As String Dim c40 As String Dim c41 As String Dim c42 As String Dim c43 As String Dim c44 As String Dim c45 As String Dim c46 As String Dim c47 As String Dim c48 As String Dim c49 As String Do While tmp1 <= var1.Length If var2(tmp1) = Nothing Then var2(tmp1) = 0 End If If var3(tmp1) = Nothing Then var3(tmp1) = 0 End If If var4(tmp1) = Nothing Then var4(tmp1) = 0 End If If var5(tmp1) = Nothing Then var5(tmp1) = 0 End If If var6(tmp1) = Nothing Then var6(tmp1) = 0 End If If var7(tmp1) = Nothing Then var7(tmp1) = 0 End If If var8(tmp1) = Nothing Then var8(tmp1) = 0 End If If var9(tmp1) = Nothing Then var9(tmp1) = 0 End If If var10(tmp1) = Nothing Then var10(tmp1) = 0 End If If var11(tmp1) = Nothing Then var11(tmp1) = 0 End If If var12(tmp1) = Nothing Then var12(tmp1) = 0 End If tmp1 += 1 Loop Do While i <= var1.Length c1 = <a><![CDATA[<v:sampleDataSet dataSetName="]]></a>.Value & "datos" & i & <a><![CDATA[">]]></a>.Value c2 = <a><![CDATA[<]]></a>.Value & nombre1 & <a><![CDATA[>]]></a>.Value c3 = <a><![CDATA[<p>]]></a>.Value & var1(i) & <a><![CDATA[</p>]]></a>.Value c4 = <a><![CDATA[</]]></a>.Value & nombre1 & <a><![CDATA[>]]></a>.Value c5 = <a><![CDATA[<v:sampleDataSet dataSetName="]]></a>.Value & "datos" & i & <a><![CDATA[">]]></a>.Value c6 = <a><![CDATA[<]]></a>.Value & nombre2 & <a><![CDATA[>]]></a>.Value c7 = <a><![CDATA[<p>]]></a>.Value & var2(i) & <a><![CDATA[</p>]]></a>.Value c8 = <a><![CDATA[</]]></a>.Value & nombre2 & <a><![CDATA[>]]></a>.Value c9 = <a><![CDATA[<v:sampleDataSet dataSetName="]]></a>.Value & "datos" & i & <a><![CDATA[">]]></a>.Value c10 = <a><![CDATA[<]]></a>.Value & nombre3 & <a><![CDATA[>]]></a>.Value c11 = <a><![CDATA[<p>]]></a>.Value & var3(i) & <a><![CDATA[</p>]]></a>.Value c12 = <a><![CDATA[</]]></a>.Value & nombre3 & <a><![CDATA[>]]></a>.Value c13 = <a><![CDATA[<v:sampleDataSet dataSetName="]]></a>.Value & "datos" & i & <a><![CDATA[">]]></a>.Value c14 = <a><![CDATA[<]]></a>.Value & nombre4 & <a><![CDATA[>]]></a>.Value c15 = <a><![CDATA[<p>]]></a>.Value & var4(i) & <a><![CDATA[</p>]]></a>.Value c16 = <a><![CDATA[</]]></a>.Value & nombre4 & <a><![CDATA[>]]></a>.Value c17 = <a><![CDATA[<v:sampleDataSet dataSetName="]]></a>.Value & "datos" & i & <a><![CDATA[">]]></a>.Value c18 = <a><![CDATA[<]]></a>.Value & nombre5 & <a><![CDATA[>]]></a>.Value c19 = <a><![CDATA[<p>]]></a>.Value & var5(i) & <a><![CDATA[</p>]]></a>.Value c20 = <a><![CDATA[</]]></a>.Value & nombre5 & <a><![CDATA[>]]></a>.Value c21 = <a><![CDATA[<v:sampleDataSet dataSetName="]]></a>.Value & "datos" & i & <a><![CDATA[">]]></a>.Value c22 = <a><![CDATA[<]]></a>.Value & nombre6 & <a><![CDATA[>]]></a>.Value c23 = <a><![CDATA[<p>]]></a>.Value & var6(i) & <a><![CDATA[</p>]]></a>.Value c24 = <a><![CDATA[</]]></a>.Value & nombre6 & <a><![CDATA[>]]></a>.Value c25 = <a><![CDATA[<v:sampleDataSet dataSetName="]]></a>.Value & "datos" & i & <a><![CDATA[">]]></a>.Value c26 = <a><![CDATA[<]]></a>.Value & nombre7 & <a><![CDATA[>]]></a>.Value c27 = <a><![CDATA[<p>]]></a>.Value & var7(i) & <a><![CDATA[</p>]]></a>.Value c28 = <a><![CDATA[</]]></a>.Value & nombre7 & <a><![CDATA[>]]></a>.Value c29 = <a><![CDATA[<v:sampleDataSet dataSetName="]]></a>.Value & "datos" & i & <a><![CDATA[">]]></a>.Value c30 = <a><![CDATA[<]]></a>.Value & nombre8 & <a><![CDATA[>]]></a>.Value c31 = <a><![CDATA[<p>]]></a>.Value & var8(i) & <a><![CDATA[</p>]]></a>.Value c32 = <a><![CDATA[</]]></a>.Value & nombre8 & <a><![CDATA[>]]></a>.Value c33 = <a><![CDATA[<v:sampleDataSet dataSetName="]]></a>.Value & "datos" & i & <a><![CDATA[">]]></a>.Value c34 = <a><![CDATA[<]]></a>.Value & nombre9 & <a><![CDATA[>]]></a>.Value c35 = <a><![CDATA[<p>]]></a>.Value & var9(i) & <a><![CDATA[</p>]]></a>.Value c36 = <a><![CDATA[</]]></a>.Value & nombre9 & <a><![CDATA[>]]></a>.Value c37 = <a><![CDATA[<v:sampleDataSet dataSetName="]]></a>.Value & "datos" & i & <a><![CDATA[">]]></a>.Value c38 = <a><![CDATA[<]]></a>.Value & nombre10 & <a><![CDATA[>]]></a>.Value c39 = <a><![CDATA[<p>]]></a>.Value & var10(i) & <a><![CDATA[</p>]]></a>.Value c40 = <a><![CDATA[</]]></a>.Value & nombre10 & <a><![CDATA[>]]></a>.Value c41 = <a><![CDATA[<v:sampleDataSet dataSetName="]]></a>.Value & "datos" & i & <a><![CDATA[">]]></a>.Value c42 = <a><![CDATA[<]]></a>.Value & nombre11 & <a><![CDATA[>]]></a>.Value c43 = <a><![CDATA[<p>]]></a>.Value & var11(i) & <a><![CDATA[</p>]]></a>.Value c44 = <a><![CDATA[</]]></a>.Value & nombre11 & <a><![CDATA[>]]></a>.Value c45 = <a><![CDATA[<v:sampleDataSet dataSetName="]]></a>.Value & "datos" & i & <a><![CDATA[">]]></a>.Value c46 = <a><![CDATA[<]]></a>.Value & nombre12 & <a><![CDATA[>]]></a>.Value c47 = <a><![CDATA[<p>]]></a>.Value & var12(i) & <a><![CDATA[</p>]]></a>.Value c48 = <a><![CDATA[</]]></a>.Value & nombre12 & <a><![CDATA[>]]></a>.Value c49 = <a><![CDATA[</v:sampleDataSet>]]></a>.Value Cuerpo_xml = Cuerpo_xml & vbCrLf & c1 & vbCrLf & c2 & vbCrLf & c3 & vbCrLf & c4 & vbCrLf & c5 & _ vbCrLf & c6 & vbCrLf & c7 & vbCrLf & c8 & vbCrLf & c9 & vbCrLf & c10 & _ vbCrLf & c11 & vbCrLf & c12 & vbCrLf & c13 & vbCrLf & c14 & vbCrLf & c15 & _ vbCrLf & c16 & vbCrLf & c17 & vbCrLf & c18 & vbCrLf & c19 & vbCrLf & c20 & _ vbCrLf & c21 & vbCrLf & c22 & vbCrLf & c23 & vbCrLf & c24 & vbCrLf & c25 & _ vbCrLf & c26 & vbCrLf & c27 & vbCrLf & c28 & vbCrLf & c29 & vbCrLf & c30 & _ vbCrLf & c31 & vbCrLf & c32 & vbCrLf & c33 & vbCrLf & c34 & vbCrLf & c35 & _ vbCrLf & c36 & vbCrLf & c37 & vbCrLf & c38 & vbCrLf & c39 & vbCrLf & c40 & _ vbCrLf & c41 & vbCrLf & c42 & vbCrLf & c43 & vbCrLf & c44 & vbCrLf & c45 & _ vbCrLf & c46 & vbCrLf & c47 & vbCrLf & c48 & vbCrLf & c49 & vbCrLf i += 1 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): Dim arrays As IEnumerable(Of Array) = { var1, var2, var3, var4, var5, var6, var7, var8, var9, var10, var11, var12 } Dim count As Integer = 0 Dim sb As New System.Text.StringBuilder With sb For Each arr As Array In arrays For Each value As String In arr count += 1 .AppendLine(String.Format("<v:sampleDataSet dataSetName=""datos {0}"">", CStr(count))) .AppendLine(String.Format("<{0}>", nombre1)) .AppendLine(String.Format("<p>{0}</p>", value)) .AppendLine(String.Format("</{0}>", nombre1)) .AppendLine() Next value Next arr End With Dim xmlText As String = Me.cuerpo_xml & sb.ToString & Me.fin_xml
Saludos!
|
|
|
|
|
|
|