Exemplo n.º 1
0
        /// <summary>
        /// This method composes and shows an error Messages to the user, if some necessary
        /// file couldn't be found.
        /// </summary>
        /// <param name="headMessage">This string should explain where this error occured.</param>
        /// <param name="exception">The actual exception that has been caught by the controller.</param>
        protected void ReportFileNotFoundErrorMessage(string headMessage, System.IO.FileNotFoundException exception)
        {
            StringBuilder builder = new StringBuilder();

            builder.AppendLine(headMessage);
            builder.AppendFormat(Messages.ErrorFileNotFoundWithName, exception.FileName);
        }
        private static bool IsExceptionKnown(Exception ex)
        {
            System.Threading.ThreadAbortException threadAbortException = ex as System.Threading.ThreadAbortException;
            if (null != threadAbortException)
            {
                return(true);
            }

            System.Messaging.MessageQueueException messageQueueException = ex as System.Messaging.MessageQueueException;
            if (null != messageQueueException && messageQueueException.MessageQueueErrorCode == System.Messaging.MessageQueueErrorCode.IOTimeout)
            {
                return(true);
            }

            System.Xml.XmlException xmlException = ex as System.Xml.XmlException;
            if (null != xmlException && xmlException.Message.StartsWith("Name cannot begin with the '<' character"))
            {
                return(true);
            }

            System.IO.FileNotFoundException fileNotFoundException = ex as System.IO.FileNotFoundException;
            if (null != fileNotFoundException &&
                null != fileNotFoundException.FileName &&
                fileNotFoundException.FileName.Contains("XmlSerializers"))
            {
                return(true);
            }

            return(false);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Funcion para obtener la cadena con los errores de una excepcion de carga de tipos
        /// </summary>
        /// <param name="_exception">_excepcion de carga de tipos</param>
        /// <returns>Cadena con el error de carga de tipos</returns>
        private static string _getReflectionTypeLoadException(System.Reflection.ReflectionTypeLoadException _exception)
        {
            System.Text.StringBuilder sb = new StringBuilder();

            // recorrer todas las excepciones de carga de ensamblado
            foreach (Exception exSub in _exception.LoaderExceptions)
            {
                // añadir mensaje de excepcion
                sb.AppendLine(exSub.Message);

                // en caso de ser una excepcion de ensamblado no encontrado, se añade el error
                if (exSub is System.IO.FileNotFoundException)
                {
                    System.IO.FileNotFoundException exFileNotFound = exSub as System.IO.FileNotFoundException;
                    if (exFileNotFound != null && !string.IsNullOrEmpty(exFileNotFound.FusionLog))
                    {
                        sb.AppendLine("Fusion Log:");
                        sb.AppendLine(exFileNotFound.FusionLog);
                    }
                }

                sb.AppendLine();
            }

            // retornar cadena con la excepcion
            return(sb.ToString());
        }
Exemplo n.º 4
0
 public static void DllNotFound(string dll, System.IO.FileNotFoundException e)
 {
     ShowError(
         Application.ProductName,
         Resources.Errors.DllNotFound,
         dll);
 }
Exemplo n.º 5
0
 public void Load_FileSystemPath_FileNotFound()
 {
     System.IO.FileNotFoundException ex = Assert.Throws <System.IO.FileNotFoundException>(
         () =>
     {
         Image.Load <Rgba32>(Guid.NewGuid().ToString());
     });
 }
Exemplo n.º 6
0
 public void ConstructorFileSystem_FileNotFound()
 {
     System.IO.FileNotFoundException ex = Assert.Throws <System.IO.FileNotFoundException>(
         () =>
     {
         new Image(Guid.NewGuid().ToString());
     });
 }
 public void WhenFileNotFound_Throws()
 {
     System.IO.FileNotFoundException ex = Assert.Throws <System.IO.FileNotFoundException>(
         () =>
     {
         Image.Load <Rgba32>(this.TopLevelConfiguration, Guid.NewGuid().ToString());
     });
 }
Exemplo n.º 8
0
 // A generic file not found message.
 public static void FileNotFound(System.IO.FileNotFoundException e)
 {
     ShowError(
         Application.ProductName,
         Resources.Errors.FileNotFound,
         e.FileName,
         e.Message,
         "\n\n");
 }
Exemplo n.º 9
0
        public void FileNotFoundExceptionĆeBitiUhvaćenKaoException()
        {
            Assert.IsTrue(ProvjeriCatchBlokove());

            Exception e = new System.IO.FileNotFoundException();

            Iznimke.VišestrukiBlokoviCatch.HvatanjeIznimkePremaTipu(e);
            Assert.AreEqual(string.Format(Iznimke.VišestrukiBlokoviCatch.FormatFiltraException, e.GetType().Name), cw.GetString());
        }
Exemplo n.º 10
0
        /// <summary>Integrates Unity when the application starts.</summary>
        public static void Start()
        {
            var container = ContainerManager.GetConfiguredContainer();

            UnityConfig.RegisterTypes(container);

            FilterProviders.Providers.Remove(FilterProviders.Providers.OfType <FilterAttributeFilterProvider>().First());
            FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));

            var assemblies = AppDomain.CurrentDomain.GetAssemblies();

            try
            {
                //http://stackoverflow.com/questions/699852/how-to-find-all-the-classes-which-implement-a-given-interface
                foreach (var assembly in assemblies)
                {
                    var instances = from t in assembly.GetTypes()
                                    where t.GetInterfaces().Contains(typeof(IDependencyRegister)) &&
                                    t.GetConstructor(Type.EmptyTypes) != null
                                    select Activator.CreateInstance(t) as IDependencyRegister;

                    foreach (var instance in instances.OrderBy(x => x.Order))
                    {
                        instance.Register(container);
                    }
                }
            }
            catch (ReflectionTypeLoadException ex)
            {
http:           //stackoverflow.com/questions/1091853/error-message-unable-to-load-one-or-more-of-the-requested-types-retrieve-the-l
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                foreach (Exception exSub in ex.LoaderExceptions)
                {
                    sb.AppendLine(exSub.Message);
                    System.IO.FileNotFoundException exFileNotFound = exSub as System.IO.FileNotFoundException;
                    if (exFileNotFound != null)
                    {
                        if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
                        {
                            sb.AppendLine("Fusion Log:");
                            sb.AppendLine(exFileNotFound.FusionLog);
                        }
                    }
                    sb.AppendLine();
                }
                string errorMessage = sb.ToString();

                throw new Exception(errorMessage, ex);
                //Display or log the error based on your application.
            }


            // TODO: Uncomment if you want to use PerRequestLifetimeManager
            // Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
        }
Exemplo n.º 11
0
        protected bool CheckFileExists(string file)
        {
            if (System.IO.File.Exists(file)) return true;

            this.WriteVerbose("Filename: {0}", file);
            this.WriteVerbose("Abs Filename: {0}", System.IO.Path.GetFullPath(file));
            var exc = new System.IO.FileNotFoundException(file);
            var er = new SMA.ErrorRecord(exc, "FILE_NOT_FOUND", SMA.ErrorCategory.ResourceUnavailable, null);
            this.WriteError(er);
            return false;
        }
Exemplo n.º 12
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="path">Assumes fully resolved path.</param>
 /// <param name="checkPath">Throws exception if file does not exist upon construction</param>
 public ImageObj( string path, bool checkPath )
 {
     this.s_fullpath = path;
     if ( checkPath )
     {
         if ( !System.IO.File.Exists( path ) )
         {
             var ex = new System.IO.FileNotFoundException( string.Format( "image file {0} does not exist and checkPath is set", path ) );
             log.Error( ex, ex.Message );
             throw ex;
         }
     }
 }
Exemplo n.º 13
0
 protected bool CheckFileExists(string file)
 {
     if (!System.IO.File.Exists(file))
     {
         this.WriteVerbose("Filename: {0}",file);
         this.WriteVerbose("Abs Filename: {0}", System.IO.Path.GetFullPath(file));
         var exc = new System.IO.FileNotFoundException(file);
         var er = new SMA.ErrorRecord(exc, "FILE_NOT_FOUND", SMA.ErrorCategory.ResourceUnavailable, null);
         this.WriteError(er);
         return false;
     }
     return true;
 }
Exemplo n.º 14
0
        public static string FormatLoaderException(Exception pluginEx)
        {
            string sException = "";

            sException += string.Format("BIDS Helper encountered an error when Visual Studio started:\r\n{0}\r\n{1}"
                                        , pluginEx.Message
                                        , pluginEx.StackTrace);

            Exception innerEx = pluginEx.InnerException;

            while (innerEx != null)
            {
                sException += string.Format("\r\nInner exception:\r\n{0}\r\n{1}"
                                            , innerEx.Message
                                            , innerEx.StackTrace);
                innerEx = innerEx.InnerException;
            }

            ReflectionTypeLoadException ex = pluginEx as ReflectionTypeLoadException;

            if (ex == null)
            {
                ex = pluginEx.InnerException as ReflectionTypeLoadException;
            }
            if (ex != null)
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                foreach (Exception exSub in ex.LoaderExceptions)
                {
                    sb.AppendLine();
                    sb.AppendLine(exSub.GetType().FullName);
                    sb.AppendLine(exSub.Message);
                    sb.AppendLine(exSub.StackTrace);
                    System.IO.FileNotFoundException exFileNotFound = exSub as System.IO.FileNotFoundException;
                    if (exFileNotFound != null)
                    {
                        if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
                        {
                            sb.AppendLine("Fusion Log:");
                            sb.AppendLine(exFileNotFound.FusionLog);
                        }
                        sb.AppendLine(string.Format("Source: {0}", exFileNotFound.Source));
                        sb.AppendLine(string.Format("TargetSite: {0}", exFileNotFound.TargetSite));
                    }
                    sb.AppendLine();
                }
                sException += sb.ToString();
            }
            return(sException);
        }
        public async Task <IActionResult> Delete()
        {
            Exception newEx = new System.IO.FileNotFoundException();

            _logger.LogError(newEx, newEx.Message);
            // try
            // {
            //     throw new Exception("oops! something went wrong!?");
            // }
            // catch (Exception ex)
            // {
            //     _logger.LogError(ex, "Error Found!");
            // }

            return(new BadRequestResult());
        }
Exemplo n.º 16
0
 /// <summary>
 /// Strips html tags from Tags property and characters from Characters property from the file at inputFileName and writes to the file at outputFileName
 /// </summary>
 /// <param name="inputFileName">An html file to be stripped</param>
 /// <param name="outputFileName">The output file for the stripped html</param>
 /// <param name="encoding">The encoding of the input and output files</param>
 /// <exception cref="System.IO.FileNotFoundException">Thrown when input file does not exist</exception>
 /// <returns>True if operation was successful</returns>
 /// <remarks>If one of the elements in Characters has the same key and value, will loop infinitely.</remarks>
 public bool StripFile(string inputFileName, string outputFileName, Encoding encoding)
 {
     if (System.IO.File.Exists(inputFileName))
     {
         HtmlDocument inputDocument = GetInputDocument(inputFileName);
         StripTags(inputDocument);
         StripCharacters(inputDocument);
         WriteOutput(inputDocument, outputFileName, inputDocument.Encoding);
         return(true);
     }
     else
     {
         System.IO.FileNotFoundException fileEx = new System.IO.FileNotFoundException("Input file does not exist", inputFileName);
         throw fileEx;
     }
 }
Exemplo n.º 17
0
        //public static void TestSimpleEmail(IAuditEventRepository auditEventRepository)
        //{
        //    Email email = new Email()
        //    {
        //        Subject = "Test email",
        //        Body = "<html><head></head><body>Test email from xG Gameplan</body></html>",
        //        Sender = "*****@*****.**",
        //        SenderDisplay = "NextGen",
        //        RecipientList = { "*****@*****.**" }
        //    };
        //    AuditEvent auditEvent = AuditEventFactory.CreateAuditEventForSimpleEmail(0, 0, email);
        //    auditEventRepository.Insert(auditEvent);
        //}

        public static void TestException(IAuditEventRepository auditEventRepository)
        {
            try
            {
                // Generate exception
                int divisor = 0;
                int result  = 10 / divisor;
            }
            catch (System.Exception exception)
            {
                // Create new exception with other exception as inner exception
                System.Exception exception2 = new System.IO.FileNotFoundException("Test exception", exception);
                exception2.Data.Add("Data1", 10);
                exception2.Data.Add("Data2", DateTime.UtcNow);
                exception2.Data.Add("Data3", "ABC");
                AuditEvent auditEvent2 = AuditEventFactory.CreateAuditEventForException(0, 0, "Test", exception2);
                auditEventRepository.Insert(auditEvent2);
            }
        }
        static void Main(string[] args)
        {
            System.IO.IOException           get           = new System.IO.IOException("get some help");
            System.IO.IOException           bad           = new System.IO.IOException("Stop it!", get);
            System.IO.FileNotFoundException notFound      = new System.IO.FileNotFoundException("Cannot fing", "Mongo.js", get);
            ApplicationException            badAplication = new ApplicationException("The site is trash", get);

            Console.WriteLine(bad.InnerException.Message);
            System.FormatException k = new System.FormatException("Invalid number");
            try
            {
                int num = int.Parse(Console.ReadLine());
                num = (int)Math.Sqrt(num);
                Console.WriteLine(num);
            }

            finally
            {
                Console.WriteLine("Good bye!");
            }
        }
Exemplo n.º 19
0
        static object QryServers(IQueryCollection query, ConnectionInfo connection, string ConxString)
        {
            object jsonObject;

            try
            {
                if (System.IO.File.Exists(ServerFileString))
                {
                    string allText = System.IO.File.ReadAllText(ServerFileString);
                    jsonObject = JsonConvert.DeserializeObject(allText);
                }
                else
                {
                    jsonObject = new System.IO.FileNotFoundException("Server File not found");
                }
            }
            catch (Exception ex)
            {
                jsonObject = ex; // JsonConvert.DeserializeObject(allText);
            }
            return(jsonObject);
        }
