Wednesday, December 9, 2015

C# Windows Form Program to monitor EDI files transferring.

        Recently, users report to me that the EDI incoming and outgoing files sit on the network share folder for a long time. When this happens, we need to restart the AS2 connector service and restart the EDI tasks. But we need monitor the files and get alert first.
        So I write this C# program to monitor the files. It will check files every 15 minutes.
        1. We need to create two csv files(incoming.csv, and outgoing.csv). It includes Customer, Folder Path, Number of Files (sit on this folder), (current) Status, Last Stauts.
         2. Use Visual Studio to create a C# windows form project. Add two lables, two dataGridViews, and one button. Just like the following.
           3. Code for the from1.cs
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.Mail;
using System.Net;
using System.Threading.Tasks;

namespace MonitorDeltaFiles
{
    public partial class Form1 : Form
    {

        string mailstring = "";
        public Form1()
        {
            InitializeComponent();
        }

        //run the following code when load the form.
         private void Form1_Load(object sender, EventArgs e)
        {
            refreshform();
            System.Windows.Forms.Timer timer1 = new System.Windows.Forms.Timer();
            timer1.Interval = 1000 * 60 * 15;
            timer1.Tick += new System.EventHandler(timer1_Tick);
            timer1.Start();
        }


        // function to refresh the from
        private void refreshform()
        {
            mailstring = "";
            int GridViewHeight = 0;
            updatestatus("incoming.csv");
            List<string[]> incomingrows = File.ReadAllLines("incoming.csv").Select(x => x.Split(',')).ToList();
            DataTable incomingdt = new DataTable();
            incomingdt.Columns.Add("Customer");
            incomingdt.Columns.Add("Folder Path");
            incomingdt.Columns.Add("Number of Files");
            incomingdt.Columns.Add("Status");
            incomingdt.Columns.Add("Last Status");
            incomingrows.ForEach(x =>
            { incomingdt.Rows.Add(x); });
            dataGridView1.DataSource = incomingdt;
            GridViewHeight = GetHeightandformatting(dataGridView1);

            lbl_outgoing.Location = new Point(13, 54 + GridViewHeight + 38);
            dataGridView2.Location = new Point(43, 54 + GridViewHeight + 38 + 23);

            updatestatus("outgoing.csv");
            List<string[]> outgoingrows = File.ReadAllLines("outgoing.csv").Select(x => x.Split(',')).ToList();
            DataTable outgoingdt = new DataTable();
            outgoingdt.Columns.Add("Customer");
            outgoingdt.Columns.Add("Folder Path");
            outgoingdt.Columns.Add("Number of Files");
            outgoingdt.Columns.Add("Status");
            outgoingdt.Columns.Add("Last Status");
            outgoingrows.ForEach(x =>
            { outgoingdt.Rows.Add(x); });
            dataGridView2.DataSource = outgoingdt;
            GridViewHeight = GetHeightandformatting(dataGridView2);

            if (mailstring.Length > 0)
            {
                mailstring = "Please check the following path(s).\r\n" + "\r\n" + mailstring;
                Task.Factory.StartNew(() => { SendMail("victor.quan@durafreight.com", mailstring); });
                //SendMail("victor.quxx@dxxxxx.com", mailstring);
               this.Activate();
            }
        }

        // function update the csv files.
        private void updatestatus(string filename)
        {
            int returnFileNum = 0 ;
            StreamReader sr = new StreamReader(filename);
            var lines = new List<string[]>();
            while (!sr.EndOfStream)
            {
                string[] Line = sr.ReadLine().Split(',');
                lines.Add(Line);
            }
            sr.Close();
            foreach (var item in lines)
            {
                returnFileNum = checkfiles(item[1]);
                item[4] = item[3];
                if (returnFileNum == 0)
                {
                    item[2] = "0";
                    item[3] = "Green";
                }
                else
                {
                    if (returnFileNum < Int32.Parse(item[2]))
                    {
                        item[2] = returnFileNum.ToString();
                        item[3] = "Orange";
                    }
                    else
                    {
                        item[2] = returnFileNum.ToString();
                        item[3] = "Red";
                    }
                }
            }

            StreamWriter newfile = new StreamWriter(filename);
            foreach (var item in lines)
            {
                newfile.WriteLine(item[0] + "," + item[1] + "," + item[2] + "," + item[3] +"," + item[4]);
            }
            lines.Clear();
            newfile.Close();
        }


        //get the files number in the folder
        private int checkfiles(string fullfilename)
        {
            string[] files = Directory.GetFiles(fullfilename, "*.*", SearchOption.TopDirectoryOnly);
            return files.Length;
        }


        //format the table, high light red when both current status and last status are red.
        private int GetHeightandformatting(DataGridView myDataGridView)
        {
            myDataGridView.AutoResizeColumns();

            int height = 0;
            foreach (DataGridViewRow row in myDataGridView.Rows)
            {
                height += row.Height;
            }
            height += myDataGridView.ColumnHeadersHeight;

            int width = 0;
            foreach (DataGridViewColumn col in myDataGridView.Columns)
            {
                width += col.Width;
            }

            myDataGridView.ClientSize = new Size(width + 3, height + 2);

            foreach (DataGridViewRow Myrow in myDataGridView.Rows)
            {
                if (Myrow.Cells[3].Value.ToString() == "Red" & Myrow.Cells[4].Value.ToString() == "Red")
                {
                    Myrow.Cells[3].Style.BackColor = Color.Red;
                    Myrow.Cells[4].Style.BackColor = Color.Red;
                    mailstring = mailstring + Myrow.Cells[1].Value.ToString() + "\r\n";
                }
            }
            return height;
        }

        private void btnrefresh_Click(object sender, EventArgs e)
        {
            refreshform();
        }

        //user timer, run it very 15 minutes.
        private void timer1_Tick(object sender, EventArgs e)
        {
            refreshform();
        }

        //send email alert when find files sit in folder more than 30 minutes.
        private void SendMail(string to, string mailbody)
        {
            MailAddress Mailto = new MailAddress(to);
            MailAddress Mailfrom = new MailAddress("smtpxx@dxxxx.xxx");
            MailMessage mail = new MailMessage(Mailfrom, Mailto);
            mail.Subject = "Please check the AS2 and Delta Server";
            mail.Body = mailbody;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "Smtp.office365.com";
            smtp.Port = 587;
            smtp.Credentials = new NetworkCredential("smtpxx@dxxxx.xxx", "Yourpassword");
            smtp.EnableSsl = true;
            smtp.Send(mail);
        }

    }
}

4.Test.


No comments:

Post a Comment