﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;
using System.ServiceProcess;
using System.Security.Principal;
using System.Security.Permissions;

namespace WinDalesa
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            if (ProcessChecker.IsOnlyProcess("WinDalesa"))
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new MainWindow());
            }
        }
        public static void serviceStartUp()
        {
            ServiceController service = new ServiceController("DCache");
            try
            {
                TimeSpan timeout = TimeSpan.FromMilliseconds(1000);
                WindowsIdentity id = WindowsIdentity.GetCurrent();
                WindowsPrincipal wPrincipal = new WindowsPrincipal(id);

                bool status = wPrincipal.IsInRole(@"BUILTIN\Administrators");

                try
                {
                    PrincipalPermission MyPermission = new PrincipalPermission(id.Name, @"BUILTIN\Administrators");
                    AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

                    service.Start();
                    service.WaitForStatus(ServiceControllerStatus.Running, timeout);
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        public static void serviceStop()
        {
            ServiceController service = new ServiceController("DCache");
            try
            {
                TimeSpan timeout = TimeSpan.FromMilliseconds(1000);
                WindowsIdentity id = WindowsIdentity.GetCurrent();
                WindowsPrincipal wPrincipal = new WindowsPrincipal(id);

                bool status = wPrincipal.IsInRole(@"BUILTIN\Administrators");

                try
                {
                    PrincipalPermission MyPermission = new PrincipalPermission(id.Name, @"BUILTIN\Administrators");
                    AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

                    service.Stop();
                    service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }

        }

    }
}
