Exemplo n.º 1
0
Arquivo: BLIO.cs Projeto: mopioid/BLIO
    /// <summary>
    ///  Performs a getall command for a given class and property, and returns
    ///  a dictionary with the property values keyed by their objects.
    /// </summary>
    /// <param name="className">The name of the class to retreive each object for.</param>
    /// <param name="property">The property to retreive for each object.</param>
    /// <returns>
    ///  A dictionary in which objects of the class key their value for the
    ///  specified property. If the property contains a singular value, the
    ///  value is a string. If it contains an array, the value is an
    ///  IReadOnlyList&lt;string&gt;.
    /// </returns>
    ///
    public static IReadOnlyDictionary <BLObject, object> GetAll(string className, string property)
    {
        // Create the dictionary we will return.
        var results = new Dictionary <BLObject, object>();

        // Run the getall command. If this fails, return the empty results.
        var output = RunCommand("getall {0} {1}", className, property);

        if (output == null)
        {
            return(results);
        }

        // getall results should be in the following format:
        //     <index>) <subclass> <object>.<property> = <value>
        // Or, if the result's property is an array:
        //     <index>) <subclass> <object>.<property> =
        Regex objectPattern = new Regex($@"^\d+\) ([^ ]+) (.+)\.{Regex.Escape(property)} =( ?)(.*)$", RegexOptions.Compiled);

        // The current object and array we are working with.
        BLObject      objectKey  = null;
        List <object> arrayValue = null;

        // Iterate over each line of output.
        foreach (string line in output)
        {
            // The match for if we test a line for an object result.
            Match objectMatch;

            // If we are currently working with an array as an object's value,
            // we will test the current line for its membership.
            if (arrayValue != null)
            {
                // Check that the current line is of the format for a member of
                // an array value.
                var memberMatch = _MemberPattern.Value.Match(line);
                if (memberMatch.Success)
                {
                    object value = BLIO.Parse(memberMatch.Groups[1].Value);
                    // If it is, add the captured value to the array, and
                    // proceed on to the next line.
                    arrayValue.Add(value);
                    continue;
                }

                // If the line is not a member of the array, check whether it is
                // of the format denoting a new object.
                objectMatch = objectPattern.Match(line);
                if (objectMatch.Success)
                {
                    // If it is, this indicates the working array value was
                    // complete, so associate with the working object, and null
                    // it to indicate we're no longer working with an array.
                    results[objectKey] = arrayValue;
                    arrayValue         = null;
                }
            }
            else
            {
                // If we are not currently working with an array, check whether
                // the line is of the format denoting a new object. If not, skip
                // this line and proceed to the next one.
                objectMatch = objectPattern.Match(line);
                if (!objectMatch.Success)
                {
                    continue;
                }
            }

            // By now we have a match for an object declaration. Extract the
            // name and class name from it, and create a new object accordingly.
            string subclassName = objectMatch.Groups[1].Value;
            string objectName   = objectMatch.Groups[2].Value;
            objectKey = new BLObject(objectName, subclassName);

            // If the value capture group for the match did capture, associate
            // the object with the value.
            if (objectMatch.Groups[3].Value.Length == 1)
            {
                results[objectKey] = BLIO.Parse(objectMatch.Groups[4].Value);
            }

            // Otherwise, we are to expect an array as the value, so create a
            // new list for indicating such and for storing the results.
            else
            {
                arrayValue = new List <object>();
            }
        }

        // At the end of the results, if we had a working array value,
        // associate with the working object.
        if (arrayValue != null)
        {
            results[objectKey] = arrayValue;
        }

        return(results);
    }
Exemplo n.º 2
0
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (xClose)
            {
                xClose = false;
            }

            if (rem != null)
            {
                rem = BLReminder.GetReminderById(rem.Id);
            }

            if (rem == null)
            {
                goto close;
            }

            if (rem.HttpId != null)
            {
                //Conditional reminder
                HttpRequests req = BLLocalDatabase.HttpRequest.GetHttpRequestById(rem.Id);
                if (req.AfterPopup == "Stop")
                {
                    rem.Deleted = 1;
                    BLReminder.EditReminder(rem);
                    goto close;
                }
                else if (req.AfterPopup == "Repeat")
                {
                    goto close;
                }
                //else .... ?
            }

            if (rem.Id != -1 && rem.Deleted == 0) //Don't do stuff if the id is -1, invalid. the id is set to -1 when the user previews an reminder
            {
                if (BLReminder.GetReminderById(rem.Id) == null)
                {
                    //The reminder popped up, it existed, but when pressing OK it doesn't exist anymore (maybe the user deleted it or tempered with the .db file)
                    BLIO.Log("DETECTED NONEXISTING REMINDER WITH ID " + rem.Id + ", Attempted to press OK on a reminder that somehow doesn't exist");
                    goto close;
                }

                if (cbPostpone.Checked)
                {
                    BLIO.Log("Postponing reminder with id " + rem.Id);
                    if (BLFormLogic.GetTextboxMinutes(tbPostpone) <= 0)
                    {
                        return;
                    }

                    DateTime newReminderTime = new DateTime();

                    if (!string.IsNullOrWhiteSpace(tbPostpone.Text)) //postpone option is x minutes
                    {
                        newReminderTime  = DateTime.Now.AddMinutes(BLFormLogic.GetTextboxMinutes(tbPostpone));
                        rem.PostponeDate = newReminderTime.ToString();
                    }
                    else
                    {
                        rem.PostponeDate = null;
                        BLReminder.UpdateReminder(rem);
                    }



                    BLIO.Log("Postpone date assigned to reminder");
                    rem.Enabled = 1;
                    BLReminder.EditReminder(rem);
                    new Thread(() =>
                    {
                        //Log an entry to the database, for data!
                        try
                        {
                            BLOnlineDatabase.PostponeCount++;
                        }
                        catch (ArgumentException ex)
                        {
                            BLIO.Log("Exception at BLOnlineDatabase.PostponeCount++. -> " + ex.Message);
                            BLIO.WriteError(ex, ex.Message, true);
                        }
                    }).Start();
                    BLIO.Log("Reminder postponed!");
                }
                else
                {
                    rem.PostponeDate = null;
                    BLReminder.UpdateReminder(rem);
                }
            }

close:
            MUCReminders.Instance.UpdateCurrentPage(rem);
            BLIO.Log("Stopping media player & Closing popup");

            if (BLLocalDatabase.Setting.Settings.PopupType != "SoundOnly")
            {
                myPlayer.controls.stop();
            }

            this.Close();

            GC.Collect();
        }
Exemplo n.º 3
0
        public Form1()
        {
            BLIO.Log("===  Initializing RemindMe Version " + IOVariables.RemindMeVersion + "  ===");
            BLIO.Log("Construct Form");
            AppDomain.CurrentDomain.SetData("DataDirectory", IOVariables.databaseFile);
            BLIO.CreateSettings();
            BLIO.CreateDatabaseIfNotExist();
            InitializeComponent();
            //--

            instance = this;

            //User controls that will be loaded into the "main" panel
            ucReminders    = new UCReminders();
            ucImportExport = new UCImportExport();
            ucSound        = new UCSound();
            ucOverlay      = new UCSettings();
            ucResizePopup  = new UCResizePopup();
            ucSupport      = new UCSupport();
            ucDebug        = new UCDebugMode();
            ucTimer        = new UCTimer();

            //Turn them invisible
            ucImportExport.Visible = false;
            ucSound.Visible        = false;
            ucOverlay.Visible      = false;
            ucResizePopup.Visible  = false;
            ucSupport.Visible      = false;
            ucDebug.Visible        = false;
            ucTimer.Visible        = false;

            //Add all of them(invisible) to the panel
            pnlMain.Controls.Add(ucImportExport);
            pnlMain.Controls.Add(ucSound);
            pnlMain.Controls.Add(ucOverlay);
            pnlMain.Controls.Add(ucResizePopup);
            pnlMain.Controls.Add(ucSupport);
            pnlMain.Controls.Add(ucDebug);
            pnlMain.Controls.Add(ucTimer);

            pnlMain.Controls.Add(ucReminders);
            ucReminders.Visible = true;
            ucReminders.Initialize();

            m_GlobalHook        = Hook.GlobalEvents();
            m_GlobalHook.KeyUp += GlobalKeyPress;

            //Set the Renderer of the menustrip to our custom renderer, which sets the highlight and border collor to DimGray, which is the same
            //As the menu's themselves, which means you will not see any highlighting color or border. This renderer also makes the text of the selected
            //toolstrip items white.
            RemindMeTrayIconMenuStrip.Renderer = new MyToolStripMenuRenderer();


            UpdateInformation.Initialize();

            formLoadAsync();

            SystemEvents.PowerModeChanged += OnPowerChange;

            RemindMeIcon.Visible = true;
            BLIO.Log("Form constructed");
        }
