예제 #1
0
파일: TestBase.cs 프로젝트: Mazrick/jni4net
 public virtual void Setup()
 {
     var sp = new FileIOPermission(PermissionState.Unrestricted);
     sp.Assert();
     string prefix;
     if (Environment.CurrentDirectory.EndsWith("target"))
     {
         prefix = "../../";
     }
     else
     {
         prefix = "../../../";
     }
     sp.Deny();
     Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
     BridgeSetup setup=new BridgeSetup (false){Verbose = true, Debug = true};
     setup.IgnoreJavaHome = true;
     setup.AddJVMOption("-Xmx512m");
     setup.AddClassPath(prefix + "jni4net.j/target/classes");
     setup.AddClassPath(prefix + "jni4net.tested.j/target/classes");
     setup.AddClassPath(prefix + "jni4net.test.j/target/test-classes");
     //setup.JavaHome = @"c:\Program Files (x86)\Java\ibm_sdk60";
     env = Bridge.CreateJVM(setup);
     Bridge.RegisterAssembly(typeof(TestBase).Assembly);
     Bridge.RegisterAssembly(typeof(JavaInstanceFields).Assembly);
 }
예제 #2
0
		bool EnsureActivateContextCreated()
		{
			lock (typeof(EnableThemingInScope))
			{
				if (!contextCreationSucceeded)
				{
					// Pull manifest from the .NET Framework install
					// directory

					string assemblyLoc = null;

					FileIOPermission fiop = new FileIOPermission(PermissionState.None);
					fiop.AllFiles = FileIOPermissionAccess.PathDiscovery;
					fiop.Assert();
					try
					{
						assemblyLoc = typeof(Object).Assembly.Location;
					}
					finally
					{
						CodeAccessPermission.RevertAssert();
					}

					string manifestLoc = null;
					string installDir = null;
					if (assemblyLoc != null)
					{
						installDir = Path.GetDirectoryName(assemblyLoc);
						const string manifestName = "XPThemes.manifest";
						manifestLoc = Path.Combine(installDir, manifestName);
					}

					if (manifestLoc != null && installDir != null)
					{
						enableThemingActivationContext = new ACTCTX();
						enableThemingActivationContext.cbSize = Marshal.SizeOf(typeof(ACTCTX));
						enableThemingActivationContext.lpSource = manifestLoc;

						// Set the lpAssemblyDirectory to the install
						// directory to prevent Win32 Side by Side from
						// looking for comctl32 in the application
						// directory, which could cause a bogus dll to be
						// placed there and open a security hole.
						enableThemingActivationContext.lpAssemblyDirectory = installDir;
						enableThemingActivationContext.dwFlags = ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID;

						// Note this will fail gracefully if file specified
						// by manifestLoc doesn't exist.
						hActCtx = CreateActCtx(ref enableThemingActivationContext);
						contextCreationSucceeded = (hActCtx != new IntPtr(-1));
					}
				}

				// If we return false, we'll try again on the next call into
				// EnsureActivateContextCreated(), which is fine.
				return contextCreationSucceeded;
			}
		}
 private static bool DoesCallerRequireFullTrust(MethodInfo method){
   Assembly assembly = method.DeclaringType.Assembly;
   // strongly-named assembly requires full trust or AllowPartiallyTrustedCallersAttribute to be called
   FileIOPermission pathDiscoveryPermission = new FileIOPermission(PermissionState.None);
   pathDiscoveryPermission.AllFiles = FileIOPermissionAccess.PathDiscovery;
   pathDiscoveryPermission.Assert();
   byte[] key = assembly.GetName().GetPublicKey();
   if (key == null || key.Length == 0)
     return false;
   if (CustomAttribute.GetCustomAttributes(assembly, typeof(AllowPartiallyTrustedCallersAttribute), true).Length != 0)
     return false;
   return true;
 }
예제 #4
0
        public static string UnsafeGetFullPath(string fileName) {
            string full = fileName;

            FileIOPermission fiop = new FileIOPermission(PermissionState.None);
            fiop.AllFiles = FileIOPermissionAccess.PathDiscovery;
            fiop.Assert();
            try {
                full = System.IO.Path.GetFullPath(fileName);
            }
            finally {
                CodeAccessPermission.RevertAssert();
            }
            return full;
        }
예제 #5
0
파일: Class1.cs 프로젝트: alannet/example
 public static void Save(string value)
 {
     try
      {
     FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Append,@"c:\audit.txt");
     permission.Assert();
     FileStream stream = new FileStream(@"c:\audit.txt",FileMode.Append, FileAccess.Write);
     // code to write to audit file here...
     CodeAccessPermission.RevertAssert();
     Console.WriteLine("Data written to audit file");
      }
      catch
      {
     Console.WriteLine("Failed to write data to audit file");
      }
 }
예제 #6
0
파일: ListView.cs 프로젝트: JianwenSun/cc
        /// <include file='doc\ListView.uex' path='docs/doc[@for="ListView.Dispose"]/*' />
        /// <devdoc>
        ///     Disposes of the component.  Call dispose when the component is no longer needed.
        ///     This method removes the component from its container (if the component has a site)
        ///     and triggers the dispose event.
        /// </devdoc>
        protected override void Dispose(bool disposing) {
            if (disposing) {
                // Remove any event sinks we have hooked up to imageLists
                if (imageListSmall != null) {
                    imageListSmall.Disposed -= new EventHandler(this.DetachImageList);
                    imageListSmall = null;
                }
                if (imageListLarge != null) {
                    imageListLarge.Disposed -= new EventHandler(this.DetachImageList);
                    imageListLarge = null;
                }
                if (imageListState != null) {
                    imageListState.Disposed -= new EventHandler(this.DetachImageList);
                    imageListState = null;
                }

                // Remove any ColumnHeaders contained in this control
                if (columnHeaders != null) {
                    for (int colIdx = columnHeaders.Length-1; colIdx >= 0; colIdx--) {
                        columnHeaders[colIdx].OwnerListview = null;
                        columnHeaders[colIdx].Dispose();
                    }
                    columnHeaders = null;
                }

                // Remove any items we have
                Items.Clear();

                if (odCacheFontHandleWrapper != null)
                {
                    odCacheFontHandleWrapper.Dispose();
                    odCacheFontHandleWrapper = null;
                }

                if (!String.IsNullOrEmpty(this.backgroundImageFileName) || this.bkImgFileNames != null) {
                    // we need the fileIoPermission when the app runs on an UNC share and
                    // the list view creates/deletes temporary files for its background image
                    
                    // SECREVIEW : Safe to assert FileIO here since we are deleting files created by us.
                    //
                    FileIOPermission fiop = new FileIOPermission(PermissionState.Unrestricted);
                    fiop.Assert();

                    try {
                        System.IO.FileInfo fi;
                        if (!String.IsNullOrEmpty(this.backgroundImageFileName)) {
                            fi = new System.IO.FileInfo(this.backgroundImageFileName);
                            Debug.Assert(fi.Exists, "who deleted our temp file?");
                            // [....]: vsWhidbey 417804.
                            // ComCtl ListView uses COM objects to manipulate the bitmap we send it to them.
                            // I could not find any resources which explain in detail when the IImgCtx objects
                            // release the temporary file. So if we get a FileIO when we delete the temporary file
                            // we don't do anything about it ( because we don't know what is a good time to try to delete the file again ).
                            try {
                                fi.Delete();
                            } catch (System.IO.IOException){}
                            this.backgroundImageFileName = String.Empty;
                        }
                        for (int i = 0; i <= this.bkImgFileNamesCount; i++) {
                            fi = new System.IO.FileInfo(this.bkImgFileNames[i]);
                            Debug.Assert(fi.Exists, "who deleted our temp file?");
                            // [....]: vsWhidbey 417804.
                            // ComCtl ListView uses COM objects to manipulate the bitmap we send it to them.
                            // I could not find any resources which explain in detail when the IImgCtx objects
                            // release the temporary file. So if we get a FileIO when we delete the temporary file
                            // we don't do anything about it ( because we don't know what is a good time to try to delete the file again ).
                            try {
                                fi.Delete();
                            } catch (System.IO.IOException){}
                        }

                        this.bkImgFileNames = null;
                        this.bkImgFileNamesCount = -1;
                    } finally {
                        System.Security.PermissionSet.RevertAssert();
                    }
                }

            }

            base.Dispose(disposing);
        }
