WriteException() public static method

Write an exceptiong to the local app data folder for the current user
public static WriteException ( Exception ex ) : void
ex System.Exception Exception object containing information about the error.
return void
Esempio n. 1
0
        private void LoadNasaImageList(int pageNumber)
        {
            try
            {
                if (pageNumber < 0)
                {
                    pageNumber          = 0;
                    _currentImageNumber = 0;
                    _displayImageNumber = 0;
                }

                _images = JsonHelper.DownloadSerializedJsonData(string.Format(NasaLatestImagesUrl, pageNumber));
                if (_images == null)
                {
                    throw new Exception("Unable to retrieve the image data");
                }

                _totalDocImageCount = Convert.ToInt32(_images.Meta.TotalRows);
            }
            catch (Exception ex)
            {
                ExceptionManager.WriteException(ex);
                throw;
            }
        }
Esempio n. 2
0
        public static bool DownloadImage(string targetDirectory, string sourceUrl)
        {
            if (targetDirectory == null)
            {
                throw new ArgumentNullException("targetDirectory");
            }
            if (sourceUrl == null)
            {
                throw new ArgumentNullException("sourceUrl");
            }
            try
            {
                using (var client = new WebClient())
                {
                    client.DownloadFile(sourceUrl, targetDirectory);
                }
                if (GlobalVariables.LoggingEnabled)
                {
                    ExceptionManager.WriteInformation("Image download completed");
                }

                return(true);
            }
            catch (Exception ex)
            {
                ExceptionManager.WriteException(ex);
                return(false);
            }
        }
Esempio n. 3
0
        public static bool UpdateIsAvailable()
        {
            //Read in the XML file
            var configDocument = new XmlDocument();

            try
            {
                configDocument.Load(ServerConfigFilePath);
            }
            catch (Exception ex)
            {
                if (GlobalVariables.LoggingEnabled)
                {
                    ExceptionManager.WriteInformation("An error occurred while checking for the update.");
                }
                ExceptionManager.WriteException(ex);
                return(false);
            }

            //Extract configuration/applicationSettings/NasaPicOfDay.Properties.Settings/setting
            var settingNode =
                configDocument.SelectSingleNode(
                    "/configuration/applicationSettings/NasaPicOfDay.Properties.Settings/setting[@name='CurrentVersion']/value");

            if (settingNode == null)
            {
                return(false);
            }

            var versionStrings = settingNode.InnerText.Split('.');

            Int32.TryParse(versionStrings[0], out _serverMajorVersion);
            Int32.TryParse(versionStrings[1], out _serverMinorVersion);
            Int32.TryParse(versionStrings[2], out _serverBuildNumber);

            if (GlobalVariables.LoggingEnabled)
            {
                ExceptionManager.WriteInformation(string.Format("Application version on GIT {0}.{1}.{2}", _serverMajorVersion, _serverMinorVersion, _serverBuildNumber));
                ExceptionManager.WriteInformation(string.Format("Application version on this machine {0}.{1}.{2}", GlobalVariables.CurrentMajorVersion, GlobalVariables.CurrentMinorVersion, GlobalVariables.CurrentBuildNumber));
            }

            //Compare against global variables for version
            if (GlobalVariables.CurrentMajorVersion < _serverMajorVersion)
            {
                //Update is required
                return(true);
            }
            //Need to check other fields
            if (GlobalVariables.CurrentMinorVersion < _serverMinorVersion)
            {
                //Update is required
                return(true);
            }

            //Need to check the other fields
            return(GlobalVariables.CurrentBuildNumber < _serverBuildNumber);
        }