Exemplo n.º 4
0
 private void UCReminders_DragEnter(object sender, DragEventArgs e)
 {
     BLIO.Log("Detected file dragging into RemindMe!");
     e.Effect = DragDropEffects.All;
 }
Exemplo n.º 5
0
        /// <summary>
        /// Transforms the part of the textbox string "API{url,data}" to the data from the API
        /// </summary>
        /// <param name="reminderText">The reminder text</param>
        /// <returns>The reminder text with the API{} replaced with the actual API value</returns>
        private async void TransformAPITextToValue(string color, string reminderText, float previewSize = 0)
        {
            float size = previewSize == 0 ? BLLocalDatabase.PopupDimension.GetPopupDimensions().FontNoteSize : previewSize;

            if (!reminderText.Contains("API{"))
            {
                return;
            }

            try
            {
                int retryCount = 0;
                htmlLblText.Text = "<p style=\"color: " + color + "; font-size: " + Math.Round(size * 1.28) + "px;\">Loading...</p>";
                new Thread(async() =>
                {
                    startMethod:



                    try
                    {
                        //if !hasinternetaccess Thread.Sleep(250); , 8 times, then error

                        if (!BLIO.HasInternetAccess())
                        {
                            retryCount++;

                            if (retryCount <= 8)
                            {
                                Thread.Sleep(250);
                                goto startMethod;
                            }
                            else
                            {
                                htmlLblText.Invoke((MethodInvoker)(() =>
                                {
                                    htmlLblText.Text = "An error occured." + rem.Note;
                                }));

                                return;
                            }
                        }

                        retryCount = 0;

                        //Interner access!

                        int startIndex = reminderText.IndexOf("API{");
                        int endIndex   = -1;

                        bool found = false;
                        int count  = 1;
                        while (!found)
                        {
                            if (reminderText[startIndex + count] == '}')
                            {
                                endIndex = startIndex + count;
                                found    = true;
                            }
                            else
                            {
                                count++;
                            }
                        }

                        //[url, dataToPick]
                        string[] data    = (reminderText.Substring(startIndex + 4, endIndex - (startIndex + 4))).Split(',');
                        JObject response = await BLIO.HttpRequest("GET", data[0]);

                        //This is the API value the user is requesting. Replace API{url,data} with this.
                        string value = response.SelectTokens(data[1]).Select(t => t.Value <string>()).ToList()[0];

                        StringBuilder stringBuilder = new StringBuilder(reminderText);
                        stringBuilder.Remove(startIndex, endIndex - (startIndex) + 1);
                        stringBuilder.Insert(startIndex, value);
                        reminderText = stringBuilder.ToString();

                        //TODO if response.status != 200   stringBuilder.Insert(startIndex, "Error occured");
                        //Bitcoin: $60,001
                        //Superfarm: Error
                        //Reef: $0,04
                        //

                        //Still contains another API{} ? again...
                        if (reminderText.Contains("API{"))
                        {
                            goto startMethod;
                        }

                        htmlLblText.Invoke((MethodInvoker)(() =>
                        {
                            htmlLblText.Text = "<p style=\"color: " + color + "; font-size: " + Math.Round(size * 1.28) + "px;\">" + reminderText + "</p>";
                        }));
                        //return reminderText;
                    }
                    catch (Exception ex)
                    {
                        retryCount++;

                        if (retryCount <= 8)
                        {
                            Thread.Sleep(250);
                            goto startMethod;
                        }
                        else
                        {
                            htmlLblText.Text = "An error occured. (" + ex.GetType().ToString() + ")\r\n" + rem.Note;
                        }
                    }
                }).Start();
            }
            catch (Exception ex)
            {
                BLIO.WriteError(ex, "TransformAPITextToValue() failed with " + ex.GetType().ToString());
                //return reminderText;
            }
        }
        public static KeyBinding[] ToKeyBindings(this List <KeybindInfo> kbis)
        {
            var bindingList = new List <KeyBinding>();

            foreach (var kbi in kbis)
            {
                try
                {
                    uint modifier = 0;
                    if (kbi.bUseCTRLModifier)
                    {
                        modifier |= 2;
                    }
                    if (kbi.bUseALTModifier)
                    {
                        modifier |= 1;
                    }
                    if (kbi.bUseSHIFTModifier)
                    {
                        modifier |= 4;
                    }
                    if (kbi.OwnerName == "textBoxHalveSpeed")
                    {
                        bindingList.Add(new KeyBinding((Keys)Enum.Parse(typeof(Keys), kbi.Key), modifier, App.HalveSpeed));
                    }
                    if (kbi.OwnerName == "textBoxDoubleSpeed")
                    {
                        bindingList.Add(new KeyBinding((Keys)Enum.Parse(typeof(Keys), kbi.Key), modifier, App.DoubleSpeed));
                    }
                    if (kbi.OwnerName == "textBoxResetSpeed")
                    {
                        bindingList.Add(new KeyBinding((Keys)Enum.Parse(typeof(Keys), kbi.Key), modifier, App.ResetSpeed));
                    }
                    if (kbi.OwnerName == "textBoxRestorePosition")
                    {
                        bindingList.Add(new KeyBinding((Keys)Enum.Parse(typeof(Keys), kbi.Key), modifier, App.RestorePosition));
                    }
                    if (kbi.OwnerName == "textBoxSavePosition")
                    {
                        bindingList.Add(new KeyBinding((Keys)Enum.Parse(typeof(Keys), kbi.Key), modifier, App.SavePosition));
                    }
                    if (kbi.OwnerName == "textBoxTogglePlayersOnly")
                    {
                        bindingList.Add(new KeyBinding((Keys)Enum.Parse(typeof(Keys), kbi.Key), modifier, App.TogglePlayersOnly));
                    }
                    if (kbi.OwnerName == "textBoxToggleHUD")
                    {
                        bindingList.Add(new KeyBinding((Keys)Enum.Parse(typeof(Keys), kbi.Key), modifier, () => BLIO.RunCommand("togglehud")));
                    }
                    if (kbi.OwnerName == "textBoxToggleDamageNumbers")
                    {
                        bindingList.Add(new KeyBinding((Keys)Enum.Parse(typeof(Keys), kbi.Key), modifier, App.ToggleDamageNumbers));
                    }
                    if (kbi.OwnerName == "textBoxToggleThirdperson")
                    {
                        bindingList.Add(new KeyBinding((Keys)Enum.Parse(typeof(Keys), kbi.Key), modifier, App.ToggleThirdPerson));
                    }
                    if (kbi.OwnerName == "textBoxDisconnect")
                    {
                        bindingList.Add(new KeyBinding((Keys)Enum.Parse(typeof(Keys), kbi.Key), modifier, () => BLIO.RunCommand("disconnect")));
                    }
                    if (kbi.OwnerName == "textBoxToggleHotkeys")
                    {
                        bindingList.Add(new KeyBinding((Keys)Enum.Parse(typeof(Keys), kbi.Key), modifier, MainWindow.mainWindow.ToggleHotkeys));
                    }
                    if (kbi.OwnerName == "textBoxTeleportForward")
                    {
                        bindingList.Add(new KeyBinding((Keys)Enum.Parse(typeof(Keys), kbi.Key), modifier, () => App.MoveForwardBackward(500)));
                    }
                    if (kbi.OwnerName == "textBoxTeleportLeft")
                    {
                        bindingList.Add(new KeyBinding((Keys)Enum.Parse(typeof(Keys), kbi.Key), modifier, () => App.MoveLeftRight(-500)));
                    }
                    if (kbi.OwnerName == "textBoxTeleportRight")
                    {
                        bindingList.Add(new KeyBinding((Keys)Enum.Parse(typeof(Keys), kbi.Key), modifier, () => App.MoveLeftRight(500)));
                    }
                    if (kbi.OwnerName == "textBoxTeleportBackward")
                    {
                        bindingList.Add(new KeyBinding((Keys)Enum.Parse(typeof(Keys), kbi.Key), modifier, () => App.MoveForwardBackward(-500)));
                    }
                    if (kbi.OwnerName == null)
                    {
                        bindingList.Add(new KeyBinding((Keys)Enum.Parse(typeof(Keys), kbi.Key), modifier, () => BLIO.RunCommand(kbi.Command)));
                    }
                }
                catch (ArgumentException) { }
            }
            return(bindingList.ToArray());
        }