예제 #7
0
파일: ListView.cs 프로젝트: JianwenSun/cc
 private void DeleteFileName(string fileName) {
     if (!String.IsNullOrEmpty(fileName)) {
         // the list view needs the FileIOPermission when the app runs on an UNC share
         // and the list view creates / destroys temporary files for its background image
         
         // SECREVIEW : Safe to assert FileIO here since we are deleting files created by us.
         //
         FileIOPermission fiop = new FileIOPermission(PermissionState.Unrestricted);
         fiop.Assert();
         try {
             System.IO.FileInfo fi = new System.IO.FileInfo(fileName);
             if (fi.Exists) {
                 // [....]: vsWhidbey 417804.
                 // ComCtl ListView uses COM objects to manipulate the bitmap we send it to them.
                 // I could not find any resources which explain in detail when the IImgCtx objects
                 // release the temporary file. So if we get a FileIO when we delete the temporary file
                 // we don't do anything about it ( because we don't know what is a good time to try to delete the file again ).
                 try {
                     fi.Delete();
                 } catch (System.IO.IOException){}
             }
         } finally {
             System.Security.PermissionSet.RevertAssert();
         }
     }
 }
예제 #8
0
파일: ListView.cs 프로젝트: JianwenSun/cc
        private void CleanPreviousBackgroundImageFiles() {
            if (this.bkImgFileNames == null) {
                return;
            }

            // SECREVIEW : Safe to assert FileIO here since we are deleting files created by us.
            //
            FileIOPermission fiop = new FileIOPermission(PermissionState.Unrestricted);
            fiop.Assert();
            try {
                System.IO.FileInfo fi;
                for (int i = 0; i <= this.bkImgFileNamesCount; i ++) {
                    fi = new System.IO.FileInfo(this.bkImgFileNames[i]);
                    if (fi.Exists) {
                        // [....]: vsWhidbey 417804.
                        // ComCtl ListView uses COM objects to manipulate the bitmap we send it to them.
                        // I could not find any resources which explain in detail when the IImgCtx objects
                        // release the temporary file. So if we get a FileIO when we delete the temporary file
                        // we don't do anything about it ( because we don't know what is a good time to try to delete the file again ).
                        try {
                            fi.Delete();
                        } catch (System.IO.IOException){}
                    }
                }
            } finally {
                System.Security.PermissionSet.RevertAssert();
            }

            this.bkImgFileNames = null;
            this.bkImgFileNamesCount = -1;
        }
예제 #9
0
 private Stream CriticalOpenFile(string filename)
 {
     Stream s = null;
     FileIOPermission filePermission = new FileIOPermission(FileIOPermissionAccess.Read, filename); 
     filePermission.Assert();
     try 
     { 
         s = System.IO.File.Open(filename, FileMode.Open, FileAccess.Read, ResourceContainer.FileShare);
     } 
     finally
     {
         CodeAccessPermission.RevertAssert();
     } 
     return s;
 } 
        private static void CreateSymbolFile(CounterCreationDataCollection creationData) {
            //SECREVIEW: PerformanceCounterPermission must have been demanded before
            FileIOPermission permission = new FileIOPermission(PermissionState.Unrestricted);
            permission.Assert();
            try {
                StreamWriter symbolWriter = new StreamWriter(SymbolFilePath);
                try {
                    symbolWriter.Write(defineKeyword);
                    symbolWriter.Write(" ");
                    symbolWriter.Write(categorySymbolPrefix);
                    symbolWriter.WriteLine("1 0;");

                    for (int counterIndex = 1; counterIndex <= creationData.Count; ++ counterIndex) {
                        symbolWriter.Write(defineKeyword);
                        symbolWriter.Write(" ");
                        symbolWriter.Write(conterSymbolPrefix);
                        symbolWriter.Write(counterIndex.ToString(CultureInfo.InvariantCulture));
                        symbolWriter.Write(" ");
                        symbolWriter.Write((counterIndex * 2).ToString(CultureInfo.InvariantCulture));
                        symbolWriter.WriteLine(";");
                    }

                    symbolWriter.WriteLine("");
                }
                finally {
                    symbolWriter.Close();
                }
            }
            finally {
                FileIOPermission.RevertAssert();
            }
        }
        private static bool IsAssemblyLoaded(String assemblyName)
        {
            // Since there is no managed API for finding the GAC path, I 
            // assert path discovery for all local files.
            FileIOPermission permission = new FileIOPermission(PermissionState.None);
            permission.AllLocalFiles = FileIOPermissionAccess.PathDiscovery;
            permission.Assert();

            foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                if (assembly.FullName.Equals(assemblyName, StringComparison.OrdinalIgnoreCase)) {
                    return true;
                }

                // Warn if they have the same assembly with different versions.  If we don't do this,
                // they will get an InvalidCastException instead.
                AssemblyName name1 = new AssemblyName(assemblyName);
                AssemblyName name2 = assembly.GetName();
                if (name1.Name == name2.Name && 
                    name1.CultureInfo.Equals(name2.CultureInfo) &&
                    Utils.PublicKeyMatches(name1, name2) && 
                    name1.Version != name2.Version)
                {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, Res.IncompatibleAddInBaseAssembly, assemblyName));
                }
            }
            return false;
        }
