예제 #1
0
 /// <summary>
 /// Requires that the given state is valid (i.e., true).
 /// </summary>
 /// <param name="state">The state to check.</param>
 /// <param name="explanation">The explanation to put in the exception.</param>
 /// <exception cref="InvalidOperationException">If <paramref name="state"/> is false.</exception>
 public static void RequireState([DoesNotReturnIf(false)] bool state, string explanation)
 {
     if (!state)
     {
         throw Exceptions.NewInvalidOperationException(explanation);
     }
 }
예제 #2
0
        public void Save()
        {
            bool saved = false;
            Dictionary <string, object> errorLogProperties = new();

            foreach (string fileName in GetPotentialFileNames())
            {
                try
                {
                    // Make sure the directory we're trying to save to actually exists.
                    string?directoryName = Path.GetDirectoryName(fileName);
                    if (!string.IsNullOrEmpty(directoryName))
                    {
                        Directory.CreateDirectory(directoryName);
                    }

                    if (File.Exists(fileName))
                    {
                        // Make sure the file isn't hidden, so XElement.Save can write to it.
                        File.SetAttributes(fileName, File.GetAttributes(fileName) & ~FileAttributes.Hidden);
                    }

                    // Attempt to save the file.
                    this.root.Save(fileName);
                    saved = true;

                    // Hide the file from normal listings since we'll be creating files for each user.
                    File.SetAttributes(fileName, File.GetAttributes(fileName) | FileAttributes.Hidden);
                    break;
                }
                catch (IOException inputOutputEx)
                {
                    errorLogProperties.Add(fileName, inputOutputEx);
                }
                catch (SecurityException securityEx)
                {
                    errorLogProperties.Add(fileName, securityEx);
                }
                catch (UnauthorizedAccessException accessEx)
                {
                    errorLogProperties.Add(fileName, accessEx);
                }
            }

            if (!saved)
            {
                const string Message = "Unable to save the user settings to a file store.";

                // Log out the exceptions first since we can't pass those additional
                // details into the new exception we're throwing.
                Log.Error(typeof(FileSettingsStore), Message, null, errorLogProperties);
                throw Exceptions.NewInvalidOperationException(Message);
            }
        }