Close() public method

public Close ( ) : void
return void
Ejemplo n.º 1
0
        /// <summary>
        /// 默认构造函数
        /// </summary>
        /// <param name="filepath">资源文件路径</param>
        public ResourceHelper(string filepath)
        {
            this.m_FilePath = filepath;
            this.m_Hashtable = new Hashtable();

            //如果存在
            if (File.Exists(filepath))
            {
                string tempFile = HConst.TemplatePath + "\\decryptFile.resx";

                //解密文件
                //System.Net.Security tSecurity = new Security();
                //tSecurity.DecryptDES(filepath, tempFile);
                File.Copy(filepath, tempFile);

                using (ResourceReader ResReader = new ResourceReader(tempFile))
                {
                    IDictionaryEnumerator tDictEnum = ResReader.GetEnumerator();
                    while (tDictEnum.MoveNext())
                    {
                        this.m_Hashtable.Add(tDictEnum.Key, tDictEnum.Value);
                    }

                    ResReader.Close();
                }

                //删除临时文件
                File.Delete(tempFile);
            }
        }
Ejemplo n.º 2
0
        protected override void Dispose(bool disposing)
        {
            if (Reader == null)
            {
                return;
            }

            if (disposing)
            {
                lock (Reader)
                {
                    _resCache = null;
                    if (_defaultReader != null)
                    {
                        _defaultReader.Close();
                        _defaultReader = null;
                    }
                    _caseInsensitiveTable = null;
                    // Set Reader to null to avoid a race in GetObject.
                    base.Dispose(disposing);
                }
            }
            else
            {
                // Just to make sure we always clear these fields in the future...
                _resCache             = null;
                _caseInsensitiveTable = null;
                _defaultReader        = null;
                base.Dispose(disposing);
            }
        }
Ejemplo n.º 3
0
        private void build_page_1()
        {
            TextView tv1 = new TextView ();

            try
            {
                string rez = "Adeptus.Resources.resources";
                string key = "mystring1";
                string resourceType = "";
                byte[] resourceData;
                ResourceReader r = new ResourceReader(rez);
                r.GetResourceData (key, out resourceType, out resourceData);
                r.Close();
                System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
                tv1.Buffer.Text = enc.GetString (resourceData);
            }
            catch (Exception exp)
            {
                tv1.Buffer.Text = exp.Message;
            }

            tv1.WrapMode = WrapMode.Word;
            tv1.Editable = false;

            this.AppendPage (tv1);
            this.SetPageTitle (tv1, "Introduction");
            this.SetPageType (tv1, AssistantPageType.Intro);
            this.SetPageComplete (tv1, true);
        }
		public void ConstructorString () 
		{
			if (!File.Exists(m_ResourceFile)) {
				Fail ("Resource file is not where it should be:" + Path.Combine (Directory.GetCurrentDirectory(), m_ResourceFile));
			}
			ResourceReader r = new ResourceReader(m_ResourceFile);
			AssertNotNull ("ResourceReader", r);
			r.Close();
		}
Ejemplo n.º 5
0
    public static int Main(string[] args)
    {
        System.Resources.ResourceReader res = new System.Resources.ResourceReader(args[0]);
        string type = "";

        Byte[] value = null;
        res.GetResourceData(args[1], out type, out value);
        using (System.IO.Stream stdout = Console.OpenStandardOutput())
        {
            stdout.Write(value, 4, value.Length - 4);
        }
        res.Close();
        return(0);
    }
Ejemplo n.º 6
0
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         lock (this) {
             _table = null;
             if (_defaultReader != null)
             {
                 _defaultReader.Close();
                 _defaultReader = null;
             }
             _caseInsensitiveTable = null;
         }
     }
     // Just to make sure we always clear these fields in the future...
     _table = null;
     _caseInsensitiveTable = null;
     _defaultReader        = null;
     base.Dispose(disposing);
 }
Ejemplo n.º 7
0
 private static System.Collections.Hashtable Load(string[] fielNames)
 {
     System.Collections.Hashtable hashtable = new System.Collections.Hashtable();
     for (int i = 0; i < fielNames.Length; i++)
     {
         string text = fielNames[i];
         if (System.IO.File.Exists(text))
         {
             System.Resources.ResourceReader resourceReader = new System.Resources.ResourceReader(text);
             foreach (System.Collections.DictionaryEntry dictionaryEntry in resourceReader)
             {
                 if (!hashtable.ContainsKey(dictionaryEntry.Key))
                 {
                     hashtable.Add(dictionaryEntry.Key, dictionaryEntry.Value);
                 }
             }
             resourceReader.Close();
         }
     }
     return(hashtable);
 }