Esempio n. 4
0
        private void LoadApplicationContent()
        {
            try
            {
                components        = new Container();
                _contextMenu1     = new ContextMenu();
                _detailsMenuItem  = new MenuItem();
                _exitMenuItem     = new MenuItem();
                _updateMenuItem   = new MenuItem();
                _imagesMenuItem   = new MenuItem();
                _settingsMenuItem = new MenuItem();
                // Create the NotifyIcon.
                _notifyIcon1 = new NotifyIcon(components)
                {
                    Icon = new Icon("world.ico"), ContextMenu = _contextMenu1
                };

                // Handle the DoubleClick event to activate the form.
                _notifyIcon1.DoubleClick += notifyIcon1_DoubleClick;

                UpdateContent();

                // Initialize contextMenu1
                _contextMenu1.MenuItems.AddRange(
                    new[] { _imagesMenuItem, _updateMenuItem, _detailsMenuItem, _settingsMenuItem, _exitMenuItem });

                //Initialize imagesMenuItme
                _imagesMenuItem.Index  = 0;
                _imagesMenuItem.Text   = Resources.ImagesLabel;
                _imagesMenuItem.Click += imagesMenuItem_Click;
                // Initialize updateMenuItem
                _updateMenuItem.Index  = 1;
                _updateMenuItem.Text   = Resources.UpdateLabel;
                _updateMenuItem.Click += updateMenuItem_Click;
                // Initialize detailsMenuItem
                _detailsMenuItem.Index  = 2;
                _detailsMenuItem.Text   = Resources.SeeDetailsLabel;
                _detailsMenuItem.Click += detailsMenuItem_Click;
                //initialize settingsMenuItem
                _settingsMenuItem.Index  = 3;
                _settingsMenuItem.Text   = Resources.SettingsLabel;
                _settingsMenuItem.Click += settingsMenuItem_Click;
                // Initialize exitMenuItem
                _exitMenuItem.Index  = 4;
                _exitMenuItem.Text   = Resources.ExitLabel;
                _exitMenuItem.Click += exitMenuItem_Click;

                // Set up how the form should be displayed.
                TopMost = true;
            }
            catch (Exception ex)
            {
                ExceptionManager.WriteException(ex);
            }
        }
Esempio n. 5
0
        public PicofDay()
        {
            InitializeComponent();

            try
            {
                //Creating a timer to retrieve the latest image once a day.
                //We did it this way to avoid setting up a scheduled task on the user's machine.
                _appTimer = new Timer();

                //Checking for updates at 12 p.m. EST (GMT-5) everyday
                if (GlobalVariables.LoggingEnabled)
                {
                    ExceptionManager.WriteInformation("Checking the system time for 12 p.m. EST update.");
                }

                //Setting the current UTC time
                DateTime utcNow = DateTime.UtcNow;
                if (GlobalVariables.LoggingEnabled)
                {
                    ExceptionManager.WriteInformation(string.Format("Current UTC time is [Hours:{0}, Minutes:{1}, Seconds:{2}]", utcNow.Hour, utcNow.Minute, utcNow.Second));
                }
                DateTime updateTime = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 17, 0, 0);

                //Get the amount of time between now and 12 p.m. EST
                TimeSpan timeUntilEst12Pm = utcNow - updateTime;
                if (GlobalVariables.LoggingEnabled)
                {
                    ExceptionManager.WriteInformation(string.Format("Time until 12 p.m. EST [Hours:{0}, Minutes:{1}, Seconds:{2}]", Math.Abs(timeUntilEst12Pm.Hours), Math.Abs(timeUntilEst12Pm.Minutes), Math.Abs(timeUntilEst12Pm.Seconds)));
                }

                //set the interval for the timer
                _appTimer.Interval = Math.Abs((int)timeUntilEst12Pm.TotalMilliseconds);
                if (GlobalVariables.LoggingEnabled)
                {
                    ExceptionManager.WriteInformation(string.Format("Next update will occur in [Hours:{0}, Minutes:{1}, Seconds:{2}]", Math.Abs(timeUntilEst12Pm.Hours), Math.Abs(timeUntilEst12Pm.Minutes), Math.Abs(timeUntilEst12Pm.Seconds)));
                }
                _appTimer.Tick += appTimer_Tick;

                //Launch the main part of the data retrieval
                LoadApplicationContent();
                //Start the application timer
                _appTimer.Start();
            }
            catch (Exception ex)
            {
                ExceptionManager.WriteException(ex);
            }
        }
Esempio n. 6
0
        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                // Show the form when the user double clicks on the notify icon.
                // Set the WindowState to normal if the form is minimized.
                if (WindowState == FormWindowState.Minimized)
                {
                    WindowState = FormWindowState.Normal;
                }

                // Activate the form.
                Visible = true;
                Activate();
            }
            catch (Exception ex)
            {
                ExceptionManager.WriteException(ex);
            }
        }
Esempio n. 7
0
        public static bool InternetAccessIsAvailable()
        {
            const string url = "http://www.nasa.gov";

            try
            {
                if (GlobalVariables.LoggingEnabled)
                {
                    ExceptionManager.WriteInformation("Building internet connectivity request.");
                }
                WebRequest myRequest = WebRequest.Create(url);
                //a 10 second timeout to limit the request attempt
                myRequest.Timeout = 10000;
                if (GlobalVariables.LoggingEnabled)
                {
                    ExceptionManager.WriteInformation("Starting request.");
                }
                using (WebResponse myResponse = myRequest.GetResponse())
                {
                    if (GlobalVariables.LoggingEnabled)
                    {
                        ExceptionManager.WriteInformation(myResponse.ToString());
                    }
                    myResponse.Close();
                    if (GlobalVariables.LoggingEnabled)
                    {
                        ExceptionManager.WriteInformation("Request completed.");
                    }
                    return(true);
                }
            }
            catch (WebException wex)
            {
                if (GlobalVariables.LoggingEnabled)
                {
                    ExceptionManager.WriteInformation(string.Format("Error occurred checking internet connection:\t{0}", wex.Message));
                }
                ExceptionManager.WriteException(wex);
                return(false);
            }
        }