Exemplo n.º 7
0
        //All uncaught exceptions will go here instead. We will replace the default windows popup with our own custom one and filter out what kind of exception is being thrown
        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            ErrorPrompt p = new ErrorPrompt(e.Exception); p.Show();

            if (e.Exception is SettingsException)
            {
                SettingsException ex = (SettingsException)e.Exception;
                BLIO.WriteError(e.Exception, ex.Message + "\r\n" + ex.Description);
            }
            else if (e.Exception is DirectoryNotFoundException)
            {
                DirectoryNotFoundException theException = (DirectoryNotFoundException)e.Exception;
                BLIO.WriteError(theException, "Folder not found.");
            }

            else if (e.Exception is UnauthorizedAccessException)
            {
                UnauthorizedAccessException theException = (UnauthorizedAccessException)e.Exception;
                BLIO.WriteError(e.Exception, "Unauthorized!");
            }

            //Here we just filter out some type of exceptions and give different messages, at the bottom is the super Exception, which can be anything.
            else if (e.Exception is FileNotFoundException)
            {
                FileNotFoundException theException = (FileNotFoundException)e.Exception; //needs in instance to call .FileName
                BLIO.WriteError(theException, "Could not find the file located at \"" + theException.FileName);
            }

            else if (e.Exception is System.Data.Entity.Core.EntityException)
            {
                BLIO.WriteError(e.Exception, "System.Data.Entity.Core.EntityException");
            }

            else if (e.Exception is ArgumentNullException)
            {
                BLIO.WriteError(e.Exception, "Null argument");
            }

            else if (e.Exception is NullReferenceException)
            {
                BLIO.WriteError(e.Exception, "Null reference");
            }

            else if (e.Exception is SQLiteException)
            {
                BLIO.WriteError(e.Exception, "SQLite Database exception");
            }

            else if (e.Exception is PathTooLongException)
            {
                BLIO.WriteError(e.Exception, "The path to the file is too long.");
            }

            else if (e.Exception is StackOverflowException)
            {
                BLIO.WriteError(e.Exception, "StackOverFlowException");
            }

            else if (e.Exception is OutOfMemoryException)
            {
                BLIO.WriteError(e.Exception, "Out of Memory");
            }
            else if (e.Exception is DbUpdateConcurrencyException)
            {
                BLIO.WriteError(e.Exception, "Database error.");
            }

            else if (e.Exception is Exception)
            {
                BLIO.WriteError(e.Exception, "Unknown exception in main.");
            }
        }
Exemplo n.º 8
0
        private void Popup2_Load(object sender, EventArgs e)
        {
            try
            {
                BLIO.Log("Popup_load");
                AdvancedReminderProperties          avrProps = BLLocalDatabase.AVRProperty.GetAVRProperties(rem.Id);
                List <AdvancedReminderFilesFolders> avrFF    = BLLocalDatabase.AVRProperty.GetAVRFilesFolders(rem.Id);
                if (avrProps != null) //Not null? this reminder has advanced properties.
                {
                    BLIO.Log("Reminder " + rem.Id + " has advanced reminder properties!");
                    this.Visible = avrProps.ShowReminder == 1;

                    if (!string.IsNullOrWhiteSpace(avrProps.BatchScript))
                    {
                        if (!this.Visible)
                        {
                            RemindMeMessageFormManager.MakeMessagePopup("Activating script of Reminder:\r\n \"" + rem.Name + "\"", 3);
                        }

                        BLIO.ExecuteBatch(avrProps.BatchScript);
                    }
                }
                else
                {
                    BLIO.Log("Reminder " + rem.Id + " does not have advanced reminder properties");
                }

                if (avrFF != null && avrFF.Count > 0)
                {
                    //Go through each action, for example c:\test , delete. c:\sometest\testFile.txt , open
                    foreach (AdvancedReminderFilesFolders avr in avrFF)
                    {
                        if (avr.Action.ToString() == "Open")
                        {
                            BLIO.Log("Executing advanced reminder action \"Open\"");

                            if (File.Exists(avr.Path) || Directory.Exists(avr.Path))
                            {
                                System.Diagnostics.Process.Start(avr.Path);
                            }
                        }
                        else if (avr.Action.ToString() == "Delete")
                        {
                            BLIO.Log("Executing advanced reminder action \"Delete\"");

                            FileAttributes attr = File.GetAttributes(avr.Path);
                            //Check if it's a file or a directory
                            if (File.Exists(avr.Path))
                            {
                                File.Delete(avr.Path);
                            }
                            else if (Directory.Exists(avr.Path))
                            {
                                Directory.Delete(avr.Path, true);
                            }
                        }
                    }
                }

                if (this.Visible)
                {
                    tmrFadeIn.Start();
                }
                else
                {
                    btnOk_Click(sender, e);
                    return;
                }

                BLIO.Log("Attempting to parse date...");
                DateTime date = Convert.ToDateTime(rem.Date.Split(',')[0]);
                BLIO.Log("Date succesfully converted (" + date + ")");

                lblSmallDate.Text = date.ToShortDateString() + " " + date.ToShortTimeString();
                lblRepeat.Text    = BLReminder.GetRepeatTypeText(rem);

                if (!string.IsNullOrWhiteSpace(rem.PostponeDate))
                {
                    BLIO.Log("Reminder has a postpone date.");

                    pbDate.BackgroundImage = Properties.Resources.RemindMeZzz;
                    lblSmallDate.Text      = Convert.ToDateTime(rem.PostponeDate) + " (Postponed)";
                }

                //If some country has a longer date string, move the repeat icon/text more to the right so it doesnt overlap
                while (lblSmallDate.Bounds.IntersectsWith(pbRepeat.Bounds))
                {
                    pbRepeat.Location  = new Point(pbRepeat.Location.X + 5, pbRepeat.Location.Y);
                    lblRepeat.Location = new Point(lblRepeat.Location.X + 5, lblRepeat.Location.Y);
                }

                //Play the sound
                if (rem.SoundFilePath != null && rem.SoundFilePath != "")
                {
                    if (System.IO.File.Exists(rem.SoundFilePath))
                    {
                        BLIO.Log("SoundFilePath not null / empty and exists on the hard drive!");
                        myPlayer.URL = rem.SoundFilePath;
                        myPlayer.controls.play();
                        BLIO.Log("Playing sound");
                    }
                    else
                    {
                        BLIO.Log("SoundFilePath not null / empty but doesn't exist on the hard drive!");
                        RemindMeBox.Show("Could not play " + Path.GetFileNameWithoutExtension(rem.SoundFilePath) + " located at \"" + rem.SoundFilePath + "\" \r\nDid you move,rename or delete the file ?\r\nThe sound effect has been removed from this reminder. If you wish to re-add it, select it from the drop-down list.", RemindMeBoxReason.OK);
                        //make sure its removed from the reminder
                        rem.SoundFilePath = "";
                    }
                }

                FlashWindowHelper.Start(this);
                //this.MaximumSize = this.Size;

                if (BLLocalDatabase.Setting.IsAlwaysOnTop())
                {
                    this.TopMost  = true; //Popup will be always on top. no matter what you are doing, playing a game, watching a video, you will ALWAYS see the popup.
                    this.TopLevel = true;
                }
                else
                {
                    this.TopMost     = false;
                    this.WindowState = FormWindowState.Minimized;
                }


                lblTitle.Text = rem.Name;

                if (rem.Note != null)
                {
                    lblNoteText.Text = rem.Note.Replace("\\n", Environment.NewLine);
                }

                if (rem.Note == "")
                {
                    lblNoteText.Text = "( No text set )";
                }

                lblNoteText.Text = Environment.NewLine + lblNoteText.Text;



                if (rem.Date == null)
                {
                    rem.Date = DateTime.Now.ToString();
                }
            }
            catch (Exception ex)
            {
                ReminderException remEx = new ReminderException(BLReminder.ToString(rem), rem);
                remEx.StackTrace = ex.StackTrace; //Copy the stacktrace

                BLIO.WriteError(remEx, "Error loading reminder popup");
                BLIO.Log("Popup_load FAILED. Exception -> " + ex.Message);
            }
        }