예제 #12
0
파일: Form.cs 프로젝트: mind0n/hive
        /// <devdoc>
        ///    This private method attempts to resolve security zone and site
        ///    information given a list of urls (sites).  This list is supplied
        ///    by the runtime and will contain the paths of all loaded assemblies
        ///    on the stack.  From here, we can examine zones and sites and
        ///    attempt to identify the unique and mixed scenarios for each.  This
        ///    information will be displayed in the titlebar of the Form in a
        ///    semi-trust environment.
        /// </devdoc>
        private void ResolveZoneAndSiteNames(ArrayList sites, ref string securityZone, ref string securitySite) {

            //Start by defaulting to 'unknown zone' and 'unknown site' strings.  We will return this
            //information if anything goes wrong while trying to resolve this information.
            //
            securityZone = SR.GetString(SR.SecurityRestrictedWindowTextUnknownZone);
            securitySite = SR.GetString(SR.SecurityRestrictedWindowTextUnknownSite);

            try
            {
                //these conditions must be met
                //
                if (sites == null || sites.Count == 0)
                    return;

                //create a new zone array list which has no duplicates and no
                //instances of mycomputer
                ArrayList zoneList = new ArrayList();
                foreach (object arrayElement in sites)
                {
                    if (arrayElement == null)
                        return;

                    string url = arrayElement.ToString();

                    if (url.Length == 0)
                        return;

                    //into a zoneName
                    //
                    Zone currentZone = Zone.CreateFromUrl(url);

                    //skip this if the zone is mycomputer
                    //
                    if (currentZone.SecurityZone.Equals(SecurityZone.MyComputer))
                        continue;

                    //add our unique zonename to our list of zones
                    //
                    string zoneName = currentZone.SecurityZone.ToString();

                    if (!zoneList.Contains(zoneName))
                    {
                        zoneList.Add(zoneName);
                    }
                }

                //now, we resolve the zone name based on the unique information
                //left in the zoneList
                //
                if (zoneList.Count == 0)
                {
                    //here, all the original zones were 'mycomputer'
                    //so we can just return that
                    securityZone = SecurityZone.MyComputer.ToString();
                }
                else if (zoneList.Count == 1)
                {
                    //we only found 1 unique zone other than
                    //mycomputer
                    securityZone = zoneList[0].ToString();
                }
                else
                {
                    //here, we found multiple zones
                    //
                    securityZone = SR.GetString(SR.SecurityRestrictedWindowTextMixedZone);
                }

                //generate a list of loaded assemblies that came from the gac, this
                //way we can safely ignore these from the url list
                ArrayList loadedAssembliesFromGac = new ArrayList();

                // SECREVIEW : Querying for assembly info is safe.
                //
                FileIOPermission fiop = new FileIOPermission( PermissionState.None );
                fiop.AllFiles = FileIOPermissionAccess.PathDiscovery;
                fiop.Assert();

                try
                {
                    foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
                    {
                        if (asm.GlobalAssemblyCache)
                        {
                            loadedAssembliesFromGac.Add(asm.CodeBase.ToUpper(CultureInfo.InvariantCulture));
                        }
                    }
                }
                finally
                {
                    CodeAccessPermission.RevertAssert();
                }

                //now, build up a sitelist which contains a friendly string
                //we've extracted via the uri class and omit any urls that reference
                //our local gac
                //
                ArrayList siteList = new ArrayList();
                foreach (object arrayElement in sites)
                {
                    //we know that each element is valid because of our
                    //first pass
                    Uri currentSite = new Uri(arrayElement.ToString());

                    //if we see a site that contains the path to our gac,
                    //we'll just skip it

                    if (loadedAssembliesFromGac.Contains(currentSite.AbsoluteUri.ToUpper(CultureInfo.InvariantCulture)))
                    {
                        continue;
                    }

                    //add the unique host name to our list
                    string hostName = currentSite.Host;
                    if (hostName.Length > 0 && !siteList.Contains(hostName))
                        siteList.Add(hostName);
                }


                //resolve the site name from our list, if siteList.count == 0
                //then we have already set our securitySite to "unknown site"
                //
                if (siteList.Count == 0) {
                    //here, we'll set the local machine name to the site string
                    //

                    // SECREVIEW : Querying for environment info is safe.
                    //
                    new EnvironmentPermission(PermissionState.Unrestricted).Assert();
                    try {
                        securitySite = Environment.MachineName;
                    }
                    finally {
                        CodeAccessPermission.RevertAssert();
                    }
                }
                else if (siteList.Count == 1)
                {
                    //We found 1 unique site other than the info in the
                    //gac
                    securitySite = siteList[0].ToString();
                }
                else
                {
                    //multiple sites, we'll have to return 'mixed sites'
                    //
                    securitySite = SR.GetString(SR.SecurityRestrictedWindowTextMultipleSites);
                }
            }
            catch
            {
                //We'll do nothing here. The idea is that zone and security strings are set
                //to "unkown" at the top of this method - if an exception is thrown, we'll
                //stick with those values
            }
        }
예제 #13
0
        protected override void ExecuteTask()
        {
            ArrayList taskTypes;
            ArrayList dataTypes;

            if (ForType == null) {
                taskTypes = new ArrayList(TypeFactory.TaskBuilders.Count);
                dataTypes = new ArrayList(TypeFactory.DataTypeBuilders.Count);

                foreach (TaskBuilder tb in TypeFactory.TaskBuilders) {
                    taskTypes.Add(tb.Assembly.GetType(tb.ClassName, true, true));
                }

                foreach (DataTypeBaseBuilder db in TypeFactory.DataTypeBuilders) {
                    dataTypes.Add(db.Assembly.GetType(db.ClassName, true, true));
                }
            } else {
                taskTypes = new ArrayList(1);
                taskTypes.Add(Type.GetType(ForType, true, true));
                dataTypes = new ArrayList();
            }

            MemoryStream ms = new MemoryStream();
            WriteSchema(ms, (Type[]) taskTypes.ToArray(typeof(Type)),
                (Type[]) dataTypes.ToArray(typeof(Type)), TargetNamespace);

            // reset position of memorystream
            ms.Position = 0;

            // let's validate whether we emitted a valid XML Schema
            try {
                XmlSchema schema = XmlSchema.Read(ms, null);
                schema.Compile(null);
            } catch (XmlSchemaException ex) {
                throw new BuildException ("The generated XML schema is not valid.",
                    Location, ex);
            }
            // reset position of memorystream
            ms.Position = 0;
            FileIOPermission FilePermission = new FileIOPermission(FileIOPermissionAccess.AllAccess, OutputFile.FullName);
            FilePermission.Assert();
            using (FileStream file = File.Open(OutputFile.FullName, FileMode.Create, FileAccess.Write, FileShare.Read)) {
                byte[] buffer = new byte[4096];
                int bytesRead = ms.Read(buffer, 0, buffer.Length);
                while (bytesRead != 0) {
                    file.Write(buffer, 0, bytesRead);
                    bytesRead = ms.Read(buffer, 0, buffer.Length);
                }
                file.Flush();
                file.Close();
            }

            Log(Level.Info, "Wrote schema to '{0}'.", OutputFile.FullName);
        }
