Foro de elhacker.net

Programación => .NET (C#, VB.NET, ASP) => Mensaje iniciado por: rochro en 7 Julio 2014, 23:08 pm



Título: REDUCIR CÓDIGO.NET
Publicado por: rochro en 7 Julio 2014, 23:08 pm
Hola a todos!
Estoy realizando una aplicación donde el cual tiene 3 botones en donde se ejecutan diferentes comandos en cada botón a un mismo archivo (la aplicación es un convertidor). La aplicación ya esta hecha, lo que pasa es que se repite el código varias veces, entonces quisiera saber como podría hacer para que  se realizo el evento click en tal botón entonces ejecutar cierto comando.

No se si me dejo entender. Pero de todas maneras adjuntaré el código completo.

pd. Mi problema también está en que no imprime en archivo de texto.

Código
  1. Imports System
  2. Imports System.IO
  3. Imports System.IO.StreamWriter
  4.  
  5. Public Class Form1
  6.    Inherits System.Windows.Forms.Form
  7.  
  8.    Private Results As String
  9.    Private Delegate Sub delUpdate()
  10.    Private Finished As New delUpdate(AddressOf UpdateText)
  11.  
  12.    Private Sub btnexaminar_Click(sender As Object, e As EventArgs) Handles btnexaminar.Click
  13.        Dim Dir As New FolderBrowserDialog
  14.        If Dir.ShowDialog = Windows.Forms.DialogResult.OK Then
  15.            TextBox1.Text = Dir.SelectedPath
  16.        End If
  17.    End Sub
  18.  
  19.    Private Sub btndat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btndat.Click
  20.        Dim midirectorio As String = TextBox1.Text
  21.        Dim CMDThread As New Threading.Thread(AddressOf CMDAutomate)
  22.        If midirectorio = "" Then
  23.            MessageBox.Show("Debe seleccionar la ruta donde se encuentra la data", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error)
  24.        Else
  25.            My.Computer.FileSystem.CopyFile("C:\Program Files\convert data\runpkr00.exe", midirectorio & "\runpkr00.exe", Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
  26.        End If
  27.        CMDThread.Start()
  28.  
  29.  
  30.    End Sub
  31.    Private Sub CMDAutomate()
  32.        Dim midirectorio As String = TextBox1.Text
  33.        Dim myprocess As New Process
  34.        Dim StartInfo As New System.Diagnostics.ProcessStartInfo
  35.        StartInfo.FileName = "cmd"
  36.        StartInfo.RedirectStandardInput = True
  37.        StartInfo.RedirectStandardOutput = True
  38.        StartInfo.UseShellExecute = False
  39.        StartInfo.CreateNoWindow = True
  40.        myprocess.StartInfo = StartInfo
  41.        myprocess.Start()
  42.        Dim SR As System.IO.StreamReader = myprocess.StandardOutput
  43.        Dim SW As System.IO.StreamWriter = myprocess.StandardInput
  44.        Dim comando As String
  45.        Dim cmdir As String
  46.        Dim nombre As String
  47.  
  48.        For Each file As String In My.Computer.FileSystem.GetFiles(midirectorio, FileIO.SearchOption.SearchTopLevelOnly, "*.T01")
  49.  
  50.            nombre = My.Computer.FileSystem.GetName(file)
  51.            cmdir = "cd " & midirectorio
  52.            comando = "runpkr00.exe -d -s " & nombre
  53.            SW.WriteLine(cmdir)
  54.            SW.WriteLine(comando)
  55.            'Results = SR.ReadToEnd
  56.            'SW.Close()
  57.            'SR.Close()
  58.            'Invoke(Finished)
  59.            MessageBox.Show("Conversión a DAT culminada." & vbNewLine & "Data: " & nombre, "Información", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
  60.        Next
  61.        Results = SR.ReadToEnd
  62.        SW.Close()
  63.        SR.Close()
  64.        Invoke(Finished)
  65.  
  66.    End Sub
  67.  
  68.    Private Sub UpdateText()
  69.  
  70.        'If Me.InvokeRequired = False Then
  71.        Dim midirectorio As String = TextBox1.Text
  72.        Dim strStreamW As Stream = Nothing
  73.        Dim strStreamWriter As StreamWriter = Nothing
  74.        Dim fecha As String = DateTime.Now.ToString("dd MMM HHmmss")
  75.        Dim rutarchivo As String = String.Concat(midirectorio, "log-", fecha & ".txt")
  76.        Windows.Forms.Cursor.Current = Cursors.WaitCursor
  77.        strStreamW = File.Create(rutarchivo)
  78.        strStreamWriter = New StreamWriter(strStreamW, System.Text.Encoding.Default)
  79.        strStreamWriter.WriteLine(Results)
  80.        strStreamWriter.Close()
  81.        ' Else
  82.        '  Dim D As delUpdate = New delUpdate(AddressOf UpdateText)
  83.        ' Me.Invoke(D)
  84.        ' End If
  85.    End Sub
  86.  
  87.    Private Sub btnrinex_Click(sender As System.Object, e As System.EventArgs) Handles btnrinex.Click
  88.        Dim midirectorio As String = TextBox1.Text
  89.        Dim CMD As New Threading.Thread(AddressOf CMDAutomaterin)
  90.        If midirectorio = "" Then
  91.            MessageBox.Show("Debe seleccionar la ruta donde se encuentra la data", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error)
  92.        Else
  93.            My.Computer.FileSystem.CopyFile("C:\Program Files\convert data\teqc.exe", midirectorio & "\teqc.exe", Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
  94.        End If
  95.        CMD.Start()
  96.    End Sub
  97.  
  98.  
  99.    Friend ReadOnly GPSDictionary As Dictionary(Of Integer, Integer) = Me.GetGPSDictionary
  100.    Private Function GetGPSDictionary() As Dictionary(Of Integer, Integer)
  101.  
  102.        Dim ThisYear As Integer = Now.Year
  103.        Dim DaysInThisYear As Integer = (From month As Integer In Enumerable.Range(1, 12)
  104.                                         Select DateTime.DaysInMonth(ThisYear, month)).Sum
  105.        Dim GPSWeeks As IEnumerable(Of Integer) = Enumerable.Range(1773 - 1, 1825)
  106.        Dim Result As New Dictionary(Of Integer, Integer)
  107.  
  108.        For Day As Integer = 1 To DaysInThisYear
  109.            Result.Add(Day, GPSWeeks(DatePart(DateInterval.WeekOfYear,
  110.                                              New DateTime(ThisYear, 1, 1).AddDays(Day - 1))))
  111.        Next Day
  112.  
  113.        Return Result
  114.    End Function
  115.  
  116.    Private Sub CMDAutomaterin()
  117.        Dim midirectorio As String = TextBox1.Text
  118.        Dim myprocess As New Process
  119.        Dim StartInfo As New System.Diagnostics.ProcessStartInfo
  120.        StartInfo.FileName = "cmd"
  121.        StartInfo.RedirectStandardInput = True
  122.        StartInfo.RedirectStandardOutput = True
  123.        StartInfo.UseShellExecute = False
  124.        StartInfo.CreateNoWindow = True
  125.        myprocess.StartInfo = StartInfo
  126.        myprocess.Start()
  127.        Dim SR As System.IO.StreamReader = myprocess.StandardOutput
  128.        Dim SW As System.IO.StreamWriter = myprocess.StandardInput
  129.        Dim comandodat As String
  130.        Dim comandorin As String
  131.        Dim cmdir As String
  132.        Dim nombre As String
  133.        Dim renombre As String
  134.  
  135.        For Each file As String In My.Computer.FileSystem.GetFiles(midirectorio, FileIO.SearchOption.SearchTopLevelOnly, "*.T01")
  136.  
  137.            nombre = Path.GetFileNameWithoutExtension(file)
  138.            renombre = Microsoft.VisualBasic.Left(nombre, Len(nombre) - 2) & "0"
  139.            Dim DayOfYear As Integer = Mid(nombre, 5, 3)
  140.            Dim semgps As Integer = Me.GPSDictionary(DayOfYear)
  141.  
  142.            cmdir = "cd " & midirectorio
  143.            comandodat = "runpkr00.exe -g -d " & nombre & ".t01"
  144.            comandorin = "teqc.exe +nav " & renombre & ".14n -O.int 5 -O.dec 5 -O.ag IGN-PERU -O.o CPG -week " & semgps & " -tr d " & nombre & ".tgd> " & renombre & ".14o"
  145.            SW.WriteLine(cmdir)
  146.            SW.WriteLine(comandodat)
  147.            SW.WriteLine(comandorin)
  148.            'Results = SR.ReadToEnd
  149.            ' SW.Close()
  150.            'SR.Close()
  151.            'Invoke(Finished)
  152.            MessageBox.Show("Conversión a RINEX culminada." & vbNewLine & "Data: " & nombre, "Información", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
  153.        Next
  154.        Results = SR.ReadToEnd
  155.        SW.Close()
  156.        SR.Close()
  157.        Invoke(Finished)
  158.  
  159.    End Sub
  160.  
  161.  
  162.  
  163.    Private Sub btntqc_Click(sender As Object, e As EventArgs) Handles btntqc.Click
  164.        Dim midirectorio As String = TextBox1.Text
  165.        Dim CMD As New Threading.Thread(AddressOf CMDAutomateqc)
  166.        If midirectorio = "" Then
  167.            MessageBox.Show("Debe seleccionar la ruta donde se encuentra la data", "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error)
  168.        Else
  169.            My.Computer.FileSystem.CopyFile("C:\Program Files\convert data\teqc.exe", midirectorio & "\teqc.exe", Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
  170.        End If
  171.        CMD.Start()
  172.    End Sub
  173.  
  174.    Private Sub CMDAutomateqc()
  175.        Dim midirectorio As String = TextBox1.Text
  176.        Dim myprocess As New Process
  177.        Dim StartInfo As New System.Diagnostics.ProcessStartInfo
  178.        StartInfo.FileName = "cmd"
  179.        StartInfo.RedirectStandardInput = True
  180.        StartInfo.RedirectStandardOutput = True
  181.        StartInfo.UseShellExecute = False
  182.        StartInfo.CreateNoWindow = True
  183.        myprocess.StartInfo = StartInfo
  184.        myprocess.Start()
  185.        Dim SR As System.IO.StreamReader = myprocess.StandardOutput
  186.        Dim SW As System.IO.StreamWriter = myprocess.StandardInput
  187.        Dim comandorin As String
  188.        Dim cmdir As String
  189.        Dim nombre As String
  190.        Dim renombre As String
  191.  
  192.        For Each file As String In My.Computer.FileSystem.GetFiles(midirectorio, FileIO.SearchOption.SearchTopLevelOnly, "*.T01")
  193.  
  194.            nombre = Path.GetFileNameWithoutExtension(file)
  195.            renombre = Microsoft.VisualBasic.Left(nombre, Len(nombre) - 2) & "0"
  196.  
  197.            If System.IO.File.Exists(midirectorio & "\" & renombre & ".14n") And System.IO.File.Exists(midirectorio & "\" & renombre & ".14o") Then
  198.                cmdir = "cd " & midirectorio
  199.                comandorin = "teqc.exe -nav " & renombre & ".14n +qc " & renombre & ".14o"
  200.                SW.WriteLine(cmdir)
  201.                SW.WriteLine(comandorin)
  202.                'Results = SR.ReadToEnd
  203.                'SW.Close()
  204.                'SR.Close()
  205.                'Invoke(Finished)
  206.                MessageBox.Show("Quality Check." & vbNewLine & "Data: " & nombre, "Información", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
  207.            Else
  208.                MessageBox.Show("Se necesitan de los archivos RINEX (14n y 14o)" & vbNewLine & "Solución: Clic en el Botón RINEX.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
  209.            End If
  210.        Next
  211.        Results = SR.ReadToEnd
  212.        SW.Close()
  213.        SR.Close()
  214.        Invoke(Finished)
  215.  
  216.    End Sub


Título: Re: REDUCIR CÓDIGO.NET
Publicado por: Eleкtro en 8 Julio 2014, 09:04 am
1. No estás liberando el FolderBrowserDialog que instancias.

Código
  1.    Private Sub btnexaminar_Click(sender As Object, e As EventArgs) Handles btnexaminar.Click
  2.  
  3.        Using Dir As New FolderBrowserDialog
  4.  
  5.            If Dir.ShowDialog = DialogResult.OK Then
  6.                TextBox1.Text = Dir.SelectedPath
  7.            End If
  8.  
  9.        End Using
  10.  
  11.    End Sub

2. Reducción de código de Botones:



Código
  1.    Private CMDThread As Threading.Thread = Nothing
  2.  
  3.    Friend ReadOnly Property MiDirectorio As String
  4.        Get
  5.            Return TextBox1.Text
  6.        End Get
  7.    End Property
  8.  
  9.    Private Sub btndat_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btndat.Click
  10.  
  11.        Me.CMDThread = New Threading.Thread(AddressOf Me.CMDAutomate)
  12.        Me.CopyFile("C:\Program Files\convert data\runpkr00.exe", IO.Path.Combine(Me.MiDirectorio, "\runpkr00.exe"))
  13.        CMDThread.Start()
  14.  
  15.    End Sub
  16.  
  17.    Private Sub btnrinex_Click(sender As Object, e As EventArgs) Handles btnrinex.Click
  18.  
  19.        Me.CMDThread = New Threading.Thread(AddressOf Me.CMDAutomaterin)
  20.        Me.CopyFile("C:\Program Files\convert data\teqc.exe", IO.Path.Combine(Me.MiDirectorio, "\teqc.exe"))
  21.        Me.CMDThread.Start()
  22.  
  23.    End Sub
  24.  
  25.    Private Sub btntqc_Click(sender As Object, e As EventArgs) Handles btntqc.Click
  26.  
  27.        Me.CMDThread = New Threading.Thread(AddressOf Me.CMDAutomateqc)
  28.        Me.CopyFile("C:\Program Files\convert data\teqc.exe", IO.Path.Combine(Me.MiDirectorio, "\teqc.exe"))
  29.        Me.CMDThread.Start()
  30.  
  31.    End Sub
  32.  
  33.    Private Sub CopyFile(ByVal sourcefile As String, ByVal destinationfile As String)
  34.  
  35.        If String.IsNullOrEmpty(Me.MiDirectorio) Then
  36.            MessageBox.Show("Debe seleccionar la ruta donde se encuentra la data", "Error",
  37.                            MessageBoxButtons.OKCancel, MessageBoxIcon.Error)
  38.  
  39.        Else
  40.            My.Computer.FileSystem.CopyFile(sourcefile, destinationfile,
  41.                                            FileIO.UIOption.OnlyErrorDialogs,
  42.                                            FileIO.UICancelOption.DoNothing)
  43.  
  44.        End If
  45.  
  46.    End Sub
  47.  

3. Reducción de código de Procesos

Eliminar todo esto repetido:
Código:
       Dim myprocess As New Process
        Dim StartInfo As New System.Diagnostics.ProcessStartInfo
        StartInfo.FileName = "cmd"
        StartInfo.RedirectStandardInput = True
        StartInfo.RedirectStandardOutput = True
        StartInfo.UseShellExecute = False
        StartInfo.CreateNoWindow = True
        myprocess.StartInfo = StartInfo

por:

Código
  1.    Friend MyProcess As New Process With
  2.    {
  3.        .StartInfo = New ProcessStartInfo With
  4.                     {
  5.                         .FileName = "cmd",
  6.                         .RedirectStandardInput = True,
  7.                         .RedirectStandardOutput = True,
  8.                         .UseShellExecute = False,
  9.                         .CreateNoWindow = True
  10.                     }
  11.    }

PD: Aun se puede simplificar más, tanto los botones como las tareas de los threads, pero creo que con eso ya te basta :P.

Saludos