Exemplo n.º 9
0
 private void tmrMusic_Tick(object sender, EventArgs e)
 {
     btnPreview.Iconimage = imgPlay;
     tmrMusic.Stop();
     BLIO.Log("Sound file playing ended");
 }
Exemplo n.º 10
0
 private void bunifuFlatButton2_Click(object sender, EventArgs e)
 {
     BLIO.Log("(MUCSupport)bunifuFlatButton2_Click [btnSendMessage]");
     //pnlSendMessages.Location = new Point(0, 0);
     //pnlMessageOverview.Location = new Point(667, 0);
 }
Exemplo n.º 11
0
        public void UpdateRemindMe() //This is called within a Thread
        {
            try
            {
                //Don't do anything without internet
                if (hasUpdated || !BLIO.HasInternetAccess())
                {
                    return;
                }

                if (GetGithubVersion() > new Version(IOVariables.RemindMeVersion))
                {
                    BLIO.Log("New version of RemindMe on Github! Starting UpdateRemindMe()...");
                    DateTime dateNow = DateTime.UtcNow;
                    //Download the updated files
                    DownloadFile("https://github.com/Stefangansevles/RemindMe/raw/master/Update/UpdateFiles.zip", IOVariables.rootFolder + "UpdateFiles.zip");

                    ZipFile zip = new ZipFile(IOVariables.rootFolder + "UpdateFiles.zip");

                    if (zip == null || !ZipFile.IsZipFile(IOVariables.rootFolder + "UpdateFiles.zip"))
                    {
                        BLIO.Log("UpdateRemindMe ABORTED. Zip is null or invalid.");
                        return;
                    }

                    try
                    {
                        BLIO.Log("UpdateFiles.zip contains files for a new RemindMe version!");

                        //First, move the running files into an /old/ directory
                        MoveOldFiles();

                        //Now, move those updates files into the application directory, so that when the program starts the next time, RemindMe is updated! :)
                        zip.ExtractProgress += Zip_ExtractProgress;
                        BLIO.Log("Extracting zip...");
                        zip.ExtractAll(IOVariables.applicationFilesFolder, ExtractExistingFileAction.OverwriteSilently);

                        while (!extractCompleted)
                        {
                        }                             //Busy waiting, but we're in a thread anyway
                        BLIO.Log("UpdateRemindMe() took: " + (long)(DateTime.UtcNow - dateNow).TotalMilliseconds + " ms");

                        BLIO.Log("Attempting to remove UpdateFiles.zip...");
                        try { File.Delete(IOVariables.rootFolder + "UpdateFiles.zip"); } catch { }

                        if (restartRemindMe && !Form1.Instance.Visible)
                        {
                            BLIO.Log("Restarting RemindMe...");
                            Application.Restart();
                        }
                        else
                        {
                            BLIO.Log("Installation complete! restartRemindMe = " + restartRemindMe);
                            Form1.Instance.restartRemindMeUpdateToolStripMenuItem.Visible = true; //Give a "Restart" option on the RemindMe Icon
                        }

                        hasUpdated = true;
                    }
                    catch (Exception ex) //do rollback
                    {
                        BLIO.Log("Something went wrong during extraction in UpdateRemindMe(). Exception: " + ex.GetType().ToString() + "\r\nDoing rollback...");

                        //Roll the files in /old/ back to the original folder
                        foreach (string fl in Directory.GetFiles(IOVariables.applicationFilesFolder + "\\old"))
                        {
                            if (File.Exists(IOVariables.applicationFilesFolder + Path.GetFileName(fl)))
                            {
                                BLIO.Log(" - Deleting file: " + Path.GetFileName(fl));
                                File.Delete(IOVariables.applicationFilesFolder + Path.GetFileName(fl));
                            }

                            BLIO.Log(" - Restoring /old file: " + Path.GetFileName(fl));
                            File.Move(fl, IOVariables.applicationFilesFolder + Path.GetFileName(fl));
                        }
                        //Delete the /old
                        BLIO.Log("Deleting directory /old");
                        Directory.Delete(IOVariables.applicationFilesFolder + "\\old");
                    }
                }
                else if (BLIO.LastLogMessage != null && !BLIO.LastLogMessage.Contains("Updating user"))
                {
                    BLIO.Log("No new version of RemindMe on Github.");
                }
            }
            catch (Exception ex)
            {
                BLIO.Log("First part of UpdateRemindMe failed. Exception: " + ex.GetType().ToString());
            }
        }
Exemplo n.º 12
0
 private void btnBack_Click(object sender, EventArgs e)
 {
     BLIO.Log("(MUCSupport)btnBack_Click");
     //pnlMessageOverview.Location = new Point(0, 0);
     //pnlSendMessages.Location = new Point(667, 0);
 }
Exemplo n.º 13
0
 private void btnCheckUpdate_Click(object sender, EventArgs e)
 {
     BLIO.Log("btnCheckUpdate_Click");
     Form1.Instance.CheckForUpdates();
 }
Exemplo n.º 14
0
        private void TimerPopup_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                BLIO.Log("TimerPopup enter pressed");
                timerMinutes         = 0;
                lblErrorText.Visible = false;



                try
                {
                    //the "m" part of the input is unnecesary. If the input is 2h15m,
                    //then 2h15 would produce the same output. 15m would also be the same as 15, since there is no 'h' present.
                    tbTime.Text = tbTime.Text.ToLower().Replace("m", "");

                    if (tbTime.Text.ToLower().Contains('h'))
                    {
                        BLIO.Log("timer popup contains 'h'. Checking what's before it");

                        //Get the index number of the 'h' in the text
                        int index = tbTime.Text.ToLower().IndexOf('h');

                        //Now get all the text before it(should be a numer) and multiply by 60 because the user input hours
                        BLIO.Log("Parsing hours....");
                        timerMinutes += Convert.ToInt32(tbTime.Text.Substring(0, index)) * 60;

                        //Now get the number after the 'h' , which should be minutes, and add it to timerMinutes
                        //But, first check if there is actually something after the 'h'

                        if (tbTime.Text.Length > index + 1)//+1 because .Length starts from 1, index starts from 0
                        {
                            BLIO.Log("Parsing minutes....");
                            timerMinutes += Convert.ToInt32(tbTime.Text.Substring(index + 1, tbTime.Text.Length - (index + 1)));
                        }
                    }
                    else
                    {
                        timerMinutes = Convert.ToInt32(tbTime.Text);
                    }

                    if (timerMinutes <= 0)
                    {
                        lblErrorText.Visible = true;
                        lblErrorText.Text    = "Invalid input time";
                        return;
                    }
                }
                catch
                {
                    lblErrorText.Visible = true;
                    lblErrorText.Text    = "Invalid input";
                    return;
                }



                BLIO.Log("Success. (" + timerMinutes + "minutes ) Creating timespan.");

                TimeSpan time = TimeSpan.FromMinutes(timerMinutes);

                UCTimer ucTimer = Form1.Instance.ucTimer;

                BLIO.Log("Setting values of (UCTimer) numericupdowns");

                ucTimer.numSeconds.Value = Math.Ceiling((decimal)time.Seconds / 60);
                ucTimer.numMinutes.Value = Math.Ceiling((decimal)time.Minutes % 60);
                ucTimer.numHours.Value   = Math.Ceiling((decimal)time.Hours);
                ucTimer.timerNote        = tbNote.Text;

                BLIO.Log("Values set");

                ucTimer.AddTimer(timerMinutes * 60, tbNote.Text);

                //ucTimer.ToggleTimer();

                BLIO.Log("Timer started");
                this.Close();
            }
        }