예제 #14
0
        protected override void ExecuteTask()
        {
            ArrayList taskTypes;
            ArrayList dataTypes;

            if (ForType == null) {
                taskTypes = new ArrayList(TypeFactory.TaskBuilders.Count);
                dataTypes = new ArrayList(TypeFactory.DataTypeBuilders.Count);

                foreach (TaskBuilder tb in TypeFactory.TaskBuilders) {
                    taskTypes.Add(Assembly.LoadFrom(tb.AssemblyFileName).GetType(tb.ClassName, true, true));
                }

                foreach (DataTypeBaseBuilder db in TypeFactory.DataTypeBuilders) {
                    dataTypes.Add(Assembly.LoadFrom(db.AssemblyFileName).GetType(db.ClassName, true, true));
                }
            } else {
                taskTypes = new ArrayList(1);
                taskTypes.Add(Type.GetType(ForType, true, true));
                dataTypes = new ArrayList();
            }

            FileIOPermission FilePermission = new FileIOPermission(FileIOPermissionAccess.AllAccess, OutputFile.FullName); 
            FilePermission.Assert();
            using (FileStream file = File.Open(OutputFile.FullName, FileMode.Create, FileAccess.Write, FileShare.Read)) {
                WriteSchema(file, (Type[]) taskTypes.ToArray(typeof(Type)),
                    (Type[]) dataTypes.ToArray(typeof(Type)), TargetNamespace);

                file.Flush();
                file.Close();
            }

            Log(Level.Info, "Wrote schema to '{0}'.", OutputFile.FullName);
예제 #15
0
        private void AddFooterToOneHtmlFile
        (
            string _sPathToInputFile,
            string _sPathToOutputFile,
            string _sFileNameInAndOut,
            string _sFooter
        )
        {
            SysIo.FileStream             fstreamRead, fstreamWrite;
            SysIo.StreamReader           streamRead  = null;
            SysIo.StreamWriter           streamWrite = null;
            SysSecuPerm.FileIOPermission fileIoPerm;
            string sWholeFileContents, sWholeFilePlusFooter;

            //

            try
            {
                fileIoPerm = new SysSecuPerm.FileIOPermission(SysSecuPerm.PermissionState.Unrestricted);
                fileIoPerm.Assert();

                fstreamRead = new SysIo.FileStream
                              (
                    _sPathToInputFile + _sFileNameInAndOut,
                    SysIo.FileMode.Open,
                    SysIo.FileAccess.Read,
                    SysIo.FileShare.Read
                              );

                streamRead         = new SysIo.StreamReader(fstreamRead);
                sWholeFileContents = streamRead.ReadToEnd();
                streamRead.Close();

                sWholeFilePlusFooter = sWholeFileContents.Replace
                                           (@"</body>", _sFooter + @"</body>");

                fstreamWrite = new SysIo.FileStream
                               (
                    _sPathToOutputFile + _sFileNameInAndOut,
                    SysIo.FileMode.Create,
                    SysIo.FileAccess.Write,
                    SysIo.FileShare.None
                               );

                streamWrite = new SysIo.StreamWriter(fstreamWrite);
                streamWrite.Write(sWholeFilePlusFooter);
                streamWrite.Flush();
                streamWrite.Close();
            }
            finally
            {
                if (null != streamRead)
                {
                    streamRead.Dispose();
                }
                if (null != streamWrite)
                {
                    streamWrite.Dispose();
                }

                SysSecuPerm.FileIOPermission.RevertAssert();
                fileIoPerm = null;
            }

            return;
        }
        // 
        // ResolveFiles - parse files referenced with <file src="" />
        //
        static void ResolveFiles(ParseState parseState, object configurationContext) {

            //
            // 1) get the directory of the configuration file currently being parsed
            //

            HttpConfigurationContext httpConfigurationContext = (HttpConfigurationContext) configurationContext;
            string configurationDirectory = null;
            bool useAssert = false;

            //
            // Only assert to read cap files when parsing machine.config 
            // (allow device updates to work in restricted trust levels).
            //
            // Machine.config can be securely identified by the context being 
            // an HttpConfigurationContext with null path.
            //
            try {
                if (httpConfigurationContext.VirtualPath == null) {
                    useAssert = true;
                    // we need to assert here to get the file path from ConfigurationException
                    FileIOPermission fiop = new FileIOPermission(PermissionState.None);
                    fiop.AllFiles = FileIOPermissionAccess.PathDiscovery;
                    fiop.Assert();
                }
                
                Pair pair0 = (Pair)parseState.FileList[0];
                XmlNode srcAttribute = (XmlNode)pair0.Second;
                configurationDirectory = Path.GetDirectoryName(ConfigurationErrorsException.GetFilename(srcAttribute));
            }
            finally {
                if (useAssert) {
                    CodeAccessPermission.RevertAssert();
                }
            }

            //
            // 2) iterate through list of referenced files, builing rule lists for each
            //
            foreach (Pair pair in parseState.FileList) {
                string srcFilename = (string)pair.First;
                string fullFilename = Path.Combine(configurationDirectory, srcFilename);

                XmlNode section;
                try {
                    if (useAssert) {
                        InternalSecurityPermissions.FileReadAccess(fullFilename).Assert();
                    }
                    
                    Exception fcmException = null;
                    
                    try {
                        HttpConfigurationSystem.AddFileDependency(fullFilename);
                    }
                    catch (Exception e) {
                        fcmException = e;
                    }

                    ConfigXmlDocument configDoc = new ConfigXmlDocument();
                    
                    try {
                        configDoc.Load(fullFilename);
                        section = configDoc.DocumentElement;
                    }
                    catch (Exception e) {
                        throw new ConfigurationErrorsException(SR.GetString(SR.Error_loading_XML_file, fullFilename, e.Message), 
                                        e, (XmlNode)pair.Second);
                    }

                    if (fcmException != null) {
                        throw fcmException;
                    }
                }
                finally {
                    if (useAssert) {
                        // Cannot apply next FileReadAccess PermissionSet unless 
                        // current set is explicitly reverted.  Also minimizes
                        // granted permissions.
                        CodeAccessPermission.RevertAssert();
                    }
                }
                
                if (section.Name != parseState.SectionName) {
                    throw new ConfigurationErrorsException(SR.GetString(SR.Capability_file_root_element, parseState.SectionName), 
                                    section);
                }
                    
                HandlerBase.CheckForUnrecognizedAttributes(section);

                ArrayList sublist = RuleListFromElement(parseState, section, true);

                if (sublist.Count > 0) {
                    parseState.RuleList.Add(new CapabilitiesSection(CapabilitiesRule.Filter, null, null, sublist));
                }
            }
        }
예제 #17
0
        private static FileVersionInfo GetAppFileVersionInfo() {
            lock (internalSyncObject) {
                if (appFileVersion == null) {
                    Type t = GetAppMainType();
                    if (t != null) {
                        // SECREVIEW : This Assert is ok, getting the module's version is a safe operation, 
                        //             the result is provided by the system.
                        //
                        FileIOPermission fiop = new FileIOPermission( PermissionState.None );
                        fiop.AllFiles = FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read;
                        fiop.Assert();

                        try {
                            appFileVersion = FileVersionInfo.GetVersionInfo(t.Module.FullyQualifiedName);
                        }
                        finally {
                            CodeAccessPermission.RevertAssert();
                        }
                    }
                    else {
                        appFileVersion = FileVersionInfo.GetVersionInfo(ExecutablePath);
                    }
                }
            }

            return(FileVersionInfo)appFileVersion;
        }
예제 #18
0
        /// <include file='doc\Application.uex' path='docs/doc[@for="Application.EnableVisualStyles"]/*' />
        /// <devdoc>
        ///    <para>
        ///    Enables visual styles for all subsequent Application.Run() and CreateHandle() calls.
        ///    Uses the default theming manifest file shipped with the redist.
        ///    </para>
        /// </devdoc>
        public static void EnableVisualStyles() {
            string assemblyLoc = null;

            // SECREVIEW : This Assert is ok, getting the module path is a safe operation, 
            //             the result is provided by the system.
            //
            FileIOPermission fiop = new FileIOPermission(PermissionState.None);
            fiop.AllFiles = FileIOPermissionAccess.PathDiscovery;
            fiop.Assert();
            try {
                assemblyLoc = typeof(Application).Assembly.Location;
            }
            finally {
                CodeAccessPermission.RevertAssert();
            }
            // Pull manifest from our resources
            if (assemblyLoc != null) {
                EnableVisualStylesInternal(assemblyLoc, 101);
            }
        }
예제 #19
0
        private static bool EnsureActCtxCreated()
        {
            lock(m_oSync)
            {
                if(m_nhCtx.HasValue) return true;

                string strAsmLoc;
                FileIOPermission p = new FileIOPermission(PermissionState.None);
                p.AllFiles = FileIOPermissionAccess.PathDiscovery;
                p.Assert();
                try { strAsmLoc = typeof(object).Assembly.Location; }
                finally { CodeAccessPermission.RevertAssert(); }
                if(string.IsNullOrEmpty(strAsmLoc)) { Debug.Assert(false); return false; }

                string strInstDir = Path.GetDirectoryName(strAsmLoc);
                string strMfLoc = Path.Combine(strInstDir, "XPThemes.manifest");

                NativeMethods.ACTCTX ctx = new NativeMethods.ACTCTX();
                ctx.cbSize = (uint)Marshal.SizeOf(typeof(NativeMethods.ACTCTX));
                Debug.Assert(((IntPtr.Size == 4) && (ctx.cbSize ==
                    NativeMethods.ACTCTXSize32)) || ((IntPtr.Size == 8) &&
                    (ctx.cbSize == NativeMethods.ACTCTXSize64)));

                ctx.lpSource = strMfLoc;
                ctx.lpAssemblyDirectory = strInstDir;
                ctx.dwFlags = NativeMethods.ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID;

                m_nhCtx = NativeMethods.CreateActCtx(ref ctx);
                if(NativeMethods.IsInvalidHandleValue(m_nhCtx.Value))
                {
                    Debug.Assert(false);
                    m_nhCtx = null;
                    return false;
                }
            }

            return true;
        }
예제 #20
0
        void Session_MessageReceived(object sender, MessageEventArgs e)
        {
            // Save the message in the preset pickup directory
            // ensure we can write
            FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Write, DumpPath);
            permission.Assert();

            StreamWriter file
                = File.AppendText(DumpPath);
            try
            {
                file.Write(_LineTerminator + "---------------START OF MESSAGE-------------------" + _LineTerminator);
                file.Write("Message Id: " + e.MessageId + _LineTerminator);
                file.Write(_LineTerminator + "From: " + e.From + _LineTerminator);
                file.Write("To: " + e.ToAsList() + _LineTerminator);
                file.Write(_LineTerminator + "Subject: " + e.Subject + _LineTerminator);
                file.Write("Data: " + e.Data + _LineTerminator);
                file.Write(_LineTerminator + "---------------END OF MESSAGE---------------------" + _LineTerminator);
                file.Close();

                SetStatus(String.Format("Recieved: {0}", e.Subject));
            }
            finally { file.Close(); }
        }
        // Parameters:
        //  assertPermissions - If true, then we'll assert all required permissions.  Used by ClientSettingsConfigurationHost.
        //                      to allow low-trust apps to use ClientSettingsStore.
        static internal void StaticWriteCompleted(string streamName, bool success, object writeContext, bool assertPermissions) {
            WriteFileContext    writeFileContext = (WriteFileContext) writeContext;
            bool                revertAssert = false;

            if (assertPermissions) {
                 // If asked to assert permissions, we will assert allAccess on the streamName, the temporary file 
                // created by WriteContext, and also the directory itself.  The last one is needed because 
                // WriteFileContext will call TempFileCollection.Dispose, which will remove a .tmp file it created.
                string dir = Path.GetDirectoryName(streamName);
                string[] filePaths = new string[] {streamName, writeFileContext.TempNewFilename, dir};
                FileIOPermission fileIOPerm = new FileIOPermission(FileIOPermissionAccess.AllAccess, AccessControlActions.View | AccessControlActions.Change, filePaths);
                fileIOPerm.Assert();
                revertAssert = true;
            }

            try {
                writeFileContext.Complete(streamName, success);
            }
            finally {
                if (revertAssert) {
                    CodeAccessPermission.RevertAssert();
                }
            }
        }