Ejemplo n.º 8
0
        /// <summary>
        /// 从resource文件还原resx文件
        /// </summary>
        /// <param name="strPath">文件路径</param>
        /// <param name="strCsProj">csproj内容</param>
        private void RestoreResXFromResource(string strPath, ref string strCsProj)
        {
            string[] files = Directory.GetFiles(strPath, "*.resources");//查询文件
            for (int i = 0; i < (int)files.Length; i++)
            {
                string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(files[i].Substring(selectPath.Length));
                //取文件名去掉扩展名
                string strResxFile = Path.Combine(strPath, string.Concat(string.Join("\\", fileNameWithoutExtension.Split(new char[] { '.' })), ".resx"));
                //resx文件路径
                ResourceReader resourceReaders = new ResourceReader(files[i]);  //读取资源文件
                ResXResourceWriter resXResourceWriter = new ResXResourceWriter(strResxFile); //打开resx文件
                foreach (DictionaryEntry resourceReader in resourceReaders)
                {//从resource文件中读取资源写入resx文件
                    try
                    {
                        resXResourceWriter.AddResource(resourceReader.Key.ToString(), resourceReader.Value);
                    }
                    catch (Exception ex)
                    {
                        UpdateMsg(resourceReader.Key.ToString() + "\r\n" + ex.ToString());
                    }
                }
                resXResourceWriter.Close();
                resourceReaders.Close();
                UpdateMsg(strResxFile.Substring(selectPath.Length));//resx文件更新消息
                if (strCsProj != null)
                {//更新csproj
                    string strResXName = strResxFile.Substring(selectPath.Length);
                    //resx文件名
                    if (!strCsProj.Contains(string.Concat("=\"", strResXName, "\"")))
                    {//csproj中不包含则添加
                        int num = strCsProj.LastIndexOf("</ItemGroup>");//最后位置
                        if (num <= 0)
                        {//适应低版本
                            num = strCsProj.LastIndexOf("=\"EmbeddedResource\"");
                            strCsProj = string.Concat(strCsProj.Substring(0, num)
                                , "=\"EmbeddedResource\" />\r\n\t\t<File RelPath=\""
                                , strResXName
                                , "\" DependentUpon=\""
                                , Path.GetFileNameWithoutExtension(strResXName)
                                ,".cs\" BuildAction"
                                , strCsProj.Substring(num));
                        }
                        else
                        {
                            strCsProj = string.Concat(strCsProj.Substring(0, num)
                                , " <EmbeddedResource Include=\""
                                , strResXName
                                , "\">\r\n\t<SubType>Designer</SubType>\r\n\t<DependentUpon>"
                                , Path.GetFileNameWithoutExtension(strResXName)
                                , ".cs</DependentUpon>\r\n\t</EmbeddedResource>"
                                , strCsProj.Substring(num));
                            //插入resx文件引用

                            strCsProj = strCsProj.Replace(string.Concat("<EmbeddedResource Include=\""
                                , Path.GetFileName(files[i])
                                , "\" />")
                                , "");//删除resources文件引用
                        }
                    }
                }
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Generates localized Baml from translations
        /// </summary>
        /// <param name="options">LocBaml options</param>
        /// <param name="dictionaries">the translation dictionaries</param>
        internal static void Generate(LocBamlOptions options, TranslationDictionariesReader dictionaries)
        {
            // base on the input, we generate differently
            switch(options.InputType)
            {
                case FileType.BAML :
                {
                    // input file name
                    string bamlName = Path.GetFileName(options.Input);

                    // outpuf file name is Output dir + input file name
                    string outputFileName = GetOutputFileName(options);

                    // construct the full path
                    string fullPathOutput = Path.Combine(options.Output, outputFileName);

                    options.Write(StringLoader.Get("GenerateBaml", fullPathOutput));

                    using (Stream input = File.OpenRead(options.Input))
                    {
                        using (Stream output = new FileStream(fullPathOutput, FileMode.Create))
                        {
                            BamlLocalizationDictionary dictionary = dictionaries[bamlName];

                            // if it is null, just create an empty dictionary.
                            if (dictionary == null)
                                dictionary = new BamlLocalizationDictionary();

                            GenerateBamlStream(input, output, dictionary, options);
                        }
                    }

                    options.WriteLine(StringLoader.Get("Done"));
                    break;
                }
                case FileType.RESOURCES :
                {
                    string outputFileName = GetOutputFileName(options);
                    string fullPathOutput = Path.Combine(options.Output, outputFileName);

                    using (Stream input = File.OpenRead(options.Input))
                    {
                        using (Stream output = File.OpenWrite(fullPathOutput))
                        {
                            // create a Resource reader on the input;
                            IResourceReader reader = new ResourceReader(input);

                            // create a writer on the output;
                            IResourceWriter writer = new ResourceWriter(output);

                            GenerateResourceStream(
                                options,         // options
                                options.Input,   // resources name
                                reader,          // resource reader
                                writer,          // resource writer
                                dictionaries);   // translations

                            reader.Close();

                            // now generate and close
                            writer.Generate();
                            writer.Close();
                        }
                    }

                    options.WriteLine(StringLoader.Get("DoneGeneratingResource", outputFileName));
                    break;
                }
            case FileType.EXE:
                case FileType.DLL:
                {
                    GenerateAssembly(options, dictionaries);
                    break;
                }
                default:
                {
                    Debug.Assert(false, "Can't generate to this type");
                    break;
                }
            }
        }
Ejemplo n.º 10
0
        /// <summary> Creates a new <code>DatabaseType</code>.
        /// 
        /// </summary>
        /// <param name="databaseType">the type of database
        /// </param>
        public DatabaseType(System.String databaseType)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            string resourceName = string.Format("AutopatchNet.{0}.resources", databaseType.ToLower());
            System.IO.Stream rs = assembly.GetManifestResourceStream(resourceName);
            if (rs == null)
            {
                throw new System.ArgumentException("Could not find SQL resources file for database '" + databaseType + "'; make sure that there is a '" + databaseType.ToLower() + ".resources' file in package.");
            }
            try
            {
                ResourceReader reader = new ResourceReader(rs);
                IDictionaryEnumerator en = reader.GetEnumerator();
                while(en.MoveNext())
                {
                    string sqlkey = (string)en.Key;
                    string sql = (string)en.Value;
                    properties.Add(sqlkey, sql);
                }

                reader.Close();
            }
            catch (System.IO.IOException e)
            {
                throw new System.ArgumentException("Could not read SQL resources file for database '" + databaseType + "'.", e);
            }
            finally
            {
                rs.Close();
            }

            this.databaseType = databaseType;
        }
Ejemplo n.º 11
0
        public bool Fill(string attemptMessage, string successMessage)
        {
            WriteLog(attemptMessage);

            if (!System.IO.File.Exists(property.FullFilePath))
            {
                WriteLog(string.Format("There is no Resource file for {0}..."), EventLogEntryType.Error);
                return false;
            }

            ResourceReader reader = new ResourceReader(property.FullFilePath);
            IDictionaryEnumerator enumerator = reader.GetEnumerator();

            while (enumerator.MoveNext())
            {
                string key = enumerator.Key.ToString();
                string value = string.IsNullOrEmpty(enumerator.Value as string) ? string.Empty : enumerator.Value as string;

                if (properties.ContainsKey(key)) properties[key] = value;
                else properties.Add(enumerator.Key.ToString(), value);
            }

            reader.Close();

            WriteLog(successMessage);

            return true;
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Loads all files specified in the passed resource.resx, creates two lists (names and schemes) and then injects them into the master lists
        /// This injections help get rid of manually specifying where to put new elements, the list just grows.
        /// </summary>
        /// <param name="embeddedResourceFullName">Full path to the embedded assembly resource file containing the schemes</param>
        private void addPresetGroup(string embeddedResourceFullName)
        {
            ResourceReader resourceReader = new ResourceReader(assembly.GetManifestResourceStream(embeddedResourceFullName));
            IDictionaryEnumerator resourceEnumerator = resourceReader.GetEnumerator();

            List<string> presetNamesToAdd = new List<string>();
            List<byte[]> presetsToAdd = new List<byte[]>();

            while (resourceEnumerator.MoveNext())
            {
                presetNamesToAdd.Add((string)resourceEnumerator.Key);
                presetsToAdd.Add((byte[])resourceEnumerator.Value);
            }

            // Inject the newly formed lists into the master lists
            presets.Add(new List<byte[]>(presetsToAdd));
            presetNames.Add(new List<string>(presetNamesToAdd));
            resourceReader.Close();
        }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            if(args.Length !=1)
            {
                Console.Write("[-] Error\nnetZunpacker.exe packedfile.exe\nPress Enter to Exit");
                Console.Read();
                return;
            }
            try
            {
                String path;

                if (!Path.IsPathRooted(args[0]))
                {
                    path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\" + args[0];
                }
                else
                {
                    path = args[0];
                }
                Assembly a = Assembly.LoadFile(path);
                ResourceManager rm = new ResourceManager("app", a);

                String[] resourceNames = a.GetManifestResourceNames();
                int p;
                foreach (string resName in resourceNames)
                {
                    Stream resStream = a.GetManifestResourceStream(resName);
                    var rr = new ResourceReader(resStream);
                    IDictionaryEnumerator dict = rr.GetEnumerator();
                    int ctr = 0;
                    while (dict.MoveNext())
                    {
                        ctr++;
                        //Console.WriteLine("\n{0:00}: {1} = {2}", ctr, dict.Key, dict.Value);
                        if (((byte[])rm.GetObject(dict.Key.ToString()))[0] == 120)
                        {
                            Decoder((byte[])rm.GetObject(dict.Key.ToString()), dict.Key.ToString());
                        }
                    }

                    rr.Close();

                }
            }
            catch(Exception e)
            {
                String s = e.Message;
                Console.Write(s);
            }
        }
Ejemplo n.º 14
0
 private static Hashtable Load(string fileName)
 {
     if (File.Exists(fileName))
     {
         Hashtable hashtable = new Hashtable();
         ResourceReader reader = new ResourceReader(fileName);
         foreach (DictionaryEntry entry in reader)
         {
             hashtable.Add(entry.Key, entry.Value);
         }
         reader.Close();
         return hashtable;
     }
     return null;
 }
Ejemplo n.º 15
0
        // Retrieve key=>values from DLL ressource file
        private static Hashtable GetRessources(Assembly pluginAssembly)
        {
            string[] names = pluginAssembly.GetManifestResourceNames();
            Hashtable ressources = new Hashtable();
            foreach (string name in names)
            {
                if (name.EndsWith(".resources"))
                {
                    ResourceReader reader = null;

                    reader = new ResourceReader(pluginAssembly.GetManifestResourceStream(name));
                    IDictionaryEnumerator en = reader.GetEnumerator();

                    while (en.MoveNext())
                    {
                        // add key and value for plugin
                        ressources.Add(en.Key, en.Value);
                        //Console.WriteLine(en.Key + " => " + en.Value);
                    }
                    reader.Close();
                }
            }
            return ressources;
        }
Ejemplo n.º 16
0
		public void Close ()
		{
			Stream stream = new FileStream (m_ResourceFile, FileMode.Open);
			ResourceReader r = new ResourceReader (stream);
			r.Close ();

			stream = new FileStream (m_ResourceFile, FileMode.Open);
			Assert.IsNotNull (stream, "FileStream");
			stream.Close ();
		}
		private int WriteResource(IResource resource)
		{
			IEmbeddedResource embeddedResource = resource as IEmbeddedResource;
			if (embeddedResource != null)
			{
				try 
				{
					byte[] buffer = embeddedResource.Value;
                    string fileName = Path.Combine(_outputDirectory, GetResourceFileName(resource));
					
					if (resource.Name.EndsWith(".resources"))
					{
						fileName = Path.ChangeExtension(fileName, ".resx");
						using (MemoryStream ms = new MemoryStream(embeddedResource.Value))
						{
							ResXResourceWriter resxw = new ResXResourceWriter(fileName);
							IResourceReader reader = new ResourceReader(ms);
							IDictionaryEnumerator en = reader.GetEnumerator();
							while (en.MoveNext()) 
							{
                                bool handled = false;
                                
                                if (en.Value != null)
                                {
                                    Type type = en.Value.GetType();
                                    if (type.FullName.EndsWith("Stream"))
                                    {
                                        Stream s = en.Value as Stream;
                                        if (s != null)
                                        {
                                            byte[] bytes = new byte[s.Length];
                                            if (s.CanSeek) s.Seek(0, SeekOrigin.Begin);
                                            s.Read(bytes, 0, bytes.Length);
                                            resxw.AddResource(en.Key.ToString(), new MemoryStream(bytes));
                                            handled = true;
                                        }
                                    }
                                }
                                if (handled) continue;

								resxw.AddResource(en.Key.ToString(), en.Value);
							}
							reader.Close();
							resxw.Close();
						}
					}
					else // other embedded resource
					{
						if (buffer != null)
						{
							using (Stream stream = File.Create(fileName))
							{
								stream.Write(buffer, 0, buffer.Length);
							}
						}
					}
					AddToProjectFiles(fileName);
					return 0;
				}
				catch (Exception ex)
				{
					WriteLine("Error in " + resource.Name + " : " + ex.Message);
				}
			}

			return WriteOtherResource(resource);
		}
Ejemplo n.º 18
0
		public void AddResource_Stream_Default ()
		{
			MemoryStream stream = new MemoryStream ();
			byte [] buff = Encoding.Unicode.GetBytes ("Miguel");
			stream.Write (buff, 0, buff.Length);
			stream.Position = 0;

			ResourceWriter rw = new ResourceWriter ("Test/resources/AddResource_Stream.resources");
			rw.AddResource ("Name", (object)stream);
			rw.Close ();

			ResourceReader rr = new ResourceReader ("Test/resources/AddResource_Stream.resources");
			IDictionaryEnumerator enumerator = rr.GetEnumerator ();

			// Get the first element
			Assert.AreEqual (true, enumerator.MoveNext (), "#A0");

			DictionaryEntry de = enumerator.Entry;
			Assert.AreEqual ("Name", enumerator.Key, "#A1");
			Stream result_stream = de.Value as Stream;
			Assert.AreEqual (true, result_stream != null, "#A2");

			// Get the data and compare
			byte [] result_buff = new byte [result_stream.Length];
			result_stream.Read (result_buff, 0, result_buff.Length);
			string string_res = Encoding.Unicode.GetString (result_buff);
			Assert.AreEqual ("Miguel", string_res, "#A3");

			rr.Close ();
			stream.Close ();
		}
		public void Stream ()
		{
			Stream stream = new FileStream (m_ResourceFile, FileMode.Open);
			ResourceReader r = new ResourceReader (stream);
			AssertNotNull ("ResourceReader", r);
			r.Close();
		}
Ejemplo n.º 20
0
		/// <summary>
		/// Bietet Zugriff auf die Resourcen in einem Updatepaket.
		/// </summary>
		/// <param name="packagePath">Der Pfad zu dem Updatepaket.</param>
		/// <param name="resID">Die ID der Resource die ausgelesen werden soll.</param>
		/// <returns>Gibt die Resource in Form eines ByteArrays zurück.</returns>
		protected byte[] accessUpdatePackage(string packagePath, string resID) {
			var resReader = new ResourceReader(packagePath);
			try {
				byte[] outData;
				string outType;
				resReader.GetResourceData(resID, out outType, out outData);
				return outData;
			}
			finally {
				resReader.Close();
			}
		}
Ejemplo n.º 21
0
      protected override bool DoCompile(){
        if (!this.isClosed && !this.isEngineCompiled){
          this.SetUpCompilerEnvironment();
          if (this.PEFileName == null){
            // we use random default names to avoid overwriting cached assembly files when debugging VSA
            this.PEFileName = this.GenerateRandomPEFileName();
          }
          this.SaveSourceForDebugging();  // Save sources needed for debugging (does nothing if no debug info)
          this.numberOfErrors = 0;        // Records number of errors during compilation.
          this.isEngineCompiled = true;         // OnCompilerError sets to false if it encounters an unrecoverable error.
          Globals.ScopeStack.Push(this.GetGlobalScope().GetObject());
          try{
            try{
              foreach (Object item in this.vsaItems){
                Debug.Assert(item is VsaReference || item is VsaStaticCode || item is VsaHostObject);
                if (item is VsaReference)
                  ((VsaReference)item).Compile(); //Load the assembly into memory.
              }
              if (this.vsaItems.Count > 0)
                this.SetEnclosingContext(new WrappedNamespace("", this)); //Provide a way to find types that are not inside of a name space
              // Add VSA global items to the global scope
              foreach (Object item in this.vsaItems){
                if (item is VsaHostObject)
                  ((VsaHostObject)item).Compile();
              }
              foreach (Object item in this.vsaItems){
                if (item is VsaStaticCode)
                  ((VsaStaticCode)item).Parse();
              }
              foreach (Object item in this.vsaItems){
                if (item is VsaStaticCode)
                  ((VsaStaticCode)item).ProcessAssemblyAttributeLists();
              }
              foreach (Object item in this.vsaItems){
                if (item is VsaStaticCode)
                  ((VsaStaticCode)item).PartiallyEvaluate();
              }
              foreach (Object item in this.vsaItems){
                if (item is VsaStaticCode)
                  ((VsaStaticCode)item).TranslateToIL();
              }
              foreach (Object item in this.vsaItems){
                if (item is VsaStaticCode)
                  ((VsaStaticCode)item).GetCompiledType();
              }
              if (null != this.globalScope)
                this.globalScope.Compile(); //In case the host added items to the global scope
            }catch(JScriptException se){
              // It's a bit strange because we may be capturing an exception 
              // thrown by VsaEngine.OnCompilerError (in the case where 
              // this.engineSite is null. This is fine though. All we end up doing
              // is capturing and then rethrowing the same error.
              this.OnCompilerError(se);
            }catch(System.IO.FileLoadException e){
              JScriptException se = new JScriptException(JSError.ImplicitlyReferencedAssemblyNotFound);
              se.value = e.FileName;
              this.OnCompilerError(se);
              this.isEngineCompiled = false;
            }catch(EndOfFile){
              // an error was reported during PartiallyEvaluate and the host decided to abort
              // swallow the exception and keep going
            }catch(Exception){
              // internal compiler error -- make sure we don't claim to have compiled, then rethrow
              this.isEngineCompiled = false;
              throw;
            }
          }finally{
            Globals.ScopeStack.Pop();
          }
          if (this.isEngineCompiled){
            // there were no unrecoverable errors, but we want to return true only if there is IL
            this.isEngineCompiled = (this.numberOfErrors == 0 || this.alwaysGenerateIL);
          }
        }

        if (this.managedResources != null){
          foreach (ResInfo managedResource in this.managedResources){
            if (managedResource.isLinked){
              this.CompilerGlobals.assemblyBuilder.AddResourceFile(managedResource.name,
                                                              Path.GetFileName(managedResource.filename),
                                                              managedResource.isPublic?
                                                              ResourceAttributes.Public:
                                                              ResourceAttributes.Private);
            }else{
              ResourceReader reader = null;
              try{
                reader = new ResourceReader(managedResource.filename);
              }catch(System.ArgumentException){
                JScriptException se = new JScriptException(JSError.InvalidResource);
                se.value = managedResource.filename;
                this.OnCompilerError(se);
                this.isEngineCompiled = false;
                return false;
              }
              IResourceWriter writer = this.CompilerGlobals.module.DefineResource(managedResource.name,
                                                                                  managedResource.filename,
                                                                                  managedResource.isPublic?
                                                                                  ResourceAttributes.Public:
                                                                                  ResourceAttributes.Private);
              foreach (DictionaryEntry resource in reader)
                writer.AddResource((string)resource.Key, resource.Value);
              reader.Close();
            }
          }
        }

        if (this.isEngineCompiled)
          this.EmitReferences();

        // Save things out to a local PE file when doSaveAfterCompile is set; this is set when an
        // output name is given (allows JSC to avoid IVsaEngine.SaveCompiledState).  The proper
        // values for VSA are doSaveAfterCompile == false and genStartupClass == true.  We allow
        // genStartupClass to be false for scenarios like JSTest and the Debugger
        if (this.isEngineCompiled){
          if (this.doSaveAfterCompile){
            if (this.PEFileKind != PEFileKinds.Dll)
              this.CreateMain();
            try {
              // After executing this code path, it is an error to call SaveCompiledState (until the engine is recompiled)
              compilerGlobals.assemblyBuilder.Save(Path.GetFileName(this.PEFileName));
            }catch(Exception e){
              throw new VsaException(VsaError.SaveCompiledStateFailed, e.Message, e);
            }
          }else if (this.genStartupClass){
            // this is generated for VSA hosting
            this.CreateStartupClass();
          }
        }
        return this.isEngineCompiled;
      }
Ejemplo n.º 22
0
		public void GetResourceData2 ()
		{
			byte [] expected = new byte [] {
				0x00, 0x01, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF,
				0xFF, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
				0x00, 0x0C, 0x02, 0x00, 0x00, 0x00, 0x51, 0x53,
				0x79, 0x73, 0x74, 0x65, 0x6D, 0x2E, 0x44, 0x72,
				0x61, 0x77, 0x69, 0x6E, 0x67, 0x2C, 0x20, 0x56,
				0x65, 0x72, 0x73, 0x69, 0x6F, 0x6E, 0x3D, 0x32,
				0x2E, 0x30, 0x2E, 0x30, 0x2E, 0x30, 0x2C, 0x20,
				0x43, 0x75, 0x6C, 0x74, 0x75, 0x72, 0x65, 0x3D,
				0x6E, 0x65, 0x75, 0x74, 0x72, 0x61, 0x6C, 0x2C,
				0x20, 0x50, 0x75, 0x62, 0x6C, 0x69, 0x63, 0x4B,
				0x65, 0x79, 0x54, 0x6F, 0x6B, 0x65, 0x6E, 0x3D,
				0x62, 0x30, 0x33, 0x66, 0x35, 0x66, 0x37, 0x66,
				0x31, 0x31, 0x64, 0x35, 0x30, 0x61, 0x33, 0x61,
				0x05, 0x01, 0x00, 0x00, 0x00, 0x13, 0x53, 0x79,
				0x73, 0x74, 0x65, 0x6D, 0x2E, 0x44, 0x72, 0x61,
				0x77, 0x69, 0x6E, 0x67, 0x2E, 0x53, 0x69, 0x7A,
				0x65, 0x02, 0x00, 0x00, 0x00, 0x05, 0x77, 0x69,
				0x64, 0x74, 0x68, 0x06, 0x68, 0x65, 0x69, 0x67,
				0x68, 0x74, 0x00, 0x00, 0x08, 0x08, 0x02, 0x00,
				0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10, 0x00,
				0x00, 0x00, 0x0B};
			ResourceReader r = new ResourceReader ("Test/resources/bug81759.resources");
			string type;
			byte [] bytes;
			r.GetResourceData ("imageList.ImageSize", out type, out bytes);
			// Note that const should not be used here.
			Assert.AreEqual ("System.Drawing.Size, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", type, "#1");
			Assert.AreEqual (expected, bytes, "#2");
			r.Close ();
		}
Ejemplo n.º 23
0
		public void LoadFile(FileName filename, Stream stream)
		{
			resources.Clear();
			metadata.Clear();
			switch (Path.GetExtension(filename).ToLowerInvariant()) {
				case ".resx":
					ResXResourceReader rx = new ResXResourceReader(stream);
					ITypeResolutionService typeResolver = null;
					rx.BasePath = Path.GetDirectoryName(filename);
					rx.UseResXDataNodes = true;
					IDictionaryEnumerator n = rx.GetEnumerator();
					while (n.MoveNext()) {
						if (!resources.ContainsKey(n.Key.ToString())) {
							ResXDataNode node = (ResXDataNode)n.Value;
							resources.Add(n.Key.ToString(), new ResourceItem(node.Name, node.GetValue(typeResolver), node.Comment));
						}
					}
					
					n = rx.GetMetadataEnumerator();
					while (n.MoveNext()) {
						if (!metadata.ContainsKey(n.Key.ToString())) {
							ResXDataNode node = (ResXDataNode)n.Value;
							metadata.Add(n.Key.ToString(), new ResourceItem(node.Name, node.GetValue(typeResolver)));
						}
					}
					
					rx.Close();
					break;
				case ".resources":
					ResourceReader rr=null;
					try {
						rr = new ResourceReader(stream);
						foreach (DictionaryEntry entry in rr) {
							if (!resources.ContainsKey(entry.Key.ToString()))
								resources.Add(entry.Key.ToString(), new ResourceItem(entry.Key.ToString(), entry.Value));
						}
					}
					finally {
						if (rr != null) {
							rr.Close();
						}
					}
					break;
			}
			InitializeListView();
		}
        private int WriteResource(IResource resource)
        {
            IEmbeddedResource embeddedResource = resource as IEmbeddedResource;
            if (embeddedResource != null)
            {
                try
                {
                    byte[] buffer = embeddedResource.Value;
                    string fileName = Path.Combine(_outputDirectory, resource.Name);

                    if (resource.Name.EndsWith(".resources"))
                    {
                        fileName = Path.ChangeExtension(fileName, ".resx");
                        using (MemoryStream ms = new MemoryStream(embeddedResource.Value))
                        {
                            ResXResourceWriter resxw = new ResXResourceWriter(fileName);
                            IResourceReader reader = new ResourceReader(ms);
                            IDictionaryEnumerator en = reader.GetEnumerator();
                            while (en.MoveNext())
                            {
                                resxw.AddResource(en.Key.ToString(), en.Value);
                            }
                            reader.Close();
                            resxw.Close();
                        }
                    }
                    else // other embedded resource
                    {
                        if (buffer != null)
                        {
                            using (Stream stream = File.Create(fileName))
                            {
                                stream.Write(buffer, 0, buffer.Length);
                            }
                        }
                    }
                    AddToProjectFiles(fileName);
                    return 0;
                }
                catch (Exception ex)
                {
                    WriteLine("Error in " + resource.Name + " : " + ex.Message);
                }
            }

            return WriteOtherResource(resource);
        }
Ejemplo n.º 25
0
		public void GetResourceDataNullName ()
		{
			ResourceReader r = new ResourceReader ("Test/resources/StreamTest.resources");
			string type;
			byte [] bytes;

			try {
				r.GetResourceData (null, out type, out bytes);
				Assert.Fail ("#1");
			} catch (ArgumentNullException ex) {
				Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
				Assert.IsNull (ex.InnerException, "#3");
				Assert.IsNotNull (ex.Message, "#4");
				Assert.IsNotNull (ex.ParamName, "#5");
				Assert.AreEqual ("resourceName", ex.ParamName, "#6");
			} finally {
				r.Close ();
			}
		}
Ejemplo n.º 26
0
		public void AddResource_Stream_Details ()
		{
			MemoryStream ms = new MemoryStream ();
			ResourceWriter rw = new ResourceWriter (ms);

			ResourceStream stream = new ResourceStream ("MonoTest");

			// Set Position so we can test the ResourceWriter is resetting
			// it to 0 when generating.
			stream.Position = 2;
			rw.AddResource ("Name", stream);
			rw.Generate ();

			ms.Position = 0;
			ResourceReader rr = new ResourceReader (ms);
			string value = GetStringFromResource (rr, "Name");
			Assert.AreEqual ("MonoTest", value, "#A1");
			Assert.AreEqual (false, stream.IsDiposed, "#A2");

			// Test the second overload
			stream.Reset ();
			ms = new MemoryStream ();
			rw = new ResourceWriter (ms);
			rw.AddResource ("Name", stream, true);
			rw.Generate ();

			ms.Position = 0;
			rr = new ResourceReader (ms);
			value = GetStringFromResource (rr, "Name");
			Assert.AreEqual ("MonoTest", value, "#B1");
			Assert.AreEqual (true, stream.IsDiposed, "#B2");

			rr.Close ();
			rw.Close ();
			stream.Close ();
		}
Ejemplo n.º 27
0
		public void Enumerator ()
		{
			Stream stream = new FileStream (m_ResourceFile, FileMode.Open);
			ResourceReader reader = new ResourceReader (stream);

			IDictionaryEnumerator en = reader.GetEnumerator ();
			// Goes through the enumerator, printing out the key and value pairs.
			while (en.MoveNext ()) {
				DictionaryEntry de = (DictionaryEntry) en.Current;
				Assert.IsTrue (String.Empty != (string) de.Key, "Current.Key should not be empty");
				Assert.IsTrue (String.Empty != (string) de.Value, "Current.Value should not be empty");
				Assert.IsTrue (String.Empty != (string) en.Key, "Entry.Key should not be empty");
				Assert.IsTrue (String.Empty != (string) en.Value, "Entry.Value should not be empty");
			}
			reader.Close ();
		}
        private bool InitResourceGridRows(EmbeddedResource er)
        {
            ResourceReader rr;
            try
            {
                rr = new ResourceReader(er.GetResourceStream());
            }
            catch
            {
                rr = null;
            }

            if (rr == null)
                return false;

            DataRow dr;
            IDictionaryEnumerator de = rr.GetEnumerator();
            int count = 0;
            while (de.MoveNext())
            {
                dr = _dtResource.NewRow();
                string name = de.Key as string;
                dr["no"] = count.ToString();
                count++;
                dr["name"] = name;
                object value = de.Value;
                dr["type"] = value == null ? null : value.GetType().FullName;
                try
                {
                    DataGridViewTextAndImageCellValue cv = new DataGridViewTextAndImageCellValue(name, value);
                    cv.Image = ConvertToImage(name, value);
                    dr["value"] = cv;
                }
                catch //(Exception ex)
                {
                    dr["value"] = new DataGridViewTextAndImageCellValue(String.Empty, value);
                    //dr["value"] = new DataGridViewTextAndImageCellValue(String.Empty, String.Format("Error: {0}", ex.Message));
                    //dr["type"] = "System.String";
                }
                _dtResource.Rows.Add(dr);
            }

            rr.Close();
            return true;
        }
Ejemplo n.º 29
0
		public void GetResourceData ()
		{
			byte [] t1 = new byte [] {0x16, 0x00, 0x00, 0x00, 0x76, 0x65, 0x72, 0x69, 0x74, 0x61, 0x73, 0x20, 0x76, 0x6F, 0x73, 0x20, 0x6C, 0x69, 0x62, 0x65, 0x72, 0x61, 0x62, 0x69, 0x74, 0x0A};
			byte [] t2 = new byte [] {0x0A, 0x73, 0x6F, 0x6D, 0x65, 0x73, 0x74, 0x72, 0x69, 0x6E, 0x67};
			byte [] t3 = new byte [] {0x0E, 0x00, 0x00, 0x00, 0x73, 0x68, 0x61, 0x72, 0x64, 0x65, 0x6E, 0x66, 0x72, 0x65, 0x75, 0x64, 0x65, 0x0A};

			ResourceReader r = new ResourceReader ("Test/resources/StreamTest.resources");
			Hashtable items = new Hashtable ();
			foreach (DictionaryEntry de in r) {
				string type;
				byte [] bytes;
				r.GetResourceData ((string) de.Key, out type, out bytes);
				items [de.Key] = new DictionaryEntry (type, bytes);
			}

			DictionaryEntry p = (DictionaryEntry) items ["test"];
			Assert.AreEqual ("ResourceTypeCode.Stream", p.Key as string, "#1-1");
			Assert.AreEqual (t1, p.Value as byte [], "#1-2");

			p = (DictionaryEntry) items ["test2"];
			Assert.AreEqual ("ResourceTypeCode.String", p.Key as string, "#2-1");
			Assert.AreEqual (t2, p.Value as byte [], "#2-2");

			p = (DictionaryEntry) items ["test3"];
			Assert.AreEqual ("ResourceTypeCode.ByteArray", p.Key as string, "#3-1");
			Assert.AreEqual (t3, p.Value as byte [], "#3-2");

			r.Close ();
		}
        public EmbeddedResource RemoveResource(EmbeddedResource er, string[] keys)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;

                var rr = new ResourceReader(er.GetResourceStream());
                var ms = new MemoryStream();
                var rw = new ResourceWriter(ms);

                var de = rr.GetEnumerator();
                while (de.MoveNext())
                {
                    string deKey = de.Key as string;
                    bool toBeDeleted = false;
                    foreach (string key in keys)
                    {
                        if (key == deKey)
                        {
                            toBeDeleted = true;
                            break;
                        }
                    }
                    if (toBeDeleted) continue;
                    rw.AddResource(deKey, de.Value);
                }

                rw.Generate();
                rw.Close();
                rr.Close();
                var newEr = new EmbeddedResource(er.Name, er.Attributes, ms.ToArray());
                ms.Close();
                return newEr;
            }
            catch
            {
                throw;
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
Ejemplo n.º 31
0
		Hashtable Load(string fileName)
		{
			if (File.Exists(fileName)) {
				Hashtable resources = new Hashtable();
				ResourceReader rr = new ResourceReader(fileName);
				foreach (DictionaryEntry entry in rr) {
					resources.Add(entry.Key, entry.Value);
				}
				rr.Close();
				return resources;
			}
			return null;
		}
        public EmbeddedResource ReplaceResource(EmbeddedResource er, string key, byte[] data)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;

                var rr = new ResourceReader(er.GetResourceStream());
                var ms = new MemoryStream();
                var rw = new ResourceWriter(ms);

                var de = rr.GetEnumerator();
                while (de.MoveNext())
                {
                    string deKey = de.Key as string;
                    if (key == deKey)
                    {
                        object o = RestoreResourceObject(key, de.Value.GetType().FullName, data);
                        rw.AddResource(key, o);
                    }
                    else
                    {
                        rw.AddResource(deKey, de.Value);
                    }
                }

                rw.Generate();
                rw.Close();
                rr.Close();
                var newEr = new EmbeddedResource(er.Name, er.Attributes, ms.ToArray());
                ms.Close();
                return newEr;
            }
            catch
            {
                throw;
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
Ejemplo n.º 33
0
		public void LoadFile(string filename, Stream stream)
		{
			resources.Clear();
			metadata.Clear();
			switch (Path.GetExtension(filename).ToLowerInvariant()) {
				case ".resx":
					ResXResourceReader rx = new ResXResourceReader(stream);
					rx.BasePath = Path.GetDirectoryName(filename);
					IDictionaryEnumerator n = rx.GetEnumerator();
					while (n.MoveNext())
						if (!resources.ContainsKey(n.Key.ToString()))
						resources.Add(n.Key.ToString(), new ResourceItem(n.Key.ToString(), n.Value));
					
					n = rx.GetMetadataEnumerator();
					while (n.MoveNext())
						if (!metadata.ContainsKey(n.Key.ToString()))
						metadata.Add(n.Key.ToString(), new ResourceItem(n.Key.ToString(), n.Value));
					
					rx.Close();
					break;
				case ".resources":
					ResourceReader rr=null;
					try {
						rr = new ResourceReader(stream);
						foreach (DictionaryEntry entry in rr) {
							if (!resources.ContainsKey(entry.Key.ToString()))
								resources.Add(entry.Key.ToString(), new ResourceItem(entry.Key.ToString(), entry.Value));
						}
					}
					finally {
						if (rr != null) {
							rr.Close();
						}
					}
					break;
			}
			InitializeListView();
		}
Ejemplo n.º 34
0
 private Library(Stream metaDataStream, Stream glyphStream, Stream previewStream, Stream sectionsStream)
 {
     IDictionaryEnumerator enumerator;
     ResourceReader reader = null;
     try
     {
         IDictionary metaData = this.MetaData;
         reader = new ResourceReader(metaDataStream);
         enumerator = reader.GetEnumerator();
         while (enumerator.MoveNext())
         {
             DictionaryEntry current = (DictionaryEntry) enumerator.Current;
             metaData[current.Key] = current.Value;
         }
     }
     finally
     {
         if (reader != null)
         {
             reader.Close();
         }
     }
     if (glyphStream != null)
     {
         ResourceReader reader2 = null;
         try
         {
             reader2 = new ResourceReader(glyphStream);
             enumerator = reader2.GetEnumerator();
             while (enumerator.MoveNext())
             {
                 DictionaryEntry entry2 = (DictionaryEntry) enumerator.Current;
                 byte[] buffer = (byte[]) entry2.Value;
                 if ((buffer != null) && (buffer.Length > 0))
                 {
                     this._glyph = new Icon(new MemoryStream(buffer));
                 }
             }
         }
         finally
         {
             if (reader2 != null)
             {
                 reader2.Close();
             }
         }
     }
     if (previewStream != null)
     {
         ResourceReader reader3 = null;
         try
         {
             reader3 = new ResourceReader(previewStream);
             enumerator = reader3.GetEnumerator();
             while (enumerator.MoveNext())
             {
                 DictionaryEntry entry3 = (DictionaryEntry) enumerator.Current;
                 byte[] buffer2 = (byte[]) entry3.Value;
                 if ((buffer2 != null) && (buffer2.Length > 0))
                 {
                     this._preview = Image.FromStream(new MemoryStream(buffer2));
                 }
             }
         }
         finally
         {
             if (reader3 != null)
             {
                 reader3.Close();
             }
         }
     }
     ResourceReader reader4 = null;
     try
     {
         reader4 = new ResourceReader(sectionsStream);
         enumerator = reader4.GetEnumerator();
         while (enumerator.MoveNext())
         {
             DictionaryEntry entry4 = (DictionaryEntry) enumerator.Current;
             string key = (string) entry4.Key;
             IDictionary section = this.GetSection(key);
             byte[] buffer3 = (byte[]) entry4.Value;
             ResourceReader reader5 = null;
             try
             {
                 reader5 = new ResourceReader(new MemoryStream(buffer3));
                 IDictionaryEnumerator enumerator2 = reader5.GetEnumerator();
                 while (enumerator2.MoveNext())
                 {
                     DictionaryEntry entry5 = (DictionaryEntry) enumerator2.Current;
                     section[(string) entry5.Key] = entry5.Value;
                 }
                 continue;
             }
             finally
             {
                 if (reader5 != null)
                 {
                     reader5.Close();
                 }
             }
         }
     }
     finally
     {
         if (reader4 != null)
         {
             reader4.Close();
         }
     }
 }