Exemplo n.º 15
0
        // Perform our own initilization when the window initilizes.
        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);

            F7Binding = new KeyBinding(Key.F7, ToggleHotkeys);

            var controlUpBinding    = new KeyBinding(Key.Up, Modifier.Control, () => App.MoveForwardBackward(500));
            var controlDownBinding  = new KeyBinding(Key.Down, Modifier.Control, () => App.MoveForwardBackward(-500));
            var controlLeftBinding  = new KeyBinding(Key.Left, Modifier.Control, () => App.MoveLeftRight(-500));
            var controlRightBinding = new KeyBinding(Key.Right, Modifier.Control, () => App.MoveLeftRight(500));

            var controlEndBinding = new KeyBinding(Key.End, Modifier.Control, () => BLIO.RunCommand("disconnect"));

            SymbolBindings = new KeyBinding[]
            {
                new KeyBinding(Key.Equals, App.ToggleThirdPerson),
                new KeyBinding(Key.LeftBracket, App.HalveSpeed),
                new KeyBinding(Key.RightBracket, App.DoubleSpeed),
                new KeyBinding(Key.Backslash, App.ResetSpeed),
                new KeyBinding(Key.Comma, App.RestorePosition),
                new KeyBinding(Key.Period, App.SavePosition),
                new KeyBinding(Key.Semicolon, () => BLIO.RunCommand("togglehud")),
                new KeyBinding(Key.Quote, App.ToggleDamageNumbers),
                new KeyBinding(Key.Slash, App.TogglePlayersOnly),
                controlUpBinding,
                controlDownBinding,
                controlLeftBinding,
                controlRightBinding,
                controlEndBinding,
            };

            NumpadBindings = new KeyBinding[]
            {
                new KeyBinding(Key.NumOne, App.HalveSpeed),
                new KeyBinding(Key.NumTwo, App.DoubleSpeed),
                new KeyBinding(Key.NumThree, App.ResetSpeed),
                new KeyBinding(Key.NumFour, App.RestorePosition),
                new KeyBinding(Key.NumFive, App.SavePosition),
                new KeyBinding(Key.NumSix, App.TogglePlayersOnly),
                new KeyBinding(Key.NumSeven, () => BLIO.RunCommand("togglehud")),
                new KeyBinding(Key.NumEight, App.ToggleDamageNumbers),
                new KeyBinding(Key.NumNine, App.ToggleThirdPerson),
                controlUpBinding,
                controlDownBinding,
                controlLeftBinding,
                controlRightBinding,
                controlEndBinding,
            };

            if (Properties.Settings.Default.NumpadBindings)
            {
                NumpadBindingsMenuItem.Checked = true;
                // Set up the dictionary entires for our keybindings and their callbacks.
                KeyBindings = NumpadBindings;
            }
            else
            {
                SymbolBindingsMenuItem.Checked = true;
                // Set up the dictionary entires for our keybindings and their callbacks.
                KeyBindings = SymbolBindings;
            }

            // Set up the handle variables for binding hotkeys, and set up our
            // callback method as the hook for receiving hotkey events.
            Handle = new WindowInteropHelper(this).Handle;
            source = HwndSource.FromHwnd(Handle);
            source.AddHook(OnHotkeyPressed);

            // Create the delegate to handle notifications of foreground window
            // changes, and register it with the system.
            ForegroundWindowDelegate = (_0, _1, windowHandle, _3, _4, _5, _6) => HandleForegroundWindow(windowHandle);
            SetWinEventHook(0x0003, 0x0003, IntPtr.Zero, ForegroundWindowDelegate, 0, 0, 0);

            // Set up bindings if the foreground window is already Borderlands.
            HandleForegroundWindow(GetForegroundWindow());
        }
Exemplo n.º 16
0
        private void TimerButton_Click(object sender, EventArgs e)
        {
            //Right click delete
            if (e.GetType().Equals(typeof(MouseEventArgs)))
            {
                MouseEventArgs mouse = (MouseEventArgs)e;
                if (mouse.Button == MouseButtons.Right)
                {
                    TimerMenuStrip.Show(Cursor.Position);
                }
            }

            //Get selected TimerItem
            BunifuFlatButton clickedButton = (BunifuFlatButton)sender;

            BLIO.Log("TimerButton " + clickedButton.Text + " clicked!");
            //Remove all the text apart from the id and store it


            int id = GetTimerButtonId(clickedButton);


            foreach (TimerItem itm in timers)
            {
                if (itm.ID == id)
                {
                    lblTimerTitle.Text = "Timer: " + itm.TimerText;

                    currentTimerItem      = itm;
                    lblTimerTitle.Visible = true;


                    if (currentTimerItem.Running)
                    {
                        tmrCountdown.Start();
                    }
                    else
                    {
                        tmrCountdown.Stop();
                    }


                    BLIO.Log("Setting values of (UCTimer) numericupdowns");
                    TimeSpan time = TimeSpan.FromSeconds((double)currentTimerItem.SecondsRemaining);
                    numSeconds.Value = time.Seconds;
                    numMinutes.Value = time.Minutes;
                    numHours.Value   = time.Hours;
                }
            }

            //Show play or pause depending on if the selected timer is running or not
            if (currentTimerItem.Running)
            {
                btnPauseResumeTimer.Iconimage = Properties.Resources.pause_2x1;
            }
            else
            {
                btnPauseResumeTimer.Iconimage = Properties.Resources.Play;
            }

            EnableButton(clickedButton);
        }
        private void RemindMeImporter_Load(object sender, EventArgs e)
        {
            BLIO.Log("RemindmeImporter_load");
            this.MaximumSize = this.Size;


            if (!HasFileAccess(this.remindmeFile)) //Do not attempt to launch the importer form if we can't open the file
            {
                BLIO.Log("Error opening .remindme file, no rights");
                MaterialRemindMeBox.Show("Can not open this .remindme file from " + Path.GetDirectoryName(this.remindmeFile) + ". Insufficient rights.", RemindMeBoxReason.OK);
                this.Close();
            }
            else
            {
                try
                {
                    BLIO.Log("Deserializing reminders.....");
                    List <object> deSerializedReminders = BLReminder.DeserializeRemindersFromFile(remindmeFile);
                    BLIO.Log(deSerializedReminders.Count - 1 + " reminders deserialized!");
                    this.Text += " (" + (deSerializedReminders.Count - 1) + " Reminders)"; //-1 because of country code
                    foreach (object rem in deSerializedReminders)
                    {
                        if (rem.GetType() == typeof(Reminder))
                        {
                            Reminder reminder = (Reminder)rem;
                            BLIO.Log(reminder.Name + " Loaded into RemindMeImporter from the .remindme file.");
                            remindersFromRemindMeFile.Add((Reminder)rem);
                        }
                        else
                        {
                            BLIO.Log("Language code" + languageCode + " read from the .remindme file!");
                            languageCode = rem.ToString(); //The language code stored in the .remindme file, "en-Us" for example
                        }
                    }

                    if (languageCode != "") //Don't need to do this when exporting.
                    {
                        BLIO.Log("Going through the reminder list once more....");
                        foreach (object rem in remindersFromRemindMeFile)
                        {
                            if (rem.GetType() == typeof(Reminder))
                            {
                                Reminder remm = (Reminder)rem;
                                //Fix the date if the .remindme file has a different time format than the current system
                                BLIO.Log("(" + remm.Name + ") Fixing the date to match the language code " + languageCode);
                                remm.Date = BLDateTime.ConvertDateTimeStringToCurrentCulture(remm.Date, languageCode);
                            }
                        }
                    }

                    if (remindersFromRemindMeFile != null)
                    {
                        BLIO.Log("Adding the reminders from the .remindme file to the listview....");
                        BLFormLogic.AddRemindersToListview(lvReminders, remindersFromRemindMeFile, true);
                        BLIO.Log("Done!");
                    }
                    else
                    {
                        BLIO.Log("Failed to load reminders.");
                        this.Text = "Failed to load reminders.";
                    }
                }
                catch (Exception ex)
                {
                    MaterialRemindMeBox.Show("Something has gone wrong loading reminders from this .remindme file.\r\nThe file might be corrupt", RemindMeBoxReason.OK);
                    BLIO.Log("Error loading reminders from .remindme file written to error log");
                    BLIO.WriteError(ex, "Error loading reminders from .remindme file");
                    Application.Exit();
                }
            }
            BLIO.Log("RemindmeImporter loaded !");
        }
Exemplo n.º 18
0
 private void MUCDebugMode_VisibleChanged(object sender, EventArgs e)
 {
     BLIO.Log("Showing debug mode");
 }
Exemplo n.º 19
0
 private void btnCancel_Click(object sender, EventArgs e)
 {
     BLIO.Log("Cancel button pressed (UCImportExport)");
     ToggleButton(null);
     lvReminders.Items.Clear();
 }