Exemplo n.º 20
0
        private void BIDSHelperOptionsVersionCheckPage_Load(object sender, EventArgs e)
        {
            try
            {
                // Get title from assembly info, e.g. "BIDS Helper for SQL 2008"
                Assembly assembly = this.GetType().Assembly;
                AssemblyTitleAttribute attribute = (AssemblyTitleAttribute)AssemblyTitleAttribute.GetCustomAttribute(assembly, typeof(AssemblyTitleAttribute));
                this.lblTitle.Text = attribute.Title;

                // Conditionally select name, BIDS vs SSDBI - Retained as suspsect BI will be dropped shortly
                string bidsName = "SSDTBI";

                if (BIDSHelperPackage.AddInLoadException != null)
                {
                    this.lblBidsHelperLoadException.Text = string.Format("BIDS Helper encountered an error when Visual Studio started:\r\n{0}\r\n{1}"
                                                                         , BIDSHelperPackage.AddInLoadException.Message
                                                                         , BIDSHelperPackage.AddInLoadException.StackTrace);

                    Exception innerEx = BIDSHelperPackage.AddInLoadException.InnerException;
                    while (innerEx != null)
                    {
                        this.lblBidsHelperLoadException.Text += string.Format("\r\nInner exception:\r\n{0}\r\n{1}"
                                                                              , innerEx.Message
                                                                              , innerEx.StackTrace);
                        innerEx = innerEx.InnerException;
                    }

                    ReflectionTypeLoadException ex = BIDSHelperPackage.AddInLoadException as ReflectionTypeLoadException;
                    if (ex == null)
                    {
                        ex = BIDSHelperPackage.AddInLoadException.InnerException as ReflectionTypeLoadException;
                    }
                    if (ex == null && BIDSHelperPackage.AddInLoadException.InnerException != null)
                    {
                        ex = BIDSHelperPackage.AddInLoadException.InnerException.InnerException as ReflectionTypeLoadException;
                    }
                    if (ex != null)
                    {
                        System.Text.StringBuilder sb = new System.Text.StringBuilder();
                        foreach (Exception exSub in ex.LoaderExceptions)
                        {
                            sb.AppendLine();
                            sb.AppendLine(exSub.Message);
                            System.IO.FileNotFoundException exFileNotFound = exSub as System.IO.FileNotFoundException;
                            if (exFileNotFound != null)
                            {
                                if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
                                {
                                    sb.AppendLine("Fusion Log:");
                                    sb.AppendLine(exFileNotFound.FusionLog);
                                }
                            }
                            sb.AppendLine();
                        }
                        this.lblBidsHelperLoadException.Text += sb.ToString();
                    }

                    this.lblBidsHelperLoadException.Visible = true;
                    this.btnCopyError.Visible = true;
                }
                else
                {
                    this.lblBidsHelperLoadException.Visible = false;
                    this.btnCopyError.Visible = false;
                }

                try
                {
                    this.lblSqlVersion.Text = string.Format("{0} {1} ({2}) for Visual Studio {3} was detected", bidsName, VersionInfo.SqlServerFriendlyVersion, VersionInfo.SqlServerVersion, VersionInfo.VisualStudioFriendlyVersion);
                }
                catch
                {
                    //if there's an exception it's because we couldn't find SSDTBI or BIDS installed in this Visual Studio version
                    try
                    {
                        this.lblSqlVersion.Text      = bidsName + " for Visual Studio " + VersionInfo.VisualStudioFriendlyVersion + " was NOT detected. BIDS Helper disabled.";
                        this.lblSqlVersion.ForeColor = System.Drawing.Color.Red;
                        if (BIDSHelperPackage.AddInLoadException != null && BIDSHelperPackage.AddInLoadException is System.Reflection.ReflectionTypeLoadException)
                        {
                            //this is the expected exception if SSDTBI isn't installed... if this is the exception, don't show it... otherwise, show the exception
                            this.lblBidsHelperLoadException.Visible = false;
                        }
                    }
                    catch
                    {
                        this.lblSqlVersion.Visible = false;
                    }
                }

                // Set current version
                this.lblLocalVersion.Text = VersionCheckPlugin.LocalVersion;
#if DEBUG
                DateTime buildDateTime = GetBuildDateTime(assembly);
                this.lblLocalVersion.Text += string.Format(CultureInfo.InvariantCulture, " (Debug Build {0:yyyy-MM-dd HH:mm:ss})", buildDateTime);
#endif

                this.lblSqlVersion.Text += string.Format("\r\nSSDT Extensions Installed: SSAS ({0}), SSIS ({1}), SSRS ({2})",
                                                         (BIDSHelperPackage.SSASExtensionVersion == null ? "N/A" : BIDSHelperPackage.SSASExtensionVersion.ToString()),
                                                         (BIDSHelperPackage.SSISExtensionVersion == null ? "N/A" : BIDSHelperPackage.SSISExtensionVersion.ToString()),
                                                         (BIDSHelperPackage.SSRSExtensionVersion == null ? "N/A" : BIDSHelperPackage.SSRSExtensionVersion.ToString()));

                //the current BI Developer Extensions version is compatible with the following versions or higher of SSDT extensions
                Version SSASExpectedVersion = new Version("2.8.15");
                Version SSRSExpectedVersion = new Version("2.5.9");
                Version SSISExpectedVersion = new Version("2.1");

                string sUpgradeSSDTMessage = string.Empty;
                if (BIDSHelperPackage.SSASExtensionVersion != null && BIDSHelperPackage.SSASExtensionVersion < SSASExpectedVersion)
                {
                    if (sUpgradeSSDTMessage != string.Empty)
                    {
                        sUpgradeSSDTMessage += ", ";
                    }
                    sUpgradeSSDTMessage += "SSAS to " + SSASExpectedVersion;
                }
                if (BIDSHelperPackage.SSRSExtensionVersion != null && BIDSHelperPackage.SSRSExtensionVersion < SSRSExpectedVersion)
                {
                    if (sUpgradeSSDTMessage != string.Empty)
                    {
                        sUpgradeSSDTMessage += ", ";
                    }
                    sUpgradeSSDTMessage += "SSRS to " + SSRSExpectedVersion;
                }
                if (BIDSHelperPackage.SSISExtensionVersion != null && BIDSHelperPackage.SSISExtensionVersion < SSISExpectedVersion)
                {
                    if (sUpgradeSSDTMessage != string.Empty)
                    {
                        sUpgradeSSDTMessage += ", ";
                    }
                    sUpgradeSSDTMessage += "SSIS to " + SSISExpectedVersion;
                }
                if (sUpgradeSSDTMessage != string.Empty)
                {
                    this.lblSqlVersion.Text += "\r\n" + "Please upgrade " + sUpgradeSSDTMessage;
                }

                // First check we have a valid instance, the add-in may be disabled.
                if (VersionCheckPlugin.Instance == null)
                {
                    bool bConnected = false;
                    try
                    {
                        // TODO - will this code even run now that we are in an extension if the extension
                        // is not loaded
                        //foreach (EnvDTE.AddIn addin in Connect.Application.AddIns)
                        //{
                        //    if (addin.ProgID.ToLower() == "BIDSHelper.Connect".ToLower())
                        //    {
                        //        if (addin.Connected)
                        //        {
                        bConnected = true;
                        //        break;
                        //    }
                        //}
                        //}
                    }
                    catch { }

                    if (bConnected)
                    {
                        // Display disabled information and exit
                        if (BIDSHelperPackage.AddInLoadException == null)
                        {
                            lblServerVersion.Text = "The BIDS Helper Add-in is not running because of problems loading!";
                        }
                        else
                        {
                            lblServerVersion.Visible = false;
                        }
                        linkNewVersion.Visible = false;
                    }
                    else
                    {
                        // Display disabled information and exit
                        lblLocalVersion.Text  += " [Add-in Disabled]";
                        lblServerVersion.Text  = "The BIDS Helper Add-in is not currently enabled.";
                        linkNewVersion.Visible = false;
                    }


                    return; //if we don't have the version check plugin loaded, then stop now and don't check version on server
                }


                lblServerVersion.Visible = false;
                linkNewVersion.Visible   = false;
                //try
                //{
                //    //VersionCheckPlugin.Instance.LastVersionCheck = DateTime.Today;
                //    //if (!VersionCheckPlugin.VersionIsLatest(VersionCheckPlugin.LocalVersion, VersionCheckPlugin.Instance.ServerVersion))
                //    //{
                //    //    lblServerVersion.Text = "Version " + VersionCheckPlugin.Instance.ServerVersion + " is available...";
                //    //    lblServerVersion.Visible = true;
                //    //    linkNewVersion.Visible = true;
                //    //}
                //    //else
                //    //{
                //    //    lblServerVersion.Text = "BIDS Helper is up to date.";
                //    //    lblServerVersion.Visible = true;
                //    //    linkNewVersion.Visible = false;
                //    //}
                //}
                //catch (Exception ex)
                //{
                //    lblServerVersion.Text = "Unable to retrieve current available BIDS Helper version from Codeplex: " + ex.Message + "\r\n" + ex.StackTrace;
                //    linkNewVersion.Visible = false;
                //}
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace, DefaultMessageBoxCaption);
            }
        }
