using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System.Diagnostics;
using System.IO.Log;

namespace orderWatch
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            this.WindowState = FormWindowState.Minimized; // Minimerer formularen

            InitializeComponent();

            tbSQLServer.Text = Properties.Settings.Default.SQLServer;
            tbSQLInstans.Text = Properties.Settings.Default.SQLInstans;
            tbSQLDb.Text = Properties.Settings.Default.SQLDb;
            tbSQLUser.Text = Properties.Settings.Default.SQLUser;
            tbSQLPassword.Text = Properties.Settings.Default.SQLPassword;

            updateNotifyIcon();

            notifyIcon.Visible = true;
        }

        private void updateNotifyIcon()
        {
            if (!String.IsNullOrEmpty(Properties.Settings.Default.SQLServer) && !String.IsNullOrEmpty(Properties.Settings.Default.SQLDb) && !String.IsNullOrEmpty(Properties.Settings.Default.SQLUser) && !String.IsNullOrEmpty(Properties.Settings.Default.SQLPassword))
            {
                if (CanWeConnectToDB())
                {
                    try
                    {
                        dgvDatagrundlag.DataSource = null;
                        dgvDatagrundlag.Rows.Clear();

                        SqlConnection conn = new SqlConnection("Server=tcp:" + Properties.Settings.Default.SQLServer + "\\" + Properties.Settings.Default.SQLInstans + ";database=" + Properties.Settings.Default.SQLDb + ";uid=" + Properties.Settings.Default.SQLUser + ";pwd=" + Properties.Settings.Default.SQLPassword + ";");

                        conn.Open();

                        SqlCommand sqlStr = new SqlCommand();
                        sqlStr.Connection = conn;
                        sqlStr.CommandText = @"
                        --TODO: Find ud af hvordan jeg også kan tage ordrer, som ikke har nogen status, med ind, hvis de har stået i x antal minutter uden status
                        --      for nu er det ikke nødvendigt, så afventer kundeservice, for at se om det bliver nødvendigt

                        SELECT
					        [SALESTABLE].[NUMBER_] AS 'Ordrenummer i LEG regnskabet',

	                        DATEDIFF(
		                        MINUTE,

		                        CONVERT(DATETIME, 
		                        (
		                        SELECT
			                        REPLACE([NOTES].[TXT], 'Ordren er lagt: ', '')

		                        FROM
			                        [NOTES]

		                        WHERE
			                        [NOTES].[DATASET] = 'DAT' AND
			                        [NOTES].[NOTESFILEID] = 127 AND
			                        [NOTES].[NOTESRECID] = [SALESTABLE].[ROWNUMBER] AND
			                        [NOTES].[TXT] LIKE 'Ordren er lagt: %'	

		                        ), 104), --Dato og klokkeslet for hvornår ordren er lagt
		
		                        GETDATE() --Dato og klokkeslet for nu
	                        ) AS 'Minutter siden ordren blev lagt'


                          FROM [dbo].[SALESTABLE]

                          WHERE
		                        [SALESTABLE].[DATASET] = 'LEG' AND

		                        [SALESTABLE].[TDS_STATUS] = 'ManuelPrint' AND

		                        [SALESTABLE].[PACKINGNOTE] = 0 AND --Pakkeseddel
		                        [SALESTABLE].[PACKINGSLIP] = 0 AND --Følgeseddel
		                        [SALESTABLE].[BACKORDER] = 0 AND --Restordrer
		                        [SALESTABLE].[LOANORDER] = 0 AND --Bruges som 'Pluk klar'

                                [SALESTABLE].[APPROVED] = 0 --Godkendt

                           ORDER BY
                               [SALESTABLE].[NUMBER_]
                        ";

                        sqlStr.ExecuteNonQuery();

                        SqlDataAdapter da = new SqlDataAdapter(sqlStr);

                        DataTable dt = new DataTable();

                        da.Fill(dt);

                        dgvDatagrundlag.DataSource = dt;

                        try
                        {
                            if (dt.Rows.Count > 0)
                            {
                                int minutesWaited = Convert.ToInt32(dt.Rows[0][1]);

                                if (minutesWaited > 0 && minutesWaited <= 30)
                                {
                                    saveNotifyIcon(minutesWaited.ToString("D2"), new Font("Segoe UI", 10, FontStyle.Regular, GraphicsUnit.Point), Color.White, Color.Green, false);
                                    updateNotifyIconIconTxt();
                                }

                                else if (minutesWaited > 30 && minutesWaited <= 60)
                                {
                                    saveNotifyIcon(minutesWaited.ToString(), new Font("Segoe UI", 10, FontStyle.Regular, GraphicsUnit.Point), Color.Black, Color.Yellow, false);
                                    updateNotifyIconIconTxt();
                                }

                                else if (minutesWaited > 60)
                                {
                                    saveNotifyIconIcon(notifyIconIcon_enum.error, true);
                                    updateNotifyIconIcon();
                                }

                                saveNotifyIconTxt(dt.Rows.Count + " Legebyen.dk ordre(r)" + Environment.NewLine + "til manuel behandling");
                                updateNotifyIconTxt(); 
                            }

                            else
                            {
                                saveNotifyIconIcon(notifyIconIcon_enum.ok, false);
                                updateNotifyIconIcon();

                                saveNotifyIconTxt("0 Legebyen.dk ordrer" + Environment.NewLine + "til manuel behandling");
                                updateNotifyIconTxt();
                            }
                        }

                        catch (Exception e)
                        {
                            // Log fejlinformationen til Windows-hændelsesloggen
                            using (EventLog eventLog = new EventLog("Application"))
                            {
                                eventLog.Source = "Order Watch";
                                eventLog.WriteEntry("Fejl opstod i forbindelse med at gemme notify icon: " + e.ToString(), EventLogEntryType.Error);
                            }
                        }

                        conn.Close();
                    }

                    catch (Exception e)
                    {
                        // Log fejlinformationen til Windows-hændelsesloggen
                        using (EventLog eventLog = new EventLog("Application"))
                        {
                            eventLog.Source = "Order Watch";
                            eventLog.WriteEntry("Fejl opstod i forbindelse med at gemme notify icon: " + e.ToString(), EventLogEntryType.Error);
                        }
                    }
                }

                else
                {
                    saveNotifyIconIcon(notifyIconIcon_enum.dbnoconn, true);
                    updateNotifyIconIcon();

                    saveNotifyIconTxt("Kan ikke forbinde til databasen");
                    updateNotifyIconTxt();
                }
            }

            else
            {
                saveNotifyIconIcon(notifyIconIcon_enum.dbnoconn, true);
                updateNotifyIconIcon();

                saveNotifyIconTxt("Kan ikke forbinde til databasen");
                updateNotifyIconTxt();
            }
        }

        private void updateNotifyIconTxt()
        {
            notifyIcon.Text = Properties.Settings.Default.notifyIconTxt;
        }

        private void saveNotifyIconTxt(string _txt)
        {
            Properties.Settings.Default.notifyIconTxt = _txt;
            Properties.Settings.Default.Save();
        }        

        private void blinkNotifyIconIcon()
        {
            if (Properties.Settings.Default.notifyIconIconType == notifyIconIconType.txt.ToString())
            {
                if (Properties.Settings.Default.notifyIconIconBlinkState)
                {
                    Properties.Settings.Default.notifyIconIconBlinkState = false;
                    Properties.Settings.Default.Save();

                    updateNotifyIconIconTxt();
                }

                else
                {
                    Properties.Settings.Default.notifyIconIconBlinkState = true;
                    Properties.Settings.Default.Save();

                    updateNotifyIconIconTxt(Properties.Settings.Default.notifyIconIconBlinkTxtColor, Properties.Settings.Default.notifyIconIconBlinkBgColor);
                }
            }

            else if (Properties.Settings.Default.notifyIconIconType == notifyIconIconType.ico.ToString())
            {
                if (Properties.Settings.Default.notifyIconIconBlinkState)
                {
                    Properties.Settings.Default.notifyIconIconBlinkState = false;
                    Properties.Settings.Default.Save();

                    updateNotifyIconIcon();
                }

                else
                {
                    Properties.Settings.Default.notifyIconIconBlinkState = true;
                    Properties.Settings.Default.Save();

                    updateNotifyIconIcon(notifyIconIcon_enum.blackFill);
                }
            }
        }

        public void saveNotifyIcon(string _text, Font _font, Color _txtColor, Color _bgColor, bool _blink)
        {
            Properties.Settings.Default.notifyIconIconType = notifyIconIconType.txt.ToString();
            Properties.Settings.Default.notifyIconIconBlink = _blink;

            Properties.Settings.Default.notifyIconIconTxt = _text;
            Properties.Settings.Default.notifyIconIconTxtFont = _font;
            Properties.Settings.Default.notifyIconIconTxtColor = _txtColor;
            Properties.Settings.Default.notifyIconIconBgColor = _bgColor;

            Properties.Settings.Default.Save();
        }

        public void saveNotifyIconIcon(notifyIconIcon_enum _icon_enum, bool _blink)
        {
            try
            { 
                Properties.Settings.Default.notifyIconIconType = notifyIconIconType.ico.ToString();
                Properties.Settings.Default.notifyIconIconBlink = _blink;

                Properties.Settings.Default.notifyIconIcon = _icon_enum.ToString();

                Properties.Settings.Default.Save();
            }

            catch (Exception e)
            {
                // Log fejlinformationen til Windows-hændelsesloggen
                using (EventLog eventLog = new EventLog("Application"))
                {
                    eventLog.Source = "Order Watch";
                    eventLog.WriteEntry("Fejl opstod i forbindelse med at gemme notify icon: " + e.ToString(), EventLogEntryType.Error);
                }
            }
        }

        public void updateNotifyIconIcon()
        {
            notifyIconIcon_enum icon_enum = (notifyIconIcon_enum)Enum.Parse(typeof(notifyIconIcon_enum), Properties.Settings.Default.notifyIconIcon);

            updateNotifyIconIcon(icon_enum);
        }

        public void updateNotifyIconIcon(notifyIconIcon_enum _icon_enum)
        {
            switch (_icon_enum)
            {
                case notifyIconIcon_enum.dbnoconn:
                    notifyIcon.Icon = Properties.Resources.dbnoconn;
                    break;

                case notifyIconIcon_enum.error:
                    notifyIcon.Icon = Properties.Resources.error;
                    break;

                case notifyIconIcon_enum.ok:
                    notifyIcon.Icon = Properties.Resources.ok;
                    break;

                case notifyIconIcon_enum.warning:
                    notifyIcon.Icon = Properties.Resources.warning;
                    break;

                case notifyIconIcon_enum.redFill:
                    setNotifyIconToColor(Color.Red);
                    break;

                case notifyIconIcon_enum.blackFill:
                    setNotifyIconToColor(Color.Black);
                    break;
            }
        }

        public void setNotifyIconToColor(Color _color)
        {
            try
            {
                using (Bitmap bitmap = new Bitmap(16, 16))
                {
                    using (Graphics graphics = Graphics.FromImage(bitmap))
                    {
                        SolidBrush bgBrush = new SolidBrush(_color);

                        graphics.FillRectangle(bgBrush, 0, 0, 16, 16);

                        using (Icon outputIcon = Icon.FromHandle(bitmap.GetHicon()))
                        {
                            bgBrush.Dispose();

                            notifyIcon.Icon = outputIcon;
                        }
                    }
                }
            }

            catch (Exception e)
            {

            }
        }

        public void updateNotifyIconIconTxt()
        {
            updateNotifyIconIconTxt(Properties.Settings.Default.notifyIconIconTxtColor, Properties.Settings.Default.notifyIconIconBgColor);
        }

        public void updateNotifyIconIconTxt(Color _txtColor, Color _bgColor)
        {
            try
            {
                using (Bitmap bitmap = new Bitmap(16, 16))
                {
                    using (Graphics graphics = Graphics.FromImage(bitmap))
                    {
                        Brush txtBrush = new SolidBrush(_txtColor);
                        SolidBrush bgBrush = new SolidBrush(_bgColor);

                        graphics.FillRectangle(bgBrush, 0, 0, 16, 16);

                        int centerX = (bitmap.Width - (int)graphics.MeasureString(Properties.Settings.Default.notifyIconIconTxt, Properties.Settings.Default.notifyIconIconTxtFont).Width) / 2;
                        int centerY = (bitmap.Height - (int)graphics.MeasureString(Properties.Settings.Default.notifyIconIconTxt, Properties.Settings.Default.notifyIconIconTxtFont).Height) / 2;

                        graphics.DrawString(Properties.Settings.Default.notifyIconIconTxt, Properties.Settings.Default.notifyIconIconTxtFont, txtBrush, centerX, centerY);

                        using (Icon icon = Icon.FromHandle(bitmap.GetHicon()))
                        {
                            notifyIcon.Icon = icon;
                        }

                        txtBrush.Dispose();
                        bgBrush.Dispose();
                    }
                }
            }

            catch (Exception e)
            {
                // Log fejlinformationen til Windows-hændelsesloggen
                using (EventLog eventLog = new EventLog("Application"))
                {
                    eventLog.Source = "Order Watch";
                    eventLog.WriteEntry("Fejl opstod under oprettelsen af Bitmap: " + e.ToString(), EventLogEntryType.Error);
                }
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                this.WindowState = FormWindowState.Minimized;

                e.Cancel = true;
            }
        }

        private void lukToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            updateNotifyIcon();
        }

        private void tbSQLServer_TextChanged(object sender, EventArgs e)
        {
        }

        private void tbSQLInstans_TextChanged(object sender, EventArgs e)
        {
        }

        private void tbSQLDb_TextChanged(object sender, EventArgs e)
        {
        }

        private void tbSQLUser_TextChanged(object sender, EventArgs e)
        {
        }

        private void tbSQLPassword_TextChanged(object sender, EventArgs e)
        {
        }

        private void btnTestOgGemDbInfo_Click(object sender, EventArgs e)
        {
            Properties.Settings.Default.SQLServer = tbSQLServer.Text;
            Properties.Settings.Default.SQLInstans = tbSQLInstans.Text;
            Properties.Settings.Default.SQLDb = tbSQLDb.Text;
            Properties.Settings.Default.SQLUser = tbSQLUser.Text;
            Properties.Settings.Default.SQLPassword = tbSQLPassword.Text;
            Properties.Settings.Default.Save();

            try
            {
                SqlConnection conn = new SqlConnection("Server=tcp:" + Properties.Settings.Default.SQLServer + "\\" + Properties.Settings.Default.SQLInstans + ";" + "database=" + Properties.Settings.Default.SQLDb + ";" + "uid=" + Properties.Settings.Default.SQLUser + ";" + "pwd=" + Properties.Settings.Default.SQLPassword + ";");

                conn.Open();

                updateNotifyIcon();

                MessageBox.Show("Der blev oprettet forbindelse til databasen og indstillingerne er gemt :)");

                conn.Close();
            }

            catch
            {
                updateNotifyIcon();

                MessageBox.Show("Der kunne IKKE forbindes til databasen!");
            }
        }

        private bool CanWeConnectToDB()
        {
            try
            {
                SqlConnection conn = new SqlConnection("Server=tcp:" + Properties.Settings.Default.SQLServer + "\\" + Properties.Settings.Default.SQLInstans + ";database=" + Properties.Settings.Default.SQLDb + ";uid=" + Properties.Settings.Default.SQLUser + ";pwd=" + Properties.Settings.Default.SQLPassword + ";");
                
                conn.Open();

                conn.Close();

                return true;
            }

            catch
            {
                return false;
            }
        }

        private void indstillingerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
        }

        private void timerBlink_Tick(object sender, EventArgs e)
        {
            if (Properties.Settings.Default.notifyIconIconBlink)
            {
                blinkNotifyIconIcon();
            }
        }
    }

    public enum notifyIconIconType
    {
        txt,

        ico
    }

    public enum notifyIconIcon_enum
    {
        dbnoconn,

        error,

        ok,

        warning,

        redFill,

        blackFill
    }
}
 