Exemplo n.º 20
0
 private void btnCheckUpdate_Click(object sender, EventArgs e)
 {
     BLIO.Log("btnCheckUpdate_Click");
     new RemindMeUpdater().UpdateRemindMe();
 }
Exemplo n.º 21
0
        private void tmrCheckReminder_Tick(object sender, EventArgs e)
        {
            if (BLReminder.GetReminders().Where(r => r.Enabled == 1).ToList().Count <= 0)
            {
                tmrCheckReminder.Stop(); //No existing reminders? no enabled reminders? stop timer.
                BLIO.Log("Stopping the reminder checking timer, because there are no more (enabled) reminders");
                return;
            }

            //If a day has passed since the start of RemindMe, we may want to refresh the listview.
            //There might be reminders happening on this day, if so, we show the time of the reminder, instead of the day
            if (dayOfStartRemindMe < DateTime.Now.Day)
            {
                BLIO.Log("Dawn of a new day -24 hours remaining- ");
                UpdateCurrentPage();
                dayOfStartRemindMe = DateTime.Now.Day;
                MessageFormManager.MakeTodaysRemindersPopup();
            }


            //We will check for reminders here every 5 seconds.
            foreach (Reminder rem in BLReminder.GetReminders())
            {
                //Create the popup. Do the other stuff afterwards.
                if ((rem.PostponeDate != null && Convert.ToDateTime(rem.PostponeDate) <= DateTime.Now && rem.Enabled == 1) || (Convert.ToDateTime(rem.Date.Split(',')[0]) <= DateTime.Now && rem.PostponeDate == null && rem.Enabled == 1))
                {
                    //temporarily disable it. When the user postpones the reminder, it will be re-enabled.
                    rem.Enabled = 0;
                    BLReminder.EditReminder(rem);
                    MakeReminderPopup(rem);
                    UpdateCurrentPage();
                }
                else
                {
                    // -- In this part we will create popups at the users right bottom corner of the screen saying x reminder is happening in 1 hour or x minutes -- \\
                    if (BLSettings.IsHourBeforeNotificationEnabled() && rem.Enabled == 1)
                    {
                        DateTime theDateToCheckOn; //Like this we dont need an if ánd an else with the same code
                        if (rem.PostponeDate != null)
                        {
                            theDateToCheckOn = Convert.ToDateTime(rem.PostponeDate);
                        }
                        else
                        {
                            theDateToCheckOn = Convert.ToDateTime(rem.Date.Split(',')[0]);
                        }


                        //The timespan between the date and now.
                        TimeSpan timeSpan = Convert.ToDateTime(theDateToCheckOn) - DateTime.Now;
                        if (timeSpan.TotalMinutes >= 59.50 && timeSpan.TotalMinutes <= 60)
                        {
                            remindersToHappenInAnHour.Add(rem);
                        }
                    }
                }
            }


            string message = "You have " + remindersToHappenInAnHour.Count + " reminders set in 60 minutes:\r\n";
            int    count   = 1;

            foreach (Reminder rem in remindersToHappenInAnHour)
            {
                if (remindersToHappenInAnHour.Count > 1)
                {
                    message += count + ") " + rem.Name + Environment.NewLine;
                }
                else
                {
                    message = rem.Name + " in 60 minutes!";
                }

                count++;
            }

            if (remindersToHappenInAnHour.Count > 1) //cut off the last \n
            {
                message = message.Remove(message.Length - 2, 2);

                if (!popupMessages.Contains(message)) //Don't create this popup if we have already created it once before
                {
                    MessageFormManager.MakeMessagePopup(message, 8);
                }

                popupMessages.Add(message);
            }
            else if (remindersToHappenInAnHour.Count > 0)
            {
                if (!popupMessages.Contains(message)) //Don't create this popup if we have already created it once before
                {
                    MessageFormManager.MakeMessagePopup(message, 8, remindersToHappenInAnHour[0]);
                }

                popupMessages.Add(message);
            }

            remindersToHappenInAnHour.Clear();
        }
Exemplo n.º 22
0
 private void btnRequery_Click(object sender, EventArgs e)
 {
     //Copy the contents of the textbox to the system clipboard
     Clipboard.SetText(tbSystemLog.Text);
     BLIO.Log("Copied system log to clipboard");
 }
Exemplo n.º 23
0
        public void Initialize()
        {
            BLIO.Log("Loading reminders from database");
            //Give initial value to newReminderUc
            newReminderUc           = new UCNewReminder(this);
            newReminderUc.Visible   = false;
            newReminderUc.saveState = false;
            this.Parent.Controls.Add(newReminderUc);


            Form1.Instance.ucNewReminder = newReminderUc;
            //BLFormLogic.AddRemindersToListview(lvReminders, BLReminder.GetReminders().Where(r => r.Hide == 0).ToList()); //Get all "active" reminders);

            BLIO.Log("Starting the reminder timer");
            tmrCheckReminder.Start();

            pnlReminders.Visible = true;

            pnlReminders.DragDrop  += UCReminders_DragDrop;
            pnlReminders.DragEnter += UCReminders_DragEnter;


            int counter = 0;

            foreach (Reminder rem in BLReminder.GetReminders().Where(r => r.Hide == 0).OrderBy(r => Convert.ToDateTime(r.Date.Split(',')[0])).Where(r => r.Enabled == 1).Where(r => r.Hide == 0))
            {
                if (pnlReminders.Controls.Count >= 7)
                {
                    break;                                   //Only 7 reminders on 1 page
                }
                pnlReminders.Controls.Add(new UCReminderItem(rem));

                if (counter > 0)
                {
                    pnlReminders.Controls[counter].Location = new Point(0, pnlReminders.Controls[counter - 1].Location.Y + pnlReminders.Controls[counter - 1].Size.Height);
                }

                counter++;
            }

            foreach (Reminder rem in BLReminder.GetReminders().Where(r => r.Hide == 0).OrderBy(r => Convert.ToDateTime(r.Date.Split(',')[0])).Where(r => r.Enabled == 0).Where(r => r.Hide == 0))
            {
                if (pnlReminders.Controls.Count >= 7)
                {
                    break;
                }

                pnlReminders.Controls.Add(new UCReminderItem(rem));

                if (counter > 0)
                {
                    pnlReminders.Controls[counter].Location = new Point(0, pnlReminders.Controls[counter - 1].Location.Y + pnlReminders.Controls[counter - 1].Size.Height);
                }

                counter++;
            }

            if (BLReminder.GetReminders().Count < 7) //Less than 7 reminders, let's fit in some invisible UCReminderItem 's
            {
                for (int i = BLReminder.GetReminders().Count; i < 7; i++)
                {
                    pnlReminders.Controls.Add(new UCReminderItem(null));

                    if (counter > 0)
                    {
                        pnlReminders.Controls[counter].Location = new Point(0, pnlReminders.Controls[counter - 1].Location.Y + pnlReminders.Controls[counter - 1].Size.Height);
                    }

                    counter++;
                }
            }
            int test = pnlReminders.Controls.Count;

            if (BLReminder.GetReminders().Where(r => r.Hide == 0).ToList().Count <= 7)
            {
                Form1.Instance.UpdatePageNumber(-1); //Tell form1 that there are not more than 1 pages
            }
            else
            {
                btnNextPage.Iconimage = Properties.Resources.NextWhite;
                Form1.Instance.UpdatePageNumber(pageNumber);
            }
        }
Exemplo n.º 24
0
 private void btnAppdataFolder_Click(object sender, EventArgs e)
 {
     BLIO.Log("btnAppdataFolder_Click");
     Process.Start(Path.GetDirectoryName(IOVariables.errorLog));
 }