Esempio n. 8
0
        public static NasaImages DownloadSerializedJsonData(string nasaUrl)
        {
            try
            {
                using (var client = new WebClient())
                {
                    var jsonData = client.DownloadString(nasaUrl);

                    if (!string.IsNullOrEmpty(jsonData))
                    {
                        var images = JsonConvert.DeserializeObject <NasaImages>(jsonData);
                        return(images);
                    }

                    throw new Exception("Unable to retrieve JSON data");
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.WriteException(ex);
                return(null);
            }
        }
Esempio n. 9
0
        public static ImageNode DownloadImageData(string imageUrl)
        {
            try
            {
                using (var client = new WebClient())
                {
                    var jsonData = client.DownloadString(imageUrl);

                    if (!string.IsNullOrEmpty(jsonData))
                    {
                        var image = JsonConvert.DeserializeObject <ImageNode>(jsonData);
                        return(image);
                    }

                    throw new Exception("Unable to retrieve JSON data for image.");
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.WriteException(ex);
                return(null);
            }
        }
Esempio n. 10
0
 /// <summary>
 /// Set the desktop to the current picture of the day
 /// <param name="fileName">Full file path to the image to set as the desktop background.</param>
 /// </summary>
 public void SetDesktopBackground(string fileName)
 {
     try
     {
         if (GlobalVariables.LoggingEnabled)
         {
             ExceptionManager.WriteInformation("Preparing to change desktop background");
         }
         SystemParametersInfo(SpiSetdeskwallpaper, 0, fileName, SpifUpdateinifile);
         if (GlobalVariables.LoggingEnabled)
         {
             ExceptionManager.WriteInformation("Completed desktop background change");
         }
     }
     catch (Exception ex)
     {
         if (GlobalVariables.LoggingEnabled)
         {
             ExceptionManager.WriteInformation("An error occurred updating the desktop background.");
         }
         ExceptionManager.WriteException(ex);
     }
 }
Esempio n. 11
0
        private bool GetImageThumbnail(int imagePosition)
        {
            try
            {
                if (_images == null)
                {
                    LoadNasaImageList(_currentPage);
                }

                if (imagePosition < 0)
                {
                    throw new Exception("Invalid image position.");
                }
                if (_images == null || _images.UberNodes.Length < 0)
                {
                    throw new Exception("Image collection error. No images retrieved.");
                }

                var imageId = _images.UberNodes[imagePosition].UberNodeId;

                var imageDatalUrl = string.Format("{0}{1}.json", NasaApiUrl, imageId);

                var currentImage = JsonHelper.DownloadImageData(imageDatalUrl);
                if (currentImage == null)
                {
                    throw new Exception(string.Format("Error retrieving image: {0}", imageDatalUrl));
                }

                var fileName = currentImage.ImageData[0].FileName;

                var localFileSystemThumbNailDirectory = string.Format("{0}\\NASA\\PicOfTheDay\\Thumbnails", Environment.GetFolderPath(Environment.SpecialFolder.MyPictures));

                if (!Directory.Exists(localFileSystemThumbNailDirectory))
                {
                    Directory.CreateDirectory(localFileSystemThumbNailDirectory);
                }

                var localFileSystemImagePath = string.Format("{0}\\{1}", localFileSystemThumbNailDirectory, fileName);

                var thumbnailUrl = string.Format("{0}{1}", NasaImageBaseUrl, currentImage.ImageData[0].LrThumbnail);

                //If the thumbnail has been previously downloaded, no need to download it again, just use the current one
                if (!File.Exists(localFileSystemImagePath))
                {
                    if (!DownloadHelper.DownloadImage(localFileSystemImagePath, thumbnailUrl))
                    {
                        throw new Exception("Error downloading image.");
                    }
                }

                picBoxCurrentImg.ImageLocation = localFileSystemImagePath;
                picBoxCurrentImg.SizeMode      = PictureBoxSizeMode.Zoom;

                return(true);
            }
            catch (Exception ex)
            {
                ExceptionManager.WriteException(ex);
                return(false);
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Overloaded GetImage that allows the retrieval of previous images based on their position in the XML document
        /// provided from the nasa.gov website.
        /// </summary>
        /// <param name="selectedOffset">Position of the image within the node list of images, 1 being the very first (newest)</param>
        /// <param name="selectedPage">Page number to retrieve the page that contains the selected image.</param>
        public BackgroundImage GetImage(int?selectedOffset, int?selectedPage)
        {
            try
            {
                if (!NetworkHelper.InternetAccessIsAvailable())
                {
                    throw new Exception("Attempted to retrieve image, but internet connection was not available.");
                }

                if (GlobalVariables.LoggingEnabled)
                {
                    ExceptionManager.WriteInformation("Retrieving system screen resolution");
                }
                GetCurrentScreenResolution();
                if (GlobalVariables.LoggingEnabled)
                {
                    ExceptionManager.WriteInformation(string.Format("System screen resolution is: {0}", _currentScreenResolution));
                }

                if (selectedOffset == null)
                {
                    selectedOffset = DefaultimageOffset;
                }

                //Get the JSON string data
                if (GlobalVariables.LoggingEnabled)
                {
                    ExceptionManager.WriteInformation("Preparing to download image information");
                }
                var nasaImages = JsonHelper.DownloadSerializedJsonData(string.Format(NasaLatestImagesUrl, selectedPage));
                if (nasaImages == null || nasaImages.UberNodes.Length == 0)
                {
                    throw new Exception("Unable to retrieve image data from JSON request");
                }

                //Get the image node
                var imageId = nasaImages.UberNodes[(int)selectedOffset].UberNodeId;

                var currentImageFullUrl = string.Format("{0}{1}.json", NasaApiUrl, imageId);

                var currentImage = JsonHelper.DownloadImageData(currentImageFullUrl);
                if (currentImage == null)
                {
                    throw new Exception(string.Format("Unable to retrieve selected image: {0}", currentImageFullUrl));
                }

                if (GlobalVariables.LoggingEnabled)
                {
                    ExceptionManager.WriteInformation("Selecting image based on current screen resolution");
                }
                switch (_currentScreenResolution)
                {
                case "100x75":
                case "226x170":
                    currentImageFullUrl = string.Format("{0}{1}", NasaImageBaseUrl, currentImage.ImageData[0].LrThumbnail);
                    break;

                case "346x260":
                case "360x225":
                case "466x248":
                case "430x323":
                    currentImageFullUrl = string.Format("{0}{1}", NasaImageBaseUrl, currentImage.ImageData[0].Crop1X1);
                    break;

                case "800x600":
                    currentImageFullUrl = string.Format("{0}{1}", NasaImageBaseUrl, currentImage.ImageData[0].Crop2X1);
                    break;

                default:
                    currentImageFullUrl = string.Format("{0}{1}", NasaImageBaseUrl, currentImage.ImageData[0].FullWidthFeature);
                    break;
                }

                var localImageFolderPath = string.Format("{0}\\NASA\\PicOfTheDay", Environment.GetFolderPath(Environment.SpecialFolder.MyPictures));

                if (!Directory.Exists(localImageFolderPath))
                {
                    Directory.CreateDirectory(localImageFolderPath);
                }

                var imageName = currentImage.ImageData[0].FileName;

                //Setting the full local image path to save the file
                var fullImagePath = string.Format("{0}\\{1}", localImageFolderPath, imageName);

                //Download the current image
                if (GlobalVariables.LoggingEnabled)
                {
                    ExceptionManager.WriteInformation(string.Format("Preparing to download image: {0}", currentImageFullUrl));
                }
                if (!DownloadHelper.DownloadImage(fullImagePath, currentImageFullUrl))
                {
                    throw new Exception("Error downloading current image.");
                }

                //Create BackgroundImage object
                var backgroundImage = new BackgroundImage
                {
                    ImageUrl         = currentImageFullUrl,
                    ImageDate        = Convert.ToDateTime(currentImage.UberData.PromoDateTime),
                    ImageDescription = StripHtml(currentImage.UberData.Body),
                    DownloadedPath   = fullImagePath,
                    ImageTitle       =
                        !string.IsNullOrEmpty(currentImage.ImageData[0].Title)
                     ? currentImage.ImageData[0].Title
                     : currentImage.UberData.Title
                };

                return(backgroundImage);
            }
            catch (Exception ex)
            {
                ExceptionManager.WriteException(ex);
                return(null);
            }
        }