NEWS: Total Picture Views: 126352 | Total Article Views: 116133 | Top 5 Most Popular Article: 1. Am I Stuck Algorithm with Becker Robot | 2. PickUpThings with Becker Robot | 3. Catch the Robots game with Becker Robots | 4. Create Wall and Things with Becker | 5. Encrypted Data GUI (Download .Zip)

Control Parental [Decide when computer must be closed] C

Description:

In this example. I'll be showing you how to access a JSON file from a website and parse it into an array. After that will check if the computer must be closed or not.

Code:

using Microsoft.Win32;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ControlParental
{
    class Program
    {
        private static bool isclosing = false;
        static void Main(string[] args)
        {
            AddApplicationToStartup();
            System.Diagnostics.Process.Start("shutdown", "/a");
            SetConsoleCtrlHandler(new HandlerRoutine(ConsoleCtrlCheck), true);
            string oldDay = "";
            int timeout = 10000;
            while (true)
            {
                String day = DateTime.Today.DayOfWeek.ToString();
                try
                {
                    JArray o = parseJSON();
                    int morning = 0;
                    int night = 0;

                    switch (day)
                    {
                        case "Sunday":
                            morning = Int32.Parse(o[0][0].ToString());
                            night = Int32.Parse(o[0][1].ToString());
                            break;
                        case "Monday":
                            morning = Int32.Parse(o[1][0].ToString());
                            night = Int32.Parse(o[1][1].ToString());
                            break;
                        case "Tuesday":
                            morning = Int32.Parse(o[2][0].ToString());
                            night = Int32.Parse(o[2][1].ToString());
                            break;
                        case "Wednesday":
                            morning = Int32.Parse(o[3][0].ToString());
                            night = Int32.Parse(o[3][1].ToString());
                            break;
                        case "Thursday":
                            morning = Int32.Parse(o[4][0].ToString());
                            night = Int32.Parse(o[4][1].ToString());
                            break;
                        case "Friday":
                            morning = Int32.Parse(o[5][0].ToString());
                            night = Int32.Parse(o[5][1].ToString());
                            break;
                        case "Saturday":
                            morning = Int32.Parse(o[6][0].ToString());
                            night = Int32.Parse(o[6][1].ToString());
                            break;
                    }

                    DateTime dtMorning = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, morning, 0, 0);
                    DateTime dtNight = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, night, 0, 0);


                    //Day is different           
                    if (day.CompareTo(oldDay) == 1)
                    {
                        Console.WriteLine("Today, your computer will stay open between: " + morning + " and " + night + ".");
                        oldDay = day;
                    }

                    if (DateTime.Now < dtMorning || DateTime.Now > dtNight)
                    {
                        Console.WriteLine("Must close computer.");
                        closeComputer();
                    }
                    //Console.WriteLine("Request Completed!");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("We can't reach the server... We will try again in 10 seconds...");
                }
                Thread.Sleep(timeout);
            }
        }

        static private JArray parseJSON()
        {
            //Console.WriteLine("Sending Request...");
            string json = get_web_content("http://jmdev.ca/hubs/");
            String day = DateTime.Today.DayOfWeek.ToString();

            JArray a = JArray.Parse(json);

            return a;
        }

        static private string get_web_content(string url)
        {
            Uri uri = new Uri(url);
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
            request.Method = WebRequestMethods.Http.Get;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream());
            string output = reader.ReadToEnd();
            response.Close();

            return output;
        }

        private static void closeComputer()
        {
            Console.WriteLine("Must close computer.");
            System.Diagnostics.Process.Start("shutdown", "/s /t 30");
        }

        private static bool ConsoleCtrlCheck(CtrlTypes ctrlType)
        {
            // Put your own handler here
            switch (ctrlType)
            {
                case CtrlTypes.CTRL_C_EVENT:                
                    Console.WriteLine("CTRL+C received!");
                    closeComputer();
                    break;

                case CtrlTypes.CTRL_BREAK_EVENT:
                    Console.WriteLine("CTRL+BREAK received!");
                    closeComputer();
                    break;

                case CtrlTypes.CTRL_CLOSE_EVENT:
                    Console.WriteLine("Program being closed!");
                    closeComputer();
                    break;

                case CtrlTypes.CTRL_LOGOFF_EVENT:
                case CtrlTypes.CTRL_SHUTDOWN_EVENT:
                    Console.WriteLine("User is logging off!");
                    break;

            }
            return true;
        }

        #region unmanaged
        // Declare the SetConsoleCtrlHandler function
        // as external and receiving a delegate.

        [DllImport("Kernel32")]
        public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);

        // A delegate type to be used as the handler routine
        // for SetConsoleCtrlHandler.
        public delegate bool HandlerRoutine(CtrlTypes CtrlType);

        // An enumerated type for the control messages
        // sent to the handler routine.
        public enum CtrlTypes
        {
            CTRL_C_EVENT = 0,
            CTRL_BREAK_EVENT,
            CTRL_CLOSE_EVENT,
            CTRL_LOGOFF_EVENT = 5,
            CTRL_SHUTDOWN_EVENT
        }

        #endregion

        public static void AddApplicationToStartup()
        {
            RegistryKey rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            rk.SetValue("ControlParental", "C:\\ControlParental.exe");
        }
    }

}
Attachments: None

Tags: JSON HttpWebResponse Uri C#

Total Views: 771

My name is Jean-Mathieu

I created this website so other people could enjoy finding useful stuff easier. If you have any question do not hesitate to contact me.

jean8mathieuCreated on 12/13/15 and updated on 12/13/15


affiliate_link

Disclosure: We are a website that needs compensation to operate like any other website on the internet.
We may receive consideration for our reviews but we are totally unbiased and do not accept paid reviews or fake reviews claiming to be something they are not.