예제 #22
0
        /// <summary>
        ///  Called whenever assemblies are being resolved for use.
        /// </summary>
        /// <param name="sender">Unknown</param>
        /// <param name="args">Assembly resolve information</param>
        /// <returns>The assembly that matches the resolve information.</returns>
        internal Assembly ResolveAssembly(Object sender, ResolveEventArgs args)
        {
            // Test for OrganismBase
            var matchAssembly = getAssemblyWithTerrariumBindingPolicy(args.Name,
                                                                      Assembly.GetAssembly(typeof (Animal)));
            if (matchAssembly != null)
            {
                return matchAssembly;
            }

            // Test for Terrarium
            matchAssembly = getAssemblyWithTerrariumBindingPolicy(args.Name,
                                                                  Assembly.GetAssembly(typeof (PrivateAssemblyCache)));
            if (matchAssembly != null)
            {
                return matchAssembly;
            }

            // See if it is an organism assembly
            // Need to assert permission to open files on disk because we need to load organism assemblies
            // and organism code could be on the stack because it may be loading an assembly that
            // has not been loaded yet.  This would fail without the assertion.
            var permission = new FileIOPermission(PermissionState.Unrestricted);
            permission.Assert();
            return LoadOrganismAssembly(args.Name);
        }
        public override string GetSavedLicenseKey(Type type, Assembly resourceAssembly) {

            if (savedLicenseKeys == null || savedLicenseKeys[type.AssemblyQualifiedName]==null) {
                Debug.WriteLineIf(RuntimeLicenseContextSwitch.TraceVerbose, "savedLicenseKey is null or doesnt contain our type");
                if (savedLicenseKeys == null) {
                    savedLicenseKeys = new Hashtable();
                }
                
                Uri licenseFile = null;

                if (resourceAssembly == null) {
                    Debug.WriteLineIf(RuntimeLicenseContextSwitch.TraceVerbose,"resourceAssembly is null");
                    string rawFile = (string)AppDomain.CurrentDomain.SetupInformation.LicenseFile;
                    Debug.WriteLineIf(RuntimeLicenseContextSwitch.TraceVerbose,"rawfile: " + rawFile);
                    string codeBase;
                    
#if !DISABLE_CAS_USE
                    // FileIOPermission is required for ApplicationBase in URL-hosted domains
                    FileIOPermission perm = new FileIOPermission(PermissionState.Unrestricted);
                    perm.Assert();
                    try {
                        codeBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                    }
                    finally {
                        CodeAccessPermission.RevertAssert();
                    }
#else
                    codeBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
#endif
                    if (rawFile != null && codeBase != null) {
                        licenseFile = new Uri(new Uri(codeBase), rawFile);
                    }
                }

                if (licenseFile == null) {
                    if(resourceAssembly == null) {
                        resourceAssembly = Assembly.GetEntryAssembly();
                    }

                    if (resourceAssembly == null) {
                        Debug.WriteLineIf(RuntimeLicenseContextSwitch.TraceVerbose,"resourceAssembly is null");
                        // If Assembly.EntryAssembly returns null, then we will 
                        // try everything!
                        // 
                        foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) {

                            // Though, I could not repro this, we seem to be hitting an AssemblyBuilder
                            // when walking through all the assemblies in the current app domain. This throws an 
                            // exception on Assembly.CodeBase and we bail out. Catching exceptions here is not a 
                            // bad thing.
                            if (asm.IsDynamic)
                                continue;

                            // file://fullpath/foo.exe
                            //
                            string fileName;
#if !DISABLE_CAS_USE
                            FileIOPermission perm = new FileIOPermission(PermissionState.Unrestricted);
                            perm.Assert();
                            try
                            {
                                fileName = GetLocalPath(asm.EscapedCodeBase);
                                fileName = new FileInfo(fileName).Name;
                            }
                            finally
                            {
                                CodeAccessPermission.RevertAssert();
                            }
#else
                            fileName = GetLocalPath(asm.EscapedCodeBase);
                            fileName = new FileInfo(fileName).Name;
#endif

                            Stream s = asm.GetManifestResourceStream(fileName + ".licenses");
                            if (s == null) {
                                //Since the casing may be different depending on how the assembly was loaded, 
                                //we'll do a case insensitive lookup for this manifest resource stream...
                                s = CaseInsensitiveManifestResourceStreamLookup(asm, fileName + ".licenses");
                            }
                            
                            if (s != null) {
                                DesigntimeLicenseContextSerializer.Deserialize(s, fileName.ToUpper(CultureInfo.InvariantCulture), this);
                                break;
                            }
                        }
                    }
                    else if(!resourceAssembly.IsDynamic) { // EscapedCodeBase won't be supported by emitted assemblies anyway
                        Debug.WriteLineIf(RuntimeLicenseContextSwitch.TraceVerbose,"resourceAssembly is not null");
                        string fileName;
                        FileIOPermission perm = new FileIOPermission(PermissionState.Unrestricted);
                        perm.Assert();
                        try
                        {
                            fileName = GetLocalPath(resourceAssembly.EscapedCodeBase);
                        }
                        finally
                        {
                            CodeAccessPermission.RevertAssert();
                        }
                        fileName = Path.GetFileName(fileName); // we don't want to use FileInfo here... it requests FileIOPermission that we
                        // might now have... see VSWhidbey 527758
                        string licResourceName = fileName + ".licenses";
                        // first try the filename
                        Stream s = resourceAssembly.GetManifestResourceStream(licResourceName);
                        if (s == null) {
                            string resolvedName = null;
                            CompareInfo comparer = CultureInfo.InvariantCulture.CompareInfo;
                            string shortAssemblyName = resourceAssembly.GetName().Name;
                            //  if the assembly has been renamed, we try our best to find a good match in the available resources
                            // by looking at the assembly name (which doesn't change even after a file rename) + ".exe.licenses" or + ".dll.licenses"
                            foreach(String existingName in resourceAssembly.GetManifestResourceNames()) {
                                if (comparer.Compare(existingName, licResourceName, CompareOptions.IgnoreCase) == 0 ||
                                 comparer.Compare(existingName, shortAssemblyName + ".exe.licenses", CompareOptions.IgnoreCase) == 0 || 
                                 comparer.Compare(existingName, shortAssemblyName + ".dll.licenses", CompareOptions.IgnoreCase) == 0) {
                                    resolvedName = existingName;
                                    break;
                                }
                            }
                            if (resolvedName != null) {
                                s = resourceAssembly.GetManifestResourceStream(resolvedName);
                            }
                        }
                        if (s != null) {
                            DesigntimeLicenseContextSerializer.Deserialize(s, fileName.ToUpper(CultureInfo.InvariantCulture), this);
                        }
                    }
                }


                if (licenseFile != null) {
                    Debug.WriteLineIf(RuntimeLicenseContextSwitch.TraceVerbose,"licenseFile: " + licenseFile.ToString());
                    Debug.WriteLineIf(RuntimeLicenseContextSwitch.TraceVerbose,"opening licenses file over URI " + licenseFile.ToString());
                    Stream s = OpenRead(licenseFile);
                    if (s != null) {
                        string[] segments = licenseFile.Segments;
                        string licFileName = segments[segments.Length - 1];
                        string key = licFileName.Substring(0, licFileName.LastIndexOf("."));
                        DesigntimeLicenseContextSerializer.Deserialize(s, key.ToUpper(CultureInfo.InvariantCulture), this);
                    }
                }

            }
            Debug.WriteLineIf(RuntimeLicenseContextSwitch.TraceVerbose,"returning : " + (string)savedLicenseKeys[type.AssemblyQualifiedName]);
            return(string)savedLicenseKeys[type.AssemblyQualifiedName];
        }
        private static void CreateIniFile(string categoryName, string categoryHelp, CounterCreationDataCollection creationData, string[] languageIds) {
            //SECREVIEW: PerformanceCounterPermission must have been demanded before
            FileIOPermission permission = new FileIOPermission(PermissionState.Unrestricted);
            permission.Assert();
            try {
                StreamWriter iniWriter = new StreamWriter(IniFilePath, false, Encoding.Unicode);
                try {
                    //NT4 won't be able to parse Unicode ini files without this
                    //extra white space.
                    iniWriter.WriteLine("");
                    iniWriter.WriteLine(infoDefinition);
                    iniWriter.Write(driverNameKeyword);
                    iniWriter.Write("=");
                    iniWriter.WriteLine(categoryName);
                    iniWriter.Write(symbolFileKeyword);
                    iniWriter.Write("=");
                    iniWriter.WriteLine(Path.GetFileName(SymbolFilePath));
                    iniWriter.WriteLine("");

                    iniWriter.WriteLine(languageDefinition);
                    foreach (string languageId in languageIds) {
                        iniWriter.Write(languageId);
                        iniWriter.Write("=");
                        iniWriter.Write(languageKeyword);
                        iniWriter.WriteLine(languageId);
                    }
                    iniWriter.WriteLine("");

                    iniWriter.WriteLine(objectDefinition);
                    foreach (string languageId in languageIds) {
                        iniWriter.Write(categorySymbolPrefix);
                        iniWriter.Write("1_");
                        iniWriter.Write(languageId);
                        iniWriter.Write(nameSufix);
                        iniWriter.Write("=");
                        iniWriter.WriteLine(categoryName);
                    }
                    iniWriter.WriteLine("");

                    iniWriter.WriteLine(textDefinition);
                    foreach (string languageId in languageIds) {
                        iniWriter.Write(categorySymbolPrefix);
                        iniWriter.Write("1_");
                        iniWriter.Write(languageId);
                        iniWriter.Write(nameSufix);
                        iniWriter.Write("=");
                        iniWriter.WriteLine(categoryName);
                        iniWriter.Write(categorySymbolPrefix);
                        iniWriter.Write("1_");
                        iniWriter.Write(languageId);
                        iniWriter.Write(helpSufix);
                        iniWriter.Write("=");
                        if (categoryHelp == null || categoryHelp == String.Empty)
                            iniWriter.WriteLine(SR.GetString(SR.HelpNotAvailable));
                        else
                            iniWriter.WriteLine(categoryHelp);


                        int counterIndex = 0;
                        foreach (CounterCreationData counterData in creationData) {
                            ++counterIndex;
                            iniWriter.WriteLine("");
                            iniWriter.Write(conterSymbolPrefix);
                            iniWriter.Write(counterIndex.ToString(CultureInfo.InvariantCulture));
                            iniWriter.Write("_");
                            iniWriter.Write(languageId);
                            iniWriter.Write(nameSufix);
                            iniWriter.Write("=");
                            iniWriter.WriteLine(counterData.CounterName);

                            iniWriter.Write(conterSymbolPrefix);
                            iniWriter.Write(counterIndex.ToString(CultureInfo.InvariantCulture));
                            iniWriter.Write("_");
                            iniWriter.Write(languageId);
                            iniWriter.Write(helpSufix);
                            iniWriter.Write("=");

                            Debug.Assert(!String.IsNullOrEmpty(counterData.CounterHelp), "CounterHelp should have been fixed up by the caller");
                            iniWriter.WriteLine(counterData.CounterHelp);
                        }
                    }

                    iniWriter.WriteLine("");
                }
                finally {
                    iniWriter.Close();
                }
            }
            finally {
                FileIOPermission.RevertAssert();
            }
        }