Exemplo n.º 21
0
        private System.Exception UpdateFilePath(string filePath, bool forceUpdate)
        {
#if REPORT_PERFORMANCE
            System.Diagnostics.Debug.WriteLine(">>>> ENTER Fork.UpdateFilePath(" + filePath + "," + forceUpdate + ") + T:" + System.Threading.Thread.CurrentThread.ManagedThreadId);
            var stopwatch = System.Diagnostics.Stopwatch.StartNew();
            try
            {
#endif // REPORT_PERFORMANCE
            System.Exception error = null;
            if ((FileSystem != null) && FileSystem.Frozen)
            {
                // During save, do not attempt to regenerate contents.
                return(error);
            }
            try
            {
                // Do some special work if this is a ROM fork.
                if ((FileSystem != null) && (FileSystem.GetForkKind(this) == ForkKind.Program))
                {
                    if (forceUpdate)
                    {
#if REPORT_PERFORMANCE
                        System.Diagnostics.Debug.WriteLine(">>>>>> ENTER Fork.UpdateFilePath(forceUpdate): GetRom");
                        var stopwatch2 = System.Diagnostics.Stopwatch.StartNew();
                        try
                        {
#endif // REPORT_PERFORMANCE
                        var filesUsingFork = FileSystem.GetFilesUsingForks(new[] { this }).Values;
                        foreach (var program in filesUsingFork.OfType <Program>())
                        {
                            // Since "Program" entries using the same Fork will all point to this one,
                            // we don't need to re-do this work for every file that might point at the fork.
                            var rom = program.Description.GetRom();
                            if ((rom != null) && !string.IsNullOrEmpty(rom.RomPath))
                            {
                                var path = string.Empty;
#if REPORT_PERFORMANCE
                                var stopwatch3 = System.Diagnostics.Stopwatch.StartNew();
#endif // REPORT_PERFORMANCE
                                path = rom.PrepareForDeployment(LuigiGenerationMode.Standard);
#if REPORT_PERFORMANCE
                                stopwatch3.Stop();
                                AccumulatedUpdateFilePathForcedPrepareTime += stopwatch3.Elapsed;
#endif // REPORT_PERFORMANCE
                                UpdateFilePath(path);
                            }
                        }
#if REPORT_PERFORMANCE
                    }
                    finally
                    {
                        stopwatch2.Stop();
                        System.Diagnostics.Debug.WriteLine(">>>>>> EXIT  Fork.UpdateFilePath(forceUpdate): GetRom");     // took: + " + stopwatch2.Elapsed.ToString());
                        AccumulatedUpdateFilePathForcedTime += stopwatch2.Elapsed;
                    }
#endif // REPORT_PERFORMANCE
                    }
                    else
                    {
                        var rom = Rom;
                        var prepareForDeployment = string.IsNullOrEmpty(filePath) && (rom != null);
                        if (!prepareForDeployment && (rom != null))
                        {
                            // We think we don't have to prepare for deployment, but do have ROM set.
                            // Let's just make sure that we have that LUIGI file, shall we?
                            prepareForDeployment = string.IsNullOrEmpty(_filePath) || !System.IO.File.Exists(_filePath);
                            if (!prepareForDeployment && System.IO.File.Exists(_filePath))
                            {
                                // Check to see if it looks like a valid LUIGI file.
                                prepareForDeployment = LuigiFileHeader.GetHeader(_filePath) == null;
                            }
                        }
                        if (prepareForDeployment)
                        {
                            // No file path, but somehow we have a ROM. Force recreation of the LUIGI file. This can
                            // occur during sync from device.
                            UpdateFilePath(Rom.PrepareForDeployment(LuigiGenerationMode.Standard));
                        }
                        else if (rom == null)
                        {
                            if (!System.IO.File.Exists(filePath))
                            {
                                // No ROM, and the file we think we have does not exist.
                                ILfsFileInfo file;
                                rom = null;
                                if (FileSystem.GetFilesUsingForks(new[] { this }).TryGetValue(this, out file))
                                {
                                    switch (FileSystem.Origin)
                                    {
                                    case FileSystemOrigin.HostComputer:
                                        var description = ((Program)file).Description;
                                        rom = description == null ? null : description.GetRom();
                                        break;

                                    case FileSystemOrigin.LtoFlash:
                                        break;
                                    }
                                }
                                prepareForDeployment = (rom != null) && !System.IO.File.Exists(filePath) && !string.IsNullOrEmpty(rom.RomPath) && System.IO.File.Exists(rom.RomPath);
                                if (prepareForDeployment)
                                {
                                    _filePath = null;
                                    UpdateFilePath(rom.PrepareForDeployment(LuigiGenerationMode.Standard));
                                }
                            }

                            // We should *always* be a LUIGI file. If not, fix it!
                            if (!string.IsNullOrEmpty(filePath) && System.IO.File.Exists(filePath))
                            {
                                if (!LuigiFileHeader.PotentialLuigiFile(filePath))
                                {
                                    rom = INTV.Core.Model.Rom.Create(filePath, null);
                                    prepareForDeployment = rom != null;
                                    if (prepareForDeployment)
                                    {
                                        _filePath = null;
                                        UpdateFilePath(rom.PrepareForDeployment(LuigiGenerationMode.Standard));
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    if (forceUpdate)
                    {
                        _filePath = null;
                    }
                    UpdateFilePath(filePath);
                    if (forceUpdate && !string.IsNullOrEmpty(_filePath) && !System.IO.File.Exists(_filePath))
                    {
                        error = new System.IO.FileNotFoundException("File for fork " + GlobalForkNumber + " not found.", filePath, null);
                    }
                }
            }
            catch (System.IO.IOException e)
            {
                error = e;
                if (!forceUpdate)
                {
                    throw;
                }
            }
            return(error);

#if REPORT_PERFORMANCE
        }

        finally
        {
            stopwatch.Stop();
            System.Diagnostics.Debug.WriteLine(">>>> EXIT  Fork.UpdateFilePath(" + filePath + ",force)");     // took: + " + stopwatch.Elapsed.ToString());
            AccumulatedUpdateFilePathTime += stopwatch.Elapsed;
        }
#endif // REPORT_PERFORMANCE
        }
Exemplo n.º 22
0
 static Exception CreateDescriptiveException(System.IO.FileNotFoundException oldException)
 {
     return(new Exception(oldException.Message + " " + SR.GetString(SR.InstallInGAC, oldException.FileName)));
 }
        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            bool bQuitting = false;

            base.Initialize();

#if DEBUG
            Log          = new Core.Logger.OutputLogger(this);
            Log.LogLevel = LogLevels.Debug;
#else
            Log          = new Core.Logger.NullLogger();
            Log.LogLevel = LogLevels.Warning;
#endif
            Log.Debug("BIDSHelper Package Initialize Starting");
            string sAddInTypeName = string.Empty;
            try
            {
                StatusBar      = new Core.VsIntegration.StatusBar(this);
                StatusBar.Text = "Loading BIDSHelper (" + this.GetType().Assembly.GetName().Version.ToString() + ")...";
                VsShell        = (IVsShell)this.GetService(typeof(SVsShell));
                DTE2           = this.GetService(typeof(Microsoft.VisualStudio.Shell.Interop.SDTE)) as EnvDTE80.DTE2;

                DebuggerService.AdviseDebuggerEvents(this, out debugEventCookie);

                if (SwitchVsixManifest())
                {
                    bQuitting = true;
                    RestartVisualStudio();
                    return;
                }

                System.Collections.Generic.List <Exception> pluginExceptions = new System.Collections.Generic.List <Exception>();
                Type[] types = null;
                try
                {
                    types = Assembly.GetExecutingAssembly().GetTypes();
                }
                catch (ReflectionTypeLoadException loadEx)
                {
                    types = loadEx.Types; //if some types can't be loaded (possibly because SSIS SSDT isn't installed, just SSAS?) then proceed with the types that work
                    pluginExceptions.Add(loadEx);
                    Log.Exception("Problem loading BIDS Helper types list", loadEx);
                }

                foreach (Type t in types)
                {
                    if (//typeof(IBIDSHelperPlugin).IsAssignableFrom(t.GetType())
                        t != null &&
                        t.GetInterfaces().Contains(typeof(IBIDSHelperPlugin)) &&
                        (!object.ReferenceEquals(t, typeof(IBIDSHelperPlugin))) &&
                        (!t.IsAbstract))
                    {
                        sAddInTypeName = t.Name;
                        Log.Verbose(string.Format("Loading Plugin: {0}", sAddInTypeName));

                        BIDSHelperPluginBase feature;
                        Type[] @params = { typeof(BIDSHelperPackage) };
                        System.Reflection.ConstructorInfo con;

                        con = t.GetConstructor(@params);

                        if (con == null)
                        {
                            System.Windows.Forms.MessageBox.Show("Problem loading type " + t.Name + ". No constructor found.");
                            continue;
                        }

                        try
                        {
                            feature = (BIDSHelperPluginBase)con.Invoke(new object[] { this });
                            Plugins.Add(feature.FullName, feature);
                        }
                        catch (Exception ex)
                        {
                            pluginExceptions.Add(new Exception("BIDS Helper plugin constructor failed on " + sAddInTypeName + ": " + ex.Message + "\r\n" + ex.StackTrace, ex));
                            Log.Exception("BIDS Helper plugin constructor failed on " + sAddInTypeName, ex);
                        }
                    }
                }

                if (pluginExceptions.Count > 0)
                {
                    string sException = "";
                    foreach (Exception pluginEx in pluginExceptions)
                    {
                        sException += string.Format("BIDS Helper encountered an error when Visual Studio started:\r\n{0}\r\n{1}"
                                                    , pluginEx.Message
                                                    , pluginEx.StackTrace);

                        Exception innerEx = pluginEx.InnerException;
                        while (innerEx != null)
                        {
                            sException += string.Format("\r\nInner exception:\r\n{0}\r\n{1}"
                                                        , innerEx.Message
                                                        , innerEx.StackTrace);
                            innerEx = innerEx.InnerException;
                        }

                        ReflectionTypeLoadException ex = pluginEx as ReflectionTypeLoadException;
                        if (ex == null)
                        {
                            ex = pluginEx.InnerException as ReflectionTypeLoadException;
                        }
                        if (ex != null)
                        {
                            System.Text.StringBuilder sb = new System.Text.StringBuilder();
                            foreach (Exception exSub in ex.LoaderExceptions)
                            {
                                sb.AppendLine();
                                sb.AppendLine(exSub.Message);
                                System.IO.FileNotFoundException exFileNotFound = exSub as System.IO.FileNotFoundException;
                                if (exFileNotFound != null)
                                {
                                    if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
                                    {
                                        sb.AppendLine("Fusion Log:");
                                        sb.AppendLine(exFileNotFound.FusionLog);
                                    }
                                }
                                sb.AppendLine();
                            }
                            sException += sb.ToString();
                        }
                    }
                    AddInLoadException = new Exception(sException);
                }

#if DENALI
                //handle assembly reference problems when the compiled reference doesn't exist in that version of Visual Studio
                //doesn't appear to be needed for VS2013
                AppDomain currentDomain = AppDomain.CurrentDomain;
                currentDomain.AssemblyResolve += new ResolveEventHandler(currentDomain_AssemblyResolve);
#endif
            }
            catch (Exception ex)
            {
                //don't show a popup anymore since this exception is viewable in the Version dialog in the Tools menu
                if (string.IsNullOrEmpty(sAddInTypeName))
                {
                    AddInLoadException = ex;
                    Log.Exception("Problem loading BIDS Helper", ex);
                    //System.Windows.Forms.MessageBox.Show("Problem loading BIDS Helper: " + ex.Message + "\r\n" + ex.StackTrace);
                }
                else
                {
                    AddInLoadException = new Exception("Problem loading BIDS Helper. Problem type was " + sAddInTypeName + ": " + ex.Message + "\r\n" + ex.StackTrace, ex);
                    Log.Exception("Problem loading BIDS Helper. Problem type was " + sAddInTypeName, ex);
                    //System.Windows.Forms.MessageBox.Show("Problem loading BIDS Helper. Problem type was " + sAddInTypeName + ": " + ex.Message + "\r\n" + ex.StackTrace);
                }
            }
            finally
            {
                if (!bQuitting)
                {
                    StatusBar.Clear();
                }
            }
        }
Exemplo n.º 24
0
        private static void AppendFileNotFoundException(this StringBuilder stringBuilder, System.IO.FileNotFoundException exception)
        {
            stringBuilder.AppendMarkdownLine("FileLoadException specific:");
            stringBuilder.Append("   ").AppendMarkdownLine($"[FileName] {exception.FileName}");
#if !(NETSTANDARD1_4 || NETSTANDARD1_5 || NETSTANDARD1_6 || NETSTANDARD1_7 || NETSTANDARD2_0)
            stringBuilder.Append("   ").AppendMarkdownLine($"[FusionLog] {exception.FusionLog}");
#endif
        }
        private void BIDSHelperOptionsVersionCheckPage_Load(object sender, EventArgs e)
        {
            try
            {
                // Get title from assembly info, e.g. "BIDS Helper for SQL 2008"
                Assembly assembly = this.GetType().Assembly;
                AssemblyTitleAttribute attribute = (AssemblyTitleAttribute)AssemblyTitleAttribute.GetCustomAttribute(assembly, typeof(AssemblyTitleAttribute));
                this.lblTitle.Text = attribute.Title;

#if DENALI || SQL2014
                string sBIDSName = "SSDTBI";
#else
                string sBIDSName = "BIDS";
#endif

                if (Connect.AddInLoadException != null)
                {
                    this.lblBidsHelperLoadException.Text = "BIDS Helper encountered an error when Visual Studio started:\r\n" + Connect.AddInLoadException.Message + "\r\n" + Connect.AddInLoadException.StackTrace;

                    ReflectionTypeLoadException ex = Connect.AddInLoadException as ReflectionTypeLoadException;
                    if (ex != null)
                    {
                        System.Text.StringBuilder sb = new System.Text.StringBuilder();
                        foreach (Exception exSub in ex.LoaderExceptions)
                        {
                            sb.AppendLine();
                            sb.AppendLine(exSub.Message);
                            System.IO.FileNotFoundException exFileNotFound = exSub as System.IO.FileNotFoundException;
                            if (exFileNotFound != null)
                            {
                                if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
                                {
                                    sb.AppendLine("Fusion Log:");
                                    sb.AppendLine(exFileNotFound.FusionLog);
                                }
                            }
                            sb.AppendLine();
                        }
                        this.lblBidsHelperLoadException.Text += sb.ToString();
                    }

                    this.lblBidsHelperLoadException.Visible = true;
                    this.btnCopyError.Visible = true;
                }
                else
                {
                    this.lblBidsHelperLoadException.Visible = false;
                    this.btnCopyError.Visible = false;
                }

                try
                {
                    this.lblSqlVersion.Text = sBIDSName + " " + GetFriendlySqlVersion() + " for Visual Studio " + GetFriendlyVisualStudioVersion() + " was detected";
                }
                catch
                {
                    //if there's an exception it's because we couldn't find SSDTBI or BIDS installed in this Visual Studio version
                    try
                    {
                        this.lblSqlVersion.Text      = sBIDSName + " for Visual Studio " + GetFriendlyVisualStudioVersion() + " was NOT detected. BIDS Helper disabled.";
                        this.lblSqlVersion.ForeColor = System.Drawing.Color.Red;
                        if (Connect.AddInLoadException != null && Connect.AddInLoadException is System.Reflection.ReflectionTypeLoadException)
                        {
                            //this is the expected exception if SSDTBI isn't installed... if this is the exception, don't show it... otherwise, show the exception
                            this.lblBidsHelperLoadException.Visible = false;
                        }
                    }
                    catch
                    {
                        this.lblSqlVersion.Visible = false;
                    }
                }

                // Set current version
                this.lblLocalVersion.Text = VersionCheckPlugin.LocalVersion;
#if DEBUG
                DateTime buildDateTime = GetBuildDateTime(assembly);
                this.lblLocalVersion.Text += string.Format(CultureInfo.InvariantCulture, " (Debug Build {0:yyyy-MM-dd HH:mm:ss})", buildDateTime);
#endif

                // First check we have a valid instance, the add-in may be disabled.
                if (VersionCheckPlugin.VersionCheckPluginInstance == null)
                {
                    bool bConnected = false;
                    try
                    {
                        foreach (EnvDTE.AddIn addin in Connect.Application.AddIns)
                        {
                            if (addin.ProgID.ToLower() == "BIDSHelper.Connect".ToLower())
                            {
                                if (addin.Connected)
                                {
                                    bConnected = true;
                                    break;
                                }
                            }
                        }
                    }
                    catch { }

                    if (bConnected)
                    {
                        // Display disabled information and exit
                        if (Connect.AddInLoadException == null)
                        {
                            lblServerVersion.Text = "The BIDS Helper Add-in is not running because of problems loading!";
                        }
                        else
                        {
                            lblServerVersion.Visible = false;
                        }
                        linkNewVersion.Visible = false;
                    }
                    else
                    {
                        // Display disabled information and exit
                        lblLocalVersion.Text  += " [Add-in Disabled]";
                        lblServerVersion.Text  = "The BIDS Helper Add-in is not currently enabled.";
                        linkNewVersion.Visible = false;
                    }


                    return; //if we don't have the version check plugin loaded, then stop now and don't check version on server
                }


                try
                {
                    VersionCheckPlugin.VersionCheckPluginInstance.LastVersionCheck = DateTime.Today;
                    if (!VersionCheckPlugin.VersionIsLatest(VersionCheckPlugin.LocalVersion, VersionCheckPlugin.VersionCheckPluginInstance.ServerVersion))
                    {
                        lblServerVersion.Text    = "Version " + VersionCheckPlugin.VersionCheckPluginInstance.ServerVersion + " is available...";
                        lblServerVersion.Visible = true;
                        linkNewVersion.Visible   = true;
                    }
                    else
                    {
                        lblServerVersion.Text    = "BIDS Helper is up to date.";
                        lblServerVersion.Visible = true;
                        linkNewVersion.Visible   = false;
                    }
                }
                catch (Exception ex)
                {
                    lblServerVersion.Text  = "Unable to retrieve current available BIDS Helper version from Codeplex: " + ex.Message + "\r\n" + ex.StackTrace;
                    linkNewVersion.Visible = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace, DefaultMessageBoxCaption);
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// This does a mapping from hr to the exception and also takes care of making default exception in case of classic COM as COMException.
        /// and in winrt and marshal APIs as Exception.
        /// </summary>
        /// <param name="errorCode"></param>
        /// <param name="message"></param>
        /// <param name="createCOMException"></param>
        /// <returns></returns>
        internal static Exception GetMappingExceptionForHR(int errorCode, string message, bool createCOMException, bool hasErrorInfo)
        {
            if (errorCode >= 0)
            {
                return(null);
            }

            Exception exception = null;

            bool shouldDisplayHR = false;

            switch (errorCode)
            {
            case __HResults.COR_E_NOTFINITENUMBER:     // NotFiniteNumberException
            case __HResults.COR_E_ARITHMETIC:
                exception = new ArithmeticException();
                break;

            case __HResults.COR_E_ARGUMENT:
            case unchecked ((int)0x800A01C1):
            case unchecked ((int)0x800A01C2):
            case __HResults.CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT:
                exception = new ArgumentException();

                if (errorCode != __HResults.COR_E_ARGUMENT)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.E_BOUNDS:
            case __HResults.COR_E_ARGUMENTOUTOFRANGE:
            case __HResults.ERROR_NO_UNICODE_TRANSLATION:
                exception = new ArgumentOutOfRangeException();

                if (errorCode != __HResults.COR_E_ARGUMENTOUTOFRANGE)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_ARRAYTYPEMISMATCH:
                exception = new ArrayTypeMismatchException();
                break;

            case __HResults.COR_E_BADIMAGEFORMAT:
            case __HResults.CLDB_E_FILE_OLDVER:
            case __HResults.CLDB_E_INDEX_NOTFOUND:
            case __HResults.CLDB_E_FILE_CORRUPT:
            case __HResults.COR_E_NEWER_RUNTIME:
            case __HResults.COR_E_ASSEMBLYEXPECTED:
            case __HResults.ERROR_BAD_EXE_FORMAT:
            case __HResults.ERROR_EXE_MARKED_INVALID:
            case __HResults.CORSEC_E_INVALID_IMAGE_FORMAT:
            case __HResults.ERROR_NOACCESS:
            case __HResults.ERROR_INVALID_ORDINAL:
            case __HResults.ERROR_INVALID_DLL:
            case __HResults.ERROR_FILE_CORRUPT:
            case __HResults.COR_E_LOADING_REFERENCE_ASSEMBLY:
            case __HResults.META_E_BAD_SIGNATURE:
                exception = new BadImageFormatException();

                // Always show HR for BadImageFormatException
                shouldDisplayHR = true;

                break;

            case __HResults.COR_E_CUSTOMATTRIBUTEFORMAT:
                exception = new FormatException();
                break;     // CustomAttributeFormatException

            case __HResults.COR_E_DATAMISALIGNED:
                exception = InteropExtensions.CreateDataMisalignedException(message);     // TODO: Do we need to add msg here?
                break;

            case __HResults.COR_E_DIVIDEBYZERO:
            case __HResults.CTL_E_DIVISIONBYZERO:
                exception = new DivideByZeroException();

                if (errorCode != __HResults.COR_E_DIVIDEBYZERO)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_DLLNOTFOUND:
#if ENABLE_WINRT
                exception = new DllNotFoundException();
#endif
                break;

            case __HResults.COR_E_DUPLICATEWAITOBJECT:
                exception = new ArgumentException();
                break;     // DuplicateWaitObjectException

            case __HResults.COR_E_ENDOFSTREAM:
            case unchecked ((int)0x800A003E):
                exception = new CoreFX_IO::System.IO.EndOfStreamException();

                if (errorCode != __HResults.COR_E_ENDOFSTREAM)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_TYPEACCESS:     // TypeAccessException
            case __HResults.COR_E_ENTRYPOINTNOTFOUND:
                exception = new TypeLoadException();

                break;     // EntryPointNotFoundException

            case __HResults.COR_E_EXCEPTION:
                exception = new Exception();
                break;

            case __HResults.COR_E_DIRECTORYNOTFOUND:
            case __HResults.STG_E_PATHNOTFOUND:
            case __HResults.CTL_E_PATHNOTFOUND:
                exception = new System.IO.DirectoryNotFoundException();

                if (errorCode != __HResults.COR_E_DIRECTORYNOTFOUND)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_FILELOAD:
            case __HResults.FUSION_E_INVALID_PRIVATE_ASM_LOCATION:
            case __HResults.FUSION_E_SIGNATURE_CHECK_FAILED:
            case __HResults.FUSION_E_LOADFROM_BLOCKED:
            case __HResults.FUSION_E_CACHEFILE_FAILED:
            case __HResults.FUSION_E_ASM_MODULE_MISSING:
            case __HResults.FUSION_E_INVALID_NAME:
            case __HResults.FUSION_E_PRIVATE_ASM_DISALLOWED:
            case __HResults.FUSION_E_HOST_GAC_ASM_MISMATCH:
            case __HResults.COR_E_MODULE_HASH_CHECK_FAILED:
            case __HResults.FUSION_E_REF_DEF_MISMATCH:
            case __HResults.SECURITY_E_INCOMPATIBLE_SHARE:
            case __HResults.SECURITY_E_INCOMPATIBLE_EVIDENCE:
            case __HResults.SECURITY_E_UNVERIFIABLE:
            case __HResults.COR_E_FIXUPSINEXE:
            case __HResults.ERROR_TOO_MANY_OPEN_FILES:
            case __HResults.ERROR_SHARING_VIOLATION:
            case __HResults.ERROR_LOCK_VIOLATION:
            case __HResults.ERROR_OPEN_FAILED:
            case __HResults.ERROR_DISK_CORRUPT:
            case __HResults.ERROR_UNRECOGNIZED_VOLUME:
            case __HResults.ERROR_DLL_INIT_FAILED:
            case __HResults.FUSION_E_CODE_DOWNLOAD_DISABLED:
            case __HResults.CORSEC_E_MISSING_STRONGNAME:
            case __HResults.MSEE_E_ASSEMBLYLOADINPROGRESS:
            case __HResults.ERROR_FILE_INVALID:
                exception = new System.IO.FileLoadException();

                shouldDisplayHR = true;
                break;

            case __HResults.COR_E_PATHTOOLONG:
                exception = new System.IO.PathTooLongException();
                break;

            case __HResults.COR_E_IO:
            case __HResults.CTL_E_DEVICEIOERROR:
            case unchecked ((int)0x800A793C):
            case unchecked ((int)0x800A793D):
                exception = new System.IO.IOException();

                if (errorCode != __HResults.COR_E_IO)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.ERROR_FILE_NOT_FOUND:
            case __HResults.ERROR_MOD_NOT_FOUND:
            case __HResults.ERROR_INVALID_NAME:
            case __HResults.CTL_E_FILENOTFOUND:
            case __HResults.ERROR_BAD_NET_NAME:
            case __HResults.ERROR_BAD_NETPATH:
            case __HResults.ERROR_NOT_READY:
            case __HResults.ERROR_WRONG_TARGET_NAME:
            case __HResults.INET_E_UNKNOWN_PROTOCOL:
            case __HResults.INET_E_CONNECTION_TIMEOUT:
            case __HResults.INET_E_CANNOT_CONNECT:
            case __HResults.INET_E_RESOURCE_NOT_FOUND:
            case __HResults.INET_E_OBJECT_NOT_FOUND:
            case __HResults.INET_E_DOWNLOAD_FAILURE:
            case __HResults.INET_E_DATA_NOT_AVAILABLE:
            case __HResults.ERROR_DLL_NOT_FOUND:
            case __HResults.CLR_E_BIND_ASSEMBLY_VERSION_TOO_LOW:
            case __HResults.CLR_E_BIND_ASSEMBLY_PUBLIC_KEY_MISMATCH:
            case __HResults.CLR_E_BIND_ASSEMBLY_NOT_FOUND:
                exception = new System.IO.FileNotFoundException();

                shouldDisplayHR = true;
                break;

            case __HResults.COR_E_FORMAT:
                exception = new FormatException();
                break;

            case __HResults.COR_E_INDEXOUTOFRANGE:
            case unchecked ((int)0x800a0009):
                exception = new IndexOutOfRangeException();

                if (errorCode != __HResults.COR_E_INDEXOUTOFRANGE)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_INVALIDCAST:
                exception = new InvalidCastException();
                break;

            case __HResults.COR_E_INVALIDCOMOBJECT:
                exception = new InvalidComObjectException();
                break;

            case __HResults.COR_E_INVALIDOLEVARIANTTYPE:
                exception = new InvalidOleVariantTypeException();
                break;

            case __HResults.COR_E_INVALIDOPERATION:
            case __HResults.E_ILLEGAL_STATE_CHANGE:
            case __HResults.E_ILLEGAL_METHOD_CALL:
            case __HResults.E_ILLEGAL_DELEGATE_ASSIGNMENT:
            case __HResults.APPMODEL_ERROR_NO_PACKAGE:
                exception = new InvalidOperationException();

                if (errorCode != __HResults.COR_E_INVALIDOPERATION)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_MARSHALDIRECTIVE:
                exception = new MarshalDirectiveException();
                break;

            case __HResults.COR_E_METHODACCESS:            // MethodAccessException
            case __HResults.META_E_CA_FRIENDS_SN_REQUIRED: // MethodAccessException
            case __HResults.COR_E_FIELDACCESS:
            case __HResults.COR_E_MEMBERACCESS:
                exception = new MemberAccessException();

                if (errorCode != __HResults.COR_E_METHODACCESS)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_MISSINGFIELD:     // MissingFieldException
            case __HResults.COR_E_MISSINGMETHOD:    // MissingMethodException
            case __HResults.COR_E_MISSINGMEMBER:
            case unchecked ((int)0x800A01CD):
                exception = new MissingMemberException();
                break;

            case __HResults.COR_E_MISSINGMANIFESTRESOURCE:
                exception = new System.Resources.MissingManifestResourceException();
                break;

            case __HResults.COR_E_NOTSUPPORTED:
            case unchecked ((int)0x800A01B6):
            case unchecked ((int)0x800A01BD):
            case unchecked ((int)0x800A01CA):
            case unchecked ((int)0x800A01CB):
                exception = new NotSupportedException();

                if (errorCode != __HResults.COR_E_NOTSUPPORTED)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_NULLREFERENCE:
                exception = new NullReferenceException();
                break;

            case __HResults.COR_E_OBJECTDISPOSED:
            case __HResults.RO_E_CLOSED:
                // No default constructor
                exception = new ObjectDisposedException(String.Empty);
                break;

            case __HResults.COR_E_OPERATIONCANCELED:
#if ENABLE_WINRT
                exception = new OperationCanceledException();
#endif
                break;

            case __HResults.COR_E_OVERFLOW:
            case __HResults.CTL_E_OVERFLOW:
                exception = new OverflowException();
                break;

            case __HResults.COR_E_PLATFORMNOTSUPPORTED:
                exception = new PlatformNotSupportedException(message);
                break;

            case __HResults.COR_E_RANK:
                exception = new RankException();
                break;

            case __HResults.COR_E_REFLECTIONTYPELOAD:
#if ENABLE_WINRT
                exception = new System.Reflection.ReflectionTypeLoadException(null, null);
#endif
                break;

            case __HResults.COR_E_SECURITY:
            case __HResults.CORSEC_E_INVALID_STRONGNAME:
            case __HResults.CTL_E_PERMISSIONDENIED:
            case unchecked ((int)0x800A01A3):
            case __HResults.CORSEC_E_INVALID_PUBLICKEY:
            case __HResults.CORSEC_E_SIGNATURE_MISMATCH:
                exception = new System.Security.SecurityException();
                break;

            case __HResults.COR_E_SAFEARRAYRANKMISMATCH:
                exception = new SafeArrayRankMismatchException();
                break;

            case __HResults.COR_E_SAFEARRAYTYPEMISMATCH:
                exception = new SafeArrayTypeMismatchException();
                break;

            case __HResults.COR_E_SERIALIZATION:
                exception = new System.Runtime.Serialization.SerializationException(message);
                break;

            case __HResults.COR_E_SYNCHRONIZATIONLOCK:
                exception = new System.Threading.SynchronizationLockException();
                break;

            case __HResults.COR_E_TARGETINVOCATION:
                exception = new System.Reflection.TargetInvocationException(null);
                break;

            case __HResults.COR_E_TARGETPARAMCOUNT:
                exception = new System.Reflection.TargetParameterCountException();
                break;

            case __HResults.COR_E_TYPEINITIALIZATION:
                exception = InteropExtensions.CreateTypeInitializationException(message);
                break;

            case __HResults.COR_E_TYPELOAD:
            case __HResults.RO_E_METADATA_NAME_NOT_FOUND:
            case __HResults.CLR_E_BIND_TYPE_NOT_FOUND:
                exception = new TypeLoadException();

                if (errorCode != __HResults.COR_E_TYPELOAD)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_UNAUTHORIZEDACCESS:
            case __HResults.CTL_E_PATHFILEACCESSERROR:
            case unchecked ((int)0x800A014F):
                exception = new UnauthorizedAccessException();

                shouldDisplayHR = true;

                break;

            case __HResults.COR_E_VERIFICATION:
                exception = new System.Security.VerificationException();
                break;

            case __HResults.E_NOTIMPL:
                exception = new NotImplementedException();
                break;

            case __HResults.E_OUTOFMEMORY:
            case __HResults.CTL_E_OUTOFMEMORY:
            case unchecked ((int)0x800A7919):
                exception = new OutOfMemoryException();

                if (errorCode != __HResults.E_OUTOFMEMORY)
                {
                    shouldDisplayHR = true;
                }

                break;

#if ENABLE_WINRT
            case __HResults.E_XAMLPARSEFAILED:
                exception = ConstructExceptionUsingReflection(
                    "Windows.UI.Xaml.Markup.XamlParseException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                    message);
                break;

            case __HResults.E_ELEMENTNOTAVAILABLE:
                exception = ConstructExceptionUsingReflection(
                    "Windows.UI.Xaml.Automation.ElementNotAvailableException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                    message);
                break;

            case __HResults.E_ELEMENTNOTENABLED:
                exception = ConstructExceptionUsingReflection(
                    "Windows.UI.Xaml.Automation.ElementNotEnabledException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                    message);
                break;

            case __HResults.E_LAYOUTCYCLE:
                exception = ConstructExceptionUsingReflection(
                    "Windows.UI.Xaml.LayoutCycleException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                    message);
                break;
#endif // ENABLE_WINRT
            case __HResults.COR_E_AMBIGUOUSMATCH:     // AmbiguousMatchException
            case __HResults.COR_E_APPLICATION:     // ApplicationException
            case __HResults.COR_E_APPDOMAINUNLOADED:          // AppDomainUnloadedException
            case __HResults.COR_E_CANNOTUNLOADAPPDOMAIN:      // CannotUnloadAppDomainException
            case __HResults.COR_E_CODECONTRACTFAILED:         // ContractException
            case __HResults.COR_E_CONTEXTMARSHAL:             // ContextMarshalException
            case __HResults.CORSEC_E_CRYPTO:                  // CryptographicException
            case __HResults.CORSEC_E_CRYPTO_UNEX_OPER:        // CryptographicUnexpectedOperationException
            case __HResults.COR_E_EXECUTIONENGINE:            // ExecutionEngineException
            case __HResults.COR_E_INSUFFICIENTEXECUTIONSTACK: // InsufficientExecutionStackException
            case __HResults.COR_E_INVALIDFILTERCRITERIA:      // InvalidFilterCriteriaException
            case __HResults.COR_E_INVALIDPROGRAM:             // InvalidProgramException
            case __HResults.COR_E_MULTICASTNOTSUPPORTED:      // MulticastNotSupportedException
            case __HResults.COR_E_REMOTING:                   // RemotingException
            case __HResults.COR_E_RUNTIMEWRAPPED:             // RuntimeWrappedException
            case __HResults.COR_E_SERVER:                     // ServerException
            case __HResults.COR_E_STACKOVERFLOW:              // StackOverflowException
            case __HResults.CTL_E_OUTOFSTACKSPACE:            // StackOverflowException
            case __HResults.COR_E_SYSTEM:                     // SystemException
            case __HResults.COR_E_TARGET:                     // TargetException
            case __HResults.COR_E_THREADABORTED:              // TargetException
            case __HResults.COR_E_THREADINTERRUPTED:          // ThreadInterruptedException
            case __HResults.COR_E_THREADSTATE:                // ThreadStateException
            case __HResults.COR_E_THREADSTART:                // ThreadStartException
            case __HResults.COR_E_TYPEUNLOADED:               // TypeUnloadedException
            case __HResults.CORSEC_E_POLICY_EXCEPTION:        // PolicyException
            case __HResults.CORSEC_E_NO_EXEC_PERM:            // PolicyException
            case __HResults.CORSEC_E_MIN_GRANT_FAIL:          // PolicyException
            case __HResults.CORSEC_E_XMLSYNTAX:               // XmlSyntaxException
            case __HResults.ISS_E_ALLOC_TOO_LARGE:            // IsolatedStorageException
            case __HResults.ISS_E_BLOCK_SIZE_TOO_SMALL:       // IsolatedStorageException
            case __HResults.ISS_E_CALLER:                     // IsolatedStorageException
            case __HResults.ISS_E_CORRUPTED_STORE_FILE:       // IsolatedStorageException
            case __HResults.ISS_E_CREATE_DIR:                 // IsolatedStorageException
            case __HResults.ISS_E_CREATE_MUTEX:               // IsolatedStorageException
            case __HResults.ISS_E_DEPRECATE:                  // IsolatedStorageException
            case __HResults.ISS_E_FILE_NOT_MAPPED:            // IsolatedStorageException
            case __HResults.ISS_E_FILE_WRITE:                 // IsolatedStorageException
            case __HResults.ISS_E_GET_FILE_SIZE:              // IsolatedStorageException
            case __HResults.ISS_E_ISOSTORE:                   // IsolatedStorageException
            case __HResults.ISS_E_LOCK_FAILED:                // IsolatedStorageException
            case __HResults.ISS_E_MACHINE:                    // IsolatedStorageException
            case __HResults.ISS_E_MACHINE_DACL:               // IsolatedStorageException
            case __HResults.ISS_E_MAP_VIEW_OF_FILE:           // IsolatedStorageException
            case __HResults.ISS_E_OPEN_FILE_MAPPING:          // IsolatedStorageException
            case __HResults.ISS_E_OPEN_STORE_FILE:            // IsolatedStorageException
            case __HResults.ISS_E_PATH_LENGTH:                // IsolatedStorageException
            case __HResults.ISS_E_SET_FILE_POINTER:           // IsolatedStorageException
            case __HResults.ISS_E_STORE_NOT_OPEN:             // IsolatedStorageException
            case __HResults.ISS_E_STORE_VERSION:              // IsolatedStorageException
            case __HResults.ISS_E_TABLE_ROW_NOT_FOUND:        // IsolatedStorageException
            case __HResults.ISS_E_USAGE_WILL_EXCEED_QUOTA:    // IsolatedStorageException
            case __HResults.E_FAIL:
            default:
                break;
            }

            if (exception == null)
            {
                if (createCOMException)
                {
                    exception = new COMException();
                    if (errorCode != __HResults.E_FAIL)
                    {
                        shouldDisplayHR = true;
                    }
                }
                else
                {
                    exception = new Exception();
                    if (errorCode != __HResults.COR_E_EXCEPTION)
                    {
                        shouldDisplayHR = true;
                    }
                }
            }

            bool shouldConstructMessage = false;
            if (hasErrorInfo)
            {
                // If there is a IErrorInfo/IRestrictedErrorInfo, only construct a new error message if
                // the message is not available and do not use the shouldDisplayHR setting
                if (message == null)
                {
                    shouldConstructMessage = true;
                }
            }
            else
            {
                // If there is no IErrorInfo, use the shouldDisplayHR setting from the big switch/case above
                shouldConstructMessage = shouldDisplayHR;
            }

            if (shouldConstructMessage)
            {
                //
                // Append the HR into error message, just in case the app wants to look at the HR in
                // message to determine behavior.  We didn't expose HResult property until v4.5 and
                // GetHRFromException has side effects so probably Message was their only choice.
                // This behavior is probably not exactly the same as in desktop but it is fine to append
                // more message at the end. In any case, having the HR in the error message are helpful
                // to developers.
                // This makes sure:
                // 1. We always have a HR 0xNNNNNNNN in the message
                // 2. Put in a nice "Exception thrown from HRESULT" message if we can
                // 3. Wrap it in () if there is an existing message
                //

                // TODO: Add Symbolic Name into Messaage, convert 0x80020006 to DISP_E_UNKNOWNNAME
                string hrMessage = String.Format("{0} 0x{1}", SR.Excep_FromHResult, errorCode.LowLevelToString());

                message = ExternalInterop.GetMessage(errorCode);

                // Always make sure we have at least the HRESULT part in retail build or when the message
                // is empty.
                if (message == null)
                {
                    message = hrMessage;
                }
                else
                {
                    message = message + " (" + hrMessage + ")";
                }
            }

            if (message != null)
            {
                // Set message explicitly rather than calling constructor because certain ctors would append a
                // prefix to the message and that is not what we want
                InteropExtensions.SetExceptionMessage(exception, message);
            }

            InteropExtensions.SetExceptionErrorCode(exception, errorCode);

            return(exception);
        }
Exemplo n.º 27
0
        static Exception GetExceptionForHRInternal(int errorCode, IntPtr errorInfo)
        {
            switch (errorCode)
            {
            case HResults.S_OK:
            case HResults.S_FALSE:
                return(null);

            case HResults.COR_E_AMBIGUOUSMATCH:
                return(new System.Reflection.AmbiguousMatchException());

            case HResults.COR_E_APPLICATION:
                return(new System.ApplicationException());

            case HResults.COR_E_ARGUMENT:
                return(new System.ArgumentException());

            case HResults.COR_E_ARGUMENTOUTOFRANGE:
                return(new System.ArgumentOutOfRangeException());

            case HResults.COR_E_ARITHMETIC:
                return(new System.ArithmeticException());

            case HResults.COR_E_ARRAYTYPEMISMATCH:
                return(new System.ArrayTypeMismatchException());

            case HResults.COR_E_BADEXEFORMAT:
                return(new System.BadImageFormatException());

            case HResults.COR_E_BADIMAGEFORMAT:
                return(new System.BadImageFormatException());

            //case HResults.COR_E_CODECONTRACTFAILED:
            //return new System.Diagnostics.Contracts.ContractException ();
            //case HResults.COR_E_COMEMULATE:
            case HResults.COR_E_CUSTOMATTRIBUTEFORMAT:
                return(new System.Reflection.CustomAttributeFormatException());

            case HResults.COR_E_DATAMISALIGNED:
                return(new System.DataMisalignedException());

            case HResults.COR_E_DIRECTORYNOTFOUND:
                return(new System.IO.DirectoryNotFoundException());

            case HResults.COR_E_DIVIDEBYZERO:
                return(new System.DivideByZeroException());

            case HResults.COR_E_DLLNOTFOUND:
                return(new System.DllNotFoundException());

            case HResults.COR_E_DUPLICATEWAITOBJECT:
                return(new System.DuplicateWaitObjectException());

            case HResults.COR_E_ENDOFSTREAM:
                return(new System.IO.EndOfStreamException());

            case HResults.COR_E_ENTRYPOINTNOTFOUND:
                return(new System.EntryPointNotFoundException());

            case HResults.COR_E_EXCEPTION:
                return(new System.Exception());

            case HResults.COR_E_EXECUTIONENGINE:
                return(new System.ExecutionEngineException());

            case HResults.COR_E_FIELDACCESS:
                return(new System.FieldAccessException());

            case HResults.COR_E_FILELOAD:
                return(new System.IO.FileLoadException());

            case HResults.COR_E_FILENOTFOUND:
                return(new System.IO.FileNotFoundException());

            case HResults.COR_E_FORMAT:
                return(new System.FormatException());

            case HResults.COR_E_INDEXOUTOFRANGE:
                return(new System.IndexOutOfRangeException());

            case HResults.COR_E_INSUFFICIENTEXECUTIONSTACK:
                return(new System.InsufficientExecutionStackException());

            case HResults.COR_E_INVALIDCAST:
                return(new System.InvalidCastException());

            case HResults.COR_E_INVALIDFILTERCRITERIA:
                return(new System.Reflection.InvalidFilterCriteriaException());

            case HResults.COR_E_INVALIDOLEVARIANTTYPE:
                return(new System.Runtime.InteropServices.InvalidOleVariantTypeException());

            case HResults.COR_E_INVALIDOPERATION:
                return(new System.InvalidOperationException());

            case HResults.COR_E_INVALIDPROGRAM:
                return(new System.InvalidProgramException());

            case HResults.COR_E_IO:
                return(new System.IO.IOException());

            case HResults.COR_E_MARSHALDIRECTIVE:
                return(new System.Runtime.InteropServices.MarshalDirectiveException());

            case HResults.COR_E_MEMBERACCESS:
                return(new System.MemberAccessException());

            case HResults.COR_E_METHODACCESS:
                return(new System.MethodAccessException());

            case HResults.COR_E_MISSINGFIELD:
                return(new System.MissingFieldException());

            case HResults.COR_E_MISSINGMANIFESTRESOURCE:
                return(new System.Resources.MissingManifestResourceException());

            case HResults.COR_E_MISSINGMEMBER:
                return(new System.MissingMemberException());

            case HResults.COR_E_MISSINGMETHOD:
                return(new System.MissingMethodException());

            case HResults.COR_E_MULTICASTNOTSUPPORTED:
                return(new System.MulticastNotSupportedException());

            case HResults.COR_E_NOTFINITENUMBER:
                return(new System.NotFiniteNumberException());

            case HResults.COR_E_NOTSUPPORTED:
                return(new System.NotSupportedException());

            case HResults.COR_E_NULLREFERENCE:
                return(new System.NullReferenceException());

            case HResults.COR_E_OBJECTDISPOSED:
                return(new System.ObjectDisposedException(""));

            case HResults.COR_E_OPERATIONCANCELED:
                return(new System.OperationCanceledException());

            case HResults.COR_E_OUTOFMEMORY:
                return(new System.OutOfMemoryException());

            case HResults.COR_E_OVERFLOW:
                return(new System.OverflowException());

            case HResults.COR_E_PATHTOOLONG:
                return(new System.IO.PathTooLongException());

            case HResults.COR_E_PLATFORMNOTSUPPORTED:
                return(new System.PlatformNotSupportedException());

            case HResults.COR_E_RANK:
                return(new System.RankException());

            case HResults.COR_E_REFLECTIONTYPELOAD:
                return(new System.MissingMethodException());

            case HResults.COR_E_RUNTIMEWRAPPED:
                return(new System.MissingMethodException());

            case HResults.COR_E_SECURITY:
                return(new System.Security.SecurityException());

            case HResults.COR_E_SERIALIZATION:
                return(new System.Runtime.Serialization.SerializationException());

            case HResults.COR_E_STACKOVERFLOW:
                return(new System.StackOverflowException());

            case HResults.COR_E_SYNCHRONIZATIONLOCK:
                return(new System.Threading.SynchronizationLockException());

            case HResults.COR_E_SYSTEM:
                return(new System.SystemException());

            case HResults.COR_E_TARGET:
                return(new System.Reflection.TargetException());

            case HResults.COR_E_TARGETINVOCATION:
                return(new System.MissingMethodException());

            case HResults.COR_E_TARGETPARAMCOUNT:
                return(new System.Reflection.TargetParameterCountException());

            case HResults.COR_E_THREADABORTED:
                return(new System.Threading.ThreadAbortException());

            case HResults.COR_E_THREADINTERRUPTED:
                return(new System.Threading.ThreadInterruptedException());

            case HResults.COR_E_THREADSTART:
                return(new System.Threading.ThreadStartException());

            case HResults.COR_E_THREADSTATE:
                return(new System.Threading.ThreadStateException());

            case HResults.COR_E_TYPEACCESS:
                return(new System.TypeAccessException());

            case HResults.COR_E_TYPEINITIALIZATION:
                return(new System.TypeInitializationException(""));

            case HResults.COR_E_TYPELOAD:
                return(new System.TypeLoadException());

            case HResults.COR_E_TYPEUNLOADED:
                return(new System.TypeUnloadedException());

            case HResults.COR_E_UNAUTHORIZEDACCESS:
                return(new System.UnauthorizedAccessException());

            //case HResults.COR_E_UNSUPPORTEDFORMAT:
            case HResults.COR_E_VERIFICATION:
                return(new System.Security.VerificationException());

            //case HResults.E_INVALIDARG:
            case HResults.E_NOTIMPL:
                return(new System.NotImplementedException());

            //case HResults.E_POINTER:
            case HResults.RO_E_CLOSED:
                return(new System.ObjectDisposedException(""));

            case HResults.COR_E_ABANDONEDMUTEX:
            case HResults.COR_E_AMBIGUOUSIMPLEMENTATION:
            case HResults.COR_E_CANNOTUNLOADAPPDOMAIN:
            case HResults.COR_E_CONTEXTMARSHAL:
            case HResults.COR_E_HOSTPROTECTION:
            case HResults.COR_E_INSUFFICIENTMEMORY:
            case HResults.COR_E_INVALIDCOMOBJECT:
            case HResults.COR_E_KEYNOTFOUND:
            case HResults.COR_E_MISSINGSATELLITEASSEMBLY:
            case HResults.COR_E_SAFEARRAYRANKMISMATCH:
            case HResults.COR_E_SAFEARRAYTYPEMISMATCH:
            case HResults.COR_E_SAFEHANDLEMISSINGATTRIBUTE:
            case HResults.COR_E_SEMAPHOREFULL:
            case HResults.COR_E_THREADSTOP:
            case HResults.COR_E_TIMEOUT:
            case HResults.COR_E_WAITHANDLECANNOTBEOPENED:
            case HResults.DISP_E_OVERFLOW:
            case HResults.E_BOUNDS:
            case HResults.E_CHANGED_STATE:
            case HResults.E_FAIL:
            case HResults.E_HANDLE:
            case HResults.ERROR_MRM_MAP_NOT_FOUND:
            case HResults.TYPE_E_TYPEMISMATCH:
            case HResults.CO_E_NOTINITIALIZED:
            case HResults.RPC_E_CHANGED_MODE:
                return(new COMException("", errorCode));

            case HResults.STG_E_PATHNOTFOUND:
            case HResults.CTL_E_PATHNOTFOUND: {
                var ex = new System.IO.DirectoryNotFoundException();
                ex.SetErrorCode(errorCode);
                return(ex);
            }

            case HResults.FUSION_E_INVALID_PRIVATE_ASM_LOCATION:
            case HResults.FUSION_E_SIGNATURE_CHECK_FAILED:
            case HResults.FUSION_E_LOADFROM_BLOCKED:
            case HResults.FUSION_E_CACHEFILE_FAILED:
            case HResults.FUSION_E_ASM_MODULE_MISSING:
            case HResults.FUSION_E_INVALID_NAME:
            case HResults.FUSION_E_PRIVATE_ASM_DISALLOWED:
            case HResults.FUSION_E_HOST_GAC_ASM_MISMATCH:
            case HResults.COR_E_MODULE_HASH_CHECK_FAILED:
            case HResults.FUSION_E_REF_DEF_MISMATCH:
            case HResults.SECURITY_E_INCOMPATIBLE_SHARE:
            case HResults.SECURITY_E_INCOMPATIBLE_EVIDENCE:
            case HResults.SECURITY_E_UNVERIFIABLE:
            case HResults.COR_E_FIXUPSINEXE:
            case HResults.ERROR_TOO_MANY_OPEN_FILES:
            case HResults.ERROR_SHARING_VIOLATION:
            case HResults.ERROR_LOCK_VIOLATION:
            case HResults.ERROR_OPEN_FAILED:
            case HResults.ERROR_DISK_CORRUPT:
            case HResults.ERROR_UNRECOGNIZED_VOLUME:
            case HResults.ERROR_DLL_INIT_FAILED:
            case HResults.FUSION_E_CODE_DOWNLOAD_DISABLED:
            case HResults.CORSEC_E_MISSING_STRONGNAME:
            case HResults.MSEE_E_ASSEMBLYLOADINPROGRESS:
            case HResults.ERROR_FILE_INVALID: {
                var ex = new System.IO.FileLoadException();
                ex.SetErrorCode(errorCode);
                return(ex);
            }

            case HResults.CTL_E_FILENOTFOUND: {
                var ex = new System.IO.FileNotFoundException();
                ex.SetErrorCode(errorCode);
                return(ex);
            }

            default:
                throw new NotImplementedException(errorCode.ToString());
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Process a script from a file
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public Results RunScript(string path)
        {
            ResetError();
            Query oQuery = new Query();
            Results oResults = new Results();

            try
            {
                if (!System.IO.File.Exists(path))
                {
                    Results oNoResults = new Results();
                    Exception oFileNotFound = new System.IO.FileNotFoundException("File not found", path);
                    oNoResults.SqlException = oFileNotFound;

                    return oNoResults;
                }

                oQuery.Sql = System.IO.File.ReadAllText(path);

                oResults = Process_SQL(oQuery, CommandType.Text);
            }
            catch (Exception ex)
            {
                oResults.SqlException = ex;
                Error = ex;
            }

            return oResults;
        }
Exemplo n.º 29
0
        //
        // Attempts to persist the security descriptor onto the object
        //

        private void Persist(string name, SafeHandle handle, AccessControlSections includeSections, object exceptionContext)
        {
            WriteLock();

            try
            {
                int error;
                SecurityInfos securityInfo = 0;

                SecurityIdentifier owner = null, group = null;
                SystemAcl sacl = null;
                DiscretionaryAcl dacl = null;

                if ((includeSections & AccessControlSections.Owner) != 0 && _securityDescriptor.Owner != null)
                {
                    securityInfo |= SecurityInfos.Owner;
                    owner = _securityDescriptor.Owner;
                }

                if ((includeSections & AccessControlSections.Group) != 0 && _securityDescriptor.Group != null)
                {
                    securityInfo |= SecurityInfos.Group;
                    group = _securityDescriptor.Group;
                }

                if ((includeSections & AccessControlSections.Audit) != 0)
                {
                    securityInfo |= SecurityInfos.SystemAcl;
                    if (_securityDescriptor.IsSystemAclPresent &&
                         _securityDescriptor.SystemAcl != null &&
                         _securityDescriptor.SystemAcl.Count > 0)
                    {
                        sacl = _securityDescriptor.SystemAcl;
                    }
                    else
                    {
                        sacl = null;
                    }

                    if ((_securityDescriptor.ControlFlags & ControlFlags.SystemAclProtected) != 0)
                    {
                        securityInfo = (SecurityInfos)((uint)securityInfo | ProtectedSystemAcl);
                    }
                    else
                    {
                        securityInfo = (SecurityInfos)((uint)securityInfo | UnprotectedSystemAcl);
                    }
                }

                if ((includeSections & AccessControlSections.Access) != 0 && _securityDescriptor.IsDiscretionaryAclPresent)
                {
                    securityInfo |= SecurityInfos.DiscretionaryAcl;

                    // if the DACL is in fact a crafted replaced for NULL replacement, then we will persist it as NULL
                    if (_securityDescriptor.DiscretionaryAcl.EveryOneFullAccessForNullDacl)
                    {
                        dacl = null;
                    }
                    else
                    {
                        dacl = _securityDescriptor.DiscretionaryAcl;
                    }

                    if ((_securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclProtected) != 0)
                    {
                        securityInfo = (SecurityInfos)((uint)securityInfo | ProtectedDiscretionaryAcl);
                    }
                    else
                    {
                        securityInfo = (SecurityInfos)((uint)securityInfo | UnprotectedDiscretionaryAcl);
                    }
                }

                if (securityInfo == 0)
                {
                    //
                    // Nothing to persist
                    //

                    return;
                }

                error = Win32.SetSecurityInfo(_resourceType, name, handle, securityInfo, owner, group, sacl, dacl);

                if (error != Interop.Errors.ERROR_SUCCESS)
                {
                    System.Exception exception = null;

                    if (_exceptionFromErrorCode != null)
                    {
                        exception = _exceptionFromErrorCode(error, name, handle, exceptionContext);
                    }

                    if (exception == null)
                    {
                        if (error == Interop.Errors.ERROR_ACCESS_DENIED)
                        {
                            exception = new UnauthorizedAccessException();
                        }
                        else if (error == Interop.Errors.ERROR_INVALID_OWNER)
                        {
                            exception = new InvalidOperationException(SR.AccessControl_InvalidOwner);
                        }
                        else if (error == Interop.Errors.ERROR_INVALID_PRIMARY_GROUP)
                        {
                            exception = new InvalidOperationException(SR.AccessControl_InvalidGroup);
                        }
                        else if (error == Interop.Errors.ERROR_INVALID_NAME)
                        {
                            exception = new ArgumentException(
                                 SR.Argument_InvalidName,
nameof(name));
                        }
                        else if (error == Interop.Errors.ERROR_INVALID_HANDLE)
                        {
                            exception = new NotSupportedException(SR.AccessControl_InvalidHandle);
                        }
                        else if (error == Interop.Errors.ERROR_FILE_NOT_FOUND)
                        {
                            exception = new FileNotFoundException();
                        }
                        else if (error == Interop.Errors.ERROR_NO_SECURITY_ON_OBJECT)
                        {
                            exception = new NotSupportedException(SR.AccessControl_NoAssociatedSecurity);
                        }
                        else
                        {
                            Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Unexpected error code {0}", error));
                            exception = new InvalidOperationException(SR.Format(SR.AccessControl_UnexpectedError, error));
                        }
                    }

                    throw exception;
                }

                //
                // Everything goes well, let us clean the modified flags.
                // We are in proper write lock, so just go ahead
                //

                this.OwnerModified = false;
                this.GroupModified = false;
                this.AccessRulesModified = false;
                this.AuditRulesModified = false;
            }
            finally
            {
                WriteUnlock();
            }
        }
Exemplo n.º 30
0
        internal static Exception CreateException(AccountError err, string msg)
        {
            Log.Info(LogTag, "Got Error " + err + " throwing Exception with msg " + msg);
            Exception exp;

            switch (err)
            {
            case AccountError.InvalidParameter:
            {
                exp = new ArgumentException(msg + " Invalid Parameters Provided");
                break;
            }

            case AccountError.OutOfMemory:
            {
                exp = new OutOfMemoryException(msg + " Out Of Memory");
                break;
            }

            case AccountError.InvalidOperation:
            {
                exp = new InvalidOperationException(msg + " Inavlid operation");
                break;
            }

            case AccountError.NoData:
            {
                exp = new InvalidOperationException(msg + " Empty Data");
                break;
            }

            case AccountError.PermissionDenied:
            {
                exp = new UnauthorizedAccessException(msg + " Permission Denied");
                break;
            }

            case AccountError.DBFailed:
            {
                exp = new InvalidOperationException(msg + " DataBase Failed");
                break;
            }

            case AccountError.DBBusy:
            {
                exp = new InvalidOperationException(msg + " DataBase Busy");
                break;
            }

            case AccountError.QuerySyntaxError:
            {
                exp = new InvalidOperationException(msg + " Network Error");
                break;
            }

            case AccountError.XMLFileNotFound:
            {
                exp = new System.IO.FileNotFoundException(msg + " XML File not found");
                break;
            }

            case AccountError.XMLParseFailed:
            {
                exp = new System.IO.InvalidDataException(msg + " XML parse error");
                break;
            }

            default:
            {
                exp = new InvalidOperationException(err + " " + msg);
                break;
            }
            }

            return(exp);
        }
Exemplo n.º 31
0
        /// <summary>
        /// This does a mapping from hr to the exception and also takes care of making default exception in case of classic COM as COMException.
        /// and in winrt and marshal APIs as Exception.
        /// </summary>
        /// <param name="errorCode"></param>
        /// <param name="message"></param>
        /// <param name="createCOMException"></param>
        /// <returns></returns>
        internal static Exception GetMappingExceptionForHR(int errorCode, string message, bool createCOMException, bool hasErrorInfo)
        {
            if (errorCode >= 0)
            {
                return null;
            }

            Exception exception = null;

            bool shouldDisplayHR = false;

            switch (errorCode)
            {
                case __HResults.COR_E_NOTFINITENUMBER: // NotFiniteNumberException
                case __HResults.COR_E_ARITHMETIC:
                    exception = new ArithmeticException();
                    break;
                case __HResults.COR_E_ARGUMENT:
                case unchecked((int)0x800A01C1):
                case unchecked((int)0x800A01C2):
                case __HResults.CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT:
                    exception = new ArgumentException();

                    if (errorCode != __HResults.COR_E_ARGUMENT)
                        shouldDisplayHR = true;

                    break;
                case __HResults.E_BOUNDS:
                case __HResults.COR_E_ARGUMENTOUTOFRANGE:
                case __HResults.ERROR_NO_UNICODE_TRANSLATION:
                    exception = new ArgumentOutOfRangeException();

                    if (errorCode != __HResults.COR_E_ARGUMENTOUTOFRANGE)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_ARRAYTYPEMISMATCH:
                    exception = new ArrayTypeMismatchException();
                    break;
                case __HResults.COR_E_BADIMAGEFORMAT:
                case __HResults.CLDB_E_FILE_OLDVER:
                case __HResults.CLDB_E_INDEX_NOTFOUND:
                case __HResults.CLDB_E_FILE_CORRUPT:
                case __HResults.COR_E_NEWER_RUNTIME:
                case __HResults.COR_E_ASSEMBLYEXPECTED:
                case __HResults.ERROR_BAD_EXE_FORMAT:
                case __HResults.ERROR_EXE_MARKED_INVALID:
                case __HResults.CORSEC_E_INVALID_IMAGE_FORMAT:
                case __HResults.ERROR_NOACCESS:
                case __HResults.ERROR_INVALID_ORDINAL:
                case __HResults.ERROR_INVALID_DLL:
                case __HResults.ERROR_FILE_CORRUPT:
                case __HResults.COR_E_LOADING_REFERENCE_ASSEMBLY:
                case __HResults.META_E_BAD_SIGNATURE:
                    exception = new BadImageFormatException();

                    // Always show HR for BadImageFormatException
                    shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_CUSTOMATTRIBUTEFORMAT:
                    exception = new FormatException();
                    break; // CustomAttributeFormatException
                case __HResults.COR_E_DATAMISALIGNED:
                    exception = InteropExtensions.CreateDataMisalignedException(message); // TODO: Do we need to add msg here?
                    break;
                case __HResults.COR_E_DIVIDEBYZERO:
                case __HResults.CTL_E_DIVISIONBYZERO:
                    exception = new DivideByZeroException();

                    if (errorCode != __HResults.COR_E_DIVIDEBYZERO)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_DLLNOTFOUND:
#if ENABLE_WINRT
                    exception = new DllNotFoundException();
#endif
                    break;
                case __HResults.COR_E_DUPLICATEWAITOBJECT:
                    exception = new ArgumentException();
                    break; // DuplicateWaitObjectException
                case __HResults.COR_E_ENDOFSTREAM:
                case unchecked((int)0x800A003E):
                    exception = new System.IO.EndOfStreamException();

                    if (errorCode != __HResults.COR_E_ENDOFSTREAM)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_TYPEACCESS: // TypeAccessException
                case __HResults.COR_E_ENTRYPOINTNOTFOUND:
                    exception = new TypeLoadException();

                    break; // EntryPointNotFoundException
                case __HResults.COR_E_EXCEPTION:
                    exception = new Exception();
                    break;
                case __HResults.COR_E_DIRECTORYNOTFOUND:
                case __HResults.STG_E_PATHNOTFOUND:
                case __HResults.CTL_E_PATHNOTFOUND:
                    exception = new System.IO.DirectoryNotFoundException();

                    if (errorCode != __HResults.COR_E_DIRECTORYNOTFOUND)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_FILELOAD:
                case __HResults.FUSION_E_INVALID_PRIVATE_ASM_LOCATION:
                case __HResults.FUSION_E_SIGNATURE_CHECK_FAILED:
                case __HResults.FUSION_E_LOADFROM_BLOCKED:
                case __HResults.FUSION_E_CACHEFILE_FAILED:
                case __HResults.FUSION_E_ASM_MODULE_MISSING:
                case __HResults.FUSION_E_INVALID_NAME:
                case __HResults.FUSION_E_PRIVATE_ASM_DISALLOWED:
                case __HResults.FUSION_E_HOST_GAC_ASM_MISMATCH:
                case __HResults.COR_E_MODULE_HASH_CHECK_FAILED:
                case __HResults.FUSION_E_REF_DEF_MISMATCH:
                case __HResults.SECURITY_E_INCOMPATIBLE_SHARE:
                case __HResults.SECURITY_E_INCOMPATIBLE_EVIDENCE:
                case __HResults.SECURITY_E_UNVERIFIABLE:
                case __HResults.COR_E_FIXUPSINEXE:
                case __HResults.ERROR_TOO_MANY_OPEN_FILES:
                case __HResults.ERROR_SHARING_VIOLATION:
                case __HResults.ERROR_LOCK_VIOLATION:
                case __HResults.ERROR_OPEN_FAILED:
                case __HResults.ERROR_DISK_CORRUPT:
                case __HResults.ERROR_UNRECOGNIZED_VOLUME:
                case __HResults.ERROR_DLL_INIT_FAILED:
                case __HResults.FUSION_E_CODE_DOWNLOAD_DISABLED:
                case __HResults.CORSEC_E_MISSING_STRONGNAME:
                case __HResults.MSEE_E_ASSEMBLYLOADINPROGRESS:
                case __HResults.ERROR_FILE_INVALID:
                    exception = new System.IO.FileLoadException();

                    shouldDisplayHR = true;
                    break;
                case __HResults.COR_E_PATHTOOLONG:
                    exception = new System.IO.PathTooLongException();
                    break;
                case __HResults.COR_E_IO:
                case __HResults.CTL_E_DEVICEIOERROR:
                case unchecked((int)0x800A793C):
                case unchecked((int)0x800A793D):
                    exception = new System.IO.IOException();

                    if (errorCode != __HResults.COR_E_IO)
                        shouldDisplayHR = true;

                    break;
                case __HResults.ERROR_FILE_NOT_FOUND:
                case __HResults.ERROR_MOD_NOT_FOUND:
                case __HResults.ERROR_INVALID_NAME:
                case __HResults.CTL_E_FILENOTFOUND:
                case __HResults.ERROR_BAD_NET_NAME:
                case __HResults.ERROR_BAD_NETPATH:
                case __HResults.ERROR_NOT_READY:
                case __HResults.ERROR_WRONG_TARGET_NAME:
                case __HResults.INET_E_UNKNOWN_PROTOCOL:
                case __HResults.INET_E_CONNECTION_TIMEOUT:
                case __HResults.INET_E_CANNOT_CONNECT:
                case __HResults.INET_E_RESOURCE_NOT_FOUND:
                case __HResults.INET_E_OBJECT_NOT_FOUND:
                case __HResults.INET_E_DOWNLOAD_FAILURE:
                case __HResults.INET_E_DATA_NOT_AVAILABLE:
                case __HResults.ERROR_DLL_NOT_FOUND:
                case __HResults.CLR_E_BIND_ASSEMBLY_VERSION_TOO_LOW:
                case __HResults.CLR_E_BIND_ASSEMBLY_PUBLIC_KEY_MISMATCH:
                case __HResults.CLR_E_BIND_ASSEMBLY_NOT_FOUND:
                    exception = new System.IO.FileNotFoundException();

                    shouldDisplayHR = true;
                    break;
                case __HResults.COR_E_FORMAT:
                    exception = new FormatException();
                    break;
                case __HResults.COR_E_INDEXOUTOFRANGE:
                case unchecked((int)0x800a0009):
                    exception = new IndexOutOfRangeException();

                    if (errorCode != __HResults.COR_E_INDEXOUTOFRANGE)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_INVALIDCAST:
                    exception = new InvalidCastException();
                    break;
                case __HResults.COR_E_INVALIDCOMOBJECT:
                    exception = new InvalidComObjectException();
                    break;
                case __HResults.COR_E_INVALIDOLEVARIANTTYPE:
                    exception = new InvalidOleVariantTypeException();
                    break;
                case __HResults.COR_E_INVALIDOPERATION:
                case __HResults.E_ILLEGAL_STATE_CHANGE:
                case __HResults.E_ILLEGAL_METHOD_CALL:
                case __HResults.E_ILLEGAL_DELEGATE_ASSIGNMENT:
                case __HResults.APPMODEL_ERROR_NO_PACKAGE:
                    exception = new InvalidOperationException();

                    if (errorCode != __HResults.COR_E_INVALIDOPERATION)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_MARSHALDIRECTIVE:
                    exception = new MarshalDirectiveException();
                    break;
                case __HResults.COR_E_METHODACCESS: // MethodAccessException
                case __HResults.META_E_CA_FRIENDS_SN_REQUIRED: // MethodAccessException
                case __HResults.COR_E_FIELDACCESS:
                case __HResults.COR_E_MEMBERACCESS:
                    exception = new MemberAccessException();

                    if (errorCode != __HResults.COR_E_METHODACCESS)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_MISSINGFIELD: // MissingFieldException
                case __HResults.COR_E_MISSINGMETHOD: // MissingMethodException
                case __HResults.COR_E_MISSINGMEMBER:
                case unchecked((int)0x800A01CD):
                    exception = new MissingMemberException();
                    break;
                case __HResults.COR_E_MISSINGMANIFESTRESOURCE:
                    exception = new System.Resources.MissingManifestResourceException();
                    break;
                case __HResults.COR_E_NOTSUPPORTED:
                case unchecked((int)0x800A01B6):
                case unchecked((int)0x800A01BD):
                case unchecked((int)0x800A01CA):
                case unchecked((int)0x800A01CB):
                    exception = new NotSupportedException();

                    if (errorCode != __HResults.COR_E_NOTSUPPORTED)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_NULLREFERENCE:
                    exception = new NullReferenceException();
                    break;
                case __HResults.COR_E_OBJECTDISPOSED:
                case __HResults.RO_E_CLOSED:
                    // No default constructor
                    exception = new ObjectDisposedException(String.Empty);
                    break;
                case __HResults.COR_E_OPERATIONCANCELED:
#if ENABLE_WINRT
                    exception = new OperationCanceledException();
#endif
                    break;
                case __HResults.COR_E_OVERFLOW:
                case __HResults.CTL_E_OVERFLOW:
                    exception = new OverflowException();
                    break;
                case __HResults.COR_E_PLATFORMNOTSUPPORTED:
                    exception = new PlatformNotSupportedException(message);
                    break;
                case __HResults.COR_E_RANK:
                    exception = new RankException();
                    break;
                case __HResults.COR_E_REFLECTIONTYPELOAD:
#if ENABLE_WINRT
                    exception = new System.Reflection.ReflectionTypeLoadException(null, null);
#endif
                    break;
                case __HResults.COR_E_SECURITY:
                case __HResults.CORSEC_E_INVALID_STRONGNAME:
                case __HResults.CTL_E_PERMISSIONDENIED:
                case unchecked((int)0x800A01A3):
                case __HResults.CORSEC_E_INVALID_PUBLICKEY:
                case __HResults.CORSEC_E_SIGNATURE_MISMATCH:
                    exception = new System.Security.SecurityException();
                    break;
                case __HResults.COR_E_SAFEARRAYRANKMISMATCH:
                    exception = new SafeArrayRankMismatchException();
                    break;
                case __HResults.COR_E_SAFEARRAYTYPEMISMATCH:
                    exception = new SafeArrayTypeMismatchException();
                    break;
                case __HResults.COR_E_SERIALIZATION:
                    exception = new System.Runtime.Serialization.SerializationException(message);
                    break;
                case __HResults.COR_E_SYNCHRONIZATIONLOCK:
                    exception = new System.Threading.SynchronizationLockException();
                    break;
                case __HResults.COR_E_TARGETINVOCATION:
                    exception = new System.Reflection.TargetInvocationException(null);
                    break;
                case __HResults.COR_E_TARGETPARAMCOUNT:
                    exception = new System.Reflection.TargetParameterCountException();
                    break;
                case __HResults.COR_E_TYPEINITIALIZATION:
                    exception = InteropExtensions.CreateTypeInitializationException(message);
                    break;
                case __HResults.COR_E_TYPELOAD:
                case __HResults.RO_E_METADATA_NAME_NOT_FOUND:
                case __HResults.CLR_E_BIND_TYPE_NOT_FOUND:
                    exception = new TypeLoadException();

                    if (errorCode != __HResults.COR_E_TYPELOAD)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_UNAUTHORIZEDACCESS:
                case __HResults.CTL_E_PATHFILEACCESSERROR:
                case unchecked((int)0x800A014F):
                    exception = new UnauthorizedAccessException();

                    shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_VERIFICATION:
                    exception = new System.Security.VerificationException();
                    break;
                case __HResults.E_NOTIMPL:
                    exception = new NotImplementedException();
                    break;
                case __HResults.E_OUTOFMEMORY:
                case __HResults.CTL_E_OUTOFMEMORY:
                case unchecked((int)0x800A7919):
                    exception = new OutOfMemoryException();

                    if (errorCode != __HResults.E_OUTOFMEMORY)
                        shouldDisplayHR = true;

                    break;
#if ENABLE_WINRT
                case __HResults.E_XAMLPARSEFAILED:
                    exception = ConstructExceptionUsingReflection(
                        "Windows.UI.Xaml.Markup.XamlParseException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                        message);
                    break;
                case __HResults.E_ELEMENTNOTAVAILABLE:
                    exception = ConstructExceptionUsingReflection(
                        "Windows.UI.Xaml.Automation.ElementNotAvailableException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                        message);
                    break;
                case __HResults.E_ELEMENTNOTENABLED:
                    exception = ConstructExceptionUsingReflection(
                        "Windows.UI.Xaml.Automation.ElementNotEnabledException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", 
                        message);
                    break;
                case __HResults.E_LAYOUTCYCLE:
                    exception = ConstructExceptionUsingReflection(
                        "Windows.UI.Xaml.LayoutCycleException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", 
                        message);
                    break;
#endif // ENABLE_WINRT
                case __HResults.COR_E_AMBIGUOUSMATCH: // AmbiguousMatchException
                case __HResults.COR_E_APPLICATION: // ApplicationException
                case __HResults.COR_E_APPDOMAINUNLOADED: // AppDomainUnloadedException
                case __HResults.COR_E_CANNOTUNLOADAPPDOMAIN: // CannotUnloadAppDomainException
                case __HResults.COR_E_CODECONTRACTFAILED: // ContractException
                case __HResults.COR_E_CONTEXTMARSHAL: // ContextMarshalException
                case __HResults.CORSEC_E_CRYPTO: // CryptographicException
                case __HResults.CORSEC_E_CRYPTO_UNEX_OPER: // CryptographicUnexpectedOperationException
                case __HResults.COR_E_EXECUTIONENGINE: // ExecutionEngineException
                case __HResults.COR_E_INSUFFICIENTEXECUTIONSTACK: // InsufficientExecutionStackException
                case __HResults.COR_E_INVALIDFILTERCRITERIA: // InvalidFilterCriteriaException
                case __HResults.COR_E_INVALIDPROGRAM: // InvalidProgramException
                case __HResults.COR_E_MULTICASTNOTSUPPORTED: // MulticastNotSupportedException
                case __HResults.COR_E_REMOTING: // RemotingException
                case __HResults.COR_E_RUNTIMEWRAPPED: // RuntimeWrappedException
                case __HResults.COR_E_SERVER: // ServerException
                case __HResults.COR_E_STACKOVERFLOW: // StackOverflowException
                case __HResults.CTL_E_OUTOFSTACKSPACE: // StackOverflowException
                case __HResults.COR_E_SYSTEM: // SystemException
                case __HResults.COR_E_TARGET: // TargetException
                case __HResults.COR_E_THREADABORTED: // TargetException
                case __HResults.COR_E_THREADINTERRUPTED: // ThreadInterruptedException
                case __HResults.COR_E_THREADSTATE: // ThreadStateException
                case __HResults.COR_E_THREADSTART: // ThreadStartException
                case __HResults.COR_E_TYPEUNLOADED: // TypeUnloadedException
                case __HResults.CORSEC_E_POLICY_EXCEPTION: // PolicyException
                case __HResults.CORSEC_E_NO_EXEC_PERM: // PolicyException
                case __HResults.CORSEC_E_MIN_GRANT_FAIL: // PolicyException
                case __HResults.CORSEC_E_XMLSYNTAX: // XmlSyntaxException
                case __HResults.ISS_E_ALLOC_TOO_LARGE: // IsolatedStorageException
                case __HResults.ISS_E_BLOCK_SIZE_TOO_SMALL: // IsolatedStorageException
                case __HResults.ISS_E_CALLER: // IsolatedStorageException
                case __HResults.ISS_E_CORRUPTED_STORE_FILE: // IsolatedStorageException
                case __HResults.ISS_E_CREATE_DIR: // IsolatedStorageException
                case __HResults.ISS_E_CREATE_MUTEX: // IsolatedStorageException
                case __HResults.ISS_E_DEPRECATE: // IsolatedStorageException
                case __HResults.ISS_E_FILE_NOT_MAPPED: // IsolatedStorageException
                case __HResults.ISS_E_FILE_WRITE: // IsolatedStorageException
                case __HResults.ISS_E_GET_FILE_SIZE: // IsolatedStorageException
                case __HResults.ISS_E_ISOSTORE: // IsolatedStorageException
                case __HResults.ISS_E_LOCK_FAILED: // IsolatedStorageException
                case __HResults.ISS_E_MACHINE: // IsolatedStorageException
                case __HResults.ISS_E_MACHINE_DACL: // IsolatedStorageException
                case __HResults.ISS_E_MAP_VIEW_OF_FILE: // IsolatedStorageException
                case __HResults.ISS_E_OPEN_FILE_MAPPING: // IsolatedStorageException
                case __HResults.ISS_E_OPEN_STORE_FILE: // IsolatedStorageException
                case __HResults.ISS_E_PATH_LENGTH: // IsolatedStorageException
                case __HResults.ISS_E_SET_FILE_POINTER: // IsolatedStorageException
                case __HResults.ISS_E_STORE_NOT_OPEN: // IsolatedStorageException
                case __HResults.ISS_E_STORE_VERSION: // IsolatedStorageException
                case __HResults.ISS_E_TABLE_ROW_NOT_FOUND: // IsolatedStorageException
                case __HResults.ISS_E_USAGE_WILL_EXCEED_QUOTA: // IsolatedStorageException
                case __HResults.E_FAIL:
                default:
                    break;
            }

            if (exception == null)
            {
                if (createCOMException)
                {
                    exception = new COMException();
                    if (errorCode != __HResults.E_FAIL)
                        shouldDisplayHR = true;
                }
                else
                {
                    exception = new Exception();
                    if (errorCode != __HResults.COR_E_EXCEPTION)
                        shouldDisplayHR = true;
                 }
            }

            bool shouldConstructMessage = false;
            if (hasErrorInfo)
            {
                // If there is a IErrorInfo/IRestrictedErrorInfo, only construct a new error message if
                // the message is not available and do not use the shouldDisplayHR setting
                if (message == null)
                    shouldConstructMessage = true;
            }
            else
            {
                // If there is no IErrorInfo, use the shouldDisplayHR setting from the big switch/case above
                shouldConstructMessage = shouldDisplayHR;
            }

            if (shouldConstructMessage)
            {
                //
                // Append the HR into error message, just in case the app wants to look at the HR in
                // message to determine behavior.  We didn't expose HResult property until v4.5 and
                // GetHRFromException has side effects so probably Message was their only choice.
                // This behavior is probably not exactly the same as in desktop but it is fine to append
                // more message at the end. In any case, having the HR in the error message are helpful
                // to developers.
                // This makes sure:
                // 1. We always have a HR 0xNNNNNNNN in the message
                // 2. Put in a nice "Exception thrown from HRESULT" message if we can
                // 3. Wrap it in () if there is an existing message
                //

                // TODO: Add Symbolic Name into Messaage, convert 0x80020006 to DISP_E_UNKNOWNNAME
                string hrMessage = String.Format("{0} 0x{1}", SR.Excep_FromHResult, errorCode.LowLevelToString());

                message = ExternalInterop.GetMessage(errorCode);

                // Always make sure we have at least the HRESULT part in retail build or when the message
                // is empty.
                if (message == null)
                    message = hrMessage;
                else
                    message = message + " (" + hrMessage + ")";
            }

            if (message != null)
            {
                // Set message explicitly rather than calling constructor because certain ctors would append a
                // prefix to the message and that is not what we want
                InteropExtensions.SetExceptionMessage(exception, message);
            }

            InteropExtensions.SetExceptionErrorCode(exception, errorCode);

            return exception;
        }
Exemplo n.º 32
0
        internal static void SetAccessControlExtracted(FileSystemSecurity security, string name)
        {
            //security.WriteLock();
            AccessControlSections includeSections = AccessControlSections.Audit | AccessControlSections.Owner | AccessControlSections.Group;

            SecurityInfos securityInfo = (SecurityInfos)0;
            SecurityIdentifier owner = null;
            SecurityIdentifier group = null;
            SystemAcl sacl = null;
            DiscretionaryAcl dacl = null;
            if ((includeSections & AccessControlSections.Owner) != AccessControlSections.None)
            {
                owner = (SecurityIdentifier)security.GetOwner(typeof(SecurityIdentifier));
                if (owner != null)
                {
                    securityInfo = securityInfo | SecurityInfos.Owner;
                }
            }

            if ((includeSections & AccessControlSections.Group) != AccessControlSections.None)
            {
                group = (SecurityIdentifier)security.GetGroup(typeof(SecurityIdentifier));
                if (group != null)
                {
                    securityInfo = securityInfo | SecurityInfos.Group;
                }
            }
            var securityDescriptorBinaryForm = security.GetSecurityDescriptorBinaryForm();
            RawSecurityDescriptor rawSecurityDescriptor = null;
            bool isDiscretionaryAclPresent = false;
            if (securityDescriptorBinaryForm != null)
            {
                rawSecurityDescriptor = new RawSecurityDescriptor(securityDescriptorBinaryForm, 0);
                isDiscretionaryAclPresent = (rawSecurityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclPresent) != ControlFlags.None;
            }

            if ((includeSections & AccessControlSections.Audit) != AccessControlSections.None)
            {
                securityInfo = securityInfo | SecurityInfos.SystemAcl;
                sacl = null;
                if (rawSecurityDescriptor != null)
                {
                    var isSystemAclPresent = (rawSecurityDescriptor.ControlFlags & ControlFlags.SystemAclPresent) != ControlFlags.None;
                    if (isSystemAclPresent && rawSecurityDescriptor.SystemAcl != null && rawSecurityDescriptor.SystemAcl.Count > 0)
                    {
                        // are all system acls on a file not a container?
                        const bool notAContainer = false;
                        const bool notADirectoryObjectACL = false;

                        sacl = new SystemAcl(notAContainer, notADirectoryObjectACL,
                            rawSecurityDescriptor.SystemAcl);
                    }
                    securityInfo = (SecurityInfos)(((rawSecurityDescriptor.ControlFlags & ControlFlags.SystemAclProtected) == ControlFlags.None ?
                        (uint)securityInfo | UnprotectedSystemAcl : (uint)securityInfo | ProtectedSystemAcl));
                }
            }
            if ((includeSections & AccessControlSections.Access) != AccessControlSections.None && isDiscretionaryAclPresent)
            {
                securityInfo = securityInfo | SecurityInfos.DiscretionaryAcl;
                dacl = null;
                if (rawSecurityDescriptor != null)
                {
                    //if (!this._securityDescriptor.DiscretionaryAcl.EveryOneFullAccessForNullDacl)
                    {
                        dacl = new DiscretionaryAcl(false, false, rawSecurityDescriptor.DiscretionaryAcl);
                    }
                    securityInfo = (SecurityInfos)(((rawSecurityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclProtected) == ControlFlags.None ?
                        (uint)securityInfo | UnprotectedDiscretionaryAcl : (uint)securityInfo | ProtectedDiscretionaryAcl));
                }
            }
            if (securityInfo == 0) return;

            int errorNum = SetSecurityInfo(ResourceType.FileObject, name, null, securityInfo, owner, group, sacl, dacl);
            if (errorNum != 0)
            {
                Exception exception = Common.GetExceptionFromWin32Error(errorNum, name);
                if (exception == null)
                {
                    if (errorNum == NativeMethods.ERROR_ACCESS_DENIED)
                    {
                        exception = new UnauthorizedAccessException();
                    }
                    else if (errorNum == NativeMethods.ERROR_INVALID_OWNER)
                    {
                        exception = new InvalidOperationException("Invalid owner");
                    }
                    else if (errorNum == NativeMethods.ERROR_INVALID_PRIMARY_GROUP)
                    {
                        exception = new InvalidOperationException("Invalid group");
                    }
                    else if (errorNum == NativeMethods.ERROR_INVALID_NAME)
                    {
                        exception = new ArgumentException("Invalid name", "name");
                    }
                    else if (errorNum == NativeMethods.ERROR_INVALID_HANDLE)
                    {
                        exception = new NotSupportedException("Invalid Handle");
                    }
                    else if (errorNum == NativeMethods.ERROR_FILE_NOT_FOUND)
                    {
                        exception = new FileNotFoundException();
                    }
                    else if (errorNum != NativeMethods.ERROR_NO_SECURITY_ON_OBJECT)
                    {
                        exception = new InvalidOperationException("Unexpected error");
                    }
                    else
                    {
                        exception = new NotSupportedException("No associated security");
                    }
                }
                throw exception;
            }
            //finally
            //{
                //security.WriteLUnlck();
            //}
        }
Exemplo n.º 33
0
        //
        // Attempts to persist the security descriptor onto the object
        //

        private void Persist(string name, SafeHandle handle, AccessControlSections includeSections, object exceptionContext)
        {
            WriteLock();

            try
            {
                int           error;
                SecurityInfos securityInfo = 0;

                SecurityIdentifier owner = null, group = null;
                SystemAcl          sacl = null;
                DiscretionaryAcl   dacl = null;

                if ((includeSections & AccessControlSections.Owner) != 0 && _securityDescriptor.Owner != null)
                {
                    securityInfo |= SecurityInfos.Owner;
                    owner         = _securityDescriptor.Owner;
                }

                if ((includeSections & AccessControlSections.Group) != 0 && _securityDescriptor.Group != null)
                {
                    securityInfo |= SecurityInfos.Group;
                    group         = _securityDescriptor.Group;
                }

                if ((includeSections & AccessControlSections.Audit) != 0)
                {
                    securityInfo |= SecurityInfos.SystemAcl;
                    if (_securityDescriptor.IsSystemAclPresent &&
                        _securityDescriptor.SystemAcl != null &&
                        _securityDescriptor.SystemAcl.Count > 0)
                    {
                        sacl = _securityDescriptor.SystemAcl;
                    }
                    else
                    {
                        sacl = null;
                    }

                    if ((_securityDescriptor.ControlFlags & ControlFlags.SystemAclProtected) != 0)
                    {
                        securityInfo = (SecurityInfos)((uint)securityInfo | ProtectedSystemAcl);
                    }
                    else
                    {
                        securityInfo = (SecurityInfos)((uint)securityInfo | UnprotectedSystemAcl);
                    }
                }

                if ((includeSections & AccessControlSections.Access) != 0 && _securityDescriptor.IsDiscretionaryAclPresent)
                {
                    securityInfo |= SecurityInfos.DiscretionaryAcl;

                    // if the DACL is in fact a crafted replaced for NULL replacement, then we will persist it as NULL
                    if (_securityDescriptor.DiscretionaryAcl.EveryOneFullAccessForNullDacl)
                    {
                        dacl = null;
                    }
                    else
                    {
                        dacl = _securityDescriptor.DiscretionaryAcl;
                    }

                    if ((_securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclProtected) != 0)
                    {
                        securityInfo = unchecked ((SecurityInfos)((uint)securityInfo | ProtectedDiscretionaryAcl));
                    }
                    else
                    {
                        securityInfo = (SecurityInfos)((uint)securityInfo | UnprotectedDiscretionaryAcl);
                    }
                }

                if (securityInfo == 0)
                {
                    //
                    // Nothing to persist
                    //

                    return;
                }

                error = Win32.SetSecurityInfo(_resourceType, name, handle, securityInfo, owner, group, sacl, dacl);

                if (error != Interop.Errors.ERROR_SUCCESS)
                {
                    System.Exception exception = null;

                    if (_exceptionFromErrorCode != null)
                    {
                        exception = _exceptionFromErrorCode(error, name, handle, exceptionContext);
                    }

                    if (exception == null)
                    {
                        if (error == Interop.Errors.ERROR_ACCESS_DENIED)
                        {
                            exception = new UnauthorizedAccessException();
                        }
                        else if (error == Interop.Errors.ERROR_INVALID_OWNER)
                        {
                            exception = new InvalidOperationException(SR.AccessControl_InvalidOwner);
                        }
                        else if (error == Interop.Errors.ERROR_INVALID_PRIMARY_GROUP)
                        {
                            exception = new InvalidOperationException(SR.AccessControl_InvalidGroup);
                        }
                        else if (error == Interop.Errors.ERROR_INVALID_NAME)
                        {
                            exception = new ArgumentException(SR.Argument_InvalidName, nameof(name));
                        }
                        else if (error == Interop.Errors.ERROR_INVALID_HANDLE)
                        {
                            exception = new NotSupportedException(SR.AccessControl_InvalidHandle);
                        }
                        else if (error == Interop.Errors.ERROR_FILE_NOT_FOUND)
                        {
                            exception = new FileNotFoundException();
                        }
                        else if (error == Interop.Errors.ERROR_NO_SECURITY_ON_OBJECT)
                        {
                            exception = new NotSupportedException(SR.AccessControl_NoAssociatedSecurity);
                        }
                        else
                        {
                            Debug.Fail($"Unexpected error code {error}");
                            exception = new InvalidOperationException(SR.Format(SR.AccessControl_UnexpectedError, error));
                        }
                    }

                    throw exception;
                }

                //
                // Everything goes well, let us clean the modified flags.
                // We are in proper write lock, so just go ahead
                //

                this.OwnerModified       = false;
                this.GroupModified       = false;
                this.AccessRulesModified = false;
                this.AuditRulesModified  = false;
            }
            finally
            {
                WriteUnlock();
            }
        }
Exemplo n.º 34
0
        /// <summary>
        ///		Create new instance signalling that a data file previously known to exist was not found on disk.
        /// </summary>
        /// <param name="folder">
        ///		The repo folder in which the accident occurred.
        /// </param>
        /// <param name="innerException">
        ///		The <see cref="System.IO.FileNotFoundException"/> which was thrown in response to the error.
        ///		Its <see cref="System.IO.FileNotFoundException.FileName"/> will be used to format the error message.
        /// </param>
        /// <returns>
        ///		New <see cref="ConcurrencyException"/> instance
        /// </returns>
        public static ConcurrencyException GetFileNotFound(IRepositoryFolder folder, System.IO.FileNotFoundException innerException)
        {
            string message = string.Format(Storage.StorageResources.DataFileNotFound, innerException.FileName);

            return(new ConcurrencyException(folder, Storage.StorageResources.PotentialConcurrencyIssueMessage, message, innerException));
        }