Exemplo n.º 25
0
        private void Popup_Load(object sender, EventArgs e)
        {
            try
            {
                BLIO.Log("Popup_load");

                if (BLLocalDatabase.Setting.Settings.PopupType == "SoundOnly")
                {
                    //Dont initialize, just play sound
                    PlayReminderSound();

                    if (rem.Id != -1) //Dont stop logic when the user is previewing an reminder
                    {
                        btnOk_Click(sender, e);
                        return;
                    }
                }

                string reminderText = rem.Note != null?rem.Note.Replace("\n", "<br>") : "( No text set )";

                //White font if dark theme, Black text if light theme
                string color = MaterialSkin.MaterialSkinManager.Instance.Theme == MaterialSkin.MaterialSkinManager.Themes.DARK ? "#e6e6e6" : "#323232";

                if (rem.Note.Contains("API{"))
                {
                    TransformAPITextToValue(color, reminderText);
                }
                else
                {
                    htmlLblText.Text = GetPopupHTMLText(color, reminderText);
                }


                AdvancedReminderProperties          avrProps = BLLocalDatabase.AVRProperty.GetAVRProperties(rem.Id);
                List <AdvancedReminderFilesFolders> avrFF    = BLLocalDatabase.AVRProperty.GetAVRFilesFolders(rem.Id);
                if (avrProps != null) //Not null? this reminder has advanced properties.
                {
                    BLIO.Log("Reminder " + rem.Id + " has advanced reminder properties!");
                    this.Visible = avrProps.ShowReminder == 1;

                    if (!string.IsNullOrWhiteSpace(avrProps.BatchScript))
                    {
                        //if (!this.Visible)
                        MaterialMessageFormManager.MakeMessagePopup("Activating script of Reminder:\r\n \"" + rem.Name + "\"", 3);

                        BLIO.ExecuteBatch(avrProps.BatchScript);
                    }
                }
                else
                {
                    BLIO.Log("Reminder " + rem.Id + " does not have advanced reminder properties");
                }

                if (avrFF != null && avrFF.Count > 0)
                {
                    //Go through each action, for example c:\test , delete. c:\sometest\testFile.txt , open
                    foreach (AdvancedReminderFilesFolders avr in avrFF)
                    {
                        if (avr.Action.ToString() == "Open")
                        {
                            BLIO.Log("Executing advanced reminder action \"Open\"");

                            if (File.Exists(avr.Path) || Directory.Exists(avr.Path))
                            {
                                System.Diagnostics.Process.Start(avr.Path);
                            }
                        }
                        else if (avr.Action.ToString() == "Delete")
                        {
                            BLIO.Log("Executing advanced reminder action \"Delete\"");

                            FileAttributes attr = File.GetAttributes(avr.Path);
                            //Check if it's a file or a directory
                            if (File.Exists(avr.Path))
                            {
                                File.Delete(avr.Path);
                            }
                            else if (Directory.Exists(avr.Path))
                            {
                                Directory.Delete(avr.Path, true);
                            }
                        }
                    }
                }

                if (this.Visible)
                {
                    tmrFadeIn.Start();
                }
                else
                {
                    btnOk_Click(sender, e);
                    return;
                }

                if (rem.HttpId == null)
                {
                    BLIO.Log("Attempting to parse date...");
                    DateTime date = Convert.ToDateTime(rem.Date.Split(',')[0]);
                    BLIO.Log("Date succesfully converted (" + date + ")");

                    lblSmallDate.Text = date.ToShortDateString() + " " + date.ToShortTimeString();
                }
                else
                {
                    lblSmallDate.Text = "Conditional";
                }


                lblRepeat.Text = BLReminder.GetRepeatTypeText(rem);

                if (!string.IsNullOrWhiteSpace(rem.PostponeDate))
                {
                    BLIO.Log("Reminder has a postpone date.");

                    pbDate.BackgroundImage = Properties.Resources.RemindMeZzz;
                    lblSmallDate.Text      = Convert.ToDateTime(rem.PostponeDate) + "";
                }

                //If some country has a longer date string, move the repeat icon/text more to the right so it doesnt overlap
                while (lblSmallDate.Bounds.IntersectsWith(pbRepeat.Bounds))
                {
                    pbRepeat.Location  = new Point(pbRepeat.Location.X + 5, pbRepeat.Location.Y);
                    lblRepeat.Location = new Point(lblRepeat.Location.X + 5, lblRepeat.Location.Y);
                }

                PlayReminderSound();

                FlashWindowHelper.Start(this);
                //this.MaximumSize = this.Size;

                if (BLLocalDatabase.Setting.Settings.PopupType == "AlwaysOnTop")
                {
                    this.TopMost  = true; //Popup will be always on top. no matter what you are doing, playing a game, watching a video, you will ALWAYS see the popup.
                    this.TopLevel = true;
                }
                else
                {
                    if (rem.Id != -1) //previewreminders should be topmost
                    {
                        this.TopMost     = false;
                        this.WindowState = FormWindowState.Minimized;
                    }
                }


                this.Text = rem.Name;
                string hexColor = ColorToHex(MaterialSkin.MaterialSkinManager.Instance.ColorScheme.AccentColor);

                foreach (string link in GetLinks(htmlLblText.Text)) //Add <a href> to make it into an actual link
                {
                    htmlLblText.Text = htmlLblText.Text.Replace(link, "<a href=\"" + link + "\" style=\"color: " + hexColor + "\"> " + link + "</a>");
                }

                if (rem.Date == null && rem.HttpId == null)
                {
                    rem.Date = DateTime.Now.ToString();
                }
            }
            catch (Exception ex)
            {
                ReminderException remEx = new ReminderException(BLReminder.ToString(rem), rem);
                remEx.StackTrace = ex.StackTrace; //Copy the stacktrace

                BLIO.WriteError(remEx, "Error loading reminder popup");
                BLIO.Log("Popup_load FAILED. Exception -> " + ex.Message);
            }
        }
Exemplo n.º 26
0
 private void btnEdit_Click(object sender, EventArgs e)
 {
     BLIO.Log("Edit button clicked on reminder item (" + rem.Id + ")");
     UCReminders.Instance.EditReminder(rem);
 }
Exemplo n.º 27
0
        /// <summary>
        /// Alternative Form_load method since form_load doesnt get called until you first double-click the RemindMe icon due to override SetVisibleCore
        /// </summary>
        private async Task formLoadAsync()
        {
            BLIO.Log("RemindMe_Load");

            BLIO.WriteUpdateBatch(Application.StartupPath);

            lblVersion.Text = "Version " + IOVariables.RemindMeVersion;

            Settings set = BLSettings.Settings;

            //set unique user string
            if (string.IsNullOrWhiteSpace(set.UniqueString))
            {
                if (File.Exists(IOVariables.uniqueString))
                {
                    set.UniqueString = File.ReadAllText(IOVariables.uniqueString);
                    BLSettings.UpdateSettings(set);
                }

                File.Delete(IOVariables.uniqueString);
            }
            BLIO.WriteUniqueString();

            if (set.LastVersion != null && (new Version(set.LastVersion) < new Version(IOVariables.RemindMeVersion)))
            {
                BLIO.Log("[VERSION CHECK] New version! last version: " + set.LastVersion + "  New version: " + IOVariables.RemindMeVersion);
                //User has a new RemindMe version!
                string releaseNotesString = "";

                foreach (KeyValuePair <string, string> entry in UpdateInformation.ReleaseNotes)
                {
                    if (new Version(entry.Key) > new Version(set.LastVersion))
                    {
                        releaseNotesString += "Version " + entry.Key + "\r\n" + entry.Value + "\r\n\r\n\r\n";
                    }
                }
                WhatsNew wn = new WhatsNew(set.LastVersion, releaseNotesString);
                wn.Show();


                //Before updating the lastVersion, log the update in the db
                BLOnlineDatabase.AddNewUpgrade(DateTime.Now, set.LastVersion, IOVariables.RemindMeVersion);

                //Update the lastVersion
                set.LastVersion = IOVariables.RemindMeVersion;
            }
            else
            {
                BLIO.Log("[VERSION CHECK] No new version! lastVersion: " + set.LastVersion + "  New version: " + IOVariables.RemindMeVersion);
            }

            //Default view should be reminders
            pnlMain.Controls.Add(ucReminders);

            RemindMeMessageFormManager.MakeTodaysRemindersPopup();
            BLIO.Log("Today's reminders popup created");

            //Create an shortcut in the windows startup folder if it doesn't already exist
            if (!File.Exists(IOVariables.startupFolderPath + "\\RemindMe" + ".lnk"))
            {
                FSManager.Shortcuts.CreateShortcut(IOVariables.startupFolderPath, "RemindMe", System.Windows.Forms.Application.StartupPath + "\\" + "RemindMe.exe", "Shortcut of RemindMe");
            }


            if (Debugger.IsAttached) //Debugging ? show extra option
            {
                btnDebugMode.Visible = true;
            }


            BLSongs.InsertWindowsSystemSounds();

            tmrUpdateRemindMe.Start();

            //If the setup still exists, delete it
            File.Delete(IOVariables.rootFolder + "SetupRemindMe.msi");

            //Call the timer once
            Thread tr = new Thread(() =>
            {
                //wait a bit, then call the update timer once. It then runs every 5 minutes
                Thread.Sleep(5000);
                tmrUpdateRemindMe_Tick(null, null);
                BLOnlineDatabase.InsertOrUpdateUser(set.UniqueString);
                Thread.Sleep(1500);
                if (set.LastVersion == null)
                {
                    //First time user! log it in the db
                    BLOnlineDatabase.InsertFirstTimeUser(set.UniqueString);
                    set.LastVersion = IOVariables.RemindMeVersion;
                }
                BLSettings.UpdateSettings(set);
            });

            tr.Start();



            this.Opacity       = 0;
            this.ShowInTaskbar = true;
            this.Show();
            tmrInitialHide.Start();

            //Insert the errorlog.txt into the DB if it is not empty
            if (new FileInfo(IOVariables.errorLog).Length > 0)
            {
                BLOnlineDatabase.InsertLocalErrorLog(set.UniqueString, File.ReadAllText(IOVariables.errorLog), File.ReadLines(IOVariables.errorLog).Count());
                File.WriteAllText(IOVariables.errorLog, "");
            }

            Random r = new Random();

            tmrCheckRemindMeMessages.Interval = (r.Next(60, 300)) * 1000; //Random interval between 1 and 5 minutes
            tmrCheckRemindMeMessages.Start();
            BLIO.Log("tmrCheckRemindMeMessages.Interval = " + tmrCheckRemindMeMessages.Interval / 1000 + " seconds.");
            BLIO.Log("RemindMe loaded");
            Cleanup();
        }