예제 #25
0
        internal bool InitExistingStore(IsolatedStorageScope scope)
        {
            FileIOPermission fp;
            StringBuilder sb = new StringBuilder();

            sb.Append(GetRootDir(scope));

            if (IsDomain(scope))
            {
                sb.Append(this.AppName);
                sb.Append(this.SeparatorExternal);

                // For Domain Stores, accounting is done in the domain root
                this.m_InfoFile = sb.ToString() + s_InfoFile;
            }

            sb.Append(this.AssemName);
            sb.Append(this.SeparatorExternal);

            if (IsDomain(scope))
            {
                sb.Append(s_Files);
            }
            else
            {
                // For Assem Stores, accounting is done in the assem root
                this.m_InfoFile = sb.ToString() + s_InfoFile;

                sb.Append(s_AssemFiles);
            }

            sb.Append(this.SeparatorExternal);

            fp = new FileIOPermission(
                FileIOPermissionAccess.AllAccess, sb.ToString());

            fp.Assert();

            if (!Directory.Exists(sb.ToString()))
                return false;

            this.m_RootDir = sb.ToString();
            this.m_fiop = fp;

            return true;
        }
예제 #26
0
        /// <include file='doc\IsolatedStorageFileStream.uex' path='docs/doc[@for="IsolatedStorageFileStream.IsolatedStorageFileStream7"]/*' />
        public IsolatedStorageFileStream(String path, FileMode mode, 
            FileAccess access, FileShare share, int bufferSize,  
            IsolatedStorageFile isf) 
        {
            if (path == null)
                throw new ArgumentNullException("path");

            if (s_BackSlash == null)
                s_BackSlash = new String(System.IO.Path.DirectorySeparatorChar,1);

            if ((path.Length == 0) || path.Equals(s_BackSlash))
                throw new ArgumentException(
                    Environment.GetResourceString(
                        "IsolatedStorage_path"));

            ulong oldFileSize=0, newFileSize;
            bool fNewFile = false;
            FileInfo fOld;
 
            if (isf == null)
            {
                m_OwnedStore = true;
                isf = IsolatedStorageFile.GetUserStoreForDomain();
            }

            m_isf = isf;

            FileIOPermission fiop = 
                new FileIOPermission(FileIOPermissionAccess.AllAccess,
                    m_isf.RootDirectory);

            fiop.Assert();

            m_GivenPath = path;
            m_FullPath  = m_isf.GetFullPath(m_GivenPath);

            // Cache the old file size if the file size could change
            // Also find if we are going to create a new file.

            switch (mode) {
            case FileMode.CreateNew:        // Assume new file
                fNewFile = true;
                break;

            case FileMode.Create:           // Check for New file & Unreserve
            case FileMode.OpenOrCreate:     // Check for new file
            case FileMode.Truncate:         // Unreserve old file size
            case FileMode.Append:           // Check for new file

                try {
                    fOld = new FileInfo(m_FullPath);
                    oldFileSize = IsolatedStorageFile.RoundToBlockSize((ulong)fOld.Length);
                } catch (Exception e) {
                    if (e is FileNotFoundException)
                        fNewFile = true;
                }

                break;

            case FileMode.Open:             // Open existing, else exception
                break;

            default:
                throw new ArgumentException(
                    Environment.GetResourceString(
                        "IsolatedStorage_FileOpenMode"));
            }

            if (fNewFile)
                m_isf.ReserveOneBlock();

            try {
                m_fs = new 
                    FileStream(m_FullPath, mode, access, share, bufferSize, 
                        false, m_GivenPath, true);
            } catch (Exception) {

                if (fNewFile)
                    m_isf.UnreserveOneBlock();

                throw;
            }

            // make adjustment to the Reserve / Unreserve state

            if ((fNewFile == false) &&
                ((mode == FileMode.Truncate) || (mode == FileMode.Create)))
            {
                newFileSize = IsolatedStorageFile.RoundToBlockSize((ulong)m_fs.Length);
    
                if (oldFileSize > newFileSize)
                    m_isf.Unreserve(oldFileSize - newFileSize);
                else if (newFileSize > oldFileSize)     // Can this happen ?
                    m_isf.Reserve(newFileSize - oldFileSize);
            }
        }
 internal bool InitExistingStore(IsolatedStorageScope scope)
 {
     StringBuilder builder = new StringBuilder();
     this.m_StoreScope = scope;
     builder.Append(GetRootDir(scope));
     if (System.IO.IsolatedStorage.IsolatedStorage.IsApp(scope))
     {
         builder.Append(base.AppName);
         builder.Append(this.SeparatorExternal);
         this.m_InfoFile = builder.ToString() + "appinfo.dat";
         builder.Append("AppFiles");
     }
     else
     {
         if (System.IO.IsolatedStorage.IsolatedStorage.IsDomain(scope))
         {
             builder.Append(base.DomainName);
             builder.Append(this.SeparatorExternal);
             this.m_InfoFile = builder.ToString() + "info.dat";
         }
         builder.Append(base.AssemName);
         builder.Append(this.SeparatorExternal);
         if (System.IO.IsolatedStorage.IsolatedStorage.IsDomain(scope))
         {
             builder.Append("Files");
         }
         else
         {
             this.m_InfoFile = builder.ToString() + "info.dat";
             builder.Append("AssemFiles");
         }
     }
     builder.Append(this.SeparatorExternal);
     FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.AllAccess, builder.ToString());
     permission.Assert();
     if (!LongPathDirectory.Exists(builder.ToString()))
     {
         return false;
     }
     this.m_RootDir = builder.ToString();
     this.m_fiop = permission;
     if (scope == (IsolatedStorageScope.Application | IsolatedStorageScope.User))
     {
         this.UpdateQuotaFromInfoFile();
     }
     return true;
 }
