Link to home
Start Free TrialLog in
Avatar of linuxrox
linuxroxFlag for United States of America

asked on

Can someone fix this c# code to work correctly in a GUI instead of a console?

I'm trying to get Form1 to show but the 'while' loop under Form1_Load is preventing it from showing.  this is a syslog server code i'm trying to port over to GUI with a lixtbox to add the syslogs it receives.  my only issue right now is getting the form to load up and accessing Listbox1.items.add() .  All of the code is below.

Thanks!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            //Form1 myform = new Form1();
            //myform.ShowDialog();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
           
            //
            IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
            UdpClient udpListener = new UdpClient(514);
            byte[] bReceive; string sReceive; string sourceIP;

            /* Main Loop */
            /* Listen for incoming data on udp port 514 (default for SysLog events) */
            while (true)
            {
                try
                {
                    bReceive = udpListener.Receive(ref anyIP);
                    /* Convert incoming data from bytes to ASCII */
                    sReceive = Encoding.ASCII.GetString(bReceive);
                    /* Get the IP of the device sending the syslog */
                    sourceIP = anyIP.Address.ToString();
                    new Thread(new logHandler(sourceIP, sReceive).handleLog).Start();
                    /* Start a new thread to handle received syslog event */
                }
                catch (Exception ex) { Console.WriteLine(ex.ToString()); }
            }
            


        }
      
            
           
        

        class logHandler
        {
            /* Phrases within the syslog that will trigger an email notification */
            private string[] emailTriggers = new string[] { "link loss", "help please" };
            private string outputPath = @"C:\syslog_c#\syslog.csv"; /* Location to store events */
            private string source; private string log;

            public logHandler(string sourceIP, string logData) /* Initialize object and clean up the raw data */
            {
                source = sourceIP.Trim(); /* Client IP */
                log = logData.Replace(Environment.NewLine, "").Trim(); /* Syslog data */
            }

            public void handleLog() /* Store the syslog and determine whether to trigger an email notification */
            {
                /* Store the syslog using a new thread */
                new Thread(new outputCsvRow(outputPath, new string[] { source, log }).addRow).Start();
                //for (int i = 0; i < emailTriggers.Count(); i++) { if (log.Contains(emailTriggers[i])) { emailEvent(); } }
                /* Search for trigger strings and send email if found */

                return;
            }

            //private void emailEvent() /* Send email notification */
            //{
            //    try
            //    {
            //        MailMessage notificationEmail = new MailMessage();
            //        notificationEmail.Subject = "SysLog Event";
            //        notificationEmail.IsBodyHtml = true;
            //        notificationEmail.Body = "<b>SysLog Event Triggered:<br/><br/>Time: </b><br/>" + 
            //            DateTime.Now.ToString() + "<br/><b>Source IP: </b><br/>” + 
            //            source + “<br/><b>Event: </b><br/>" + log; /* Throw in some basic HTML for readability */
            //        notificationEmail.From = new MailAddress("SysLog@metastruct.com", "SysLog Server"); /* From Address */
            //        notificationEmail.To.Add(new MailAddress("metastructblog@gmail.com", "metastruct")); /* To Address */
            //        SmtpClient emailClient = new SmtpClient("10.10.10.10"); /* Address of your SMTP server of choice */
            //        //emailClient.UseDefaultCredentials = false; /* If your SMTP server requires credentials to send email */
            //        //emailClient.Credentials = new NetworkCredential(“username”, “password”); /* Supply User Name and Password */
            //        emailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            //        emailClient.Send(notificationEmail); /* Send the email */
            //    }
            //    catch (Exception ex) { Console.WriteLine(ex.ToString()); }
            //    return;
            //}
        }
        class outputCsvRow : Form
        {
            private string formattedRow = null;
            private string outputPath = null;

            public outputCsvRow(string filePath, string[] columns) /* Initialize object */
            {
                outputPath = filePath;
                formattedRow = (char)34 + DateTime.Now.ToString() + (char)34; /* Construct csv row starting with the timestamp */
                for (int i = 0; i < columns.Count(); i++) { formattedRow += "," + (char)34 + columns[i] + (char)34; }
            }

            public void addRow()
            {
                int attempts = 0;
                bool canAccess = false;
                StreamWriter logWriter = null;
                if (!File.Exists(outputPath)) /* If the file doesn't exist, give it some column headers */
                {
                    logWriter = new StreamWriter(outputPath, true);
                    logWriter.WriteLine((char)34 + "Event_Time" + (char)34 + "," +
                      (char)34 + "Device_IP" + (char)34 + "," + (char)34 + "SysLog" + (char)34);
                    logWriter.Close();
                }
                /* Thread safety first! This is a poor man's SpinLock */
                while (true)
                {
                    try
                    {
                        logWriter = new StreamWriter(outputPath, true); /* Try to open the file for writing */
                        canAccess = true; /* Success! */
                        break;
                    }
                    catch (IOException ex)
                    {
                        if (attempts < 15) { attempts++; Thread.Sleep(50); }
                        else { Console.WriteLine(ex.ToString()); break; } /* Give up after 15 attempts */
                    }
                }
                if (canAccess) /* Write the line if the file is accessible */
                {
                   
                   //myform.Show;
                    
                    logWriter.WriteLine(formattedRow);
                    logWriter.Close();
                    
                    //Form1.listBox1.Items.Add(formattedRow);
                }
                return;
            }
        }


    }
}

Open in new window

SOLUTION
Avatar of d_york
d_york

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of linuxrox

ASKER

I see.  i'm new to c# so trying to learn.  Thanks and i'll take a look at what you've shown me here so maybe I can get this thing to work!  thanks again!
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
oh thank you!  yes samples are great and i love this stuff!!  it's so addictive for me.  i started off with VB6 and my jobs have moved me over into php/mysql and whatnot but i dabble in a bit of everything...borland delphi 7 and such.  but my life now doesn't allow me to really focus on anything in particular.   just no time for it but when i get on a project i really love to dig into it and learn as much as i can.  The reason i even started this project for a syslog server is because we need it to log WIFI connections and problems and i found some src code for a console c# syslog server and adapted it a bit to work for me and it works perfectly as a console but i just want to make it into a GUI and possibly let others have it for free because the other GUI programs out there as a free version only allow like 10 or 15 connections to the server...that's lame.  i can dish one out for free that accepts unlimited.  just isn't cost affective for most to have something that achieves a very simple goal.  to me it's like you are paying for unlimited connections to a socket!?!?!  wtf!  no way dude.  not in my world!