Пример #1
0
        private void ServicesManualButton_Click(object sender, EventArgs e)
        {
            bool ItemExists = false;

            var selected = ServicesTextBox.Text;

            if (selected != string.Empty)
            {
                try
                {
                    ServiceController sc = new ServiceController(selected);

                    var displayName = sc.DisplayName;

                    foreach (string item in ServicesManualBox.Items)
                    {
                        if (item == selected + ';' + displayName)
                        {
                            ItemExists = true;
                            break;
                        }
                    }

                    if (!ItemExists)
                    {
                        ServicesManualBox.Items.Add(selected + ';' + displayName);
                        Default.ServicesToManual.Add(selected + ';' + displayName);
                    }
                }
                catch (Exception ex)
                {
                    EasyLogger.Error(selected + " : " + ex + Environment.NewLine);
                    BeginInvoke(new MethodInvoker(() => Console(selected + " : " + ex.Message)));
                }

                ServicesTextBox.Text = string.Empty;
            }

            Default.Save();
        }
        public void DesktopWeatherXML(string url, string savePath)
        {
            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                try
                {
                    XDocument xml = XDocument.Load(url);

                    xml.Save(savePath);
                }
                catch (Exception ex)
                {
                    ConnectedToInternet = false;

                    EasyLogger.Info("It appears that you do not have an internet connection. We will retry later. The actual error message is: " + Environment.NewLine + Environment.NewLine + "     " + ex.Message + Environment.NewLine);
                }

                if (File.Exists(NWSAlertsDirectory + "\\WeatherInfo.xml"))
                {
                    EasyLogger.Info("New weather information downloaded and saved successfully");

                    fileInfo = new FileInfo(NWSAlertsDirectory + "\\WeatherInfo.xml");

                    FileTime = fileInfo.LastWriteTime;
                }
                else
                {
                    EasyLogger.Info("It appears you are not connected to the internet. Please check your internet connection and try again.");

                    MessageBox.Show("It appears you are not connected to the internet. Please check your internet connection and try again.", "NWS Alerts", MessageBoxButton.OK, MessageBoxImage.Information);

                    NotifyTray.notifyIcon.Visible = false;

                    Environment.Exit(0);
                }

                SetWeatherUI();
            }));
        }