Exemplo n.º 28
0
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(tbPrompt.Text))
            {
                return;
            }

            if (promptReason == PromptReason.NUMERIC)
            {
                try
                {
                    intReturnValue = Convert.ToInt32(tbPrompt.Text);
                    this.Close(); //Won't reach this if the input text is not numeric.
                }
                catch
                {
                    tbPrompt.Text = "";
                }
            }
            else if (promptReason == PromptReason.TEXT)
            {
                strReturnValue = tbPrompt.Text;
                this.Close();
            }
            else if (promptReason == PromptReason.MINUTES)
            {
                try
                {
                    if (tbPrompt.Text.ToLower().Contains('h'))
                    {
                        BLIO.Log("timer popup contains 'h'. Checking what's before it");

                        //Text without the 'm'. We know the number after 'h' is in minutes, no need to keep it in the string
                        string tbText = tbPrompt.Text.Replace("m", "");

                        //Get the index number of the 'h' in the text
                        int index = tbPrompt.Text.ToLower().IndexOf('h');

                        //Now get all the text before it(should be a numer) and multiply by 60 because the user input hours
                        BLIO.Log("Parsing hours....");
                        minutes += Convert.ToInt32(tbPrompt.Text.Substring(0, index)) * 60;

                        //Now get the number after the 'h' , which should be minutes, and add it to timerMinutes
                        //But, first check if there is actually something after the 'h'

                        if (tbText.Length > index + 1)//+1 because .Length starts from 1, index starts from 0
                        {
                            BLIO.Log("Parsing minutes....");
                            minutes += Convert.ToInt32(tbText.Substring(index + 1, tbText.Length - (index + 1)));
                        }
                    }
                    else
                    {
                        minutes = Convert.ToInt32(tbPrompt.Text);
                    }
                }
                catch { }

                if (minutes <= 0)
                {
                    tbPrompt.ForeColor = Color.Firebrick;
                }
                else
                {
                    this.Close();
                }
            }
        }
Exemplo n.º 29
0
        private void ucTimerDeleteToolstrip_Click(object sender, EventArgs e)
        {
            //First, see what button is pressed
            BunifuFlatButton button = null;

            foreach (Control c in pnlRunningTimers.Controls)
            {
                if (c is BunifuFlatButton)
                {
                    button = (BunifuFlatButton)c;

                    if (button.Normalcolor == Color.Gray)
                    {
                        break;
                    }
                }
            }

            //Now that we have the selected button stored in the "button" variable, let's work with it
            //Get the id
            int id = Convert.ToInt32(button.Text.Replace("Timer", "").Replace(" ", ""));
            //Use the id to get the correct TimerItem from the "timers" collection, and delete it
            TimerItem toRemoveItem = timers.Where(t => t.ID == id).ToList()[0];

            RemoveTimer(toRemoveItem);
            toRemoveItem.Dispose();

            //Set the current timer to the first one in the list
            if (timers.Count > 0)
            {
                currentTimerItem = timers[0];


                BLIO.Log("Setting values of (UCTimer) numericupdowns");
                TimeSpan time = TimeSpan.FromSeconds((double)currentTimerItem.SecondsRemaining);
                numSeconds.Value = time.Seconds;
                numMinutes.Value = time.Minutes;
                numHours.Value   = time.Hours;
            }
            else  //Nothing left
            {
                numSeconds.Value = 0;
                numMinutes.Value = 0;
                numHours.Value   = 0;
                btnPauseResumeTimer.Iconimage = Properties.Resources.pause_2x1;
            }

            //Set the pause/resume icon image depending on the current timer
            if (currentTimerItem.Disposed || currentTimerItem == null)
            {
                return;
            }

            tmrCountdown.Enabled = currentTimerItem.IsRunning();

            if (currentTimerItem.IsRunning())
            {
                btnPauseResumeTimer.Iconimage = Properties.Resources.pause_2x1;
            }
            else
            {
                btnPauseResumeTimer.Iconimage = Properties.Resources.Play;
            }

            //Now make the current TimerItem button selected
            foreach (Control c in pnlRunningTimers.Controls)
            {
                if (c is BunifuFlatButton)
                {
                    button = (BunifuFlatButton)c;

                    if (Convert.ToInt32(button.Text.Replace("Timer", "").Replace(" ", "")) == currentTimerItem.ID)
                    {
                        button.Normalcolor = Color.Gray; //This is our button
                    }
                }
            }
        }
Exemplo n.º 30
0
        static void Main(string[] args)
        {
            string resource1 = "RemindMe.External_DLL.Bunifu_UI_v1.5.3.dll";

            EmbeddedAssembly.Load(resource1, "Bunifu_UI_v1.5.3.dll");
            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

            try
            {
                AppDomain.CurrentDomain.SetData("DataDirectory", IOVariables.databaseFile);
                BLIO.CreateDatabaseIfNotExist();

                if (!BLLocalDatabase.HasAllTables())
                {
                    isMaterial = true;
                }
                else
                {
                    //See if the user wants Material Design or old RemindMe-Design (Default = Material)
                    Settings set = BLLocalDatabase.Setting.Settings;
                    if (set != null && set.MaterialDesign != null && set.MaterialDesign.HasValue) //not null
                    {
                        isMaterial = Convert.ToBoolean(BLLocalDatabase.Setting.Settings.MaterialDesign.Value);
                    }
                }



                if (args.Length > 0)
                {//The user double-clicked an .remindme file!
                    BLIO.Log("Detected the double clicking of a .remindme file!");
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);

                    if (isMaterial)
                    {
                        Application.Run(new MaterialRemindMeImporter(args[0]));
                    }
                    else
                    {
                        Application.Run(new RemindMeImporter(args[0]));
                    }
                }
            }
            catch (Exception ex)
            {
                BLIO.Log("!!!! EXCEPTION IN PROGRAM.CS !!!! (" + ex.GetType() + ")");
                BLOnlineDatabase.AddException(ex, DateTime.Now, IOVariables.systemLog);
            }
            //This code should always execute!!!! Remember the 3.0.6 disaster? yeahhhhh...
            using (Mutex mutex = new Mutex(false, "Global\\" + "RemindMe"))
            {
                if (!mutex.WaitOne(0, false)) //one instance of remindme already running
                {
                    return;
                }

                // Set the unhandled exception mode to force all Windows Forms errors to go through our handler.
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(true);
                Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

                // Add the event handler for handling non-UI thread exceptions to the event.
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                if (isMaterial)
                {
                    Application.Run(new MaterialForm1());
                }
                else
                {
                    Application.Run(new Form1());
                }
            }
        }