C Sharp Online Compiler

Write, Run & Share C# code online using OneCompiler's C# online compiler for free. It's one of the robust, feature-rich online compilers for C# language, running on the latest version 8.0. Getting started with the OneCompiler's C# compiler is simple and pretty fast. The editor shows sample boilerplate code when you choose language as C# and start coding.

Read inputs from stdin

OneCompiler's C# online compiler supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample program which takes name as input and print your name with hello.

using System;
 
namespace Sample
{
  class Test
    {
      public static void Main(string[] args)
       {
         string name;
         name = Console.ReadLine();
         Console.WriteLine("Hello {0} ", name);
	}
     }
}

About C Sharp

C# is a general purpose object-oriented programming language by Microsoft. Though initially it was developed as part of .net but later it was approved by ECMA and ISO standards.

You can use C# to create variety of applications, like web, windows, mobile, console applications and much more using Visual studio.

Syntax help

Data types

Data TypeDescriptionRangesize
intTo store integers-2,147,483,648 to 2,147,483,6474 bytes
doubleto store large floating point numbers with decimalscan store 15 decimal digits8 bytes
floatto store floating point numbers with decimalscan store upto 7 decimal digits4 bytes
charto store single characters-2 bytes
stringto stores text-2 bytes per character
boolto stores either true or false-1 bit

Variables

Syntax

datatype variable-name = value;

Loops

1. If-Else:

When ever you want to perform a set of operations based on a condition or set of few conditions IF-ELSE is used.

if(conditional-expression) {
   // code
} 
else {
   // code
}

You can also use if-else for nested Ifs and If-Else-If ladder when multiple conditions are to be performed on a single variable.

2. Switch:

Switch is an alternative to If-Else-If ladder.

switch(conditional-expression) {    
case value1:    
 // code    
 break;  // optional  
case value2:    
 // code    
 break;  // optional  
...    
    
default:     
 // code to be executed when all the above cases are not matched;    
} 

3. For:

For loop is used to iterate a set of statements based on a condition.

for(Initialization; Condition; Increment/decrement) {
  // code  
} 

4. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while(condition) {
 // code 
}

5. Do-While:

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

do {
  // code 
} while (condition);

Arrays

Array is a collection of similar data which is stored in continuous memory addresses. Array values can be fetched using index. Index starts from 0 to size-1.

Syntax

data-type[] array-name;

Methods

Method is a set of statements which gets executed only when they are called. Call the method name in the main function to execute the method.

Syntax

static void method-name() 
{
  // code to be executed
}