Inheritance: IOException, System.Runtime.Serialization.ISerializable, System.Runtime.InteropServices._Exception
 public static void Ctor_String()
 {
     string message = "this is not the file you're looking for";
     var exception = new FileNotFoundException(message);
     ExceptionUtility.ValidateExceptionProperties(exception, hResult: HResults.COR_E_FILENOTFOUND, message: message);
     Assert.Null(exception.FileName);
 }
    public bool PosTest1()
    {
        bool retVal = true;
        FileNotFoundException fnfe;
        string str;

        TestLibrary.TestFramework.BeginScenario("PosTest1: FileNotFoundException.Ctor(string)");

        try
        {
            str = TestLibrary.Generator.GetString(-55, false, c_MIN_STRLEN, c_MAX_STRLEN);
            fnfe = new FileNotFoundException(str);

            if (!fnfe.Message.Equals(str))
            {
                TestLibrary.TestFramework.LogError("001", "Message is not expected: Expected("+str+") Actual("+fnfe.Message+")");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
    public bool PosTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest2: Create a new FileNotFoundException instance,string is empty.");

        try
        {
            string expectString = string.Empty;
            //Create the application domain setup information.
            FileNotFoundException myFileNotFoundException = new FileNotFoundException(expectString);
            if (myFileNotFoundException.Message != expectString)
            {
                TestLibrary.TestFramework.LogError("002.1", "the FileNotFoundException ctor error occurred.the message should be " + expectString);
                retVal = false;
            }

        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
    public bool PosTest3()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest3: Create a new FileNotFoundException instance,string is null,then its inner exception set to a null reference .");

        try
        {
            string expectString = null;
            //Create the application domain setup information.
            FileNotFoundException myFileNotFoundException = new FileNotFoundException(expectString);
            if (myFileNotFoundException.Message != null)
            {
                TestLibrary.TestFramework.LogError("003.1", "the FileNotFoundException ctor error occurred. the message should be null");
                retVal = false;
            }

        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Create a new FileNotFoundException instance.");

        try
        {
            //Create the application domain setup information.
            FileNotFoundException myFileNotFoundException = new FileNotFoundException();
            if (myFileNotFoundException == null)
            {
                TestLibrary.TestFramework.LogError("001.1", "the FileNotFoundException ctor error occurred. ");
                retVal = false;
            }

        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
Exemplo n.º 6
0
    public bool PosTest1()
    {
        bool retVal = true;
        FileNotFoundException fnfe;

        TestLibrary.TestFramework.BeginScenario("PosTest1: FileNotFoundException.Ctor");

        try
        {
            fnfe = new FileNotFoundException();

            if (null == fnfe.Message)
            {
                TestLibrary.TestFramework.LogError("001", "Message is null!");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
 public static void Ctor_String_Exception()
 {
     string message = "this is not the file you're looking for";
     var innerException = new Exception("Inner exception");
     var exception = new FileNotFoundException(message, innerException);
     ExceptionUtility.ValidateExceptionProperties(exception, hResult: HResults.COR_E_FILENOTFOUND, innerException: innerException, message: message);
     Assert.Equal(null, exception.FileName);
 }
        public static void ToStringTest()
        {
            string message = "this is not the file you're looking for";
            string fileName = "file.txt";
            var innerException = new Exception("Inner exception");
            var exception = new FileNotFoundException(message, fileName, innerException);

            var toString = exception.ToString();
            Assert.Contains(": " + message, toString);
            Assert.Contains(": '" + fileName + "'", toString);
            Assert.Contains("---> " + innerException.ToString(), toString);

            // set the stack trace
            try { throw exception; }
            catch
            {
                Assert.False(string.IsNullOrEmpty(exception.StackTrace));
                Assert.Contains(exception.StackTrace, exception.ToString());
            }
        }
Exemplo n.º 9
0
        protected override void ProcessRecord()
        {
            foreach (var computer in _computername)
            {
                ConnectionInfo connectInfo;
                if (_keyfile.Equals(""))
                {
                    WriteVerbose("Using SSH Username and Password authentication for connection.");
                    var kIconnectInfo = new KeyboardInteractiveAuthenticationMethod(_credential.UserName);
                    connectInfo = ConnectionInfoGenerator.GetCredConnectionInfo(computer,
                                                                                _port,
                                                                                _credential,
                                                                                _proxyserver,
                                                                                _proxytype,
                                                                                _proxyport,
                                                                                _proxycredential,
                                                                                kIconnectInfo);

                    // Event Handler for interactive Authentication
                    kIconnectInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
                    {
                        foreach (var prompt in e.Prompts)
                        {
                            if (prompt.Request.Contains("Password"))
                            {
                                prompt.Response = _credential.GetNetworkCredential().Password;
                            }
                        }
                    };
                }
                else
                {
                    WriteVerbose("Using SSH Key authentication for connection.");
                    connectInfo = ConnectionInfoGenerator.GetKeyConnectionInfo(computer,
                                                                               _port,
                                                                               _keyfile,
                                                                               _credential,
                                                                               _proxyserver,
                                                                               _proxytype,
                                                                               _proxyport,
                                                                               _proxycredential);
                }

                //Ceate instance of SSH Client with connection info
                var client = new ScpClient(connectInfo);


                // Handle host key
                var computer1 = computer;
                client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                {
                    var sb = new StringBuilder();
                    foreach (var b in e.FingerPrint)
                    {
                        sb.AppendFormat("{0:x}:", b);
                    }
                    var fingerPrint = sb.ToString().Remove(sb.ToString().Length - 1);

                    if (_sshHostKeys.ContainsKey(computer1))
                    {
                        if (_sshHostKeys[computer1] == fingerPrint)
                        {
                            if (MyInvocation.BoundParameters.ContainsKey("Verbose"))
                            {
                                Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerprint for host " + computer1);
                            }
                            e.CanTrust = true;
                        }
                        else
                        {
                            var ex = new System.Security.SecurityException("SSH fingerprint mismatch for host " + computer1);
                            ThrowTerminatingError(new ErrorRecord(
                                                      ex,
                                                      "SSH fingerprint mismatch for host " + computer1,
                                                      ErrorCategory.SecurityError,
                                                      computer1));
                        }
                    }
                    else
                    {
                        int choice;
                        if (_acceptkey)
                        {
                            choice = 0;
                        }
                        else
                        {
                            var choices = new Collection <ChoiceDescription>
                            {
                                new ChoiceDescription("Y"),
                                new ChoiceDescription("N")
                            };

                            choice = Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + fingerPrint, choices, 1);
                        }
                        if (choice == 0)
                        {
                            var keymng = new TrustedKeyMng();
                            keymng.SetKey(computer1, fingerPrint);
                            e.CanTrust = true;
                        }
                        else
                        {
                            e.CanTrust = false;
                        }
                    }
                };
                // Set the connection timeout
                client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout);

                // Connect to host using Connection info
                client.Connect();
                //client.BufferSize = 1024;

                var counter = 0;
                // Print progess of download.
                client.Uploading += delegate(object sender, ScpUploadEventArgs e)
                {
                    if (e.Size != 0)
                    {
                        counter++;

                        if (counter > 900)
                        {
                            var percent = Convert.ToInt32((e.Uploaded * 100) / e.Size);

                            if (percent == 100)
                            {
                                return;
                            }

                            var progressRecord = new ProgressRecord(1,
                                                                    "Uploading " + e.Filename,
                                                                    String.Format("{0} Bytes Uploaded of {1}",
                                                                                  e.Uploaded, e.Size))
                            {
                                PercentComplete = percent
                            };

                            Host.UI.WriteProgress(1, progressRecord);
                            counter = 0;
                        }
                    }
                };

                WriteVerbose("Connection successful");

                // Resolve the path even if a relative one is given.
                ProviderInfo provider;
                var          pathinfo      = GetResolvedProviderPathFromPSPath(_localfile, out provider);
                var          localfullPath = pathinfo[0];

                if (File.Exists(@localfullPath))
                {
                    WriteVerbose("Uploading " + localfullPath);
                    var fil            = new FileInfo(@localfullPath);
                    var remoteFullpath = RemotePath.TrimEnd(new[] { '/' }) + "/" + fil.Name;
                    client.Upload(fil, remoteFullpath);

                    client.Disconnect();
                }
                else
                {
                    var ex = new FileNotFoundException("File to upload " + localfullPath + " was not found.");

                    ThrowTerminatingError(new ErrorRecord(
                                              ex,
                                              "File to upload " + localfullPath + " was not found.",
                                              ErrorCategory.InvalidArgument,
                                              localfullPath));
                }
            }
        } // End process record
Exemplo n.º 10
0
 private void SinkWarning(FileNotFoundException ex)
 {
     // no-op - we're just getting rid of compiler warnings...
 }
Exemplo n.º 11
0
    private void OpenBackground_DoWork(object sender, DoWorkEventArgs e)
    {
        try
        {
            using (FileStream stream = new FileStream(ProjectSavePath, FileMode.Open))
            {
                ZipFile zippy = new ZipFile(stream);

                //File (*.depro) Version
                int Fileversion = Convert.ToInt32(zippy.ZipFileComment);
                if (Fileversion == 2) { OpenProjectV2(zippy); }
                else
                {
                    ThreadException = new NotSupportedException("This fileversion is not supported! Sorry!");
                    e.Result = false;
                    return;
                }
            }

            //checking for missing files: (make option to search for it later)
            bool filenotfound = false;
            for (int i = 0; i < AllFiles.Count; i++)
            {
                if (File.Exists(AllFiles[i].FilePath) == false){ filenotfound = true; break; }
            }
            if (filenotfound == true)
            {
                ThreadException = new FileNotFoundException();
                e.Result = false;
                return;
            }

            e.Result = true;
        }
        catch (Exception ex)
        {
            e.Result = false;
            ThreadException = ex;
        }
    }
Exemplo n.º 12
0
        /// <summary>
        /// Implements the record processing for this cmdlet.
        /// </summary>
        protected override void ProcessRecord()
        {
            ProviderInfo        provider = null;
            Collection <string> filePaths;

            try
            {
                if (Context.EngineSessionState.IsProviderLoaded(Context.ProviderNames.FileSystem))
                {
                    filePaths =
                        SessionState.Path.GetResolvedProviderPathFromPSPath(_path, out provider);
                }
                else
                {
                    filePaths = new Collection <string>();
                    filePaths.Add(_path);
                }
            }
            catch (ItemNotFoundException)
            {
                string message            = StringUtil.Format(Modules.ModuleNotFound, _path);
                FileNotFoundException fnf = new FileNotFoundException(message);
                ErrorRecord           er  = new ErrorRecord(fnf, "Modules_ModuleNotFound",
                                                            ErrorCategory.ResourceUnavailable, _path);
                WriteError(er);
                return;
            }

            // Make sure that the path is in the file system - that's all we can handle currently...
            if (!provider.NameEquals(this.Context.ProviderNames.FileSystem))
            {
                // "The current provider ({0}) cannot open a file"
                throw InterpreterError.NewInterpreterException(_path, typeof(RuntimeException),
                                                               null, "FileOpenError", ParserStrings.FileOpenError, provider.FullName);
            }

            // Make sure at least one file was found...
            if (filePaths == null || filePaths.Count < 1)
            {
                string message            = StringUtil.Format(Modules.ModuleNotFound, _path);
                FileNotFoundException fnf = new FileNotFoundException(message);
                ErrorRecord           er  = new ErrorRecord(fnf, "Modules_ModuleNotFound",
                                                            ErrorCategory.ResourceUnavailable, _path);
                WriteError(er);
                return;
            }

            if (filePaths.Count > 1)
            {
                // "The path resolved to more than one file; can only process one file at a time."
                throw InterpreterError.NewInterpreterException(filePaths, typeof(RuntimeException),
                                                               null, "AmbiguousPath", ParserStrings.AmbiguousPath);
            }

            string             filePath   = filePaths[0];
            ExternalScriptInfo scriptInfo = null;
            string             ext        = System.IO.Path.GetExtension(filePath);

            if (ext.Equals(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase))
            {
                // Create a script info for loading the file...
                string scriptName;
                scriptInfo = GetScriptInfoForFile(filePath, out scriptName, false);

                // we should reserve the Context.ModuleBeingProcessed unchanged after loadModuleManifest(), otherwise the module won't be importable next time.
                PSModuleInfo module;
                string       _origModuleBeingProcessed = Context.ModuleBeingProcessed;
                try
                {
                    module = LoadModuleManifest(
                        scriptInfo,
                        ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings /* but don't stop on first error and don't load elements */,
                        null,
                        null,
                        null,
                        null);

                    if (module != null)
                    {
                        // Validate file existence
                        if (module.RequiredAssemblies != null)
                        {
                            foreach (string requiredAssembliespath in module.RequiredAssemblies)
                            {
                                if (!IsValidFilePath(requiredAssembliespath, module, true) && !IsValidGacAssembly(requiredAssembliespath))
                                {
                                    string errorMsg    = StringUtil.Format(Modules.InvalidRequiredAssembliesInModuleManifest, requiredAssembliespath, filePath);
                                    var    errorRecord = new ErrorRecord(new DirectoryNotFoundException(errorMsg), "Modules_InvalidRequiredAssembliesInModuleManifest",
                                                                         ErrorCategory.ObjectNotFound, _path);
                                    WriteError(errorRecord);
                                }
                            }
                        }

                        // RootModule can be null, empty string or point to a valid .psm1, , .cdxml, .xaml or .dll.  Anything else is invalid.
                        if (module.RootModule != null && module.RootModule != string.Empty)
                        {
                            string rootModuleExt = System.IO.Path.GetExtension(module.RootModule);
                            if ((!IsValidFilePath(module.RootModule, module, true) && !IsValidGacAssembly(module.RootModule)) ||
                                (!rootModuleExt.Equals(StringLiterals.PowerShellModuleFileExtension, StringComparison.OrdinalIgnoreCase) &&
                                 !rootModuleExt.Equals(".dll", StringComparison.OrdinalIgnoreCase) &&
                                 !rootModuleExt.Equals(".cdxml", StringComparison.OrdinalIgnoreCase) &&
                                 !rootModuleExt.Equals(".xaml", StringComparison.OrdinalIgnoreCase))
                                )
                            {
                                string errorMsg    = StringUtil.Format(Modules.InvalidModuleManifest, module.RootModule, filePath);
                                var    errorRecord = new ErrorRecord(new ArgumentException(errorMsg), "Modules_InvalidRootModuleInModuleManifest",
                                                                     ErrorCategory.InvalidArgument, _path);
                                WriteError(errorRecord);
                            }
                        }

                        Hashtable data            = null;
                        Hashtable localizedData   = null;
                        bool      containerErrors = false;
                        LoadModuleManifestData(scriptInfo, ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out data, out localizedData, ref containerErrors);
                        ModuleSpecification[] nestedModules;
                        GetScalarFromData(data, scriptInfo.Path, "NestedModules", ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out nestedModules);
                        if (nestedModules != null)
                        {
                            foreach (ModuleSpecification nestedModule in nestedModules)
                            {
                                if (!IsValidFilePath(nestedModule.Name, module, true) &&
                                    !IsValidFilePath(nestedModule.Name + StringLiterals.PowerShellILAssemblyExtension, module, true) &&
                                    !IsValidFilePath(nestedModule.Name + StringLiterals.PowerShellNgenAssemblyExtension, module, true) &&
                                    !IsValidFilePath(nestedModule.Name + StringLiterals.PowerShellModuleFileExtension, module, true) &&
                                    !IsValidGacAssembly(nestedModule.Name))
                                {
                                    Collection <PSModuleInfo> modules = GetModuleIfAvailable(nestedModule);
                                    if (0 == modules.Count)
                                    {
                                        string errorMsg    = StringUtil.Format(Modules.InvalidNestedModuleinModuleManifest, nestedModule.Name, filePath);
                                        var    errorRecord = new ErrorRecord(new DirectoryNotFoundException(errorMsg), "Modules_InvalidNestedModuleinModuleManifest",
                                                                             ErrorCategory.ObjectNotFound, _path);
                                        WriteError(errorRecord);
                                    }
                                }
                            }
                        }

                        ModuleSpecification[] requiredModules;
                        GetScalarFromData(data, scriptInfo.Path, "RequiredModules", ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out requiredModules);
                        if (requiredModules != null)
                        {
                            foreach (ModuleSpecification requiredModule in requiredModules)
                            {
                                var modules = GetModule(new[] { requiredModule.Name }, all: false, refresh: true);
                                if (modules.Count == 0)
                                {
                                    string errorMsg    = StringUtil.Format(Modules.InvalidRequiredModulesinModuleManifest, requiredModule.Name, filePath);
                                    var    errorRecord = new ErrorRecord(new DirectoryNotFoundException(errorMsg), "Modules_InvalidRequiredModulesinModuleManifest",
                                                                         ErrorCategory.ObjectNotFound, _path);
                                    WriteError(errorRecord);
                                }
                            }
                        }

                        string[] fileListPaths;
                        GetScalarFromData(data, scriptInfo.Path, "FileList", ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out fileListPaths);
                        if (fileListPaths != null)
                        {
                            foreach (string fileListPath in fileListPaths)
                            {
                                if (!IsValidFilePath(fileListPath, module, true))
                                {
                                    string errorMsg    = StringUtil.Format(Modules.InvalidFilePathinModuleManifest, fileListPath, filePath);
                                    var    errorRecord = new ErrorRecord(new DirectoryNotFoundException(errorMsg), "Modules_InvalidFilePathinModuleManifest",
                                                                         ErrorCategory.ObjectNotFound, _path);
                                    WriteError(errorRecord);
                                }
                            }
                        }

                        ModuleSpecification[] moduleListModules;
                        GetScalarFromData(data, scriptInfo.Path, "ModuleList", ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out moduleListModules);
                        if (moduleListModules != null)
                        {
                            foreach (ModuleSpecification moduleListModule in moduleListModules)
                            {
                                var modules = GetModule(new[] { moduleListModule.Name }, all: false, refresh: true);
                                if (modules.Count == 0)
                                {
                                    string errorMsg    = StringUtil.Format(Modules.InvalidModuleListinModuleManifest, moduleListModule.Name, filePath);
                                    var    errorRecord = new ErrorRecord(new DirectoryNotFoundException(errorMsg), "Modules_InvalidModuleListinModuleManifest",
                                                                         ErrorCategory.ObjectNotFound, _path);
                                    WriteError(errorRecord);
                                }
                            }
                        }

                        if (module.CompatiblePSEditions.Any())
                        {
                            // The CompatiblePSEditions module manifest key is supported only on PowerShell version '5.1' or higher.
                            // Ensure that PowerShellVersion module manifest key value is '5.1' or higher.
                            //
                            var minimumRequiredPowerShellVersion = new Version(5, 1);
                            if ((module.PowerShellVersion == null) || module.PowerShellVersion < minimumRequiredPowerShellVersion)
                            {
                                string errorMsg    = StringUtil.Format(Modules.InvalidPowerShellVersionInModuleManifest, filePath);
                                var    errorRecord = new ErrorRecord(new ArgumentException(errorMsg), "Modules_InvalidPowerShellVersionInModuleManifest", ErrorCategory.InvalidArgument, _path);
                                WriteError(errorRecord);
                            }
                        }
                    }
                }
                finally
                {
                    Context.ModuleBeingProcessed = _origModuleBeingProcessed;
                }

                DirectoryInfo parent = null;
                try
                {
                    parent = Directory.GetParent(filePath);
                }
                catch (IOException) { }
                catch (UnauthorizedAccessException) { }
                catch (ArgumentException) { }

                Version version;
                if (parent != null && Version.TryParse(parent.Name, out version))
                {
                    if (!version.Equals(module.Version))
                    {
                        string      message = StringUtil.Format(Modules.InvalidModuleManifestVersion, filePath, module.Version.ToString(), parent.FullName);
                        var         ioe     = new InvalidOperationException(message);
                        ErrorRecord er      = new ErrorRecord(ioe, "Modules_InvalidModuleManifestVersion",
                                                              ErrorCategory.InvalidArgument, _path);
                        ThrowTerminatingError(er);
                    }

                    WriteVerbose(Modules.ModuleVersionEqualsToVersionFolder);
                }

                if (module != null)
                {
                    WriteObject(module);
                }
            }
            else
            {
                string message = StringUtil.Format(Modules.InvalidModuleManifestPath, filePath);
                InvalidOperationException ioe = new InvalidOperationException(message);
                ErrorRecord er = new ErrorRecord(ioe, "Modules_InvalidModuleManifestPath",
                                                 ErrorCategory.InvalidArgument, _path);
                ThrowTerminatingError(er);
            }
        }
Exemplo n.º 13
0
        private void RegisterTypeOrInstanceToUnity(Config.ObjectItem objectConfiguration)
        {
            try
            {
                //判断配置的值
                if (string.IsNullOrEmpty(objectConfiguration.Name) || string.IsNullOrEmpty(objectConfiguration.Interface) || string.IsNullOrEmpty(objectConfiguration.Implement))
                {
                    return;
                }

                //获取程序集名称,判断是否已经有后缀
                string assemblyName = objectConfiguration.Implement;

                string[] assemblyInfos = assemblyName.Split(';');
                if (assemblyInfos.Length != 2)
                {
                    return;
                }

                assemblyName = assemblyInfos[0];

                if (assemblyName.LastIndexOf(".dll") < 0)
                {
                    assemblyName += ".dll";
                }

                string assemblyPath = System.IO.Path.Combine(PlatformConfig.ServerConfig.IOCSetting.AssemblyFilePath, assemblyName);

                //判断程序集是否存在
                if (!System.IO.File.Exists(assemblyPath))
                {
                    return;
                }

                //装载程序集
                System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFile(assemblyPath);

                //如果装载失败
                if (assembly == null)
                {
                    return;
                }

                //反射得到所有的程序集中的类型
                Type[] types = assembly.GetTypes();

                //循环所有的类型,准备注册
                foreach (var type in types)
                {
                    if (type.IsAbstract || type.IsInterface || type.IsGenericType)
                    {
                        continue;
                    }

                    //if (Config.PlatformConfig.ServerConfig.IOCSetting.InterceptionItems.Where(pre => System.IO.Path.GetFileNameWithoutExtension(pre.AssemblyName) == (System.IO.Path.GetFileNameWithoutExtension(objectConfiguration.Value))).Count() == 0) //判断如果注册拦截其器则拦截,否则不拦截
                    //    RegisterType(type, objectConfiguration.LifeCycle);
                    //else
                    RegisterInterceptionType(type, "Singleton");
                }
            }
            catch (ReflectionTypeLoadException ex)
            {
                StringBuilder sb = new StringBuilder();
                foreach (Exception exSub in ex.LoaderExceptions)
                {
                    sb.AppendLine(exSub.Message);
                    if (exSub is FileNotFoundException)
                    {
                        FileNotFoundException exFileNotFound = exSub as FileNotFoundException;
                        if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
                        {
                            sb.AppendLine("Fusion Log:");
                            sb.AppendLine(exFileNotFound.FusionLog);
                        }
                    }
                    sb.AppendLine();
                }
                string errorMessage = sb.ToString();

                log4netLogger.Debug("注册类型的过程中出现错误" + errorMessage);
#if DEBUG
                throw;
#endif
            }
        }
Exemplo n.º 14
0
        protected override void ProcessRecord()
        {
            // check if the path specified actually exists.
            // Resolve the path even if a relative one is given for PowerShell.
            ProviderInfo provider;
            var          pathinfo      = GetResolvedProviderPathFromPSPath(_localpath, out provider);
            var          localfullPath = pathinfo[0];

            if (Directory.Exists(@localfullPath))
            {
                foreach (var sftpSession in ToProcess)
                {
                    foreach (string remotepath in _remotepath)
                    {
                        // Check that the path we are downloading from actually exists on the target.
                        if (sftpSession.Session.Exists(remotepath))
                        {
                            // Check if the remote path is a file or a directory to perform proper action.
                            var attribs = sftpSession.Session.GetAttributes(remotepath);

                            if (attribs.IsDirectory)
                            {
                                string dirName      = new DirectoryInfo(remotepath).Name;
                                var    fileFullPath = $"{@localfullPath}{System.IO.Path.DirectorySeparatorChar}{dirName}";

                                var present = Directory.Exists(fileFullPath);
                                if ((present & _overwrite) || (!present))
                                {
                                    var res = new Action <ulong>(rs =>
                                    {
                                        if (attribs.Size != 0)
                                        {
                                            var percent = (int)((((double)rs) / attribs.Size) * 100.0);
                                            if (percent % 10 == 0)
                                            {
                                                // This should prevent the progress message from being stuck on the screen.
                                                if (percent == 100)
                                                {
                                                    return;
                                                }

                                                var progressRecord = new ProgressRecord(1,
                                                                                        "Downloading " + remotepath,
                                                                                        String.Format("{0} Bytes Downloaded of {1}", rs, attribs.Size))
                                                {
                                                    PercentComplete = percent
                                                };

                                                Host.UI.WriteProgress(1, progressRecord);
                                            }
                                        }
                                    });
                                    DownloadDirectory(sftpSession.Session, remotepath, fileFullPath, _skipsymlink, res);
                                }
                                else
                                {
                                    var ex = new SftpPermissionDeniedException($"Item {remotepath} already present on local host.");
                                    WriteError(new ErrorRecord(
                                                   ex,
                                                   $"Item {remotepath} already present on local host.",
                                                   ErrorCategory.InvalidOperation,
                                                   sftpSession));
                                }
                            }
                            else if (attribs.IsRegularFile)
                            {
                                var fileName = new FileInfo(remotepath).Name;
                                // Setup Action object for showing download progress.
                                var res = new Action <ulong>(rs =>
                                {
                                    if (attribs.Size != 0)
                                    {
                                        var percent = (int)((((double)rs) / attribs.Size) * 100.0);
                                        if (percent % 10 == 0)
                                        {
                                            // This should prevent the progress message from being stuck on the screen.
                                            if (percent == 100)
                                            {
                                                return;
                                            }

                                            var progressRecord = new ProgressRecord(1,
                                                                                    "Downloading: " + fileName,
                                                                                    String.Format("{0} Bytes Downloaded of {1}", rs, attribs.Size))
                                            {
                                                PercentComplete = percent
                                            };

                                            Host.UI.WriteProgress(1, progressRecord);
                                        }
                                    }
                                });

                                var fileFullPath = $"{@localfullPath}{System.IO.Path.DirectorySeparatorChar}{fileName}";

                                var present = File.Exists(fileFullPath);

                                if ((present & _overwrite) || (!present))
                                {
                                    var localstream = File.Create(fileFullPath);
                                    try
                                    {
                                        WriteVerbose($"Downloading: {remotepath}");
                                        sftpSession.Session.DownloadFile(remotepath, localstream, res);
                                        localstream.Close();
                                        var progressRecord = new ProgressRecord(1,
                                                                                "Downloading: " + remotepath,
                                                                                String.Format("{0} Bytes Downloaded of {1}", attribs.Size, attribs.Size))
                                        {
                                            PercentComplete = 100
                                        };

                                        WriteProgress(progressRecord);
                                    }
                                    catch
                                    {
                                        localstream.Close();
                                        var ex = new SftpPermissionDeniedException($"Unable to download {remotepath} from host.");
                                        WriteError(new ErrorRecord(
                                                       ex,
                                                       $"Unable to download {remotepath} from host.",
                                                       ErrorCategory.InvalidOperation,
                                                       sftpSession));
                                    }
                                }
                                else
                                {
                                    var ex = new SftpPermissionDeniedException($"Item {remotepath} already present on local host.");
                                    WriteError(new ErrorRecord(
                                                   ex,
                                                   $"Item {remotepath} already present on local host.",
                                                   ErrorCategory.InvalidOperation,
                                                   sftpSession));
                                }
                            }
                            else
                            {
                            }
                        }
                        else
                        {
                            var ex = new SftpPathNotFoundException(remotepath + " does not exist.");

                            WriteError(new ErrorRecord(
                                           ex,
                                           remotepath + " does not exist.",
                                           ErrorCategory.InvalidOperation,
                                           sftpSession));
                        }
                    }
                }
            }
            else
            {
                var ex = new FileNotFoundException("Local path" + localfullPath + " was not found.");

                ThrowTerminatingError(new ErrorRecord(
                                          ex,
                                          "Local path" + localfullPath + " was not found.",
                                          ErrorCategory.InvalidOperation,
                                          localfullPath));
            }
        }
Exemplo n.º 15
0
        public static string GetFusionLog([NotNull] this FileNotFoundException ex) =>
#if !LESSTHAN_NETSTANDARD20 && !LESSTHAN_NETCOREAPP20
        ex.FusionLog;
Exemplo n.º 16
0
        //CopyMove helper
        private void CopyMoveImplementation(string sourcePath, string targetPath, bool recurse = false, bool isCopyOperation = true, bool reCreateSourceFolder = true)
        {
            var sourceUrl = GetServerRelativePath(sourcePath);
            var source    = GetFileOrFolder(sourcePath) as ClientObject;

            if (source == null)
            {
                return;
            }

            var targetUrl        = GetServerRelativePath(targetPath);
            var targetIsFile     = targetUrl.Split(PathSeparator.ToCharArray()).Last().Contains(".");
            var targetFolderPath = (targetIsFile) ? GetParentServerRelativePath(targetUrl) : targetUrl;
            var sourceWeb        = ((ClientContext)source.Context).Web;
            var targetWeb        = FindWebInPath(targetFolderPath);

            if (!isCopyOperation && targetUrl.StartsWith(sourceUrl))
            {
                var msg = "Cannot move source. Target is inside source";
                var err = new ArgumentException(msg);
                WriteErrorInternal(msg, sourcePath, ErrorCategory.InvalidOperation, true, err);
                return;
            }

            if (targetWeb == null)
            {
                var msg = "Target web not found";
                var err = new FileNotFoundException(msg);
                WriteErrorInternal(msg, sourcePath, ErrorCategory.ObjectNotFound, true, err);
                return;
            }

            var isSameWeb              = IsSameWeb(sourceWeb, targetWeb);
            var targetFolder           = GetFileOrFolder(targetFolderPath, false) as Folder;
            var endOfPathFolderCreated = false;

            if (targetFolder == null)
            {
                //Create target folder
                endOfPathFolderCreated = true;
                targetFolder           = targetWeb.EnsureFolderPath(PathSeparator + GetWebRelativePath(targetFolderPath));
            }

            if (ShouldProcess($"{GetServerRelativePath(sourcePath)} to {targetUrl}"))
            {
                if (source is File)
                {
                    var sourceFile     = source as File;
                    var targetFilePath = (targetIsFile) ? targetUrl : targetFolderPath + PathSeparator + sourceFile.Name;

                    if (isSameWeb)
                    {
                        if (isCopyOperation)
                        {
                            sourceFile.CopyTo(targetFilePath, Force);
                        }
                        else
                        {
                            var moveToOperations = (Force) ? MoveOperations.Overwrite : MoveOperations.None;
                            sourceFile.MoveTo(targetFilePath, moveToOperations);
                        }
                        sourceFile.Context.ExecuteQueryRetry();
                    }
                    else
                    {
                        var sourceStream = sourceFile.OpenBinaryStream();
                        sourceFile.Context.ExecuteQueryRetry();

                        targetFolder.UploadFile(targetFilePath.Split(PathSeparator.ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Last(), sourceStream.Value, Force);

                        if (!isCopyOperation)
                        {
                            sourceFile.DeleteObject();
                            sourceFile.Context.ExecuteQueryRetry();
                        }
                    }
                }
                else if (source is Folder && !targetIsFile)
                {
                    var sourceFolder = source as Folder;
                    var rootFolder   = (endOfPathFolderCreated || !reCreateSourceFolder) ? targetFolder : targetFolder.CreateFolder(sourceFolder.Name);

                    if (recurse)
                    {
                        var folderAndFiles = GetFolderItems(sourceFolder);

                        foreach (var folder in folderAndFiles.OfType <Folder>())
                        {
                            var subFolder = rootFolder.CreateFolder(folder.Name);
                            CopyMoveImplementation(folder.ServerRelativeUrl, subFolder.ServerRelativeUrl, recurse, isCopyOperation, false);
                        }

                        foreach (var file in folderAndFiles.OfType <File>())
                        {
                            CopyMoveImplementation(file.ServerRelativeUrl, rootFolder.ServerRelativeUrl, recurse, isCopyOperation);
                        }
                    }

                    if (!isCopyOperation)
                    {
                        sourceFolder.DeleteObject();
                        sourceFolder.Context.ExecuteQueryRetry();
                    }
                }
                else
                {
                    WriteErrorInternal("Operation not supported", sourcePath, ErrorCategory.InvalidOperation);
                }
            }
        }
Exemplo n.º 17
0
        public static void GetDataFromFile(AucResponseHandler handler, string realm)
        {
            if (handler == null)
            {
                return;
            }
            var fileitem = Path.Combine(@"AucInfo\", realm + ".json");

            if (!File.Exists(fileitem))
            {
                var ex = new Exception();

                var f = new FileNotFoundException();
                return;
            }
            //var jsarr = ReadFileInString(fileitem);

            //JsonTextReader reader = new JsonTextReader(new StringReader(jsarr)) {SupportMultipleContent = true};
            //var st = "";
            //    while (reader.Read())
            //    {
            //        if (reader.Value != null) st += reader.Value+" ";
            //        // Console.WriteLine("Token: {0}, Value: {1} Path {2}", reader.TokenType, reader.Value,reader.Path);
            //        else
            //            //Console.WriteLine("Token: {0}", reader.TokenType);
            //            if (reader.TokenType.ToString() == "StartObject" )
            //            {
            //                handler(st);
            //                st = "";
            //            }

            //        //  var a = reader.Value;
            //        //  handler(new WoWAucInfo(a));
            //    }

            var lists = new List <WoWAucInfo>();

            using (var stream = new FileStream(fileitem, FileMode.Open))
            {
                var str = new StreamReader(stream);

                string f;

                while ((f = str.ReadLine()) != null)

                {
                    var s = f;
                    var t = s.Trim();
                    if (t.LastOrDefault() == ',')
                    {
                        t = t.Remove(t.LastIndexOf(','));
                    }
                    var r    = new Regex(@"\[");
                    var open = r.Matches(t).Count;

                    r = new Regex(@"\]");
                    var close = r.Matches(t).Count;
                    if (open != close)
                    {
                        t = t.Replace("]", "");
                        t = t.Remove(t.Length - 1);
                    }
                    if (t.FirstOrDefault() == '{' && t.LastOrDefault() == '}')
                    {
                        lists.Add(new WoWAucInfo(t));
                    }
                }
            }
            handler(lists);
        }
Exemplo n.º 18
0
        internal static Job2 LoadJobFromStore(string definitionName, DateTime jobRun)
        {
            FileStream fileForJobRunItem = null;
            Exception  exception         = null;
            bool       flag = false;
            Job2       job2 = null;

            try
            {
                try
                {
                    fileForJobRunItem = ScheduledJobStore.GetFileForJobRunItem(definitionName, jobRun, ScheduledJobStore.JobRunItem.Results, FileMode.Open, FileAccess.Read, FileShare.Read);
                    job2 = ScheduledJobSourceAdapter.LoadResultsFromFile(fileForJobRunItem);
                }
                catch (ArgumentException argumentException1)
                {
                    ArgumentException argumentException = argumentException1;
                    exception = argumentException;
                }
                catch (DirectoryNotFoundException directoryNotFoundException1)
                {
                    DirectoryNotFoundException directoryNotFoundException = directoryNotFoundException1;
                    exception = directoryNotFoundException;
                }
                catch (FileNotFoundException fileNotFoundException1)
                {
                    FileNotFoundException fileNotFoundException = fileNotFoundException1;
                    exception = fileNotFoundException;
                    flag      = true;
                }
                catch (UnauthorizedAccessException unauthorizedAccessException1)
                {
                    UnauthorizedAccessException unauthorizedAccessException = unauthorizedAccessException1;
                    exception = unauthorizedAccessException;
                }
                catch (IOException oException1)
                {
                    IOException oException = oException1;
                    exception = oException;
                }
                catch (SerializationException serializationException)
                {
                    flag = true;
                }
                catch (InvalidDataContractException invalidDataContractException)
                {
                    flag = true;
                }
                catch (XmlException xmlException)
                {
                    flag = true;
                }
                catch (TypeInitializationException typeInitializationException)
                {
                    flag = true;
                }
            }
            finally
            {
                if (fileForJobRunItem != null)
                {
                    fileForJobRunItem.Close();
                }
            }
            if (flag)
            {
                ScheduledJobStore.RemoveJobRun(definitionName, jobRun);
            }
            if (exception == null)
            {
                return(job2);
            }
            else
            {
                object[] objArray = new object[2];
                objArray[0] = definitionName;
                objArray[1] = jobRun;
                string str = StringUtil.Format(ScheduledJobErrorStrings.CantLoadJobRunFromStore, objArray);
                throw new ScheduledJobException(str, exception);
            }
        }
        /// <summary>
        /// Deserializes an object from a file. No exception is thrown here, default data is returned whenever anything goes wrong.
        /// </summary>
        /// <param name="fileName">
        /// The full path.
        /// </param>
        /// <param name="type">
        /// The object type to deserialize.
        /// </param>
        /// <param name="exception">
        /// An exception in case of anything went wrong.
        /// </param>
        /// <param name="serializeIfDataNotFound">
        /// A value indicating whether to serialize the default data if file not found.
        /// </param>
        /// <returns>
        /// The deserialized object. A null object in case of errors.
        /// </returns>
        public static object XmlDeserializeObject(string fileName, Type type, out Exception exception, bool serializeIfDataNotFound)
        {
            object result = null;

            if (!string.IsNullOrEmpty(fileName) && File.Exists(fileName))
            {
                TextReader tr = null;
                try
                {
                    var serializer = new XmlSerializer(type);
                    tr     = new StreamReader(fileName);
                    result = serializer.Deserialize(tr);
                    OnDeserialized(result);
                    tr.Close();
                    exception = null;
                    return(result);
                }
                catch (Exception ex)
                {
                    exception = ex;
                    if (tr != null)
                    {
                        tr.Close();
                    }
                }
            }
            else
            {
                exception = new FileNotFoundException(string.Format("File {0} not found.", fileName));
            }

            try
            {
                // Deserialize not successfull, take the default data.
                var constructorInfo = type.GetConstructor(new Type[0]);
                if (constructorInfo != null)
                {
                    var arrayMemberInfo = type.FindMembers(
                        MemberTypes.Method,
                        BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance,
                        new MemberFilter(DelegateToSearchCriteria),
                        typeof(DefaultDataSetterAttribute));

                    if (arrayMemberInfo.Length > 0)
                    {
                        result = constructorInfo.Invoke(new object[0]);
                        type.InvokeMember(arrayMemberInfo[0].Name, BindingFlags.InvokeMethod, null, result, new object[0]);

                        // Serialize on demand.
                        if (serializeIfDataNotFound)
                        {
                            XmlSerializeObject(fileName, result);
                        }
                    }
                }
            }
            catch (Exception)
            {
            }

            return(result);
        }
Exemplo n.º 20
0
        public override Assembly Deploy(FileInfo dllFile)
        {
            var      newDllFile = CopyToDynamicDirectory(dllFile);
            Assembly assembly   = Assembly.LoadFrom(newDllFile.FullName);
            var      plusInfo   = this.GetPluginInfo(assembly, dllFile);

            switch (plusInfo.PlusConfigInfo.AssemblyType)
            {
            case Magicodes.Web.Interfaces.Plus.Info.AssemblyTypes.WF:
                break;

            case Magicodes.Web.Interfaces.Plus.Info.AssemblyTypes.Resource:
                break;

            case Magicodes.Web.Interfaces.Plus.Info.AssemblyTypes.Code:
                break;

            case Magicodes.Web.Interfaces.Plus.Info.AssemblyTypes.Theme:
                break;

            case Magicodes.Web.Interfaces.Plus.Info.AssemblyTypes.Strategy:
                this.LoadPlusStrategys(assembly);
                break;

            case Magicodes.Web.Interfaces.Plus.Info.AssemblyTypes.Models:
                break;

            case Magicodes.Web.Interfaces.Plus.Info.AssemblyTypes.MVC:
            case Magicodes.Web.Interfaces.Plus.Info.AssemblyTypes.MVCHome:
            {
                //配置插件路由
                MvcConfigManager.Config(assembly, plusInfo.PlusConfigInfo.AssemblyType);
            }
            break;

            default:
                break;
            }
            try
            {
                //将程序集添加到当前应用程序域
                BuildManager.AddReferencedAssembly(assembly);
                //执行插件初始化函数
                assembly.GetTypes().Where(p => p.IsClass && p.GetInterface(typeof(IPlus).FullName) != null).Each(
                    t =>
                {
                    using (new CodeWatch("Plu Initialize", 3000))
                    {
                        try
                        {
                            var type = (IPlus)Activator.CreateInstance(t);
                            type.Initialize();
                        }
                        catch (Exception ex)
                        {
                            throw new MagicodesException(string.Format("插件初始化失败!Assembly:{0},Type:{1}{2}", assembly.FullName, t.FullName, Environment.NewLine), ex);
                        }
                    }
                });
            }
            catch (FileLoadException ex)
            {
                throw new MagicodesException(string.Format("加载此程序失败!Assembly:{0},FileName:{1}", assembly.FullName, ex.FileName), ex);
            }
            catch (System.Reflection.ReflectionTypeLoadException ex)
            {
                StringBuilder sb = new StringBuilder();
                foreach (Exception exSub in ex.LoaderExceptions)
                {
                    sb.AppendLine(exSub.Message);
                    FileNotFoundException exFileNotFound = exSub as 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 MagicodesException(errorMessage);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(assembly);
        }
Exemplo n.º 21
0
        private bool CheckPolicy(ExternalScriptInfo script, PSHost host, out Exception reason)
        {
            bool policyCheckPassed = false;

            reason = null;
            string path = script.Path;
            string reasonMessage;

            // path is assumed to be fully qualified here
            if (path.IndexOf(System.IO.Path.DirectorySeparatorChar) < 0)
            {
                throw PSTraceSource.NewArgumentException("path");
            }

            if (path.LastIndexOf(System.IO.Path.DirectorySeparatorChar) == (path.Length - 1))
            {
                throw PSTraceSource.NewArgumentException("path");
            }

            FileInfo fi = new FileInfo(path);

            // Return false if the file does not exist, so that
            // we don't introduce a race condition
            if (!fi.Exists)
            {
                reason = new FileNotFoundException(path);
                return(false);
            }

            // Quick exit if we don't support the file type
            if (!IsSupportedExtension(fi.Extension))
            {
                return(true);
            }

            // Product binaries are always trusted
            if (SecuritySupport.IsProductBinary(path))
            {
                return(true);
            }

            // Get the execution policy
            _executionPolicy = SecuritySupport.GetExecutionPolicy(_shellId);

            // See if they want to bypass the authorization manager
            if (_executionPolicy == ExecutionPolicy.Bypass)
            {
                return(true);
            }
#if !CORECLR
            // Always check the SAFER APIs if code integrity isn't being handled system-wide through
            // WLDP or AppLocker. In those cases, the scripts will be run in ConstrainedLanguage.
            // Otherwise, block.
            // SAFER APIs are not on CSS or OneCore
            if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Enforce)
            {
                SaferPolicy saferPolicy    = SaferPolicy.Disallowed;
                int         saferAttempt   = 0;
                bool        gotSaferPolicy = false;

                // We need to put in a retry workaround, as the SAFER APIs fail when under stress.
                while ((!gotSaferPolicy) && (saferAttempt < 5))
                {
                    try
                    {
                        saferPolicy    = SecuritySupport.GetSaferPolicy(path, null);
                        gotSaferPolicy = true;
                    }
                    catch (System.ComponentModel.Win32Exception)
                    {
                        if (saferAttempt > 4)
                        {
                            throw;
                        }

                        saferAttempt++;
                        System.Threading.Thread.Sleep(100);
                    }
                }

                // If the script is disallowed via AppLocker, block the file
                // unless the system-wide lockdown policy is "Enforce" (where all PowerShell
                // scripts are in blocked). If the system policy is "Enforce", then the
                // script will be allowed (but ConstrainedLanguage will be applied).
                if (saferPolicy == SaferPolicy.Disallowed)
                {
                    reasonMessage = StringUtil.Format(Authenticode.Reason_DisallowedBySafer, path);
                    reason        = new UnauthorizedAccessException(reasonMessage);

                    return(false);
                }
            }
#endif
            if (_executionPolicy == ExecutionPolicy.Unrestricted)
            {
                // We need to give the "Remote File" warning
                // if the file originated from the internet
                if (!IsLocalFile(fi.FullName))
                {
                    // Get the signature of the file.
                    if (String.IsNullOrEmpty(script.ScriptContents))
                    {
                        reasonMessage = StringUtil.Format(Authenticode.Reason_FileContentUnavailable, path);
                        reason        = new UnauthorizedAccessException(reasonMessage);

                        return(false);
                    }

                    Signature signature = GetSignatureWithEncodingRetry(path, script);

                    // The file is signed, with a publisher that
                    // we trust
                    if (signature.Status == SignatureStatus.Valid)
                    {
                        // The file is signed by a trusted publisher
                        if (IsTrustedPublisher(signature, path))
                        {
                            policyCheckPassed = true;
                        }
                    }

                    // We don't care about the signature.  If you distrust them,
                    // or the signature does not exist, we prompt you only
                    // because it's remote.
                    if (!policyCheckPassed)
                    {
                        RunPromptDecision decision = RunPromptDecision.DoNotRun;

                        // Get their remote prompt answer, allowing them to
                        // enter nested prompts, if wanted.
                        do
                        {
                            decision = RemoteFilePrompt(path, host);

                            if (decision == RunPromptDecision.Suspend)
                            {
                                host.EnterNestedPrompt();
                            }
                        } while (decision == RunPromptDecision.Suspend);

                        switch (decision)
                        {
                        case RunPromptDecision.RunOnce:
                            policyCheckPassed = true;
                            break;

                        case RunPromptDecision.DoNotRun:
                        default:
                            policyCheckPassed = false;
                            reasonMessage     = StringUtil.Format(Authenticode.Reason_DoNotRun, path);
                            reason            = new UnauthorizedAccessException(reasonMessage);
                            break;
                        }
                    }
                }
                else
                {
                    policyCheckPassed = true;
                }
            }
            // Don't need to check the signature if the file is local
            // and we're in "RemoteSigned" mode
            else if ((IsLocalFile(fi.FullName)) &&
                     (_executionPolicy == ExecutionPolicy.RemoteSigned))
            {
                policyCheckPassed = true;
            }
            else if ((_executionPolicy == ExecutionPolicy.AllSigned) ||
                     (_executionPolicy == ExecutionPolicy.RemoteSigned))
            {
                // if policy requires signature verification,
                // make it so.

                // Get the signature of the file.
                if (String.IsNullOrEmpty(script.ScriptContents))
                {
                    reasonMessage = StringUtil.Format(Authenticode.Reason_FileContentUnavailable, path);
                    reason        = new UnauthorizedAccessException(reasonMessage);

                    return(false);
                }

                Signature signature = GetSignatureWithEncodingRetry(path, script);

                // The file is signed.
                if (signature.Status == SignatureStatus.Valid)
                {
                    // The file is signed by a trusted publisher
                    if (IsTrustedPublisher(signature, path))
                    {
                        policyCheckPassed = true;
                    }
                    // The file is signed by an unknown publisher,
                    // So prompt.
                    else
                    {
                        policyCheckPassed = SetPolicyFromAuthenticodePrompt(path, host, ref reason, signature);
                    }
                }
                // The file is UnknownError, NotSigned, HashMismatch,
                // NotTrusted, NotSupportedFileFormat
                else
                {
                    policyCheckPassed = false;

                    if (signature.Status == SignatureStatus.NotTrusted)
                    {
                        reason = new UnauthorizedAccessException(
                            StringUtil.Format(Authenticode.Reason_NotTrusted,
                                              path,
                                              signature.SignerCertificate.SubjectName.Name));
                    }
                    else
                    {
                        reason = new UnauthorizedAccessException(
                            StringUtil.Format(Authenticode.Reason_Unknown,
                                              path,
                                              signature.StatusMessage));
                    }
                }
            }
            else // if(executionPolicy == ExecutionPolicy.Restricted)
            {
                // Deny everything
                policyCheckPassed = false;

                // But accept mshxml files from publishers that we
                // trust, or files in the system protected directories
                bool reasonSet = false;
                if (String.Equals(fi.Extension, ".ps1xml", StringComparison.OrdinalIgnoreCase))
                {
                    string[] trustedDirectories = new string[]
                    { Environment.GetFolderPath(Environment.SpecialFolder.System),
                      Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) };

                    foreach (string trustedDirectory in trustedDirectories)
                    {
                        if (fi.FullName.StartsWith(trustedDirectory, StringComparison.OrdinalIgnoreCase))
                        {
                            policyCheckPassed = true;
                        }
                    }

                    if (!policyCheckPassed)
                    {
                        // Get the signature of the file.
                        Signature signature = GetSignatureWithEncodingRetry(path, script);

                        // The file is signed by a trusted publisher
                        if (signature.Status == SignatureStatus.Valid)
                        {
                            if (IsTrustedPublisher(signature, path))
                            {
                                policyCheckPassed = true;
                            }
                            // The file is signed by an unknown publisher,
                            // So prompt.
                            else
                            {
                                policyCheckPassed = SetPolicyFromAuthenticodePrompt(path, host, ref reason, signature);
                                reasonSet         = true;
                            }
                        }
                    }
                }

                if (!policyCheckPassed && !reasonSet)
                {
                    reason = new UnauthorizedAccessException(
                        StringUtil.Format(Authenticode.Reason_RestrictedMode,
                                          path));
                }
            }

            return(policyCheckPassed);
        }
Exemplo n.º 22
0
 public FileNotFoundSequence(FileNotFoundException exception)
 {
     this.exception = exception;
 }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            CommandLineParser parser = new CommandLineParser();

            parser.Parse(args);

            string projectPath = parser.Arguments["-ProjectPath"];

            if (string.IsNullOrEmpty(projectPath) || !File.Exists(projectPath))
            {
                Console.WriteLine(DecorateMessage($"ProjectPath cannot be empty"));
                return;
            }
            if (!File.Exists(projectPath))
            {
                Console.WriteLine(DecorateMessage($"{projectPath} does not exist"));
                return;
            }

            string outputPath = parser.Arguments["-OutputPath"];

            if (string.IsNullOrEmpty(outputPath))
            {
                Console.WriteLine(DecorateMessage($"OutputPath cannot be empty"));
                return;
            }

            string configuration = parser.Arguments["-Configuration"];

            if (string.IsNullOrEmpty(configuration))
            {
                Console.WriteLine(DecorateMessage($"Configuration cannot be empty"));
                return;
            }

            string platform = parser.Arguments["-Platform"];

            if (string.IsNullOrEmpty(platform))
            {
                Console.WriteLine(DecorateMessage($"Platform cannot be empty"));
                return;
            }

            DiModule diModule = new DiModule(projectPath, outputPath);

            Directory.CreateDirectory(Path.GetDirectoryName(outputPath));

            Console.WriteLine(DecorateMessage($"Generating stubs for project: {projectPath}"));

            try
            {
                string stubsCode = diModule.StubsGenerator.GenerateStubs(projectPath, configuration, platform).Result;
                Console.WriteLine(DecorateMessage($"Writing stubs to file: {outputPath}"));
                File.WriteAllText(outputPath, stubsCode);
            }
            catch (ReflectionTypeLoadException ex)
            {
                StringBuilder sb = new StringBuilder();
                foreach (Exception exSub in ex.LoaderExceptions)
                {
                    sb.AppendLine(exSub.Message);
                    FileNotFoundException exFileNotFound = exSub as FileNotFoundException;
                    if (exFileNotFound != null)
                    {
                        if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
                        {
                            sb.AppendLine("Fusion Log:");
                            sb.AppendLine(exFileNotFound.FusionLog);
                        }
                    }
                    sb.AppendLine();
                }
                string errorMessage = sb.ToString();
                Console.WriteLine(DecorateMessage($"Failed to generate stubs: {errorMessage}"));
            }
            catch (Exception e)
            {
                Console.WriteLine(DecorateMessage($"Failed to generate stubs: {e.ToString()}"));
            }
        }
Exemplo n.º 24
0
        public async override Tasks.Task RunCommand(object sender)
        {
            var engine           = (IAutomationEngineInstance)sender;
            var exceptionMessage = (string)await v_ExceptionMessage.EvaluateCode(engine);

            Exception ex;

            switch (v_ExceptionType)
            {
            case "AccessViolationException":
                ex = new AccessViolationException(exceptionMessage);
                break;

            case "ArgumentException":
                ex = new ArgumentException(exceptionMessage);
                break;

            case "ArgumentNullException":
                ex = new ArgumentNullException(exceptionMessage);
                break;

            case "ArgumentOutOfRangeException":
                ex = new ArgumentOutOfRangeException(exceptionMessage);
                break;

            case "DivideByZeroException":
                ex = new DivideByZeroException(exceptionMessage);
                break;

            case "Exception":
                ex = new Exception(exceptionMessage);
                break;

            case "FileNotFoundException":
                ex = new FileNotFoundException(exceptionMessage);
                break;

            case "FormatException":
                ex = new FormatException(exceptionMessage);
                break;

            case "IndexOutOfRangeException":
                ex = new IndexOutOfRangeException(exceptionMessage);
                break;

            case "InvalidDataException":
                ex = new InvalidDataException(exceptionMessage);
                break;

            case "InvalidOperationException":
                ex = new InvalidOperationException(exceptionMessage);
                break;

            case "KeyNotFoundException":
                ex = new KeyNotFoundException(exceptionMessage);
                break;

            case "NotSupportedException":
                ex = new NotSupportedException(exceptionMessage);
                break;

            case "NullReferenceException":
                ex = new NullReferenceException(exceptionMessage);
                break;

            case "OverflowException":
                ex = new OverflowException(exceptionMessage);
                break;

            case "TimeoutException":
                ex = new TimeoutException(exceptionMessage);
                break;

            default:
                throw new NotImplementedException("Selected exception type " + v_ExceptionType + " is not implemented.");
            }
            throw ex;
        }
Exemplo n.º 25
0
 public void OnFileNotFoundException(FileNotFoundException e,
                                     Object state)
 {
     Log.Error("Facebook", e.Message);
     e.PrintStackTrace();
 }
 public static void FileNotFoundException_ReturnA()
 {
     var exception = new FileNotFoundException("test");
 }
Exemplo n.º 27
0
        /// <summary>
        /// 解压到文件夹
        /// </summary>
        /// <param name="progress"></param>
        /// <param name="isdone"></param>
        /// <param name="fileName"></param>
        /// <param name="onerror"></param>
        /// <param name="destinateDir"></param>
        /// <param name="password"></param>
        public static void AsyncUnCompressionFile(Action <float> progress, Action isdone, string fileName, Action <Exception> onerror = null, string destinateDir = "", string password = "")
        {
            FileInfo zipFile = new FileInfo(fileName);

            if (zipFile.Exists == false)
            {
                var e = new FileNotFoundException("找不到压缩文件:" + zipFile.FullName);
                if (onerror != null)
                {
                    onerror(e);
                    return;
                }
                throw e;
            }

            try
            {
                ZipFile file    = new ZipFile(fileName);
                string  estName = string.IsNullOrEmpty(destinateDir) ? "ExtractData\\" : destinateDir;
                if (estName.EndsWith("\\") == false)
                {
                    estName += "\\";
                }

                if (!string.IsNullOrEmpty(password))
                {
                    file.Password = password;
                }

                int index = 0;

                foreach (ZipEntry entery in file)
                {
                    index++;
                    progress(index * 1f / file.Count);
                    if (entery != null)
                    {
                        string   fname = estName + entery.Name;
                        FileInfo f     = new FileInfo(fname);
                        if (!f.Directory.Exists)
                        {
                            f.Directory.Create();
                        }
                        using (var fs = f.Create())
                        {
                            using (var stream = file.GetInputStream(entery))
                            {
                                stream.CopyTo(fs);
                                fs.Flush();
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (onerror != null)
                {
                    onerror(e);
                    return;
                }
                throw e;
            }

            isdone();
        }
Exemplo n.º 28
0
        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 != Win32Native.ERROR_SUCCESS )
                {
                    System.Exception exception = null;

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

                    if ( exception == null )
                    {
                        if ( error == Win32Native.ERROR_ACCESS_DENIED )
                        {
                            exception = new UnauthorizedAccessException();
                        }
                        else if ( error == Win32Native.ERROR_INVALID_OWNER )
                        {
                            exception = new InvalidOperationException( Environment.GetResourceString( "AccessControl_InvalidOwner" ) );
                        }
                        else if ( error == Win32Native.ERROR_INVALID_PRIMARY_GROUP )
                        {
                            exception = new InvalidOperationException( Environment.GetResourceString( "AccessControl_InvalidGroup" ) );
                        }
                        else if ( error == Win32Native.ERROR_INVALID_NAME )
                        {
                            exception = new ArgumentException(
                                Environment.GetResourceString( "Argument_InvalidName" ),
                                "name" );
                        }
                        else if ( error == Win32Native.ERROR_INVALID_HANDLE )
                        {
                            exception = new NotSupportedException( Environment.GetResourceString( "AccessControl_InvalidHandle" ));
                        }
                        else if ( error == Win32Native.ERROR_FILE_NOT_FOUND )
                        {
                            exception = new FileNotFoundException();
                        }
                        else if (error == Win32Native.ERROR_NO_SECURITY_ON_OBJECT)
                        {
                            exception = new NotSupportedException(Environment.GetResourceString("AccessControl_NoAssociatedSecurity"));
                        }
                        else
                        {
                            Contract.Assert( false, string.Format( CultureInfo.InvariantCulture, "Unexpected error code {0}", error ));
                            exception = new InvalidOperationException( Environment.GetResourceString( "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();
            }
        }
        protected override void ProcessRecord()
        {
            // check if the file specified actually exists.
            // Resolve the path even if a relative one is given.
            ProviderInfo provider;
            var          pathinfo      = GetResolvedProviderPathFromPSPath(_localpath, out provider);
            var          localfullPath = pathinfo[0];

            if (Directory.Exists(@localfullPath))
            {
                var filename = Path.GetFileName(_remotefile);

                var localfilefullpath = localfullPath + "/" + filename;
                var fil = new FileInfo(@localfilefullpath);


                foreach (var sftpSession in ToProcess)
                {
                    WriteVerbose("Downloading " + filename + " to " + localfilefullpath + " from " + sftpSession.Host);



                    // Check that the path we are downloading from actually exists on the target.
                    if (sftpSession.Session.Exists(_remotefile))
                    {
                        // Ensure the remote path is a directory.
                        var attribs = sftpSession.Session.GetAttributes(_remotefile);
                        if (!attribs.IsRegularFile)
                        {
                            throw new SftpPathNotFoundException("Specified path is not a file.");
                        }

                        // Setup Action object for showing download progress.

                        var res = new Action <ulong>(rs =>
                        {
                            //if (!MyInvocation.BoundParameters.ContainsKey("Verbose")) return;
                            if (attribs.Size != 0)
                            {
                                var percent = (int)((((double)rs) / attribs.Size) * 100.0);
                                if (percent % 10 == 0)
                                {
                                    // This will prevent the progress message from being stuck on the screen.
                                    if (percent == 100)
                                    {
                                        return;
                                    }

                                    var progressRecord = new ProgressRecord(1,
                                                                            "Downloading " + fil.Name,
                                                                            String.Format("{0} Bytes Downloaded of {1}", rs, attribs.Size))
                                    {
                                        PercentComplete = percent
                                    };

                                    Host.UI.WriteProgress(1, progressRecord);
                                }
                            }
                        });

                        var present = File.Exists(localfilefullpath);

                        if ((present & _overwrite) || (!present))
                        {
                            var localstream = File.Create(@localfilefullpath);
                            try
                            {
                                sftpSession.Session.DownloadFile(_remotefile, localstream, res);
                                localstream.Close();
                            }
                            catch
                            {
                                localstream.Close();
                                var ex = new SftpPermissionDeniedException("Unable to download file from host.");
                                WriteError(new ErrorRecord(
                                               ex,
                                               "Unable to download file from host.",
                                               ErrorCategory.InvalidOperation,
                                               sftpSession));
                            }
                        }
                        else
                        {
                            var ex = new SftpPermissionDeniedException("File already present on local host.");
                            WriteError(new ErrorRecord(
                                           ex,
                                           "File already present on local host.",
                                           ErrorCategory.InvalidOperation,
                                           sftpSession));
                        }
                    }
                    else
                    {
                        var ex = new SftpPathNotFoundException(RemoteFile + " does not exist.");

                        WriteError(new ErrorRecord(
                                       ex,
                                       RemoteFile + " does not exist.",
                                       ErrorCategory.InvalidOperation,
                                       sftpSession));
                    }
                }
            }
            else
            {
                var ex = new FileNotFoundException("Local path" + localfullPath + " was not found.");

                WriteError(new ErrorRecord(
                               ex,
                               "Local path" + localfullPath + " was not found.",
                               ErrorCategory.InvalidOperation,
                               localfullPath));
            }
        }
Exemplo n.º 30
0
		public void OnFileNotFoundException (FileNotFoundException e,
		                                     Object state)
		{
			Log.Error ("Facebook", e.Message);
			e.PrintStackTrace ();
		}
Exemplo n.º 31
0
        /// <summary>
        /// Finds script aliases in the provided assemblies.
        /// </summary>
        /// <param name="assemblies">The assemblies to find script aliases in.</param>
        /// <returns>The script aliases that were found.</returns>
        public IReadOnlyList <ScriptAlias> FindAliases(IEnumerable <Assembly> assemblies)
        {
            var result = new List <ScriptAlias>();

            if (assemblies != null)
            {
                foreach (var reference in assemblies)
                {
                    try
                    {
                        foreach (var type in reference.DefinedTypes)
                        {
                            if (type.IsStatic())
                            {
                                foreach (var method in GetAliasMethods(type))
                                {
                                    var alias = CreateAlias(method);
                                    if (alias != null)
                                    {
                                        result.Add(alias);
                                    }
                                }
                            }
                        }
                    }
                    catch (ReflectionTypeLoadException ex)
                    {
                        HashSet <string> notFound = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                        foreach (Exception loaderException in ex.LoaderExceptions)
                        {
                            _log.Debug(loaderException.Message);
                            FileNotFoundException fileNotFoundException = loaderException as FileNotFoundException;
                            if (fileNotFoundException != null)
                            {
                                if (!notFound.Contains(fileNotFoundException.FileName))
                                {
                                    notFound.Add(fileNotFoundException.FileName);
                                }

                                if (!string.IsNullOrEmpty(fileNotFoundException.FusionLog))
                                {
                                    _log.Debug("Fusion Log:");
                                    _log.Debug(fileNotFoundException.FusionLog);
                                }
                            }
                            _log.Debug(string.Empty);
                        }

                        foreach (var file in notFound)
                        {
                            _log.Warning("Could not load {0} (missing {1})", reference.Location, file);
                        }
                    }
                    catch (FileNotFoundException ex)
                    {
                        _log.Warning("Could not load {0} (missing {1}))", reference.Location, ex.FileName);
                    }
                }
            }
            return(result);
        }
Exemplo n.º 32
0
        /// <summary>
        /// get the HL7 item provided via the cmdlet parameter HL7ItemPosition
        /// </summary>
        protected override void ProcessRecord()
        {
            // validate the that all of the list of locations to remove are valid.
            foreach (string item in this.itemPosition)
            {
                // confirm each filter is formatted correctly
                if (!Common.IsItemLocationValid(item))
                {
                    ArgumentException ex    = new ArgumentException(item + " does not appear to be a valid HL7 location. Ensure the -ItemPosition list is formatted correctly.");
                    ErrorRecord       error = new ErrorRecord(ex, "InvalidFilter", ErrorCategory.InvalidArgument, item);
                    this.WriteError(error);
                    return;
                }
            }

            // confirm the filter parameter is valid before processing any files
            foreach (string currentFilter in this.filter)
            {
                // confirm each filter is formatted correctly
                if (!Common.IsFilterValid(currentFilter))
                {
                    ArgumentException ex    = new ArgumentException(currentFilter + " does not appear to be a valid filter");
                    ErrorRecord       error = new ErrorRecord(ex, "InvalidFilter", ErrorCategory.InvalidArgument, currentFilter);
                    this.WriteError(error);
                    return;
                }
            }

            // expand the file or directory information provided in the -Path or -LiteralPath parameters
            foreach (string path in paths)
            {
                // This will hold information about the provider containing the items that this path string might resolve to.
                ProviderInfo provider;

                // This will be used by the method that processes literal paths
                PSDriveInfo drive;

                // this contains the paths to process for this iteration of the loop to resolve and optionally expand wildcards.
                List <string> filePaths = new List <string>();

                // if the path provided is a directory, expand the files in the directy and add these to the list.
                if (Directory.Exists(path))
                {
                    filePaths.AddRange(Directory.GetFiles(path));
                }

                // not a directory, could be a wildcard or literal filepath
                else
                {
                    // expand wildcards. This assumes if the user listed a directory it is literal
                    if (expandWildcards)
                    {
                        // Turn *.txt into foo.txt,foo2.txt etc. If path is just "foo.txt," it will return unchanged. If the filepath expands into a directory ignore it.
                        foreach (string expandedFilePath in this.GetResolvedProviderPathFromPSPath(path, out provider))
                        {
                            if (!Directory.Exists(expandedFilePath))
                            {
                                filePaths.Add(expandedFilePath);
                            }
                        }
                    }
                    else
                    {
                        // no wildcards, so don't try to expand any * or ? symbols.
                        filePaths.Add(this.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path, out provider, out drive));
                    }
                    // ensure that this path (or set of paths after wildcard expansion)
                    // is on the filesystem. A wildcard can never expand to span multiple providers.
                    if (Common.IsFileSystemPath(provider, path) == false)
                    {
                        // no, so skip to next path in paths.
                        continue;
                    }
                }

                // At this point, we have a list of paths on the filesystem, process each file.
                foreach (string filePath in filePaths)
                {
                    // If the file does not exist display an error and return.
                    if (!File.Exists(filePath))
                    {
                        FileNotFoundException fileException     = new FileNotFoundException("File not found", filePath);
                        ErrorRecord           fileNotFoundError = new ErrorRecord(fileException, "FileNotFound", ErrorCategory.ObjectNotFound, filePath);
                        WriteError(fileNotFoundError);
                        return;
                    }

                    // process the message
                    try {
                        // assume the filter is true, until a failed match is found
                        this.filterConditionsMet = true;
                        // load the file into a HL7Message object for processing
                        string     fileContents = File.ReadAllText(filePath);
                        HL7Message message      = new HL7Message(fileContents);
                        // if a filter was supplied, evaluate if the file matches the filter condition
                        if (this.filter != null)
                        {
                            // check to see is all of the filter conditions are met (ie AND all filters supplied).
                            foreach (string currentFilter in this.filter)
                            {
                                bool   anyItemMatch = false;
                                string filterItem   = Common.GetFilterItem(currentFilter);
                                string filterValue  = Common.GetFilterValue(currentFilter);
                                // for repeating fields, only one of the items returned has to match for the filter to be evaluated as true.
                                foreach (string itemValue in message.GetHL7ItemValue(filterItem))
                                {
                                    if (itemValue.ToUpper() == filterValue.ToUpper())
                                    {
                                        anyItemMatch = true;
                                    }
                                }
                                // if none of the repeating field items match, then fail the filter match for this file.
                                if (!anyItemMatch)
                                {
                                    this.filterConditionsMet = false;
                                }
                            }
                        }

                        // if the filter supplied matches this message (or no filter provided) then process the file to optain the HL7 item requested
                        if (filterConditionsMet)
                        {
                            foreach (string locationItem in this.itemPosition)
                            {
                                List <HL7Item> hl7Items = message.GetHL7Item(locationItem);
                                // if the hl7Items array is  empty, the item was not found in the message
                                if (hl7Items.Count == 0)
                                {
                                    WriteWarning("Item " + this.itemPosition + " not found in the message " + filePath);
                                }

                                //  items were located in the message, so proceed with replacing the original value with the new value.
                                else
                                {
                                    // update all repeats/occurances of the specified item
                                    if (this.allrepeats)
                                    {
                                        foreach (HL7Item item in hl7Items)
                                        {
                                            RemoveHL7ItemResult result = new RemoveHL7ItemResult(item.ToString(), filePath, locationItem);
                                            item.SetValueFromString(string.Empty);
                                            WriteObject(result);
                                        }
                                    }
                                    // update only the first occurrance. This is the default action.
                                    else
                                    {
                                        RemoveHL7ItemResult result = new RemoveHL7ItemResult(hl7Items.ElementAt(0).ToString(), filePath, locationItem);
                                        hl7Items.ElementAt(0).SetValueFromString(string.Empty);
                                        WriteObject(result);
                                    }
                                    // save the changes back to the original file
                                    if (this.ShouldProcess(filePath, "Saving changes to file"))
                                    {
                                        System.IO.File.WriteAllText(filePath, message.ToString());
                                    }
                                }
                            }
                        }
                    }

                    // if the file does not start with a MSH segment, the constructor will throw an exception.
                    catch (System.ArgumentException) {
                        ArgumentException argException     = new ArgumentException("The file does not appear to be a valid HL7 v2 message", filePath);
                        ErrorRecord       invalidFileError = new ErrorRecord(argException, "FileNotValid", ErrorCategory.InvalidData, filePath);
                        WriteError(invalidFileError);
                        return;
                    }
                }
            }
        }
 public static void FileNotFoundException_ReturnB()
 {
     var exception = new FileNotFoundException("test", new Exception());
 }
Exemplo n.º 34
0
        static void Main(string[] args)
        {
            //Exercise 1
            int  num1, num2;
            byte result;

            num1 = 30;
            num2 = 60;
            try
            {
                result = Convert.ToByte(num1 * num2);
                Console.WriteLine("{0} x {1} = {2}", num1, num2, result);
            }
            catch (OverflowException)
            {
                Console.WriteLine("Result does not fit byte.");
            }

            //Exercise 2
            Exception ex1 = new FileNotFoundException("Custom file now found message");

            try
            {
                throw ex1;
            }
            catch (FileNotFoundException fe)
            {
                Console.WriteLine(fe.Message);
            }

            //Exercise 4
            int[] myArr     = { 10, 20, 30, 40, 50, 60, 70, 80, 90 };
            var   resultArr = from num in myArr where num > 44 select num;

            PrintArr(resultArr.ToArray());

            //Exercise 4.1
            var methodArr = myArr.Where(num12 => num12 > 44);

            PrintArr(methodArr.ToArray());

            //Exercise 5
            ArrayClass ac = new ArrayClass();

            int[] methodArray = ac.GetArray();
            PrintArr(methodArray);

            PrintArr(methodArray.OrderBy(w => w).ToArray());

            PrintArr(methodArray.OrderByDescending(w => w).ToArray());

            PrintArr(methodArray.Where(w => w > 30).OrderBy(w => w).ToArray());

            Console.WriteLine("Provide values divided by ;");
            string[]   valuesToCreate = Console.ReadLine().Split(";");
            ArrayClass nextArr        = new ArrayClass();

            try
            {
                int size  = Convert.ToInt32(valuesToCreate[0]);
                int nFrom = Convert.ToInt32(valuesToCreate[1]);
                int nTo   = Convert.ToInt32(valuesToCreate[2]);
                nextArr = new ArrayClass(size, nFrom, nTo);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            PrintArr(nextArr.GetArray());
        }
Exemplo n.º 35
0
Arquivo: test.cs Projeto: mono/gert
	static int Main () {
		FileNotFoundException fnf = null;

		fnf = new FileNotFoundException ();
		if (fnf.Message != "Unable to find the specified file.") {
			Console.WriteLine ("#A1:" + fnf.Message);
			return 1;
		}
		if (fnf.ToString () != "System.IO.FileNotFoundException: Unable to find the specified file.") {
			Console.WriteLine ("#A2: " + fnf.ToString ());
			return 1;
		}

		fnf = new FileNotFoundException ("message");
		if (fnf.Message != "message") {
			Console.WriteLine ("#B1:" + fnf.Message);
			return 1;
		}
		if (fnf.ToString () != "System.IO.FileNotFoundException: message") {
			Console.WriteLine ("#B2: " + fnf.ToString ());
			return 1;
		}

		fnf = new FileNotFoundException ("message", new ArithmeticException ());
		if (fnf.Message != "message") {
			Console.WriteLine ("#C1:" + fnf.Message);
			return 1;
		}
		if (fnf.ToString () != "System.IO.FileNotFoundException: message ---> System.ArithmeticException: Overflow or underflow in the arithmetic operation.") {
			Console.WriteLine ("#C2: " + fnf.ToString ());
			return 1;
		}

		fnf = new FileNotFoundException ("message", "file.txt");
		if (fnf.Message != "message") {
			Console.WriteLine ("#D1:" + fnf.Message);
			return 1;
		}
#if NET_2_0
		if (fnf.ToString () != ("System.IO.FileNotFoundException: message" + Environment.NewLine + "File name: 'file.txt'")) {
#else
		if (fnf.ToString () != ("System.IO.FileNotFoundException: message" + Environment.NewLine + "File name: \"file.txt\"")) {
#endif
			Console.WriteLine ("#D2: " + fnf.ToString ());
			return 1;
		}

		fnf = new FileNotFoundException ("message", "file.txt", new ArithmeticException ());
		if (fnf.Message != "message") {
			Console.WriteLine ("#E1");
			return 1;
		}
#if NET_2_0
		if (fnf.ToString () != ("System.IO.FileNotFoundException: message" + Environment.NewLine + "File name: 'file.txt' ---> System.ArithmeticException: Overflow or underflow in the arithmetic operation.")) {
#else
		if (fnf.ToString () != ("System.IO.FileNotFoundException: message" + Environment.NewLine + "File name: \"file.txt\" ---> System.ArithmeticException: Overflow or underflow in the arithmetic operation.")) {
#endif
			Console.WriteLine ("#E2: " + fnf.ToString ());
			return 1;
		}

		fnf = new FileNotFoundException (null);
#if NET_2_0
		if (fnf.Message != null) {
#else
		if (fnf.Message != "File or assembly name (null), or one of its dependencies, was not found.") {
#endif
			Console.WriteLine ("#F1:" + fnf.Message);
			return 1;
		}
#if NET_2_0
		if (fnf.ToString () != "System.IO.FileNotFoundException: ") {
#else
		if (fnf.ToString () != "System.IO.FileNotFoundException: File or assembly name (null), or one of its dependencies, was not found.") {
#endif
			Console.WriteLine ("#F2");
			return 1;
		}

		fnf = new FileNotFoundException (null, "file.txt");
#if NET_2_0
		if (fnf.Message != "Could not load file or assembly 'file.txt' or one of its dependencies. The system cannot find the file specified.") {
#else
		if (fnf.Message != "File or assembly name file.txt, or one of its dependencies, was not found.") {
#endif
			Console.WriteLine ("#G1: " + fnf.Message);
			return 1;
		}
#if NET_2_0
		if (fnf.ToString () != ("System.IO.FileNotFoundException: Could not load file or assembly 'file.txt' or one of its dependencies. The system cannot find the file specified." + Environment.NewLine + "File name: 'file.txt'")) {
#else
		if (fnf.ToString () != ("System.IO.FileNotFoundException: File or assembly name file.txt, or one of its dependencies, was not found." + Environment.NewLine + "File name: \"file.txt\"")) {
#endif
			Console.WriteLine ("#G2: " + fnf.ToString ());
			return 1;
		}

		fnf = new FileNotFoundException (null, (string) null);
#if NET_2_0
		if (fnf.Message != null) {
#else
		if (fnf.Message != "File or assembly name (null), or one of its dependencies, was not found.") {
#endif
			Console.WriteLine ("#H1: " + fnf.Message);
			return 1;
		}
#if NET_2_0
		if (fnf.ToString () != "System.IO.FileNotFoundException: ") {
#else
		if (fnf.ToString () != "System.IO.FileNotFoundException: File or assembly name (null), or one of its dependencies, was not found.") {
#endif
			Console.WriteLine ("#H2: " + fnf.ToString ());
			return 1;
		}

		fnf = new FileNotFoundException (null, string.Empty);
#if NET_2_0
		if (fnf.Message != "Could not load file or assembly '' or one of its dependencies. The system cannot find the file specified.") {
#else
		if (fnf.Message != "File or assembly name , or one of its dependencies, was not found.") {
#endif
			Console.WriteLine ("#I1: " + fnf.Message);
			return 1;
		}
#if NET_2_0
		if (fnf.ToString () != "System.IO.FileNotFoundException: Could not load file or assembly '' or one of its dependencies. The system cannot find the file specified.") {
#else
		if (fnf.ToString () != "System.IO.FileNotFoundException: File or assembly name , or one of its dependencies, was not found.") {
#endif
			Console.WriteLine ("#I2: " + fnf.ToString ());
			return 1;
		}

		fnf = new FileNotFoundException (string.Empty, string.Empty);
#if NET_2_0
		if (fnf.Message != string.Empty) {
#else
		if (fnf.Message != string.Empty) {
#endif
			Console.WriteLine ("#J1: " + fnf.Message);
			return 1;
		}
#if NET_2_0
		if (fnf.ToString () != "System.IO.FileNotFoundException: ") {
#else
		if (fnf.ToString () != "System.IO.FileNotFoundException: ") {
#endif
			Console.WriteLine ("#J2: " + fnf.ToString ());
			return 1;
		}

		fnf = new FileNotFoundException (string.Empty, (string) null);
#if NET_2_0
		if (fnf.Message != string.Empty) {
#else
		if (fnf.Message != string.Empty) {
#endif
			Console.WriteLine ("#K1: " + fnf.Message);
			return 1;
		}
#if NET_2_0
		if (fnf.ToString () != "System.IO.FileNotFoundException: ") {
#else
		if (fnf.ToString () != "System.IO.FileNotFoundException: ") {
#endif
			Console.WriteLine ("#K2: " + fnf.ToString ());
			return 1;
		}

		try {
			Assembly.LoadFrom ("b.dll");
			return 1;
		} catch (FileNotFoundException ex) {
			if (ex.Message == null) {
				Console.WriteLine ("#L1");
				return 1;
			}
#if NET_2_0
			if (ex.Message != "Could not load file or assembly 'b.dll' or one of its dependencies. The system cannot find the file specified.") {
#else
			if (ex.Message != "File or assembly name b.dll, or one of its dependencies, was not found.") {
#endif
				Console.WriteLine ("#L2: " + ex.Message);
				return 1;
			}
			if (ex.FileName == null) {
				Console.WriteLine ("#L3");
				return 1;
			}
			if (ex.FileName != "b.dll") {
				Console.WriteLine ("#L4");
				return 1;
			}
		}

		try {
			Assembly.Load ("whatever");
			return 1;
		} catch (FileNotFoundException ex) {
			if (ex.Message == null) {
				Console.WriteLine ("#M1");
				return 1;
			}
#if NET_2_0
			if (ex.Message != "Could not load file or assembly 'whatever' or one of its dependencies. The system cannot find the file specified.") {
#else
			if (ex.Message != "File or assembly name whatever, or one of its dependencies, was not found.") {
#endif
				Console.WriteLine ("#M2: " + ex.Message);
				return 1;
			}
			if (ex.FileName == null) {
				Console.WriteLine ("#M3");
				return 1;
			}
			if (ex.FileName != "whatever") {
				Console.WriteLine ("#M4");
				return 1;
			}
		}

		try {
			AppDomain.CurrentDomain.ExecuteAssembly ("c.dll");
			return 1;
		} catch (FileNotFoundException ex) {
			if (ex.Message == null) {
				Console.WriteLine ("#N1");
				return 1;
			}
#if NET_2_0
			if (ex.Message != "Could not load file or assembly 'c.dll' or one of its dependencies. The system cannot find the file specified.") {
#else
			if (ex.Message != "File or assembly name c.dll, or one of its dependencies, was not found.") {
#endif
				Console.WriteLine ("#N2: " + ex.Message);
				return 1;
			}
			if (ex.FileName == null) {
				Console.WriteLine ("#N3");
				return 1;
			}
			if (ex.FileName != "c.dll") {
				Console.WriteLine ("#N4");
				return 1;
			}
		}
		return 0;
	}
}
 public NameNotFoundException(string message, FileNotFoundException inner) : base(message, inner)
 {
 }
Exemplo n.º 37
0
 public static void Ctor_Empty()
 {
     var exception = new FileNotFoundException();
     ExceptionUtility.ValidateExceptionProperties(exception, hResult: HResults.COR_E_FILENOTFOUND, validateMessage: false);
     Assert.Null(exception.FileName);
 }
Exemplo n.º 38
0
        /// <summary>
        /// Loads test suite assembly.
        /// </summary>
        public void LoadTestSuiteAssembly()
        {
            try
            {
                appConfig.GetAdapterMethods();
            }
            catch (ReflectionTypeLoadException ex)
            {
                StringBuilder sb = new StringBuilder();
                foreach (Exception exSub in ex.LoaderExceptions)
                {
                    sb.AppendLine(exSub.Message);
                    FileNotFoundException exFileNotFound = exSub as FileNotFoundException;
                    if (exFileNotFound != null)
                    {
                        if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
                        {
                            sb.AppendLine("Fusion Log:");
                            sb.AppendLine(exFileNotFound.FusionLog);
                        }
                    }
                    sb.AppendLine();
                }

                throw new Exception(string.Format(StringResource.LoadAdapterError, sb.ToString()));
            }
            catch (Exception e)
            {
                throw new Exception(string.Format(StringResource.LoadAdapterError, e.Message));
            }
            testSuite = new TestSuite();
            try
            {
                AppDomain.CurrentDomain.AssemblyResolve += UnitTestFrameworkResolveHandler;
                testSuite.LoadFrom(appConfig.TestSuiteAssembly);
                AppDomain.CurrentDomain.AssemblyResolve -= UnitTestFrameworkResolveHandler;
            }
            catch (Exception e)
            {
                throw new Exception(string.Format(StringResource.LoadAssemblyError, e.Message));
            }
            if (appConfig.TestCategory != null)
            {
                try
                {
                    testSuite.AppendCategoryByConfigFile(appConfig.TestCategory);
                }
                catch (Exception e)
                {
                    throw new Exception(string.Format(StringResource.AppendCategoryError, e.Message));
                }
            }

            if (filter != null)
            {
                Dictionary <string, List <Rule> > reverseMappingTable;
                Dictionary <string, List <Rule> > featureMappingTable = CreateFeatureMappingTable(out reverseMappingTable);
                if (featureMappingTable != null)
                {
                    RuleGroup targetFilterGroup  = filter[targetFilterIndex];
                    RuleGroup mappingFilterGroup = filter[mappingFilterIndex];
                    targetFilterGroup.featureMappingTable = featureMappingTable;
                    targetFilterGroup.mappingRuleGroup    = mappingFilterGroup;

                    mappingFilterGroup.reverseFeatureMappingTable = reverseMappingTable;
                    mappingFilterGroup.targetRuleGroup            = targetFilterGroup;
                }
            }
        }
Exemplo n.º 39
0
        /// <summary>
        /// Find all monitors
        /// </summary>
        private List <EDDIMonitor> findMonitors()
        {
            DirectoryInfo      dir      = new DirectoryInfo(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
            List <EDDIMonitor> monitors = new List <EDDIMonitor>();
            Type pluginType             = typeof(EDDIMonitor);

            foreach (FileInfo file in dir.GetFiles("*Monitor.dll", SearchOption.AllDirectories))
            {
                Logging.Debug("Checking potential plugin at " + file.FullName);
                try
                {
                    Assembly assembly = Assembly.LoadFrom(file.FullName);
                    foreach (Type type in assembly.GetTypes())
                    {
                        if (type.IsInterface || type.IsAbstract)
                        {
                            continue;
                        }
                        else
                        {
                            if (type.GetInterface(pluginType.FullName) != null)
                            {
                                Logging.Debug("Instantiating monitor plugin at " + file.FullName);
                                EDDIMonitor monitor = type.InvokeMember(null,
                                                                        BindingFlags.CreateInstance,
                                                                        null, null, null) as EDDIMonitor;
                                monitors.Add(monitor);
                            }
                        }
                    }
                }
                catch (BadImageFormatException)
                {
                    // Ignore this; probably due to CPU architecture mismatch
                }
                catch (ReflectionTypeLoadException ex)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (Exception exSub in ex.LoaderExceptions)
                    {
                        sb.AppendLine(exSub.Message);
                        FileNotFoundException exFileNotFound = exSub as FileNotFoundException;
                        if (exFileNotFound != null)
                        {
                            if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
                            {
                                sb.AppendLine("Fusion Log:");
                                sb.AppendLine(exFileNotFound.FusionLog);
                            }
                        }
                        sb.AppendLine();
                    }
                    Logging.Warn("Failed to instantiate plugin at " + file.FullName + ":\n" + sb.ToString());
                }
                catch (FileLoadException flex)
                {
                    string msg = "Failed to load monitor.  Please ensure that " + dir.FullName + " is not on a network share, or itself shared";
                    Logging.Error(msg, flex);
                    SpeechService.Instance.Say(null, msg, false);
                }
            }
            return(monitors);
        }
Exemplo n.º 40
0
        /// <summary>
        ///
        /// </summary>
        protected override void ProcessRecord()
        {
            ProviderInfo        provider = null;
            Collection <string> filePaths;

            try
            {
                if (this.Context.EngineSessionState.IsProviderLoaded(Context.ProviderNames.FileSystem))
                {
                    filePaths = SessionState.Path.GetResolvedProviderPathFromPSPath(_path, out provider);
                }
                else
                {
                    filePaths = new Collection <string>();
                    filePaths.Add(_path);
                }
            }
            catch (ItemNotFoundException)
            {
                string message            = StringUtil.Format(RemotingErrorIdStrings.PSSessionConfigurationFileNotFound, _path);
                FileNotFoundException fnf = new FileNotFoundException(message);
                ErrorRecord           er  = new ErrorRecord(fnf, "PSSessionConfigurationFileNotFound",
                                                            ErrorCategory.ResourceUnavailable, _path);
                WriteError(er);
                return;
            }

            // Make sure that the path is in the file system - that's all we can handle currently...
            if (!provider.NameEquals(this.Context.ProviderNames.FileSystem))
            {
                // "The current provider ({0}) cannot open a file"
                throw InterpreterError.NewInterpreterException(_path, typeof(RuntimeException),
                                                               null, "FileOpenError", ParserStrings.FileOpenError, provider.FullName);
            }

            // Make sure at least one file was found...
            if (filePaths == null || filePaths.Count < 1)
            {
                string message            = StringUtil.Format(RemotingErrorIdStrings.PSSessionConfigurationFileNotFound, _path);
                FileNotFoundException fnf = new FileNotFoundException(message);
                ErrorRecord           er  = new ErrorRecord(fnf, "PSSessionConfigurationFileNotFound",
                                                            ErrorCategory.ResourceUnavailable, _path);
                WriteError(er);
                return;
            }

            if (filePaths.Count > 1)
            {
                // "The path resolved to more than one file; can only process one file at a time."
                throw InterpreterError.NewInterpreterException(filePaths, typeof(RuntimeException),
                                                               null, "AmbiguousPath", ParserStrings.AmbiguousPath);
            }

            string             filePath   = filePaths[0];
            ExternalScriptInfo scriptInfo = null;
            string             ext        = System.IO.Path.GetExtension(filePath);

            if (ext.Equals(StringLiterals.PowerShellDISCFileExtension, StringComparison.OrdinalIgnoreCase))
            {
                // Create a script info for loading the file...
                string scriptName;
                scriptInfo = DISCUtils.GetScriptInfoForFile(this.Context, filePath, out scriptName);


                Hashtable configTable = null;

                try
                {
                    configTable = DISCUtils.LoadConfigFile(this.Context, scriptInfo);
                }
                catch (RuntimeException e)
                {
                    WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCErrorParsingConfigFile, filePath, e.Message));
                    WriteObject(false);
                    return;
                }

                if (configTable == null)
                {
                    WriteObject(false);
                    return;
                }

                DISCUtils.ExecutionPolicyType = typeof(ExecutionPolicy);
                WriteObject(DISCUtils.VerifyConfigTable(configTable, this, filePath));
            }
            else
            {
                string message = StringUtil.Format(RemotingErrorIdStrings.InvalidPSSessionConfigurationFilePath, filePath);
                InvalidOperationException ioe = new InvalidOperationException(message);
                ErrorRecord er = new ErrorRecord(ioe, "InvalidPSSessionConfigurationFilePath",
                                                 ErrorCategory.InvalidArgument, _path);
                ThrowTerminatingError(er);
            }
        }
Exemplo n.º 41
0
        public static void FusionLogTest()
        {
            string message = "this is not the file you're looking for";
            string fileName = "file.txt";
            var innerException = new Exception("Inner exception");
            var exception = new FileNotFoundException(message, fileName, innerException);

            Assert.Null(exception.FusionLog);
        }
Exemplo n.º 42
0
        public MainWindow()
        {
            InitializeComponent();
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("pl");
            Thread.CurrentThread.CurrentCulture   = new CultureInfo("pl");
            Assembly a = Assembly.Load("PluginApp");

            rm = new ResourceManager("PluginApp.Resources", a);
            colorBtn.Content     = rm.GetString("Color");
            uddoBtn.Content      = rm.GetString("Undo");
            redoBtn.Content      = rm.GetString("Redo");
            changeLngBtn.Content = rm.GetString("Changelanguage");

            //String folderPath = @"L:\vcprojekty\PluginApp2\plugins\netstandard2.0";
            String folderPath = @"..\..\..\plugins\netstandard2.0";
            //String folderPath = @"X:\PluginApp2\plugins\netstandard2.0";

            List <Assembly> assemblyList = new List <Assembly>();

            foreach (string file in Directory.EnumerateFiles(folderPath, "*.dll"))
            {
                //if (!file.Equals("PluginInterface.dll"))
                {
                    //var temp = Assembly.LoadFile(file);
                    var temp = Assembly.LoadFile(System.IO.Path.GetFullPath(file));
                    assemblyList.Add(temp);
                }
            }

            foreach (Assembly assembly in assemblyList)
            {
                System.Type t1 = null;
                try
                {
                    foreach (var t in assembly.GetTypes())
                    {
                        if (t.IsClass && t.IsPublic && typeof(PluginInterface).IsAssignableFrom(t))
                        {
                            t1 = t;
                            break;
                        }
                    }
                }
                catch (ReflectionTypeLoadException ex)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (Exception exSub in ex.LoaderExceptions)
                    {
                        sb.AppendLine(exSub.Message);
                        FileNotFoundException exFileNotFound = exSub as FileNotFoundException;
                        if (exFileNotFound != null)
                        {
                            if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
                            {
                                sb.AppendLine("Fusion Log:");
                                sb.AppendLine(exFileNotFound.FusionLog);
                            }
                        }
                        sb.AppendLine();
                    }
                    string errorMessage = sb.ToString();
                    //Display or log the error based on your application.
                    Console.WriteLine(sb);
                }

                if (t1 != null)
                {
                    var o = Activator.CreateInstance(t1);
                    plugins.Add((PluginInterface)o);
                }
            }
            InkCanvas.DefaultDrawingAttributes.Color = Colors.Black;
            InkCanvas.Strokes.StrokesChanged        += Strokes_StrokesChanged;
            addedStrokes   = new Stack <System.Windows.Ink.StrokeCollection>();
            removedStrokes = new Stack <System.Windows.Ink.StrokeCollection>();

            addMenuItems();
        }