public static void ExportElement(string nodeName, object nodeValue, string filename)
        {
            XDocument xml        = XDocument.Load(filename);
            XElement  settingsXE = xml.Descendants(ns + "Settings").FirstOrDefault();

            try {
                XElement xe = settingsXE.Elements(ns + nodeName).First();
                xe.SetValue(nodeValue);
                xml.Save(filename);
                log.Debug("Setting '" + nodeName + "' updated to '" + nodeValue + "'");
            } catch (System.Exception ex) {
                if (OGCSexception.GetErrorCode(ex) == "0x80131509")   //Sequence contains no elements
                {
                    log.Debug("Adding Setting " + nodeName + " to settings.xml");
                    //This appends to the end, which won't import properly.
                    //settingsXE.Add(new XElement(ns + nodeName, nodeValue));
                    //To save writing a sort method, let's just save everything!
                    Settings.Instance.Save();
                }
                else
                {
                    OGCSexception.Analyse(ex);
                    log.Error("Failed to export setting " + nodeName + "=" + nodeValue + " to settings.xml file.");
                }
            }
        }
Esempio n. 2
0
        public static void ExportElement(string nodeName, object nodeValue, string filename)
        {
            XDocument xml        = XDocument.Load(filename);
            XElement  settingsXE = xml.Descendants(ns + "Settings").FirstOrDefault();

            try {
                XElement xe = settingsXE.Elements(ns + nodeName).First();
                xe.SetValue(nodeValue);
                if (nodeValue is Boolean && nodeValue != null)
                {
                    xe.RemoveAttributes(); //Remove nullable attribute 'i:nil="true"'
                }
                xml.Save(filename);
                log.Debug("Setting '" + nodeName + "' updated to '" + nodeValue + "'");
            } catch (System.Exception ex) {
                if (OGCSexception.GetErrorCode(ex) == "0x80131509")   //Sequence contains no elements
                {
                    log.Debug("Adding Setting " + nodeName + " to settings.xml");
                    settingsXE.Add(new XElement(ns + nodeName, nodeValue));
                    xml.Root.Sort();
                    xml.Save(filename);
                }
                else
                {
                    OGCSexception.Analyse(ex);
                    log.Error("Failed to export setting " + nodeName + "=" + nodeValue + " to settings.xml file.");
                }
            }
        }
        private static void Main(string[] args)
        {
            initialiseFiles();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Splash.ShowMe();

            log.Debug("Loading settings from file.");
            Settings.Load();

            isNewVersion();
            Updater = new Updater();
            Updater.CheckForUpdate();

            TimezoneDB.Instance.CheckForUpdate();

            try {
                try {
                    Application.Run(new MainForm(startingTab));
                } catch (ApplicationException ex) {
                    log.Fatal(ex.Message);
                    MessageBox.Show(ex.Message, "Application terminated!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    throw new ApplicationException();
                } catch (System.Runtime.InteropServices.COMException ex) {
                    if (OGCSexception.GetErrorCode(ex, 0x000FFFFF) == "0x00040115")
                    {
                        log.Error(ex.Message);
                        MessageBox.Show("OGCS is not able to run as Outlook is not properly connected to the Exchange server.\r\n" +
                                        "Please try again later.", "Application cannot initialise!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                    else
                    {
                        OGCSexception.Analyse(ex);
                    }
                    throw new ApplicationException();
                } catch (System.Exception ex) {
                    OGCSexception.Analyse(ex);
                    log.Fatal("Application unexpectedly terminated!");
                    MessageBox.Show(ex.Message, "Application unexpectedly terminated!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    throw new ApplicationException();
                }
            } catch (ApplicationException) {
                log.Warn("Tidying down any remaining Outlook references, as OGCS crashed out.");
                try {
                    OutlookCalendar.InstanceConnect = false;
                    OutlookCalendar.Instance.IOutlook.Disconnect();
                } catch { }
            }
            Splash.CloseMe();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            while (Updater.IsBusy)
            {
                Application.DoEvents();
                System.Threading.Thread.Sleep(100);
            }
            log.Info("Application closed.");
        }
 public static string ImportElement(string nodeName, string filename)
 {
     try {
         XDocument xml        = XDocument.Load(filename);
         XElement  settingsXE = xml.Descendants(ns + "Settings").FirstOrDefault();
         XElement  xe         = settingsXE.Elements(ns + nodeName).First();
         log.Debug("Retrieved setting '" + nodeName + "' with value '" + xe.Value + "'");
         return(xe.Value);
     } catch (System.InvalidOperationException ex) {
         if (OGCSexception.GetErrorCode(ex) == "0x80131509")   //Sequence contains no elements
         {
             log.Warn("'" + nodeName + "' could not be found.");
         }
         else
         {
             log.Error("Failed retrieving '" + nodeName + "' from " + filename);
             OGCSexception.Analyse(ex);
         }
         return(null);
     } catch (System.Exception ex) {
         log.Error("Failed retrieving '" + nodeName + "' from " + filename);
         OGCSexception.Analyse(ex);
         return(null);
     }
 }
Esempio n. 5
0
        private void findCalendars(Folders folders, Dictionary <string, MAPIFolder> calendarFolders, String excludeDeletedFolder, MAPIFolder defaultCalendar = null)
        {
            //Initiate progress bar (red line underneath "Getting calendars" text)
            System.Drawing.Graphics g          = MainForm.Instance.tabOutlook.CreateGraphics();
            System.Drawing.Pen      p          = new System.Drawing.Pen(System.Drawing.Color.Red, 3);
            System.Drawing.Point    startPoint = new System.Drawing.Point(MainForm.Instance.lOutlookCalendar.Location.X,
                                                                          MainForm.Instance.lOutlookCalendar.Location.Y + MainForm.Instance.lOutlookCalendar.Size.Height + 3);
            double stepSize = MainForm.Instance.lOutlookCalendar.Size.Width / folders.Count;

            int fldCnt = 0;

            foreach (MAPIFolder folder in folders)
            {
                fldCnt++;
                System.Drawing.Point endPoint = new System.Drawing.Point(MainForm.Instance.lOutlookCalendar.Location.X + Convert.ToInt16(fldCnt * stepSize),
                                                                         MainForm.Instance.lOutlookCalendar.Location.Y + MainForm.Instance.lOutlookCalendar.Size.Height + 3);
                try { g.DrawLine(p, startPoint, endPoint); } catch { /*May get GDI+ error if g has been repainted*/ }
                System.Windows.Forms.Application.DoEvents();
                try {
                    OlItemType defaultItemType = folder.DefaultItemType;
                    if (defaultItemType == OlItemType.olAppointmentItem)
                    {
                        if (defaultCalendar == null ||
                            (folder.EntryID != defaultCalendar.EntryID))
                        {
                            calendarFolders.Add(folder.Name, folder);
                        }
                    }
                    if (folder.EntryID != excludeDeletedFolder && folder.Folders.Count > 0)
                    {
                        findCalendars(folder.Folders, calendarFolders, excludeDeletedFolder, defaultCalendar);
                    }
                } catch (System.Exception ex) {
                    OGCSexception.Analyse(ex);
                    if (oApp.Session.ExchangeConnectionMode.ToString().Contains("Disconnected") ||
                        ex.Message.StartsWith("Network problems are preventing connection to Microsoft Exchange.") ||
                        OGCSexception.GetErrorCode(ex, 0x000FFFFF) == "0x00040115")
                    {
                        log.Info("Currently disconnected from Exchange - unable to retrieve MAPI folders.");
                        MainForm.Instance.ToolTips.SetToolTip(MainForm.Instance.cbOutlookCalendars,
                                                              "The Outlook calendar to synchonize with.\nSome may not be listed as you are currently disconnected.");
                    }
                    else
                    {
                        log.Error("Failed to recurse MAPI folders.");
                        log.Error(ex.Message);
                        MessageBox.Show("A problem was encountered when searching for Outlook calendar folders.",
                                        "Calendar Folders", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            p.Dispose();
            try { g.Clear(System.Drawing.Color.White); } catch { }
            g.Dispose();
            System.Windows.Forms.Application.DoEvents();
        }
 private static void clickOnceUninstallError(System.Exception ex)
 {
     if (OGCSexception.GetErrorCode(ex) == "0x80131509")
     {
         log.Debug("No ClickOnce install found.");
     }
     else
     {
         log.Error("Failed removing ClickOnce install.");
         OGCSexception.Analyse(ex, true);
     }
 }
        public static void ExportElement(string nodeName, object nodeValue, string filename)
        {
            XDocument xml = null;

            try {
                xml = XDocument.Load(filename);
            } catch (System.Exception ex) {
                OGCSexception.Analyse("Failed to load " + filename, ex, true);
                throw;
            }
            XElement settingsXE = null;

            try {
                settingsXE = xml.Descendants(ns + "Settings").FirstOrDefault();
            } catch (System.Exception ex) {
                log.Debug(filename + " head: " + xml.ToString().Substring(0, Math.Min(200, xml.ToString().Length)));
                OGCSexception.Analyse("Could not access 'Settings' element.", ex, true);
                return;
            }
            try {
                XElement xe = settingsXE.Elements(ns + nodeName).First();
                if (nodeValue == null && nodeName == "CloudLogging")   //Nullable Boolean node(s)
                {
                    XNamespace i = "http://www.w3.org/2001/XMLSchema-instance";
                    xe.SetAttributeValue(i + "nil", "true"); //Add nullable attribute 'i:nil="true"'
                    xe.SetValue(String.Empty);
                }
                else
                {
                    xe.SetValue(nodeValue);
                    if (nodeValue is Boolean && nodeValue != null)
                    {
                        xe.RemoveAttributes(); //Remove nullable attribute 'i:nil="true"'
                    }
                }
                xml.Save(filename);
                log.Debug("Setting '" + nodeName + "' updated to '" + nodeValue + "'");
            } catch (System.Exception ex) {
                if (OGCSexception.GetErrorCode(ex) == "0x80131509")   //Sequence contains no elements
                {
                    log.Debug("Adding Setting " + nodeName + " to settings.xml");
                    settingsXE.Add(new XElement(ns + nodeName, nodeValue));
                    xml.Root.Sort();
                    xml.Save(filename);
                }
                else
                {
                    OGCSexception.Analyse("Failed to export setting " + nodeName + "=" + nodeValue + " to " + filename + " file.", ex);
                }
            }
        }
Esempio n. 8
0
 private static void onFirstRun()
 {
     try {
         log.Debug("Removing ClickOnce install...");
         var migrator = new ClickOnceToSquirrelMigrator.InSquirrelAppMigrator(Application.ProductName);
         migrator.Execute().Wait();
         log.Info("ClickOnce install has been removed.");
     } catch (System.InvalidOperationException ex) {
         if (OGCSexception.GetErrorCode(ex) == "0x80131509")
         {
             log.Debug("No ClickOnce install found.");
         }
     } catch (System.Exception ex) {
         log.Error("Failed removing ClickOnce install.");
         OGCSexception.Analyse(ex, true);
     }
 }
Esempio n. 9
0
 /// <summary>
 /// Handles non-unique calendar names by recursively adding parent folders to the name
 /// </summary>
 /// <param name="name">Name/path of calendar (dictionary key)</param>
 /// <param name="folder">The target folder (dictionary value)</param>
 /// <param name="parentFolder">Recursive parent folder - leave null on initial call</param>
 private void calendarFolderAdd(String name, MAPIFolder folder, MAPIFolder parentFolder = null)
 {
     try {
         calendarFolders.Add(name, folder);
     } catch (System.ArgumentException ex) {
         if (OGCSexception.GetErrorCode(ex) == "0x80070057")
         {
             //An item with the same key has already been added.
             //Let's recurse up to the parent folder, looking to make it unique
             object parentObj = (parentFolder != null ? parentFolder.Parent : folder.Parent);
             if (parentObj is NameSpace)
             {
                 //We've traversed all the way up the folder path to the root and still not unique
                 log.Warn("MAPIFolder " + name + " does not have a unique name - so cannot use!");
             }
             else if (parentObj is MAPIFolder)
             {
                 String parentFolderName = (parentObj as MAPIFolder).FolderPath.Split('\\').Last();
                 calendarFolderAdd(System.IO.Path.Combine(parentFolderName, name), folder, parentObj as MAPIFolder);
             }
         }
     }
 }
        public static Boolean IsSquirrelInstall()
        {
            Boolean isSquirrelInstall = false;

            try {
                using (var updateManager = new Squirrel.UpdateManager(null)) {
                    //This just checks if there is an Update.exe file in the parent directory of the OGCS executable
                    isSquirrelInstall = updateManager.IsInstalledApp;
                }
            } catch (System.Exception ex) {
                if (OGCSexception.GetErrorCode(ex) == "0x80131500") //Update.exe not found
                {
                    log.Debug(ex.Message);
                }
                else
                {
                    log.Error("Failed to determine if app is a Squirrel install. Assuming not.");
                    OGCSexception.Analyse(ex);
                }
            }

            log.Info("This " + (isSquirrelInstall ? "is" : "is not") + " a Squirrel install.");
            return(isSquirrelInstall);
        }
Esempio n. 11
0
        private void checkForZip(object sender, DoWorkEventArgs e)
        {
            string releaseURL     = null;
            string releaseVersion = null;
            string releaseType    = null;

            log.Debug("Checking for ZIP update...");
            string html         = "";
            String errorDetails = "";

            try {
                html = new System.Net.WebClient().DownloadString("https://github.com/phw198/OutlookGoogleCalendarSync/blob/master/docs/latest_zip_release.md");
            } catch (System.Net.WebException ex) {
                errorDetails = ex.Message;
                if (OGCSexception.GetErrorCode(ex) == "0x80131509")
                {
                    log.Warn("Failed to retrieve data (no network?): " + errorDetails);
                }
                else
                {
                    OGCSexception.Analyse(ex);
                    log.Error("Failed to retrieve data: " + errorDetails);
                }
            } catch (System.Exception ex) {
                errorDetails = ex.Message;
                OGCSexception.Analyse(ex);
                log.Error("Failed to retrieve data: " + errorDetails);
            }

            if (!string.IsNullOrEmpty(html))
            {
                log.Debug("Finding Beta release...");
                MatchCollection release = getRelease(html, @"<strong>Beta</strong>: <a href=""(.*?)"">v([\d\.]+)</a>");
                if (release.Count > 0)
                {
                    releaseType    = "Beta";
                    releaseURL     = release[0].Result("$1");
                    releaseVersion = release[0].Result("$2");
                }
                if (Settings.Instance.AlphaReleases)
                {
                    log.Debug("Finding Alpha release...");
                    release = getRelease(html, @"<strong>Alpha</strong>: <a href=""(.*?)"">v([\d\.]+)</a>");
                    if (release.Count > 0)
                    {
                        releaseType    = "Alpha";
                        releaseURL     = release[0].Result("$1");
                        releaseVersion = release[0].Result("$2");
                    }
                }
            }

            if (releaseVersion != null)
            {
                String paddedVersion = "";
                foreach (String versionBit in releaseVersion.Split('.'))
                {
                    paddedVersion += versionBit.PadLeft(2, '0');
                }
                Int32 releaseNum = Convert.ToInt32(paddedVersion);
                paddedVersion = "";
                foreach (String versionBit in Application.ProductVersion.Split('.'))
                {
                    paddedVersion += versionBit.PadLeft(2, '0');
                }
                Int32 myReleaseNum = Convert.ToInt32(paddedVersion);
                if (releaseNum > myReleaseNum)
                {
                    log.Info("New " + releaseType + " ZIP release found: " + releaseVersion);
                    DialogResult dr = MessageBox.Show("A new " + releaseType + " release is available for OGCS. Would you like to upgrade to v" + releaseVersion + "?", "New OGCS Release Available", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (dr == DialogResult.Yes)
                    {
                        System.Diagnostics.Process.Start(releaseURL);
                    }
                }
                else
                {
                    log.Info("Already on latest ZIP release.");
                    if (isManualCheck)
                    {
                        MessageBox.Show("You are already on the latest release", "No Update Required", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            else
            {
                log.Info("Did not find ZIP release.");
                if (isManualCheck)
                {
                    MessageBox.Show("Failed to check for ZIP release." + (string.IsNullOrEmpty(errorDetails) ? "" : "\r\n" + errorDetails),
                                    "Update Check Failed", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
Esempio n. 12
0
        /// <returns>True if the user has upgraded</returns>
        private async Task <Boolean> githubCheck()
        {
            log.Debug("Checking for Squirrel update...");
            UpdateManager updateManager = null;

            isBusy = true;
            try {
                String installRootDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                if (string.IsNullOrEmpty(nonGitHubReleaseUri))
                {
                    updateManager = await Squirrel.UpdateManager.GitHubUpdateManager("https://github.com/phw198/OutlookGoogleCalendarSync", "OutlookGoogleCalendarSync", installRootDir,
                                                                                     new Squirrel.FileDownloader(new Extensions.OgcsWebClient()), prerelease : Settings.Instance.AlphaReleases);
                }
                else
                {
                    updateManager = new Squirrel.UpdateManager(nonGitHubReleaseUri, "OutlookGoogleCalendarSync", installRootDir);
                }

                UpdateInfo updates = await updateManager.CheckForUpdate();

                if (updates.ReleasesToApply.Any())
                {
                    if (updates.CurrentlyInstalledVersion != null)
                    {
                        log.Info("Currently installed version: " + updates.CurrentlyInstalledVersion.Version.ToString());
                    }
                    log.Info("Found " + updates.ReleasesToApply.Count() + " newer releases available.");
                    log.Info("Download directory = " + updates.PackageDirectory);

                    DialogResult dr = DialogResult.Cancel;
                    String       squirrelAnalyticsLabel = "";
                    String       releaseNotes           = "";
                    String       releaseVersion         = "";
                    String       releaseType            = "";

                    foreach (ReleaseEntry update in updates.ReleasesToApply.OrderBy(x => x.Version).Reverse())
                    {
                        log.Info("New " + update.Version.SpecialVersion + " version available: " + update.Version.Version.ToString());

                        if (!this.isManualCheck && update.Version.Version.ToString() == Settings.Instance.SkipVersion)
                        {
                            log.Info("The user has previously requested to skip this version.");
                            break;
                        }

                        String localFile = updates.PackageDirectory + "\\" + update.Filename;
                        if (updateManager.CheckIfAlreadyDownloaded(update, localFile))
                        {
                            log.Debug("This has already been downloaded.");
                        }
                        else
                        {
                            try {
                                //"https://github.com/phw198/OutlookGoogleCalendarSync/releases/download/v2.8.6-alpha"
                                String nupkgUrl = "https://github.com/phw198/OutlookGoogleCalendarSync/releases/download/v" + update.Version + "/" + update.Filename;
                                log.Debug("Downloading " + nupkgUrl);
                                new Extensions.OgcsWebClient().DownloadFile(nupkgUrl, localFile);
                                log.Debug("Download complete.");
                            } catch (System.Exception ex) {
                                OGCSexception.Analyse("Failed downloading release file for " + update.Version, ex);
                                throw new ApplicationException("Failed upgrading OGCS.", ex);
                            }
                        }

                        if (string.IsNullOrEmpty(releaseNotes))
                        {
                            log.Debug("Retrieving release notes.");
                            releaseNotes           = update.GetReleaseNotes(updates.PackageDirectory);
                            releaseVersion         = update.Version.Version.ToString();
                            releaseType            = update.Version.SpecialVersion;
                            squirrelAnalyticsLabel = "from=" + Application.ProductVersion + ";to=" + update.Version.Version.ToString();
                        }
                    }

                    var t = new System.Threading.Thread(() => new Forms.UpdateInfo(releaseVersion, releaseType, releaseNotes, out dr));
                    t.SetApartmentState(System.Threading.ApartmentState.STA);
                    t.Start();
                    t.Join();

                    if (dr == DialogResult.No)
                    {
                        log.Info("User chose not to upgrade right now.");
                        Telemetry.Send(Analytics.Category.squirrel, Analytics.Action.upgrade, squirrelAnalyticsLabel + ";later");
                    }
                    else if (dr == DialogResult.Ignore)
                    {
                        Telemetry.Send(Analytics.Category.squirrel, Analytics.Action.upgrade, squirrelAnalyticsLabel + ";skipped");
                    }
                    else if (dr == DialogResult.Yes)
                    {
                        try {
                            Telemetry.Send(Analytics.Category.squirrel, Analytics.Action.download, squirrelAnalyticsLabel + ";successful");
                            log.Info("Applying the updated release(s)...");
                            //updateManager.UpdateApp().Wait();

                            int ApplyAttempt = 1;
                            while (ApplyAttempt <= 5)
                            {
                                try {
                                    updateManager.ApplyReleases(updates).Wait();
                                    break;
                                } catch (System.AggregateException ex) {
                                    ApplyAttempt++;
                                    if (OGCSexception.GetErrorCode(ex.InnerException) == "0x80070057")   //File does not exist
                                    //File does not exist: C:\Users\Paul\AppData\Local\OutlookGoogleCalendarSync\packages\OutlookGoogleCalendarSync-2.8.4-alpha-full.nupkg
                                    //Extract the nupkg filename
                                    {
                                        String regexMatch = ".*" + updates.PackageDirectory.Replace(@"\", @"\\") + @"\\(.*?([\d\.]+-\w+).*)$";
                                        System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(ex.InnerException.Message, regexMatch);

                                        if (match?.Groups?.Count == 3)
                                        {
                                            log.Warn("Could not update as missing file " + match.Groups[1]);
                                            String nupkgUrl = "https://github.com/phw198/OutlookGoogleCalendarSync/releases/download/v" + match.Groups[2] + "/" + match.Groups[1];
                                            log.Debug("Downloading " + nupkgUrl);
                                            new Extensions.OgcsWebClient().DownloadFile(nupkgUrl, updates.PackageDirectory + "\\" + match.Groups[1]);
                                            log.Debug("Download complete.");
                                        }
                                    }
                                    else
                                    {
                                        throw;
                                    }
                                }
                            }

                            log.Info("The application has been successfully updated.");
                            OgcsMessageBox.Show("The application has been updated and will now restart.",
                                                "OGCS successfully updated!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            restartUpdateExe = updateManager.RootAppDirectory + "\\Update.exe";
                            return(true);
                        } catch (System.AggregateException ae) {
                            foreach (System.Exception ex in ae.InnerExceptions)
                            {
                                OGCSexception.Analyse(ex, true);
                                ex.Data.Add("analyticsLabel", squirrelAnalyticsLabel);
                                throw new ApplicationException("Failed upgrading OGCS.", ex);
                            }
                        } catch (System.Exception ex) {
                            OGCSexception.Analyse(ex, true);
                            ex.Data.Add("analyticsLabel", squirrelAnalyticsLabel);
                            throw new ApplicationException("Failed upgrading OGCS.", ex);
                        }
                    }
                }
                else
                {
                    log.Info("Already running the latest version of OGCS.");
                    if (this.isManualCheck)   //Was a manual check, so give feedback
                    {
                        OgcsMessageBox.Show("You are already running the latest version of OGCS.", "Latest Version", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            } catch (ApplicationException ex) {
                Telemetry.Send(Analytics.Category.squirrel, Analytics.Action.download, ex.Data["analyticsLabel"] + ";failed");
                throw;
            } catch (System.AggregateException ae) {
                log.Fail("Failed checking for update.");
                foreach (System.Exception ex in ae.InnerExceptions)
                {
                    OGCSexception.Analyse(OGCSexception.LogAsFail(ex), true);
                    throw;
                }
            } catch (System.Exception ex) {
                OGCSexception.Analyse("Failed checking for update.", OGCSexception.LogAsFail(ex), true);
                throw;
            } finally {
                isBusy = false;
                updateManager.Dispose();
            }
            return(false);
        }
Esempio n. 13
0
 public static string ImportElement(string nodeName, string filename, Boolean debugLog = true)
 {
     try {
         XDocument xml        = XDocument.Load(filename);
         XElement  settingsXE = xml.Descendants(ns + "Settings").FirstOrDefault();
         XElement  xe         = settingsXE.Elements(ns + nodeName).First();
         if (debugLog)
         {
             log.Debug("Retrieved setting '" + nodeName + "' with value '" + xe.Value + "'");
         }
         return(xe.Value);
     } catch (System.InvalidOperationException ex) {
         if (OGCSexception.GetErrorCode(ex) == "0x80131509")   //Sequence contains no elements
         {
             log.Warn("'" + nodeName + "' could not be found.");
         }
         else
         {
             log.Error("Failed retrieving '" + nodeName + "' from " + filename);
             OGCSexception.Analyse(ex);
         }
         return(null);
     } catch (System.IO.IOException ex) {
         if (OGCSexception.GetErrorCode(ex) == "0x80070020")   //Setting file in use by another process
         {
             log.Warn("Failed retrieving '" + nodeName + "' from " + filename);
             log.Warn(ex.Message);
         }
         else
         {
             log.Error("Failed retrieving '" + nodeName + "' from " + filename);
             OGCSexception.Analyse(ex);
         }
         return(null);
     } catch (System.Xml.XmlException ex) {
         log.Warn("Failed retrieving '" + nodeName + "' from " + filename);
         if (OGCSexception.GetErrorCode(ex) == "0x80131940")   //hexadecimal value 0x00, is an invalid character
         {
             log.Warn(ex.Message);
             Settings.ResetFile(filename);
             try {
                 XDocument xml        = XDocument.Load(filename);
                 XElement  settingsXE = xml.Descendants(ns + "Settings").FirstOrDefault();
                 XElement  xe         = settingsXE.Elements(ns + nodeName).First();
                 if (debugLog)
                 {
                     log.Debug("Retrieved setting '" + nodeName + "' with value '" + xe.Value + "'");
                 }
                 return(xe.Value);
             } catch (System.Exception ex2) {
                 OGCSexception.Analyse("Still failed to retrieve '" + nodeName + "' from " + filename, ex2);
                 return(null);
             }
         }
         else
         {
             OGCSexception.Analyse(ex);
             return(null);
         }
     } catch (System.Exception ex) {
         log.Error("Failed retrieving '" + nodeName + "' from " + filename);
         OGCSexception.Analyse(ex);
         return(null);
     }
 }
Esempio n. 14
0
        public static void ExportElement(Object settingStore, String nodeName, object nodeValue, string filename)
        {
            XDocument xml = null;

            try {
                xml = XDocument.Load(filename);
            } catch (System.Exception ex) {
                OGCSexception.Analyse("Failed to load " + filename, ex, true);
                throw;
            }
            XElement settingsXE = null;

            try {
                settingsXE = xml.Descendants(ns + "Settings").FirstOrDefault();
            } catch (System.Exception ex) {
                log.Debug(filename + " head: " + xml.ToString().Substring(0, Math.Min(200, xml.ToString().Length)));
                OGCSexception.Analyse("Could not access 'Settings' element.", ex, true);
                return;
            }
            XElement xe        = null;
            XElement xeProfile = null;

            try {
                if (Settings.Profile.GetType(settingStore) == Settings.Profile.Type.Calendar)
                {
                    //It's a Calendar setting
                    SettingsStore.Calendar calSettings = settingStore as SettingsStore.Calendar;
                    XElement        xeCalendars        = settingsXE.Elements(ns + "Calendars").First();
                    List <XElement> xeCalendar         = xeCalendars.Elements(ns + Settings.Profile.Type.Calendar.ToString()).ToList();
                    xeProfile = xeCalendar.First(c => c.Element(ns + "_ProfileName").Value == calSettings._ProfileName);
                    xe        = xeProfile.Elements(ns + nodeName).First();
                }
                else if (settingStore is Settings)
                {
                    //It's a "global" setting
                    xe = settingsXE.Elements(ns + nodeName).First();
                }
                if (nodeValue == null && nodeName == "CloudLogging")   //Nullable Boolean node(s)
                {
                    XNamespace i = "http://www.w3.org/2001/XMLSchema-instance";
                    xe.SetAttributeValue(i + "nil", "true"); //Add nullable attribute 'i:nil="true"'
                    xe.SetValue(String.Empty);
                }
                else
                {
                    xe.SetValue(nodeValue);
                    if (nodeValue is Boolean && nodeValue != null)
                    {
                        xe.RemoveAttributes(); //Remove nullable attribute 'i:nil="true"'
                    }
                }
                xml.Save(filename);
                log.Debug("Setting '" + nodeName + "' updated to '" + nodeValue + "'");
            } catch (System.Exception ex) {
                if (OGCSexception.GetErrorCode(ex) == "0x80131509")   //Sequence contains no elements
                {
                    log.Debug("Adding Setting " + nodeName + " for " + settingStore.ToString() + " to " + filename);
                    if (xeProfile != null)
                    {
                        xeProfile.Add(new XElement(ns + nodeName, nodeValue));
                    }
                    else
                    {
                        settingsXE.Add(new XElement(ns + nodeName, nodeValue));
                    }
                    xml.Root.Sort();
                    xml.Save(filename);
                }
                else
                {
                    OGCSexception.Analyse("Failed to export setting " + nodeName + "=" + nodeValue + " for " + settingStore.ToString() + " to " + filename + " file.", ex);
                }
            }
        }
Esempio n. 15
0
        public NameSpace GetCurrentUser(NameSpace oNS)
        {
            //We only need the current user details when syncing meeting attendees.
            //If GAL had previously been detected as blocked, let's always try one attempt to see if it's been opened up
            if (!Settings.Instance.OutlookGalBlocked && !Settings.Instance.AddAttendees)
            {
                return(oNS);
            }

            Boolean releaseNamespace = (oNS == null);

            if (releaseNamespace)
            {
                oNS = oApp.GetNamespace("mapi");
            }

            Recipient currentUser = null;

            try {
                DateTime triggerOOMsecurity = DateTime.Now;
                try {
                    currentUser = oNS.CurrentUser;
                    if (!MainForm.Instance.IsHandleCreated && (DateTime.Now - triggerOOMsecurity).TotalSeconds > 1)
                    {
                        log.Warn(">1s delay possibly due to Outlook security popup.");
                        OutlookCalendar.OOMsecurityInfo = true;
                    }
                } catch (System.Exception ex) {
                    OGCSexception.Analyse(ex);
                    if (Settings.Instance.OutlookGalBlocked)   //Fail fast
                    {
                        log.Debug("Corporate policy is still blocking access to GAL.");
                        return(oNS);
                    }
                    log.Warn("We seem to have a faux connection to Outlook! Forcing starting it with a system call :-/");
                    oNS = (NameSpace)OutlookCalendar.ReleaseObject(oNS);
                    Disconnect();
                    OutlookCalendar.AttachToOutlook(ref oApp, openOutlookOnFail: true, withSystemCall: true);
                    oNS = oApp.GetNamespace("mapi");

                    int maxDelay = 5;
                    int delay    = 1;
                    while (delay <= maxDelay)
                    {
                        log.Debug("Sleeping..." + delay + "/" + maxDelay);
                        System.Threading.Thread.Sleep(10000);
                        try {
                            currentUser = oNS.CurrentUser;
                            delay       = maxDelay;
                        } catch (System.Exception ex2) {
                            if (delay == maxDelay)
                            {
                                if (OGCSexception.GetErrorCode(ex2) == "0x80004004")   //E_ABORT
                                {
                                    log.Warn("Corporate policy or possibly anti-virus is blocking access to GAL.");
                                }
                                else
                                {
                                    OGCSexception.Analyse(ex2);
                                }
                                log.Warn("OGCS is unable to obtain CurrentUser from Outlook.");
                                Settings.Instance.OutlookGalBlocked = true;
                                return(oNS);
                            }
                            OGCSexception.Analyse(ex2);
                        }
                        delay++;
                    }
                }
                if (Settings.Instance.OutlookGalBlocked)
                {
                    log.Debug("GAL is no longer blocked!");
                }
                Settings.Instance.OutlookGalBlocked = false;
                currentUserSMTP = GetRecipientEmail(currentUser);
                currentUserName = currentUser.Name;
            } finally {
                currentUser = (Recipient)OutlookCalendar.ReleaseObject(currentUser);
                if (releaseNamespace)
                {
                    oNS = (NameSpace)OutlookCalendar.ReleaseObject(oNS);
                }
            }
            return(oNS);
        }