Пример #3
0
        // Disable Sceduled Tasks
        static void DisableSetTask(string taskname)
        {
            ProcessStartInfo start = new ProcessStartInfo();

            start.FileName               = "schtasks.exe";
            start.UseShellExecute        = false;
            start.CreateNoWindow         = true;
            start.WindowStyle            = ProcessWindowStyle.Hidden;
            start.Arguments              = "/query /TN " + "\"" + taskname + "\"";
            start.RedirectStandardOutput = true;

            using (Process process = Process.Start(start))
            {
                using (StreamReader reader = process.StandardOutput)
                {
                    string stdout = reader.ReadToEnd();
                    if (stdout.Contains(taskname))
                    {
                        if (stdout.Contains("Ready"))
                        {
                            EasyLogger.Info("Disabling task: " + taskname);

                            ProcessStartInfo info = new ProcessStartInfo();
                            info.FileName               = "schtasks.exe";
                            info.UseShellExecute        = false;
                            info.CreateNoWindow         = true;
                            info.WindowStyle            = ProcessWindowStyle.Hidden;
                            info.Arguments              = "/change /TN " + "\"" + taskname + "\"" + " /DISABLE";
                            info.RedirectStandardOutput = true;
                            using (Process proc = Process.Start(info))
                            {
                                proc.WaitForExit();
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Publish a post with image
        /// </summary>
        /// <returns>result</returns>
        /// <param name="message">message to publish</param>
        /// <param name="pathToImage">image to attach</param>
        internal string PublishTweet(string message)
        {
            try
            {
                Task <string> rezText = Task.Run(async() =>
                {
                    string response = await Tweet(TweetLimit.CutTweetToLimit(message));
                    return(response);
                });

                if (rezText.Result != "OK")
                {
                    EasyLogger.Warning(rezText.Result);
                }

                return("OK");
            }
            catch (Exception ex)
            {
                EasyLogger.Error("TweetMessage - @PublishTweet(1): " + ex);
                return(ex.Message);
            }
        }
Пример #5
0
 public static void MessageLogging(string text, string title = null, MessageBoxButtons buttons = MessageBoxButtons.OK, MessageBoxIcon icon = MessageBoxIcon.Information, MessageBoxDefaultButton defaultButton = MessageBoxDefaultButton.Button2)
 {
     try
     {
         // Log this message for debugging
         if (icon == MessageBoxIcon.Error)
         {
             EasyLogger.Error(text);
         }
         else if (icon == MessageBoxIcon.Warning)
         {
             EasyLogger.Info(text);
         }
         else
         {
             EasyLogger.Info(text);
         }
     }
     catch (Exception ex)
     {
         EasyLogger.Error(ex);
     }
 }
Пример #6
0
 private void Proc_DataReceived(object sender, DataReceivedEventArgs e)
 {
     try
     {
         if (e.Data != null)
         {
             if (!e.Data.Contains("[=") && !e.Data.Contains("%") && e.Data != string.Empty)
             {
                 string Output = Regex.Replace(e.Data, "\x00", "");
                 if (Output != string.Empty)
                 {
                     EasyLogger.Info(Output);
                     BeginInvoke(new MethodInvoker(() => Console(Output)));
                 }
             }
         }
     }
     catch (Exception ex)
     {
         EasyLogger.Error(ex + Environment.NewLine);
         BeginInvoke(new MethodInvoker(() => Console(ex.Message)));
     }
 }
        public void SetWeatherUI()
        {
            EasyLogger.Info("Updating Desktop Weather info using WeatherInfo.xml");

            using (FileStream fileStream = new FileStream(NWSAlertsDirectory + "\\WeatherInfo.xml",
                                                          FileMode.Open,
                                                          FileAccess.Read,
                                                          FileShare.ReadWrite))
            {
                xmlDoc = new XmlDocument();
                xmlDoc.Load(fileStream);

                xPathNavigator = xmlDoc.CreateNavigator();

                // Location
                LargeTileInfoNode = xPathNavigator.SelectSingleNode(@"(//tile/visual/binding[@template='TileLarge'])");

                LocationLabel.Content = LargeTileInfoNode.GetAttribute("DisplayName", "");

                // Background Image
                LargeTileInfoNode = xPathNavigator.SelectSingleNode(@"(//tile/visual/binding[@template='TileLarge']/image)");

                Uri uri = new Uri(WeatherInstallLocation + Assets + LargeTileInfoNode.GetAttribute("src", "").Replace("?a", "").Replace("/", "\\"), UriKind.Absolute);

                windowBackground.Source  = new BitmapImage(uri);
                Background.Opacity       = OpacitySlider.Value;
                windowBackground.Opacity = OpacitySlider.Value;

                SettingsPanel.Background = new ImageBrush(windowBackground.Source);
                SettingsPanel.Background.SetValue(RenderOptions.BitmapScalingModeProperty, BitmapScalingMode.HighQuality);


                // Current Conditions
                LargeTileInfoNode         = xPathNavigator.SelectSingleNode(@"(//tile/visual/binding[@template='TileLarge']/text)");
                CurrentConditions.Content = LargeTileInfoNode.Value;

                // Current Temps
                LargeTileInfoNode = xPathNavigator.SelectSingleNode(@"(//group/subgroup[@hint-weight='100']/text)");

                CurrentTemp.Content = LargeTileInfoNode.Value.Replace("Â", "");


                // Day1 Forecast Day
                LargeTileInfoNode = xPathNavigator.SelectSingleNode(@"(//group/subgroup[@hint-weight='18']/text)[1]");

                day1.Content = LargeTileInfoNode.Value;


                // Day1 Forecast Image
                LargeTileInfoNode = xPathNavigator.SelectSingleNode(@"(//group/subgroup[@hint-weight='18']/image)[1]");
                image1.Source     = new BitmapImage(new Uri(WeatherInstallLocation + Assets + LargeTileInfoNode.GetAttribute("src", "").Replace("?a", "").Replace("/", "\\"), UriKind.Absolute));

                // Day1 Forecast High
                LargeTileInfoNode = xPathNavigator.SelectSingleNode(@"(//group/subgroup[@hint-weight='18']/text)[2]");

                high1.Content = LargeTileInfoNode.Value.Replace("Â", "");


                // Day1 Forecast Low
                LargeTileInfoNode = xPathNavigator.SelectSingleNode(@"(//group/subgroup[@hint-weight='18']/text)[3]");

                low1.Content = LargeTileInfoNode.Value.Replace("Â", "");


                // Day2 Forecast Day
                LargeTileInfoNode = xPathNavigator.SelectSingleNode(@"(//group/subgroup[@hint-weight='18']/text)[4]");

                day2.Content = LargeTileInfoNode.Value;


                // Day2 Forecast Image
                LargeTileInfoNode = xPathNavigator.SelectSingleNode(@"(//group/subgroup[@hint-weight='18']/image)[2]");

                image2.Source = new BitmapImage(new Uri(WeatherInstallLocation + Assets + LargeTileInfoNode.GetAttribute("src", "").Replace("?a", "").Replace("/", "\\"), UriKind.Absolute));


                // Day2 Forecast High
                LargeTileInfoNode = xPathNavigator.SelectSingleNode(@"(//group/subgroup[@hint-weight='18']/text)[5]");

                high2.Content = LargeTileInfoNode.Value.Replace("Â", "");


                // Day2 Forecast Low
                LargeTileInfoNode = xPathNavigator.SelectSingleNode(@"(//group/subgroup[@hint-weight='18']/text)[6]");

                low2.Content = LargeTileInfoNode.Value.Replace("Â", "");


                // Day3 Forecast Day
                LargeTileInfoNode = xPathNavigator.SelectSingleNode(@"(//group/subgroup[@hint-weight='18']/text)[7]");

                day3.Content = LargeTileInfoNode.Value;


                // Day3 Forecast Image
                LargeTileInfoNode = xPathNavigator.SelectSingleNode(@"(//group/subgroup[@hint-weight='18']/image)[3]");

                image3.Source = new BitmapImage(new Uri(WeatherInstallLocation + Assets + LargeTileInfoNode.GetAttribute("src", "").Replace("?a", "").Replace("/", "\\"), UriKind.Absolute));


                // Day3 Forecast High
                LargeTileInfoNode = xPathNavigator.SelectSingleNode(@"(//group/subgroup[@hint-weight='18']/text)[8]");

                high3.Content = LargeTileInfoNode.Value.Replace("Â", "");


                // Day3 Forecast Low
                LargeTileInfoNode = xPathNavigator.SelectSingleNode(@"(//group/subgroup[@hint-weight='18']/text)[9]");

                low3.Content = LargeTileInfoNode.Value.Replace("Â", "");


                // Day4 Forecast Day
                LargeTileInfoNode = xPathNavigator.SelectSingleNode(@"(//group/subgroup[@hint-weight='18']/text)[10]");

                day4.Content = LargeTileInfoNode.Value;


                // Day4 Forecast Image
                LargeTileInfoNode = xPathNavigator.SelectSingleNode(@"(//group/subgroup[@hint-weight='18']/image)[4]");

                image4.Source = new BitmapImage(new Uri(WeatherInstallLocation + Assets + LargeTileInfoNode.GetAttribute("src", "").Replace("?a", "").Replace("/", "\\"), UriKind.Absolute));


                // Day4 Forecast High
                LargeTileInfoNode = xPathNavigator.SelectSingleNode(@"(//group/subgroup[@hint-weight='18']/text)[11]");

                high4.Content = LargeTileInfoNode.Value.Replace("Â", "");


                // Day4 Forecast Low
                LargeTileInfoNode = xPathNavigator.SelectSingleNode(@"(//group/subgroup[@hint-weight='18']/text)[12]");

                low4.Content = LargeTileInfoNode.Value.Replace("Â", "");


                // Day5 Forecast Day
                LargeTileInfoNode = xPathNavigator.SelectSingleNode(@"(//group/subgroup[@hint-weight='18']/text)[13]");

                day5.Content = LargeTileInfoNode.Value;


                // Day5 Forecast Image
                LargeTileInfoNode = xPathNavigator.SelectSingleNode(@"(//group/subgroup[@hint-weight='18']/image)[5]");

                image5.Source = new BitmapImage(new Uri(WeatherInstallLocation + Assets + LargeTileInfoNode.GetAttribute("src", "").Replace("?a", "").Replace("/", "\\"), UriKind.Absolute));


                // Day5 Forecast High
                LargeTileInfoNode = xPathNavigator.SelectSingleNode(@"(//group/subgroup[@hint-weight='18']/text)[14]");

                high5.Content = LargeTileInfoNode.Value.Replace("Â", "");


                // Day5 Forecast Low
                LargeTileInfoNode = xPathNavigator.SelectSingleNode(@"(//group/subgroup[@hint-weight='18']/text)[15]");

                low5.Content = LargeTileInfoNode.Value.Replace("Â", "");

                NotifyTray.notifyIcon.Text = (string)LocationLabel.Content + Environment.NewLine + (string)CurrentConditions.Content + " " + (string)CurrentTemp.Content;

                Updating = false;
            }
        }
        internal static async Task <string> PostMessage(string PAGE_NAME, string USER_ID, string PAGE_ID, string USER_TOKEN, bool isImage, string MESSAGE_STRING, string IMAGE_PATH, string LINK_URL)
        {
            try
            {
                using (WebClient wb = new WebClient())
                {
                    string responseInString = wb.DownloadString("https://graph.facebook.com/" + USER_ID + "/accounts?access_token=" + USER_TOKEN);

                    JObject jdata = JObject.Parse(responseInString);
                    JToken  array = jdata["data"];

                    foreach (JToken account in array)
                    {
                        if (account["name"].ToString().Equals(PAGE_NAME))
                        {
                            string PAGE_TOKEN = account["access_token"].ToString();

                            try
                            {
                                string response = null;

                                if (!isImage)
                                {
                                    response = await Task.Run(() => FacebookText.PostAsync(PAGE_ID, PAGE_TOKEN, MESSAGE_STRING, LINK_URL));

                                    if (response != "OK")
                                    {
                                        EasyLogger.Warning(response);

                                        Form.ActiveForm.TopMost     = true;
                                        Form.ActiveForm.WindowState = FormWindowState.Minimized;
                                        Form.ActiveForm.Show();
                                        Form.ActiveForm.ShowInTaskbar = true;
                                        Form.ActiveForm.WindowState   = FormWindowState.Normal;
                                        Form.ActiveForm.WindowState   = Properties.Settings.Default.windowState;
                                        Form.ActiveForm.BringToFront();
                                        Form.ActiveForm.Focus();
                                        Form.ActiveForm.Activate();
                                        Form.ActiveForm.TopMost = false;

                                        Scheduler.tabControlOne.SelectedIndex = 4;
                                    }
                                    else
                                    {
                                        EasyLogger.Info("Requested message posted successfully!");

                                        return("OK");
                                    }
                                }
                                else if (isImage)
                                {
                                    response = await Task.Run(() => FacebookImage.PostAsync(PAGE_ID, PAGE_TOKEN, MESSAGE_STRING, IMAGE_PATH));

                                    if (response != "OK")
                                    {
                                        EasyLogger.Warning(response);

                                        Form.ActiveForm.TopMost     = true;
                                        Form.ActiveForm.WindowState = FormWindowState.Minimized;
                                        Form.ActiveForm.Show();
                                        Form.ActiveForm.ShowInTaskbar = true;
                                        Form.ActiveForm.WindowState   = FormWindowState.Normal;
                                        Form.ActiveForm.WindowState   = Properties.Settings.Default.windowState;
                                        Form.ActiveForm.BringToFront();
                                        Form.ActiveForm.Focus();
                                        Form.ActiveForm.Activate();
                                        Form.ActiveForm.TopMost = false;

                                        Scheduler.tabControlOne.SelectedIndex = 4;
                                    }
                                    else
                                    {
                                        EasyLogger.Info("Requested message posted successfully!");

                                        return("OK");
                                    }
                                }

                                return("OK");
                            }
                            catch (Exception ex)
                            {
                                EasyLogger.Error("GetToken - @PostMessage(1): " + ex);

                                return("Error: " + ex.Message);
                            }
                        }
                    }
                }

                return(string.Empty);
            }
            catch (Exception ex)
            {
                EasyLogger.Error("GetToken - @GetPageToken(1): " + ex);

                return(ex.Message);
            }
        }
Пример #9
0
        /// <summary>
        /// Publish a post with image
        /// </summary>
        /// <returns>result</returns>
        /// <param name="message">message to publish</param>
        /// <param name="image">image to attach</param>
        internal string PublishTweet(string message, string image = null)
        {
            try
            {
                string mediaID = string.Empty;
                Task <Tuple <int, string> > rezImage = Task.Run(async() =>
                {
                    Tuple <int, string> response = await Tweet(image);
                    return(response);
                });
                JObject rezImageJson = JObject.Parse(rezImage.Result.Item2);

                if (rezImage.Result.Item1 != 200)
                {
                    try
                    {
                        return($"Error uploading image to Twitter. {rezImageJson["errors"][0]["message"].Value<string>()}");
                    }
                    catch
                    {
                        return("Unknown error uploading image to Twitter");
                    }
                }
                mediaID = rezImageJson["media_id_string"].Value <string>();

                Task <Tuple <int, string> > rezText = Task.Run(async() =>
                {
                    Tuple <int, string> response = await TweetText(TweetLimit.CutTweetToLimit(message), mediaID);
                    return(response);
                });
                JObject rezTextJson = JObject.Parse(rezText.Result.Item2);

                if (rezText.Result.Item1 != 200)
                {
                    try
                    {
                        return($"Error sending image to Twitter. {rezTextJson["errors"][0]["message"].Value<string>()} - Response Code: " + rezText.Result.Item1);
                    }
                    catch
                    {
                        return("Unknown error sending image to Twitter - Response Code: " + rezText.Result.Item1);
                    }
                }

                try
                {
                    if (File.Exists(image))
                    {
                        File.Delete(image);
                    }
                }
                catch (Exception ex)
                {
                    EasyLogger.Error("TweetImage - @PublishTweet(1): " + ex);
                }

                return("OK");
            }
            catch (Exception ex)
            {
                EasyLogger.Error("TweetImage - @PublishTweet(2): " + ex);
                return(ex.Message);
            }
        }
Пример #10
0
 private static void AppDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
 {
     EasyLogger.Error(((Exception)e.ExceptionObject).Message + " AppDomain.UnhandledException");
 }
Пример #11
0
        private void StartCheckup()
        {
            StopRequested             = false;
            StopCheckupButton.Enabled = true;
            FullSystemCheckup.Enabled = true;
            Checkup.Enabled           = false;
            FullSystemCheckup.Enabled = false;
            DiskCheck.Enabled         = false;

            EasyLogger.Info("*********************  Flush DNS  *********************" + Environment.NewLine);
            BeginInvoke(new MethodInvoker(() => Console("*********************  Flush DNS  *********************")));
            RunCommand("ipconfig.exe", "/flushdns", "Flush DNS");
            if (StopRequested)
            {
                Stop();
                return;
            }

            RunCommand("ipconfig.exe", "/registerdns", "Register DNS");
            if (StopRequested)
            {
                Stop();
                return;
            }

            EasyLogger.Info("*********************  Sync Time  *********************" + Environment.NewLine);
            BeginInvoke(new MethodInvoker(() => Console("*********************  Sync Time  *********************")));

            RunCommand("net.exe", "start w32time", "w32time");
            if (StopRequested)
            {
                Stop();
                return;
            }
            RunCommand("w32tm.exe", "/resync /force", "w32time");
            if (StopRequested)
            {
                Stop();
                return;
            }

            EasyLogger.Info("*********************  DISM Checkup  *********************" + Environment.NewLine);
            BeginInvoke(new MethodInvoker(() => Console("*********************  DISM Checkup  *********************")));

            RunCommand("DISM.exe", "/online /Cleanup-Image /StartComponentCleanup /ResetBase /RestoreHealth", "DISM");
            if (StopRequested)
            {
                Stop();
                return;
            }
            RunCommand("DISM.exe", "/online /Cleanup-Image /StartComponentCleanup", "DISM");
            if (StopRequested)
            {
                Stop();
                return;
            }

            EasyLogger.Info("*********************  System File Checker  *********************" + Environment.NewLine);
            BeginInvoke(new MethodInvoker(() => Console("*********************  System File Checker  *********************")));
            RunCommand("sfc.exe", "/scannow", "SFC");
            if (StopRequested)
            {
                Stop();
                return;
            }

            StopCheckupButton.Enabled = false;
            FullSystemCheckup.Enabled = false;
            Checkup.Enabled           = true;
            FullSystemCheckup.Enabled = true;
            DiskCheck.Enabled         = true;

            notifyIcon1.Visible = true;
            notifyIcon1.ShowBalloonTip(7000);
            notifyIcon1.Visible = false;

            Console("***************************  Checkup Completed  ***************************");

            if (RebootBox.Checked)
            {
                Console("************************  Rebooting in 30 seconds  ************************");

                using (Process p = new Process())
                {
                    p.StartInfo.FileName  = "shutdown";
                    p.StartInfo.Arguments = "-r -t 30";
                    p.Start();
                }
                Environment.Exit(0);
            }
        }
Пример #12
0
        // Add Menu Items
        private void AddMenuItems(string[] array)
        {
            try
            {
                // Disabler
                bool isShortcut   = false;
                bool isExeDllFile = false;
                foreach (string path in array)
                {
                    try
                    {
                        if (Path.GetExtension(path) == ".lnk")
                        {
                            isShortcut = true;
                        }
                        if (Path.GetExtension(path) != ".exe" && Path.GetExtension(path) != ".dll")
                        {
                            isExeDllFile = false;
                        }
                        if (Path.GetExtension(path) == ".exe" || Path.GetExtension(path) == ".dll")
                        {
                            isExeDllFile = true;
                        }
                        if (Directory.Exists(ShortcutHandler.GetShortcutTarget(path)))
                        {
                        }
                    }
                    catch (Exception ex)
                    {
                        EasyLogger.Error(ex.Message + " Error at ShortcutHandler.GetShortcutTarget(path)");
                        continue;
                    }
                }
                object OpenNotepadFiles = xMenuToolsSettings.GetValue("OpenNotepadFiles");
                if (OpenNotepadFiles != null)
                {
                    if (OpenNotepadFiles.ToString() == "1")
                    {
                        xMenuToolsMenu.DropDownItems.Add(OpenNotepad);
                    }
                }
                object BlockWithFirewallFiles = xMenuToolsSettings.GetValue("BlockWithFirewallFiles");
                if (BlockWithFirewallFiles != null)
                {
                    if (BlockWithFirewallFiles.ToString() == "1")
                    {
                        xMenuToolsMenu.DropDownItems.Add(BlockFirewall);
                    }
                }
                object CopyPathFiles = xMenuToolsSettings.GetValue("CopyPathFiles");
                if (CopyPathFiles != null && !isShortcut)
                {
                    if (CopyPathFiles.ToString() == "1")
                    {
                        xMenuToolsMenu.DropDownItems.Add(CopyPath);
                    }
                }
                object CopyNameFiles = xMenuToolsSettings.GetValue("CopyNameFiles");
                if (CopyNameFiles != null && !isShortcut)
                {
                    if (CopyNameFiles.ToString() == "1")
                    {
                        xMenuToolsMenu.DropDownItems.Add(CopyName);
                    }
                }
                object AttributesFiles = xMenuToolsSettings.GetValue("AttributesFiles");
                if (AttributesFiles != null)
                {
                    if (AttributesFiles.ToString() == "1")
                    {
                        xMenuToolsMenu.DropDownItems.Add(Attributes);
                        Attributes.DropDownItems.Add(AttributesMenu);
                        Attributes.DropDownItems.Add(new ToolStripSeparator());
                        Attributes.DropDownItems.Add(HiddenAttributes);
                        Attributes.DropDownItems.Add(SystemAttributes);
                        Attributes.DropDownItems.Add(ReadOnlyAttributes);
                    }
                }
                object SymlinkFiles = xMenuToolsSettings.GetValue("SymlinkFiles");
                if (SymlinkFiles != null)
                {
                    if (SymlinkFiles.ToString() == "1")
                    {
                        xMenuToolsMenu.DropDownItems.Add(SymLink);
                    }
                }
                object TakeOwnershipFiles = xMenuToolsSettings.GetValue("TakeOwnershipFiles");
                if (TakeOwnershipFiles != null)
                {
                    if (TakeOwnershipFiles.ToString() == "1")
                    {
                        xMenuToolsMenu.DropDownItems.Add(TakeOwnership);
                    }
                }
                object AttributesShortcuts = xMenuToolsSettings.GetValue("AttributesShortcuts");
                if (AttributesShortcuts != null && isShortcut)
                {
                    if (AttributesShortcuts.ToString() == "1")
                    {
                        xMenuToolsMenu.DropDownItems.Add(Attributes);
                    }
                    else
                    {
                        Attributes.Dispose();
                    }
                }
                object OpenNotepadShort = xMenuToolsSettings.GetValue("OpenNotepadShort");
                if (OpenNotepadShort != null && isShortcut)
                {
                    if (OpenNotepadShort.ToString() == "1")
                    {
                        xMenuToolsMenu.DropDownItems.Add(OpenNotepad);
                    }
                    else
                    {
                        OpenNotepad.Dispose();
                    }
                }
                object CopyPathShortFiles = xMenuToolsSettings.GetValue("CopyPathShortFiles");
                if (CopyPathShortFiles != null && isShortcut)
                {
                    if (CopyPathShortFiles.ToString() == "1")
                    {
                        xMenuToolsMenu.DropDownItems.Add(CopyPath);
                    }
                }
                object CopyNameShortFiles = xMenuToolsSettings.GetValue("CopyNameShortFiles");
                if (CopyNameShortFiles != null && isShortcut)
                {
                    if (CopyNameShortFiles.ToString() == "1")
                    {
                        xMenuToolsMenu.DropDownItems.Add(CopyName);
                    }
                }

                MenuItemDisabler(isShortcut, isExeDllFile);
            }
            catch (System.ComponentModel.Win32Exception ex)
            {
                StartProcess.StartInfo(AttributesInfo.GetAssembly.AssemblyInformation("directory") + @"\xMenuTools.exe", "\"" + ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine + ex.Source + Environment.NewLine + ex.GetBaseException() + Environment.NewLine + ex.TargetSite + "\"" + " -catchhandler");
            }
        }
Пример #13
0
        private static void StartLightCleanup()
        {
            if (Default.DeleteBrokenShortcuts)
            {
                EasyLogger.Info("*********************  Delete Broken Shortcuts  *********************" + Environment.NewLine);
                BrokenShortcuts.Remove();
            }
            if (Default.InvalidFirewallBox)
            {
                EasyLogger.Info("*********************  Remove Invalid Firewall Rules  *********************" + Environment.NewLine);
                WindowsFirewall.DeleteInvalid();
            }

            if (Default.InvalidVariablesBox)
            {
                EasyLogger.Info("*********************  Remove Invalid Environment Variables  *********************" + Environment.NewLine);
                WindowsVariables.DeleteInvalid();
            }

            if (Default.TasksToDisable.Count > 0)
            {
                EasyLogger.Info("*********************  Disable Scheduled Tasks  *********************" + Environment.NewLine);
                DisableTasks.SetTasks();
            }

            if (Default.ServicesToManual.Count > 0 || Default.ServicesToDisable.Count > 0)
            {
                EasyLogger.Info("*********************  Unused Services To Manual  *********************" + Environment.NewLine);
                SetServices.SetStatus();
            }

            if (Default.FilesToHide.Count > 0)
            {
                EasyLogger.Info("*********************  Set Files to Hidden  *********************" + Environment.NewLine);
                HideFiles.SetAsHidden();
            }

            if (Default.PathFilesToDelete.Count > 0)
            {
                EasyLogger.Info("*********************  Delete Files In Directory  *********************" + Environment.NewLine);
                DeleteInDirectory.DeleteSetFiles();
            }

            if (Default.PathFilesToDeleteOlder.Count > 0)
            {
                EasyLogger.Info("*********************  Delete Files in Directory Older  *********************" + Environment.NewLine);
                DeleteInDirectoryOlder.DeleteSetFiles();
            }

            if (Default.FilesToDelete.Count > 0)
            {
                EasyLogger.Info("*********************  Delete Specific Files  *********************" + Environment.NewLine);
                DeleteFiles.DeleteSetFiles();
            }

            if (Default.DirectoriesToDelete.Count > 0)
            {
                EasyLogger.Info("*********************  Delete Specific Directories  *********************" + Environment.NewLine);
                DeleteDirectories.DeleteSetPaths();
            }
        }
Пример #14
0
        internal static void Remove()
        {
            try
            {
                string[] directories = { Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory), Environment.GetFolderPath(Environment.SpecialFolder.StartMenu), Environment.GetFolderPath(Environment.SpecialFolder.CommonStartMenu), Environment.GetFolderPath(Environment.SpecialFolder.Programs), Environment.GetFolderPath(Environment.SpecialFolder.CommonPrograms) };

                foreach (string directory in directories)
                {
                    EasyLogger.Info("Searching " + directory + " for broken shortcuts...");

                    try
                    {
                        var files = Directory.EnumerateFiles(directory, "*.lnk", SearchOption.AllDirectories);

                        foreach (var file in files)
                        {
                            if (file.Length > 0)
                            {
                                RemoveBrokenShortcuts(file);
                            }
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        continue;
                    }
                    catch (PathTooLongException)
                    {
                        continue;
                    }

                    try
                    {
                        var files = Directory.EnumerateFiles(directory, "*.url", SearchOption.AllDirectories);

                        foreach (var file in files)
                        {
                            if (file.Length > 0)
                            {
                                RemoveBrokenShortcuts(file);
                            }
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        continue;
                    }
                    catch (PathTooLongException)
                    {
                        continue;
                    }
                }
            }
            catch (Exception ex)
            {
                EasyLogger.Error(ex);
            }

            try
            {
                string[] directories = { Environment.GetFolderPath(Environment.SpecialFolder.StartMenu), Environment.GetFolderPath(Environment.SpecialFolder.CommonStartMenu), Environment.GetFolderPath(Environment.SpecialFolder.Programs), Environment.GetFolderPath(Environment.SpecialFolder.CommonPrograms) };
                foreach (string directory in directories)
                {
                    try
                    {
                        if (directory.Length > 0)
                        {
                            DeleteEmptySubdirectories(directory);
                        }
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }
            }
            catch (Exception ex)
            {
                EasyLogger.Error(ex);
            }
        }
Пример #15
0
        private void AddToFirewall(string operation)
        {
            TryAgain :;
            try
            {
                int dotCount = 0;
                FilesCount = 0;
                Thread thread = new Thread(() => EnumerateFiles())
                {
                    IsBackground = true
                };
                thread.Start();
                progressBar1.Value = 0;
                current            = 0;

                if (operation == Resources.FirewallArgs && RootPath != null)
                {
                    while (CountingFilesOperation)
                    {
                        Thread.Sleep(500);

                        dotCount++;
                        if (dotCount == 2)
                        {
                            label1.Text = Operation;
                        }

                        if (dotCount == 4)
                        {
                            label1.Text = Operation + ".";
                        }

                        if (dotCount == 6)
                        {
                            label1.Text = Operation + "..";
                        }
                        if (dotCount == 8)
                        {
                            label1.Text = Operation + "...";
                            dotCount    = 0;
                        }
                        Application.DoEvents();
                    }
                    label1.Text = Resources.Blocking + Resources.outbound;
                    foreach (string item in RootPath)
                    {
                        try
                        {
                            while (PauseOperation)
                            {
                                Thread.Sleep(500);
                            }

                            current++;
                            string path      = Path.GetDirectoryName(item);
                            string title     = Path.GetFileName(path) + " - " + Path.GetFileName(item);
                            string arguments = "advfirewall firewall add rule name=" + "\"" + MainFolderName + " - " + title + "\"" + " dir=out program=" + "\"" + item + "\"" + " action=block";
                            progressBar1.Value = (current * 100) / FilesCount;
                            try
                            {
                                Text = Resources.BlockingFilesTitle + progressBar1.Value + Resources.Percentage;
                            }
                            catch (ArgumentOutOfRangeException ex)
                            {
                                EasyLogger.Error(ex);
                                continue;
                            }
                            label2.Text = Path.GetFileName(Path.GetDirectoryName(item)) + ": " + Path.GetFileName(item);
                            Application.DoEvents();
                            StartProcess.StartInfo("netsh.exe", arguments, true, true, true);
                        }
                        catch (ArgumentOutOfRangeException ex)
                        {
                            EasyLogger.Error(ex);
                            continue;
                        }
                    }
                    current            = 0;
                    progressBar1.Value = 0;
                    label1.Text        = Resources.Blocking + Resources.inbound;
                    foreach (string item in RootPath)
                    {
                        try
                        {
                            while (PauseOperation)
                            {
                                Thread.Sleep(500);
                            }

                            current++;
                            string path      = Path.GetDirectoryName(item);
                            string title     = Path.GetFileName(path) + " - " + Path.GetFileName(item);
                            string arguments = "advfirewall firewall add rule name=" + "\"" + MainFolderName + " - " + title + "\"" + " dir=in program=" + "\"" + item + "\"" + " action=block";
                            progressBar1.Value = (current * 100) / FilesCount;
                            try
                            {
                                Text = Resources.BlockingFilesTitle + progressBar1.Value + Resources.Percentage;
                            }
                            catch (ArgumentOutOfRangeException ex)
                            {
                                EasyLogger.Error(ex);
                                continue;
                            }
                            label2.Text = Path.GetFileName(Path.GetDirectoryName(item)) + ": " + Path.GetFileName(item);
                            Application.DoEvents();
                            StartProcess.StartInfo("netsh.exe", arguments, true, true, true);
                        }
                        catch (ArgumentOutOfRangeException ex)
                        {
                            EasyLogger.Error(ex);
                            continue;
                        }
                    }
                    Thread.Sleep(1500);
                    if (current > 0 && NoMoreThreads)
                    {
                        Hide();

                        DialogResult results = MessageForm(Resources.DialogMessageBlockFolder, Resources.DialogTitleSuccess, MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                        if (results == DialogResult.Yes)
                        {
                            StartProcess.StartInfo("wf.msc");
                        }
                    }
                    else if (current == 0)
                    {
                        Hide();

                        MessageForm(Resources.DialogMessageFail, Resources.DialogTitleFail, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                ThreadRunning = false;
                if (NoMoreThreads)
                {
                    ExplorerRefresh.RefreshWindowsExplorer();
                    Environment.Exit(0);
                }
            }
            catch (Exception ex)
            {
                EasyLogger.Error(ex);
                goto TryAgain;
            }
        }
Пример #16
0
        private void MultiSelectFirewallFiles(string[] array)
        {
            try
            {
                // wait for the form to load
                while (!Ready)
                {
                    Thread.Sleep(200);
                    Application.DoEvents();
                }
                try
                {
                    Invoke(new Action(() =>
                    {
                        progressBar1.Enabled = true;

                        progressBar1.Style = ProgressBarStyle.Marquee;

                        PauseButton.Enabled = false;
                        StopButton.Enabled  = false;

                        label3.Text = "Task:";

                        label2.Text = "Firewall";

                        label1.Text = "Add files to Windows Defender Firewall inbound and outbound rules.";
                    }));
                }
                catch (Exception ex)
                {
                    EasyLogger.Error(ex);
                }

                foreach (string item in array)
                {
                    try
                    {
                        MainFolderName = Path.GetFileName(item);

                        string path      = Path.GetDirectoryName(item);
                        string title     = Path.GetFileName(path) + " - " + Path.GetFileName(item);
                        string arguments = "advfirewall firewall add rule name=" + "\"" + MainFolderName + " - " + title + "\"" + " dir=out program=" + "\"" + item + "\"" + " action=block";

                        StartProcess.StartInfo("netsh.exe", arguments, true, true, true);

                        path      = Path.GetDirectoryName(item);
                        title     = Path.GetFileName(path) + " - " + Path.GetFileName(item);
                        arguments = "advfirewall firewall add rule name=" + "\"" + MainFolderName + " - " + title + "\"" + " dir=in program=" + "\"" + item + "\"" + " action=block";

                        StartProcess.StartInfo("netsh.exe", arguments, true, true, true);
                    }
                    catch (Exception ex)
                    {
                        MessageForm(ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine + ex.Source + Environment.NewLine + ex.GetBaseException() + Environment.NewLine + ex.TargetSite, "xMenuTools", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        NoErrors = false;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageForm(ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine + ex.Source + Environment.NewLine + ex.GetBaseException() + Environment.NewLine + ex.TargetSite, "xMenuTools", MessageBoxButtons.OK, MessageBoxIcon.Error);
                NoErrors = false;
            }

            try
            {
                // wait for the form to load
                while (!Ready)
                {
                    Thread.Sleep(200);
                    Application.DoEvents();
                }
                try
                {
                    Invoke(new Action(() =>
                    {
                        Hide();
                        if (NoErrors)
                        {
                            DialogResult results = MessageForm(Resources.DialogMessageBlockFiles, Resources.DialogTitleSuccess, MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                            if (results == DialogResult.Yes)
                            {
                                StartProcess.StartInfo("wf.msc");
                            }
                        }
                    }));
                }
                catch (Exception ex)
                {
                    EasyLogger.Error(ex);
                }
            }
            catch (Exception ex)
            {
                MessageForm(ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine + ex.Source + Environment.NewLine + ex.GetBaseException() + Environment.NewLine + ex.TargetSite, "xMenuTools", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            Environment.Exit(0);
        }
Пример #17
0
        private void StartDiskCheck(bool DoFullCheckup)
        {
            StopRequested             = false;
            StopCheckupButton.Enabled = true;
            FullSystemCheckup.Enabled = true;
            Checkup.Enabled           = false;
            FullSystemCheckup.Enabled = false;
            DiskCheck.Enabled         = false;

            try
            {
                EasyLogger.Info("Running disk check(s)...");
                BeginInvoke(new MethodInvoker(() => Console("Running disk check(s)...")));

                DriveInfo[] SysDrives = DriveInfo.GetDrives();
                foreach (var drive in SysDrives)
                {
                    string    driveName = drive.Name;
                    DriveType driveType = drive.DriveType;
                    switch (driveType)
                    {
                    case DriveType.CDRom:
                        break;

                    case DriveType.Fixed:
                        // Local Drive
                        if (StopRequested)
                        {
                            break;
                        }
                        RunCommand("cmd.exe", "/C echo y|ChkDsk.exe " + string.Concat(drive.ToString().Replace("\\", ""), " /x /f"), "Check Disk");

                        if (StopRequested)
                        {
                            StopCheckupButton.Enabled = false;
                            FullSystemCheckup.Enabled = false;
                            Checkup.Enabled           = true;
                            FullSystemCheckup.Enabled = true;
                            DiskCheck.Enabled         = true;
                            return;
                        }
                        break;

                    case DriveType.Network:
                        // Mapped Drive
                        break;

                    case DriveType.NoRootDirectory:
                        break;

                    case DriveType.Ram:
                        break;

                    case DriveType.Removable:
                        // Usually a USB Drive
                        break;

                    case DriveType.Unknown:
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                EasyLogger.Error(ex + Environment.NewLine);
                BeginInvoke(new MethodInvoker(() => Console(ex.Message)));
            }

            if (StopRequested)
            {
                StopCheckupButton.Enabled = false;
                FullSystemCheckup.Enabled = false;
                Checkup.Enabled           = true;
                FullSystemCheckup.Enabled = true;
                DiskCheck.Enabled         = true;
                return;
            }

            Console("*********************  Disk Check Completed  *********************");

            if (!DoFullCheckup)
            {
                StopCheckupButton.Enabled = false;
                FullSystemCheckup.Enabled = false;
                Checkup.Enabled           = true;
                FullSystemCheckup.Enabled = true;
                DiskCheck.Enabled         = true;

                notifyIcon1.Visible = true;
                notifyIcon1.ShowBalloonTip(7000);
                notifyIcon1.Visible = false;

                if (RebootBox.Checked)
                {
                    Console("*********************  Rebooting in 30 seconds  *********************");
                    using (Process p = new Process())
                    {
                        p.StartInfo.FileName  = "shutdown";
                        p.StartInfo.Arguments = "-r -t 30";
                        p.Start();
                    }
                    Environment.Exit(0);
                }
            }
            else
            {
                StartCheckup();
            }
        }
Пример #18
0
        static void Main(string[] args)
        {
            var context = new LoggerContextFactory().CreateDbContext(null);


            EasyLogger logger = new EasyLogger(
                new ApenLoggerConfiguration()
            {
                LogRepository = LogRepository.Database,
                FileLogOption = new FileLogOption()
                {
                    LogFileInterval = LogFileInterval.Hourly,
                    FilePath        = @".\Logs\"
                }
            }, context
                );
            EasyAuditor auditor = new EasyAuditor(
                new ApenLoggerConfiguration()
            {
                LogRepository = LogRepository.Database,
                FileLogOption = new FileLogOption()
                {
                    LogFileInterval = LogFileInterval.Hourly,
                    FilePath        = @".\Logs\"
                }
            }, context
                );

            logger.LogInformation("", "", ActionType.Approve, "StartUp", null);
            for (int i = 0; i < 99; i++)
            {
                var d = i <= 30 ? (i + 1) : (i % 30 == 0 ? 1 : (i % 30));
                var x = new WeatherForecastWithPOCOs()
                {
                    Date = DateTime.Now.AddDays(i),
                    TemperatureCelsius = i,
                    Summary            = $"Hot",
                    DatesAvailable     = new List <DateTimeOffset>()
                    {
                        DateTime.Parse($"2019-08-{d:00}T00:00:00-07:00"),
                        DateTime.Parse($"2019-08-{d:00}T00:00:00-07:00")
                    },
                    SummaryWords = new List <string> {
                        "Cool", "Windy", "Humid"
                    }.ToArray()
                };
                logger.LogInformation(nameof(Program), i.ToString(), ActionType.Execute, "StartUp", x);
                if (i % 2 == 0)
                {
                    logger.LogInformation(nameof(Program), i.ToString(), ActionType.Create, $"Looping Values ({i})", x);
                    auditor.AuditEvent(nameof(Program), i.ToString(), ActionType.Create, "*****@*****.**", "Create", x);
                }
                if (i % 3 == 0)
                {
                    logger.LogCritical(nameof(Program), i.ToString(), ActionType.Update, $"Looping Values ({i})", x);
                    auditor.AuditEvent(nameof(Program), i.ToString(), ActionType.Update, "*****@*****.**", "Updated", x);
                }
                if (i % 5 == 0)
                {
                    logger.LogError(nameof(Program), i.ToString(), ActionType.Approve, $"Looping Values ({i})", x);
                    auditor.AuditEvent(nameof(Program), i.ToString(), ActionType.Approve, "*****@*****.**", "Approve", x);
                }
                if (i % 7 == 0)
                {
                    logger.LogWarning(nameof(Program), i.ToString(), ActionType.Delete, $"Looping Values ({i})", x);
                    auditor.AuditEvent(nameof(Program), i.ToString(), ActionType.Delete, "*****@*****.**", "Deleted", x);
                }
            }

            var logs = context.SystemLogs.ToList();

            foreach (var item in logs)
            {
                Console.WriteLine($"{item.Id} | {item.Executed} | {item.LogLevel} | {item.Source} | {item.ActionType} | {item.Action} | {item.Reference} | {item.Detail}");
            }

            var audittrail = context.AuditLogs.ToList();

            foreach (var item in audittrail)
            {
                Console.WriteLine($"{item.Id} | {item.Executed} | {item.Actor} | {item.Source} | {item.ActionType} | {item.Action} | {item.Reference} | {item.Detail}");
            }
        }
        /// <summary>
        /// {instagram_id}/media?image_url={image_url}&access_token={access_token}
        /// {instagram_id}/media_publish?creation_id={creation-id}&access_token={access_token}
        /// </summary>
        internal static void PostToInstagram()
        {
            try
            {
                string USER_TOKEN = GetToken.RenewAccessToken(Properties.Settings.Default.InstagramToken, Properties.Settings.Default.InstagramAppSecret, Properties.Settings.Default.InstagramAppID);
                if (USER_TOKEN.Contains("ERROR:"))
                {
                    EasyLogger.Error(USER_TOKEN);
                }
                else
                {
                    if (USER_TOKEN != "The remote server returned an error: (400) Bad Request.")
                    {
                        EasyLogger.Info("Your Instagram user token has been renewed successfully!");

                        Properties.Settings.Default.InstagramToken = USER_TOKEN;
                        Properties.Settings.Default.Save();
                        Properties.Settings.Default.Reload();
                    }
                    else
                    {
                        EasyLogger.Warning("Error: The remote server returned an error: (400) Bad Request.");
                        return;
                    }

                    HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(Properties.Settings.Default.WebsiteFeed);
                    hwr.Accept = "text/xml, */*";
                    hwr.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-us");
                    hwr.UserAgent = "Mozilla";
                    hwr.KeepAlive = true;
                    hwr.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;

                    using (var resp = (HttpWebResponse)hwr.GetResponse())
                    {
                        using (Stream s = resp.GetResponseStream())
                        {
                            string   cs = String.IsNullOrEmpty(resp.CharacterSet) ? "UTF-8" : resp.CharacterSet;
                            Encoding e  = Encoding.GetEncoding(cs);

                            using (StreamReader sr = new StreamReader(s, e))
                            {
                                var allXml = sr.ReadToEnd();

                                allXml = Regex.Replace(allXml,
                                                       "(.*)<script type='text/javascript'>.+?</script>(.*)",
                                                       "$1$2",
                                                       RegexOptions.Singleline);

                                using (XmlReader xmlr = XmlReader.Create(new StringReader(allXml)))
                                {
                                    SyndicationFeed        feedContent = SyndicationFeed.Load(xmlr);
                                    List <SyndicationItem> feedItems   = new List <SyndicationItem>();

                                    foreach (SyndicationItem item in feedContent.Items)
                                    {
                                        feedItems.Add(item);
                                    }
                                    feedItems.Reverse();
                                    feedContent.Items = feedItems;

                                    if (null == feedContent)
                                    {
                                        return;
                                    }

                                    foreach (SyndicationItem item in feedContent.Items)
                                    {
                                        string quota_total = string.Empty;
                                        string quota_usage = string.Empty;
                                        try
                                        {
                                            using (WebClient wb = new WebClient())
                                            {
                                                string responseInString = wb.DownloadString("https://graph.facebook.com/" + Properties.Settings.Default.InstagramPageID + "/content_publishing_limit?fields=config&access_token=" + Properties.Settings.Default.InstagramToken);

                                                JObject jdata = JObject.Parse(responseInString);
                                                JToken  array = jdata["data"];
                                                foreach (JToken info in array)
                                                {
                                                    quota_total = info["config"]["quota_total"].ToString();
                                                }
                                            }

                                            using (WebClient wb = new WebClient())
                                            {
                                                string responseInString = wb.DownloadString("https://graph.facebook.com/" + Properties.Settings.Default.InstagramPageID + "/content_publishing_limit?fields=quota_usage&access_token=" + Properties.Settings.Default.InstagramToken);

                                                JObject jdata = JObject.Parse(responseInString);
                                                JToken  array = jdata["data"];

                                                foreach (JToken info in array)
                                                {
                                                    quota_usage = info["quota_usage"].ToString();
                                                }
                                            }
                                        }
                                        catch { }

                                        int usage = Convert.ToInt32(quota_usage);
                                        int total = Convert.ToInt32(quota_total);

                                        if (usage >= total)
                                        {
                                            EasyLogger.Info("Instagram post quota reached!");
                                            break;
                                        }

                                        try
                                        {
                                            System.Collections.ObjectModel.Collection <SyndicationLink> links = item.Links;

                                            string         title = item.Title.Text + " - " + links[0].Uri.ToString();
                                            string         image = ExtensionMethods.GetEnclosureUri(item);
                                            DateTimeOffset date  = item.PublishDate;

                                            if (StringToDTOffset(Properties.Settings.Default.PublishDate) < date)
                                            {
                                                Task <string> success    = PostAsync(image, title);
                                                int           posts_used = Convert.ToInt32(quota_usage);
                                                posts_used++;
                                                EasyLogger.Info(success.Result + Environment.NewLine + "Instagram Post usage for the day: " + posts_used + " of " + quota_total);

                                                Properties.Settings.Default.PublishDate = date.ToString();
                                                Properties.Settings.Default.Save();
                                                Properties.Settings.Default.Reload();
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            EasyLogger.Error(ex);
                                            continue;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                EasyLogger.Error(ex);
            }
        }
Пример #20
0
        public static void DeleteSetFiles()
        {
            // Delete Files and Folders in a Directory
            foreach (string paths in Default.PathFilesToDelete)
            {
                try
                {
                    if (Directory.Exists(paths))
                    {
                        var filesPath = Environment.ExpandEnvironmentVariables(paths);

                        // Files
                        foreach (string file in Directory.GetFiles(filesPath))
                        {
                            bool deleted = false;
                            try
                            {
                                File.Delete(file);
                                deleted = true;
                            }
                            catch (Exception ex)
                            {
                                deleted = false;
                                EasyLogger.Error(file + " : " + ex);
                                continue;
                            }
                            if (deleted)
                            {
                                EasyLogger.Info("Deleting file: " + file);
                            }
                        }

                        // Directories
                        foreach (string directory in Directory.GetDirectories(filesPath))
                        {
                            bool deleted = false;
                            try
                            {
                                Directory.Delete(directory, true);
                                deleted = true;
                            }
                            catch (Exception ex)
                            {
                                deleted = false;
                                EasyLogger.Error(directory + " : " + ex);
                                continue;
                            }
                            if (deleted)
                            {
                                EasyLogger.Info("Deleting directory: " + directory);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    EasyLogger.Error(paths + " : " + ex);
                    continue;
                }
            }
        }
Пример #21
0
        static void Main(string[] args)
        {
            if (Default.LoggingEnabled)
            {
                EasyLogger.BackupLogs(EasyLogger.LogFile, 30);
                EasyLogger.AddListener(EasyLogger.LogFile);
            }

            if (Default.UpgradeRequired)
            {
                Default.Upgrade();
                Default.UpgradeRequired = false;
                Default.Save();
                Default.Reload();
            }
            if (Default.FirstRun)
            {
                Default.FirstRun = false;
                Default.Save();
                Default.Reload();

                SettingsForm settings = new SettingsForm();
                settings.ShowDialog();

                Environment.Exit(0);
            }

            if (args.Length > 0)
            {
                try
                {
                    string A0 = args[0].ToLower();

                    if (args[0] == "/optimize" || args[0] == "-optimize")
                    {
                        StartLightCleanup();
                    }
                    else
                    {
                        StartLightCleanup();
                    }
                }
                catch (Exception ex)
                {
                    EasyLogger.Info(ex.Message);
                }
            }
            else
            {
                // Run Settings and Close
                SettingsForm settings = new SettingsForm();
                settings.ShowDialog();
            }

            EasyLogger.Info("*********************  END OF OPTIMIZATIONS  *********************");

            EasyLogger.RemoveListener();

#if DEBUG
            using (StreamReader sr = File.OpenText(EasyLogger.LogFile))
            {
                string lines = sr.ReadToEnd();

                if (lines.ToLower().Contains("[error]"))
                {
                    MessageBox.Show("The log file contains errors!", "Maintenance", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                    Process.Start(EasyLogger.LogDirectory);
                }
            }
#endif

            Environment.Exit(0);
        }
Пример #22
0
 public HomeController(LoggerDbContext logContext)
 {
     _logger  = new EasyLogger(nameof(HomeController), logContext);
     _auditor = new EasyAuditor(nameof(HomeController), logContext);
 }
Пример #23
0
        // Delete Files and Folders in a Directory older than x days
        public static void DeleteSetFiles()
        {
            foreach (string path in Default.PathFilesToDeleteOlder)
            {
                try
                {
                    int days      = Convert.ToInt32(path.Split(',')[0]);
                    var filesPath = Environment.ExpandEnvironmentVariables(path.Split(',')[1].Trim());

                    // Files
                    foreach (string f in Directory.GetFiles(filesPath, "*", SearchOption.AllDirectories))
                    {
                        bool deleted = false;
                        try
                        {
                            FileInfo fi = new FileInfo(f);
                            if (fi.LastWriteTime < DateTime.Now.AddDays(-days))
                            {
                                File.Delete(f);
                                deleted = true;
                            }
                        }
                        catch (Exception ex)
                        {
                            deleted = false;
                            EasyLogger.Error(f + " : " + ex);
                            continue;
                        }
                        if (deleted)
                        {
                            EasyLogger.Info("Deleting file: " + f);
                        }
                    }

                    // Directories
                    string[] dirs = Directory.GetDirectories(filesPath, "*", SearchOption.AllDirectories);
                    foreach (string d in dirs)
                    {
                        bool deleted = false;
                        try
                        {
                            DirectoryInfo fi = new DirectoryInfo(d);
                            if (fi.LastWriteTime < DateTime.Now.AddDays(-days))
                            {
                                try
                                {
                                    Directory.Delete(d, false);
                                    deleted = true;
                                }
                                catch
                                {
                                    continue;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            deleted = false;
                            EasyLogger.Error(d + " : " + ex);
                            continue;
                        }
                        if (deleted)
                        {
                            EasyLogger.Info("Deleting file: " + d);
                        }
                    }
                }
                catch (Exception ex)
                {
                    EasyLogger.Error(path + " : " + ex);
                    continue;
                }
            }
        }
Пример #24
0
 private static void AppDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
 {
     EasyLogger.Error(((Exception)e.ExceptionObject).Message + Environment.NewLine + ((Exception)e.ExceptionObject).StackTrace + Environment.NewLine + ((Exception)e.ExceptionObject).InnerException + " AppDomain.UnhandledException");
 }
Пример #25
0
        private static void RemoveBrokenShortcuts(string shortcut)
        {
            try
            {
                Shell shell = new Shell();

                string shortcut_path = shortcut.Substring(0, shortcut.LastIndexOf("\\"));
                string shortcut_name = shortcut.Substring(shortcut.LastIndexOf("\\") + 1);

                if (shortcut_name.EndsWith(".lnk"))
                {
                    Folder shortcut_folder = shell.NameSpace(shortcut_path);

                    FolderItem folder_item = shortcut_folder.Items().Item(shortcut_name);

                    try
                    {
                        ShellLinkObject lnk  = (ShellLinkObject)folder_item.GetLink;
                        string          path = lnk.Path;
                        if (!string.IsNullOrEmpty(path))
                        {
                            try
                            {
                                if (!FileExistance.FileExists(path))
                                {
                                    EasyLogger.Info("Deleting broken shortcut: " + shortcut + ". The target doesn't exits: " + path);
                                    try
                                    {
                                        File.Delete(shortcut);
                                    }
                                    catch { /* ignore */ }
                                    try
                                    {
                                        Directory.Delete(shortcut);
                                    }
                                    catch { /* ignore */ }
                                }
                            }
                            catch { /* ignore */ }
                        }
                    }
                    catch { /* ignore */ }
                }

                // Epic Games & Steam
                if (shortcut_name.EndsWith(".url"))
                {
                    string line;
                    bool   deleteItem = false;

                    StreamReader file = new StreamReader(shortcut);
                    while ((line = file.ReadLine()) != null)
                    {
                        if (line.Contains("IconFile="))
                        {
                            string shortPath = line.Replace("IconFile=", "");

                            if (!FileExistance.FileExists(shortPath))
                            {
                                EasyLogger.Info("Deleting broken shortcut: " + shortcut + ". The target icon file doesn't exits: " + shortPath);

                                try
                                {
                                    deleteItem = true;
                                    break;
                                }
                                catch (Exception ex)
                                {
#if DEBUG
                                    EasyLogger.Error(ex);
#endif
                                    break;
                                }
                            }
                        }
                    }

                    file.Close();

                    if (deleteItem)
                    {
                        File.Delete(shortcut);
                    }
                }
            }
            catch (Exception ex)
            {
                EasyLogger.Error(ex);
            }
        }
Пример #26
0
        internal static void Uninstall()
        {
            try
            {
                RegistryKey RegUninstallKey64 = Registry.LocalMachine.OpenSubKey(Resources.Uninstall64Bit, true);
                RegistryKey RegUninstallKey32 = Registry.LocalMachine.OpenSubKey(Resources.Uninstall32Bit, true);
                RegistryKey RegistrySoftware  = Registry.CurrentUser.OpenSubKey("SOFTWARE", true);
                RegistryKey UninstallInfo     = RegUninstallKey64;
                if (ArchitectureCheck.ProcessorIs64Bit())
                {
                    UninstallInfo = RegUninstallKey64;
                }
                if (!ArchitectureCheck.ProcessorIs64Bit())
                {
                    UninstallInfo = RegUninstallKey32;
                }
                StartProcess.StartInfo(@"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\RegAsm.exe", "-unregister " + "\"" + GetAssembly.AssemblyInformation("directory") + "\\xMenuTools.dll" + "\"", true, true, true);

                UninstallInfo.DeleteSubKeyTree("xMenuTools", false);
                RegistrySoftware.DeleteSubKey("xMenuTools\\Settings", false);
                RegistrySoftware.DeleteSubKey("xMenuTools", false);

                // Restart Explorer
                DialogResult dialog = SendMessage.MessageForm(Resources.UninstallComplete, Resources.xMenuTools, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dialog == DialogResult.Yes)
                {
                    foreach (Process proc in Process.GetProcessesByName("explorer"))
                    {
                        proc.Kill();

                        proc.WaitForExit();
                    }
                }

                try
                {
                    // Delete shortcut
                    StringBuilder allUserProfile = new StringBuilder(260);
                    NativeMethods.SHGetSpecialFolderPath(IntPtr.Zero, allUserProfile, NativeMethods.CSIDL_COMMON_STARTMENU, false);
                    string programs_path  = Path.Combine(allUserProfile.ToString(), "Programs");
                    string shortcutFolder = Path.Combine(programs_path, @"xMenuTools");
                    foreach (string file in Directory.GetFiles(shortcutFolder))
                    {
                        try
                        {
                            File.Delete(file);
                        }
                        catch
                        {
                            continue;
                        }
                    }
                    Directory.Delete(shortcutFolder, true);
                }
                catch (Exception ex)
                {
                    EasyLogger.Error(ex);
                }

                try
                {
                    File.Copy(GetAssembly.AssemblyInformation("directory") + @"\Deleter.exe", Path.GetTempPath() + "Deleter.exe", true);

                    using (Process p = new Process())
                    {
                        p.StartInfo.Arguments = "\"" + GetAssembly.AssemblyInformation("directory") + "\"";
                        p.StartInfo.FileName  = Path.GetTempPath() + @"\Deleter.exe";
                        p.Start();
                    }
                }
                catch (Exception ex)
                {
                    EasyLogger.Error(ex);
                }

                Environment.Exit(0);
            }
            catch (Exception ex)
            {
                MessageForm(ex.Message + Environment.NewLine + ex.StackTrace + Environment.NewLine + ex.Source + Environment.NewLine + ex.GetBaseException() + Environment.NewLine + ex.TargetSite, "xMenuTools", MessageBoxButtons.OK, MessageBoxIcon.Error);

                Environment.Exit(0);
            }
        }
Пример #27
0
        internal static void DeleteInvalid()
        {
            Directory.CreateDirectory("Backup");
            foreach (string file in Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "\\Backup\\"))
            {
                FileInfo fileInfo = new FileInfo(file);
                bool     DatabaseBackedUpStatus = fileInfo.LastWriteTime <= DateTime.Now.AddDays(-30);
                if (DatabaseBackedUpStatus)
                {
                    File.Delete(file);
                }
            }

            // User Path
            string NewUserPath = string.Empty;
            string OldUserPath = GetUserPath(@"Environment", "Path");

            string[] sArray = OldUserPath.Split(';');

            foreach (string path in sArray)
            {
                if (!Directory.Exists(path))
                {
                    EasyLogger.Info("Removing: " + path);
                }
                else
                {
                    if (NewUserPath == string.Empty)
                    {
                        NewUserPath += path;
                    }
                    else
                    {
                        NewUserPath += ";" + path;
                    }
                }
            }

            if (NewUserPath != OldUserPath)
            {
                RunCommand("reg", "export " + @"HKEY_CURRENT_USER\Environment" + "\"" + AppDomain.CurrentDomain.BaseDirectory + "\\Backup\\" + DateTime.Now.ToString("Mdhms") + "_SystemPath.reg" + "\"");

                EditUser(@"Environment", NewUserPath);

                EasyLogger.Info("Updated User Path: " + NewUserPath);
            }

            // System Path
            string NewSystemPath = string.Empty;
            string OldSystemPath = GetSystemPath(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", "Path");

            sArray = OldSystemPath.Split(';');

            foreach (string path in sArray)
            {
                if (!Directory.Exists(path))
                {
                    EasyLogger.Info("Removing: " + path);
                }
                else
                {
                    if (NewSystemPath == string.Empty)
                    {
                        NewSystemPath += path;
                    }
                    else
                    {
                        NewSystemPath += ";" + path;
                    }
                }
            }

            if (NewSystemPath != OldSystemPath)
            {
                RunCommand("reg", "export " + @"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" + "\"" + AppDomain.CurrentDomain.BaseDirectory + "\\Backup\\" + DateTime.Now.ToString("Mdhms") + "_SystemPath.reg" + "\"");

                EditSystem(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", NewSystemPath);

                EasyLogger.Info("Updated System Path: " + NewSystemPath);
            }
        }
Пример #28
0
 private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
 {
     EasyLogger.Error(e.Exception.Message + " Application.ThreadException");
 }
Пример #29
0
        public MainWindow()
        {
            InitializeComponent();

            EasyLogger.BackupLogs(EasyLogger.LogFile);
            EasyLogger.AddListener(EasyLogger.LogFile);

            ((MainWindow)Application.Current.MainWindow).mainWindow.StateChanged += MainWindow_StateChanged;

            HideThisWindow();

            Closing += MainWindow_Closing;

            if (Default.UpgradeRequired)
            {
                Default.Upgrade();

                Default.UpgradeRequired = false;

                Default.Save();

                Default.Reload();

                if (Default.FirstRun)
                {
                    Default.FirstRun = false;

                    SettingsWindow settingsWindow = new SettingsWindow();
                    settingsWindow.ShowDialog();

                    LocationBox locationBox = new LocationBox();
                    locationBox.ShowDialog();

                    MessageBox.Show("Right click on the Desktop App to change the weather location to your preferred location." + Environment.NewLine + Environment.NewLine + "You will need to find your lattitude and longitude in order for me to find your local weather.", "NWS Alerts", MessageBoxButton.OK, MessageBoxImage.Information);

                    Default.Save();

                    Default.Reload();
                }
            }

            NotifyTray.TrayIconCreate();

            if (Default.MuteToast)
            {
                NotifyTray.MuteMenuItem.Checked = true;
                ParseWeatherXML.MuteAlerts      = true;
            }

            NotificationActivatorBase.RegisterComType(typeof(NotificationActivator), OnActivated);

            NotificationHelper.RegisterComServer(typeof(NotificationActivator), Assembly.GetExecutingAssembly().Location);

            if (CheckForInternet.Connected())
            {
                ParseWeatherXML.NWSAlertsInfo();
            }
            else
            {
                ((MainWindow)Application.Current.MainWindow).AlertTextBody.Text = "You may not be connected to the internet...";
            }

            WeatherApp = new DesktopWeather();
            WeatherApp.Show();
        }
Пример #30
0
 private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
 {
     EasyLogger.Error(e.Exception.Message + Environment.NewLine + e.Exception.StackTrace + Environment.NewLine + e.Exception.InnerException + " Application.ThreadException");
 }