예제 #28
0
        /// <summary>
        /// Loads the DataSet from its XML-serialized copy or file.
        /// </summary>
        /// <param name="dataSource">The XML-serialized copy or file path.</param>
        private DataSet GetDataSet(string dataSource)
        {
            DataSet dataSet = new DataSet();

            // is this XML or file path?
            if (dataSource.IndexOf("<") >= 0)
            {
                // XML
                StringReader reader = new StringReader(dataSource);
                dataSet.ReadXml(reader);
            }
            else
            {
                // file path
                FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Read, dataSource);
                permission.Assert();

                dataSet.ReadXml(dataSource);
            }

            return dataSet;
        }
        internal InspectionResults Inspect(PipelineComponentType componentType, string assemblyFileName, string pipelineRootDirectory)
        {
            System.Diagnostics.Contracts.Contract.Requires(assemblyFileName != null);
            System.Diagnostics.Contracts.Contract.Requires(pipelineRootDirectory != null);

            _assemblyFileName = assemblyFileName;
            _pipelineRootDirectory = pipelineRootDirectory;

            // Set up the assembly resolve event.
            _currentComponentType = componentType;
            ResolveEventHandler assemblyResolver = new ResolveEventHandler(ResolveAssembly);
            AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += assemblyResolver;

            InspectionResults retval = new InspectionResults();
            retval.Components = new List<PipelineComponent>();
            retval.Warnings = new Collection<String>();
            Type[] publicTypes;
            String assemblyName = null;

            // Need to assert again here because we are in a new appdomain
            FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.PathDiscovery |
                    FileIOPermissionAccess.Read, _pipelineRootDirectory);
            permission.Assert();

            try
            {
                // We want to load the assembly WITHOUT REGARD OF PUBLISHER POLICY.
                // If the directory structure contains v1.0 of a component and v1.1
                // exists in the GAC and is a security fix to v1.0, we still want to
                // inspect v1.0.  (The reason is we have other parts of the 
                // pipeline that were likely compiled against v1.0, not v1.1, and
                // we do type comparisons by comparing the fully qualified assembly 
                // name.)  LoadFrom unfortunately respects policy.  Assembly's
                // ReflectionOnlyLoad(byte[]) doesn't.  ReflectionOnlyLoadFrom(String)
                // does respect policy if you've set DEVPATH, but only as a bug.
                // We don't think setting DEVPATH is interesting.
                Assembly a = Assembly.ReflectionOnlyLoadFrom(_assemblyFileName);
                publicTypes = a.GetTypes();
                assemblyName = a.FullName;
            }
            catch (FileNotFoundException fnf)
            {
                retval.Warnings.Add(String.Format(CultureInfo.CurrentCulture, Res.AssemblyLoadFileNotFound, fnf.Message, fnf.FileName));
                return retval;
            }
            catch (Exception e)
            {
                retval.Warnings.Add(String.Format(CultureInfo.CurrentCulture, Res.AssemblyLoadThrew, e.GetType().Name, e.Message, _assemblyFileName));
                return retval;
            }
            PipelineComponent component = null;

            String relativeFileName = Utils.MakeRelativePath(_assemblyFileName, _pipelineRootDirectory);
            Type lastType = null;
            try
            {
                // Iterate over public types, looking for the appropriate custom attributes.
                foreach (Type type in publicTypes)
                {
                    component = null;
                    lastType = type;
                    switch (componentType)
                    {
                        case PipelineComponentType.Contract:
                            if (!Utils.HasCustomAttribute(PipelineComponent.ContractAttributeInReflectionLoaderContext, type))
                                continue;

                            component = new ContractComponent(new TypeInfo(type), relativeFileName);
                            break;

                        case PipelineComponentType.AddInAdapter:
                            if (!Utils.HasCustomAttribute(PipelineComponent.AddInAdapterAttributeInReflectionLoaderContext, type))
                                continue;

                            component = new AddInAdapter(new TypeInfo(type), relativeFileName);
                            break;

                        case PipelineComponentType.AddInBase:
                            if (Utils.HasCustomAttribute(PipelineComponent.AddInAttributeInReflectionLoaderContext, type))
                                retval.Warnings.Add(String.Format(CultureInfo.CurrentCulture, Res.AddInInAddInViewFolder, type.Name, _assemblyFileName));

                            if (!Utils.HasCustomAttribute(PipelineComponent.AddInBaseAttributeInReflectionLoaderContext, type))
                                continue;

                            TypeInfo[] activatableAs = null;
                            CustomAttributeData cad = Utils.GetCustomAttributeData(PipelineComponent.AddInBaseAttributeInReflectionLoaderContext, type);
                            foreach(CustomAttributeNamedArgument cana in cad.NamedArguments)
                            {
                                if (cana.MemberInfo.Name == "ActivatableAs")
                                {
                                    CustomAttributeTypedArgument arg = cana.TypedValue;
                                    ReadOnlyCollection<CustomAttributeTypedArgument> types = (ReadOnlyCollection<CustomAttributeTypedArgument>)arg.Value;
                                    activatableAs = new TypeInfo[types.Count];
                                    int i = 0;
                                    foreach (CustomAttributeTypedArgument subArg in types)
                                    {
                                        activatableAs[i++] = new TypeInfo((Type)subArg.Value);
                                    }
                                }
                            }

                            component = new AddInBase(new TypeInfo(type), activatableAs, relativeFileName, assemblyName);

                            break;

                        default:
                            System.Diagnostics.Contracts.Contract.Assert(false, "Fell through switch - unrecognized componentType in InspectionWorker.Inspect");
                            break;
                    }  // switch

                    // If we found a component, make sure it satisfies all of its constraints, and give our
                    // PipelineComponents a chance to initialize state.
                    if (component != null)
                    {
                        if (component.Validate(type, retval.Warnings))
                            retval.Components.Add(component);
                    }
                } // foreach type in the assembly
            } // try
            catch (FileNotFoundException fnf)
            {
                retval.Warnings.Add(String.Format(CultureInfo.CurrentCulture, Res.AssemblyLoadFileNotFound, fnf.Message, fnf.FileName));
                return retval;
            }
            catch (NotImplementedException)
            {
                retval.Warnings.Add(String.Format(CultureInfo.CurrentCulture, Res.NotImplementedFeatureBadCtorParamOrAssembly, 
                    _assemblyFileName, (lastType == null) ? "" : lastType.FullName));
                return retval;
            }
            catch (Exception e)
            {
                retval.Warnings.Add(String.Format(CultureInfo.CurrentCulture, Res.InspectingAssemblyThrew, e.GetType().Name, e.Message, _assemblyFileName));
                return retval;
            }

            AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= assemblyResolver;

            if (retval.Components.Count == 0 && _currentComponentType != PipelineComponentType.AddIn && _currentComponentType != PipelineComponentType.AddInBase)
            {
                retval.Warnings.Add(String.Format(CultureInfo.CurrentCulture, Res.NoAddInModelPartsFound, componentType, _assemblyFileName));
            }
#if ADDIN_VERBOSE_WARNINGS
            foreach (PipelineComponent c in retval.Components)
                retval.Warnings.Add(String.Format(CultureInfo.CurrentCulture, "Found a {0}.  Name: {1}  Assembly: {2}", componentType, c.SimpleName, c.AssemblySimpleName));
#endif
            return retval;
        }
        public IsolatedStorageFileStream(String path, FileMode mode, 
            FileAccess access, FileShare share, int bufferSize, 
            IsolatedStorageFile isf)
        { 
            if (path == null)
                throw new ArgumentNullException("path");
            Contract.EndContractBlock();
 
#if FEATURE_PAL
            if (s_BackSlash == null) 
                s_BackSlash = new String(System.IO.Path.DirectorySeparatorChar,1); 
#endif // FEATURE_PAL
 
            if ((path.Length == 0) || path.Equals(s_BackSlash))
                throw new ArgumentException(
                    Environment.GetResourceString(
                        "IsolatedStorage_Path")); 

            ulong oldFileSize=0, newFileSize; 
            bool fNewFile = false, fLock=false; 

            if (isf == null) 
            {
#if FEATURE_ISOSTORE_LIGHT
                throw new ArgumentNullException("isf");
#else // !FEATURE_ISOSTORE_LIGHT 
                m_OwnedStore = true;
                isf = IsolatedStorageFile.GetUserStoreForDomain(); 
#endif // !FEATURE_ISOSTORE_LIGHT 
            }
 
            if (isf.Disposed)
                throw new ObjectDisposedException(null, Environment.GetResourceString("IsolatedStorage_StoreNotOpen"));

 
            m_isf = isf;
 
            FileIOPermission fiop = 
                new FileIOPermission(FileIOPermissionAccess.AllAccess,
                    m_isf.RootDirectory); 

            fiop.Assert();
            fiop.PermitOnly();
 
            m_GivenPath = path;
            m_FullPath  = m_isf.GetFullPath(m_GivenPath); 
 
            RuntimeHelpers.PrepareConstrainedRegions();
            try { // for finally Unlocking locked store 

                // Cache the old file size if the file size could change
                // Also find if we are going to create a new file.
 
                switch (mode) {
                case FileMode.CreateNew:        // Assume new file 
#if FEATURE_ISOSTORE_LIGHT 
                    // We are going to call Reserve so we need to lock the store.
                    m_isf.Lock(ref fLock); 
#endif
                    fNewFile = true;
                    break;
 
                case FileMode.Create:           // Check for New file & Unreserve
                case FileMode.OpenOrCreate:     // Check for new file 
                case FileMode.Truncate:         // Unreserve old file size 
                case FileMode.Append:           // Check for new file
 
                    m_isf.Lock(ref fLock);      // oldFileSize needs to be
                                                // protected

                    try { 
#if FEATURE_ISOSTORE_LIGHT
                        oldFileSize = IsolatedStorageFile.RoundToBlockSize((ulong)(new FileInfo(m_FullPath).Length)); 
#else 
                        oldFileSize = IsolatedStorageFile.RoundToBlockSize((ulong)LongPathFile.GetLength(m_FullPath));
#endif 
                    } catch (FileNotFoundException) {
                        fNewFile = true;
                    } catch {
                    } 

                    break; 
 
                case FileMode.Open:             // Open existing, else exception
                    break; 

                default:
                    throw new ArgumentException(
                        Environment.GetResourceString( 
                            "IsolatedStorage_FileOpenMode"));
                } 
 
                if (fNewFile)
                    m_isf.ReserveOneBlock(); 

                try {
#if FEATURE_ISOSTORE_LIGHT
                    m_fs = new 
                        FileStream(m_FullPath, mode, access, share, bufferSize,
                            FileOptions.None, m_GivenPath, true); 
#else 
                    m_fs = new
                        FileStream(m_FullPath, mode, access, share, bufferSize, 
                            FileOptions.None, m_GivenPath, true, true);
#endif
                } catch {
 
                    if (fNewFile)
                        m_isf.UnreserveOneBlock(); 
#if FEATURE_ISOSTORE_LIGHT 
                    // IsoStore generally does not let arbitrary exceptions flow out: a
                    // IsolatedStorageException is thrown instead (see examples in IsolatedStorageFile.cs 
                    // Keeping this scoped to coreclr just because changing the exception type thrown is a
                    // breaking change and that should not be introduced into the desktop without deliberation.
                    throw new IsolatedStorageException(Environment.GetResourceString("IsolatedStorage_Operation_ISFS"));
#else 
                    throw;
#endif // FEATURE_ISOSTORE_LIGHT 
                } 

                // make adjustment to the Reserve / Unreserve state 

                if ((fNewFile == false) &&
                    ((mode == FileMode.Truncate) || (mode == FileMode.Create)))
                { 
                    newFileSize = IsolatedStorageFile.RoundToBlockSize((ulong)m_fs.Length);
 
                    if (oldFileSize > newFileSize) 
                        m_isf.Unreserve(oldFileSize - newFileSize);
                    else if (newFileSize > oldFileSize)     // Can this happen ? 
                        m_isf.Reserve(newFileSize - oldFileSize);
                }

            } finally { 
                if (fLock)
                    m_isf.Unlock(); 
            } 
            CodeAccessPermission.RevertAll();
 
        }
        private void RunButton_Click(object sender, EventArgs e)
        {
            // remove the IO permission to prevent malicious plugin code!
            FileIOPermission fp = new FileIOPermission(PermissionState.Unrestricted);
            fp.AllFiles = FileIOPermissionAccess.AllAccess;
            fp.Assert();
            //fp.Deny();

            try
            {
                Assembly asm = PluginComboBox.SelectedItem as Assembly;
                Type[] types = asm.GetTypes();

                foreach (Type t in types)
                {
                    if (t.GetInterface("IExamplePlugin") != null)
                    {
                        IExamplePlugin plugin = asm.CreateInstance(t.FullName) as IExamplePlugin;
                        MessageBox.Show(plugin.GenerateLuckyMessage());
                    }
                }

            }
            catch (SecurityException se)
            {
                MessageBox.Show("Security violation!\r\n" + se.ToString());
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.ToString());
            }
        }